]> git.basschouten.com Git - openhab-addons.git/blob
220ddc76dfc460b70ffaa21e379e898cdeddee09
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ihc.internal;
14
15 import java.time.Duration;
16
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Class to handle button press durations
22  *
23  * @author Pauli Anttila - Initial contribution
24  */
25 public class ButtonPressDurationDetector {
26     private final Logger logger = LoggerFactory.getLogger(ButtonPressDurationDetector.class);
27
28     private boolean shortPress;
29     private boolean longPress;
30     private Duration duration;
31     private long longPressTime;
32     private long longPressMaxTime;
33
34     public boolean isShortPress() {
35         return shortPress;
36     }
37
38     public boolean isLongPress() {
39         return longPress;
40     }
41
42     public ButtonPressDurationDetector(Duration duration, long longPressTime, long longPressMaxTime) {
43         this.duration = duration;
44         this.longPressTime = longPressTime;
45         this.longPressMaxTime = longPressMaxTime;
46
47         calculate();
48     }
49
50     private void calculate() {
51         if (duration.toMillis() < 0) {
52             logger.debug("Button press duration < 0ms");
53         } else if (isBetween(duration.toMillis(), 0, longPressTime)) {
54             logger.debug("Button press duration > {}ms and < {}ms", 0, longPressTime);
55             shortPress = true;
56         } else if (isBetween(duration.toMillis(), longPressTime, longPressMaxTime)) {
57             logger.debug("Button press duration > {}ms and < {}ms", longPressTime, longPressMaxTime);
58             longPress = true;
59         } else {
60             logger.debug("Button press duration > {}ms, ignore it", longPressMaxTime);
61         }
62     }
63
64     private boolean isBetween(long value, long minValue, long maxValueInclusive) {
65         return (value > minValue && value <= maxValueInclusive);
66     }
67
68     @Override
69     public String toString() {
70         return String.format("[ duration=%sms, shortPress=%b, longPress=%b ]", duration.toMillis(), shortPress,
71                 longPress);
72     }
73 }