graphicek/server/services/mqtt_service.go

31 lines
666 B
Go
Raw Normal View History

2024-04-01 17:26:30 +02:00
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
}