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.miele.internal.handler;
15 import static org.openhab.binding.miele.internal.MieleBindingConstants.*;
17 import java.io.BufferedInputStream;
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.io.StringReader;
23 import java.net.DatagramPacket;
24 import java.net.HttpURLConnection;
25 import java.net.InetAddress;
26 import java.net.MalformedURLException;
27 import java.net.MulticastSocket;
28 import java.net.SocketTimeoutException;
30 import java.net.UnknownHostException;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.List;
36 import java.util.Random;
38 import java.util.concurrent.CopyOnWriteArrayList;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
41 import java.util.concurrent.Future;
42 import java.util.concurrent.ScheduledFuture;
43 import java.util.concurrent.TimeUnit;
44 import java.util.regex.Pattern;
45 import java.util.zip.GZIPInputStream;
47 import org.apache.commons.lang3.StringUtils;
48 import org.openhab.core.common.NamedThreadFactory;
49 import org.openhab.core.thing.Bridge;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.ThingTypeUID;
55 import org.openhab.core.thing.binding.BaseBridgeHandler;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.RefreshType;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 import com.google.gson.Gson;
62 import com.google.gson.JsonArray;
63 import com.google.gson.JsonElement;
64 import com.google.gson.JsonObject;
65 import com.google.gson.JsonParser;
68 * The {@link MieleBridgeHandler} is responsible for handling commands, which are
69 * sent to one of the channels.
71 * @author Karel Goderis - Initial contribution
72 * @author Kai Kreuzer - Fixed lifecycle issues
73 * @author Martin Lepsy - Added protocol information to support WiFi devices & some refactoring for HomeDevice
75 public class MieleBridgeHandler extends BaseBridgeHandler {
77 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_XGW3000);
79 private static final Pattern IP_PATTERN = Pattern
80 .compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
82 protected static final int POLLING_PERIOD = 15; // in seconds
83 protected static final int JSON_RPC_PORT = 2810;
84 protected static final String JSON_RPC_MULTICAST_IP1 = "239.255.68.139";
85 protected static final String JSON_RPC_MULTICAST_IP2 = "224.255.68.139";
86 private boolean lastBridgeConnectionState = false;
87 private boolean currentBridgeConnectionState = false;
89 protected Random rand = new Random();
90 protected Gson gson = new Gson();
91 private final Logger logger = LoggerFactory.getLogger(MieleBridgeHandler.class);
93 protected List<ApplianceStatusListener> applianceStatusListeners = new CopyOnWriteArrayList<>();
94 protected ScheduledFuture<?> pollingJob;
95 protected ExecutorService executor;
96 protected Future<?> eventListenerJob;
98 protected List<HomeDevice> previousHomeDevices = new CopyOnWriteArrayList<>();
101 protected Map<String, String> headers;
103 // Data structures to de-JSONify whatever Miele appliances are sending us
104 public class HomeDevice {
106 private static final String PROTOCOL_LAN = "LAN";
109 public String Status;
110 public String ParentUID;
111 public String ProtocolAdapterName;
112 public String Vendor;
115 public JsonArray DeviceClasses;
116 public String Version;
117 public String TimestampAdded;
118 public JsonObject Error;
119 public JsonObject Properties;
124 public String getId() {
125 return getApplianceId().replaceAll("[^a-zA-Z0-9_]", "_");
128 public String getProtocol() {
129 return ProtocolAdapterName.equals(PROTOCOL_LAN) ? HDM_LAN : HDM_ZIGBEE;
132 public String getApplianceId() {
133 return ProtocolAdapterName.equals(PROTOCOL_LAN) ? StringUtils.right(UID, UID.length() - HDM_LAN.length())
134 : StringUtils.right(UID, UID.length() - HDM_ZIGBEE.length());
138 public class DeviceClassObject {
139 public String DeviceClassType;
140 public JsonArray Operations;
141 public String DeviceClass;
142 public JsonArray Properties;
144 DeviceClassObject() {
148 public class DeviceOperation {
150 public String Arguments;
151 public JsonObject Metadata;
157 public class DeviceProperty {
161 public JsonObject Metadata;
167 public class DeviceMetaData {
168 public String Filter;
169 public String description;
170 public String LocalizedID;
171 public String LocalizedValue;
172 public JsonObject MieleEnum;
173 public String access;
176 public MieleBridgeHandler(Bridge bridge) {
181 public void initialize() {
182 logger.debug("Initializing the Miele bridge handler.");
184 if (getConfig().get(HOST) != null && getConfig().get(INTERFACE) != null) {
185 if (IP_PATTERN.matcher((String) getConfig().get(HOST)).matches()
186 && IP_PATTERN.matcher((String) getConfig().get(INTERFACE)).matches()) {
188 url = new URL("http://" + (String) getConfig().get(HOST) + "/remote/json-rpc");
189 } catch (MalformedURLException e) {
190 logger.debug("An exception occurred while defining an URL :'{}'", e.getMessage());
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
195 // for future usage - no headers to be set for now
196 headers = new HashMap<>();
199 updateStatus(ThingStatus.UNKNOWN);
201 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
202 "Invalid IP address for the Miele@Home gateway or multicast interface:" + getConfig().get(HOST)
203 + "/" + getConfig().get(INTERFACE));
206 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
207 "Cannot connect to the Miele gateway. host IP address or multicast interface are not set.");
211 private Runnable pollingRunnable = new Runnable() {
214 if (IP_PATTERN.matcher((String) getConfig().get(HOST)).matches()) {
216 if (isReachable((String) getConfig().get(HOST))) {
217 currentBridgeConnectionState = true;
219 currentBridgeConnectionState = false;
220 lastBridgeConnectionState = false;
224 if (!lastBridgeConnectionState && currentBridgeConnectionState) {
225 logger.debug("Connection to Miele Gateway {} established.", getConfig().get(HOST));
226 lastBridgeConnectionState = true;
227 onConnectionResumed();
230 if (currentBridgeConnectionState) {
231 if (getThing().getStatus() == ThingStatus.ONLINE) {
232 List<HomeDevice> currentHomeDevices = getHomeDevices();
233 for (HomeDevice hd : currentHomeDevices) {
234 boolean isExisting = false;
235 for (HomeDevice phd : previousHomeDevices) {
236 if (phd.UID.equals(hd.UID)) {
242 logger.debug("A new appliance with ID '{}' has been added", hd.UID);
243 for (ApplianceStatusListener listener : applianceStatusListeners) {
244 listener.onApplianceAdded(hd);
249 for (HomeDevice hd : previousHomeDevices) {
250 boolean isCurrent = false;
251 for (HomeDevice chd : currentHomeDevices) {
252 if (chd.UID.equals(hd.UID)) {
258 logger.debug("The appliance with ID '{}' has been removed", hd);
259 for (ApplianceStatusListener listener : applianceStatusListeners) {
260 listener.onApplianceRemoved(hd);
265 previousHomeDevices = currentHomeDevices;
267 for (Thing appliance : getThing().getThings()) {
268 if (appliance.getStatus() == ThingStatus.ONLINE) {
269 String applianceId = (String) appliance.getConfiguration().getProperties()
271 String protocol = appliance.getProperties().get(PROTOCOL_PROPERTY_NAME);
272 if (protocol == null) {
273 logger.error("Protocol property is missing for {}", applianceId);
276 String UID = protocol + applianceId;
278 Object[] args = new Object[2];
281 JsonElement result = invokeRPC("HDAccess/getDeviceClassObjects", args);
283 if (result != null) {
284 for (JsonElement obj : result.getAsJsonArray()) {
286 DeviceClassObject dco = gson.fromJson(obj, DeviceClassObject.class);
288 for (ApplianceStatusListener listener : applianceStatusListeners) {
289 listener.onApplianceStateChanged(applianceId, dco);
291 } catch (Exception e) {
292 logger.debug("An exception occurred while quering an appliance : '{}'",
301 } catch (Exception e) {
302 logger.debug("An exception occurred while polling an appliance :'{}'", e.getMessage());
305 logger.debug("Invalid IP address for the Miele@Home gateway : '{}'", getConfig().get(HOST));
309 private boolean isReachable(String ipAddress) {
311 // note that InetAddress.isReachable is unreliable, see
312 // http://stackoverflow.com/questions/9922543/why-does-inetaddress-isreachable-return-false-when-i-can-ping-the-ip-address
313 // That's why we do an HTTP access instead
315 // If there is no connection, this line will fail
316 JsonElement result = invokeRPC("system.listMethods", null);
317 if (result == null) {
318 logger.debug("{} is not reachable", ipAddress);
321 } catch (Exception e) {
325 logger.debug("{} is reachable", ipAddress);
330 public List<HomeDevice> getHomeDevices() {
331 List<HomeDevice> devices = new ArrayList<>();
333 if (getThing().getStatus() == ThingStatus.ONLINE) {
335 String[] args = new String[1];
336 args[0] = "(type=SuperVision)";
337 JsonElement result = invokeRPC("HDAccess/getHomeDevices", args);
339 for (JsonElement obj : result.getAsJsonArray()) {
340 HomeDevice hd = gson.fromJson(obj, HomeDevice.class);
343 } catch (Exception e) {
344 logger.debug("An exception occurred while getting the home devices :'{}'", e.getMessage());
350 private Runnable eventListenerRunnable = () -> {
351 if (IP_PATTERN.matcher((String) getConfig().get(INTERFACE)).matches()) {
353 // Get the address that we are going to connect to.
354 InetAddress address1 = null;
355 InetAddress address2 = null;
357 address1 = InetAddress.getByName(JSON_RPC_MULTICAST_IP1);
358 address2 = InetAddress.getByName(JSON_RPC_MULTICAST_IP2);
359 } catch (UnknownHostException e) {
360 logger.debug("An exception occurred while setting up the multicast receiver : '{}'",
364 byte[] buf = new byte[256];
365 MulticastSocket clientSocket = null;
369 clientSocket = new MulticastSocket(JSON_RPC_PORT);
370 clientSocket.setSoTimeout(100);
372 clientSocket.setInterface(InetAddress.getByName((String) getConfig().get(INTERFACE)));
373 clientSocket.joinGroup(address1);
374 clientSocket.joinGroup(address2);
379 DatagramPacket packet = new DatagramPacket(buf, buf.length);
380 clientSocket.receive(packet);
382 String event = new String(packet.getData());
383 logger.debug("Received a multicast event '{}' from '{}:{}'", event, packet.getAddress(),
386 DeviceProperty dp = new DeviceProperty();
389 String[] parts = StringUtils.split(event, "&");
390 for (String p : parts) {
391 String[] subparts = StringUtils.split(p, "=");
392 switch (subparts[0]) {
394 dp.Name = subparts[1];
398 dp.Value = subparts[1];
408 for (ApplianceStatusListener listener : applianceStatusListeners) {
409 listener.onAppliancePropertyChanged(uid, dp);
411 } catch (SocketTimeoutException e) {
414 } catch (InterruptedException ex) {
415 logger.debug("Eventlistener has been interrupted.");
420 } catch (Exception ex) {
421 logger.debug("An exception occurred while receiving multicast packets : '{}'", ex.getMessage());
424 // restart the cycle with a clean slate
426 if (clientSocket != null) {
427 clientSocket.leaveGroup(address1);
428 clientSocket.leaveGroup(address2);
430 } catch (IOException e) {
431 logger.debug("An exception occurred while leaving multicast group : '{}'", e.getMessage());
433 if (clientSocket != null) {
434 clientSocket.close();
439 logger.debug("Invalid IP address for the multicast interface : '{}'", getConfig().get(INTERFACE));
443 public JsonElement invokeOperation(String UID, String modelID, String methodName) {
444 return invokeOperation(UID, modelID, methodName, HDM_ZIGBEE);
447 public JsonElement invokeOperation(String UID, String modelID, String methodName, String protocol) {
448 if (getThing().getStatus() == ThingStatus.ONLINE) {
449 Object[] args = new Object[4];
450 args[0] = protocol + UID;
451 args[1] = "com.miele.xgw3000.gateway.hdm.deviceclasses.Miele" + modelID;
452 args[2] = methodName;
454 return invokeRPC("HDAccess/invokeDCOOperation", args);
456 logger.debug("The Bridge is offline - operations can not be invoked.");
461 protected JsonElement invokeRPC(String methodName, Object[] args) {
462 int id = rand.nextInt(Integer.MAX_VALUE);
464 JsonObject req = new JsonObject();
465 req.addProperty("jsonrpc", "2.0");
466 req.addProperty("id", id);
467 req.addProperty("method", methodName);
469 JsonElement result = null;
471 JsonArray params = new JsonArray();
473 for (Object o : args) {
474 params.add(gson.toJsonTree(o));
477 req.add("params", params);
479 String requestData = req.toString();
480 String responseData = null;
482 responseData = post(url, headers, requestData);
483 } catch (Exception e) {
484 logger.debug("An exception occurred while posting data : '{}'", e.getMessage());
487 if (responseData != null) {
488 logger.debug("The request '{}' yields '{}'", requestData, responseData);
489 JsonObject resp = (JsonObject) JsonParser.parseReader(new StringReader(responseData));
491 result = resp.get("result");
492 JsonElement error = resp.get("error");
494 if (error != null && !error.isJsonNull()) {
495 if (error.isJsonPrimitive()) {
496 logger.debug("A remote exception occurred: '{}'", error.getAsString());
497 } else if (error.isJsonObject()) {
498 JsonObject o = error.getAsJsonObject();
499 Integer code = (o.has("code") ? o.get("code").getAsInt() : null);
500 String message = (o.has("message") ? o.get("message").getAsString() : null);
501 String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString()
502 : o.get("data").getAsString()) : null);
503 logger.debug("A remote exception occurred: '{}':'{}':'{}'", code, message, data);
505 logger.debug("An unknown remote exception occurred: '{}'", error.toString());
513 protected String post(URL url, Map<String, String> headers, String data) throws IOException {
514 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
516 if (headers != null) {
517 for (Map.Entry<String, String> entry : headers.entrySet()) {
518 connection.addRequestProperty(entry.getKey(), entry.getValue());
522 connection.addRequestProperty("Accept-Encoding", "gzip");
524 connection.setRequestMethod("POST");
525 connection.setDoOutput(true);
526 connection.connect();
528 OutputStream out = null;
531 out = connection.getOutputStream();
533 out.write(data.getBytes());
536 int statusCode = connection.getResponseCode();
537 if (statusCode != HttpURLConnection.HTTP_OK) {
538 logger.debug("An unexpected status code was returned: '{}'", statusCode);
546 String responseEncoding = connection.getHeaderField("Content-Encoding");
547 responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());
549 ByteArrayOutputStream bos = new ByteArrayOutputStream();
551 InputStream in = connection.getInputStream();
553 in = connection.getInputStream();
554 if ("gzip".equalsIgnoreCase(responseEncoding)) {
555 in = new GZIPInputStream(in);
557 in = new BufferedInputStream(in);
559 byte[] buff = new byte[1024];
561 while ((n = in.read(buff)) > 0) {
562 bos.write(buff, 0, n);
572 return bos.toString();
575 private synchronized void onUpdate() {
576 logger.debug("Scheduling the Miele polling job");
577 if (pollingJob == null || pollingJob.isCancelled()) {
578 logger.trace("Scheduling the Miele polling job period is {}", POLLING_PERIOD);
579 pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, POLLING_PERIOD, TimeUnit.SECONDS);
580 logger.trace("Scheduling the Miele polling job Job is done ?{}", pollingJob.isDone());
582 logger.debug("Scheduling the Miele event listener job");
584 if (eventListenerJob == null || eventListenerJob.isCancelled()) {
585 executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("binding-miele"));
586 eventListenerJob = executor.submit(eventListenerRunnable);
591 * This method is called whenever the connection to the given {@link MieleBridge} is lost.
594 public void onConnectionLost() {
595 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR);
599 * This method is called whenever the connection to the given {@link MieleBridge} is resumed.
601 * @param bridge the hue bridge the connection is resumed to
603 public void onConnectionResumed() {
604 updateStatus(ThingStatus.ONLINE);
605 for (Thing thing : getThing().getThings()) {
606 MieleApplianceHandler<?> handler = (MieleApplianceHandler<?>) thing.getHandler();
607 if (handler != null) {
608 handler.onBridgeConnectionResumed();
613 public boolean registerApplianceStatusListener(ApplianceStatusListener applianceStatusListener) {
614 if (applianceStatusListener == null) {
615 throw new IllegalArgumentException("It's not allowed to pass a null ApplianceStatusListener.");
617 boolean result = applianceStatusListeners.add(applianceStatusListener);
618 if (result && isInitialized()) {
621 for (HomeDevice hd : getHomeDevices()) {
622 applianceStatusListener.onApplianceAdded(hd);
628 public boolean unregisterApplianceStatusListener(ApplianceStatusListener applianceStatusListener) {
629 boolean result = applianceStatusListeners.remove(applianceStatusListener);
630 if (result && isInitialized()) {
637 public void handleCommand(ChannelUID channelUID, Command command) {
638 // Nothing to do here - the XGW bridge does not handle commands, for now
639 if (command instanceof RefreshType) {
640 // Placeholder for future refinement
646 public void dispose() {
648 if (pollingJob != null) {
649 pollingJob.cancel(true);
652 if (eventListenerJob != null) {
653 eventListenerJob.cancel(true);
654 eventListenerJob = null;
656 if (executor != null) {
657 executor.shutdownNow();