/
mqtt.go
76 lines (63 loc) · 1.84 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
package mqtt
import (
"math/rand"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
)
type MQTTServer interface {
Publish(address string, topic string, payload interface{})
Subscribe(address string, topic string, handler mqtt.MessageHandler)
}
type server struct{}
func init() {
rand.Seed(time.Now().UnixNano())
}
func New() *server {
return &server{}
}
func randStringRunes(n int) string {
letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// Subscribe - subscribe to an MQTT topic and pass in a messageHandler
func (m *server) Subscribe(address string, topic string, handler mqtt.MessageHandler) {
if address == "" {
log.Error("mqtt address isn't configured")
return
}
opts := mqtt.NewClientOptions().AddBroker(address)
opts.SetClientID("member-server-subscriber-" + randStringRunes(12))
opts.OnConnect = func(c mqtt.Client) {
if token := c.Subscribe(topic, 0, handler); token.Wait() && token.Error() != nil {
log.Error(token.Error())
}
}
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Error(token.Error())
return
}
log.Debug("Connected to server\n")
}
// Publish - publish to an MQTT topic
func (m *server) Publish(address string, topic string, payload interface{}) {
if address == "" {
log.Error("mqtt address isn't configured")
return
}
opts := mqtt.NewClientOptions().AddBroker(address)
opts.SetClientID("member-server-publisher-" + randStringRunes(12))
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Error(token.Error())
return
}
token := client.Publish(topic, 0, false, payload)
token.Wait()
client.Disconnect(250)
}