Skip to content

Instantly share code, notes, and snippets.

@sidorares
Last active September 4, 2016 02:38
Show Gist options
  • Save sidorares/e25d447e9f831e897b756e9e07c8b01a to your computer and use it in GitHub Desktop.
Save sidorares/e25d447e9f831e897b756e9e07c8b01a to your computer and use it in GitHub Desktop.
function crc16 (buf) {
var crc = 0xffff;
var i;
var c;
var len = buf.length;
var start = 0;
while (len--) {
c = buf[start];
for (i = 0; i < 8; i++) {
if ((crc ^ c) & 1) {
crc = (crc >> 1) ^ 0x8408;
} else {
crc >>= 1;
}
c >>= 1;
}
start++;
}
crc = (crc ^ 0xFFFF);
return crc;
}
var escapeChars = [];
[0x11, 0x12, 0x13, 0x7e, 0x7D].forEach(function(ch) {
escapeChars[ch] = 1;
});
function hldlcEscape(data) {
var result = [0x7e];
for (var i=0; i < data.length; ++i) {
if (escapeChars[data[i]]) {
result.push(0x7D);
result.push(data[i] ^ 0x20);
} else {
result.push(data[i]);
}
}
result.push(0x7e);
return Buffer(result);
}
function makeEVSEpacket (amps) {
var res = new Buffer('ff03500101036fbacf4159861c3da1437b3e2056', 'hex');
res.writeFloatLE(amps/3, 6);
var crc = crc16(res.slice(0, 18));
res.writeUInt16LE(crc, 18);
return hldlcEscape(res);
}
return {
payload: makeEVSEpacket(msg.payload)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment