Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decodePacket.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { ERROR_PACKET, PACKET_TYPES_REVERSE } from "./commons.js";
  2. const decodePacket = (encodedPacket, binaryType) => {
  3. if (typeof encodedPacket !== "string") {
  4. return {
  5. type: "message",
  6. data: mapBinary(encodedPacket, binaryType)
  7. };
  8. }
  9. const type = encodedPacket.charAt(0);
  10. if (type === "b") {
  11. const buffer = Buffer.from(encodedPacket.substring(1), "base64");
  12. return {
  13. type: "message",
  14. data: mapBinary(buffer, binaryType)
  15. };
  16. }
  17. if (!PACKET_TYPES_REVERSE[type]) {
  18. return ERROR_PACKET;
  19. }
  20. return encodedPacket.length > 1
  21. ? {
  22. type: PACKET_TYPES_REVERSE[type],
  23. data: encodedPacket.substring(1)
  24. }
  25. : {
  26. type: PACKET_TYPES_REVERSE[type]
  27. };
  28. };
  29. const mapBinary = (data, binaryType) => {
  30. const isBuffer = Buffer.isBuffer(data);
  31. switch (binaryType) {
  32. case "arraybuffer":
  33. return isBuffer ? toArrayBuffer(data) : data;
  34. case "nodebuffer":
  35. default:
  36. return data; // assuming the data is already a Buffer
  37. }
  38. };
  39. const toArrayBuffer = (buffer) => {
  40. const arrayBuffer = new ArrayBuffer(buffer.length);
  41. const view = new Uint8Array(arrayBuffer);
  42. for (let i = 0; i < buffer.length; i++) {
  43. view[i] = buffer[i];
  44. }
  45. return arrayBuffer;
  46. };
  47. export default decodePacket;