-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.go
93 lines (79 loc) · 2.16 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 main
import (
"fmt"
"strings"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
)
type MQTT struct {
Enabled bool `yaml:"enabled"`
Broker *Broker `yaml:"broker"`
Topic Topic `yaml:"topic"`
Client *Client `yaml:"-"`
}
type Topic string
func (t *Topic) Name(name string) string {
if !strings.HasSuffix(string(*t), "/") {
return string(*t) + "/" + name
}
return string(*t) + name
}
type Broker struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"`
ClientID string `yaml:"client_id"`
}
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
log.WithFields(log.Fields{
"type": "mqtt",
"topic": msg.Topic(),
"payload": msg.Payload(),
}).Debug("received message")
}
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
r := client.OptionsReader()
s := r.Servers()
log.WithFields(log.Fields{
"type": "mqtt",
"urls": fmt.Sprintf("%+v", s),
}).Infof("connected")
}
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
r := client.OptionsReader()
s := r.Servers()
log.WithFields(log.Fields{
"type": "mqtt",
"error": err.Error(),
"urls": fmt.Sprintf("%+v", s),
}).Warn("connection lost")
}
type Client struct {
c mqtt.Client
}
func NewClient(broker *Broker) (*Client, error) {
if broker.Port == 0 {
broker.Port = 1833
}
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker.Host, broker.Port))
opts.SetClientID(broker.ClientID)
opts.SetUsername(broker.Username)
opts.SetPassword(broker.Password)
opts.SetDefaultPublishHandler(messagePubHandler)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
return nil, fmt.Errorf("failed to connect to broker: %w", token.Error())
}
return &Client{c: client}, nil
}
func (c *Client) Publish(topic string, data []byte) {
token := c.c.Publish(topic, 1, false, data)
token.Wait()
}
func (c *Client) Client() mqtt.Client {
return c.c
}