2 * Copyright (c) 2010-2020 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 static org.openhab.binding.remoteopenhab.internal.RemoteopenhabBindingConstants.BINDING_ID;
17 import java.net.MalformedURLException;
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;
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 long CONNECTION_TIMEOUT_MILLIS = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES);
100 private static final int MAX_STATE_SIZE_FOR_LOGGING = 50;
102 private final Logger logger = LoggerFactory.getLogger(RemoteopenhabBridgeHandler.class);
104 private final HttpClient httpClientTrustingCert;
105 private final RemoteopenhabChannelTypeProvider channelTypeProvider;
106 private final RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider;
108 private final Object updateThingLock = new Object();
110 private @NonNullByDefault({}) RemoteopenhabServerConfiguration config;
112 private @Nullable ScheduledFuture<?> checkConnectionJob;
113 private RemoteopenhabRestClient restClient;
115 public RemoteopenhabBridgeHandler(Bridge bridge, HttpClient httpClient, HttpClient httpClientTrustingCert,
116 ClientBuilder clientBuilder, SseEventSourceFactory eventSourceFactory,
117 RemoteopenhabChannelTypeProvider channelTypeProvider,
118 RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider, final Gson jsonParser) {
120 this.httpClientTrustingCert = httpClientTrustingCert;
121 this.channelTypeProvider = channelTypeProvider;
122 this.stateDescriptionProvider = stateDescriptionProvider;
123 this.restClient = new RemoteopenhabRestClient(httpClient, clientBuilder, eventSourceFactory, jsonParser);
127 public void initialize() {
128 logger.debug("Initializing remote openHAB handler for bridge {}", getThing().getUID());
130 config = getConfigAs(RemoteopenhabServerConfiguration.class);
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");
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");
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");
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");
161 String urlStr = url.toString();
162 if (urlStr.endsWith("/")) {
163 urlStr = urlStr.substring(0, urlStr.length() - 1);
165 logger.debug("REST URL = {}", urlStr);
167 restClient.setRestUrl(urlStr);
168 restClient.setAccessToken(config.token);
169 if (config.useHttps && config.trustedCertificate) {
170 restClient.setHttpClient(httpClientTrustingCert);
171 restClient.setTrustedCertificate(true);
174 updateStatus(ThingStatus.UNKNOWN);
176 startCheckConnectionJob();
180 public void dispose() {
181 logger.debug("Disposing remote openHAB handler for bridge {}", getThing().getUID());
182 stopStreamingUpdates();
183 stopCheckConnectionJob();
187 public void handleCommand(ChannelUID channelUID, Command command) {
188 if (getThing().getStatus() != ThingStatus.ONLINE) {
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) + "...",
204 } catch (RemoteopenhabException e) {
205 logger.debug("{}", e.getMessage());
209 private void createChannels(List<RemoteopenhabItem> items, boolean replace) {
210 synchronized (updateThingLock) {
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
222 itemType = item.groupType;
225 if (item.stateDescription != null && item.stateDescription.readOnly) {
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);
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);
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());
251 ThingBuilder thingBuilder = editThing();
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) {
259 for (Channel channel : channels) {
260 if (getThing().getChannel(channel.getUID()) != null) {
261 thingBuilder.withoutChannel(channel.getUID());
266 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
269 for (Channel channel : channels) {
270 thingBuilder.withChannel(channel);
272 updateThing(thingBuilder.build());
274 logger.debug("{} channels added for the thing {} (from {} items including {} groups)",
275 channels.size(), getThing().getUID(), items.size(), nbGroups);
277 logger.debug("{} channels added for the thing {} (from {} items)", channels.size(),
278 getThing().getUID(), items.size());
284 private void removeChannels(List<RemoteopenhabItem> items) {
285 synchronized (updateThingLock) {
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());
296 updateThing(thingBuilder.build());
297 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
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));
313 stateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions);
314 logger.trace("{} options set for the channel {}", options.size(), channel.getUID());
319 public void checkConnection() {
320 logger.debug("Try the root REST API...");
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();
329 createChannels(items, true);
330 setStateOptions(items);
331 for (RemoteopenhabItem item : items) {
332 updateChannelState(item.name, null, item.state);
335 updateStatus(ThingStatus.ONLINE);
337 restartStreamingUpdates();
339 } catch (RemoteopenhabException e) {
340 logger.debug("{}", e.getMessage());
341 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
342 stopStreamingUpdates();
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);
356 logger.debug("Check: Receiving streaming events, millisSinceLastEvent={}", millisSinceLastEvent);
358 }, 0, CONNECTION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
362 private void stopCheckConnectionJob() {
363 ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
364 if (localCheckConnectionJob != null) {
365 localCheckConnectionJob.cancel(true);
366 checkConnectionJob = null;
370 private void restartStreamingUpdates() {
371 synchronized (restClient) {
372 stopStreamingUpdates();
373 startStreamingUpdates();
377 private void startStreamingUpdates() {
378 synchronized (restClient) {
379 restClient.addStreamingDataListener(this);
380 restClient.addItemsDataListener(this);
385 private void stopStreamingUpdates() {
386 synchronized (restClient) {
388 restClient.removeStreamingDataListener(this);
389 restClient.removeItemsDataListener(this);
393 public RemoteopenhabRestClient gestRestClient() {
398 public void onConnected() {
399 updateStatus(ThingStatus.ONLINE);
403 public void onError(String message) {
404 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
408 public void onItemStateEvent(String itemName, String stateType, String state) {
409 updateChannelState(itemName, stateType, state);
413 public void onItemAdded(RemoteopenhabItem item) {
414 createChannels(List.of(item), false);
418 public void onItemRemoved(RemoteopenhabItem item) {
419 removeChannels(List.of(item));
423 public void onItemUpdated(RemoteopenhabItem newItem, RemoteopenhabItem oldItem) {
424 if (!newItem.type.equals(oldItem.type)) {
425 createChannels(List.of(newItem), false);
427 logger.trace("Updated remote item {} ignored because item type {} is unchanged", newItem.name,
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);
438 String acceptedItemType = channel.getAcceptedItemType();
439 if (acceptedItemType == null) {
440 logger.trace("Channel without accepted item type for item {}", itemName);
443 if (!isLinked(channel.getUID())) {
444 logger.trace("Unlinked channel {}", channel.getUID());
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)) {
455 channelState = UnDefType.NULL;
458 channelState = UnDefType.UNDEF;
461 logger.debug("Invalid UnDef value {} for item {}", state, itemName);
464 } else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
465 // Item type Number with dimension
466 if (checkStateType(itemName, stateType, "Quantity")) {
467 List<Class<? extends State>> stateTypes = Collections.singletonList(QuantityType.class);
468 channelState = TypeParser.parseState(stateTypes, state);
471 switch (acceptedItemType) {
472 case CoreItemFactory.STRING:
473 if (checkStateType(itemName, stateType, "String")) {
474 channelState = new StringType(state);
477 case CoreItemFactory.NUMBER:
478 if (checkStateType(itemName, stateType, "Decimal")) {
479 channelState = new DecimalType(state);
482 case CoreItemFactory.SWITCH:
483 if (checkStateType(itemName, stateType, "OnOff")) {
484 channelState = "ON".equals(state) ? OnOffType.ON : OnOffType.OFF;
487 case CoreItemFactory.CONTACT:
488 if (checkStateType(itemName, stateType, "OpenClosed")) {
489 channelState = "OPEN".equals(state) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
492 case CoreItemFactory.DIMMER:
493 if (checkStateType(itemName, stateType, "Percent")) {
494 channelState = new PercentType(state);
497 case CoreItemFactory.COLOR:
498 if (checkStateType(itemName, stateType, "HSB")) {
499 channelState = HSBType.valueOf(state);
502 case CoreItemFactory.DATETIME:
503 if (checkStateType(itemName, stateType, "DateTime")) {
505 channelState = new DateTimeType(ZonedDateTime.parse(state, FORMATTER_DATE));
506 } catch (DateTimeParseException e) {
507 logger.debug("Failed to parse date {} for item {}", state, itemName);
512 case CoreItemFactory.LOCATION:
513 if (checkStateType(itemName, stateType, "Point")) {
514 channelState = new PointType(state);
517 case CoreItemFactory.IMAGE:
518 if (checkStateType(itemName, stateType, "Raw")) {
519 channelState = RawType.valueOf(state);
522 case CoreItemFactory.PLAYER:
523 if (checkStateType(itemName, stateType, "PlayPause")) {
526 channelState = PlayPauseType.PLAY;
529 channelState = PlayPauseType.PAUSE;
532 logger.debug("Unexpected value {} for item {}", state, itemName);
537 case CoreItemFactory.ROLLERSHUTTER:
538 if (checkStateType(itemName, stateType, "Percent")) {
539 channelState = new PercentType(state);
543 logger.debug("Item type {} is not yet supported", acceptedItemType);
547 if (channelState != null) {
548 updateState(channel.getUID(), channelState);
549 String channelStateStr = channelState.toFullString();
550 logger.debug("updateState {} with {}", channel.getUID(),
551 channelStateStr.length() < MAX_STATE_SIZE_FOR_LOGGING ? channelStateStr
552 : channelStateStr.substring(0, MAX_STATE_SIZE_FOR_LOGGING) + "...");
556 private boolean checkStateType(String itemName, @Nullable String stateType, String expectedType) {
557 if (stateType != null && !expectedType.equals(stateType)) {
558 logger.debug("Unexpected value type {} for item {}", stateType, itemName);
566 public Collection<Class<? extends ThingHandlerService>> getServices() {
567 return Collections.singleton(RemoteopenhabDiscoveryService.class);