From 70761426c7cc2e89717bd198956605ea5decbe80 Mon Sep 17 00:00:00 2001 From: Stephan Mante Date: Fri, 18 Oct 2024 09:09:16 +0200 Subject: [PATCH] ModbusServer vector with SetRegister --- lib/modbus/modbus_server.js | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/lib/modbus/modbus_server.js b/lib/modbus/modbus_server.js index b201dd7..f9815a5 100644 --- a/lib/modbus/modbus_server.js +++ b/lib/modbus/modbus_server.js @@ -9,7 +9,6 @@ class ModbusServer { this.adapter = adapterInstance; this.log = this.adapter.logger; this._isConnected = false; - //this._modbusClient = null; this._stat = {}; this.vector = { @@ -31,9 +30,10 @@ class ModbusServer { this._addInfoStat('#getCoil',addr, 1 , unitId); callback({ modbusErrorCode: 0x01, msg: 'Illegal function (device does not support this read/write function)' }); }, - setRegister: (addr, value,unitId, callback) => { - this._addInfoStat('#readDeviceIdentification',addr, value, unitId); - callback({ modbusErrorCode: 0x01, msg: 'Illegal function (device does not support this read/write function)' }); + setRegister: async (addr, value,unitId, callback) => { + //this._addInfoStat('#readDeviceIdentification',addr, value, unitId); + await this._handleSetReg(addr,value,unitId, callback); + //callback({ modbusErrorCode: 0x01, msg: 'Illegal function (device does not support this read/write function)' }); }, setCoil: (addr, value, unitId, callback) => { this._addInfoStat('#setCoil',addr, value, unitId); @@ -171,12 +171,29 @@ class ModbusServer { callback({ modbusErrorCode: 0x04, msg: 'Slave device failure (device reports internal error)' }); } } - /* - async process(modbusClient) { - this._modbusClient = modbusClient; - // + + async _handleSetReg(address,data, unitId, callback) { + try { + this.log.debug('Modbus-proxy: Try to write data to id/address ' + unitId + '/' + address+'/'+data); + if (!this.adapter.isConnected) { + callback({ modbusErrorCode: 0x05, msg: 'Acknowledge (requested data will be available later)' }); + return; + } + if (!this.adapter.modbusClient) { + this.log.error('No modbus-client is registered!'); + callback({ modbusErrorCode: 0x04, msg: 'Slave device failure (device reports internal error)' }); + return; + } + + this.adapter.modbusClient.setID(unitId); + await this.adapter.modbusClient.writeRegisters(address,[data]); + callback(); + } catch (err) { + this.log.warn('Modbus-proxy: '+err.modbusCode+' '+err.message); + //callback(JSON.stringify(err)); + callback({ modbusErrorCode: err?.modbusCode, msg: err?.message }); + } } - */ wait(ms){ return new Promise(resolve => setTimeout(resolve, ms));