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;
28 import java.util.stream.Collectors;
30 import javax.ws.rs.client.ClientBuilder;
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;
84 import com.google.gson.Gson;
87 * The {@link RemoteopenhabBridgeHandler} is responsible for handling commands and updating states
88 * using the REST API of the remote openHAB server.
90 * @author Laurent Garnier - Initial contribution
93 public class RemoteopenhabBridgeHandler extends BaseBridgeHandler
94 implements RemoteopenhabStreamingDataListener, RemoteopenhabItemsDataListener {
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);
99 private static final int MAX_STATE_SIZE_FOR_LOGGING = 50;
101 private final Logger logger = LoggerFactory.getLogger(RemoteopenhabBridgeHandler.class);
103 private final HttpClient httpClientTrustingCert;
104 private final RemoteopenhabChannelTypeProvider channelTypeProvider;
105 private final RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider;
107 private final Object updateThingLock = new Object();
109 private @NonNullByDefault({}) RemoteopenhabServerConfiguration config;
111 private @Nullable ScheduledFuture<?> checkConnectionJob;
112 private RemoteopenhabRestClient restClient;
114 private Map<ChannelUID, State> channelsLastStates = new HashMap<>();
116 public RemoteopenhabBridgeHandler(Bridge bridge, HttpClient httpClient, HttpClient httpClientTrustingCert,
117 ClientBuilder clientBuilder, SseEventSourceFactory eventSourceFactory,
118 RemoteopenhabChannelTypeProvider channelTypeProvider,
119 RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider, final Gson jsonParser) {
121 this.httpClientTrustingCert = httpClientTrustingCert;
122 this.channelTypeProvider = channelTypeProvider;
123 this.stateDescriptionProvider = stateDescriptionProvider;
124 this.restClient = new RemoteopenhabRestClient(httpClient, clientBuilder, eventSourceFactory, jsonParser);
128 public void initialize() {
129 logger.debug("Initializing remote openHAB handler for bridge {}", getThing().getUID());
131 config = getConfigAs(RemoteopenhabServerConfiguration.class);
133 String host = config.host.trim();
134 if (host.length() == 0) {
135 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
136 "Undefined server address setting in the thing configuration");
139 List<String> localIpAddresses = NetUtil.getAllInterfaceAddresses().stream()
140 .filter(a -> !a.getAddress().isLinkLocalAddress())
141 .map(a -> a.getAddress().getHostAddress().split("%")[0]).collect(Collectors.toList());
142 if (localIpAddresses.contains(host)) {
143 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
144 "Do not use the local server as a remote server in the thing configuration");
147 String path = config.restPath.trim();
148 if (path.length() == 0 || !path.startsWith("/")) {
149 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
150 "Invalid REST API path setting in the thing configuration");
155 url = new URL(config.useHttps ? "https" : "http", host, config.port, path);
156 } catch (MalformedURLException e) {
157 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
158 "Invalid REST URL built from the settings in the thing configuration");
162 String urlStr = url.toString();
163 if (urlStr.endsWith("/")) {
164 urlStr = urlStr.substring(0, urlStr.length() - 1);
166 logger.debug("REST URL = {}", urlStr);
168 restClient.setRestUrl(urlStr);
169 restClient.setAccessToken(config.token);
170 if (config.useHttps && config.trustedCertificate) {
171 restClient.setHttpClient(httpClientTrustingCert);
172 restClient.setTrustedCertificate(true);
175 updateStatus(ThingStatus.UNKNOWN);
177 scheduler.submit(this::checkConnection);
178 if (config.accessibilityInterval > 0) {
179 startCheckConnectionJob(config.accessibilityInterval, config.aliveInterval);
184 public void dispose() {
185 logger.debug("Disposing remote openHAB handler for bridge {}", getThing().getUID());
186 stopStreamingUpdates(false);
187 stopCheckConnectionJob();
188 channelsLastStates.clear();
192 public void handleCommand(ChannelUID channelUID, Command command) {
193 if (getThing().getStatus() != ThingStatus.ONLINE) {
198 if (command instanceof RefreshType) {
199 String state = restClient.getRemoteItemState(channelUID.getId());
200 updateChannelState(channelUID.getId(), null, state, false);
201 } else if (isLinked(channelUID)) {
202 restClient.sendCommandToRemoteItem(channelUID.getId(), command);
203 String commandStr = command.toFullString();
204 logger.debug("Sending command {} to remote item {} succeeded",
205 commandStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? commandStr
206 : commandStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...",
209 } catch (RemoteopenhabException e) {
210 logger.debug("{}", e.getMessage());
214 private boolean createChannels(List<RemoteopenhabItem> items, boolean replace) {
215 synchronized (updateThingLock) {
218 int nbChannelTypesCreated = 0;
219 List<Channel> channels = new ArrayList<>();
220 for (RemoteopenhabItem item : items) {
221 String itemType = item.type;
222 boolean readOnly = false;
223 if ("Group".equals(itemType)) {
224 if (item.groupType.isEmpty()) {
225 // Standard groups are ignored
229 itemType = item.groupType;
232 if (item.stateDescription != null && item.stateDescription.readOnly) {
236 // Ignore pattern containing a transformation (detected by a parenthesis in the pattern)
237 RemoteopenhabStateDescription stateDescription = item.stateDescription;
238 String pattern = (stateDescription == null || stateDescription.pattern.contains("(")) ? ""
239 : stateDescription.pattern;
240 ChannelTypeUID channelTypeUID;
241 ChannelType channelType = channelTypeProvider.getChannelType(itemType, readOnly, pattern);
244 if (channelType == null) {
245 channelTypeUID = channelTypeProvider.buildNewChannelTypeUID(itemType);
246 logger.trace("Create the channel type {} for item type {} ({} and with pattern {})",
247 channelTypeUID, itemType, readOnly ? "read only" : "read write", pattern);
248 label = String.format("Remote %s Item", itemType);
249 description = String.format("An item of type %s from the remote server.", itemType);
250 StateDescriptionFragmentBuilder stateDescriptionBuilder = StateDescriptionFragmentBuilder
251 .create().withReadOnly(readOnly);
252 if (!pattern.isEmpty()) {
253 stateDescriptionBuilder = stateDescriptionBuilder.withPattern(pattern);
255 channelType = ChannelTypeBuilder.state(channelTypeUID, label, itemType)
256 .withDescription(description)
257 .withStateDescriptionFragment(stateDescriptionBuilder.build())
258 .withAutoUpdatePolicy(AutoUpdatePolicy.VETO).build();
259 channelTypeProvider.addChannelType(itemType, channelType);
260 nbChannelTypesCreated++;
262 channelTypeUID = channelType.getUID();
264 ChannelUID channelUID = new ChannelUID(getThing().getUID(), item.name);
265 logger.trace("Create the channel {} of type {}", channelUID, channelTypeUID);
266 label = "Item " + item.name;
267 description = String.format("Item %s from the remote server.", item.name);
268 channels.add(ChannelBuilder.create(channelUID, itemType).withType(channelTypeUID)
269 .withKind(ChannelKind.STATE).withLabel(label).withDescription(description).build());
271 ThingBuilder thingBuilder = editThing();
273 thingBuilder.withChannels(channels);
274 updateThing(thingBuilder.build());
276 "{} channels defined (with {} different channel types) for the thing {} (from {} items including {} groups)",
277 channels.size(), nbChannelTypesCreated, getThing().getUID(), items.size(), nbGroups);
278 } else if (channels.size() > 0) {
280 for (Channel channel : channels) {
281 if (getThing().getChannel(channel.getUID()) != null) {
282 thingBuilder.withoutChannel(channel.getUID());
287 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved,
288 getThing().getUID(), items.size());
290 for (Channel channel : channels) {
291 thingBuilder.withChannel(channel);
293 updateThing(thingBuilder.build());
295 logger.debug("{} channels added for the thing {} (from {} items including {} groups)",
296 channels.size(), getThing().getUID(), items.size(), nbGroups);
298 logger.debug("{} channels added for the thing {} (from {} items)", channels.size(),
299 getThing().getUID(), items.size());
303 } catch (IllegalArgumentException e) {
304 logger.warn("An error occurred while creating the channels for the server {}: {}", getThing().getUID(),
311 private void removeChannels(List<RemoteopenhabItem> items) {
312 synchronized (updateThingLock) {
314 ThingBuilder thingBuilder = editThing();
315 for (RemoteopenhabItem item : items) {
316 Channel channel = getThing().getChannel(item.name);
317 if (channel != null) {
318 thingBuilder.withoutChannel(channel.getUID());
323 updateThing(thingBuilder.build());
324 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
330 private void setStateOptions(List<RemoteopenhabItem> items) {
331 for (RemoteopenhabItem item : items) {
332 Channel channel = getThing().getChannel(item.name);
333 RemoteopenhabStateDescription descr = item.stateDescription;
334 List<RemoteopenhabStateOption> options = descr == null ? null : descr.options;
335 if (channel != null && options != null && options.size() > 0) {
336 List<StateOption> stateOptions = new ArrayList<>();
337 for (RemoteopenhabStateOption option : options) {
338 stateOptions.add(new StateOption(option.value, option.label));
340 stateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions);
341 logger.trace("{} options set for the channel {}", options.size(), channel.getUID());
346 public void checkConnection() {
347 logger.debug("Try the root REST API...");
350 if (restClient.getRestApiVersion() == null) {
351 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
352 "OH 1.x server not supported by the binding");
353 } else if (getThing().getStatus() != ThingStatus.ONLINE) {
354 List<RemoteopenhabItem> items = restClient.getRemoteItems("name,type,groupType,state,stateDescription");
356 if (createChannels(items, true)) {
357 setStateOptions(items);
358 for (RemoteopenhabItem item : items) {
359 updateChannelState(item.name, null, item.state, false);
362 updateStatus(ThingStatus.ONLINE);
364 restartStreamingUpdates();
366 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
367 "Dynamic creation of the channels for the remote server items failed");
368 stopStreamingUpdates();
371 } catch (RemoteopenhabException e) {
372 logger.debug("{}", e.getMessage());
373 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
374 stopStreamingUpdates();
378 private void startCheckConnectionJob(int accessibilityInterval, int aliveInterval) {
379 ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
380 if (localCheckConnectionJob == null || localCheckConnectionJob.isCancelled()) {
381 checkConnectionJob = scheduler.scheduleWithFixedDelay(() -> {
382 long millisSinceLastEvent = System.currentTimeMillis() - restClient.getLastEventTimestamp();
383 if (getThing().getStatus() != ThingStatus.ONLINE || aliveInterval == 0
384 || restClient.getLastEventTimestamp() == 0) {
385 logger.debug("Time to check server accessibility");
387 } else if (millisSinceLastEvent > (aliveInterval * 60000)) {
389 "Time to check server accessibility (maybe disconnected from streaming events, millisSinceLastEvent={})",
390 millisSinceLastEvent);
394 "Bypass server accessibility check (receiving streaming events, millisSinceLastEvent={})",
395 millisSinceLastEvent);
397 }, accessibilityInterval, accessibilityInterval, TimeUnit.MINUTES);
401 private void stopCheckConnectionJob() {
402 ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
403 if (localCheckConnectionJob != null) {
404 localCheckConnectionJob.cancel(true);
405 checkConnectionJob = null;
409 private void restartStreamingUpdates() {
410 synchronized (restClient) {
411 stopStreamingUpdates();
412 startStreamingUpdates();
416 private void startStreamingUpdates() {
417 synchronized (restClient) {
418 restClient.addStreamingDataListener(this);
419 restClient.addItemsDataListener(this);
424 private void stopStreamingUpdates() {
425 stopStreamingUpdates(true);
428 private void stopStreamingUpdates(boolean waitingForCompletion) {
429 synchronized (restClient) {
430 restClient.stop(waitingForCompletion);
431 restClient.removeStreamingDataListener(this);
432 restClient.removeItemsDataListener(this);
436 public RemoteopenhabRestClient gestRestClient() {
441 public void onConnected() {
442 updateStatus(ThingStatus.ONLINE);
446 public void onDisconnected() {
447 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Disconected from the remote server");
451 public void onError(String message) {
452 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
456 public void onItemStateEvent(String itemName, String stateType, String state, boolean onlyIfStateChanged) {
457 updateChannelState(itemName, stateType, state, onlyIfStateChanged);
461 public void onItemAdded(RemoteopenhabItem item) {
462 createChannels(List.of(item), false);
466 public void onItemRemoved(RemoteopenhabItem item) {
467 removeChannels(List.of(item));
471 public void onItemUpdated(RemoteopenhabItem newItem, RemoteopenhabItem oldItem) {
472 if (!newItem.type.equals(oldItem.type)) {
473 createChannels(List.of(newItem), false);
475 logger.trace("Updated remote item {} ignored because item type {} is unchanged", newItem.name,
480 private void updateChannelState(String itemName, @Nullable String stateType, String state,
481 boolean onlyIfStateChanged) {
482 Channel channel = getThing().getChannel(itemName);
483 if (channel == null) {
484 logger.trace("No channel for item {}", itemName);
487 String acceptedItemType = channel.getAcceptedItemType();
488 if (acceptedItemType == null) {
489 logger.trace("Channel without accepted item type for item {}", itemName);
492 if (!isLinked(channel.getUID())) {
493 logger.trace("Unlinked channel {}", channel.getUID());
496 State channelState = null;
498 if (stateType == null && "NULL".equals(state)) {
499 channelState = UnDefType.NULL;
500 } else if (stateType == null && "UNDEF".equals(state)) {
501 channelState = UnDefType.UNDEF;
502 } else if ("UnDef".equals(stateType)) {
505 channelState = UnDefType.NULL;
508 channelState = UnDefType.UNDEF;
511 logger.debug("Invalid UnDef value {} for item {}", state, itemName);
514 } else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
515 // Item type Number with dimension
516 if (stateType == null || "Quantity".equals(stateType)) {
517 List<Class<? extends State>> stateTypes = Collections.singletonList(QuantityType.class);
518 channelState = TypeParser.parseState(stateTypes, state);
519 } else if ("Decimal".equals(stateType)) {
520 channelState = new DecimalType(state);
522 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
525 switch (acceptedItemType) {
526 case CoreItemFactory.STRING:
527 if (checkStateType(itemName, stateType, "String")) {
528 channelState = new StringType(state);
531 case CoreItemFactory.NUMBER:
532 if (checkStateType(itemName, stateType, "Decimal")) {
533 channelState = new DecimalType(state);
536 case CoreItemFactory.SWITCH:
537 if (checkStateType(itemName, stateType, "OnOff")) {
538 channelState = "ON".equals(state) ? OnOffType.ON : OnOffType.OFF;
541 case CoreItemFactory.CONTACT:
542 if (checkStateType(itemName, stateType, "OpenClosed")) {
543 channelState = "OPEN".equals(state) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
546 case CoreItemFactory.DIMMER:
547 if (checkStateType(itemName, stateType, "Percent")) {
548 channelState = new PercentType(state);
551 case CoreItemFactory.COLOR:
552 if (checkStateType(itemName, stateType, "HSB")) {
553 channelState = HSBType.valueOf(state);
556 case CoreItemFactory.DATETIME:
557 if (checkStateType(itemName, stateType, "DateTime")) {
558 channelState = new DateTimeType(ZonedDateTime.parse(state, FORMATTER_DATE));
561 case CoreItemFactory.LOCATION:
562 if (checkStateType(itemName, stateType, "Point")) {
563 channelState = new PointType(state);
566 case CoreItemFactory.IMAGE:
567 if (checkStateType(itemName, stateType, "Raw")) {
568 channelState = RawType.valueOf(state);
571 case CoreItemFactory.PLAYER:
572 if (checkStateType(itemName, stateType, "PlayPause")) {
575 channelState = PlayPauseType.PLAY;
578 channelState = PlayPauseType.PAUSE;
581 logger.debug("Unexpected value {} for item {}", state, itemName);
586 case CoreItemFactory.ROLLERSHUTTER:
587 if (checkStateType(itemName, stateType, "Percent")) {
588 channelState = new PercentType(state);
592 logger.debug("Item type {} is not yet supported", acceptedItemType);
596 } catch (IllegalArgumentException | DateTimeException e) {
597 logger.warn("Failed to parse state \"{}\" for item {}: {}", state, itemName, e.getMessage());
598 channelState = UnDefType.UNDEF;
600 if (channelState != null) {
601 if (onlyIfStateChanged && channelState.equals(channelsLastStates.get(channel.getUID()))) {
602 logger.trace("ItemStateChangedEvent ignored for item {} as state is identical to the last state",
606 channelsLastStates.put(channel.getUID(), channelState);
607 updateState(channel.getUID(), channelState);
608 String channelStateStr = channelState.toFullString();
609 logger.debug("updateState {} with {}", channel.getUID(),
610 channelStateStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? channelStateStr
611 : channelStateStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...");
615 private boolean checkStateType(String itemName, @Nullable String stateType, String expectedType) {
616 if (stateType != null && !expectedType.equals(stateType)) {
617 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
625 public Collection<Class<? extends ThingHandlerService>> getServices() {
626 return Collections.singleton(RemoteopenhabDiscoveryService.class);