so I am writing a small application which exposes the serial port to a web service.
The client is allowed to open ports and the server keeps track on what ports are opened.
I am a complete newbie to javascript so please also point out any other errors you can see in my code!
anyway I have websockets to pass messaged between the client and the server.
There is a ser_con
event which instructs the server to open a new connection to a serial port. This also appends serialport object to an array so I can later refer to it.
var ser = []
...
socket.on('ser_con', function(d) {
console.log('connect event')
sp = new SerialPort.SerialPort(d.name, {
baudrate: d.baudrate,
databits: d.databits,
stopbits: d.stopbits,
parity: d.parity,
buffersize: d.buffersize,
parser: SerialPort.parsers.raw
},false);
sp.open(function (err) {
if (err) {
console.log('Error connecting to port: ' + d.name + ', error: ' + err);
socket.emit('ser_err', 'Error connecting to port: ' + d.name + ', error: ' + err);
} else {
console.log('connected to serial port ' + d.name);
data = {
name: d.name,
b:'connected to serial port ' + d.name + '\n'
}
socket.emit('data', data);
ser.push({'name':d.name,'sp':sp})
}
})
});
So once connection is succesfull I append the name of the port and the instance of the serialport object to the ser
array.
The problem I am having is on how I can listen to events on all the serialports instances
I tried doing this but it doesn't work, I assume this isn't allowed since the for loop isn't an event by itself. I have no idea how to solve this though since...
for (var i=0; i < ser.length; i++){
ser[i].sp.on('data', function(d) {
console.log('recieved data on port ' + ser[i].name)
data = {
name: ser[i].name,
b: d
}
socket.emit('data', data);
});
}
any help is appreciated.