-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
237 lines (206 loc) · 5.43 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
package main
import "context"
import "encoding/json"
import "flag"
import "html/template"
import "io/ioutil"
import "log"
import "net"
import "net/http"
import "os"
import "os/signal"
import "runtime"
import "strconv"
import "sync"
import "time"
import "github.com/hatstand/hodoor/dash"
import "github.com/hatstand/hodoor/doorbell"
import "github.com/hatstand/hodoor/model"
import "github.com/hatstand/hodoor/webpush"
import "github.com/stianeikeland/go-rpio"
import wp "github.com/SherClockHolmes/webpush-go"
var port = flag.Int("port", 8080, "Port to start HTTP server on")
var deviceIndex = flag.Int("device", 2, "Audio device to listen with")
var threshold = flag.Int("threshold", 3000, "Arbitrary threshold for doorbell activation")
var webpushKey = flag.String("key", "", "Private key for sending webpush requests")
var GPIOPin = flag.Int("pin", 18, "GPIO pin to toggle to open door")
var delaySeconds = flag.Duration("delay", 5*time.Second, "Time in seconds to hold door open")
var dashMAC = flag.String("dash", "", "MAC address of dash button")
func mustParseMAC(s string) net.HardwareAddr {
mac, err := net.ParseMAC(s)
if err != nil {
panic(err)
}
return mac
}
type AssistantResponse struct {
Speech string `json:"speech"`
DisplayText string `json:"displayText"`
}
type gpioHandler struct {
lock sync.Mutex
pin rpio.Pin
db *model.Database
}
func GpioHandler(pin rpio.Pin) *gpioHandler {
db, err := model.OpenDatabase("db")
if err != nil {
log.Fatal("Failed to open database: ", err)
}
return &gpioHandler{pin: pin, db: db}
}
func (f *gpioHandler) HandleButtonPress() {
log.Printf("Dash button pressed!")
f.openDoor()
}
func (f *gpioHandler) openDoor() {
timer := time.NewTimer(*delaySeconds)
go func() {
f.lock.Lock()
defer f.lock.Unlock()
log.Printf("Toggling door on pin %d for %d seconds", f.pin, *delaySeconds)
f.pin.Output()
f.pin.High()
defer f.pin.Low()
<-timer.C
}()
}
func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch path := r.URL.Path; path {
case "/":
f.handleRoot(w, r)
case "/hodoor":
f.handleOpenDoor(w, r)
case "/subscribe":
f.handleSubscribe(w, r)
case "/ping":
f.handlePing(w, r)
default:
f.handleRoot(w, r)
}
}
func (f *gpioHandler) handleRoot(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/index.html")
if err != nil {
log.Fatal(err)
}
t.Execute(w, nil)
}
func (f *gpioHandler) handleOpenDoor(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/hodoor.html")
if err != nil {
log.Fatal(err)
}
type TemplateOutput struct {
Pin rpio.Pin
Delay int
}
output := &TemplateOutput{f.pin, int(delaySeconds.Seconds())}
t.Execute(w, output)
f.openDoor()
}
func (f *gpioHandler) handleSubscribe(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
sub, err := webpush.SubscriptionFromJSON(body)
if err != nil {
log.Printf("Failed to parse subscription: %v", err)
http.Error(w, "Failed to parse subscription", 400)
return
}
defer r.Body.Close()
log.Printf("Subscribing user: %v", sub)
f.db.Subscribe(sub)
}
func (f *gpioHandler) handlePing(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resp := AssistantResponse{"Opening door", "Opening door"}
j, err := json.Marshal(resp)
if err != nil {
http.Error(w, "Failed to serialise JSON", 500)
return
}
err = f.notifySubscribers("Ping!")
if err != nil {
http.Error(w, "Failed to notify subscribers", 500)
return
}
w.Write(j)
}
func (f *gpioHandler) notifySubscribers(message string) error {
subs, err := f.db.GetSubscriptions()
if err != nil {
log.Printf("Failed to fetch subscribers: %v", err)
return err
}
for _, sub := range subs {
go func(sub *wp.Subscription) {
log.Printf("Sending webpush to endpoint: %v", sub.Endpoint)
err := webpush.Send([]byte(message), sub, *webpushKey, 60)
if err != nil {
log.Printf("Failed to send webpush: %v", err)
} else {
log.Printf("Sent webpush successfully")
}
}(sub)
}
runtime.Gosched()
return nil
}
func main() {
flag.Parse()
runtime.GOMAXPROCS(6)
err := rpio.Open()
defer rpio.Close()
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
handler := GpioHandler(rpio.Pin(*GPIOPin))
ringCh, err := doorbell.Listen(ctx, *deviceIndex, *threshold)
if err != nil {
log.Fatal(err)
}
buttonCh, err := dash.Listen(ctx, mustParseMAC(*dashMAC))
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case <-ringCh:
handler.notifySubscribers("DING DONG!")
case <-buttonCh:
handler.openDoor()
case <-ctx.Done():
return
}
}
}()
http.Handle("/hodoor", handler)
http.Handle("/", handler)
http.Handle("/subscribe", handler)
http.Handle("/ping", handler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
srv := &http.Server{Addr: ":" + strconv.Itoa(*port)}
go func() {
log.Printf("Starting HTTP Server on port: %d", *port)
err := srv.ListenAndServe()
if err != nil {
// Probably happens during shutdown.
log.Printf("HTTP Server error: %v", err)
}
}()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
signal.Notify(signalCh, os.Kill)
select {
case <-ctx.Done():
timeout, httpCancel := context.WithDeadline(ctx, time.Now().Add(time.Second*5))
defer httpCancel()
srv.Shutdown(timeout)
return
case <-signalCh:
cancel()
}
}