modbus-connect
Version:
Modbus RTU over Web Serial and Node.js SerialPort
53 lines (41 loc) • 1.54 kB
JavaScript
// function-codes/read-discrete-inputs.js
const { FUNCTION_CODES } = require('../constants/constants.js');
const { allocUint8Array, uint16ToBytesBE, isUint8Array } = require('../utils/utils.js');
function buildReadDiscreteInputsRequest(startAddress, quantity) {
if (quantity < 1 || quantity > 2000) {
throw new RangeError('Quantity must be between 1 and 2000');
}
const pdu = allocUint8Array(5);
pdu[0] = FUNCTION_CODES.READ_DISCRETE_INPUTS;
const addrBytes = uint16ToBytesBE(startAddress);
const qtyBytes = uint16ToBytesBE(quantity);
pdu[1] = addrBytes[0];
pdu[2] = addrBytes[1];
pdu[3] = qtyBytes[0];
pdu[4] = qtyBytes[1];
return pdu;
}
function parseReadDiscreteInputsResponse(pdu) {
if (!isUint8Array(pdu)) {
throw new TypeError('PDU must be Uint8Array');
}
if (pdu[0] !== FUNCTION_CODES.READ_DISCRETE_INPUTS) {
throw new Error(`Invalid function code: expected 0x02, got 0x${pdu[0].toString(16)}`);
}
const byteCount = pdu[1];
if (pdu.length !== byteCount + 2) {
throw new Error(`Invalid byte count: expected ${byteCount} bytes, got ${pdu.length - 2}`);
}
const bits = [];
for (let i = 0; i < byteCount; i++) {
const byte = pdu[2 + i];
for (let bit = 0; bit < 8; bit++) {
bits.push((byte >> bit) & 1);
}
}
return bits;
}
module.exports = {
buildReadDiscreteInputsRequest,
parseReadDiscreteInputsResponse
}