Skip to content

Commit

Permalink
Don't accidentally try to read from the same Modbus device simultaneo…
Browse files Browse the repository at this point in the history
…usly

Shouldn't really be a problem with Modbus TCP, but better safe than sorry
  • Loading branch information
Jalle19 committed Oct 14, 2024
1 parent e23d7c6 commit 75bac2b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 10 deletions.
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"dependencies": {
"@influxdata/influxdb-client": "^1.33.2",
"async-mutex": "^0.5.0",
"modbus-serial": "^8.0.16",
"mqtt": "^5.1.2",
"set-interval-async": "^3.0.3",
Expand Down
25 changes: 15 additions & 10 deletions src/sensor/modbus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { createLogger } from '../logger'
import { getClient, requestTimeout } from '../modbus/client'
import { getRegisterLength, ModbusRegister, RegisterType, stringify } from '../modbus/register'
import ModbusRTU from 'modbus-serial'
import { Mutex } from 'async-mutex'

export const DEFAULT_PORT = 502
export const DEFAULT_UNIT = 1

const logger = createLogger('sensor.modbus')
const mutex = new Mutex()

export const getSensorData: PowerSensorPollFunction = async (
timestamp: number,
Expand Down Expand Up @@ -58,16 +60,19 @@ const readRegisters = async (
const address = register.address
const length = getRegisterLength(register)

switch (register.registerType) {
case RegisterType.HOLDING_REGISTER:
return client.readHoldingRegisters(address, length)
case RegisterType.INPUT_REGISTER:
return client.readInputRegisters(address, length)
case RegisterType.COIL:
return client.readCoils(address, length)
case RegisterType.DISCRETE_INPUT:
return client.readDiscreteInputs(address, length)
}
// Serialize access to the underlying Modbus client
return mutex.runExclusive(async () => {
switch (register.registerType) {
case RegisterType.HOLDING_REGISTER:
return client.readHoldingRegisters(address, length)
case RegisterType.INPUT_REGISTER:
return client.readInputRegisters(address, length)
case RegisterType.COIL:
return client.readCoils(address, length)
case RegisterType.DISCRETE_INPUT:
return client.readDiscreteInputs(address, length)
}
})
}

const parseReadRegisterResult = (result: ReadRegisterResult | ReadCoilResult, register: ModbusRegister): number => {
Expand Down

0 comments on commit 75bac2b

Please sign in to comment.