Pi4J / pi4j-v2

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

Allow GPIO actions before shutdown #213

Closed mvanassche closed 2 years ago

mvanassche commented 2 years ago

There is a java.lang.Runtime.getRuntime().addShutdownHook call in the DefaultRuntime.

However, you may want to run some cleanup on the GPIO before shutting down. For example, turn off the backlight of a I2C LCD.

Either make this shutdown hook optional, or add an event listener before the shutdown?

savageautomate commented 2 years ago

There is some basic support for configuring GPIO states on shutdown.

Example:

Context pi4j pi4j = Pi4J.newAutoContext();
DigitalOutputConfigBuilder builder = DigitalOutput.newConfigBuilder(pi4j);
builder.address(1);
builder.id("MyLCDBacklight");
builder.shutdown(DigitalState.LOW);           //  <---- STATE TO APPLY ON SHUTDOWN EVENT
DigitalOutput output = pi4j.digitalOutput().create(builder);

There is also generic support on the Pi4J Context for registering an event for shutdown notifications. However, it looks like this event is fired AFTER all I/O instances and I/O providers have been shutdown. So that may not be all that helpful in your use case.

        pi4j = Pi4J.newAutoContext();
        pi4j.addListener(new ShutdownListener() {
            @Override
            public void onShutdown(ShutdownEvent event) {
                // DO SOMETHING ON SHUTDOWN
            }
        });
savageautomate commented 2 years ago

FYI, I added a beforeShutdown optional handler in the ShutdownListener interface to allow users to handle any custom pre-shutdown logic needed. This is included in the latest snapshot builds.

        // add shutdown listener
        pi4j.addListener(new ShutdownListener() {

            @Override
            public void beforeShutdown(ShutdownEvent event) {
                logger.info("Pi4J RUNTIME EVENT --> BEFORE SHUTDOWN EVENT");
            }

            @Override
            public void onShutdown(ShutdownEvent event) {
                logger.info("Pi4J RUNTIME EVENT --> (AFTER) SHUTDOWN EVENT");
            }
        });

Full example test code: https://github.com/Pi4J/pi4j-v2/blob/develop/pi4j-test/src/test/java/com/pi4j/test/runtime/RuntimeTest.java