-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (78 loc) · 1.87 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
package main
import (
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/go-playground/log"
"time"
)
const TOPIC = "/feeds/door"
const THRESHOLD = 10
var done = make(chan bool)
var open = false
func main() {
log.Info("starting ...")
c := createClient()
connect(c)
forever := make(chan bool)
go listen(c)
<-forever
}
func createClient() mqtt.Client {
log.Info("creating client ...")
opts := mqtt.NewClientOptions().AddBroker("farmer.cloudmqtt.com:10812")
opts.SetUsername("...")
opts.SetPassword("...")
return mqtt.NewClient(opts)
}
func connect(c mqtt.Client) {
log.Info("trying to connect ...")
if token := c.Connect(); token.Wait() && token.Error() != nil {
log.Error("Error when trying to connect", token.Error())
}
/* token := c.Connect()
for !token.WaitTimeout(3 * time.Second) {
}
if err := token.Error(); err != nil {
log.Fatal(err)
}*/
}
func listen(c mqtt.Client) {
connect(c)
log.Info("subscribing to channel " + TOPIC)
c.Subscribe(TOPIC, 0, func(client mqtt.Client, msg mqtt.Message) {
log.Info("Received value " + string(msg.Payload()) + " from channel " + TOPIC)
if string(msg.Payload()) == "1" && open == false {
done = make(chan bool)
open = true
counter := 1
time.Sleep(THRESHOLD * time.Second)
handleOpenDoor(counter)
} else if string(msg.Payload()) == "1" && open == true {
log.Info("Door is still open")
} else if string(msg.Payload()) == "0" {
log.Info("Door is closed again")
open = false
close(done)
} else {
log.Info("Unknown message. ")
}
})
}
func handleOpenDoor(counter int) {
log.Info("Door is open... Sven will handle this!")
go func() {
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-done:
log.Info("done")
ticker.Stop()
return
case <-ticker.C:
counter++
fmt.Print("Trigger Warning #")
fmt.Println(counter)
}
}
}()
}