-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
255 lines (235 loc) · 5.06 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
package main
import (
"context"
"flag"
"html/template"
"log"
"net/http"
"os"
"os/signal"
"sort"
"sync"
"syscall"
"time"
"lib.hemtjan.st/client"
"lib.hemtjan.st/server"
"lib.hemtjan.st/transport/mqtt"
)
func main() {
mCfg := mqtt.MustFlags(flag.String, flag.Bool)
flgDelete := flag.String("delete", "", "Delete device (by topic)")
flgHttpBind := flag.String("http.bind", ":8933", "Bind HTTP to host:port")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
mq, err := mqtt.New(ctx, mCfg())
if err != nil {
log.Fatal(err)
}
go func() {
defer stop()
for {
ok, err := mq.Start()
if err != nil {
log.Printf("Error from MQTT: %s", err)
}
// If ok=true then the error is recoverable
if !ok {
break
}
log.Printf("Disconnected from MQTT, retrying in 3 seconds")
time.Sleep(3 * time.Second)
}
}()
srv := server.New(mq)
l := sync.RWMutex{}
devices := map[string]server.Device{}
getDevices := func() (out []server.Device) {
l.RLock()
for _, v := range devices {
out = append(out, v)
}
l.RUnlock()
sort.Slice(out, func(i, j int) bool {
return out[i].Id() < out[j].Id()
})
return
}
waitDelete := map[string][]chan struct{}{}
ch := make(chan server.Update, 1)
srv.SetUpdateChannel(ch)
go func() {
for {
upd, open := <-ch
if !open {
return
}
dev := upd.Device
switch upd.Type {
case server.AddedDevice:
if *flgDelete != "" && dev.Id() == *flgDelete {
_ = client.DeleteDevice(dev.Info(), mq)
}
log.Printf("Device Created: %s (\"%s\" with serial %s model %s made by %s)",
dev.Id(), dev.Name(), dev.SerialNumber(), dev.Model(), dev.Manufacturer())
l.Lock()
devices[dev.Id()] = dev
l.Unlock()
for _, ft := range dev.Features() {
log.Printf(" * %s (min/max/step: %d/%d/%d", ft.Name(), ft.Min(), ft.Max(), ft.Step())
go func(ft server.Feature) {
ch, _ := ft.OnUpdate()
for {
d, open := <-ch
if !open {
log.Printf("Device: %s feature: %s disappeared", dev.Id(), ft.Name())
return
}
log.Printf("Device: %s feature: %s is now %s", dev.Id(), ft.Name(), d)
}
}(ft)
}
case server.UpdatedDevice:
if dev != nil {
l.Lock()
devices[dev.Id()] = dev
l.Unlock()
}
for _, upd := range upd.Changes {
log.Printf("[%s] %s changed \"%s\" -> \"%s\" (%+v)",
dev.Id(),
upd.Field,
upd.Old,
upd.New,
upd.FeatureInfo,
)
}
case server.RemovedDevice:
if dev != nil {
l.Lock()
delete(devices, dev.Id())
v, ok := waitDelete[dev.Id()]
if ok {
delete(waitDelete, dev.Id())
}
l.Unlock()
if ok {
for _, ch := range v {
ch <- struct{}{}
}
}
}
log.Printf("Device Removed: %+v", dev)
}
}
}()
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
err := srv.Start(ctx)
if err != nil {
stop()
log.Print(err)
}
}()
web := http.Server{Addr: *flgHttpBind}
go func() {
defer wg.Done()
mux := http.NewServeMux()
web.Handler = mux
mux.HandleFunc("/", indexFunc(getDevices))
mux.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query()
id := qs.Get("id")
l.RLock()
dev := devices[id]
l.RUnlock()
if dev != nil {
ch := make(chan struct{}, 1)
l.Lock()
if _, ok := waitDelete[dev.Id()]; !ok {
waitDelete[dev.Id()] = []chan struct{}{}
}
waitDelete[dev.Id()] = append(waitDelete[dev.Id()], ch)
l.Unlock()
_ = client.DeleteDevice(dev.Info(), mq)
select {
case <-ch:
case <-time.After(2 * time.Second):
}
}
w.Header().Add("Location", "/")
w.WriteHeader(302)
})
err := web.ListenAndServe()
if err != nil {
stop()
log.Print(err)
}
}()
<-ctx.Done()
shutctx, shutcancel := context.WithTimeout(context.Background(), 10*time.Second)
_ = web.Shutdown(shutctx)
wg.Wait()
shutcancel()
}
func indexFunc(getDevices func() []server.Device) http.HandlerFunc {
tplIndex, err := template.New("index").Parse(htmlIndex)
if err != nil {
log.Fatalf("Error parsing template: %v", err)
}
return func(w http.ResponseWriter, r *http.Request) {
devs := getDevices()
err := tplIndex.Execute(w, devs)
if err != nil {
w.Write([]byte(err.Error()))
log.Print(err)
}
}
}
const htmlIndex = `<!DOCTYPE html>
<html>
<head>
<style>
html {
width: 100%;
max-width: 1000px;
margin: 0 auto;
}
table {
width: 100%;
}
.btn {
border: 0.1em solid red;
border-radius: 0.25em;
display: inline-block;
padding: 0.1em
}
.topic {
font-family: monospace;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Info</th>
</tr>
</thead>
<tbody>
{{ range $d := . }}
<tr>
<td><a class="btn" role="button" href="/delete?id={{$d.Id}}">Delete</a></td>
<td class="topic">{{$d.Id}}</td>
<td>{{$d.Name}}</td>
<td>{{$d.Manufacturer}} {{$d.Model}}</td>
</tr>
{{ end }}
</tbody>
</table>
`