41 lines
872 B
Go
41 lines
872 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
)
|
|
|
|
type Mqtt struct {
|
|
client mqtt.Client
|
|
}
|
|
|
|
func ConnectMqtt(cf MqttConfig) (Mqtt, error) {
|
|
var ret Mqtt
|
|
opts := mqtt.NewClientOptions()
|
|
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", cf.Remote, cf.Port))
|
|
if cf.ClientID != "" {
|
|
opts.SetClientID(cf.ClientID)
|
|
}
|
|
if cf.Username != "" {
|
|
opts.SetUsername(cf.Username)
|
|
}
|
|
if cf.Password != "" {
|
|
opts.SetPassword(cf.Password)
|
|
}
|
|
//opts.SetDefaultPublishHandler(messagePubHandler)
|
|
//opts.OnConnect = connectHandler
|
|
//opts.OnConnectionLost = connectLostHandler
|
|
opts.AutoReconnect = true
|
|
ret.client = mqtt.NewClient(opts)
|
|
token := ret.client.Connect()
|
|
token.Wait()
|
|
return ret, token.Error()
|
|
}
|
|
|
|
func (m *Mqtt) Publish(topic string, message string) error {
|
|
tok := m.client.Publish(topic, 0, false, message)
|
|
tok.Wait()
|
|
return tok.Error()
|
|
}
|