mqtt stuff 3
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful

This commit is contained in:
2024-01-14 13:59:01 +01:00
parent 9624d5d53d
commit dd394877f3
3 changed files with 74 additions and 4 deletions

56
src/locsrv/mqtt/mqtt.go Normal file
View File

@ -0,0 +1,56 @@
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
}
return &mqttHandle
}
func (self *MqttHandle) Publish(message string) error {
if ! self.initialized {
return fmt.Errorf("MQTT connection not initialized")
}
token := self.client.Publish(self.pubTopic, 0, false, message)
token.Wait()
if token.Error() != nil {
return fmt.Errorf("MQTT publish failed: %v", token.Error())
}
return nil
}