UNPKG

modbus-connect

Version:

Modbus RTU over Web Serial and Node.js SerialPort

85 lines (74 loc) 2.44 kB
// utils/utils.js // Создание Uint8Array из чисел function fromBytes(...bytes) { return Uint8Array.from(bytes); } // Конкатенация нескольких Uint8Array function concatUint8Arrays(arrays) { const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); const result = new Uint8Array(totalLength); let offset = 0; for (const arr of arrays) { result.set(arr, offset); offset += arr.length; } return result; } // Преобразование числа в Uint8Array (2 байта, Big Endian) function uint16ToBytesBE(value) { const buf = new Uint8Array(2); buf[0] = (value >> 8) & 0xff; buf[1] = value & 0xff; return buf; } // Преобразование Uint8Array (2 байта, Big Endian) в число function bytesToUint16BE(buf, offset = 0) { return (buf[offset] << 8) | buf[offset + 1]; } // Получить срез из Uint8Array function sliceUint8Array(arr, start, end) { return arr.subarray(start, end); // .slice() в Uint8Array создаёт копию } // Проверка, является ли объект Uint8Array function isUint8Array(obj) { return obj instanceof Uint8Array; } // Подобие Buffer.alloc(size) function allocUint8Array(size, fill = 0) { const arr = new Uint8Array(size); if (fill !== 0) arr.fill(fill); return arr; } // Преобразует Uint8Array в hex-строку (например: '0aff12') function toHex(uint8arr) { if (!isUint8Array(uint8arr)) { throw new Error('Argument must be a Uint8Array'); } return Array.from(uint8arr) .map(b => b.toString(16).padStart(2, '0')) .join(''); } // Преобразование числа в Uint8Array (Little Endian) function toBytesLE(value, byteLength = 2) { const arr = new Uint8Array(byteLength); for (let i = 0; i < byteLength; i++) { arr[i] = (value >> (8 * i)) & 0xFF; } return arr; } // Преобразование Little Endian байтов в число (например, byte0 + byte1) function fromBytesLE(lo, hi) { return (hi << 8) | lo; } module.exports = { fromBytes, concatUint8Arrays, uint16ToBytesBE, bytesToUint16BE, sliceUint8Array, isUint8Array, allocUint8Array, toHex, toBytesLE, fromBytesLE }