@@ -7,6 +7,8 @@ import { getFlagStatus, root, setFlagStatus, setSetting, summary } from './app/h
7
7
import { publishValues , subscribeToChanges , handleMessage , publishDeviceInformation } from './app/mqtt.mjs'
8
8
import { configureMqttDiscovery } from './app/homeassistant.mjs'
9
9
10
+ const MQTT_INITIAL_RECONNECT_RETRY_INTERVAL_SECONDS = 5
11
+
10
12
const argv = yargs ( process . argv . slice ( 2 ) )
11
13
. usage ( 'node $0 [options]' )
12
14
. options ( {
@@ -117,7 +119,25 @@ const argv = yargs(process.argv.slice(2))
117
119
}
118
120
}
119
121
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 )
121
141
122
142
// Publish device information once only (since it doesn't change)
123
143
await publishDeviceInformation ( modbusClient , mqttClient )
@@ -145,8 +165,6 @@ const argv = yargs(process.argv.slice(2))
145
165
mqttClient . on ( 'reconnect' , ( ) => {
146
166
console . log ( `Attempting to reconnect to ${ argv . mqttBrokerUrl } ` )
147
167
} )
148
- } catch ( e ) {
149
- console . error ( `Failed to connect to MQTT broker: ${ e . message } ` )
150
- }
168
+ } catch ( e ) { }
151
169
}
152
170
} ) ( )
0 commit comments