forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_config_site_handler.go
89 lines (74 loc) · 1.88 KB
/
http_config_site_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package server
import (
"encoding/json"
"net/http"
"github.com/evcc-io/evcc/core/site"
"github.com/evcc-io/evcc/util/config"
)
// siteHandler returns a device configurations by class
func siteHandler(site site.API) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
res := struct {
Title string `json:"title"`
Grid string `json:"grid"`
PV []string `json:"pv"`
Battery []string `json:"battery"`
}{
Title: site.GetTitle(),
Grid: site.GetGridMeterRef(),
PV: site.GetPVMeterRefs(),
Battery: site.GetBatteryMeterRefs(),
}
jsonResult(w, res)
}
}
func validateRefs(w http.ResponseWriter, refs []string) bool {
for _, m := range refs {
if _, err := config.Meters().ByName(m); err != nil {
jsonError(w, http.StatusBadRequest, err)
return false
}
}
return true
}
// siteHandler returns a device configurations by class
func updateSiteHandler(site site.API) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var payload struct {
Title *string
Grid *string
PV *[]string
Battery *[]string
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
if payload.Title != nil {
site.SetTitle(*payload.Title)
}
if payload.Grid != nil {
if *payload.Grid != "" && !validateRefs(w, []string{*payload.Grid}) {
return
}
site.SetGridMeterRef(*payload.Grid)
setConfigDirty()
}
if payload.PV != nil {
if !validateRefs(w, *payload.PV) {
return
}
site.SetPVMeterRefs(*payload.PV)
setConfigDirty()
}
if payload.Battery != nil {
if !validateRefs(w, *payload.Battery) {
return
}
site.SetBatteryMeterRefs(*payload.Battery)
setConfigDirty()
}
status := map[bool]int{false: http.StatusOK, true: http.StatusAccepted}
w.WriteHeader(status[ConfigDirty()])
}
}