2 * Copyright (c) 2010-2023 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.IOException;
18 import java.net.DatagramPacket;
19 import java.net.InetAddress;
20 import java.net.MulticastSocket;
21 import java.net.SocketTimeoutException;
22 import java.net.URISyntaxException;
23 import java.net.UnknownHostException;
24 import java.util.ArrayList;
25 import java.util.IllformedLocaleException;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Locale;
30 import java.util.Map.Entry;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.ScheduledFuture;
37 import java.util.concurrent.TimeUnit;
38 import java.util.regex.Pattern;
40 import org.eclipse.jdt.annotation.NonNullByDefault;
41 import org.eclipse.jdt.annotation.Nullable;
42 import org.eclipse.jetty.client.HttpClient;
43 import org.openhab.binding.miele.internal.FullyQualifiedApplianceIdentifier;
44 import org.openhab.binding.miele.internal.MieleGatewayCommunicationController;
45 import org.openhab.binding.miele.internal.api.dto.DeviceClassObject;
46 import org.openhab.binding.miele.internal.api.dto.DeviceProperty;
47 import org.openhab.binding.miele.internal.api.dto.HomeDevice;
48 import org.openhab.binding.miele.internal.exceptions.MieleRpcException;
49 import org.openhab.core.common.NamedThreadFactory;
50 import org.openhab.core.config.core.Configuration;
51 import org.openhab.core.thing.Bridge;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.ThingTypeUID;
56 import org.openhab.core.thing.binding.BaseBridgeHandler;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.RefreshType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import com.google.gson.Gson;
63 import com.google.gson.JsonElement;
66 * The {@link MieleBridgeHandler} is responsible for handling commands, which are
67 * sent to one of the channels.
69 * @author Karel Goderis - Initial contribution
70 * @author Kai Kreuzer - Fixed lifecycle issues
71 * @author Martin Lepsy - Added protocol information to support WiFi devices & some refactoring for HomeDevice
72 * @author Jacob Laursen - Fixed multicast and protocol support (ZigBee/LAN)
75 public class MieleBridgeHandler extends BaseBridgeHandler {
77 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(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 private static final int POLLING_PERIOD = 15; // in seconds
83 private static final int JSON_RPC_PORT = 2810;
84 private static final String JSON_RPC_MULTICAST_IP1 = "239.255.68.139";
85 private static final String JSON_RPC_MULTICAST_IP2 = "224.255.68.139";
87 private final Logger logger = LoggerFactory.getLogger(MieleBridgeHandler.class);
89 private boolean lastBridgeConnectionState = false;
91 private final HttpClient httpClient;
92 private final Gson gson = new Gson();
93 private @NonNullByDefault({}) MieleGatewayCommunicationController gatewayCommunication;
95 private Set<DiscoveryListener> discoveryListeners = ConcurrentHashMap.newKeySet();
96 private Map<String, ApplianceStatusListener> applianceStatusListeners = new ConcurrentHashMap<>();
97 private @Nullable ScheduledFuture<?> pollingJob;
98 private @Nullable ExecutorService executor;
99 private @Nullable Future<?> eventListenerJob;
101 private Map<String, HomeDevice> cachedHomeDevicesByApplianceId = new ConcurrentHashMap<>();
102 private Map<String, HomeDevice> cachedHomeDevicesByRemoteUid = new ConcurrentHashMap<>();
104 public MieleBridgeHandler(Bridge bridge, HttpClient httpClient) {
106 this.httpClient = httpClient;
110 public void initialize() {
111 logger.debug("Initializing handler for bridge {}", getThing().getUID());
113 if (!validateConfig(getConfig())) {
118 gatewayCommunication = new MieleGatewayCommunicationController(httpClient, (String) getConfig().get(HOST));
119 } catch (URISyntaxException e) {
120 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
124 updateStatus(ThingStatus.UNKNOWN);
125 lastBridgeConnectionState = false;
126 schedulePollingAndEventListener();
129 private boolean validateConfig(Configuration config) {
130 if (config.get(HOST) == null || ((String) config.get(HOST)).isBlank()) {
131 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
132 "@text/offline.configuration-error.ip-address-not-set");
135 if (config.get(INTERFACE) == null || ((String) config.get(INTERFACE)).isBlank()) {
136 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
137 "@text/offline.configuration-error.ip-multicast-interface-not-set");
140 if (!IP_PATTERN.matcher((String) config.get(INTERFACE)).matches()) {
141 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
142 "@text/offline.configuration-error.invalid-ip-multicast-interface [\"" + config.get(INTERFACE)
146 String language = (String) config.get(LANGUAGE);
147 if (language != null && !language.isBlank()) {
149 new Locale.Builder().setLanguageTag(language).build();
150 } catch (IllformedLocaleException e) {
151 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
152 "@text/offline.configuration-error.invalid-language [\"" + language + "\"]");
159 private Runnable pollingRunnable = new Runnable() {
162 String host = (String) getConfig().get(HOST);
164 List<HomeDevice> homeDevices = getHomeDevices();
166 if (!lastBridgeConnectionState) {
167 logger.debug("Connection to Miele Gateway {} established.", host);
168 lastBridgeConnectionState = true;
170 updateStatus(ThingStatus.ONLINE);
172 refreshHomeDevices(homeDevices);
174 for (Entry<String, ApplianceStatusListener> entry : applianceStatusListeners.entrySet()) {
175 String applianceId = entry.getKey();
176 ApplianceStatusListener listener = entry.getValue();
177 FullyQualifiedApplianceIdentifier applianceIdentifier = getApplianceIdentifierFromApplianceId(
179 if (applianceIdentifier == null) {
180 logger.debug("The appliance with ID '{}' was not found in appliance list from bridge.",
182 listener.onApplianceRemoved();
186 Object[] args = new Object[2];
187 args[0] = applianceIdentifier.getUid();
189 JsonElement result = gatewayCommunication.invokeRPC("HDAccess/getDeviceClassObjects", args);
191 for (JsonElement obj : result.getAsJsonArray()) {
193 DeviceClassObject dco = gson.fromJson(obj, DeviceClassObject.class);
195 // Skip com.prosyst.mbs.services.zigbee.hdm.deviceclasses.ReportingControl
196 if (dco == null || !dco.DeviceClass.startsWith(MIELE_CLASS)) {
200 listener.onApplianceStateChanged(dco);
201 } catch (Exception e) {
202 logger.debug("An exception occurred while querying an appliance : '{}'", e.getMessage());
206 } catch (MieleRpcException e) {
207 Throwable cause = e.getCause();
210 message = e.getMessage();
211 logger.debug("An exception occurred while polling an appliance: '{}'", message);
213 message = cause.getMessage();
214 logger.debug("An exception occurred while polling an appliance: '{}' -> '{}'", e.getMessage(),
217 if (lastBridgeConnectionState) {
218 logger.debug("Connection to Miele Gateway {} lost.", host);
219 lastBridgeConnectionState = false;
221 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
226 private synchronized void refreshHomeDevices(List<HomeDevice> homeDevices) {
227 for (HomeDevice hd : homeDevices) {
228 String key = hd.getApplianceIdentifier().getApplianceId();
229 if (!cachedHomeDevicesByApplianceId.containsKey(key)) {
230 logger.debug("A new appliance with ID '{}' has been added", hd.UID);
231 for (DiscoveryListener listener : discoveryListeners) {
232 listener.onApplianceAdded(hd);
234 ApplianceStatusListener listener = applianceStatusListeners
235 .get(hd.getApplianceIdentifier().getApplianceId());
236 if (listener != null) {
237 listener.onApplianceAdded(hd);
240 cachedHomeDevicesByApplianceId.put(key, hd);
241 cachedHomeDevicesByRemoteUid.put(hd.getRemoteUid(), hd);
244 Set<Entry<String, HomeDevice>> cachedEntries = cachedHomeDevicesByApplianceId.entrySet();
245 Iterator<Entry<String, HomeDevice>> iterator = cachedEntries.iterator();
247 while (iterator.hasNext()) {
248 Entry<String, HomeDevice> cachedEntry = iterator.next();
249 HomeDevice cachedHomeDevice = cachedEntry.getValue();
250 if (!homeDevices.stream().anyMatch(d -> d.UID.equals(cachedHomeDevice.UID))) {
251 logger.debug("The appliance with ID '{}' has been removed", cachedHomeDevice.UID);
252 for (DiscoveryListener listener : discoveryListeners) {
253 listener.onApplianceRemoved(cachedHomeDevice);
255 ApplianceStatusListener listener = applianceStatusListeners
256 .get(cachedHomeDevice.getApplianceIdentifier().getApplianceId());
257 if (listener != null) {
258 listener.onApplianceRemoved();
260 cachedHomeDevicesByRemoteUid.remove(cachedHomeDevice.getRemoteUid());
266 public List<HomeDevice> getHomeDevicesEmptyOnFailure() {
268 return getHomeDevices();
269 } catch (MieleRpcException e) {
270 Throwable cause = e.getCause();
272 logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
274 logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
277 return new ArrayList<>();
281 private List<HomeDevice> getHomeDevices() throws MieleRpcException {
282 List<HomeDevice> devices = new ArrayList<>();
284 if (!isInitialized()) {
288 String[] args = new String[1];
289 args[0] = "(type=SuperVision)";
290 JsonElement result = gatewayCommunication.invokeRPC("HDAccess/getHomeDevices", args);
292 for (JsonElement obj : result.getAsJsonArray()) {
293 HomeDevice hd = gson.fromJson(obj, HomeDevice.class);
301 private @Nullable FullyQualifiedApplianceIdentifier getApplianceIdentifierFromApplianceId(String applianceId) {
302 HomeDevice homeDevice = this.cachedHomeDevicesByApplianceId.get(applianceId);
303 if (homeDevice == null) {
307 return homeDevice.getApplianceIdentifier();
310 private Runnable eventListenerRunnable = () -> {
311 if (IP_PATTERN.matcher((String) getConfig().get(INTERFACE)).matches()) {
313 // Get the address that we are going to connect to.
314 InetAddress address1 = null;
315 InetAddress address2 = null;
317 address1 = InetAddress.getByName(JSON_RPC_MULTICAST_IP1);
318 address2 = InetAddress.getByName(JSON_RPC_MULTICAST_IP2);
319 } catch (UnknownHostException e) {
320 logger.debug("An exception occurred while setting up the multicast receiver: '{}'", e.getMessage());
323 byte[] buf = new byte[256];
324 MulticastSocket clientSocket = null;
328 clientSocket = new MulticastSocket(JSON_RPC_PORT);
329 clientSocket.setSoTimeout(100);
331 clientSocket.setInterface(InetAddress.getByName((String) getConfig().get(INTERFACE)));
332 clientSocket.joinGroup(address1);
333 clientSocket.joinGroup(address2);
338 DatagramPacket packet = new DatagramPacket(buf, buf.length);
339 clientSocket.receive(packet);
341 String event = new String(packet.getData());
342 logger.debug("Received a multicast event '{}' from '{}:{}'", event, packet.getAddress(),
345 String[] parts = event.split("&");
346 String id = null, name = null, value = null;
347 for (String p : parts) {
348 String[] subparts = p.split("=");
349 switch (subparts[0]) {
355 value = subparts[1].strip().trim();
365 if (id == null || name == null || value == null) {
369 // In XGW 3000 firmware 2.03 this was changed from UID (hdm:ZigBee:0123456789abcdef#210)
370 // to serial number (001234567890)
371 FullyQualifiedApplianceIdentifier applianceIdentifier;
372 if (id.startsWith("hdm:")) {
373 applianceIdentifier = new FullyQualifiedApplianceIdentifier(id);
375 HomeDevice device = cachedHomeDevicesByRemoteUid.get(id);
376 if (device == null) {
377 logger.debug("Multicast event not handled as id {} is unknown.", id);
380 applianceIdentifier = device.getApplianceIdentifier();
382 var deviceProperty = new DeviceProperty();
383 deviceProperty.Name = name;
384 deviceProperty.Value = value;
385 ApplianceStatusListener listener = applianceStatusListeners
386 .get(applianceIdentifier.getApplianceId());
387 if (listener != null) {
388 listener.onAppliancePropertyChanged(deviceProperty);
390 } catch (SocketTimeoutException e) {
393 } catch (InterruptedException ex) {
394 logger.debug("Event listener has been interrupted.");
399 } catch (Exception ex) {
400 logger.debug("An exception occurred while receiving multicast packets: '{}'", ex.getMessage());
403 // restart the cycle with a clean slate
405 if (clientSocket != null) {
406 clientSocket.leaveGroup(address1);
407 clientSocket.leaveGroup(address2);
409 } catch (IOException e) {
410 logger.debug("An exception occurred while leaving multicast group: '{}'", e.getMessage());
412 if (clientSocket != null) {
413 clientSocket.close();
418 logger.debug("Invalid IP address for the multicast interface: '{}'", getConfig().get(INTERFACE));
422 public JsonElement invokeOperation(String applianceId, String modelID, String methodName) throws MieleRpcException {
423 if (getThing().getStatus() != ThingStatus.ONLINE) {
424 throw new MieleRpcException("Bridge is offline, operations can not be invoked");
427 FullyQualifiedApplianceIdentifier applianceIdentifier = getApplianceIdentifierFromApplianceId(applianceId);
428 if (applianceIdentifier == null) {
429 throw new MieleRpcException("Appliance with ID" + applianceId
430 + " was not found in appliance list from gateway - operations can not be invoked");
433 return gatewayCommunication.invokeOperation(applianceIdentifier, modelID, methodName);
436 private synchronized void schedulePollingAndEventListener() {
437 logger.debug("Scheduling the Miele polling job");
438 ScheduledFuture<?> pollingJob = this.pollingJob;
439 if (pollingJob == null || pollingJob.isCancelled()) {
440 logger.trace("Scheduling the Miele polling job period is {}", POLLING_PERIOD);
441 pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, POLLING_PERIOD, TimeUnit.SECONDS);
442 this.pollingJob = pollingJob;
443 logger.trace("Scheduling the Miele polling job Job is done ?{}", pollingJob.isDone());
446 logger.debug("Scheduling the Miele event listener job");
447 Future<?> eventListenerJob = this.eventListenerJob;
448 if (eventListenerJob == null || eventListenerJob.isCancelled()) {
449 ExecutorService executor = Executors
450 .newSingleThreadExecutor(new NamedThreadFactory("binding-" + BINDING_ID));
451 this.executor = executor;
452 this.eventListenerJob = executor.submit(eventListenerRunnable);
456 public boolean registerApplianceStatusListener(String applianceId,
457 ApplianceStatusListener applianceStatusListener) {
458 ApplianceStatusListener existingListener = applianceStatusListeners.get(applianceId);
459 if (existingListener != null) {
460 if (!existingListener.equals(applianceStatusListener)) {
461 logger.warn("Unsupported configuration: appliance with ID '{}' referenced by multiple things",
464 logger.debug("Duplicate listener registration attempted for '{}'", applianceId);
468 applianceStatusListeners.put(applianceId, applianceStatusListener);
470 HomeDevice cachedHomeDevice = cachedHomeDevicesByApplianceId.get(applianceId);
471 if (cachedHomeDevice != null) {
472 applianceStatusListener.onApplianceAdded(cachedHomeDevice);
475 refreshHomeDevices(getHomeDevices());
476 } catch (MieleRpcException e) {
477 Throwable cause = e.getCause();
479 logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
481 logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
490 public boolean unregisterApplianceStatusListener(String applianceId,
491 ApplianceStatusListener applianceStatusListener) {
492 return applianceStatusListeners.remove(applianceId) != null;
495 public boolean registerDiscoveryListener(DiscoveryListener discoveryListener) {
496 if (!discoveryListeners.add(discoveryListener)) {
499 if (cachedHomeDevicesByApplianceId.isEmpty()) {
501 refreshHomeDevices(getHomeDevices());
502 } catch (MieleRpcException e) {
503 Throwable cause = e.getCause();
505 logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
507 logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
512 for (Entry<String, HomeDevice> entry : cachedHomeDevicesByApplianceId.entrySet()) {
513 discoveryListener.onApplianceAdded(entry.getValue());
519 public boolean unregisterDiscoveryListener(DiscoveryListener discoveryListener) {
520 return discoveryListeners.remove(discoveryListener);
524 public void handleCommand(ChannelUID channelUID, Command command) {
525 // Nothing to do here - the XGW bridge does not handle commands, for now
526 if (command instanceof RefreshType) {
527 // Placeholder for future refinement
533 public void dispose() {
535 ScheduledFuture<?> pollingJob = this.pollingJob;
536 if (pollingJob != null) {
537 pollingJob.cancel(true);
538 this.pollingJob = null;
540 Future<?> eventListenerJob = this.eventListenerJob;
541 if (eventListenerJob != null) {
542 eventListenerJob.cancel(true);
543 this.eventListenerJob = null;
545 ExecutorService executor = this.executor;
546 if (executor != null) {
547 executor.shutdownNow();
548 this.executor = null;