Search code examples
javaraspberry-pigpio

Java GPIO deconstructor


I'm very new to the programming world. So here is my problem:

I'm building a simple IRCBot (PIRCBot) which can receive commands like Turn on and Turn off which will set the pins of a raspberry to high or low. When i terminate the application or when it crashes then the pins will stay active.

So my questions are: How can I make sure that the GPIO is released when i terminate the application with a SIGINT? (Solved with below comment)

How can I make sure that the GPIO is release when my Application crashes?

My code MainBot:

    public static void main(String[] args) throws Exception {
        try(IRCBot bot = new IRCBot()) {
            bot.setVerbose(true);
            bot.connect("192.168.1.137", 6667, "somesecretpasswd");
            bot.joinChannel("#test");

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

IRCBot Class:

public class IRCBot extends PircBot implements AutoCloseable {
    private final static String[] ALLOWED_USER = {"USER1", "USER2", "IRCBot"};
    private final static String TURN_LIGHT_ON = "Turn on";
    private final static String TURN_LIGHT_OFF = "Turn off";
    private final static String DISCO = "Disco";
    private GPIOController gpio;

    public IRCBot() {
        this.gpio = new GPIOController();
        this.setName("IRCBot");
    }
///other stuff
  @Override
    public void close() throws Exception {
        gpio.close();
    }

GPIOController Class

public class GPIOController implements AutoCloseable {
    private final GpioController gpio = GpioFactory.getInstance();
    private GpioPinDigitalOutput gpio20;
    private GpioPinDigitalOutput gpio21;
    private GpioPinDigitalOutput gpio26;
    private boolean status = false;

    Logger LOGGER = Logger.getLogger(GPIOController.class.getName());

    public GPIOController() {
        GpioFactory.setDefaultProvider(new RaspiGpioProvider(RaspiPinNumberingScheme.BROADCOM_PIN_NUMBERING));
        gpio.setShutdownOptions(true, PinState.LOW, PinPullResistance.OFF);
        gpio20 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_20, "LED", PinState.HIGH);
        gpio21 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_21, "LED", PinState.HIGH);
        gpio26 = gpio.provisionDigitalOutputPin(RaspiBcmPin.GPIO_26, "LED", PinState.HIGH);
    }
///some other stuff

@Override
    public void close() throws Exception {
        gpio.shutdown();
        LOGGER.info("Shuting down");
    }

Solution

  • If you make your classes inherit from the java.lang.AutoCloseable interface and add your cleanup code in the close method you can use it like this:

    try(MyClassThatNeedsCleanup x = new MyClassThatNeedsCleanup()){
      // use the class here
    }
    

    This will automatically call close() when exiting the scope.