From 874aee24ff56f1aa2c728c35479d856ba1836304 Mon Sep 17 00:00:00 2001 From: Joerg Lehmann Date: Fri, 12 Mar 2021 21:50:41 +0100 Subject: [PATCH] still improving map logic --- main.go | 1 - metrics.go | 172 +- minify-fa.sh | 2 +- snippets/graph.html | 63 - snippets/map.html | 105 + snippets/tracker.html | 212 +- static/css/wo-bisch-web-custom.css | 26 +- static/js/apexcharts.min.js | 16 - static/js/fontawesome-5.11.2/all-minified.js | 8 +- static/js/map.js | 48 + static/js/map.js.orig | 69 - static/js/{scales.js => tracker.js} | 2 +- static/wo-bisch-web-custom.css | 84 - static/wo-bisch-web.css | 20353 ----------------- 14 files changed, 287 insertions(+), 20874 deletions(-) delete mode 100644 snippets/graph.html create mode 100644 snippets/map.html delete mode 100644 static/js/apexcharts.min.js create mode 100644 static/js/map.js delete mode 100644 static/js/map.js.orig rename static/js/{scales.js => tracker.js} (99%) delete mode 100644 static/wo-bisch-web-custom.css delete mode 100644 static/wo-bisch-web.css diff --git a/main.go b/main.go index efeda96..38fb494 100644 --- a/main.go +++ b/main.go @@ -94,7 +94,6 @@ func main() { http.HandleFunc("/logout", logoutHandler) http.HandleFunc("/confirm", confirmHandler) http.HandleFunc("/metrics", metricsHandler) - http.HandleFunc("/lastmetrics", lastmetricsHandler) http.HandleFunc("/save_tracker_settings", save_tracker_settingsHandler) http.HandleFunc("/getstripepaymentintent", getstripepaymentintentHandler) http.HandleFunc("/stripewebhook", stripeWebhookHandler) diff --git a/metrics.go b/metrics.go index e6d2e4e..2b3541e 100644 --- a/metrics.go +++ b/metrics.go @@ -8,6 +8,8 @@ import ( "io/ioutil" "log" "net/http" + "sort" + "strconv" "strings" "time" ) @@ -31,33 +33,10 @@ type OneMetric struct { // metrics handler -func validProperty(prop string) bool { - valid_properties := [...]string{"lat", "lon", "vbat", "fw"} - for _, p := range valid_properties { - if p == prop { - return true - } - } - return false -} - func metricsHandler(response http.ResponseWriter, request *http.Request) { name := getUserName(request) if name != "" { - property, ok := request.URL.Query()["property"] - if !ok || len(property[0]) < 1 { - log.Println("Url Param 'property' is missing") - fmt.Fprintf(response, "{ \"msg\": \"error: property must be specified in URL\" }") - return - } - - if !validProperty(property[0]) { - log.Println("Url Param 'property' is invalid") - fmt.Fprintf(response, "{ \"msg\": \"error: invalid property\" }") - return - } - deveui, ok := request.URL.Query()["deveui"] if !ok || len(deveui[0]) < 1 { @@ -116,7 +95,7 @@ func metricsHandler(response http.ResponseWriter, request *http.Request) { } url := "http://localhost:8086/api/v2/query?org=wobischorg" - data := []byte(fmt.Sprintf(`from(bucket:"wobischbucket") |> range(start: %s, stop: %s) |> filter(fn: (r) => r._measurement == "measurement") |> filter(fn: (r) => r._field == "%s") |> filter(fn: (r) => r.deveui == "%s")`, mystart, mystop, property[0], mydeveui)) + data := []byte(fmt.Sprintf(`from(bucket:"wobischbucket") |> range(start: %s, stop: %s) |> filter(fn: (r) => r._measurement == "measurement") |> filter(fn: (r) => r._field == "lon" or r._field == "lat") |> filter(fn: (r) => r.deveui == "%s")`, mystart, mystop, mydeveui)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(data)) if err != nil { @@ -145,27 +124,60 @@ func metricsHandler(response http.ResponseWriter, request *http.Request) { if err != nil { log.Fatal("Error reading body. ", err) } + fmt.Println("response Body:", string(body)) + + m := make(map[int64][2]float64) - fmt.Fprintf(response, "[\n") scanner := bufio.NewScanner(strings.NewReader(string(body))) - first := true for scanner.Scan() { s := strings.Split(scanner.Text(), ",") + fmt.Printf("Scanned Line: %v\n", s) if (len(s) >= 7) && !(strings.HasPrefix(s[5], "_")) { t, err := time.Parse(time.RFC3339, s[5]) if err != nil { + fmt.Printf("error converting time: %s\n", s[5]) continue } a := t.Unix() b := s[6] - if !(first) { - fmt.Fprintf(response, ",") + if b == "0" { + fmt.Println("skip 0 value for lon/lat") } else { - first = false + t := s[7] + f, err := strconv.ParseFloat(b, 64) + if err == nil { + v := m[a] + if t == "lon" { + v[0] = f + } + if t == "lat" { + v[1] = f + } + m[a] = v + } else { + fmt.Printf("error converting string to float64: %s\n", b) + } } - fmt.Fprintf(response, "[%d000,%s]\n", a, b) + } } + first := true + fmt.Fprintf(response, "[\n") + keys := make([]int64, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.SliceStable(keys, func(i, j int) bool { return keys[i] < keys[j] }) + + for _, k := range keys { + if !(first) { + fmt.Fprintf(response, ",") + } else { + first = false + } + + fmt.Fprintf(response, "[%d, %f, %f]\n", k, m[k][0], m[k][1]) + } fmt.Fprintf(response, "]\n") } else { @@ -173,106 +185,6 @@ func metricsHandler(response http.ResponseWriter, request *http.Request) { } } -func lastmetricsHandler(response http.ResponseWriter, request *http.Request) { - name := getUserName(request) - if name != "" { - - deveui, ok := request.URL.Query()["deveui"] - - if !ok || len(deveui[0]) < 1 { - log.Println("Url Param 'deveui' is missing") - fmt.Fprintf(response, "{ \"msg\": \"deveui must be specified in URL\" }") - return - } - // Query()["deveui"] will return an array of items, - // we only want the single item. - mydeveui := deveui[0] - - if !(Contains(getMyDevs(name), mydeveui)) { - log.Println("specified 'deveui' does not belong to this user") - fmt.Fprintf(response, "{ \"msg\": \"specified deveui does not belong to this user\" }") - return - } - - log.Println("Url Param 'deveui' is: " + string(mydeveui)) - - url := "http://localhost:8086/api/v2/query?org=wobischorg" - data := []byte(fmt.Sprintf(`from(bucket:"wobischbucket") - |> range(start:-365d) - |> filter(fn: (r) => r._measurement == "measurement" and r.deveui == "%s") - |> filter(fn: (r) => r._field == "lat" or r._field == "lon" or r._field == "vbat" or r._field == "fw") - |> last(column: "_time") |> yield(name: "last")`, mydeveui)) - - req, err := http.NewRequest("POST", url, bytes.NewBuffer(data)) - if err != nil { - log.Fatal("Error reading request. ", err) - } - - // Set headers - req.Header.Set("Authorization", "Token TQvQxxLLAj1kTKWuEqcx7BA-KfE6WtJUeDlPa_Dnvms6Zqf6uh6lMbpXtzcsCjKO_x3PrpxxGDR5E6YnDB5PFg==") - req.Header.Set("accept", "application/csv") - req.Header.Set("content-type", "application/vnd.flux") - - // Set client timeout - client := &http.Client{Timeout: time.Second * 10} - - // Send request - resp, err := client.Do(req) - if err != nil { - log.Fatal("Error reading response. ", err) - } - defer resp.Body.Close() - - fmt.Println("response Status:", resp.Status) - fmt.Println("response Headers:", resp.Header) - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - log.Fatal("Error reading body. ", err) - } - fmt.Println("response Body 1:", string(body)) - - scanner := bufio.NewScanner(strings.NewReader(string(body))) - ts := "" - lat := "" - lon := "" - vbat := "" - fw := "" - location, err := time.LoadLocation("Europe/Zurich") - for scanner.Scan() { - s := strings.Split(scanner.Text(), ",") - if (len(s) >= 7) && !(strings.HasPrefix(s[5], "_")) { - mytime, err := time.Parse(time.RFC3339, s[5]) - if err != nil { - continue - } - ts = mytime.In(location).Format("02.01.2006 15:04") - value := s[6] - field := s[7] - if field == "lat" { - lat = value - } else if field == "lon" { - lon = value - } else if field == "vbat" { - vbat = value - } else if field == "fw" { - fw = value - } - } - } - fmt.Fprintf(response, `{ - "ts": "%s", - "lat": "%s", - "lon": "%s", - "vbat": "%s", - "fw": "%s" -}`, ts, lat, lon, vbat, fw) - - } else { - fmt.Fprintf(response, "{ \"msg\": \"Only available for logged in users\" }") - } -} - func CalcDaysUntil(mydate string) int { var days int layout := "02.01.2006" diff --git a/minify-fa.sh b/minify-fa.sh index 3d12a1e..5df31e1 100755 --- a/minify-fa.sh +++ b/minify-fa.sh @@ -1 +1 @@ -cat /home/appuser/wo-bisch-web/static/js/fontawesome-5.11.2/all.js |/home/appuser/wo-bisch-web/minify-fa-js.py home,address-card,balance-scale,sign-out-alt,sign-in-alt,calendar,balance-scale,thermometer-half,tint,cloud,battery-three-quarters,envelope,check,lock,exclamation-triangle,cog,plus,shopping-cart,minus,arrow-right,caret-down,map-marked-alt >/home/appuser/wo-bisch-web/static/js/fontawesome-5.11.2/all-minified.js +cat /home/appuser/wo-bisch-web/static/js/fontawesome-5.11.2/all.js |/home/appuser/wo-bisch-web/minify-fa-js.py home,address-card,balance-scale,sign-out-alt,sign-in-alt,calendar,globe,tint,battery-three-quarters,envelope,check,lock,exclamation-triangle,cog,plus,shopping-cart,minus,arrow-right,caret-down,map-marked-alt >/home/appuser/wo-bisch-web/static/js/fontawesome-5.11.2/all-minified.js diff --git a/snippets/graph.html b/snippets/graph.html deleted file mode 100644 index 3cc2fb8..0000000 --- a/snippets/graph.html +++ /dev/null @@ -1,63 +0,0 @@ -{{define "body_content"}} -{{ if ne .UserName "" }} - - - - - - - - - -
-
-
-   - -
-
- -
- - - -
-
- -
-
- - - - - -{{ else }} -

Bitte zuerst einloggen

-{{end}} -{{end}} diff --git a/snippets/map.html b/snippets/map.html new file mode 100644 index 0000000..090c373 --- /dev/null +++ b/snippets/map.html @@ -0,0 +1,105 @@ +{{define "body_content"}} +{{ if ne .UserName "" }} + + + + + + + + + +
+
+
+   + +
+
+
+
+
+ + + + +
+
+ +
+
+ + +
+ + + + +
+ + + +
+
+ 0 +
+{{ else }} +

Bitte zuerst einloggen

+{{end}} +{{end}} diff --git a/snippets/tracker.html b/snippets/tracker.html index 6a3edf5..544e5ec 100644 --- a/snippets/tracker.html +++ b/snippets/tracker.html @@ -1,5 +1,6 @@ {{define "body_content"}} {{ if ne .UserName "" }} +