-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.go
55 lines (47 loc) · 1.23 KB
/
mqtt.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
package main
import (
"fmt"
"log"
"net/url"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
var (
client mqtt.Client
goalTopic = "goals"
)
func connect(clientID string, uri *url.URL) mqtt.Client {
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s", uri.Host))
client = mqtt.NewClient(opts)
token := client.Connect()
for !token.WaitTimeout(3 * time.Second) {
}
if err := token.Error(); err != nil {
log.Fatal(err)
}
return client
}
func subscribe(uri *url.URL) {
client.Subscribe("goals", 0, func(client mqtt.Client, msg mqtt.Message) {
increaseScore(string(msg.Payload()))
})
client.Subscribe("score/increase", 0, func(client mqtt.Client, msg mqtt.Message) {
increaseScore(string(msg.Payload()))
})
client.Subscribe("score/undo", 0, func(client mqtt.Client, msg mqtt.Message) {
undoScore()
})
client.Subscribe("score/reset", 0, func(client mqtt.Client, msg mqtt.Message) {
resetScore()
})
client.Subscribe("game/start", 0, func(client mqtt.Client, msg mqtt.Message) {
startGame()
})
client.Subscribe("game/stop", 0, func(client mqtt.Client, msg mqtt.Message) {
stopGame()
})
}
func publish(topic string, message string, retain bool) {
client.Publish(topic, 0, retain, message)
}