pi4j-v2 icon indicating copy to clipboard operation
pi4j-v2 copied to clipboard

Add a callback to the Serial class fire when its open

Open mbcoder opened this issue 2 years ago • 3 comments

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.

mbcoder avatar Jul 04 '23 16:07 mbcoder

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.

FDelporte avatar Jul 05 '23 06:07 FDelporte

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

eitch avatar Jul 06 '23 05:07 eitch

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.

DieterHolz avatar Jul 17 '23 17:07 DieterHolz