我对编程世界很陌生。所以这是我的问题:

我正在构建一个简单的IRCBot(PIRCBot),它可以接收Turn onTurn off之类的命令,这些命令会将树莓的引脚设置为highlow。当我终止应用程序或当它崩溃时,引脚将保持为active

所以我的问题是:
使用SIGINT终止应用程序时,如何确保释放GPIO?
(解决以下评论)

我的应用程序崩溃时,如何确保释放GPIO?

我的密码
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类:

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类

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");
    }

最佳答案

如果您使类从java.lang.AutoCloseable接口继承,并在close方法中添加清除代码,则可以这样使用它:

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


退出范围时,它将自动调用close()。

10-07 13:57