modbus-connect
Version:
Modbus RTU over Web Serial and Node.js SerialPort
59 lines (47 loc) • 1.74 kB
JavaScript
// function-codes/write-single-coil.js
const { FUNCTION_CODES } = require('../constants/constants.js');
const { allocUint8Array, uint16ToBytesBE, isUint8Array, bytesToUint16BE } = require('../utils/utils.js');
function buildWriteSingleCoilRequest(address, value) {
if (typeof address !== 'number' || address < 0 || address > 0xFFFF) {
throw new RangeError('Invalid coil address');
}
const pdu = allocUint8Array(5);
pdu[0] = FUNCTION_CODES.WRITE_SINGLE_COIL;
const addressBytes = uint16ToBytesBE(address);
pdu[1] = addressBytes[0];
pdu[2] = addressBytes[1];
// Значения: 0xFF00 — ON, 0x0000 — OFF
if (value === true || value === 1) {
pdu[3] = 0xFF;
pdu[4] = 0x00;
} else if (value === false || value === 0) {
pdu[3] = 0x00;
pdu[4] = 0x00;
} else {
throw new TypeError('Invalid coil value. Use true/false or 1/0.');
}
return pdu;
}
function parseWriteSingleCoilResponse(pdu) {
if (!isUint8Array(pdu)) {
throw new TypeError('PDU must be Uint8Array');
}
if (pdu[0] !== FUNCTION_CODES.WRITE_SINGLE_COIL) {
throw new Error(`Invalid function code: expected 0x05, got 0x${pdu[0].toString(16)}`);
}
const address = bytesToUint16BE(pdu, 1);
const valueRaw = bytesToUint16BE(pdu, 3);
let value;
if (valueRaw === 0xFF00) {
value = true;
} else if (valueRaw === 0x0000) {
value = false;
} else {
throw new Error(`Unexpected coil value: 0x${valueRaw.toString(16)}`);
}
return { address, value };
}
module.exports = {
buildWriteSingleCoilRequest,
parseWriteSingleCoilResponse
}