2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.gpio.internal.handler;
15 import java.util.Date;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
18 import java.util.function.Consumer;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.binding.gpio.internal.NoGpioIdException;
22 import org.openhab.binding.gpio.internal.configuration.GPIOInputConfiguration;
23 import org.openhab.core.library.types.OnOffType;
24 import org.openhab.core.types.Command;
25 import org.openhab.core.types.RefreshType;
26 import org.openhab.core.types.State;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 import eu.xeli.jpigpio.GPIO;
31 import eu.xeli.jpigpio.JPigpio;
32 import eu.xeli.jpigpio.PigpioException;
35 * Thing Handler for digital GPIO inputs.
37 * @author Nils Bauer - Initial contribution
38 * @author Jan N. Klug - Channel redesign
41 public class PigpioDigitalInputHandler implements ChannelHandler {
43 private final Logger logger = LoggerFactory.getLogger(PigpioDigitalInputHandler.class);
44 private Date lastChanged = new Date();
46 private final GPIOInputConfiguration configuration;
47 private final GPIO gpio;
48 private final Consumer<State> updateStatus;
50 public PigpioDigitalInputHandler(GPIOInputConfiguration configuration, JPigpio jPigpio,
51 ScheduledExecutorService scheduler, Consumer<State> updateStatus)
52 throws PigpioException, NoGpioIdException {
53 this.configuration = configuration;
54 this.updateStatus = updateStatus;
55 Integer gpioId = configuration.gpioId;
57 throw new NoGpioIdException();
59 gpio = new GPIO(jPigpio, gpioId, JPigpio.PI_INPUT);
60 jPigpio.gpioSetAlertFunc(gpio.getPin(), (gpio, level, tick) -> {
61 lastChanged = new Date();
62 Date thisChange = new Date();
63 scheduler.schedule(() -> afterDebounce(thisChange), configuration.debouncingTime, TimeUnit.MILLISECONDS);
65 Integer pullupdown = configuration.pullupdown;
66 jPigpio.gpioSetPullUpDown(gpio.getPin(), pullupdown);
69 private void afterDebounce(Date thisChange) {
71 // Check if value changed over time
72 if (!thisChange.before(lastChanged)) {
73 updateStatus.accept(OnOffType.from(configuration.invert != gpio.getValue()));
75 } catch (PigpioException e) {
76 logger.warn("Unknown pigpio exception", e);
81 public void handleCommand(Command command) {
82 if (command instanceof RefreshType) {
84 updateStatus.accept(OnOffType.from(configuration.invert != gpio.getValue()));
85 } catch (PigpioException e) {
86 logger.warn("Unknown pigpio exception while handling Refresh", e);