59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package mqtt
|
|
|
|
import (
|
|
"log"
|
|
"os"
|
|
"fmt"
|
|
MQTT "github.com/eclipse/paho.mqtt.golang"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
|
|
|
|
type MqttHandle struct {
|
|
initialized bool
|
|
pubTopic string
|
|
client MQTT.Client
|
|
}
|
|
|
|
func New() *MqttHandle {
|
|
var mqttHandle MqttHandle
|
|
mqttHandle.initialized = true
|
|
|
|
mqttOpts := MQTT.NewClientOptions().
|
|
AddBroker(os.Getenv("MQTT_BROKER")).
|
|
SetClientID(fmt.Sprintf("locsrv-%s", uuid.New())).
|
|
SetConnectRetry(true)
|
|
mqttHandle.client= MQTT.NewClient(mqttOpts)
|
|
if token := mqttHandle.client.Connect(); token.Wait() && token.Error() != nil {
|
|
log.Printf("Unable to connect to broker, error %v", token.Error())
|
|
mqttHandle.initialized = false
|
|
}
|
|
|
|
mqttHandle.pubTopic = os.Getenv("MQTT_TOPIC")
|
|
if mqttHandle.pubTopic == "" {
|
|
log.Printf("No topic set")
|
|
mqttHandle.initialized = false
|
|
}
|
|
log.Printf("MQTT connection established")
|
|
return &mqttHandle
|
|
}
|
|
|
|
func (self *MqttHandle) Publish(topicPost string, message string) error {
|
|
if ! self.initialized {
|
|
return fmt.Errorf("MQTT connection not initialized")
|
|
}
|
|
|
|
topic := fmt.Sprintf("%s/%s", self.pubTopic, topicPost)
|
|
token := self.client.Publish(topic, 0, true, message)
|
|
token.Wait()
|
|
if token.Error() != nil {
|
|
return fmt.Errorf("MQTT publish failed: %v", token.Error())
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
|
|
|