package main import ( "fmt" "time" MQTT "github.com/eclipse/paho.mqtt.golang" "github.com/spf13/viper" ) var MQTTclient MQTT.Client 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", "") // 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) //MQTTclient.Subscribe("some_topic", 0, nil); //MQTTclient.Disconnect(250) } // 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) } }