From 266269f5320ceb7cf677c1f505d6b3ecc564bfff Mon Sep 17 00:00:00 2001 From: Thomas Klaehn Date: Tue, 28 Feb 2023 08:06:06 +0100 Subject: [PATCH] Initial commit --- bicycle.go | 245 ++++++++++++++++++++++++++++++++++++++++++++++++ bicycle_test.go | 11 +++ go.mod | 12 +++ go.sum | 81 ++++++++++++++++ 4 files changed, 349 insertions(+) create mode 100644 bicycle.go create mode 100644 bicycle_test.go create mode 100644 go.mod create mode 100644 go.sum diff --git a/bicycle.go b/bicycle.go new file mode 100644 index 0000000..f382d80 --- /dev/null +++ b/bicycle.go @@ -0,0 +1,245 @@ +package bicycle + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "math" + "net/http" + "os" + "path" + "strconv" + "sync" + "time" + + influxdb2 "github.com/influxdata/influxdb-client-go/v2" +) + +type drive struct { + StartTime time.Time + TotalDistance float64 +} + +type distance struct { + Value float64 `json:"value"` + Unit string `json:"unit"` +} + +type year_collect struct { + TotalDistance distance `json:"total_distance"` + YearResult distance `json:"year_result"` + Months map[string]distance `json:"months"` +} + +type api_cycle struct { + Years map[string]year_collect +} + +type config struct { + InfluxUrl string `json:"influx_url"` + InfluxToken string `json:"influx_token"` + InfluxBucket string `json:"influx_bucket"` + InfluxOrg string `json:"influx_org"` +} + +const ( + DISTANCE_UNIT = "km" +) + +var ( + logger log.Logger = *log.Default() + cycle_api api_cycle + api_mutex sync.Mutex + config_cache = config{ // Default config - written if not existing @ config_path + InfluxUrl: "http://nuc:8086", + InfluxToken: "", + InfluxBucket: "home", + InfluxOrg: "tkl", + } + // config_path string = "/var/lib/apiservice/bicycle/config.json" + config_path string = "./config.json" +) + +func init() { + logger.SetPrefix("apiservice/bike: ") + configure() +} + +func configure() { + _, err := os.Stat(config_path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + logger.Printf("Config file does not exist at '%s'. Creating one...", config_path) + + // Create config directory + dir := path.Dir(config_path) + err := os.MkdirAll(dir, os.ModePerm) + if err != nil { + logger.Fatal(err) + } + + file, err := os.OpenFile(config_path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + logger.Fatal(err) + } + defer file.Close() + + content, err := json.Marshal(config_cache) + if err != nil { + logger.Fatal(err) + } + file.Write(content) + return + } else { + logger.Fatal(err) + } + } + data, err := os.ReadFile(config_path) + if err != nil { + logger.Fatal(err) + } + err = json.Unmarshal(data, &config_cache) + if err != nil { + logger.Fatal(err) + } +} + +func roundFloat(val float64, precision uint) float64 { + ratio := math.Pow(10, float64(precision)) + return math.Round(val*ratio) / ratio +} + +func get_total_distances(client *influxdb2.Client, org string, bucket string, start time.Time, stop time.Time) ([]drive, error) { + var res []drive + queryAPI := (*client).QueryAPI(org) + query := fmt.Sprintf(`from(bucket: "%s") + |> range(start: %s, stop: %s) + |> filter(fn: (r) => r._measurement == "activity") + |> filter(fn: (r) => r["_field"] == "TotalDistance")`, bucket, start.Format(time.RFC3339), stop.Format(time.RFC3339)) + result, err := queryAPI.Query(context.Background(), query) + if err != nil { + fmt.Print(err) + return nil, err + } + for result.Next() { + var tmp drive + tmp.StartTime = result.Record().Time() + tmp.TotalDistance = result.Record().Value().(float64) / 100000.0 + res = append(res, tmp) + } + return res, nil +} + +func api_endpoint_cycle(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-type", "application/json; charset=utf-8;") + if r.Method == http.MethodGet { + // build json object of api struct + api_mutex.Lock() + res, err := json.Marshal(cycle_api) + api_mutex.Unlock() + if err != nil { + logger.Print(err) + w.WriteHeader(http.StatusInternalServerError) + w.Write(json.RawMessage(`{"error": "cannot marshal object to json"}`)) + } else { + w.WriteHeader(http.StatusOK) + w.Write(res) + } + } else { + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func api_builder() { + // create influx client + client := influxdb2.NewClient(config_cache.InfluxUrl, config_cache.InfluxToken) + defer client.Close() + for { + // end date for query + stop := time.Now() + + // start date for query (1st january of the same year as stop) + start := time.Date(stop.Year(), time.January, 1, 0, 0, 0, 0, time.UTC) + + // get TotalDistance(s) between start and stop + distances, err := get_total_distances(&client, config_cache.InfluxOrg, config_cache.InfluxBucket, start, stop) + if err != nil { + logger.Print(err) + time.Sleep(time.Second) + continue + } + + // get number of years + var year_list []int + for i := range distances { + year := distances[i].StartTime.Year() + exists := false + for _, value := range year_list { + if value == year { + exists = true + break + } + } + if !exists { + year_list = append(year_list, year) + } + } + + api_mutex.Lock() + // init api structs + cycle_api.Years = make(map[string]year_collect) + for _, value := range year_list { + years := cycle_api.Years + months := make(map[string]distance) + var tmp year_collect + tmp.Months = months + years[strconv.Itoa(value)] = tmp + cycle_api.Years = years + } + + // take over values into api struct + for i := range distances { + // get nested struct elements + year_key := strconv.Itoa(distances[i].StartTime.Year()) + year := cycle_api.Years[year_key] + months := year.Months + year_distance := year.TotalDistance + key := distances[i].StartTime.Month() + entry := months[key.String()] + + // takeover values + entry.Value = roundFloat(entry.Value+distances[i].TotalDistance, 2) + entry.Unit = DISTANCE_UNIT + year_distance.Value = roundFloat(year_distance.Value+distances[i].TotalDistance, 2) + year_distance.Unit = DISTANCE_UNIT + // year result + var year_result distance + year_result.Unit = DISTANCE_UNIT + if distances[i].StartTime.Year() == time.Now().Year() { + elapsed_days := time.Now().YearDay() + relation := float64(elapsed_days) * 100 / 365 + year_result.Value = roundFloat(year_distance.Value*relation, 2) + } else { + year_result = year_distance + } + + // replace nested struct elements + months[key.String()] = entry + year.TotalDistance = year_distance + year.YearResult = year_result + year.Months = months + cycle_api.Years[year_key] = year + } + + api_mutex.Unlock() + time.Sleep(time.Minute) + } +} + +func Start() { + configure() + http.HandleFunc("/api/bicycle", api_endpoint_cycle) + go api_builder() +} diff --git a/bicycle_test.go b/bicycle_test.go new file mode 100644 index 0000000..b7b5f13 --- /dev/null +++ b/bicycle_test.go @@ -0,0 +1,11 @@ +package bicycle + +import ( + "net/http" + "testing" +) + +func TestMain(t *testing.T) { + Start() + http.ListenAndServe(":5000", nil) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7d036a8 --- /dev/null +++ b/go.mod @@ -0,0 +1,12 @@ +module bicycle + +go 1.20 + +require github.com/influxdata/influxdb-client-go/v2 v2.12.2 + +require ( + github.com/deepmap/oapi-codegen v1.8.2 // indirect + github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 // indirect + github.com/pkg/errors v0.9.1 // indirect + golang.org/x/net v0.0.0-20210119194325-5f4716e94777 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7c09717 --- /dev/null +++ b/go.sum @@ -0,0 +1,81 @@ +github.com/cyberdelia/templates v0.0.0-20141128023046-ca7fffd4298c/go.mod h1:GyV+0YP4qX0UQ7r2MoYZ+AvYDp12OF5yg4q8rGnyNh4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deepmap/oapi-codegen v1.8.2 h1:SegyeYGcdi0jLLrpbCMoJxnUUn8GBXHsvr4rbzjuhfU= +github.com/deepmap/oapi-codegen v1.8.2/go.mod h1:YLgSKSDv/bZQB7N4ws6luhozi3cEdRktEqrX88CvjIw= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/getkin/kin-openapi v0.61.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-chi/chi/v5 v5.0.0/go.mod h1:BBug9lr0cqtdAhsu6R4AAdvufI0/XBzAQSsUqJpoZOs= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219/go.mod h1:/X8TswGSh1pIozq4ZwCfxS0WA5JGXguxk94ar/4c87Y= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/influxdata/influxdb-client-go/v2 v2.12.2 h1:uYABKdrEKlYm+++qfKdbgaHKBPmoWR5wpbmj6MBB/2g= +github.com/influxdata/influxdb-client-go/v2 v2.12.2/go.mod h1:YteV91FiQxRdccyJ2cHvj2f/5sq4y4Njqu1fQzsQCOU= +github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 h1:W9WBk7wlPfJLvMCdtV4zPulc4uCPrlywQOmbFOhgQNU= +github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839/go.mod h1:xaLFMmpvUxqXtVkUJfg9QmT88cDaCJ3ZKgdZ78oO8Qo= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/labstack/echo/v4 v4.2.1/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg= +github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/matryer/moq v0.0.0-20190312154309-6cfb0558e1bd/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= +github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=