使用node.js获取继电器信息
function unpack(format, data) { //仿 PHP 的 unpack() 函数:从二进制字符串对数据进行解包。 const ret = []; var offset = 0; const fs = format.split(''); try { for (var i = 0; i < fs.length; i++) { const sign = fs[i]; if (0) { } else if (sign === 'c') { ret.push(data.readInt8(offset)); offset += 1; } else if (sign === 'C') { ret.push(data.readUInt8(offset)); offset += 1; } else if (sign === 'n') { ret.push(data.readInt16BE(offset)); offset += 2; } else if (sign === 'l') { ret.push(data.readInt32BE(offset)); offset += 4; } else if (sign === 'N') { ret.push(data.readUInt32BE(offset)); offset += 4; } else { } } } catch (e) { return ret; } return ret; } function getReg3ByMsg(message) { // 对单相空气开关的3区数据进行解析 const aReg3 = unpack('CCCnnnnnllnNNnnnnNnnnnnnnnnnnnnN', message); function getReg(pos, fix) { if (pos > aReg3.length - 1) { return; } var s = aReg3[pos]; if (fix < 0) { s = s.toString(); s = s.substr(0, s.length + fix) + '.' + s.substr(fix); } return parseFloat(s); } const mOut = {}; mOut['零线温度'] = getReg(3, -1); mOut['火线温度'] = getReg(4, -1); mOut['芯片温度'] = getReg(5, -1); mOut['电压'] = getReg(6, -1); mOut['电流'] = getReg(7, -2); mOut['有功功率'] = getReg(8, -1); mOut['无功功率'] = getReg(9, -1); mOut['测量频率'] = getReg(10, -1); mOut['有功电度量'] = getReg(11, -2); mOut['无功电度量'] = getReg(12, -2); mOut['功率因数'] = getReg(13, 0); mOut['开关状态'] = getReg(14, 0); mOut['视在功率'] = getReg(17, 0); mOut['开关状态'] = getReg(14, 0);//21为开启,26为关闭 mOut['漏电流'] = getReg(21, 0); mOut['挂锁状态'] = getReg(22, 0); mOut['分合闸日志'] = getReg(30, 0); mOut['时间戳'] = getReg(31, 0); console.log('断路器最新状态=>', mOut); } function TM(url, TMSN) { /* * 连接mqtt服务器并获取最新数据 * url是服务器地址和用户名密码,例如mqtt://user:pass@host:port * TMSN是断路器的序列号 */ const mqtt = require('mqtt'); const mqtt_client = mqtt.connect(url); mqtt_client.on('connect', function () { mqtt_client.subscribe(`gateway/${TMSN}/stateraw`); }) mqtt_client.on('message', function (topic, message) { const int16arr = new Int16Array(message); console.log('topic=>', topic, int16arr); const a = unpack('CC', message); if (a[1] === 4) { getReg3ByMsg(message); } }) const buf = Buffer.from('01040000002931D4', 'hex'); mqtt_client.publish(`gateway/${TMSN}/ctr`, buf); }