-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.go
37 lines (31 loc) · 1.07 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
package main
import (
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"log"
)
func getMQTTClient(config Config, logger Logger) (mqtt.Client, error) {
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
logger.Info(fmt.Sprintf("Connected to %s:%d", config.MQTTBroker, config.MQTTBrokerPort))
}
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
logger.Warn(fmt.Sprintf("Connect lost: %v", err))
logger.Info("Reconnecting...")
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatalln(token.Error())
}
}
logger.Info("Connecting...")
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", config.MQTTBroker, config.MQTTBrokerPort))
opts.SetClientID(config.ClientId)
opts.SetUsername(config.MQTTUser)
opts.SetPassword(config.MQTTPassword)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return client, nil
}