From b5755bf4dc509711e45868a9d610bc9caba2e287 Mon Sep 17 00:00:00 2001 From: Sam Stenvall Date: Mon, 14 Oct 2024 21:20:15 +0300 Subject: [PATCH] Work around "isOpen" not being true right after opening a connection While a static amount of waiting isn't ideal, it's better than unconditionally returning empty sensor data --- src/sensor/modbus.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/sensor/modbus.ts b/src/sensor/modbus.ts index 6db612e..654ff2a 100644 --- a/src/sensor/modbus.ts +++ b/src/sensor/modbus.ts @@ -23,7 +23,7 @@ export const getSensorData: PowerSensorPollFunction = async ( const client = getClient(sensorSettings.address, sensorSettings.port, sensorSettings.unit) try { - // Connect if not connected yet + // Connect if not connected yet, skip if (!client.isOpen) { logger.info(`Connecting to ${sensorSettings.address}:${sensorSettings.port}...`) await client.connectTCP(sensorSettings.address, { @@ -34,6 +34,14 @@ export const getSensorData: PowerSensorPollFunction = async ( client.setID(sensorSettings.unit) // Request timeout client.setTimeout(requestTimeout) + + // Wait 100 ms for the port to open, if it's not open, give up and return empty data + await new Promise(resolve => setTimeout(resolve, 100)) + + if (!client.isOpen) { + logger.warn(`Modbus TCP channel not open after 100ms, will not attempt to read values this tick`) + return emptySensorData(timestamp, circuit) + } } // Read the register and parse it accordingly