p5-serial / p5.serialserver

Server for use with p5.serialport
https://p5-serial.github.io/p5.serialserver
MIT License
159 stars 68 forks source link

Feature request: Callbacks should be able to access the port name #14

Open tigoe opened 9 years ago

tigoe commented 9 years ago

I was thinking about how to implement two-port sketches today. In Processing, the port generating the event is returned to serialEvent as a parameter like so:

void serialEvent(port) {

}

With this, you can take different actions depending on which port is sending data. It might be useful to have this option in P5 too. I tried to see if I could access the port using "this" in the callback functions, but it didn't work.

vanevery commented 9 years ago

What do you think about following the JavaScript Event.target syntax? It might not be a good idea since it isn't a proper JS Event object but it would be familiar to a lot of people.

void serialPort(evt) { if (evt.target === someport) { // Do this } else if (evt.target === someotherport) { // Do that } }

I would also pass the data in via evt.data and get rid of the "raw" callback.

tigoe commented 9 years ago

I like it as a way to transition people to the way JS handles events natively. It's also a nice way to get at the other properties. I particularly like the evt. data bit. I'm not sure why you say it's not a proper event, aren't you generating the event through the libary?

vanevery commented 9 years ago

There is a standard Event object that is used heavily by DOM elements which uses a standard addEventListener/dispatchEvent syntax. It didn't seem appropriate for this when I started writing it (overkill) but perhaps as the library matures...

Regardless, I'll add an object to the callback that includes the serialport object (target) and the data (data). It

In the mean time, unlike Java you can have different function names for the different port callbacks: (it's ugly but probably easy to understand)

var firstSerialPort = ... var secondSerialPort = ...

firstSerialPort.on('data', firstSerialPortDataEvent); secondSerialPort.on('data', secondSerialPortDataEvent);

function firstSerialPortDataEvent() {

}

function secondSerialPortDataEvent() {

}