Skip to content

Commit

Permalink
fix: modbus to write different for FC6 and FC16 #1175
Browse files Browse the repository at this point in the history
  • Loading branch information
unocelli committed Sep 6, 2024
1 parent bfbcb38 commit b5fc6bc
Showing 1 changed file with 46 additions and 37 deletions.
83 changes: 46 additions & 37 deletions server/runtime/devices/modbus/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* 'modbus': modbus wrapper to communicate with PLC throw RTU/TCP
* 'modbus': modbus wrapper to communicate with PLC throw RTU/TCP
*/

'use strict';
Expand All @@ -13,7 +13,7 @@ const TOKEN_LIMIT = 100;
function MODBUSclient(_data, _logger, _events, _runtime) {
var memory = {}; // Loaded Signal grouped by memory { memory index, start, size, ... }
var data = JSON.parse(JSON.stringify(_data)); // Current Device data { id, name, tags, enabled, ... }
var logger = _logger;
var logger = _logger;
var client = new ModbusRTU(); // Client Modbus (Master)
var working = false; // Working flag to manage overloading polling and connection
var events = _events; // Events to commit change to runtime
Expand All @@ -27,7 +27,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
var runtime = _runtime; // Access runtime config such as scripts

/**
* initialize the modubus type
* initialize the modubus type
*/
this.init = function (_type) {
type = _type;
Expand All @@ -39,7 +39,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
*/
this.connect = function () {
return new Promise(function (resolve, reject) {
if (data.property && data.property.address && (type === ModbusTypes.TCP ||
if (data.property && data.property.address && (type === ModbusTypes.TCP ||
(type === ModbusTypes.RTU && data.property.baudrate && data.property.databits && data.property.stopbits && data.property.parity))) {
try {
if (!client.isOpen && _checkWorking(true)) {
Expand Down Expand Up @@ -110,7 +110,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
}

/**
* Read values in polling mode
* Read values in polling mode
* Update the tags values list, save in DAQ if value changed or in interval and emit values to clients
*/
this.polling = async function () {
Expand Down Expand Up @@ -139,7 +139,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
// _checkWorking(false);
try{
const result = await Promise.all(readVarsfnc);

_checkWorking(false);
if (result.length) {
let varsValueChanged = await _updateVarsValue(result);
Expand All @@ -152,7 +152,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
// console.error('then error');
}
if (lastStatus !== 'connect-ok') {
_emitStatus('connect-ok');
_emitStatus('connect-ok');
}
} catch (reason) {
if (reason) {
Expand Down Expand Up @@ -194,7 +194,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
memory[memaddr].Items[offset] = new MemoryItem(data.tags[id].type, offset);
}
memory[memaddr].Items[offset].Tags.push(data.tags[id]); // because you can have multiple tags at the same DB address

if (offset < memory[memaddr].Start) {
if (memory[memaddr].Start != 65536) {
memory[memaddr].MaxSize += memory[memaddr].Start - offset;
Expand Down Expand Up @@ -225,7 +225,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
var adr = parseInt(key); // tag address
let lastAdrSize = adr + stepsMap[key].size;
let offset = stepsMap[key].offset;
if (nextAdr < adr) {
if (nextAdr < adr) {
// to fragment then new range
lastStart = adr;
let mits = new MemoryItems();
Expand All @@ -235,7 +235,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
lastMemAdr = getMemoryAddress(lastStart, true, token);
mits.Items = getMemoryItems(memory[lastMemAdr].Items, mits.Start, mits.MaxSize);
mixItemsMap[lastStart] = mits;
} else if (mixItemsMap[lastStart]) {
} else if (mixItemsMap[lastStart]) {
// to attach of exist range
mixItemsMap[lastStart].MaxSize = lastAdrSize - lastStart;
mixItemsMap[lastStart].Items = getMemoryItems(memory[lastMemAdr].Items, mixItemsMap[lastStart].Start, mixItemsMap[lastStart].MaxSize);
Expand Down Expand Up @@ -285,7 +285,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Set the Tag value
* Read the current Tag object, write the value in object and send to SPS
* Read the current Tag object, write the value in object and send to SPS
*/
this.setValue = async function (sigid, value) {
if (data.tags[sigid]) {
Expand Down Expand Up @@ -327,7 +327,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
} else {
val = datatypes[data.tags[sigid].type].formatter(divVal);
}

if (type === ModbusTypes.RTU) {
const start = Date.now();
let now = start;
Expand Down Expand Up @@ -375,27 +375,27 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
this.addDaq = fnc; // Add the DAQ value to db history
}

this.addDaq = null;
this.addDaq = null;

/**
* Return the timestamp of last read tag operation on polling
* @returns
* @returns
*/
this.lastReadTimestamp = () => {
return lastTimestampValue;
}

/**
* Return the Daq settings of Tag
* @returns
* @returns
*/
this.getTagDaqSettings = (tagId) => {
return data.tags[tagId] ? data.tags[tagId].daq : null;
}

/**
* Set Daq settings of Tag
* @returns
* @returns
*/
this.setTagDaqSettings = (tagId, settings) => {
if (data.tags[tagId]) {
Expand All @@ -413,7 +413,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
baudRate: parseInt(data.property.baudrate),
dataBits: parseInt(data.property.databits),
stopBits: parseFloat(data.property.stopbits),
parity: data.property.parity.toLowerCase()
parity: data.property.parity.toLowerCase()
}
if (data.property.connectionOption === ModbusOptionType.RTUBufferedPort) {
client.connectRTUBuffered(data.property.address, rtuOptions, callback);
Expand Down Expand Up @@ -563,9 +563,9 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Write value to modbus
* @param {*} memoryAddress
* @param {*} start
* @param {*} value
* @param {*} memoryAddress
* @param {*} start
* @param {*} value
*/
var _writeMemory = function (memoryAddress, start, value) {
return new Promise((resolve, reject) => {
Expand All @@ -581,12 +581,21 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
} else if (memoryAddress === ModbusMemoryAddress.InputRegisters) { // Input Registers (Read 300001-365536)
reject();
} else if (memoryAddress === ModbusMemoryAddress.HoldingRegisters) { // Holding Registers (Read/Write 400001-465535)
client.writeRegisters(start, value).then(res => {
resolve();
}, reason => {
console.error(reason);
reject(reason);
});
if (data.property.options) {
client.writeRegister(start, value).then(res => { // FC6 "Preset Single Register"
resolve();
}, reason => {
console.error(reason);
reject(reason);
});
} else { // FC16 "Preset Multiple Registers"
client.writeRegisters(start, value).then(res => {
resolve();
}, reason => {
console.error(reason);
reject(reason);
});
}
} else {
reject();
}
Expand All @@ -609,7 +618,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Update the Tags values read
* @param {*} vars
* @param {*} vars
*/
var _updateVarsValue = async (vars) => {
var someval = false;
Expand All @@ -623,7 +632,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
let rawValue = items[itemidx].rawValue;
let tags = items[itemidx].Tags;
tags.forEach(tag => {
tempTags[tag.id] = {
tempTags[tag.id] = {
id: tag.id,
rawValue: convertValue(rawValue, tag.divisor),
type: type,
Expand Down Expand Up @@ -667,15 +676,15 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Emit the PLC Tags values array { id: <name>, value: <value>, type: <type> }
* @param {*} values
* @param {*} values
*/
var _emitValues = function (values) {
events.emit('device-value:changed', { id: data.id, values: values });
}

/**
* Emit the PLC connection status
* @param {*} status
* @param {*} status
*/
var _emitStatus = function (status) {
lastStatus = status;
Expand All @@ -684,7 +693,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Used to manage the async connection and polling automation (that not overloading)
* @param {*} check
* @param {*} check
*/
var _checkWorking = function (check) {
if (check && working) {
Expand All @@ -710,7 +719,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
if (address < ModbusMemoryAddress.DigitalInputs) {
if (askey) {
return formatAddress('000000', token);
}
}
return ModbusMemoryAddress.CoilStatus;
} else if (address < ModbusMemoryAddress.InputRegisters) {
if (askey) {
Expand All @@ -729,7 +738,7 @@ function MODBUSclient(_data, _logger, _events, _runtime) {
return ModbusMemoryAddress.HoldingRegisters;
}
}
const convertValue = function (value, divisor, tosrc = false) {
const convertValue = function (value, divisor, tosrc = false) {
try {
if (divisor && parseFloat(divisor)) {
if (tosrc) {
Expand All @@ -746,10 +755,10 @@ function MODBUSclient(_data, _logger, _events, _runtime) {

/**
* Return the Items that are wit address and size in the range start, size
* @param {*} items
* @param {*} start
* @param {*} size
* @returns
* @param {*} items
* @param {*} start
* @param {*} size
* @returns
*/
const getMemoryItems = function(items, start, size) {
let result = {};
Expand Down

0 comments on commit b5fc6bc

Please sign in to comment.