31 lines
666 B
Go
31 lines
666 B
Go
|
|
package services
|
||
|
|
|
||
|
|
import (
|
||
|
|
MQTT "github.com/eclipse/paho.mqtt.golang"
|
||
|
|
)
|
||
|
|
|
||
|
|
type MQTTService struct {
|
||
|
|
// TODO:
|
||
|
|
// ctx *Context
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *MQTTService) Publish(server string, username string, password string, clientId string, retain bool, qos byte, topic string, message string) error {
|
||
|
|
opts := MQTT.NewClientOptions()
|
||
|
|
opts.AddBroker(server)
|
||
|
|
opts.SetUsername(username)
|
||
|
|
opts.SetPassword(password)
|
||
|
|
opts.SetClientID(clientId)
|
||
|
|
|
||
|
|
client := MQTT.NewClient(opts)
|
||
|
|
if token := client.Connect(); token.Wait() && token.Error() != nil {
|
||
|
|
return token.Error()
|
||
|
|
}
|
||
|
|
|
||
|
|
token := client.Publish(topic, qos, retain, message)
|
||
|
|
token.Wait()
|
||
|
|
|
||
|
|
client.Disconnect(250)
|
||
|
|
|
||
|
|
return nil
|
||
|
|
}
|