node-zserial 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/zserial.js +234 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-zserial",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "description": "Node-RED nodes to talk to serial ports",
5
5
  "dependencies": {
6
6
  "serialport": "^12.0.0"
package/zserial.js CHANGED
@@ -328,13 +328,17 @@ module.exports = function (RED) {
328
328
  node.send([node._msg, null, null]);
329
329
  }
330
330
  if (err) {
331
+ if (err.payload) {
332
+ err.sendPayload = err.payload;
333
+ err.payload = ''
334
+ }
331
335
  node.errorMsg[port] = err
332
336
  node.send([null, node._msg, null]);
333
337
  }
334
338
  sendAll(done);
335
339
  }
336
340
  function onMsg(msg, send, done) {
337
-
341
+
338
342
  initMsg(msg);
339
343
  if (!msg.serialConfigs) {
340
344
  node.error("需要配置批量配置:msg.serialConfigs");
@@ -462,7 +466,7 @@ module.exports = function (RED) {
462
466
  msgout.status = "ERR_TIMEOUT";
463
467
  msgout.port = curPort.serial.path;
464
468
  node.status({ fill: "red", shape: "ring", text: "timeout:::" + curPort.serial.path });
465
- zsend(null,msgout, null, curPort.serial.path, done);
469
+ zsend(null, msgout, null, curPort.serial.path, done);
466
470
  });
467
471
 
468
472
  curPort.on('initerror', function (port, retryNum, olderr) {
@@ -546,10 +550,12 @@ module.exports = function (RED) {
546
550
  // State variables to be used by the on('data') handler
547
551
  var i = 0; // position in the buffer
548
552
  // .newline is misleading as its meaning depends on the split input policy:
549
- // "char" : a msg will be sent after a character with value .newline is received
550
- // "time" : a msg will be sent after .newline milliseconds
551
- // "count" : a msg will be sent after .newline characters
552
- // if we use "count", we already know how big the buffer will be
553
+ // - "char" : send when a character equal to .newline is received
554
+ // - "time" : send after .newline milliseconds
555
+ // - "interbyte" : send when no byte arrives for .newline milliseconds
556
+ // - "count" : send after .newline characters
557
+ // - "frame" : (NEW) parse DL/T645 & DL/T698.45 (Len & HDLC) frames; emit on complete frame
558
+ // If "count", we already know how big the buffer will be
553
559
  var bufSize = (spliton === "count") ? Number(newline) : bufMaxSize;
554
560
 
555
561
  waitfor = waitfor.replace("\\n", "\n").replace("\\r", "\r")
@@ -741,10 +747,195 @@ module.exports = function (RED) {
741
747
  obj._emitter.emit('ready', id);
742
748
  });
743
749
 
750
+
751
+ /***** -------------------------------- Frame parsers for DL/T645 & DL/T698.45 (FULL) -------------------------------- *****/
752
+ // FE 去前导(645)
753
+ function stripFE(buf) {
754
+ let s = 0;
755
+ while (s < buf.length && buf[s] === 0xFE) s++;
756
+ return buf.slice(s);
757
+ }
758
+ // 计算 8bit 累加和([start,end))
759
+ function sum8(buf, start, end) {
760
+ let sum = 0;
761
+ for (let i = start; i < end; i++) sum = (sum + buf[i]) & 0xFF;
762
+ return sum;
763
+ }
764
+ // CRC-16/X25(HDLC/LAPB 常用):init 0xFFFF, poly 0x1021, refin/refout=true(实现中按位),xorout 0xFFFF
765
+ function crc16x25(buf, start, end) {
766
+ let crc = 0xFFFF;
767
+ for (let i = start; i < end; i++) {
768
+ crc ^= buf[i];
769
+ for (let b = 0; b < 8; b++) {
770
+ if (crc & 1) crc = (crc >>> 1) ^ 0x8408; // 0x8408 = reflect(0x1021)
771
+ else crc >>>= 1;
772
+ }
773
+ }
774
+ crc ^= 0xFFFF;
775
+ // 返回 16-bit,低字节在前(与帧内 FCS 字节序一致)
776
+ return crc & 0xFFFF;
777
+ }
778
+ // HDLC 解转义:0x7D 0xXX -> 0xXX ^ 0x20
779
+ function unescapeHDLC(src) {
780
+ const out = [];
781
+ for (let i = 0; i < src.length; i++) {
782
+ const b = src[i];
783
+ if (b === 0x7D && i + 1 < src.length) {
784
+ out.push(src[i + 1] ^ 0x20);
785
+ i++;
786
+ } else {
787
+ out.push(b);
788
+ }
789
+ }
790
+ return Buffer.from(out);
791
+ }
792
+
793
+ // 解析 645:FE* 68 + 6 addr + 68 + ctrl + len + data + cs + 16
794
+ function tryParse645(input) {
795
+ let b = stripFE(input);
796
+ if (b.length < 12) return { ok: false };
797
+ if (b[0] !== 0x68) return { ok: false };
798
+ if (b.length >= 8 && b[7] !== 0x68) return { ok: false }; // 第二个 0x68 缺失
799
+ if (b.length < 12) return { ok: false };
800
+
801
+ const dataLen = b[9] >>> 0;
802
+ const total = 12 + dataLen;
803
+ if (b.length < total) return { ok: false }; // 半包
804
+
805
+ const csIdx = total - 2;
806
+ const endIdx = total - 1;
807
+ const csExpect = sum8(b, 8, csIdx); // 从 ctrl(索引8) 到 data 末
808
+ const csGot = b[csIdx];
809
+ const endFlag = b[endIdx];
810
+ const frame = b.slice(0, total);
811
+
812
+ if (endFlag !== 0x16) {
813
+ return { ok: false, used: total, frame, err: "645_END_FLAG_16_MISSING" };
814
+ }
815
+ if (csGot !== csExpect) {
816
+ return { ok: false, used: total, frame, err: "645_CHECKSUM_MISMATCH" };
817
+ }
818
+ return { ok: true, used: total, frame };
819
+ }
820
+
821
+ // 解析 698 “Len 变体”:68 LL LH C ... DATA ... CS 16
822
+ function tryParse698Len(input) {
823
+ // 注意:不要 stripFE(698 不用 FE 前导);但现场可能混入 FE 噪声,外层会先剔除非 {FE,68,7E}
824
+ const b = input;
825
+ if (b.length < 5) return { ok: false };
826
+ if (b[0] !== 0x68) return { ok: false };
827
+ // 若字节7为 68,多为 645,交给 645 解析器
828
+ if (b.length >= 8 && b[7] === 0x68) return { ok: false };
829
+
830
+ const len = (b[1] | (b[2] << 8)) >>> 0;
831
+ if (len <= 0 || len > 4096) {
832
+ return { ok: false, used: 1, frame: b.slice(0, 1), err: "698_BAD_LENGTH" };
833
+ }
834
+ const total = 1 + 2 + len + 2; // 68 + LL,LH + payload(len) + CS,16
835
+ if (b.length < total) return { ok: false }; // 半包
836
+
837
+ const csIdx = total - 2;
838
+ const endIdx = total - 1;
839
+ const endFlag = b[endIdx];
840
+ const csExpect = sum8(b, 3, csIdx); // 从 control(索引3) 起,到 CS 前
841
+ const csGot = b[csIdx];
842
+ const frame = b.slice(0, total);
843
+
844
+ if (endFlag !== 0x16) {
845
+ return { ok: false, used: total, frame, err: "698_END_FLAG_16_MISSING" };
846
+ }
847
+ if (csGot !== csExpect) {
848
+ return { ok: false, used: total, frame, err: "698_CHECKSUM_MISMATCH" };
849
+ }
850
+ return { ok: true, used: total, frame };
851
+ }
852
+
853
+ // 解析 698 标准 HDLC:7E ... FCS(lo,hi) 7E,支持 0x7D 透明传输与 FCS 校验
854
+ function tryParse698HDLC(input) {
855
+ const b = input;
856
+ if (b.length < 6) return { ok: false }; // 7E + 最小帧 + 7E
857
+ if (b[0] !== 0x7E) return { ok: false };
858
+
859
+ // 找到下一枚结束 0x7E(允许中间出现其他 0x7E? 正常应视为下一帧结束)
860
+ let endPos = -1;
861
+ for (let i = 1; i < b.length; i++) {
862
+ if (b[i] === 0x7E) { endPos = i; break; }
863
+ }
864
+ if (endPos === -1) return { ok: false }; // 半包
865
+
866
+ const rawFrame = b.slice(0, endPos + 1); // [0 .. endPos]
867
+ const payloadEscaped = b.slice(1, endPos); // 去掉前后 0x7E
868
+ // HDLC 透明传输反转义
869
+ const payload = unescapeHDLC(payloadEscaped);
870
+ if (payload.length < 3) {
871
+ // 至少 1 字节信息 + 2 字节 FCS
872
+ return { ok: false, used: endPos + 1, frame: rawFrame, err: "698_HDLC_TOO_SHORT" };
873
+ }
874
+
875
+ // FCS:最后两字节,低字节在前
876
+ const fcsLo = payload[payload.length - 2];
877
+ const fcsHi = payload[payload.length - 1];
878
+ const fcs = (fcsHi << 8) | fcsLo;
879
+ const calc = crc16x25(payload, 0, payload.length - 2);
880
+
881
+ if (calc !== fcs) {
882
+ return { ok: false, used: endPos + 1, frame: rawFrame, err: "698_HDLC_CRC_FAIL" };
883
+ }
884
+ // 校验 OK,返回原始帧(包含 7E .. 7E),便于上层直接下发/记录
885
+ return { ok: true, used: endPos + 1, frame: rawFrame };
886
+ }
887
+
888
+ // 统一喂入器:抽取多帧、报告错误帧、剔除噪声
889
+ let assembleBuf = Buffer.alloc(0);
890
+ function feedAndExtract(d, emitOk, emitErr) {
891
+ if (!Buffer.isBuffer(d)) d = Buffer.from(d);
892
+ assembleBuf = Buffer.concat([assembleBuf, d]);
893
+
894
+ // 防溢出保护
895
+ if (assembleBuf.length > bufMaxSize) {
896
+ emitErr(Buffer.from(assembleBuf), "BUFFER_OVERFLOW_DROP_OLD");
897
+ assembleBuf = Buffer.alloc(0);
898
+ return;
899
+ }
900
+
901
+ // 剔除前导噪声:仅保留以 0xFE(645 前导)、0x68(645/698-Len)或 0x7E(698-HDLC)开头
902
+ let s = 0;
903
+ while (s < assembleBuf.length) {
904
+ const c = assembleBuf[s];
905
+ if (c === 0xFE || c === 0x68 || c === 0x7E) break;
906
+ s++;
907
+ }
908
+ if (s > 0) assembleBuf = assembleBuf.slice(s);
909
+
910
+ // 抽帧循环
911
+ while (assembleBuf.length >= 5) {
912
+ // 优先 HDLC(避免 7E 被误当噪声),其次 645,再次 698-Len
913
+ let r = tryParse698HDLC(assembleBuf);
914
+ if (!r.ok) r = tryParse645(assembleBuf);
915
+ if (!r.ok) r = tryParse698Len(assembleBuf);
916
+
917
+ if (r.ok) {
918
+ emitOk(r.frame);
919
+ assembleBuf = assembleBuf.slice(r.used);
920
+ continue;
921
+ }
922
+ if (r.used) {
923
+ // 有足够信息判断该段为坏帧:直接丢弃并上报错误
924
+ emitErr(r.frame, r.err || "FRAME_INVALID");
925
+ assembleBuf = assembleBuf.slice(r.used);
926
+ continue;
927
+ }
928
+ // 需要更多数据
929
+ break;
930
+ }
931
+ }
932
+
933
+ /***** -------------------------------- Frame parsers for DL/T645 & DL/T698.45 (FULL) End-------------------------------- *****/
934
+
935
+
744
936
  obj.serial.on('data', function (d) {
745
937
  // RED.log.info("data::::" + d);
746
938
  function emitData(data) {
747
-
748
939
  if (active === true) {
749
940
  var m = Buffer.from(data);
750
941
  var last_sender = null;
@@ -758,6 +949,42 @@ module.exports = function (RED) {
758
949
  active = (waitfor === "") ? true : false;
759
950
  }
760
951
 
952
+ // —— 新增:frame 模式(645/698 全覆盖),完整帧即回,错帧带原始数据与原因 ——
953
+ if (spliton === "frame") {
954
+ feedAndExtract(
955
+ d,
956
+ // 完整 OK 帧
957
+ function (frameBuf) {
958
+ var m = Buffer.from(frameBuf);
959
+ var last_sender = null;
960
+ if (obj.queue.length) { last_sender = obj.queue[0].sender; }
961
+ var msgout = obj.dequeue() || {};
962
+ if (binoutput !== "bin") { m = m.toString(); } // 若需要字符串
963
+ msgout.payload = m;
964
+ msgout.port = port;
965
+ msgout.status = "OK";
966
+ obj._emitter.emit('data', msgout, last_sender);
967
+ },
968
+ // 错误帧(已有边界但校验/结束符不通过)
969
+ function (badBuf, reason) {
970
+ var m = Buffer.from(badBuf);
971
+ var last_sender = null;
972
+ if (obj.queue.length) { last_sender = obj.queue[0].sender; }
973
+ var msgout = obj.dequeue() || {};
974
+ if (binoutput !== "bin") { m = m.toString(); }
975
+ msgout.payload = m; // 原样数据(便于上层记录/重放)
976
+ msgout.port = port;
977
+ msgout.status = "ERR_FRAME";
978
+ msgout.reason = reason || "FRAME_INVALID";
979
+ obj._emitter.emit('data', msgout, last_sender);
980
+ }
981
+ );
982
+ return; // 已处理
983
+ }
984
+
985
+ // —— 其余兼容模式(time/interbyte/count/char)保持原逻辑 ——
986
+ // -------- existing legacy split modes (time/interbyte/count/char) --------
987
+
761
988
  for (var z = 0; z < d.length; z++) {
762
989
  var c = d[z];
763
990
  if (c === waitfor) { active = true; }