Skip to content

Instantly share code, notes, and snippets.

@astagi
Created December 22, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astagi/7431522a9dabf3177fc24f9e508a408a to your computer and use it in GitHub Desktop.
Save astagi/7431522a9dabf3177fc24f9e508a408a to your computer and use it in GitHub Desktop.
R2D2
const ESC = 0xAB;
const SOP = 0x8D;
const EOP = 0xD8;
const ESC_ESC = 0x23;
const ESC_SOP = 0x05;
const ESC_EOP = 0x50;
let seq = 0;
let buildPacket = (init, payload=[]) => {
let packet = [SOP];
let body = [];
let packetEncoded = [];
body.push(...init);
body.push(seq);
body.push(...payload);
body.push(calculateChk(body));
for (let i = 0 ; i < body.length ; i++) {
if (body[i] == ESC) {
packetEncoded.push(...[ESC, ESC_ESC]);
}
else if (body[i] == SOP) {
packetEncoded.push(...[ESC, ESC_SOP]);
}
else if (body[i] == EOP) {
packetEncoded.push(...[ESC, ESC_EOP]);
}
else {
packetEncoded.push(body[i])
}
}
packet.push(...packetEncoded);
packet.push(EOP);
seq++;
return packet;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment