-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
460 lines (380 loc) · 10.6 KB
/
main.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/sausheong/hs1xxplug"
yaml "gopkg.in/yaml.v2"
)
type options struct {
Port int
RepeatCount int
Remote remoteControl
RemoteName string
IRSendPath string
OutletHost string `yaml:"outlet_host"`
PowerOffThreshold float64 `yaml:"power_off_threshold"`
LowHeatLowThreshold float64 `yaml:"medium_heat_low_threshold"`
LowHeatHighThreshold float64 `yaml:"medium_heat_high_threshold"`
}
type PowerState string
const (
Off PowerState = "off"
FlameOnly = "flame_only"
Low = "low"
High = "high"
)
type remoteControl map[string]string
type fireplaceServer struct {
opts options
mu sync.Mutex
remote remoteControl
plug hs1xxplug.Hs1xxPlug
}
// Just a subset of what this returns; all we need
type powerStats struct {
Emeter struct {
GetRealtime struct {
Current float64 `json:"current"`
Voltage float64 `json:"voltage"`
Power float64 `json:"power"`
} `json:"get_realtime"`
} `json:"emeter"`
}
func (f *fireplaceServer) getPowerStatus() (bool, error) {
results, err := f.plug.MeterInfo()
if err != nil {
return false, fmt.Errorf("could not get plug meter info: %s", err.Error())
}
var stats powerStats
if err := json.Unmarshal([]byte(results), &stats); err != nil {
return false, fmt.Errorf("could not unmarshal power meter JSON: %s", err.Error())
}
return stats.Emeter.GetRealtime.Power > f.opts.PowerOffThreshold, nil
}
func (f *fireplaceServer) getHeatStatus() (PowerState, error) {
results, err := f.plug.MeterInfo()
if err != nil {
return "", fmt.Errorf("could not get plug meter info: %s", err.Error())
}
var stats powerStats
if err := json.Unmarshal([]byte(results), &stats); err != nil {
return "", fmt.Errorf("could not unmarshal power meter JSON: %s", err.Error())
}
power := stats.Emeter.GetRealtime.Power
switch {
case power < f.opts.PowerOffThreshold:
return Off, nil
case power < f.opts.LowHeatLowThreshold:
return FlameOnly, nil
case power < f.opts.LowHeatHighThreshold:
return Low, nil
default:
return High, nil
}
}
func (f *fireplaceServer) getUsage(w http.ResponseWriter, r *http.Request) {
results, err := f.plug.MeterInfo()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error getting outlet status: %s", err.Error())
return
}
var stats powerStats
if err := json.Unmarshal([]byte(results), &stats); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "could not unmarshal power meter JSON: %s", err.Error())
return
}
w.Header().Set("content-type", "application/json")
json.NewEncoder(w).Encode(stats.Emeter.GetRealtime)
}
func (f *fireplaceServer) getStatus(w http.ResponseWriter, r *http.Request) {
status, err := f.getPowerStatus()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error getting outlet status: %s", err.Error())
return
}
if status {
fmt.Fprint(w, "1")
} else {
fmt.Fprint(w, "0")
}
}
func (f *fireplaceServer) setHeat(w http.ResponseWriter, r *http.Request, desiredState PowerState) {
if desiredState == Off {
f.turnOff(w, r)
return
}
f.turnOn(w, r)
if err := f.setToLevel(desiredState); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error setting new state: %s", err.Error())
return
}
}
func (f *fireplaceServer) setToLevel(newLevel PowerState) error {
f.mu.Lock()
defer f.mu.Unlock()
curLevel, err := f.getHeatStatus()
if err != nil {
return err
}
var transitions []PowerState
switch curLevel {
case FlameOnly:
switch newLevel {
case Low:
transitions = []PowerState{Low}
case High:
transitions = []PowerState{Low, High}
}
case Low:
switch newLevel {
case High:
transitions = []PowerState{High}
case FlameOnly:
transitions = []PowerState{High, FlameOnly}
}
case High:
switch newLevel {
case FlameOnly:
transitions = []PowerState{FlameOnly}
case Low:
transitions = []PowerState{FlameOnly, Low}
}
}
for _, desiredState := range transitions {
if err := f.waitForHeatState(desiredState); err != nil {
return err
}
}
return nil
}
func (f *fireplaceServer) heatLowOn(w http.ResponseWriter, r *http.Request) {
f.setHeat(w, r, Low)
}
func (f *fireplaceServer) heatLowOff(w http.ResponseWriter, r *http.Request) {
f.setHeat(w, r, FlameOnly)
}
func (f *fireplaceServer) heatHighOn(w http.ResponseWriter, r *http.Request) {
f.setHeat(w, r, High)
}
func (f *fireplaceServer) heatHighOff(w http.ResponseWriter, r *http.Request) {
f.setHeat(w, r, FlameOnly)
}
func (f *fireplaceServer) heatLowStatus(w http.ResponseWriter, r *http.Request) {
f.heatStatus(w, Low)
}
func (f *fireplaceServer) heatHighStatus(w http.ResponseWriter, r *http.Request) {
f.heatStatus(w, High)
}
func (f *fireplaceServer) heatStatus(w http.ResponseWriter, desiredStatus PowerState) {
status, err := f.getHeatStatus()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error getting outlet status: %s", err.Error())
return
}
if status == desiredStatus {
fmt.Fprintf(w, "1")
} else {
fmt.Fprintf(w, "0")
}
}
func (f *fireplaceServer) waitForHeatState(desiredState PowerState) error {
keyCode := f.opts.Remote["heat"]
t := time.NewTimer(time.Second * 60)
for {
select {
case <-t.C:
return fmt.Errorf("timed out waiting for power state transition")
default:
}
if err := func() error {
if err := exec.Command(f.opts.IRSendPath,
fmt.Sprintf("--count=%d", f.opts.RepeatCount),
"SEND_ONCE",
f.opts.RemoteName,
keyCode).Run(); err != nil {
return err
}
return nil
}(); err != nil {
return fmt.Errorf("error sending power command: %s", err.Error())
}
waitTimeout := time.NewTimer(time.Second * 20)
timeoutLoop:
for {
select {
case <-time.After(time.Millisecond * 250):
status, err := f.getHeatStatus()
if err != nil {
return fmt.Errorf("error checking power status: %s", err.Error())
}
if status == desiredState {
return nil
}
case <-waitTimeout.C:
break timeoutLoop
}
}
}
}
func (f *fireplaceServer) waitForPowerState(w http.ResponseWriter, on bool) {
// Allow sending only one command at a time
f.mu.Lock()
defer f.mu.Unlock()
status, err := f.getPowerStatus()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error checking power status: %s", err.Error())
return
}
if status == on {
return
}
t := time.NewTimer(time.Second * 30)
keyCode := f.opts.Remote["power"]
for {
select {
case <-t.C:
w.WriteHeader(http.StatusRequestTimeout)
fmt.Fprint(w, "timed out waiting for power state transition")
return
default:
}
if err := func() error {
if err := exec.Command(f.opts.IRSendPath,
fmt.Sprintf("--count=%d", f.opts.RepeatCount),
"SEND_ONCE",
f.opts.RemoteName,
keyCode).Run(); err != nil {
return err
}
return nil
}(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error sending power command: %s", err.Error())
return
}
waitTimeout := time.NewTimer(time.Second * 15)
timeoutLoop:
for {
select {
case <-time.After(time.Millisecond * 250):
status, err := f.getPowerStatus()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error checking power status: %s", err.Error())
return
}
if status == on {
return
}
case <-waitTimeout.C:
break timeoutLoop
}
}
}
}
func (f *fireplaceServer) turnOn(w http.ResponseWriter, r *http.Request) {
f.waitForPowerState(w, true)
}
func (f *fireplaceServer) turnOff(w http.ResponseWriter, r *http.Request) {
f.waitForPowerState(w, false)
}
func (f *fireplaceServer) sendCommand(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
command := vars["command"]
if command == "power" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "use the /power/on and /power/off routes for power")
return
}
keyCode := f.remote[command]
if keyCode == "" {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "could not find key code for command %s", command)
return
}
if err := func() error {
// Allow sending only one command at a time
f.mu.Lock()
defer f.mu.Unlock()
if err := exec.Command(f.opts.IRSendPath,
fmt.Sprintf("--count=%d", f.opts.RepeatCount),
"SEND_ONCE",
f.opts.RemoteName,
keyCode).Run(); err != nil {
return err
}
return nil
}(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error executing command: %s", err.Error())
return
}
}
func main() {
opts := options{
Port: 8080,
RepeatCount: 5,
IRSendPath: "/usr/bin/irsend",
RemoteName: "fireplace",
PowerOffThreshold: 1.0,
LowHeatLowThreshold: 650.0,
LowHeatHighThreshold: 750.0,
}
if len(os.Args) < 2 {
fmt.Printf("usage: %s config.yml\n", os.Args[0])
os.Exit(1)
}
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatalf("error reading config file: %s", err.Error())
}
if err := yaml.Unmarshal(b, &opts); err != nil {
log.Fatalf("error parsing config file: %s", err.Error())
}
if _, ok := opts.Remote["power"]; !ok {
log.Fatal("must specify a remote with a power button")
}
if opts.OutletHost == "" {
log.Fatal("must specify outlet_host in config!")
}
rtr := mux.NewRouter()
f := &fireplaceServer{
opts: opts,
remote: opts.Remote,
plug: hs1xxplug.Hs1xxPlug{IPAddress: opts.OutletHost},
}
rtr.HandleFunc("/send/{command}", f.sendCommand).Methods(http.MethodGet)
rtr.HandleFunc("/power/on", f.turnOn).Methods(http.MethodGet)
rtr.HandleFunc("/power/off", f.turnOff).Methods(http.MethodGet)
rtr.HandleFunc("/power/status", f.getStatus).Methods(http.MethodGet)
rtr.HandleFunc("/heat/low/on", f.heatLowOn).Methods(http.MethodGet)
rtr.HandleFunc("/heat/low/off", f.heatLowOff).Methods(http.MethodGet)
rtr.HandleFunc("/heat/low/status", f.heatLowStatus).Methods(http.MethodGet)
rtr.HandleFunc("/heat/high/on", f.heatHighOn).Methods(http.MethodGet)
rtr.HandleFunc("/heat/high/off", f.heatHighOff).Methods(http.MethodGet)
rtr.HandleFunc("/heat/high/status", f.heatHighStatus).Methods(http.MethodGet)
rtr.HandleFunc("/energy/usage", f.getUsage).Methods(http.MethodGet)
srv := &http.Server{
Handler: rtr,
Addr: fmt.Sprintf(":%d", opts.Port),
}
if _, err := f.getPowerStatus(); err != nil {
log.Fatalf("could not get power status: %s", err.Error())
}
log.Printf("Listening on :%d...\n", opts.Port)
log.Fatal(srv.ListenAndServe())
}