-
Notifications
You must be signed in to change notification settings - Fork 3
/
mqtt.go
93 lines (77 loc) · 1.67 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package mqtt
import (
"context"
"strconv"
"strings"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/rs/zerolog/log"
"github.com/thejerf/suture/v4"
)
func Int(i int64) string {
return strconv.FormatInt(i, 10)
}
type Topic string
func (t Topic) Join(topics ...string) string {
return string(t) + "/" + Join(topics...)
}
func Join(topics ...string) string {
return strings.Join(topics, "/")
}
func Wait(t mqtt.Token) error {
t.Wait()
return t.Error()
}
func TopicServerState(topic Topic) string {
return topic.Join("server", "state")
}
func NewConn(topic Topic, address, username, password string) Conn {
client := mqtt.NewClient(mqtt.NewClientOptions().
AddBroker(address).
SetUsername(username).
SetPassword(password).
SetWill(TopicServerState(topic), "offline", 0, true).
SetOnConnectHandler(func(c mqtt.Client) {
c.Publish(TopicServerState(topic), 0, true, "online")
}))
return Conn{
Client: client,
Topic: topic,
address: address,
username: username,
readyC: make(chan struct{}),
}
}
type Conn struct {
Client mqtt.Client
Topic Topic
address string
username string
readyC chan struct{}
}
func (h Conn) String() string {
return "mqtt.Conn"
}
func (h Conn) Serve(ctx context.Context) error {
select {
case <-h.readyC:
return suture.ErrDoNotRestart
default:
}
t := h.Client.Connect()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.Done():
}
if err := t.Error(); err != nil {
return err
}
log.Info().Str("address", h.address).Str("username", h.username).Msg("Connected to MQTT broker")
close(h.readyC)
<-ctx.Done()
h.Client.Disconnect(0)
return ctx.Err()
}
func (h Conn) Ready() {
<-h.readyC
}