/
mqtt.go
79 lines (66 loc) · 1.55 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/eclipse/paho.mqtt.golang"
)
type mqttClient struct {
options *mqtt.ClientOptions
hub *Hub
}
func newMqttClient(hub *Hub, mqttHost string, mqttPort int) *mqttClient {
m := &mqttClient{
options: mqtt.NewClientOptions(),
hub: hub,
}
m.options.SetConnectTimeout(5 * time.Second)
m.options.SetMaxReconnectInterval(10 * time.Second)
m.options.AddBroker(fmt.Sprintf("tcp://%s:%d", mqttHost, mqttPort))
m.options.SetOnConnectHandler(func(cl mqtt.Client) {
m.onConnect(cl)
})
return m
}
func (m *mqttClient) run(ctx context.Context) {
var client mqtt.Client
// Try connecting
// Once connected, mqtt will keep reconnecting
for {
client = mqtt.NewClient(m.options)
token := client.Connect()
token.Wait()
if token.Error() == nil {
break
}
// Handle stop request during just connection attempts
select {
case <-ctx.Done():
return
default:
}
}
<-ctx.Done()
client.Disconnect(0)
}
func (m *mqttClient) onConnect(cl mqtt.Client) {
log.Print("Connected to MQTT broker")
if cl.Subscribe("thsensor/+/report", 0, func(cl mqtt.Client, msg mqtt.Message) {
m.onMessage(cl, msg)
}).Wait() != true {
log.Print("Subscribing failed")
}
}
func (m *mqttClient) onMessage(cl mqtt.Client, msg mqtt.Message) {
idstr := strings.Split(msg.Topic(), "/")
var id uint64
var err error
if id, err = strconv.ParseUint(idstr[1], 16, 8); err != nil {
log.Printf("Received invalid topic: %s\n", msg.Topic())
return
}
m.hub.fromMqtt <- uint8(id)
}