Pi4J / pi4j-v2

Pi4J Version 2.0
Apache License 2.0
273 stars 57 forks source link

Add a callback to the Serial class fire when its open #283

Open mbcoder opened 1 year ago

mbcoder commented 1 year ago

I've just starting using the Pi4J libs and have to say its a great API with solid documentation which got me going really quickly.

I've used Pi4J in this example GPS data logger blog and when I had opened a serial port I had the following code to wait until the port was open:

            while (!serial.isOpen()) {
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

I was thinking a nice enhancement to the API would be to add a listener to the serial class which would fire once the serial port is ready to read from. If this existed then the above code could be replaced with something like:

serial.addOpenedListener(() -> {//do something now the serial port is open});

If you think this is a worthwhile addition I'd be happy to make a PR for review.

FDelporte commented 1 year ago

We had a similar idea in the past, see #118, with a reference to the implementation in V1. Maybe we should indeed consider extending the serial implementation.

eitch commented 1 year ago

The idea is great. Do you mind creating a PR? We gladly accept PRs.

DieterHolz commented 1 year ago

Wouldn't that more or less mean, that your whole application is inside the lambda expression of 'addOpenedListener'?

How about doing the 'wait' inside Pi4J instead.

When calling

pi4j.create(Serial.newConfigBuilder(pi4j)...

it does not return until 'Serial' is open and ready for being used.

If that kind of synchronous call is not acceptable then provide two methods: 'serial.open' will wait until serial is ready and 'serial.asynOpen(onFinishedHandler)' will do the opening asynchronously.