mqtt stuff 3
This commit is contained in:
56
src/locsrv/mqtt/mqtt.go
Normal file
56
src/locsrv/mqtt/mqtt.go
Normal 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
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user