Skip to content

Commit 1168eae

Browse files
committed
Reconnect to MQTT broker manually until we've connected once
Fixes #61
1 parent 3e7a90e commit 1168eae

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Change log
22

3+
## future release
4+
5+
* Fix automatic reconnect to MQTT broker when initial connection attempt fails (https://github.com/Jalle19/eda-modbus-bridge/issues/61)
6+
37
## 2.3.0
48

59
* Add initial support for MD automation units (https://github.com/Jalle19/eda-modbus-bridge/issues/58), mainly "eco mode"

eda-modbus-bridge.mjs

+22-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { getFlagStatus, root, setFlagStatus, setSetting, summary } from './app/h
77
import { publishValues, subscribeToChanges, handleMessage, publishDeviceInformation } from './app/mqtt.mjs'
88
import { configureMqttDiscovery } from './app/homeassistant.mjs'
99

10+
const MQTT_INITIAL_RECONNECT_RETRY_INTERVAL_SECONDS = 5
11+
1012
const argv = yargs(process.argv.slice(2))
1113
.usage('node $0 [options]')
1214
.options({
@@ -117,7 +119,25 @@ const argv = yargs(process.argv.slice(2))
117119
}
118120
}
119121

120-
const mqttClient = await MQTT.connectAsync(argv.mqttBrokerUrl, clientOptions)
122+
// The MQTT client handles reconnections automatically, but only after it has connected successfully once.
123+
// Retry manually until we get an initial connection.
124+
let mqttClient
125+
let connectedOnce = false
126+
const retryIntervalMs = MQTT_INITIAL_RECONNECT_RETRY_INTERVAL_SECONDS * 1000
127+
128+
do {
129+
try {
130+
mqttClient = await MQTT.connectAsync(argv.mqttBrokerUrl, clientOptions)
131+
connectedOnce = true
132+
console.log(`Successfully connected to MQTT broker at ${argv.mqttBrokerUrl}`)
133+
} catch (e) {
134+
console.error(
135+
`Failed to connect to MQTT broker: ${e.message}. Retrying in ${retryIntervalMs} milliseconds`
136+
)
137+
138+
await new Promise((resolve) => setTimeout(resolve, retryIntervalMs))
139+
}
140+
} while (!connectedOnce)
121141

122142
// Publish device information once only (since it doesn't change)
123143
await publishDeviceInformation(modbusClient, mqttClient)
@@ -145,8 +165,6 @@ const argv = yargs(process.argv.slice(2))
145165
mqttClient.on('reconnect', () => {
146166
console.log(`Attempting to reconnect to ${argv.mqttBrokerUrl}`)
147167
})
148-
} catch (e) {
149-
console.error(`Failed to connect to MQTT broker: ${e.message}`)
150-
}
168+
} catch (e) {}
151169
}
152170
})()

0 commit comments

Comments
 (0)