1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.chabala.brick.controllab;
20
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.Set;
27
28 import static org.chabala.brick.controllab.Protocol.STOP_RELEASED;
29
30
31
32
33 public class StopButton {
34 private final Logger log = LoggerFactory.getLogger(getClass());
35 private final Set<StopButtonListener> stopButtonListeners;
36 private boolean stopDepressed = false;
37
38 StopButton(InputManager inputManager) {
39 stopButtonListeners = Collections.synchronizedSet(new HashSet<>(2));
40 inputManager.setStopButtonCallback(this::processStopButton);
41 }
42
43
44
45
46
47
48
49
50 public void addListener(StopButtonListener listener) {
51 stopButtonListeners.add(listener);
52 }
53
54
55
56
57
58 public void removeListener(StopButtonListener listener) {
59 stopButtonListeners.remove(listener);
60 }
61
62
63
64
65
66 public boolean isStopDepressed() {
67 return stopDepressed;
68 }
69
70 @SuppressWarnings("squid:S2629")
71 private void processStopButton(byte b) {
72 if (STOP_RELEASED != b) {
73 if (!stopDepressed) {
74 StopButtonEvent event = new StopButtonEvent(this, b);
75 log.info("Stop button depressed {}", String.format("0x%02X", b));
76 synchronized (stopButtonListeners) {
77 stopButtonListeners.forEach(l -> l.stopButtonPressed(event));
78 }
79 stopDepressed = true;
80 }
81 } else {
82 if (stopDepressed) {
83 StopButtonEvent event = new StopButtonEvent(this, b);
84 log.info("Stop button released {}", String.format("0x%02X", b));
85 synchronized (stopButtonListeners) {
86 stopButtonListeners.forEach(l -> l.stopButtonReleased(event));
87 }
88 stopDepressed = false;
89 }
90 }
91 }
92 }