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.remoteopenhab.internal.handler;
15 import java.net.MalformedURLException;
17 import java.time.DateTimeException;
18 import java.time.ZonedDateTime;
19 import java.time.format.DateTimeFormatter;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
29 import javax.ws.rs.client.ClientBuilder;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.openhab.binding.remoteopenhab.internal.RemoteopenhabChannelTypeProvider;
35 import org.openhab.binding.remoteopenhab.internal.RemoteopenhabStateDescriptionOptionProvider;
36 import org.openhab.binding.remoteopenhab.internal.config.RemoteopenhabServerConfiguration;
37 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabItem;
38 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateDescription;
39 import org.openhab.binding.remoteopenhab.internal.data.RemoteopenhabStateOption;
40 import org.openhab.binding.remoteopenhab.internal.discovery.RemoteopenhabDiscoveryService;
41 import org.openhab.binding.remoteopenhab.internal.exceptions.RemoteopenhabException;
42 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabItemsDataListener;
43 import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabStreamingDataListener;
44 import org.openhab.binding.remoteopenhab.internal.rest.RemoteopenhabRestClient;
45 import org.openhab.core.library.CoreItemFactory;
46 import org.openhab.core.library.types.DateTimeType;
47 import org.openhab.core.library.types.DecimalType;
48 import org.openhab.core.library.types.HSBType;
49 import org.openhab.core.library.types.OnOffType;
50 import org.openhab.core.library.types.OpenClosedType;
51 import org.openhab.core.library.types.PercentType;
52 import org.openhab.core.library.types.PlayPauseType;
53 import org.openhab.core.library.types.PointType;
54 import org.openhab.core.library.types.QuantityType;
55 import org.openhab.core.library.types.RawType;
56 import org.openhab.core.library.types.StringType;
57 import org.openhab.core.thing.Bridge;
58 import org.openhab.core.thing.Channel;
59 import org.openhab.core.thing.ChannelUID;
60 import org.openhab.core.thing.ThingStatus;
61 import org.openhab.core.thing.ThingStatusDetail;
62 import org.openhab.core.thing.binding.BaseBridgeHandler;
63 import org.openhab.core.thing.binding.ThingHandlerService;
64 import org.openhab.core.thing.binding.builder.ChannelBuilder;
65 import org.openhab.core.thing.binding.builder.ThingBuilder;
66 import org.openhab.core.thing.type.AutoUpdatePolicy;
67 import org.openhab.core.thing.type.ChannelKind;
68 import org.openhab.core.thing.type.ChannelType;
69 import org.openhab.core.thing.type.ChannelTypeBuilder;
70 import org.openhab.core.thing.type.ChannelTypeUID;
71 import org.openhab.core.types.Command;
72 import org.openhab.core.types.RefreshType;
73 import org.openhab.core.types.State;
74 import org.openhab.core.types.StateDescriptionFragmentBuilder;
75 import org.openhab.core.types.StateOption;
76 import org.openhab.core.types.TypeParser;
77 import org.openhab.core.types.UnDefType;
78 import org.osgi.service.jaxrs.client.SseEventSourceFactory;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
82 import com.google.gson.Gson;
85 * The {@link RemoteopenhabBridgeHandler} is responsible for handling commands and updating states
86 * using the REST API of the remote openHAB server.
88 * @author Laurent Garnier - Initial contribution
91 public class RemoteopenhabBridgeHandler extends BaseBridgeHandler
92 implements RemoteopenhabStreamingDataListener, RemoteopenhabItemsDataListener {
94 private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
95 private static final DateTimeFormatter FORMATTER_DATE = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN);
97 private static final int MAX_STATE_SIZE_FOR_LOGGING = 50;
99 private final Logger logger = LoggerFactory.getLogger(RemoteopenhabBridgeHandler.class);
101 private final HttpClient httpClientTrustingCert;
102 private final RemoteopenhabChannelTypeProvider channelTypeProvider;
103 private final RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider;
105 private final Object updateThingLock = new Object();
107 private @NonNullByDefault({}) RemoteopenhabServerConfiguration config;
109 private @Nullable ScheduledFuture<?> checkConnectionJob;
110 private RemoteopenhabRestClient restClient;
112 private Map<ChannelUID, State> channelsLastStates = new HashMap<>();
114 public RemoteopenhabBridgeHandler(Bridge bridge, HttpClient httpClient, HttpClient httpClientTrustingCert,
115 ClientBuilder clientBuilder, SseEventSourceFactory eventSourceFactory,
116 RemoteopenhabChannelTypeProvider channelTypeProvider,
117 RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider, final Gson jsonParser) {
119 this.httpClientTrustingCert = httpClientTrustingCert;
120 this.channelTypeProvider = channelTypeProvider;
121 this.stateDescriptionProvider = stateDescriptionProvider;
122 this.restClient = new RemoteopenhabRestClient(httpClient, clientBuilder, eventSourceFactory, jsonParser);
126 public void initialize() {
127 logger.debug("Initializing remote openHAB handler for bridge {}", getThing().getUID());
129 config = getConfigAs(RemoteopenhabServerConfiguration.class);
131 String host = config.host.trim();
132 if (host.length() == 0) {
133 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
134 "Undefined server address setting in the thing configuration");
137 String path = config.restPath.trim();
138 if (path.length() == 0 || !path.startsWith("/")) {
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
140 "Invalid REST API path setting in the thing configuration");
145 url = new URL(config.useHttps ? "https" : "http", host, config.port, path);
146 } catch (MalformedURLException e) {
147 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
148 "Invalid REST URL built from the settings in the thing configuration");
152 String urlStr = url.toString();
153 logger.debug("REST URL = {}", urlStr);
155 restClient.setRestUrl(urlStr);
156 restClient.setAuthenticationData(config.authenticateAnyway, config.token, config.username, config.password);
157 if (config.useHttps && config.trustedCertificate) {
158 restClient.setHttpClient(httpClientTrustingCert);
159 restClient.setTrustedCertificate(true);
162 updateStatus(ThingStatus.UNKNOWN);
164 scheduler.submit(() -> checkConnection(false));
165 if (config.accessibilityInterval > 0) {
166 startCheckConnectionJob(config.accessibilityInterval, config.aliveInterval, config.restartIfNoActivity);
171 public void dispose() {
172 logger.debug("Disposing remote openHAB handler for bridge {}", getThing().getUID());
173 stopStreamingUpdates(false);
174 stopCheckConnectionJob();
175 channelsLastStates.clear();
179 public void handleCommand(ChannelUID channelUID, Command command) {
180 if (getThing().getStatus() != ThingStatus.ONLINE) {
185 if (command instanceof RefreshType) {
186 String state = restClient.getRemoteItemState(channelUID.getId());
187 updateChannelState(channelUID.getId(), null, state, false);
188 } else if (isLinked(channelUID)) {
189 restClient.sendCommandToRemoteItem(channelUID.getId(), command);
190 String commandStr = command.toFullString();
191 logger.debug("Sending command {} to remote item {} succeeded",
192 commandStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? commandStr
193 : commandStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...",
196 } catch (RemoteopenhabException e) {
197 logger.debug("{}", e.getMessage());
201 private boolean createChannels(List<RemoteopenhabItem> items, boolean replace) {
202 synchronized (updateThingLock) {
205 int nbChannelTypesCreated = 0;
206 List<Channel> channels = new ArrayList<>();
207 for (RemoteopenhabItem item : items) {
208 String itemType = item.type;
209 boolean readOnly = false;
210 if ("Group".equals(itemType)) {
211 if (item.groupType.isEmpty()) {
212 // Standard groups are ignored
216 itemType = item.groupType;
219 if (item.stateDescription != null && item.stateDescription.readOnly) {
223 // Ignore pattern containing a transformation (detected by a parenthesis in the pattern)
224 RemoteopenhabStateDescription stateDescription = item.stateDescription;
225 String pattern = (stateDescription == null || stateDescription.pattern.contains("(")) ? ""
226 : stateDescription.pattern;
227 ChannelTypeUID channelTypeUID;
228 ChannelType channelType = channelTypeProvider.getChannelType(itemType, readOnly, pattern);
231 if (channelType == null) {
232 channelTypeUID = channelTypeProvider.buildNewChannelTypeUID(itemType);
233 logger.trace("Create the channel type {} for item type {} ({} and with pattern {})",
234 channelTypeUID, itemType, readOnly ? "read only" : "read write", pattern);
235 label = String.format("Remote %s Item", itemType);
236 description = String.format("An item of type %s from the remote server.", itemType);
237 StateDescriptionFragmentBuilder stateDescriptionBuilder = StateDescriptionFragmentBuilder
238 .create().withReadOnly(readOnly);
239 if (!pattern.isEmpty()) {
240 stateDescriptionBuilder = stateDescriptionBuilder.withPattern(pattern);
242 channelType = ChannelTypeBuilder.state(channelTypeUID, label, itemType)
243 .withDescription(description)
244 .withStateDescriptionFragment(stateDescriptionBuilder.build())
245 .withAutoUpdatePolicy(AutoUpdatePolicy.VETO).build();
246 channelTypeProvider.addChannelType(itemType, channelType);
247 nbChannelTypesCreated++;
249 channelTypeUID = channelType.getUID();
251 ChannelUID channelUID = new ChannelUID(getThing().getUID(), item.name);
252 logger.trace("Create the channel {} of type {}", channelUID, channelTypeUID);
253 label = "Item " + item.name;
254 description = String.format("Item %s from the remote server.", item.name);
255 channels.add(ChannelBuilder.create(channelUID, itemType).withType(channelTypeUID)
256 .withKind(ChannelKind.STATE).withLabel(label).withDescription(description).build());
258 ThingBuilder thingBuilder = editThing();
260 thingBuilder.withChannels(channels);
261 updateThing(thingBuilder.build());
263 "{} channels defined (with {} different channel types) for the thing {} (from {} items including {} groups)",
264 channels.size(), nbChannelTypesCreated, getThing().getUID(), items.size(), nbGroups);
265 } else if (!channels.isEmpty()) {
267 for (Channel channel : channels) {
268 if (getThing().getChannel(channel.getUID()) != null) {
269 thingBuilder.withoutChannel(channel.getUID());
274 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved,
275 getThing().getUID(), items.size());
277 for (Channel channel : channels) {
278 thingBuilder.withChannel(channel);
280 updateThing(thingBuilder.build());
282 logger.debug("{} channels added for the thing {} (from {} items including {} groups)",
283 channels.size(), getThing().getUID(), items.size(), nbGroups);
285 logger.debug("{} channels added for the thing {} (from {} items)", channels.size(),
286 getThing().getUID(), items.size());
290 } catch (IllegalArgumentException e) {
291 logger.warn("An error occurred while creating the channels for the server {}: {}", getThing().getUID(),
298 private void removeChannels(List<RemoteopenhabItem> items) {
299 synchronized (updateThingLock) {
301 ThingBuilder thingBuilder = editThing();
302 for (RemoteopenhabItem item : items) {
303 Channel channel = getThing().getChannel(item.name);
304 if (channel != null) {
305 thingBuilder.withoutChannel(channel.getUID());
310 updateThing(thingBuilder.build());
311 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
317 private void setStateOptions(List<RemoteopenhabItem> items) {
318 for (RemoteopenhabItem item : items) {
319 Channel channel = getThing().getChannel(item.name);
320 RemoteopenhabStateDescription descr = item.stateDescription;
321 List<RemoteopenhabStateOption> options = descr == null ? null : descr.options;
322 if (channel != null && options != null && !options.isEmpty()) {
323 List<StateOption> stateOptions = new ArrayList<>();
324 for (RemoteopenhabStateOption option : options) {
325 stateOptions.add(new StateOption(option.value, option.label));
327 stateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions);
328 logger.trace("{} options set for the channel {}", options.size(), channel.getUID());
333 public void checkConnection(boolean restartSse) {
334 logger.debug("Try the root REST API...");
337 if (restClient.getRestApiVersion() == null) {
338 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
339 "OH 1.x server not supported by the binding");
340 } else if (getThing().getStatus() != ThingStatus.ONLINE) {
341 List<RemoteopenhabItem> items = restClient.getRemoteItems("name,type,groupType,state,stateDescription");
343 if (createChannels(items, true)) {
344 setStateOptions(items);
345 for (RemoteopenhabItem item : items) {
346 updateChannelState(item.name, null, item.state, false);
349 updateStatus(ThingStatus.ONLINE);
351 restartStreamingUpdates();
353 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
354 "Dynamic creation of the channels for the remote server items failed");
355 stopStreamingUpdates();
357 } else if (restartSse) {
358 logger.debug("The SSE connection is restarted because there was no recent event received");
359 restartStreamingUpdates();
361 } catch (RemoteopenhabException e) {
362 logger.debug("{}", e.getMessage());
363 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
364 stopStreamingUpdates();
368 private void startCheckConnectionJob(int accessibilityInterval, int aliveInterval, boolean restartIfNoActivity) {
369 ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
370 if (localCheckConnectionJob == null || localCheckConnectionJob.isCancelled()) {
371 checkConnectionJob = scheduler.scheduleWithFixedDelay(() -> {
372 long millisSinceLastEvent = System.currentTimeMillis() - restClient.getLastEventTimestamp();
373 if (getThing().getStatus() != ThingStatus.ONLINE || aliveInterval == 0
374 || restClient.getLastEventTimestamp() == 0) {
375 logger.debug("Time to check server accessibility");
376 checkConnection(restartIfNoActivity && aliveInterval != 0);
377 } else if (millisSinceLastEvent > (aliveInterval * 60000)) {
379 "Time to check server accessibility (maybe disconnected from streaming events, millisSinceLastEvent={})",
380 millisSinceLastEvent);
381 checkConnection(restartIfNoActivity);
384 "Bypass server accessibility check (receiving streaming events, millisSinceLastEvent={})",
385 millisSinceLastEvent);
387 }, accessibilityInterval, accessibilityInterval, TimeUnit.MINUTES);
391 private void stopCheckConnectionJob() {
392 ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
393 if (localCheckConnectionJob != null) {
394 localCheckConnectionJob.cancel(true);
395 checkConnectionJob = null;
399 private void restartStreamingUpdates() {
400 synchronized (restClient) {
401 stopStreamingUpdates();
402 startStreamingUpdates();
406 private void startStreamingUpdates() {
407 synchronized (restClient) {
408 restClient.addStreamingDataListener(this);
409 restClient.addItemsDataListener(this);
414 private void stopStreamingUpdates() {
415 stopStreamingUpdates(true);
418 private void stopStreamingUpdates(boolean waitingForCompletion) {
419 synchronized (restClient) {
420 restClient.stop(waitingForCompletion);
421 restClient.removeStreamingDataListener(this);
422 restClient.removeItemsDataListener(this);
426 public RemoteopenhabRestClient gestRestClient() {
431 public void onConnected() {
432 updateStatus(ThingStatus.ONLINE);
436 public void onDisconnected() {
437 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Disconected from the remote server");
441 public void onError(String message) {
442 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
446 public void onItemStateEvent(String itemName, String stateType, String state, boolean onlyIfStateChanged) {
447 updateChannelState(itemName, stateType, state, onlyIfStateChanged);
451 public void onItemAdded(RemoteopenhabItem item) {
452 createChannels(List.of(item), false);
456 public void onItemRemoved(RemoteopenhabItem item) {
457 removeChannels(List.of(item));
461 public void onItemUpdated(RemoteopenhabItem newItem, RemoteopenhabItem oldItem) {
462 if (!newItem.type.equals(oldItem.type)) {
463 createChannels(List.of(newItem), false);
465 logger.trace("Updated remote item {} ignored because item type {} is unchanged", newItem.name,
470 private void updateChannelState(String itemName, @Nullable String stateType, String state,
471 boolean onlyIfStateChanged) {
472 Channel channel = getThing().getChannel(itemName);
473 if (channel == null) {
474 logger.trace("No channel for item {}", itemName);
477 String acceptedItemType = channel.getAcceptedItemType();
478 if (acceptedItemType == null) {
479 logger.trace("Channel without accepted item type for item {}", itemName);
482 if (!isLinked(channel.getUID())) {
483 logger.trace("Unlinked channel {}", channel.getUID());
486 State channelState = null;
488 if (stateType == null && "NULL".equals(state)) {
489 channelState = UnDefType.NULL;
490 } else if (stateType == null && "UNDEF".equals(state)) {
491 channelState = UnDefType.UNDEF;
492 } else if ("UnDef".equals(stateType)) {
495 channelState = UnDefType.NULL;
498 channelState = UnDefType.UNDEF;
501 logger.debug("Invalid UnDef value {} for item {}", state, itemName);
504 } else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
505 // Item type Number with dimension
506 if (stateType == null || "Quantity".equals(stateType)) {
507 List<Class<? extends State>> stateTypes = Collections.singletonList(QuantityType.class);
508 channelState = TypeParser.parseState(stateTypes, state);
509 } else if ("Decimal".equals(stateType)) {
510 channelState = new DecimalType(state);
512 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
515 switch (acceptedItemType) {
516 case CoreItemFactory.STRING:
517 if (checkStateType(itemName, stateType, "String")) {
518 channelState = new StringType(state);
521 case CoreItemFactory.NUMBER:
522 if (checkStateType(itemName, stateType, "Decimal")) {
523 channelState = new DecimalType(state);
526 case CoreItemFactory.SWITCH:
527 if (checkStateType(itemName, stateType, "OnOff")) {
528 channelState = "ON".equals(state) ? OnOffType.ON : OnOffType.OFF;
531 case CoreItemFactory.CONTACT:
532 if (checkStateType(itemName, stateType, "OpenClosed")) {
533 channelState = "OPEN".equals(state) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
536 case CoreItemFactory.DIMMER:
537 if (checkStateType(itemName, stateType, "Percent")) {
538 channelState = new PercentType(state);
541 case CoreItemFactory.COLOR:
542 if (checkStateType(itemName, stateType, "HSB")) {
543 channelState = HSBType.valueOf(state);
546 case CoreItemFactory.DATETIME:
547 if (checkStateType(itemName, stateType, "DateTime")) {
548 channelState = new DateTimeType(ZonedDateTime.parse(state, FORMATTER_DATE));
551 case CoreItemFactory.LOCATION:
552 if (checkStateType(itemName, stateType, "Point")) {
553 channelState = new PointType(state);
556 case CoreItemFactory.IMAGE:
557 if (checkStateType(itemName, stateType, "Raw")) {
558 channelState = RawType.valueOf(state);
561 case CoreItemFactory.PLAYER:
562 if (checkStateType(itemName, stateType, "PlayPause")) {
565 channelState = PlayPauseType.PLAY;
568 channelState = PlayPauseType.PAUSE;
571 logger.debug("Unexpected value {} for item {}", state, itemName);
576 case CoreItemFactory.ROLLERSHUTTER:
577 if (checkStateType(itemName, stateType, "Percent")) {
578 channelState = new PercentType(state);
582 logger.debug("Item type {} is not yet supported", acceptedItemType);
586 } catch (IllegalArgumentException | DateTimeException e) {
587 logger.warn("Failed to parse state \"{}\" for item {}: {}", state, itemName, e.getMessage());
588 channelState = UnDefType.UNDEF;
590 if (channelState != null) {
591 if (onlyIfStateChanged && channelState.equals(channelsLastStates.get(channel.getUID()))) {
592 logger.trace("ItemStateChangedEvent ignored for item {} as state is identical to the last state",
596 channelsLastStates.put(channel.getUID(), channelState);
597 updateState(channel.getUID(), channelState);
598 String channelStateStr = channelState.toFullString();
599 logger.debug("updateState {} with {}", channel.getUID(),
600 channelStateStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? channelStateStr
601 : channelStateStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...");
605 private boolean checkStateType(String itemName, @Nullable String stateType, String expectedType) {
606 if (stateType != null && !expectedType.equals(stateType)) {
607 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
615 public Collection<Class<? extends ThingHandlerService>> getServices() {
616 return Collections.singleton(RemoteopenhabDiscoveryService.class);