/
registers.go
80 lines (74 loc) · 2.48 KB
/
registers.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
package httpServer
import (
"github.com/gin-gonic/gin"
"github.com/koestler/go-iotdevice/dataflow"
"github.com/pkg/errors"
"log"
"net/http"
"time"
)
type registerResponse struct {
Category string `json:"category" example:"Monitor"`
Name string `json:"name" example:"PanelPower"`
Description string `json:"description" example:"Panel power"`
Type string `json:"type" example:"numeric"`
Unit *string `json:"unit" example:"W"`
}
// setupRegisters godoc
// @Summary Outputs information about all the available fields.
// @Description Depending on the device model (bmv, bluesolar) a different set of variables are available.
// @Description This endpoint outputs a list of fields (variables) including a name, a unit and a datatype.
// @ID registers
// @Param viewName path string true "View name as provided by the config endpoint"
// @Param deviceName path string true "Device name as provided in devices array of the config endpoint"
// @Produce json
// @success 200 {array} registerResponse
// @Failure 404 {object} ErrorResponse
// @Router /registers/{viewName}/{deviceName}.json [get]
// @Security ApiKeyAuth
func setupRegisters(r *gin.RouterGroup, env *Environment) {
// add dynamic routes
for _, v := range env.Views {
view := v
for _, deviceName := range view.DeviceNames() {
device := env.DevicePoolInstance.GetDevice(deviceName)
if device == nil {
continue
}
relativePath := "registers/" + view.Name() + "/" + deviceName + ".json"
r.GET(relativePath, func(c *gin.Context) {
// check authorization
if !isViewAuthenticated(view, c) {
jsonErrorResponse(c, http.StatusForbidden, errors.New("User is not allowed here"))
return
}
registers := dataflow.FilterRegisters(device.GetRegisters(), view.SkipFields(), view.SkipCategories())
response := make([]registerResponse, len(registers))
for i, v := range registers {
response[i] = registerResponse{
Category: v.Category(),
Name: v.Name(),
Description: v.Description(),
Type: typeString(v.Type()),
Unit: v.Unit(),
}
}
setCacheControlPublic(c, 10*time.Second)
jsonGetResponse(c, response)
})
if env.Config.LogConfig() {
log.Printf("httpServer: %s%s -> serve fields", r.BasePath(), relativePath)
}
}
}
}
func typeString(rt dataflow.RegisterType) string {
switch rt {
case dataflow.StringRegister:
return "string"
case dataflow.NumberRegister:
return "number"
default:
return ""
}
}