I am using the SerialPort library in nodejs to list the available ports, and send data to each of them. If any of them return "OK", I would like to find out which is the port that returns it:
SerialPort.list().then(ports => {
ports.forEach(port => {
var rtuSocket = new SerialPort(port.path, { baudRate: 9600 }, (err, data) => {
rtuSocket.on('data', (err, data) => {
console.log(rtuSocket.path)
console.log("[RTU][CONNECTED]")
})
rtuSocket.write("AT")
})
})
})
Obviously the rtuSocket will be a different variable by the time data return. Is there a way to know which port is returning the data inside .on("data") ?
You need some sort of timeout to detect if a port is not responding. I also strongly suggest you check the response data and send something more than a simple "AT" command because a lot of other devices respond to AT commands such as RGB controllers for gaming PCs and some Android phones configured as modems.
Something like the following should work:
Now you can check which port is connected:
Now to find the connected port simply do:
Promises and async/await
While the code above works. For asynchronous code that requires a lot of conditional logic like this I find using async/await much easier to reason about. For that you need to convert your code to return promises:
Now the for loop is easier to understand albeit now you cannot use
forEachormaporfilteror any array methods. You need to usefororwhileif you want to use async/await:Now you can simply get the connected port by doing: