forked from shirou/mqttcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.go
197 lines (166 loc) · 4.33 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
package main
import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"sync"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
var MaxClientIdLen = 8
var MaxRetryCount = 3
var messageReceived = false
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.Info("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()))
err := m.Disconnect()
if err != nil {
log.Error("Could not disconnect")
}
messageReceived = true
}
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()
host := c.String("host")
port := c.Int("p")
if host == "" {
getSettingsFromFile(c.String("conf"), opts)
}
clientId := c.String("i")
if clientId == "" {
clientId = getRandomClientId()
}
opts.SetClientID(clientId)
scheme := "tcp"
cafile := c.String("cafile")
key := c.String("key")
cert := c.String("cert")
insecure := c.Bool("insecure")
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 != "" {
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
}