forked from Will1604/infinitive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.go
229 lines (188 loc) · 4.68 KB
/
webserver.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package main
import (
"encoding/hex"
"errors"
"net/http"
"regexp"
"strconv"
"golang.org/x/net/websocket"
log "github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
)
func handleErrors(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
c.JSON(-1, c.Errors) // -1 == not override the current error code
}
}
func webserver(port int) {
r := gin.Default()
r.Use(handleErrors) // attach error handling middleware
api := r.Group("/api")
api.GET("/zone/1/config", func(c *gin.Context) {
cfg, ok := getConfig()
if ok {
c.JSON(200, cfg)
}
})
api.GET("/airhandler", func(c *gin.Context) {
ah, ok := getAirHandler()
if ok {
c.JSON(200, ah)
}
})
api.GET("/airhandler2", func(c *gin.Context) {
ah, ok := getAirHandler()
if ok {
c.JSON(200, ah)
}
})
api.GET("/heatpump", func(c *gin.Context) {
hp, ok := getHeatPump()
if ok {
c.JSON(200, hp)
}
})
api.GET("/devices", func(c *gin.Context) {
dv, ok := getDevices()
if ok {
ts, ok := getDeviceInfo(devTSTAT)
if ok {
dv.Thermostat = *ts
} else {
return
}
hp, ok := getDeviceInfo(devHeatPump)
if ok {
dv.HeatPump = *hp
c.IndentedJSON(200, dv)
}
}
})
api.GET("/zone/1/vacation", func(c *gin.Context) {
vac := TStatVacationParams{}
ok := infinity.ReadTable(devTSTAT, &vac)
if ok {
c.JSON(200, vac.toAPI())
}
})
api.PUT("/zone/1/vacation", func(c *gin.Context) {
var args APIVacationConfig
if c.Bind(&args) != nil {
log.Printf("bind failed")
return
}
params := TStatVacationParams{}
flags := params.fromAPI(&args)
infinity.WriteTable(devTSTAT, params, flags)
})
api.PUT("/zone/1/config", func(c *gin.Context) {
var args TStatZoneConfig
if c.Bind(&args) == nil {
params := TStatZoneParams{}
flags := byte(0)
if len(args.FanMode) > 0 {
mode, _ := stringFanModeToRaw(args.FanMode)
// FIXME: check for ok here
params.Z1FanMode = mode
flags |= 0x01
}
if args.Hold != nil {
if *args.Hold {
params.ZoneHold = 0x01
} else {
params.ZoneHold = 0x00
}
flags |= 0x02
}
// if args.HoldDuration > 0 {
// params.Z1HoldDuration = args.HoldDuration
// flags |= 0x04 # not sure how to determine the correct value to indicate this has changed
// }
if args.HeatSetpoint > 0 {
params.Z1HeatSetpoint = args.HeatSetpoint
flags |= 0x04
}
if args.CoolSetpoint > 0 {
params.Z1CoolSetpoint = args.CoolSetpoint
flags |= 0x08
}
if flags != 0 {
log.Printf("calling doWrite with flags: %x", flags)
infinity.WriteTable(devTSTAT, params, flags)
}
if len(args.Mode) > 0 {
p := TStatCurrentParams{Mode: stringModeToRaw(args.Mode)}
infinity.WriteTable(devTSTAT, p, 0x10)
}
} else {
log.Printf("bind failed")
}
})
api.GET("/raw/:device/:table", func(c *gin.Context) {
matched, _ := regexp.MatchString("^[a-f0-9]{4}$", c.Param("device"))
if !matched {
c.AbortWithError(400, errors.New("name must be a 4 character hex string"))
return
}
matched, _ = regexp.MatchString("^[a-f0-9]{6}$", c.Param("table"))
if !matched {
c.AbortWithError(400, errors.New("table must be a 6 character hex string"))
return
}
d, _ := strconv.ParseUint(c.Param("device"), 16, 16)
a, _ := hex.DecodeString(c.Param("table"))
var addr InfinityTableAddr
copy(addr[:], a[0:3])
raw := InfinityProtocolRawRequest{&[]byte{}}
success := infinity.Read(uint16(d), addr, raw)
if success {
c.JSON(200, gin.H{"response": hex.EncodeToString(*raw.data)})
} else {
c.AbortWithError(504, errors.New("timed out waiting for response"))
}
})
api.GET("/ws", func(c *gin.Context) {
h := websocket.Handler(attachListener)
h.ServeHTTP(c.Writer, c.Request)
})
r.StaticFS("/ui", assetFS())
// r.Static("/ui", "github.com/acd/infinitease/assets")
r.GET("/", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "ui")
})
r.Run(":" + strconv.Itoa(port)) // listen and server on 0.0.0.0:8080
}
func attachListener(ws *websocket.Conn) {
listener := &EventListener{make(chan []byte, 32)}
defer func() {
Dispatcher.deregister <- listener
log.Printf("closing websocket")
err := ws.Close()
if err != nil {
log.Println("error on ws close:", err.Error())
}
}()
Dispatcher.register <- listener
log.Printf("dumping cached data")
for source, data := range cache {
log.Printf("dumping %s", source)
ws.Write(serializeEvent(source, data))
}
// wait for events
for {
select {
case message, ok := <-listener.ch:
if !ok {
log.Printf("read from listener.ch was not okay")
return
} else {
_, err := ws.Write(message)
if err != nil {
log.Printf("error on websocket write: %s", err.Error())
return
}
}
}
}
}