From 95bc899bcdfdccd8be41a8c92423cb65fb12be33 Mon Sep 17 00:00:00 2001 From: Jan Schill Date: Wed, 24 Jul 2024 22:28:33 +0200 Subject: [PATCH] Prepare Events Cache --- internal/db/sqlite.go | 34 +++++++++++++++++++++++++++++++++- internal/server/handlers.go | 12 ++++++------ internal/server/http.go | 25 +++++++++++++++++-------- 3 files changed, 56 insertions(+), 15 deletions(-) diff --git a/internal/db/sqlite.go b/internal/db/sqlite.go index b7032f2..5de8b3b 100644 --- a/internal/db/sqlite.go +++ b/internal/db/sqlite.go @@ -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) @@ -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) @@ -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() @@ -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) diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 88e1bfd..5767e6a 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -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) } @@ -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 diff --git a/internal/server/http.go b/internal/server/http.go index a57a407..ee22ae5 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -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 { @@ -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, @@ -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()