/** * Payload Decoder for The Things Network * * Copyright 2023 Milesight IoT * * @product WS50x v2 */ function Decoder(bytes, port) { return milesight(bytes); } function milesight(bytes) { var decoded = {}; for (var i = 0; i < bytes.length; ) { var channel_id = bytes[i++]; var channel_type = bytes[i++]; // SWITCH STATE if (channel_id === 0x08 && channel_type === 0x29) { // payload (0 0 0 0 0 0 0 0) // Switch 3 2 1 3 2 1 // ------- ------- // bit mask change state decoded.switch_1 = (bytes[i] & 1) == 1 ? "on" : "off"; decoded.switch_1_change = ((bytes[i] >> 4) & 1) == 1 ? "yes" : "no"; decoded.switch_2 = ((bytes[i] >> 1) & 1) == 1 ? "on" : "off"; decoded.switch_2_change = ((bytes[i] >> 5) & 1) == 1 ? "yes" : "no"; decoded.switch_3 = ((bytes[i] >> 2) & 1) == 1 ? "on" : "off"; decoded.switch_3_change = ((bytes[i] >> 6) & 1) == 1 ? "yes" : "no"; i += 1; } // VOLTAGE else if (channel_id === 0x03 && channel_type === 0x74) { decoded.voltage = readUInt16LE(bytes.slice(i, i + 2)) / 10; i += 2; } // ACTIVE POWER else if (channel_id === 0x04 && channel_type === 0x80) { decoded.power = readUInt32LE(bytes.slice(i, i + 4)); i += 4; } // POWER FACTOR else if (channel_id === 0x05 && channel_type === 0x81) { decoded.factor = bytes[i]; i += 1; } // POWER CONSUMPTION else if (channel_id === 0x06 && channel_type == 0x83) { decoded.power_sum = readUInt32LE(bytes.slice(i, i + 4)); i += 4; } // CURRENT else if (channel_id === 0x07 && channel_type == 0xc9) { decoded.current = readUInt16LE(bytes.slice(i, i + 2)); i += 2; } else { break; } } return decoded; } function readUInt16LE(bytes) { var value = (bytes[1] << 8) + bytes[0]; return value & 0xffff; } function readInt16LE(bytes) { var ref = readUInt16LE(bytes); return ref > 0x7fff ? ref - 0x10000 : ref; } function readUInt32LE(bytes) { var value = (bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]; return (value & 0xffffffff) >>> 0; } function readInt32LE(bytes) { var ref = readUInt32LE(bytes); return ref > 0x7fffffff ? ref - 0x100000000 : ref; }