]> git.basschouten.com Git - openhab-addons.git/blob
f9f277a056426df12f68a60b94a422e13b13f08c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.miele.internal.handler;
14
15 import static org.openhab.binding.miele.internal.MieleBindingConstants.*;
16
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;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
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;
39
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;
61
62 import com.google.gson.Gson;
63 import com.google.gson.JsonElement;
64
65 /**
66  * The {@link MieleBridgeHandler} is responsible for handling commands, which are
67  * sent to one of the channels.
68  *
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)
73  **/
74 @NonNullByDefault
75 public class MieleBridgeHandler extends BaseBridgeHandler {
76
77     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_XGW3000);
78
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])$");
81
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";
86
87     private final Logger logger = LoggerFactory.getLogger(MieleBridgeHandler.class);
88
89     private boolean lastBridgeConnectionState = false;
90
91     private final HttpClient httpClient;
92     private final Gson gson = new Gson();
93     private @NonNullByDefault({}) MieleGatewayCommunicationController gatewayCommunication;
94
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;
100
101     private Map<String, HomeDevice> cachedHomeDevicesByApplianceId = new ConcurrentHashMap<>();
102     private Map<String, HomeDevice> cachedHomeDevicesByRemoteUid = new ConcurrentHashMap<>();
103
104     public MieleBridgeHandler(Bridge bridge, HttpClient httpClient) {
105         super(bridge);
106         this.httpClient = httpClient;
107     }
108
109     @Override
110     public void initialize() {
111         logger.debug("Initializing handler for bridge {}", getThing().getUID());
112
113         if (!validateConfig(getConfig())) {
114             return;
115         }
116
117         try {
118             gatewayCommunication = new MieleGatewayCommunicationController(httpClient, (String) getConfig().get(HOST));
119         } catch (URISyntaxException e) {
120             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
121             return;
122         }
123
124         updateStatus(ThingStatus.UNKNOWN);
125         lastBridgeConnectionState = false;
126         schedulePollingAndEventListener();
127     }
128
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");
133             return false;
134         }
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");
138             return false;
139         }
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)
143                             + "\"]");
144             return false;
145         }
146         String language = (String) config.get(LANGUAGE);
147         if (language != null && !language.isBlank()) {
148             try {
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 + "\"]");
153                 return false;
154             }
155         }
156         return true;
157     }
158
159     private Runnable pollingRunnable = new Runnable() {
160         @Override
161         public void run() {
162             String host = (String) getConfig().get(HOST);
163             try {
164                 List<HomeDevice> homeDevices = getHomeDevices();
165
166                 if (!lastBridgeConnectionState) {
167                     logger.debug("Connection to Miele Gateway {} established.", host);
168                     lastBridgeConnectionState = true;
169                 }
170                 updateStatus(ThingStatus.ONLINE);
171
172                 refreshHomeDevices(homeDevices);
173
174                 for (Entry<String, ApplianceStatusListener> entry : applianceStatusListeners.entrySet()) {
175                     String applianceId = entry.getKey();
176                     ApplianceStatusListener listener = entry.getValue();
177                     FullyQualifiedApplianceIdentifier applianceIdentifier = getApplianceIdentifierFromApplianceId(
178                             applianceId);
179                     if (applianceIdentifier == null) {
180                         logger.debug("The appliance with ID '{}' was not found in appliance list from bridge.",
181                                 applianceId);
182                         listener.onApplianceRemoved();
183                         continue;
184                     }
185
186                     Object[] args = new Object[2];
187                     args[0] = applianceIdentifier.getUid();
188                     args[1] = true;
189                     JsonElement result = gatewayCommunication.invokeRPC("HDAccess/getDeviceClassObjects", args);
190
191                     for (JsonElement obj : result.getAsJsonArray()) {
192                         try {
193                             DeviceClassObject dco = gson.fromJson(obj, DeviceClassObject.class);
194
195                             // Skip com.prosyst.mbs.services.zigbee.hdm.deviceclasses.ReportingControl
196                             if (dco == null || !dco.DeviceClass.startsWith(MIELE_CLASS)) {
197                                 continue;
198                             }
199
200                             listener.onApplianceStateChanged(dco);
201                         } catch (Exception e) {
202                             logger.debug("An exception occurred while querying an appliance : '{}'", e.getMessage());
203                         }
204                     }
205                 }
206             } catch (MieleRpcException e) {
207                 Throwable cause = e.getCause();
208                 String message;
209                 if (cause == null) {
210                     message = e.getMessage();
211                     logger.debug("An exception occurred while polling an appliance: '{}'", message);
212                 } else {
213                     message = cause.getMessage();
214                     logger.debug("An exception occurred while polling an appliance: '{}' -> '{}'", e.getMessage(),
215                             message);
216                 }
217                 if (lastBridgeConnectionState) {
218                     logger.debug("Connection to Miele Gateway {} lost.", host);
219                     lastBridgeConnectionState = false;
220                 }
221                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
222             }
223         }
224     };
225
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);
233                 }
234                 ApplianceStatusListener listener = applianceStatusListeners
235                         .get(hd.getApplianceIdentifier().getApplianceId());
236                 if (listener != null) {
237                     listener.onApplianceAdded(hd);
238                 }
239             }
240             cachedHomeDevicesByApplianceId.put(key, hd);
241             cachedHomeDevicesByRemoteUid.put(hd.getRemoteUid(), hd);
242         }
243
244         Set<Entry<String, HomeDevice>> cachedEntries = cachedHomeDevicesByApplianceId.entrySet();
245         Iterator<Entry<String, HomeDevice>> iterator = cachedEntries.iterator();
246
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);
254                 }
255                 ApplianceStatusListener listener = applianceStatusListeners
256                         .get(cachedHomeDevice.getApplianceIdentifier().getApplianceId());
257                 if (listener != null) {
258                     listener.onApplianceRemoved();
259                 }
260                 cachedHomeDevicesByRemoteUid.remove(cachedHomeDevice.getRemoteUid());
261                 iterator.remove();
262             }
263         }
264     }
265
266     public List<HomeDevice> getHomeDevicesEmptyOnFailure() {
267         try {
268             return getHomeDevices();
269         } catch (MieleRpcException e) {
270             Throwable cause = e.getCause();
271             if (cause == null) {
272                 logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
273             } else {
274                 logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
275                         cause.getMessage());
276             }
277             return new ArrayList<>();
278         }
279     }
280
281     private List<HomeDevice> getHomeDevices() throws MieleRpcException {
282         List<HomeDevice> devices = new ArrayList<>();
283
284         if (!isInitialized()) {
285             return devices;
286         }
287
288         String[] args = new String[1];
289         args[0] = "(type=SuperVision)";
290         JsonElement result = gatewayCommunication.invokeRPC("HDAccess/getHomeDevices", args);
291
292         for (JsonElement obj : result.getAsJsonArray()) {
293             HomeDevice hd = gson.fromJson(obj, HomeDevice.class);
294             if (hd != null) {
295                 devices.add(hd);
296             }
297         }
298         return devices;
299     }
300
301     private @Nullable FullyQualifiedApplianceIdentifier getApplianceIdentifierFromApplianceId(String applianceId) {
302         HomeDevice homeDevice = this.cachedHomeDevicesByApplianceId.get(applianceId);
303         if (homeDevice == null) {
304             return null;
305         }
306
307         return homeDevice.getApplianceIdentifier();
308     }
309
310     private Runnable eventListenerRunnable = () -> {
311         if (IP_PATTERN.matcher((String) getConfig().get(INTERFACE)).matches()) {
312             while (true) {
313                 // Get the address that we are going to connect to.
314                 InetAddress address1 = null;
315                 InetAddress address2 = null;
316                 try {
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());
321                 }
322
323                 byte[] buf = new byte[256];
324                 MulticastSocket clientSocket = null;
325
326                 while (true) {
327                     try {
328                         clientSocket = new MulticastSocket(JSON_RPC_PORT);
329                         clientSocket.setSoTimeout(100);
330
331                         clientSocket.setInterface(InetAddress.getByName((String) getConfig().get(INTERFACE)));
332                         clientSocket.joinGroup(address1);
333                         clientSocket.joinGroup(address2);
334
335                         while (true) {
336                             try {
337                                 buf = new byte[256];
338                                 DatagramPacket packet = new DatagramPacket(buf, buf.length);
339                                 clientSocket.receive(packet);
340
341                                 String event = new String(packet.getData());
342                                 logger.debug("Received a multicast event '{}' from '{}:{}'", event, packet.getAddress(),
343                                         packet.getPort());
344
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]) {
350                                         case "property": {
351                                             name = subparts[1];
352                                             break;
353                                         }
354                                         case "value": {
355                                             value = subparts[1].strip().trim();
356                                             break;
357                                         }
358                                         case "id": {
359                                             id = subparts[1];
360                                             break;
361                                         }
362                                     }
363                                 }
364
365                                 if (id == null || name == null || value == null) {
366                                     continue;
367                                 }
368
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);
374                                 } else {
375                                     HomeDevice device = cachedHomeDevicesByRemoteUid.get(id);
376                                     if (device == null) {
377                                         logger.debug("Multicast event not handled as id {} is unknown.", id);
378                                         continue;
379                                     }
380                                     applianceIdentifier = device.getApplianceIdentifier();
381                                 }
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);
389                                 }
390                             } catch (SocketTimeoutException e) {
391                                 try {
392                                     Thread.sleep(500);
393                                 } catch (InterruptedException ex) {
394                                     logger.debug("Event listener has been interrupted.");
395                                     break;
396                                 }
397                             }
398                         }
399                     } catch (Exception ex) {
400                         logger.debug("An exception occurred while receiving multicast packets: '{}'", ex.getMessage());
401                     }
402
403                     // restart the cycle with a clean slate
404                     try {
405                         if (clientSocket != null) {
406                             clientSocket.leaveGroup(address1);
407                             clientSocket.leaveGroup(address2);
408                         }
409                     } catch (IOException e) {
410                         logger.debug("An exception occurred while leaving multicast group: '{}'", e.getMessage());
411                     }
412                     if (clientSocket != null) {
413                         clientSocket.close();
414                     }
415                 }
416             }
417         } else {
418             logger.debug("Invalid IP address for the multicast interface: '{}'", getConfig().get(INTERFACE));
419         }
420     };
421
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");
425         }
426
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");
431         }
432
433         return gatewayCommunication.invokeOperation(applianceIdentifier, modelID, methodName);
434     }
435
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());
444         }
445
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);
453         }
454     }
455
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",
462                         applianceId);
463             } else {
464                 logger.debug("Duplicate listener registration attempted for '{}'", applianceId);
465             }
466             return false;
467         }
468         applianceStatusListeners.put(applianceId, applianceStatusListener);
469
470         HomeDevice cachedHomeDevice = cachedHomeDevicesByApplianceId.get(applianceId);
471         if (cachedHomeDevice != null) {
472             applianceStatusListener.onApplianceAdded(cachedHomeDevice);
473         } else {
474             try {
475                 refreshHomeDevices(getHomeDevices());
476             } catch (MieleRpcException e) {
477                 Throwable cause = e.getCause();
478                 if (cause == null) {
479                     logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
480                 } else {
481                     logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
482                             cause.getMessage());
483                 }
484             }
485         }
486
487         return true;
488     }
489
490     public boolean unregisterApplianceStatusListener(String applianceId,
491             ApplianceStatusListener applianceStatusListener) {
492         return applianceStatusListeners.remove(applianceId) != null;
493     }
494
495     public boolean registerDiscoveryListener(DiscoveryListener discoveryListener) {
496         if (!discoveryListeners.add(discoveryListener)) {
497             return false;
498         }
499         if (cachedHomeDevicesByApplianceId.isEmpty()) {
500             try {
501                 refreshHomeDevices(getHomeDevices());
502             } catch (MieleRpcException e) {
503                 Throwable cause = e.getCause();
504                 if (cause == null) {
505                     logger.debug("An exception occurred while getting the home devices: '{}'", e.getMessage());
506                 } else {
507                     logger.debug("An exception occurred while getting the home devices: '{}' -> '{}", e.getMessage(),
508                             cause.getMessage());
509                 }
510             }
511         } else {
512             for (Entry<String, HomeDevice> entry : cachedHomeDevicesByApplianceId.entrySet()) {
513                 discoveryListener.onApplianceAdded(entry.getValue());
514             }
515         }
516         return true;
517     }
518
519     public boolean unregisterDiscoveryListener(DiscoveryListener discoveryListener) {
520         return discoveryListeners.remove(discoveryListener);
521     }
522
523     @Override
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
528             return;
529         }
530     }
531
532     @Override
533     public void dispose() {
534         super.dispose();
535         ScheduledFuture<?> pollingJob = this.pollingJob;
536         if (pollingJob != null) {
537             pollingJob.cancel(true);
538             this.pollingJob = null;
539         }
540         Future<?> eventListenerJob = this.eventListenerJob;
541         if (eventListenerJob != null) {
542             eventListenerJob.cancel(true);
543             this.eventListenerJob = null;
544         }
545         ExecutorService executor = this.executor;
546         if (executor != null) {
547             executor.shutdownNow();
548             this.executor = null;
549         }
550     }
551 }