python bytes() in serialport2 with node.js

I am trying to get a python script to write to a serial port with pyserial, to node.js using serialport2.

I am very confused about bytes() in python, wonder can anyone give me a hand?

python:

ser.write(bytes(chr(160))
ser.write(bytes(chr(157))

so how do I do this in node.js?

serialport2 used in node.js is located here.

Probably you search String.fromCharCode(code) to convert a character code to a string in JS.

Try this with serialport2:

port.write(String.fromCharCode(160, 157));

From the node-serialport2 readme:

write(buffer, [callback])

Writes data to the serial port.

Arguments

  • buffer - This can be a node Buffer object or a string.
  • callback(err, byteWritten) - Callback called after writing bytes.

So, you can give a string object or Buffer object as the argument. A Buffer object will probably do what you want (send integer values):

var buffer = new Buffer([ 8, 6, 7, 5, 3, 0, 9]);

This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes.

For your data, it would be:

var buffer = new Buffer([160, 157]);

By the way, you don't need to do any special casting in Python with PySerial. From the PySerial API documentation:

write(data)

  • Parameters: data – Data to send.
  • Returns: Number of bytes written.
  • Raises SerialTimeoutException: In case a write timeout is configured for the port and the time is exceeded.

Write the string data to the port.

Changed in version 2.5: Accepts instances of bytes and bytearray when available (Python 2.6 and newer) and str otherwise.

Note the "changed in version 2.5" note.