Skip to content

Commit

Permalink
Work around "isOpen" not being true right after opening a connection
Browse files Browse the repository at this point in the history
While a static amount of waiting isn't ideal, it's better than unconditionally returning empty sensor data
  • Loading branch information
Jalle19 committed Oct 14, 2024
1 parent 75bac2b commit b5755bf
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/sensor/modbus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand All @@ -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
Expand Down

0 comments on commit b5755bf

Please sign in to comment.