]> git.basschouten.com Git - openhab-addons.git/blob
b6324ca66c7b9a0303a803efa17bfafe4026b093
[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.remoteopenhab.internal.handler;
14
15 import static org.openhab.binding.remoteopenhab.internal.RemoteopenhabBindingConstants.BINDING_ID;
16
17 import java.net.MalformedURLException;
18 import java.net.URL;
19 import java.time.ZonedDateTime;
20 import java.time.format.DateTimeFormatter;
21 import java.time.format.DateTimeParseException;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.stream.Collectors;
29
30 import javax.ws.rs.client.ClientBuilder;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.eclipse.jetty.client.HttpClient;
35 import org.openhab.binding.remoteopenhab.internal.RemoteopenhabChannelTypeProvider;
36 import org.openhab.binding.remoteopenhab.internal.RemoteopenhabStateDescriptionOptionProvider;
37 import org.openhab.binding.remoteopenhab.internal.config.RemoteopenhabServerConfiguration;
38 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabItem;
39 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateDescription;
40 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateOption;
41 import org.openhab.binding.remoteopenhab.internal.discovery.RemoteopenhabDiscoveryService;
42 import org.openhab.binding.remoteopenhab.internal.exceptions.RemoteopenhabException;
43 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabItemsDataListener;
44 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabStreamingDataListener;
45 import org.openhab.binding.remoteopenhab.internal.rest.RemoteopenhabRestClient;
46 import org.openhab.core.library.CoreItemFactory;
47 import org.openhab.core.library.types.DateTimeType;
48 import org.openhab.core.library.types.DecimalType;
49 import org.openhab.core.library.types.HSBType;
50 import org.openhab.core.library.types.OnOffType;
51 import org.openhab.core.library.types.OpenClosedType;
52 import org.openhab.core.library.types.PercentType;
53 import org.openhab.core.library.types.PlayPauseType;
54 import org.openhab.core.library.types.PointType;
55 import org.openhab.core.library.types.QuantityType;
56 import org.openhab.core.library.types.RawType;
57 import org.openhab.core.library.types.StringType;
58 import org.openhab.core.net.NetUtil;
59 import org.openhab.core.thing.Bridge;
60 import org.openhab.core.thing.Channel;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.ThingStatus;
63 import org.openhab.core.thing.ThingStatusDetail;
64 import org.openhab.core.thing.binding.BaseBridgeHandler;
65 import org.openhab.core.thing.binding.ThingHandlerService;
66 import org.openhab.core.thing.binding.builder.ChannelBuilder;
67 import org.openhab.core.thing.binding.builder.ThingBuilder;
68 import org.openhab.core.thing.type.AutoUpdatePolicy;
69 import org.openhab.core.thing.type.ChannelKind;
70 import org.openhab.core.thing.type.ChannelType;
71 import org.openhab.core.thing.type.ChannelTypeBuilder;
72 import org.openhab.core.thing.type.ChannelTypeUID;
73 import org.openhab.core.types.Command;
74 import org.openhab.core.types.RefreshType;
75 import org.openhab.core.types.State;
76 import org.openhab.core.types.StateDescriptionFragmentBuilder;
77 import org.openhab.core.types.StateOption;
78 import org.openhab.core.types.TypeParser;
79 import org.openhab.core.types.UnDefType;
80 import org.osgi.service.jaxrs.client.SseEventSourceFactory;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 import com.google.gson.Gson;
85
86 /**
87  * The {@link RemoteopenhabBridgeHandler} is responsible for handling commands and updating states
88  * using the REST API of the remote openHAB server.
89  *
90  * @author Laurent Garnier - Initial contribution
91  */
92 @NonNullByDefault
93 public class RemoteopenhabBridgeHandler extends BaseBridgeHandler
94         implements RemoteopenhabStreamingDataListener, RemoteopenhabItemsDataListener {
95
96     private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
97     private static final DateTimeFormatter FORMATTER_DATE = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN);
98
99     private static final long CONNECTION_TIMEOUT_MILLIS = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES);
100     private static final int MAX_STATE_SIZE_FOR_LOGGING = 50;
101
102     private final Logger logger = LoggerFactory.getLogger(RemoteopenhabBridgeHandler.class);
103
104     private final HttpClient httpClientTrustingCert;
105     private final RemoteopenhabChannelTypeProvider channelTypeProvider;
106     private final RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider;
107
108     private final Object updateThingLock = new Object();
109
110     private @NonNullByDefault({}) RemoteopenhabServerConfiguration config;
111
112     private @Nullable ScheduledFuture<?> checkConnectionJob;
113     private RemoteopenhabRestClient restClient;
114
115     public RemoteopenhabBridgeHandler(Bridge bridge, HttpClient httpClient, HttpClient httpClientTrustingCert,
116             ClientBuilder clientBuilder, SseEventSourceFactory eventSourceFactory,
117             RemoteopenhabChannelTypeProvider channelTypeProvider,
118             RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider, final Gson jsonParser) {
119         super(bridge);
120         this.httpClientTrustingCert = httpClientTrustingCert;
121         this.channelTypeProvider = channelTypeProvider;
122         this.stateDescriptionProvider = stateDescriptionProvider;
123         this.restClient = new RemoteopenhabRestClient(httpClient, clientBuilder, eventSourceFactory, jsonParser);
124     }
125
126     @Override
127     public void initialize() {
128         logger.debug("Initializing remote openHAB handler for bridge {}", getThing().getUID());
129
130         config = getConfigAs(RemoteopenhabServerConfiguration.class);
131
132         String host = config.host.trim();
133         if (host.length() == 0) {
134             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
135                     "Undefined server address setting in the thing configuration");
136             return;
137         }
138         List<String> localIpAddresses = NetUtil.getAllInterfaceAddresses().stream()
139                 .filter(a -> !a.getAddress().isLinkLocalAddress())
140                 .map(a -> a.getAddress().getHostAddress().split("%")[0]).collect(Collectors.toList());
141         if (localIpAddresses.contains(host)) {
142             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
143                     "Do not use the local server as a remote server in the thing configuration");
144             return;
145         }
146         String path = config.restPath.trim();
147         if (path.length() == 0 || !path.startsWith("/")) {
148             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
149                     "Invalid REST API path setting in the thing configuration");
150             return;
151         }
152         URL url;
153         try {
154             url = new URL(config.useHttps ? "https" : "http", host, config.port, path);
155         } catch (MalformedURLException e) {
156             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
157                     "Invalid REST URL built from the settings in the thing configuration");
158             return;
159         }
160
161         String urlStr = url.toString();
162         if (urlStr.endsWith("/")) {
163             urlStr = urlStr.substring(0, urlStr.length() - 1);
164         }
165         logger.debug("REST URL = {}", urlStr);
166
167         restClient.setRestUrl(urlStr);
168         restClient.setAccessToken(config.token);
169         if (config.useHttps && config.trustedCertificate) {
170             restClient.setHttpClient(httpClientTrustingCert);
171             restClient.setTrustedCertificate(true);
172         }
173
174         updateStatus(ThingStatus.UNKNOWN);
175
176         startCheckConnectionJob();
177     }
178
179     @Override
180     public void dispose() {
181         logger.debug("Disposing remote openHAB handler for bridge {}", getThing().getUID());
182         stopStreamingUpdates();
183         stopCheckConnectionJob();
184     }
185
186     @Override
187     public void handleCommand(ChannelUID channelUID, Command command) {
188         if (getThing().getStatus() != ThingStatus.ONLINE) {
189             return;
190         }
191
192         try {
193             if (command instanceof RefreshType) {
194                 String state = restClient.getRemoteItemState(channelUID.getId());
195                 updateChannelState(channelUID.getId(), null, state);
196             } else if (isLinked(channelUID)) {
197                 restClient.sendCommandToRemoteItem(channelUID.getId(), command);
198                 String commandStr = command.toFullString();
199                 logger.debug("Sending command {} to remote item {} succeeded",
200                         commandStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? commandStr
201                                 : commandStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...",
202                         channelUID.getId());
203             }
204         } catch (RemoteopenhabException e) {
205             logger.debug("{}", e.getMessage());
206         }
207     }
208
209     private void createChannels(List<RemoteopenhabItem> items, boolean replace) {
210         synchronized (updateThingLock) {
211             int nbGroups = 0;
212             List<Channel> channels = new ArrayList<>();
213             for (RemoteopenhabItem item : items) {
214                 String itemType = item.type;
215                 boolean readOnly = false;
216                 if ("Group".equals(itemType)) {
217                     if (item.groupType.isEmpty()) {
218                         // Standard groups are ignored
219                         nbGroups++;
220                         continue;
221                     } else {
222                         itemType = item.groupType;
223                     }
224                 } else {
225                     if (item.stateDescription != null && item.stateDescription.readOnly) {
226                         readOnly = true;
227                     }
228                 }
229                 String channelTypeId = String.format("item%s%s", itemType.replace(":", ""), readOnly ? "RO" : "");
230                 ChannelTypeUID channelTypeUID = new ChannelTypeUID(BINDING_ID, channelTypeId);
231                 ChannelType channelType = channelTypeProvider.getChannelType(channelTypeUID, null);
232                 String label;
233                 String description;
234                 if (channelType == null) {
235                     logger.trace("Create the channel type {} for item type {}", channelTypeUID, itemType);
236                     label = String.format("Remote %s Item", itemType);
237                     description = String.format("An item of type %s from the remote server.", itemType);
238                     channelType = ChannelTypeBuilder.state(channelTypeUID, label, itemType).withDescription(description)
239                             .withStateDescriptionFragment(
240                                     StateDescriptionFragmentBuilder.create().withReadOnly(readOnly).build())
241                             .withAutoUpdatePolicy(AutoUpdatePolicy.VETO).build();
242                     channelTypeProvider.addChannelType(channelType);
243                 }
244                 ChannelUID channelUID = new ChannelUID(getThing().getUID(), item.name);
245                 logger.trace("Create the channel {} of type {}", channelUID, channelTypeUID);
246                 label = "Item " + item.name;
247                 description = String.format("Item %s from the remote server.", item.name);
248                 channels.add(ChannelBuilder.create(channelUID, itemType).withType(channelTypeUID)
249                         .withKind(ChannelKind.STATE).withLabel(label).withDescription(description).build());
250             }
251             ThingBuilder thingBuilder = editThing();
252             if (replace) {
253                 thingBuilder.withChannels(channels);
254                 updateThing(thingBuilder.build());
255                 logger.debug("{} channels defined for the thing {} (from {} items including {} groups)",
256                         channels.size(), getThing().getUID(), items.size(), nbGroups);
257             } else if (channels.size() > 0) {
258                 int nbRemoved = 0;
259                 for (Channel channel : channels) {
260                     if (getThing().getChannel(channel.getUID()) != null) {
261                         thingBuilder.withoutChannel(channel.getUID());
262                         nbRemoved++;
263                     }
264                 }
265                 if (nbRemoved > 0) {
266                     logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
267                             items.size());
268                 }
269                 for (Channel channel : channels) {
270                     thingBuilder.withChannel(channel);
271                 }
272                 updateThing(thingBuilder.build());
273                 if (nbGroups > 0) {
274                     logger.debug("{} channels added for the thing {} (from {} items including {} groups)",
275                             channels.size(), getThing().getUID(), items.size(), nbGroups);
276                 } else {
277                     logger.debug("{} channels added for the thing {} (from {} items)", channels.size(),
278                             getThing().getUID(), items.size());
279                 }
280             }
281         }
282     }
283
284     private void removeChannels(List<RemoteopenhabItem> items) {
285         synchronized (updateThingLock) {
286             int nbRemoved = 0;
287             ThingBuilder thingBuilder = editThing();
288             for (RemoteopenhabItem item : items) {
289                 Channel channel = getThing().getChannel(item.name);
290                 if (channel != null) {
291                     thingBuilder.withoutChannel(channel.getUID());
292                     nbRemoved++;
293                 }
294             }
295             if (nbRemoved > 0) {
296                 updateThing(thingBuilder.build());
297                 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
298                         items.size());
299             }
300         }
301     }
302
303     private void setStateOptions(List<RemoteopenhabItem> items) {
304         for (RemoteopenhabItem item : items) {
305             Channel channel = getThing().getChannel(item.name);
306             RemoteopenhabStateDescription descr = item.stateDescription;
307             List<RemoteopenhabStateOption> options = descr == null ? null : descr.options;
308             if (channel != null && options != null && options.size() > 0) {
309                 List<StateOption> stateOptions = new ArrayList<>();
310                 for (RemoteopenhabStateOption option : options) {
311                     stateOptions.add(new StateOption(option.value, option.label));
312                 }
313                 stateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions);
314                 logger.trace("{} options set for the channel {}", options.size(), channel.getUID());
315             }
316         }
317     }
318
319     public void checkConnection() {
320         logger.debug("Try the root REST API...");
321         try {
322             restClient.tryApi();
323             if (restClient.getRestApiVersion() == null) {
324                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
325                         "OH 1.x server not supported by the binding");
326             } else if (getThing().getStatus() != ThingStatus.ONLINE) {
327                 List<RemoteopenhabItem> items = restClient.getRemoteItems();
328
329                 createChannels(items, true);
330                 setStateOptions(items);
331                 for (RemoteopenhabItem item : items) {
332                     updateChannelState(item.name, null, item.state);
333                 }
334
335                 updateStatus(ThingStatus.ONLINE);
336
337                 restartStreamingUpdates();
338             }
339         } catch (RemoteopenhabException e) {
340             logger.debug("{}", e.getMessage());
341             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
342             stopStreamingUpdates();
343         }
344     }
345
346     private void startCheckConnectionJob() {
347         ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
348         if (localCheckConnectionJob == null || localCheckConnectionJob.isCancelled()) {
349             checkConnectionJob = scheduler.scheduleWithFixedDelay(() -> {
350                 long millisSinceLastEvent = System.currentTimeMillis() - restClient.getLastEventTimestamp();
351                 if (millisSinceLastEvent > CONNECTION_TIMEOUT_MILLIS) {
352                     logger.debug("Check: Maybe disconnected from streaming events, millisSinceLastEvent={}",
353                             millisSinceLastEvent);
354                     checkConnection();
355                 } else {
356                     logger.debug("Check: Receiving streaming events, millisSinceLastEvent={}", millisSinceLastEvent);
357                 }
358             }, 0, CONNECTION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
359         }
360     }
361
362     private void stopCheckConnectionJob() {
363         ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
364         if (localCheckConnectionJob != null) {
365             localCheckConnectionJob.cancel(true);
366             checkConnectionJob = null;
367         }
368     }
369
370     private void restartStreamingUpdates() {
371         synchronized (restClient) {
372             stopStreamingUpdates();
373             startStreamingUpdates();
374         }
375     }
376
377     private void startStreamingUpdates() {
378         synchronized (restClient) {
379             restClient.addStreamingDataListener(this);
380             restClient.addItemsDataListener(this);
381             restClient.start();
382         }
383     }
384
385     private void stopStreamingUpdates() {
386         synchronized (restClient) {
387             restClient.stop();
388             restClient.removeStreamingDataListener(this);
389             restClient.removeItemsDataListener(this);
390         }
391     }
392
393     public RemoteopenhabRestClient gestRestClient() {
394         return restClient;
395     }
396
397     @Override
398     public void onConnected() {
399         updateStatus(ThingStatus.ONLINE);
400     }
401
402     @Override
403     public void onError(String message) {
404         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
405     }
406
407     @Override
408     public void onItemStateEvent(String itemName, String stateType, String state) {
409         updateChannelState(itemName, stateType, state);
410     }
411
412     @Override
413     public void onItemAdded(RemoteopenhabItem item) {
414         createChannels(List.of(item), false);
415     }
416
417     @Override
418     public void onItemRemoved(RemoteopenhabItem item) {
419         removeChannels(List.of(item));
420     }
421
422     @Override
423     public void onItemUpdated(RemoteopenhabItem newItem, RemoteopenhabItem oldItem) {
424         if (!newItem.type.equals(oldItem.type)) {
425             createChannels(List.of(newItem), false);
426         } else {
427             logger.trace("Updated remote item {} ignored because item type {} is unchanged", newItem.name,
428                     newItem.type);
429         }
430     }
431
432     private void updateChannelState(String itemName, @Nullable String stateType, String state) {
433         Channel channel = getThing().getChannel(itemName);
434         if (channel == null) {
435             logger.trace("No channel for item {}", itemName);
436             return;
437         }
438         String acceptedItemType = channel.getAcceptedItemType();
439         if (acceptedItemType == null) {
440             logger.trace("Channel without accepted item type for item {}", itemName);
441             return;
442         }
443         if (!isLinked(channel.getUID())) {
444             logger.trace("Unlinked channel {}", channel.getUID());
445             return;
446         }
447         State channelState = null;
448         if (stateType == null && "NULL".equals(state)) {
449             channelState = UnDefType.NULL;
450         } else if (stateType == null && "UNDEF".equals(state)) {
451             channelState = UnDefType.UNDEF;
452         } else if ("UnDef".equals(stateType)) {
453             switch (state) {
454                 case "NULL":
455                     channelState = UnDefType.NULL;
456                     break;
457                 case "UNDEF":
458                     channelState = UnDefType.UNDEF;
459                     break;
460                 default:
461                     logger.debug("Invalid UnDef value {} for item {}", state, itemName);
462                     break;
463             }
464         } else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
465             // Item type Number with dimension
466             if (stateType == null || "Quantity".equals(stateType)) {
467                 List<Class<? extends State>> stateTypes = Collections.singletonList(QuantityType.class);
468                 channelState = TypeParser.parseState(stateTypes, state);
469             } else if ("Decimal".equals(stateType)) {
470                 channelState = new DecimalType(state);
471             } else {
472                 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
473             }
474         } else {
475             switch (acceptedItemType) {
476                 case CoreItemFactory.STRING:
477                     if (checkStateType(itemName, stateType, "String")) {
478                         channelState = new StringType(state);
479                     }
480                     break;
481                 case CoreItemFactory.NUMBER:
482                     if (checkStateType(itemName, stateType, "Decimal")) {
483                         channelState = new DecimalType(state);
484                     }
485                     break;
486                 case CoreItemFactory.SWITCH:
487                     if (checkStateType(itemName, stateType, "OnOff")) {
488                         channelState = "ON".equals(state) ? OnOffType.ON : OnOffType.OFF;
489                     }
490                     break;
491                 case CoreItemFactory.CONTACT:
492                     if (checkStateType(itemName, stateType, "OpenClosed")) {
493                         channelState = "OPEN".equals(state) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
494                     }
495                     break;
496                 case CoreItemFactory.DIMMER:
497                     if (checkStateType(itemName, stateType, "Percent")) {
498                         channelState = new PercentType(state);
499                     }
500                     break;
501                 case CoreItemFactory.COLOR:
502                     if (checkStateType(itemName, stateType, "HSB")) {
503                         channelState = HSBType.valueOf(state);
504                     }
505                     break;
506                 case CoreItemFactory.DATETIME:
507                     if (checkStateType(itemName, stateType, "DateTime")) {
508                         try {
509                             channelState = new DateTimeType(ZonedDateTime.parse(state, FORMATTER_DATE));
510                         } catch (DateTimeParseException e) {
511                             logger.debug("Failed to parse date {} for item {}", state, itemName);
512                             channelState = null;
513                         }
514                     }
515                     break;
516                 case CoreItemFactory.LOCATION:
517                     if (checkStateType(itemName, stateType, "Point")) {
518                         channelState = new PointType(state);
519                     }
520                     break;
521                 case CoreItemFactory.IMAGE:
522                     if (checkStateType(itemName, stateType, "Raw")) {
523                         channelState = RawType.valueOf(state);
524                     }
525                     break;
526                 case CoreItemFactory.PLAYER:
527                     if (checkStateType(itemName, stateType, "PlayPause")) {
528                         switch (state) {
529                             case "PLAY":
530                                 channelState = PlayPauseType.PLAY;
531                                 break;
532                             case "PAUSE":
533                                 channelState = PlayPauseType.PAUSE;
534                                 break;
535                             default:
536                                 logger.debug("Unexpected value {} for item {}", state, itemName);
537                                 break;
538                         }
539                     }
540                     break;
541                 case CoreItemFactory.ROLLERSHUTTER:
542                     if (checkStateType(itemName, stateType, "Percent")) {
543                         channelState = new PercentType(state);
544                     }
545                     break;
546                 default:
547                     logger.debug("Item type {} is not yet supported", acceptedItemType);
548                     break;
549             }
550         }
551         if (channelState != null) {
552             updateState(channel.getUID(), channelState);
553             String channelStateStr = channelState.toFullString();
554             logger.debug("updateState {} with {}", channel.getUID(),
555                     channelStateStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? channelStateStr
556                             : channelStateStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...");
557         }
558     }
559
560     private boolean checkStateType(String itemName, @Nullable String stateType, String expectedType) {
561         if (stateType != null && !expectedType.equals(stateType)) {
562             logger.debug("Unexpected value type {} for item {}", stateType, itemName);
563             return false;
564         } else {
565             return true;
566         }
567     }
568
569     @Override
570     public Collection<Class<? extends ThingHandlerService>> getServices() {
571         return Collections.singleton(RemoteopenhabDiscoveryService.class);
572     }
573 }