-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
394 lines (328 loc) · 9.81 KB
/
main.go
File metadata and controls
394 lines (328 loc) · 9.81 KB
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
package main
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
gorillaWs "github.com/gorilla/websocket"
"github.com/joho/godotenv"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/websocket"
"github.com/kataras/neffos"
"github.com/kataras/neffos/gorilla"
"go.bug.st/serial"
"gocv.io/x/gocv"
)
// ngrok http -auth="username:password" 8080
// nohup go run main.go > ngrok.log &
// nohup ./ngrok http 8080 > ngrok.log &
// curl http://localhost:4040/api/tunnels
// jobs
func validPassword(password string) error {
correctPassword := os.Getenv("APP_PASSWORD")
if password != correctPassword {
return errors.New("Invalid token!")
}
return nil
}
func authMiddleware(ctx iris.Context) {
type authHeader struct {
Authorization string `header:"Authorization,required"`
}
var authHeaders authHeader
if err := ctx.ReadHeaders(&authHeaders); err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
if err := validPassword(authHeaders.Authorization); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Next()
return
}
// Limit pump runtime in "pumpRuntimeLimit" seconds for safety
func setTimer(duration int64, channel chan bool) {
startTime := time.Now().Unix()
for {
currentTime := time.Now().Unix()
channel <- true
// Stop timer
if (currentTime - startTime) > duration {
channel <- false
break
}
}
}
func main() {
// Loading .env vars file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
humiditySensorMinEnvVar := "APP_HUMIDITY_SENSOR_MIN"
pumpRuntimeLimitSecondsEnvVar := "APP_PUMP_RUNTIME_LIMIT_SECONDS"
lightStatusEnvVar := "APP_LIGHT_STATUS"
pumpStatusEnvVar := "APP_PUMP_STATUS"
enableCORSEnvVar := "APP_ENABLE_CORS"
portEnvVar := "APP_PORT"
var pumpRuntimeLimitSeconds int = 5
if len(os.Getenv(pumpRuntimeLimitSecondsEnvVar)) > 0 {
if value, err := strconv.Atoi(os.Getenv(pumpRuntimeLimitSecondsEnvVar)); err == nil {
pumpRuntimeLimitSeconds = value
}
}
var lightRelayStatus byte = '0'
if os.Getenv(lightStatusEnvVar) == "on" {
lightRelayStatus = '1'
}
var pumpRelayStatus byte = '0'
if os.Getenv(pumpStatusEnvVar) == "on" {
pumpRelayStatus = '1'
}
var websocketUpgrader neffos.Upgrader = websocket.DefaultGorillaUpgrader
if os.Getenv(enableCORSEnvVar) == "true" {
// For dev use only
websocketUpgrader = gorilla.Upgrader(gorillaWs.Upgrader{
CheckOrigin: func(*http.Request) bool {
return true
}})
}
websocketServer := websocket.New(websocketUpgrader, websocket.Events{
websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {
log.Printf("Server got: %s from [%s]", msg.Body, nsConn.Conn.ID())
return nil
},
})
websocketServer.OnConnect = func(c *websocket.Conn) error {
ctx := websocket.GetContext(c)
if err := validPassword(ctx.URLParamDefault("password", "")); err != nil {
c.Close()
ctx.StopWithError(iris.StatusInternalServerError, err)
return err
}
log.Printf("[%s] Connected to server!", c.ID())
return nil
}
websocketServer.OnDisconnect = func(c *websocket.Conn) {
log.Printf("[%s] Disconnected from server", c.ID())
}
websocketServer.OnUpgradeError = func(err error) {
log.Printf("Upgrade Error: %v", err)
}
sensorChannel := make(chan []byte)
defer close(sensorChannel)
// Initialize sensor data
var sensorOptionsBuffer []byte
sensorOptionsBuffer = append(sensorOptionsBuffer, lightRelayStatus)
sensorOptionsBuffer = append(sensorOptionsBuffer, pumpRelayStatus)
// Collect arduino sensor data and stream it via Websockets to the client
go func(sensorChannel chan []byte) {
mode := &serial.Mode{
BaudRate: 9600, // Same as Arduino code,
}
port, err := serial.Open("/dev/ttyACM0", mode)
defer port.Close()
if err != nil {
log.Fatal(err)
}
timerChannel := make(chan bool)
defer close(timerChannel)
timerChannelActive := false
// First position representes the Light Relay
// Second position represents the Pump Relay
sensorInputBuffer := <-sensorChannel
sensorOutputBuffer := make([]byte, 4)
// Create a cache to hold the last 10 humidty sensor values
cacheSize := 10
cache := NewFIFO(cacheSize)
var sensorOutput []byte
for {
select {
case sensorInputBuffer = <-sensorChannel:
fmt.Printf("Changed switch: %v\n", sensorInputBuffer)
case timerChannelActive = <-timerChannel:
if timerChannelActive {
sensorInputBuffer[1] = '1'
} else {
sensorInputBuffer[1] = '0'
}
default:
}
_, sensorInputBufferErr := port.Write(sensorInputBuffer)
if sensorInputBufferErr != nil {
log.Fatal(sensorInputBufferErr.Error())
break
}
n, sensorOutputBufferErr := port.Read(sensorOutputBuffer)
if sensorOutputBufferErr != nil {
log.Fatal(sensorOutputBufferErr)
break
}
if n == 0 {
fmt.Println("\nEOF")
break
}
for _, b := range sensorOutputBuffer[:n] {
if b == '{' {
sensorOutput = nil
} else if b == '}' {
sensorOutput = append(sensorOutput, b)
var sensorOutputJSON map[string]interface{}
if err := json.Unmarshal(sensorOutput, &sensorOutputJSON); err == nil {
humidityValue := sensorOutputJSON["humidityValue"].(float64)
// Push new sensor value to cache
cache.Set(time.Now().Unix(), humidityValue)
// cache.dump()
// Take average of the 10 last seen humidity sensor values
humidityValuesSum := cache.Avg()
humiditySensorMin, humiditySensorMinErr := strconv.ParseFloat(os.Getenv(humiditySensorMinEnvVar), 64)
if humiditySensorMinErr != nil {
humiditySensorMin = 300
}
// Water manually
if !timerChannelActive && sensorInputBuffer[1] == '1' {
go setTimer(int64(pumpRuntimeLimitSeconds), timerChannel)
// Water automatically based on parameter baseline
} else if !timerChannelActive && humidityValuesSum > humiditySensorMin {
sensorInputBuffer[1] = '1'
go setTimer(int64(pumpRuntimeLimitSeconds), timerChannel)
}
message := websocket.Message{
Body: sensorOutput,
IsNative: true,
}
websocketServer.Broadcast(nil, message)
}
sensorOutput = nil
}
sensorOutput = append(sensorOutput, b)
}
}
}(sensorChannel)
sensorChannel <- sensorOptionsBuffer
// Connect to USB/Pi Camera and send base64 images via Websockets to the client
go func() {
camera, err := gocv.VideoCaptureDevice(0)
if err != nil {
panic(err)
}
defer camera.Close()
image := gocv.NewMat()
for {
camera.Read(&image)
imageData, err := gocv.IMEncode(".jpg", image)
if err != nil {
fmt.Println(err)
} else {
imageEncodedLen := base64.StdEncoding.EncodedLen(len(imageData))
imageByteArr := make([]byte, imageEncodedLen)
base64.StdEncoding.Encode(imageByteArr, imageData)
urldata := "data:image/jpeg;base64," + string(imageByteArr)
message := websocket.Message{
Body: []byte(urldata),
IsNative: true,
}
websocketServer.Broadcast(nil, message)
}
time.Sleep(time.Second / 2)
}
}()
app := iris.New()
app.HandleDir("/", iris.Dir("./build"))
app.Get("/realtime", websocket.Handler(websocketServer))
if os.Getenv(enableCORSEnvVar) == "true" {
// Our custom CORS middleware.
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "http://localhost:3000")
ctx.Header("Access-Control-Allow-Headers", "Content-Type,Authorization,Sec-WebSocket-Protocol")
ctx.Header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
ctx.Header("Access-Control-Allow-Credentials", "true")
if ctx.Method() == iris.MethodOptions {
ctx.Header("Access-Control-Methods",
"POST, PUT, PATCH, DELETE")
ctx.Header("Access-Control-Allow-Headers",
"Access-Control-Allow-Origin,Content-Type,Authorization,Sec-WebSocket-Protocol")
ctx.Header("Access-Control-Max-Age",
"86400")
ctx.StatusCode(iris.StatusNoContent)
return
}
ctx.Next()
}
app.UseRouter(crs)
}
app.Post("/humiditySensorMin", authMiddleware, func(ctx iris.Context) {
type HumidityBody struct {
Value int
}
humidityBody := HumidityBody{Value: 400}
err := ctx.ReadJSON(&humidityBody)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
os.Setenv(humiditySensorMinEnvVar, strconv.Itoa(humidityBody.Value))
ctx.JSON(iris.Map{
"value": os.Getenv(humiditySensorMinEnvVar),
})
})
app.Get("/humiditySensorMin", authMiddleware, func(ctx iris.Context) {
if value, ok := os.LookupEnv(humiditySensorMinEnvVar); ok {
ctx.JSON(iris.Map{
"value": value,
})
return
}
})
app.Post("/lightRelay", authMiddleware, func(ctx iris.Context) {
type LightRelayBody struct {
Value string
}
lightRelayBody := LightRelayBody{Value: ""}
err := ctx.ReadJSON(&lightRelayBody)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
var lightRelayStatus byte = '0'
if lightRelayBody.Value == "on" {
lightRelayStatus = '1'
}
sensorOptionsBuffer[0] = lightRelayStatus
sensorChannel <- sensorOptionsBuffer
// Wait a bit for update to propagate on the Arduino
time.Sleep(time.Second * 3)
ctx.JSON(iris.Map{
"value": lightRelayStatus,
})
})
app.Post("/pumpRelay", authMiddleware, func(ctx iris.Context) {
type PumpRelayBody struct {
Value string
}
pumpRelayBody := PumpRelayBody{Value: ""}
err := ctx.ReadJSON(&pumpRelayBody)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
var pumpRelayStatus byte = '0'
if pumpRelayBody.Value == "on" {
pumpRelayStatus = '1'
}
sensorOptionsBuffer[1] = pumpRelayStatus
sensorChannel <- sensorOptionsBuffer
// Wait a bit for update to propagate on the Arduino
time.Sleep(time.Second * 3)
ctx.JSON(iris.Map{
"value": pumpRelayStatus,
})
})
app.Run(iris.Addr(":" + os.Getenv(portEnvVar)))
}