-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmqtt.go
213 lines (180 loc) · 4.72 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"sync"
log "github.com/Sirupsen/logrus"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/urfave/cli/v2"
)
var MaxClientIdLen = 8
var MaxRetryCount = 3
type MQTTClient struct {
Client MQTT.Client
Opts *MQTT.ClientOptions
RetryCount int
Subscribed map[string]byte
lock *sync.Mutex // use for reconnect
}
// Connects connect to the MQTT broker with Options.
func (m *MQTTClient) Connect() (MQTT.Client, error) {
m.Client = MQTT.NewClient(m.Opts)
log.Infof("connecting...")
if token := m.Client.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return m.Client, nil
}
func (m *MQTTClient) Publish(topic string, payload []byte, qos int, retain bool, sync bool) error {
token := m.Client.Publish(topic, byte(qos), retain, payload)
if sync == true {
token.Wait()
}
return token.Error()
}
func (m *MQTTClient) Disconnect() error {
if m.Client.IsConnected() {
m.Client.Disconnect(20)
log.Info("client disconnected")
}
return nil
}
func (m *MQTTClient) SubscribeOnConnect(client MQTT.Client) {
log.Infof("client connected")
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) onMessageReceived(client MQTT.Client, message MQTT.Message) {
log.Infof("topic:%s / msg:%s", message.Topic(), message.Payload())
fmt.Println(string(message.Payload()))
}
func getCertPool(pemPath string) (*x509.CertPool, error) {
certs := x509.NewCertPool()
pemData, err := ioutil.ReadFile(pemPath)
if err != nil {
return nil, err
}
certs.AppendCertsFromPEM(pemData)
return certs, 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 "mqttcli-" + string(bytes)
}
// NewOption returns ClientOptions via parsing command line options.
func NewOption(c *cli.Context) (*MQTT.ClientOptions, error) {
opts := MQTT.NewClientOptions()
conf := c.String("conf")
defaultConf, exists := existsDefaultConfigFile()
if conf != DefaultConfigFilePath {
log.Debugf("reading from config file: %s", conf)
if err := getSettingsFromFile(conf, opts); err != nil {
return nil, err
}
} else if conf != "" && exists {
log.Debugf("reading from default config file: %s", defaultConf)
if err := getSettingsFromFile(defaultConf, opts); err != nil {
return nil, err
}
}
// override
host := c.String("host")
port := c.Int("p")
clientId := c.String("i")
if clientId == "" {
clientId = getRandomClientId()
}
opts.SetClientID(clientId)
scheme := "tcp"
if port == 8883 {
scheme = "ssl"
}
cafile := c.String("cafile")
key := c.String("key")
cert := c.String("cert")
insecure := c.Bool("insecure")
if cafile != "" || key != "" || cert != "" {
log.Debugf("reading from args")
tlsConfig, ok, err := makeTlsConfig(cafile, cert, key, insecure)
if err != nil {
return nil, err
}
if ok {
opts.SetTLSConfig(tlsConfig)
scheme = "ssl"
}
}
user := c.String("u")
if user != "" {
opts.SetUsername(user)
}
password := c.String("P")
if password != "" {
opts.SetPassword(password)
}
if host == "" {
host = "localhost"
}
if len(opts.Servers) == 0 {
brokerUri := fmt.Sprintf("%s://%s:%d", scheme, host, port)
log.Infof("Broker URI: %s", brokerUri)
opts.AddBroker(brokerUri)
}
opts.SetAutoReconnect(true)
return opts, nil
}
// makeTlsConfig creats new tls.Config. If returned ok is false, does not need set to MQTToption.
func makeTlsConfig(cafile, cert, key string, insecure bool) (*tls.Config, bool, error) {
TLSConfig := &tls.Config{InsecureSkipVerify: false}
var ok bool
if insecure {
TLSConfig.InsecureSkipVerify = true
ok = true
}
if cafile != "" {
certPool, err := getCertPool(cafile)
if err != nil {
return nil, false, err
}
TLSConfig.RootCAs = certPool
ok = true
}
if cert != "" {
certPool, err := getCertPool(cert)
if err != nil {
return nil, false, err
}
TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
TLSConfig.ClientCAs = certPool
ok = true
}
if key != "" {
if cert == "" {
return nil, false, fmt.Errorf("key specified but cert is not specified")
}
cert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, false, err
}
TLSConfig.Certificates = []tls.Certificate{cert}
ok = true
}
return TLSConfig, ok, nil
}