From 2ec25ca6fd4d125dde7295b523eec511c5fa34a9 Mon Sep 17 00:00:00 2001 From: Daniel Ledda Date: Sat, 7 Nov 2020 01:10:27 +0100 Subject: [PATCH] Changed endpoints and db queries, chart now shows suggested mins and maxes --- Database.go | 21 +++++++++++++++++++++ climate-server.go | 20 ++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/Database.go b/Database.go index 2dd92bc..47deb46 100644 --- a/Database.go +++ b/Database.go @@ -39,6 +39,27 @@ func writeSnapshotToDb(snapshotSub *SnapshotSubmission) error { return nil } +func getLastSnapshotRecordFromDb() (*SnapshotRecord, error) { + var snapshotRecord SnapshotRecord + query := "SELECT `%s`, `%s`, `%s`, `%s`, `%s` FROM `snapshots` ORDER BY `id` DESC LIMIT 1;" + rows, err := ClimateDb.Query(fmt.Sprintf(query, "id", "temp", "humidity", "co2", "time")) + if err != nil { + return nil, err + } + rows.Next() + err = rows.Scan( + &snapshotRecord.Id, + &snapshotRecord.Temp, + &snapshotRecord.Humidity, + &snapshotRecord.Co2, + &snapshotRecord.Timestamp, + ) + if err != nil { + return nil, err + } + return &snapshotRecord, nil +} + func getSnapshotRecordsFromDb(minuteAgo int) ([]*SnapshotRecord, error) { snapshots := make([]*SnapshotRecord, 0) query := "SELECT `%s`, `%s`, `%s`, `%s`, `%s` FROM `snapshots` WHERE `%s` > date_sub(now(), interval %v minute) ORDER BY `id` DESC;" diff --git a/climate-server.go b/climate-server.go index 9b2c83f..3b8392f 100644 --- a/climate-server.go +++ b/climate-server.go @@ -39,6 +39,7 @@ func startServer() { r.HandleFunc("/since/{mins}", showCharts).Methods("GET") r.HandleFunc("/data/", sendData).Methods("GET") r.HandleFunc("/data/since/{mins}", sendData).Methods("GET") + r.HandleFunc("/data/last/", sendLastSnapshot).Methods("GET") r.HandleFunc("/", saveSnapshot).Methods("POST") r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) http.Handle("/", r) @@ -84,6 +85,25 @@ func sendData(w http.ResponseWriter, r *http.Request) { } } +func sendLastSnapshot(w http.ResponseWriter, r *http.Request) { + record, err := getLastSnapshotRecordFromDb() + if err != nil { + sendInternalError(fmt.Errorf("couldn't read last snapshot from the database: %w", err), w, r) + return + } + json, err := createJsonFromSnapshotRecords(record) + if err != nil { + sendInternalError(fmt.Errorf("couldn't create a json from the last record: %w", err), w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, err = fmt.Fprintf(w, string(json)) + if err != nil { + sendInternalError(err, w, r) + return + } +} + func saveSnapshot(w http.ResponseWriter, r *http.Request) { snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body) if err != nil {