简体   繁体   中英

Nodejs serialport data.toString() Failing encoding

I've got a barcode scanner hooked up to a raspberry pi running nodejs serialport. The serialport instance is listening to /dev/input/event0

When I run this

var serialport = require("serialport");
var SP = serialport.SerialPort;
var port = "/dev/input/event0"
var sp = new SP(port);


sp.on('data', function(data) {
  console.log( data);
});

I git a blob of Buffer objects from a scan. (I think it counts each number in the code as a data event.

My problem is, I can't even get it to converto to proper utf8 numbers. How can I get the data decoded?

Update-1: This is the result of the raw console.log(data) after scanning a barcode with the numbers 19024336

<Buffer 32 a9 3b 51 54 76 0c 00 04 00 04 00 1e 00 07 00 32 a9 3b 51 6d 76 0c 00 01 00 02 00 01 00 00 00 32 a9 3b 51 76 76 0c 00 00 00 00 00 00 00 00 00>
<Buffer 32 a9 3b 51 c6 8d 0c 00 04 00 04 00 1e 00 07 00 32 a9 3b 51 dc 8d 0c 00 01 00 02 00 00 00 00 00 32 a9 3b 51 e2 8d 0c 00 04 00 04 00 26 00 07 00 32 a9 3b ...>
<Buffer 32 a9 3b 51 61 cc 0c 00 04 00 04 00 1f 00 07 00 32 a9 3b 51 78 cc 0c 00 01 00 03 00 00 00 00 00 32 a9 3b 51 7e cc 0c 00 04 00 04 00 21 00 07 00 32 a9 3b ...>
<Buffer 32 a9 3b 51 5f fb 0c 00 00 00 00 00 00 00 00 00 32 a9 3b 51 e4 0a 0d 00 04 00 04 00 20 00 07 00 32 a9 3b 51 fc 0a 0d 00 01 00 04 00 00 00 00 00 32 a9 3b ...>
<Buffer 32 a9 3b 51 f6 d5 0d 00 04 00 04 00 28 00 07 00 32 a9 3b 51 0a d6 0d 00 01 00 1c 00 00 00 00 00 32 a9 3b 51 12 d6 0d 00 00 00 00 00 00 00 00 00>

It returns different results (from what my human eyes can read here) each time I scan

You may also be interested to know that Buffer.isBuffer(data); returns true

You should take a look at a module like this: https://github.com/Bornholm/node-keyboard

To elaborate though, the answer is that the output of /dev/input/event0 is not ASCII characters. The output is a series of structs in the format described here https://www.kernel.org/doc/Documentation/input/input.txt as struct input_event .

For instance, that means given the second chunk of your output

32 a9 3b 51 54 76 0c 00 04 00 04 00 1e 00 07 00

breaks down like this:

// 32-bit int timestamp (1362864434) - Sat, 09 Mar 2013 21:27:14 GMT
32 a9 3b 51 

// microsecond-granularity time
54 76 0c 00

// 16-bit short (1) indicating it is a key event 
01 00

// 16-bit short (2) is the keycode for the key '1'.
02 00

// 32-bit int (1) indicating it was a keypress.
01 00 00 00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM