|
18 | 18 | import java.io.PrintWriter;
|
19 | 19 | import java.net.Socket;
|
20 | 20 | import java.net.SocketTimeoutException;
|
21 |
| -import java.util.Optional; |
| 21 | +import java.net.UnknownHostException; |
| 22 | +import java.util.Random; |
22 | 23 |
|
23 | 24 | import org.eclipse.jdt.annotation.NonNullByDefault;
|
24 | 25 | import org.openhab.binding.gce.internal.model.M2MMessageParser;
|
| 26 | +import org.openhab.binding.gce.internal.model.PortDefinition; |
| 27 | +import org.openhab.binding.gce.internal.model.StatusFile; |
| 28 | +import org.openhab.binding.gce.internal.model.StatusFileAccessor; |
25 | 29 | import org.openhab.core.thing.ThingUID;
|
26 | 30 | import org.slf4j.Logger;
|
27 | 31 | import org.slf4j.LoggerFactory;
|
| 32 | +import org.xml.sax.SAXException; |
28 | 33 |
|
29 | 34 | /**
|
30 | 35 | * The {@link Ipx800DeviceConnector} is responsible for connecting,
|
|
35 | 40 | */
|
36 | 41 | @NonNullByDefault
|
37 | 42 | public class Ipx800DeviceConnector extends Thread {
|
38 |
| - private static final int DEFAULT_SOCKET_TIMEOUT_MS = 5000; |
39 |
| - private static final int DEFAULT_RECONNECT_TIMEOUT_MS = 5000; |
| 43 | + private static final int DEFAULT_SOCKET_TIMEOUT_MS = 10000; |
40 | 44 | private static final int MAX_KEEPALIVE_FAILURE = 3;
|
41 |
| - private static final String ENDL = "\r\n"; |
42 | 45 |
|
43 | 46 | private final Logger logger = LoggerFactory.getLogger(Ipx800DeviceConnector.class);
|
| 47 | + private final Random randomizer = new Random(); |
44 | 48 |
|
45 |
| - private final String hostname; |
46 |
| - private final int portNumber; |
47 |
| - |
48 |
| - private Optional<M2MMessageParser> messageParser = Optional.empty(); |
49 |
| - private Optional<Socket> socket = Optional.empty(); |
50 |
| - private Optional<BufferedReader> input = Optional.empty(); |
51 |
| - private Optional<PrintWriter> output = Optional.empty(); |
| 49 | + private final M2MMessageParser parser; |
| 50 | + private final StatusFileAccessor statusAccessor; |
| 51 | + private final Ipx800EventListener listener; |
| 52 | + private final Socket socket; |
| 53 | + private final BufferedReader input; |
| 54 | + private final PrintWriter output; |
52 | 55 |
|
53 | 56 | private int failedKeepalive = 0;
|
54 | 57 | private boolean waitingKeepaliveResponse = false;
|
| 58 | + private boolean interrupted = false; |
55 | 59 |
|
56 |
| - public Ipx800DeviceConnector(String hostname, int portNumber, ThingUID uid) { |
| 60 | + public Ipx800DeviceConnector(String hostname, int portNumber, ThingUID uid, Ipx800EventListener listener) |
| 61 | + throws UnknownHostException, IOException { |
57 | 62 | super("OH-binding-" + uid);
|
58 |
| - this.hostname = hostname; |
59 |
| - this.portNumber = portNumber; |
| 63 | + this.listener = listener; |
| 64 | + |
| 65 | + logger.debug("Connecting to {}:{}...", hostname, portNumber); |
| 66 | + Socket socket = new Socket(hostname, portNumber); |
| 67 | + socket.setSoTimeout(DEFAULT_SOCKET_TIMEOUT_MS); |
| 68 | + this.socket = socket; |
| 69 | + |
| 70 | + output = new PrintWriter(socket.getOutputStream(), true); |
| 71 | + input = new BufferedReader(new InputStreamReader(socket.getInputStream())); |
| 72 | + parser = new M2MMessageParser(listener); |
| 73 | + statusAccessor = new StatusFileAccessor(hostname); |
60 | 74 | setDaemon(true);
|
61 | 75 | }
|
62 | 76 |
|
| 77 | + /** |
| 78 | + * |
| 79 | + * Stop the device thread |
| 80 | + */ |
| 81 | + |
| 82 | + public void dispose() { |
| 83 | + interrupted = true; |
| 84 | + } |
| 85 | + |
63 | 86 | public synchronized void send(String message) {
|
64 |
| - output.ifPresentOrElse(out -> { |
65 |
| - logger.debug("Sending '{}' to Ipx800", message); |
66 |
| - out.write(message + ENDL); |
67 |
| - out.flush(); |
68 |
| - }, () -> logger.warn("Trying to send '{}' while the output stream is closed.", message)); |
| 87 | + logger.debug("Sending '{}' to Ipx800", message); |
| 88 | + output.println(message); |
69 | 89 | }
|
70 | 90 |
|
71 | 91 | /**
|
72 |
| - * Connect to the ipx800 |
73 | 92 | *
|
74 |
| - * @throws IOException |
| 93 | + * Send a random keepalive command which cause the IPX to send an update. |
| 94 | + * If we don't receive the update maxKeepAliveFailure time, the connection |
| 95 | + * is closed |
75 | 96 | */
|
76 |
| - private void connect() throws IOException { |
77 |
| - disconnect(); |
78 | 97 |
|
79 |
| - logger.debug("Connecting to {}:{}...", hostname, portNumber); |
80 |
| - Socket socket = new Socket(hostname, portNumber); |
81 |
| - socket.setSoTimeout(DEFAULT_SOCKET_TIMEOUT_MS); |
82 |
| - socket.getInputStream().skip(socket.getInputStream().available()); |
83 |
| - this.socket = Optional.of(socket); |
| 98 | + private void sendKeepalive() { |
| 99 | + PortDefinition pd = PortDefinition.values()[randomizer.nextInt(PortDefinition.AS_SET.size())]; |
| 100 | + String command = "%s%d".formatted(pd.m2mCommand, randomizer.nextInt(pd.quantity) + 1); |
| 101 | + |
| 102 | + if (waitingKeepaliveResponse) { |
| 103 | + failedKeepalive++; |
| 104 | + logger.debug("Sending keepalive {}, attempt {}", command, failedKeepalive); |
| 105 | + } else { |
| 106 | + failedKeepalive = 0; |
| 107 | + logger.debug("Sending keepalive {}", command); |
| 108 | + } |
| 109 | + |
| 110 | + output.println(command); |
| 111 | + parser.setExpectedResponse(command); |
84 | 112 |
|
85 |
| - input = Optional.of(new BufferedReader(new InputStreamReader(socket.getInputStream()))); |
86 |
| - output = Optional.of(new PrintWriter(socket.getOutputStream(), true)); |
| 113 | + waitingKeepaliveResponse = true; |
87 | 114 | }
|
88 | 115 |
|
89 |
| - /** |
90 |
| - * Disconnect the device |
91 |
| - */ |
92 |
| - private void disconnect() { |
93 |
| - logger.debug("Disconnecting"); |
| 116 | + @Override |
| 117 | + public void run() { |
| 118 | + while (!interrupted) { |
| 119 | + if (failedKeepalive > MAX_KEEPALIVE_FAILURE) { |
| 120 | + interrupted = true; |
| 121 | + listener.errorOccurred(new IOException("Max keep alive attempts has been reached")); |
| 122 | + } |
| 123 | + try { |
| 124 | + String command = input.readLine(); |
| 125 | + waitingKeepaliveResponse = false; |
| 126 | + parser.unsolicitedUpdate(command); |
| 127 | + } catch (SocketTimeoutException e) { |
| 128 | + sendKeepalive(); |
| 129 | + } catch (IOException e) { |
| 130 | + interrupted = true; |
| 131 | + listener.errorOccurred(e); |
| 132 | + } |
| 133 | + } |
| 134 | + if (output instanceof PrintWriter out) { |
| 135 | + out.close(); |
| 136 | + } |
94 | 137 |
|
95 |
| - input.ifPresent(in -> { |
| 138 | + if (input instanceof BufferedReader in) { |
96 | 139 | try {
|
97 | 140 | in.close();
|
98 |
| - } catch (IOException ignore) { |
| 141 | + } catch (IOException e) { |
| 142 | + logger.warn("Exception input stream: {}", e.getMessage()); |
99 | 143 | }
|
100 |
| - input = Optional.empty(); |
101 |
| - }); |
102 |
| - |
103 |
| - output.ifPresent(PrintWriter::close); |
104 |
| - output = Optional.empty(); |
| 144 | + } |
105 | 145 |
|
106 |
| - socket.ifPresent(client -> { |
| 146 | + if (socket instanceof Socket client) { |
107 | 147 | try {
|
| 148 | + logger.debug("Closing socket"); |
108 | 149 | client.close();
|
109 |
| - } catch (IOException ignore) { |
| 150 | + } catch (IOException e) { |
| 151 | + logger.warn("Exception closing socket: {}", e.getMessage()); |
110 | 152 | }
|
111 |
| - socket = Optional.empty(); |
112 |
| - }); |
| 153 | + } |
| 154 | + } |
113 | 155 |
|
114 |
| - logger.debug("Disconnected"); |
| 156 | + public StatusFile readStatusFile() throws SAXException, IOException { |
| 157 | + return statusAccessor.read(); |
115 | 158 | }
|
116 | 159 |
|
117 | 160 | /**
|
118 |
| - * Stop the device thread |
| 161 | + * |
| 162 | + * Set output of the device sending the corresponding command |
| 163 | + * |
| 164 | + * @param targetPort |
| 165 | + * @param targetValue |
119 | 166 | */
|
120 |
| - public void dispose() { |
121 |
| - interrupt(); |
122 |
| - disconnect(); |
| 167 | + public void setOutput(String targetPort, int targetValue, boolean pulse) { |
| 168 | + logger.debug("Sending {} to {}", targetValue, targetPort); |
| 169 | + String command = "Set%02d%s%s".formatted(Integer.parseInt(targetPort), targetValue, pulse ? "p" : ""); |
| 170 | + send(command); |
123 | 171 | }
|
124 | 172 |
|
125 | 173 | /**
|
126 |
| - * Send an arbitrary keepalive command which cause the IPX to send an update. |
127 |
| - * If we don't receive the update maxKeepAliveFailure time, the connection is closed and reopened |
| 174 | + * |
| 175 | + * Resets the counter value to 0 |
| 176 | + * |
| 177 | + * @param targetCounter |
128 | 178 | */
|
129 |
| - private void sendKeepalive() { |
130 |
| - output.ifPresent(out -> { |
131 |
| - if (waitingKeepaliveResponse) { |
132 |
| - failedKeepalive++; |
133 |
| - logger.debug("Sending keepalive, attempt {}", failedKeepalive); |
134 |
| - } else { |
135 |
| - failedKeepalive = 0; |
136 |
| - logger.debug("Sending keepalive"); |
137 |
| - } |
138 |
| - out.println("GetIn01"); |
139 |
| - out.flush(); |
140 |
| - waitingKeepaliveResponse = true; |
141 |
| - }); |
142 |
| - } |
143 |
| - |
144 |
| - @Override |
145 |
| - public void run() { |
146 |
| - try { |
147 |
| - waitingKeepaliveResponse = false; |
148 |
| - failedKeepalive = 0; |
149 |
| - connect(); |
150 |
| - while (!interrupted()) { |
151 |
| - if (failedKeepalive > MAX_KEEPALIVE_FAILURE) { |
152 |
| - throw new IOException("Max keep alive attempts has been reached"); |
153 |
| - } |
154 |
| - input.ifPresent(in -> { |
155 |
| - try { |
156 |
| - String command = in.readLine(); |
157 |
| - waitingKeepaliveResponse = false; |
158 |
| - messageParser.ifPresent(parser -> parser.unsolicitedUpdate(command)); |
159 |
| - } catch (IOException e) { |
160 |
| - handleException(e); |
161 |
| - } |
162 |
| - }); |
163 |
| - } |
164 |
| - disconnect(); |
165 |
| - } catch (IOException e) { |
166 |
| - handleException(e); |
167 |
| - } |
168 |
| - try { |
169 |
| - Thread.sleep(DEFAULT_RECONNECT_TIMEOUT_MS); |
170 |
| - } catch (InterruptedException e) { |
171 |
| - dispose(); |
172 |
| - } |
173 |
| - } |
174 |
| - |
175 |
| - private void handleException(Exception e) { |
176 |
| - if (!interrupted()) { |
177 |
| - if (e instanceof SocketTimeoutException) { |
178 |
| - sendKeepalive(); |
179 |
| - return; |
180 |
| - } else if (e instanceof IOException) { |
181 |
| - logger.warn("Communication error: '{}'. Will retry in {} ms", e, DEFAULT_RECONNECT_TIMEOUT_MS); |
182 |
| - } |
183 |
| - messageParser.ifPresent(parser -> parser.errorOccurred(e)); |
184 |
| - } |
| 179 | + public void resetCounter(int targetCounter) { |
| 180 | + logger.debug("Resetting counter {} to 0", targetCounter); |
| 181 | + send("ResetCount%d".formatted(targetCounter)); |
185 | 182 | }
|
186 | 183 |
|
187 |
| - public void setParser(M2MMessageParser parser) { |
188 |
| - this.messageParser = Optional.of(parser); |
| 184 | + public void resetPLC() { |
| 185 | + send("Reset"); |
189 | 186 | }
|
190 | 187 | }
|
0 commit comments