forked from shirou/mqforward
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.go
155 lines (129 loc) · 3.35 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package main
import (
"crypto/rand"
"fmt"
"strings"
"sync"
log "github.com/Sirupsen/logrus"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
const (
MaxClientIdLen = 10
)
type MqttConf struct {
Hostname string
Port int
Username string
Password string
Cafilepath string
Topic string
Debug string
}
type MqttClient struct {
Client MQTT.Client
Opts *MQTT.ClientOptions
Config MqttConf
Subscribed map[string]byte
mqttChan chan Message // chan to forwarder
commandChan chan string // chan from forwarder
lock *sync.Mutex // use for reconnect
}
//
// with Connects connect to the MQTT broker with Options.
func NewMqttClient(conf MqttConf, mqttChan chan Message, commandChan chan string) (*MqttClient, error) {
opts := MQTT.NewClientOptions()
port := conf.Port
if port == 0 {
port = 1883
}
scheme := "tcp"
if port == 8883 {
scheme = "ssl"
}
brokerUri := fmt.Sprintf("%s://%s:%d", scheme, conf.Hostname, port)
log.Infof("Broker URI: %s", brokerUri)
opts.AddBroker(brokerUri)
if conf.Username != "" {
opts.SetUsername(conf.Username)
}
if conf.Password != "" {
opts.SetPassword(conf.Password)
}
clientId := getRandomClientId()
opts.SetClientID(clientId)
opts.SetAutoReconnect(true)
topic := conf.Topic
if strings.HasSuffix(topic, "#") == false {
topic = topic + "#"
}
subscribed := map[string]byte{
topic: byte(0),
}
ret := &MqttClient{
Config: conf,
Subscribed: subscribed,
lock: new(sync.Mutex),
mqttChan: mqttChan,
commandChan: commandChan,
}
opts.SetOnConnectHandler(ret.SubscribeOnConnect)
opts.SetConnectionLostHandler(ret.ConnectionLost)
ret.Opts = opts
client, err := ret.Connect(conf, opts, subscribed)
if err != nil {
return nil, err
}
ret.Client = client
return ret, nil
}
// connects MQTT broker
func (m MqttClient) Connect(conf MqttConf, opts *MQTT.ClientOptions, subscribed map[string]byte) (MQTT.Client, error) {
m.Client = MQTT.NewClient(m.Opts)
log.Info("connecting...")
if token := m.Client.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return m.Client, nil
}
// getRandomClientId returns randomized ClientId.
func getRandomClientId() string {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, MaxClientIdLen)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
return "mqttforward-" + string(bytes)
}
func (m *MqttClient) SubscribeOnConnect(client MQTT.Client) {
log.Infof("mqtt connected")
log.Infof("subscribed: %v", m.Subscribed)
if len(m.Subscribed) > 0 {
token := client.SubscribeMultiple(m.Subscribed, m.onMessageReceived)
token.Wait()
if token.Error() != nil {
log.Error(token.Error())
}
}
}
func (m *MqttClient) ConnectionLost(client MQTT.Client, reason error) {
log.Errorf("client disconnected: %s", reason)
}
func (m *MqttClient) Disconnect() error {
if m.Client.IsConnected() {
m.Client.Disconnect(20)
log.Info("client disconnected")
}
return nil
}
func (m *MqttClient) onMessageReceived(client MQTT.Client, message MQTT.Message) {
log.Infof("topic:%s", message.Topic())
// Remove topic root
ct := strings.TrimRight(m.Config.Topic, "#")
topic := strings.Replace(message.Topic(), ct, "", 1)
chun := Message{
Topic: topic,
Payload: message.Payload(),
}
m.mqttChan <- chun
}