Need to produce packets exchange with hardware device via com port, in c, c++ – is not a problem with types of vars like intuint with binary length, but in js – all variables is signed)
device request:
[ 0x0A, 0xC7, 0xAC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE2, 0xAF ]
device answer:
[ 0xFE, 0x9A, 0xAC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA4, 0x9B ]
32 byte per packet, where 0x00 – is filled data, send data – no problem:
something.write(new Uint8Array(packets.request)) – all fine
device answer parse – in js – problems with encoding received data, its received as encoded text, not as binary data
example to repeat:
let bytes = new Uint8Array(packets.answer);
let text = new TextDecoder(‘ascii’).decode(bytes);
console.log(bytes);
console.log(text);
console.log(text.getBytes());
console.log(text.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join(' '));
outputs:
Uint8Array(32) [254, 154, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 164, 155, buffer:
ArrayBuffer(32), byteLength: 32, byteOffset: 0, length: 32,
Symbol(Symbol.toStringTag): ‘Uint8Array’] þ𬠤›
(32) [254, 353, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 164, 8250] fe 161 ac 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 a4
203a
yyyep, we all knows about ascii and <= 0x7F, but what happens with.. see “device answer” bytes, 0xFE – is displayed as 254 – ok, but at same time 0x9A -> 353 ?!, and same fun with 0xA4 at end of answer – 164, and 9B – 8250 q[O,o]p
next example:
let x = [ 0x7E, 0x7F, 0x80, 0x81, 0x82 ];
let bytes = new Uint8Array(x);
let text = new TextDecoder('ascii').decode(bytes);
console.log(bytes);
console.log(text);
console.log(text.getBytes());
console.log(text.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join(' '));
output:
Uint8Array(5) [126, 127, 128, 129, 130, buffer: ArrayBuffer(5),
byteLength: 5, byteOffset: 0, length: 5, Symbol(Symbol.toStringTag):
‘Uint8Array’] (5) [126, 127, 8364, 129, 8218] 7e 7f 20ac 81 201a
what a magic! 🙂