]> git.basschouten.com Git - openhab-addons.git/blob
7a8c945f210fa6e0b8b9935731e1d747aebfdb1d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.pjlinkdevice.internal.device;
14
15 import java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.net.ConnectException;
19 import java.net.InetAddress;
20 import java.net.InetSocketAddress;
21 import java.net.NoRouteToHostException;
22 import java.net.Socket;
23 import java.net.SocketAddress;
24 import java.net.SocketTimeoutException;
25 import java.text.MessageFormat;
26 import java.time.Duration;
27 import java.time.Instant;
28 import java.util.Arrays;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.pjlinkdevice.internal.device.command.AuthenticationException;
36 import org.openhab.binding.pjlinkdevice.internal.device.command.CachedCommand;
37 import org.openhab.binding.pjlinkdevice.internal.device.command.ResponseException;
38 import org.openhab.binding.pjlinkdevice.internal.device.command.authentication.AuthenticationCommand;
39 import org.openhab.binding.pjlinkdevice.internal.device.command.errorstatus.ErrorStatusQueryCommand;
40 import org.openhab.binding.pjlinkdevice.internal.device.command.errorstatus.ErrorStatusQueryResponse.ErrorStatusDevicePart;
41 import org.openhab.binding.pjlinkdevice.internal.device.command.errorstatus.ErrorStatusQueryResponse.ErrorStatusQueryResponseState;
42 import org.openhab.binding.pjlinkdevice.internal.device.command.identification.IdentificationCommand;
43 import org.openhab.binding.pjlinkdevice.internal.device.command.input.Input;
44 import org.openhab.binding.pjlinkdevice.internal.device.command.input.InputInstructionCommand;
45 import org.openhab.binding.pjlinkdevice.internal.device.command.input.InputListQueryCommand;
46 import org.openhab.binding.pjlinkdevice.internal.device.command.input.InputQueryCommand;
47 import org.openhab.binding.pjlinkdevice.internal.device.command.input.InputQueryResponse;
48 import org.openhab.binding.pjlinkdevice.internal.device.command.lampstatus.LampStatesCommand;
49 import org.openhab.binding.pjlinkdevice.internal.device.command.lampstatus.LampStatesResponse;
50 import org.openhab.binding.pjlinkdevice.internal.device.command.lampstatus.LampStatesResponse.LampState;
51 import org.openhab.binding.pjlinkdevice.internal.device.command.mute.MuteInstructionCommand;
52 import org.openhab.binding.pjlinkdevice.internal.device.command.mute.MuteInstructionCommand.MuteInstructionChannel;
53 import org.openhab.binding.pjlinkdevice.internal.device.command.mute.MuteInstructionCommand.MuteInstructionState;
54 import org.openhab.binding.pjlinkdevice.internal.device.command.mute.MuteQueryCommand;
55 import org.openhab.binding.pjlinkdevice.internal.device.command.mute.MuteQueryResponse.MuteQueryResponseValue;
56 import org.openhab.binding.pjlinkdevice.internal.device.command.power.PowerInstructionCommand;
57 import org.openhab.binding.pjlinkdevice.internal.device.command.power.PowerQueryCommand;
58 import org.openhab.binding.pjlinkdevice.internal.device.command.power.PowerQueryResponse;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Represents a PJLink device and takes care of managing the TCP connection, executing commands, and authentication.
64  *
65  * The central interface to get information about and set status on the device.
66  *
67  * @author Nils Schnabel - Initial contribution
68  */
69 @NonNullByDefault
70 public class PJLinkDevice {
71     private static final int TIMEOUT = 30000;
72     protected int tcpPort;
73     protected InetAddress ipAddress;
74     protected @Nullable String adminPassword;
75     protected boolean authenticationRequired;
76     protected @Nullable BufferedReader reader;
77     protected @Nullable Socket socket;
78     protected int timeout = TIMEOUT;
79     private final Logger logger = LoggerFactory.getLogger(PJLinkDevice.class);
80     private String prefixForNextCommand = "";
81     private @Nullable Instant socketCreatedOn;
82     private CachedCommand<LampStatesResponse> cachedLampHoursCommand = new CachedCommand<>(new LampStatesCommand(this));
83
84     public PJLinkDevice(int tcpPort, InetAddress ipAddress, @Nullable String adminPassword, int timeout) {
85         this.tcpPort = tcpPort;
86         this.ipAddress = ipAddress;
87         this.adminPassword = adminPassword;
88         this.timeout = timeout;
89     }
90
91     public PJLinkDevice(int tcpPort, InetAddress ipAddress, @Nullable String adminPassword) {
92         this(tcpPort, ipAddress, adminPassword, TIMEOUT);
93     }
94
95     @Override
96     public String toString() {
97         return "PJLink " + this.ipAddress + ":" + this.tcpPort;
98     }
99
100     protected Socket connect() throws IOException, ResponseException, AuthenticationException {
101         return connect(false);
102     }
103
104     protected BufferedReader getReader() throws IOException, ResponseException, AuthenticationException {
105         BufferedReader reader = this.reader;
106         if (reader == null) {
107             this.reader = reader = new BufferedReader(new InputStreamReader(connect().getInputStream()));
108         }
109         return reader;
110     }
111
112     protected void closeSocket(@Nullable Socket socket) {
113         if (socket != null) {
114             try {
115                 socket.close();
116             } catch (IOException e) {
117                 // okay then, at least we tried
118                 logger.trace("closing of socket failed", e);
119             }
120         }
121         this.socket = null;
122         this.reader = null;
123     }
124
125     protected Socket connect(boolean forceReconnect) throws IOException, ResponseException, AuthenticationException {
126         Instant now = Instant.now();
127         Socket socket = this.socket;
128         boolean connectionTooOld = false;
129         if (this.socketCreatedOn != null) {
130             long millisecondsSinceLastConnect = Duration.between(this.socketCreatedOn, now).toMillis();
131             // according to the PJLink specification, the device closes the connection after 30s idle (without notice),
132             // so to be on the safe side we do not reuse sockets older than 20s
133             connectionTooOld = millisecondsSinceLastConnect > 20 * 1000;
134         }
135
136         if (forceReconnect || connectionTooOld) {
137             if (socket != null) {
138                 closeSocket(socket);
139             }
140         }
141
142         this.socketCreatedOn = now;
143         if (socket != null && socket.isConnected() && !socket.isClosed()) {
144             return socket;
145         }
146
147         SocketAddress socketAddress = new InetSocketAddress(ipAddress, tcpPort);
148
149         try {
150             this.socket = socket = new Socket();
151             socket.connect(socketAddress, timeout);
152             socket.setSoTimeout(timeout);
153             BufferedReader reader = getReader();
154             String header = reader.readLine();
155             if (header == null) {
156                 throw new ResponseException("No PJLink header received from the device");
157             }
158             header = header.toUpperCase();
159             switch (header.substring(0, "PJLINK x".length())) {
160                 case "PJLINK 0":
161                     logger.debug("Authentication not needed");
162                     this.authenticationRequired = false;
163                     break;
164                 case "PJLINK 1":
165                     logger.debug("Authentication needed");
166                     this.authenticationRequired = true;
167                     if (this.adminPassword == null) {
168                         closeSocket(socket);
169                         throw new AuthenticationException("No password provided, but device requires authentication");
170                     } else {
171                         try {
172                             authenticate(header.substring("PJLINK 1 ".length()));
173                         } catch (AuthenticationException e) {
174                             // propagate AuthenticationException
175                             throw e;
176                         } catch (ResponseException e) {
177                             // maybe only the test command is broken on the device
178                             // as long as we don't get an AuthenticationException, we'll just ignore it for now
179                         }
180                     }
181                     break;
182                 default:
183                     logger.debug("Cannot handle introduction response {}", header);
184                     throw new ResponseException("Invalid header: " + header);
185             }
186             return socket;
187         } catch (ConnectException | SocketTimeoutException | NoRouteToHostException e) {
188             // these exceptions indicate that there's no device at this address, just throw without logging
189             throw e;
190         } catch (IOException | ResponseException e) {
191             // these exceptions seem to be more interesting in the log during a scan
192             // This should not happen and might be a user configuration issue, we log a warning message therefore.
193             logger.debug("Could not create a socket connection", e);
194             throw e;
195         }
196     }
197
198     private void authenticate(String challenge) throws ResponseException, IOException, AuthenticationException {
199         new AuthenticationCommand<>(this, challenge, new PowerQueryCommand(this)).execute();
200     }
201
202     public PowerQueryResponse getPowerStatus() throws ResponseException, IOException, AuthenticationException {
203         return new PowerQueryCommand(this).execute();
204     }
205
206     public void addPrefixToNextCommand(String cmd) throws IOException, AuthenticationException {
207         this.prefixForNextCommand = cmd;
208     }
209
210     public static String preprocessResponse(String response) {
211         // some devices send leading zero bytes, see https://github.com/openhab/openhab-addons/issues/6725
212         return response.replaceAll("^\0*|\0*$", "");
213     }
214
215     public synchronized String execute(String command) throws IOException, AuthenticationException, ResponseException {
216         String fullCommand = this.prefixForNextCommand + command;
217         this.prefixForNextCommand = "";
218         for (int numberOfTries = 0; true; numberOfTries++) {
219             try {
220                 Socket socket = connect();
221                 socket.getOutputStream().write((fullCommand).getBytes());
222                 socket.getOutputStream().flush();
223
224                 // success, no further tries needed
225                 break;
226             } catch (java.net.SocketException e) {
227                 closeSocket(socket);
228                 if (numberOfTries >= 2) {
229                     // do not retry endlessly
230                     throw e;
231                 }
232             }
233         }
234
235         String response = null;
236         while ((response = getReader().readLine()) != null && preprocessResponse(response).isEmpty()) {
237             logger.debug("Got empty string response for request '{}' from {}, waiting for another line", response,
238                     fullCommand.replaceAll("\r", "\\\\r"));
239         }
240         if (response == null) {
241             throw new ResponseException(MessageFormat.format("Response to request ''{0}'' was null",
242                     fullCommand.replaceAll("\r", "\\\\r")));
243         }
244
245         if (logger.isDebugEnabled()) {
246             logger.debug("Got response '{}' ({}) for request '{}' from {}", response,
247                     Arrays.toString(response.getBytes()), fullCommand.replaceAll("\r", "\\\\r"), ipAddress);
248         }
249         return preprocessResponse(response);
250     }
251
252     public void checkAvailability() throws IOException, AuthenticationException, ResponseException {
253         connect();
254     }
255
256     public String getName() throws IOException, ResponseException, AuthenticationException {
257         return new IdentificationCommand(this, IdentificationCommand.IdentificationProperty.NAME).execute().getResult();
258     }
259
260     public String getManufacturer() throws IOException, ResponseException, AuthenticationException {
261         return new IdentificationCommand(this, IdentificationCommand.IdentificationProperty.MANUFACTURER).execute()
262                 .getResult();
263     }
264
265     public String getModel() throws IOException, ResponseException, AuthenticationException {
266         return new IdentificationCommand(this, IdentificationCommand.IdentificationProperty.MODEL).execute()
267                 .getResult();
268     }
269
270     public String getFullDescription() throws AuthenticationException, ResponseException {
271         StringBuilder sb = new StringBuilder();
272         try {
273             sb.append(getManufacturer());
274             sb.append(" ");
275         } catch (ResponseException | IOException e) {
276             // okay, we'll try the other identification commands
277         }
278
279         try {
280             sb.append(getModel());
281         } catch (ResponseException | IOException e1) {
282             // okay, we'll try the other identification commands
283         }
284
285         try {
286             String name = getName();
287             if (!name.isEmpty()) {
288                 sb.append(": ");
289                 sb.append(name);
290             }
291         } catch (ResponseException | IOException e2) {
292             // okay, we'll try the other identification commands
293         }
294
295         if (sb.length() == 0) {
296             throw new ResponseException("None of the identification commands worked");
297         }
298
299         return sb.toString();
300     }
301
302     public String getPJLinkClass() throws IOException, AuthenticationException, ResponseException {
303         return new IdentificationCommand(this, IdentificationCommand.IdentificationProperty.CLASS).execute()
304                 .getResult();
305     }
306
307     public void powerOn() throws ResponseException, IOException, AuthenticationException {
308         new PowerInstructionCommand(this, PowerInstructionCommand.PowerInstructionState.ON).execute();
309     }
310
311     public void powerOff() throws IOException, ResponseException, AuthenticationException {
312         new PowerInstructionCommand(this, PowerInstructionCommand.PowerInstructionState.OFF).execute();
313     }
314
315     public @Nullable String getAdminPassword() {
316         return this.adminPassword;
317     }
318
319     public Boolean getAuthenticationRequired() {
320         return this.authenticationRequired;
321     }
322
323     public InputQueryResponse getInputStatus() throws ResponseException, IOException, AuthenticationException {
324         return new InputQueryCommand(this).execute();
325     }
326
327     public void setInput(Input input) throws ResponseException, IOException, AuthenticationException {
328         new InputInstructionCommand(this, input).execute();
329     }
330
331     public MuteQueryResponseValue getMuteStatus() throws ResponseException, IOException, AuthenticationException {
332         return new MuteQueryCommand(this).execute().getResult();
333     }
334
335     public void setMute(MuteInstructionChannel channel, boolean muteOn)
336             throws ResponseException, IOException, AuthenticationException {
337         new MuteInstructionCommand(this, muteOn ? MuteInstructionState.ON : MuteInstructionState.OFF, channel)
338                 .execute();
339     }
340
341     public Map<ErrorStatusDevicePart, ErrorStatusQueryResponseState> getErrorStatus()
342             throws ResponseException, IOException, AuthenticationException {
343         return new ErrorStatusQueryCommand(this).execute().getResult();
344     }
345
346     public List<LampState> getLampStates() throws ResponseException, IOException, AuthenticationException {
347         return new LampStatesCommand(this).execute().getResult();
348     }
349
350     public List<LampState> getLampStatesCached() throws ResponseException, IOException, AuthenticationException {
351         return cachedLampHoursCommand.execute().getResult();
352     }
353
354     public String getOtherInformation() throws ResponseException, IOException, AuthenticationException {
355         return new IdentificationCommand(this, IdentificationCommand.IdentificationProperty.OTHER_INFORMATION).execute()
356                 .getResult();
357     }
358
359     public Set<Input> getAvailableInputs() throws ResponseException, IOException, AuthenticationException {
360         return new InputListQueryCommand(this).execute().getResult();
361     }
362
363     public void dispose() {
364         final Socket socket = this.socket;
365         if (socket != null) {
366             closeSocket(socket);
367         }
368     }
369 }