Java GPIO 解构器

Java GPIO deconstructor

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

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

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

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

我的代码 主机器人:

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

GPIO控制器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");
    }

如果您使 类 继承自 java.lang.AutoCloseable 接口并在关闭方法中添加清理代码,您可以像这样使用它:

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

这将在退出范围时自动调用 close()。