code beautifying

This commit is contained in:
2023-11-25 16:11:08 +01:00
parent b6332400b1
commit b0faf7378c

68
main.go
View File

@ -65,6 +65,48 @@ func dispatcher() {
}
}
func startMqttClient() MQTT.Client {
broker := os.Getenv("MQTT_BROKER")
if broker == "" {
log.Fatal("No broker given, set env var MQTT_BROKER")
}
prefix := "UDI"
uuid := uuid.New()
clientId := fmt.Sprintf("%s-%s", prefix, uuid)
opts := MQTT.NewClientOptions().
AddBroker(broker).
SetClientID(clientId).
SetConnectionLostHandler(onConnectionLost).
SetOnConnectHandler(onConnect).
SetReconnectingHandler(onReconnecting).
SetConnectRetry(true)
username := os.Getenv("MQTT_USERNAME")
if username != "" {
opts.SetUsername(username)
}
password := os.Getenv("MQTT_PASSWORD")
if password != "" {
opts.SetPassword(password)
}
log.Println("Trying to connect to broker")
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatalf("Unable to connect to broker %s, error %s", broker, token.Error())
}
log.Printf("Successfully connected to broker %s", broker)
return client
}
func stopMqttClient(client MQTT.Client) {
log.Println("Disconnecting from broker")
client.Disconnect(250)
}
func main() {
log.SetPrefix("UDI: ")
@ -75,29 +117,8 @@ func main() {
messageChannel = make(chan Message, 100)
go dispatcher()
broker := os.Getenv("MQTT_BROKER")
if broker == "" {
log.Fatal("No broker given, set env var MQTT_BROKER")
}
prefix := "UDI"
uuid := uuid.New()
clientId := fmt.Sprintf("%s-%s", prefix, uuid)
mqttOpts := MQTT.NewClientOptions().
AddBroker(broker).
SetClientID(clientId).
SetConnectionLostHandler(onConnectionLost).
SetOnConnectHandler(onConnect).
SetReconnectingHandler(onReconnecting).
SetConnectRetry(true)
client := MQTT.NewClient(mqttOpts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatalf("Unable to connect to broker %s, error %s", broker, token.Error())
}
log.Printf("Successfully connected to broker %s", broker)
mqttClient := startMqttClient()
defer stopMqttClient(mqttClient)
log.Println("UDI running")
@ -106,6 +127,5 @@ func main() {
<-c
log.Println("Terminating UDI")
client.Disconnect(250)
}