Fail on mqtt connection failure

Fail to start the service, if the initial mqtt connection fails
This commit is contained in:
Felix Niederwanger 2023-12-04 22:03:36 +01:00
parent 22bfe751de
commit 1b1419961b
Signed by: phoenix
GPG key ID: 6E77A590E3F6D71C
2 changed files with 6 additions and 9 deletions

View file

@ -92,7 +92,6 @@ func parseProgramArguments() error {
}
func main() {
fmt.Println("ot-browser")
devices = make(map[string]Location, 0)
config.SetDefaults()
parseProgramArguments()
@ -104,7 +103,8 @@ func main() {
}
mqtt.Received = mqttRecv
if err := mqtt.Connect(config.mqttRemote, config.mqttTopic, "", "", config.mqttClientId); err != nil {
fmt.Fprintf(os.Stderr, "mqtt error: %s\n", err)
fmt.Fprintf(os.Stderr, "%s\n", err)
fmt.Fprintf(os.Stderr, "error: mqtt connection failed\n")
os.Exit(1)
}
@ -115,7 +115,7 @@ func main() {
http.HandleFunc("/devices.json", handlerDevices)
http.HandleFunc("/locations", handlerLocations)
http.HandleFunc("/devices/", handlerDeviceQuery)
fmt.Println("Serving: http://" + config.bindAddr)
fmt.Println("ot-browser serving: http://" + config.bindAddr)
log.Fatal(http.ListenAndServe(config.bindAddr, nil))
}

View file

@ -32,7 +32,6 @@ func (mqtt *MQTTReceiver) Connect(remote string, topic string, username string,
}
// Add default port to remote if not existing
// TODO: IPv6 handling is not yet implemented
if !strings.Contains(remote, ":") {
remote += ":1883"
}
@ -55,9 +54,8 @@ func (mqtt *MQTTReceiver) Connect(remote string, topic string, username string,
opts.SetAutoReconnect(true)
c := MQTT.NewClient(opts)
mqtt.mqtt = c
// TODO: Add listener also if initial connection fails (and attempt reconnects)
if token := c.Connect(); token.Wait() && token.Error() != nil {
log.Println(fmt.Sprintf("Error connecting to MQTT %s - %s", remote, token.Error()))
return token.Error()
} else {
if token := c.Subscribe(topic, 0, mqtt.mqttReceive); token.Wait() && token.Error() != nil {
log.Println(fmt.Sprintf("Error subscribing listener %s - %s", remote, token.Error()))
@ -97,9 +95,8 @@ func (mqtt *MQTTReceiver) mqttReceive(client MQTT.Client, msg MQTT.Message) {
if mqtt.Received != nil {
mqtt.Received(identifier, loc)
}
} else {
// Invalid topic. Ignore for now.
}
// Ignore invalid topic.
}
func (mqtt *MQTTReceiver) mqttConnectionLost(client MQTT.Client, err error) {
@ -108,7 +105,7 @@ func (mqtt *MQTTReceiver) mqttConnectionLost(client MQTT.Client, err error) {
remotes := options.Servers()
remote := ""
if len(remotes) > 0 {
// TODO:: What to do if there are more?
// TODO: What to do if there are more?
remote = remotes[0].String()
}
for {