index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CCTalkParser = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * Parse the CCTalk protocol
  7. * @extends Transform
  8. *
  9. * A transform stream that emits CCTalk packets as they are received.
  10. */
  11. class CCTalkParser extends stream_1.Transform {
  12. array;
  13. cursor;
  14. lastByteFetchTime;
  15. maxDelayBetweenBytesMs;
  16. constructor(maxDelayBetweenBytesMs = 50) {
  17. super();
  18. this.array = [];
  19. this.cursor = 0;
  20. this.lastByteFetchTime = 0;
  21. this.maxDelayBetweenBytesMs = maxDelayBetweenBytesMs;
  22. }
  23. _transform(buffer, encoding, cb) {
  24. if (this.maxDelayBetweenBytesMs > 0) {
  25. const now = Date.now();
  26. if (now - this.lastByteFetchTime > this.maxDelayBetweenBytesMs) {
  27. this.array = [];
  28. this.cursor = 0;
  29. }
  30. this.lastByteFetchTime = now;
  31. }
  32. this.cursor += buffer.length;
  33. // TODO: Better Faster es7 no supported by node 4
  34. // ES7 allows directly push [...buffer]
  35. // this.array = this.array.concat(Array.from(buffer)) //Slower ?!?
  36. Array.from(buffer).map(byte => this.array.push(byte));
  37. while (this.cursor > 1 && this.cursor >= this.array[1] + 5) {
  38. // full frame accumulated
  39. // copy command from the array
  40. const FullMsgLength = this.array[1] + 5;
  41. const frame = Buffer.from(this.array.slice(0, FullMsgLength));
  42. // Preserve Extra Data
  43. this.array = this.array.slice(frame.length, this.array.length);
  44. this.cursor -= FullMsgLength;
  45. this.push(frame);
  46. }
  47. cb();
  48. }
  49. }
  50. exports.CCTalkParser = CCTalkParser;