cfry / dde

Dexter Development Environment
Other
44 stars 25 forks source link

Issues with the serial port only working once in DDE. #65

Open JamesNewton opened 3 years ago

JamesNewton commented 3 years ago

DDE uses the NPM package "SerialPort" to communicate via serial devices. It is currently using version 8: https://serialport.io/docs/8.x.x Carefully reading and following the documentation for that object is critical. Especially: https://serialport.io/docs/8.x.x/api-stream

One problem we have had in the past is that we close the port, and then delete the reference to the serial port object from the map. If the close fails, or isn't a complete close, then we have lost the ability to access that port object. Why the port doesn't close and release the object is the question.

It MAY be that this describes the issue: https://stackoverflow.com/questions/46307803/nodejs-serialport-re-establish-connection-to-port-after-closed see this microscopic bit of cryptic documentation: https://serialport.io/docs/8.x.x/api-stream#serialportresume

Another possibility is that the issue comes from the "port" and the "stream" being two different things. The SerialPort library documents these separately: https://serialport.io/docs/8.x.x/api-serialport https://serialport.io/docs/8.x.x/api-stream Only the stream API has a close method, but maybe that doesn't close the serial port?

But our solution has just been to /never/ close the port once it's open. So the logic is:

This comment on this issue (scroll down to the bottom) may be helpful: https://github.com/HaddingtonDynamics/Dexter/issues/60#issuecomment-605376411

JamesNewton commented 3 years ago

As much as the parsers are a nightmare, the one for reading "lines" (which can be delimited by anything) is pretty easy to use. see this example: https://github.com/serialport/node-serialport/blob/master/packages/serialport/examples/readline.js

You could perhaps use a delimiter of "}\n" if the device always sent a \n after the end of the JSON object?

JamesNewton commented 3 years ago

Also, note that the .on('data' callback has a parameter which IS the data, it just needs to be converted to a string. Do not use the .buffer attribute of the port object as is an internal variable.

https://github.com/serialport/node-serialport/blob/master/packages/serialport/examples/open-event.js has a good example:


const SerialPort = require('serialport')
const port = new SerialPort('/dev/tty-usbserial1')

port.on('open', () => {
  console.log('Port Opened')
})

port.write('main screen turn on', err => {
  if (err) {
    return console.log('Error: ', err.message)
  }
  console.log('message written')
})

port.on('data', data => {
  /* get a buffer of data from the serial port */
  console.log(data.toString())
})