Skip to content

Commit

Permalink
Prepare Events Cache
Browse files Browse the repository at this point in the history
  • Loading branch information
janschill committed Jul 24, 2024
1 parent 8035488 commit 95bc899
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 15 deletions.
34 changes: 33 additions & 1 deletion internal/db/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,19 @@ func CreateTables(filePath string) {
FOREIGN KEY (eventId) REFERENCES Event(id)
);`

createEventsCacheTableSQL := `CREATE TABLE IF NOT EXISTS events_cache (
date DATE PRIMARY KEY,
points_data TEXT NOT NULL
);`

createMessagesTableSQL := `CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timeStamp INTEGER NOT NULL,
name TEXT,
message TEXT,
sentToGarmin INTEGER,
);`

_, err = Db.Exec(createTripTableSQL)
if err != nil {
log.Fatal("Failed to create trips table:", err)
Expand All @@ -114,6 +127,16 @@ func CreateTables(filePath string) {
log.Fatal("Failed to create addresses table:", err)
}

_, err = Db.Exec(createEventsCacheTableSQL)
if err != nil {
log.Fatal("Failed to create events_cache table:", err)
}

_, err = Db.Exec(createMessagesTableSQL)
if err != nil {
log.Fatal("Failed to create messages table:", err)
}

log.Println("Tables created successfully.")
if err := Db.Close(); err != nil {
log.Fatal("Failed to close database connection:", err)
Expand All @@ -133,6 +156,10 @@ func Seed(filePath string) {
}
defer file.Close()

startDate := time.Date(2024, time.September, 8, 0, 0, 0, 0, time.UTC)
// every 1500 entrys increment day
rowCount := 0

scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
Expand All @@ -153,11 +180,16 @@ func Seed(filePath string) {
log.Fatal("Failed to parse latitude:", err)
}

currentDate := startDate.Add(time.Hour * 24 * time.Duration(rowCount/1500))
timeStamp := currentDate.Unix()

_, err = Db.Exec("INSERT INTO events(tripId, imei, messageCode, timeStamp, latitude, longitude, altitude, gpsFix, course, speed, autonomous, lowBattery, intervalChange, resetDetected) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
1, "fake-imei", 0, time.Now().Unix(), latitude, longitude, int(elevation), 0, 0, 0, 0, 0, 0, 0)
1, "fake-imei", 0, timeStamp, latitude, longitude, int(elevation), 0, 0, 0, 0, 0, 0, 0)
if err != nil {
log.Fatal("Failed to insert into events table:", err)
}

rowCount++
}
if err := scanner.Err(); err != nil {
log.Fatal("Error reading file:", err)
Expand Down
12 changes: 6 additions & 6 deletions internal/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,17 @@ func (s *httpServer) handleGarminOutbound(w http.ResponseWriter, r *http.Request
}

log.Printf("GarminOutbound payload received. %v event(s)\n", len(payload.Events))
s.Events.prepareAndSave(payload)
s.EventStore.prepareAndSave(payload)

w.WriteHeader(http.StatusOK)
w.Write([]byte("Payload received successfully."))
}

func (s *httpServer) handleEvents(w http.ResponseWriter, r *http.Request) {
s.Events.mu.Lock()
defer s.Events.mu.Unlock()
s.EventStore.mu.Lock()
defer s.EventStore.mu.Unlock()

if err := json.NewEncoder(w).Encode(s.Events.events); err != nil {
if err := json.NewEncoder(w).Encode(s.EventStore.events); err != nil {
http.Error(w, "Error encoding response", http.StatusInternalServerError)
log.Printf("Error encoding response: %v", err)
}
Expand All @@ -77,13 +77,13 @@ type IndexPageData struct {
func (s *httpServer) handleIndex(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/index.html"))

events, err := db.GetAllEvents(s.Events.db)
events, err := db.GetAllEvents(s.EventStore.db)
if err != nil {
http.Error(w, "An unexpected error happened.", http.StatusBadGateway)
return
}

lastEvent, err := db.GetLastEvent(s.Events.db)
lastEvent, err := db.GetLastEvent(s.EventStore.db)
if err != nil {
http.Error(w, "An unexpected error happened.", http.StatusBadGateway)
return
Expand Down
25 changes: 17 additions & 8 deletions internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import (
)

type httpServer struct {
Events *EventStore
EventStore *EventStore
}

type EventStore struct {
mu sync.Mutex
db *sql.DB
events []db.Event
cache map[int]db.Event
}

func (c *EventStore) prepareAndSave(payload GarminOutboundPayload) error {
Expand All @@ -29,12 +30,12 @@ func (c *EventStore) prepareAndSave(payload GarminOutboundPayload) error {
FreeText: pEvent.FreeText,
TimeStamp: pEvent.TimeStamp,
Addresses: make([]db.Address, len(pEvent.Addresses)),
Latitude: pEvent.Point.Latitude,
Longitude: pEvent.Point.Longitude,
Altitude: pEvent.Point.Altitude,
GpsFix: pEvent.Point.GpsFix,
Course: pEvent.Point.Course,
Speed: pEvent.Point.Speed,
Latitude: pEvent.Point.Latitude,
Longitude: pEvent.Point.Longitude,
Altitude: pEvent.Point.Altitude,
GpsFix: pEvent.Point.GpsFix,
Course: pEvent.Point.Course,
Speed: pEvent.Point.Speed,
Status: db.Status{
Autonomous: pEvent.Status.Autonomous,
LowBattery: pEvent.Status.LowBattery,
Expand All @@ -55,13 +56,21 @@ func (c *EventStore) prepareAndSave(payload GarminOutboundPayload) error {

}

func reduce(events []db.Event) []db.Event {
return events
}

func fillCache() {

}

func HttpServer(addr string) *http.Server {
db, err := db.InitializeDB("./data/trips.db")
if err != nil {
log.Fatal(err)
}
server := &httpServer{
Events: &EventStore{db: db},
EventStore: &EventStore{db: db},
}
fs := http.FileServer(http.Dir("assets/"))
router := mux.NewRouter()
Expand Down

0 comments on commit 95bc899

Please sign in to comment.