From a5824bf5f0157bc206821a0778eeecfea67d30ad Mon Sep 17 00:00:00 2001 From: andig Date: Wed, 18 Feb 2026 19:31:40 +0100 Subject: [PATCH] Add location service (#27471) --- util/service/location.go | 62 ++++++++++++++++++++++++++++++++++++ util/templates/defaults.yaml | 2 ++ 2 files changed, 64 insertions(+) create mode 100644 util/service/location.go diff --git a/util/service/location.go b/util/service/location.go new file mode 100644 index 000000000..b2217b89a --- /dev/null +++ b/util/service/location.go @@ -0,0 +1,62 @@ +package service + +import ( + "encoding/json" + "net" + "net/http" + "sync" + + "github.com/evcc-io/evcc/server/service" + "github.com/evcc-io/evcc/util" + "github.com/evcc-io/evcc/util/request" + "github.com/spf13/cast" +) + +func init() { + mux := http.NewServeMux() + mux.HandleFunc("GET /lat", update(getLatitude)) + mux.HandleFunc("GET /lon", update(getLongitude)) + mux.HandleFunc("GET /ip", update(getIP)) + + service.Register("location", mux) +} + +type IpApi struct { + CountryCode string + City string + Zip string + Lat float64 + Lon float64 + Query net.IP +} + +var ( + onceLocation sync.Once + location IpApi +) + +func update(fun func(http.ResponseWriter, *http.Request)) func(w http.ResponseWriter, req *http.Request) { + return func(w http.ResponseWriter, req *http.Request) { + onceLocation.Do(func() { + log := util.NewLogger("main") + client := request.NewHelper(log) + if err := client.GetJSON("http://ip-api.com/json", &location); err != nil { + log.ERROR.Printf("location: %v", err) + } + }) + + fun(w, req) + } +} + +func getLatitude(w http.ResponseWriter, req *http.Request) { + json.NewEncoder(w).Encode([]string{cast.ToString(location.Lat)}) +} + +func getLongitude(w http.ResponseWriter, req *http.Request) { + json.NewEncoder(w).Encode([]string{cast.ToString(location.Lon)}) +} + +func getIP(w http.ResponseWriter, req *http.Request) { + json.NewEncoder(w).Encode([]string{location.Query.String()}) +} diff --git a/util/templates/defaults.yaml b/util/templates/defaults.yaml index ce105d967..30252250e 100644 --- a/util/templates/defaults.yaml +++ b/util/templates/defaults.yaml @@ -461,6 +461,7 @@ params: de: Breitengrad type: float example: 55.7351 + service: location/lat - name: lon private: true description: @@ -468,6 +469,7 @@ params: de: Längengrad type: float example: 9.1275 + service: location/lon presets: vehicle-base: