openpdu/src/mqtt.go

87 lines
2.2 KiB
Go
Raw Normal View History

2020-12-23 09:11:11 +00:00
package main
import (
"fmt"
"time"
2020-12-23 09:11:11 +00:00
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/viper"
2020-12-23 09:11:11 +00:00
)
var MQTTclient MQTT.Client
2020-12-23 09:11:11 +00:00
func init() {
viper.SetDefault("MqttCliendID", "OpenPDU") // max 23 chars
viper.SetDefault("MqttPrefix", "openpdu") // max 23 chars
viper.SetDefault("MqttSchema", "tcp")
viper.SetDefault("MqttHost", "localhost")
viper.SetDefault("MqttPort", "1883")
viper.SetDefault("MqttUsername", "")
viper.SetDefault("MqttPassword", "")
2020-12-23 09:11:11 +00:00
// MQTT.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
// MQTT.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
// MQTT.WARN = log.New(os.Stdout, "[WARN] ", 0)
// MQTT.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
2020-12-23 09:11:11 +00:00
//MQTTclient.Subscribe("some_topic", 0, nil);
//MQTTclient.Disconnect(250)
2020-12-23 09:11:11 +00:00
}
// https://girishjoshi.io/post/golang-paho-mqtt/
func mqttLoop() {
uri := viper.GetString("MqttSchema") + "://" + viper.GetString("MqttHost") + ":" + viper.GetString("MqttPort")
opts := MQTT.NewClientOptions().AddBroker(uri)
opts.SetClientID(viper.GetString("MqttCliendID"))
if username := viper.GetString("MqttUsername"); username != "" {
opts.SetUsername(username)
}
if password := viper.GetString("MqttPassword"); password != "" {
opts.SetPassword(password)
}
opts.SetAutoReconnect(true)
opts.SetConnectRetryInterval(5 * time.Second)
opts.SetConnectTimeout(5 * time.Second)
opts.SetConnectionLostHandler(func(c MQTT.Client, err error) {
fmt.Printf("!!!!!! mqtt connection lost error: %s\n" + err.Error())
})
opts.SetReconnectingHandler(func(c MQTT.Client, options *MQTT.ClientOptions) {
fmt.Println("...... mqtt reconnecting ......")
})
opts.SetOnConnectHandler(func(c MQTT.Client) {
fmt.Println("...... mqtt connected ......")
// MQTTclient.Publish("openpdu/status", 0, false, "connected")
})
MQTTclient = MQTT.NewClient(opts)
for {
token := MQTTclient.Connect()
token.Wait()
if MQTTclient.IsConnected() {
break
}
time.Sleep(5 * time.Second)
}
}
func MQTTreconfigure() {
if MQTTclient.IsConnected() {
MQTTclient.Disconnect(250)
}
go mqttLoop()
}
func MQTTpublish(topic string, value string) {
if MQTTclient.IsConnected() {
MQTTclient.Publish(viper.GetString("MqttPrefix")+"/"+topic, 0, false, value)
}
}