]> git.basschouten.com Git - openhab-addons.git/blob
a47f233d040cebb432f5e4ba6ad217c69f5cd457
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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 java.net.MalformedURLException;
16 import java.net.URL;
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;
25 import java.util.Map;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28
29 import javax.ws.rs.client.ClientBuilder;
30
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;
81
82 import com.google.gson.Gson;
83
84 /**
85  * The {@link RemoteopenhabBridgeHandler} is responsible for handling commands and updating states
86  * using the REST API of the remote openHAB server.
87  *
88  * @author Laurent Garnier - Initial contribution
89  */
90 @NonNullByDefault
91 public class RemoteopenhabBridgeHandler extends BaseBridgeHandler
92         implements RemoteopenhabStreamingDataListener, RemoteopenhabItemsDataListener {
93
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);
96
97     private static final int MAX_STATE_SIZE_FOR_LOGGING = 50;
98
99     private final Logger logger = LoggerFactory.getLogger(RemoteopenhabBridgeHandler.class);
100
101     private final HttpClient httpClientTrustingCert;
102     private final RemoteopenhabChannelTypeProvider channelTypeProvider;
103     private final RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider;
104
105     private final Object updateThingLock = new Object();
106
107     private @NonNullByDefault({}) RemoteopenhabServerConfiguration config;
108
109     private @Nullable ScheduledFuture<?> checkConnectionJob;
110     private RemoteopenhabRestClient restClient;
111
112     private Map<ChannelUID, State> channelsLastStates = new HashMap<>();
113
114     public RemoteopenhabBridgeHandler(Bridge bridge, HttpClient httpClient, HttpClient httpClientTrustingCert,
115             ClientBuilder clientBuilder, SseEventSourceFactory eventSourceFactory,
116             RemoteopenhabChannelTypeProvider channelTypeProvider,
117             RemoteopenhabStateDescriptionOptionProvider stateDescriptionProvider, final Gson jsonParser) {
118         super(bridge);
119         this.httpClientTrustingCert = httpClientTrustingCert;
120         this.channelTypeProvider = channelTypeProvider;
121         this.stateDescriptionProvider = stateDescriptionProvider;
122         this.restClient = new RemoteopenhabRestClient(httpClient, clientBuilder, eventSourceFactory, jsonParser);
123     }
124
125     @Override
126     public void initialize() {
127         logger.debug("Initializing remote openHAB handler for bridge {}", getThing().getUID());
128
129         config = getConfigAs(RemoteopenhabServerConfiguration.class);
130
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");
135             return;
136         }
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");
141             return;
142         }
143         URL url;
144         try {
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");
149             return;
150         }
151
152         String urlStr = url.toString();
153         logger.debug("REST URL = {}", urlStr);
154
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);
160         }
161
162         updateStatus(ThingStatus.UNKNOWN);
163
164         scheduler.submit(() -> checkConnection(false));
165         if (config.accessibilityInterval > 0) {
166             startCheckConnectionJob(config.accessibilityInterval, config.aliveInterval, config.restartIfNoActivity);
167         }
168     }
169
170     @Override
171     public void dispose() {
172         logger.debug("Disposing remote openHAB handler for bridge {}", getThing().getUID());
173         stopStreamingUpdates(false);
174         stopCheckConnectionJob();
175         channelsLastStates.clear();
176     }
177
178     @Override
179     public void handleCommand(ChannelUID channelUID, Command command) {
180         if (getThing().getStatus() != ThingStatus.ONLINE) {
181             return;
182         }
183
184         try {
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) + "...",
194                         channelUID.getId());
195             }
196         } catch (RemoteopenhabException e) {
197             logger.debug("{}", e.getMessage());
198         }
199     }
200
201     private boolean createChannels(List<RemoteopenhabItem> items, boolean replace) {
202         synchronized (updateThingLock) {
203             try {
204                 int nbGroups = 0;
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
213                             nbGroups++;
214                             continue;
215                         } else {
216                             itemType = item.groupType;
217                         }
218                     } else {
219                         if (item.stateDescription != null && item.stateDescription.readOnly) {
220                             readOnly = true;
221                         }
222                     }
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);
229                     String label;
230                     String description;
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);
241                         }
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++;
248                     } else {
249                         channelTypeUID = channelType.getUID();
250                     }
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());
257                 }
258                 ThingBuilder thingBuilder = editThing();
259                 if (replace) {
260                     thingBuilder.withChannels(channels);
261                     updateThing(thingBuilder.build());
262                     logger.debug(
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()) {
266                     int nbRemoved = 0;
267                     for (Channel channel : channels) {
268                         if (getThing().getChannel(channel.getUID()) != null) {
269                             thingBuilder.withoutChannel(channel.getUID());
270                             nbRemoved++;
271                         }
272                     }
273                     if (nbRemoved > 0) {
274                         logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved,
275                                 getThing().getUID(), items.size());
276                     }
277                     for (Channel channel : channels) {
278                         thingBuilder.withChannel(channel);
279                     }
280                     updateThing(thingBuilder.build());
281                     if (nbGroups > 0) {
282                         logger.debug("{} channels added for the thing {} (from {} items including {} groups)",
283                                 channels.size(), getThing().getUID(), items.size(), nbGroups);
284                     } else {
285                         logger.debug("{} channels added for the thing {} (from {} items)", channels.size(),
286                                 getThing().getUID(), items.size());
287                     }
288                 }
289                 return true;
290             } catch (IllegalArgumentException e) {
291                 logger.warn("An error occurred while creating the channels for the server {}: {}", getThing().getUID(),
292                         e.getMessage());
293                 return false;
294             }
295         }
296     }
297
298     private void removeChannels(List<RemoteopenhabItem> items) {
299         synchronized (updateThingLock) {
300             int nbRemoved = 0;
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());
306                     nbRemoved++;
307                 }
308             }
309             if (nbRemoved > 0) {
310                 updateThing(thingBuilder.build());
311                 logger.debug("{} channels removed for the thing {} (from {} items)", nbRemoved, getThing().getUID(),
312                         items.size());
313             }
314         }
315     }
316
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));
326                 }
327                 stateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions);
328                 logger.trace("{} options set for the channel {}", options.size(), channel.getUID());
329             }
330         }
331     }
332
333     public void checkConnection(boolean restartSse) {
334         logger.debug("Try the root REST API...");
335         try {
336             restClient.tryApi();
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");
342
343                 if (createChannels(items, true)) {
344                     setStateOptions(items);
345                     for (RemoteopenhabItem item : items) {
346                         updateChannelState(item.name, null, item.state, false);
347                     }
348
349                     updateStatus(ThingStatus.ONLINE);
350
351                     restartStreamingUpdates();
352                 } else {
353                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
354                             "Dynamic creation of the channels for the remote server items failed");
355                     stopStreamingUpdates();
356                 }
357             } else if (restartSse) {
358                 logger.debug("The SSE connection is restarted because there was no recent event received");
359                 restartStreamingUpdates();
360             }
361         } catch (RemoteopenhabException e) {
362             logger.debug("{}", e.getMessage());
363             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
364             stopStreamingUpdates();
365         }
366     }
367
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)) {
378                     logger.debug(
379                             "Time to check server accessibility (maybe disconnected from streaming events, millisSinceLastEvent={})",
380                             millisSinceLastEvent);
381                     checkConnection(restartIfNoActivity);
382                 } else {
383                     logger.debug(
384                             "Bypass server accessibility check (receiving streaming events, millisSinceLastEvent={})",
385                             millisSinceLastEvent);
386                 }
387             }, accessibilityInterval, accessibilityInterval, TimeUnit.MINUTES);
388         }
389     }
390
391     private void stopCheckConnectionJob() {
392         ScheduledFuture<?> localCheckConnectionJob = checkConnectionJob;
393         if (localCheckConnectionJob != null) {
394             localCheckConnectionJob.cancel(true);
395             checkConnectionJob = null;
396         }
397     }
398
399     private void restartStreamingUpdates() {
400         synchronized (restClient) {
401             stopStreamingUpdates();
402             startStreamingUpdates();
403         }
404     }
405
406     private void startStreamingUpdates() {
407         synchronized (restClient) {
408             restClient.addStreamingDataListener(this);
409             restClient.addItemsDataListener(this);
410             restClient.start();
411         }
412     }
413
414     private void stopStreamingUpdates() {
415         stopStreamingUpdates(true);
416     }
417
418     private void stopStreamingUpdates(boolean waitingForCompletion) {
419         synchronized (restClient) {
420             restClient.stop(waitingForCompletion);
421             restClient.removeStreamingDataListener(this);
422             restClient.removeItemsDataListener(this);
423         }
424     }
425
426     public RemoteopenhabRestClient gestRestClient() {
427         return restClient;
428     }
429
430     @Override
431     public void onConnected() {
432         updateStatus(ThingStatus.ONLINE);
433     }
434
435     @Override
436     public void onDisconnected() {
437         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Disconected from the remote server");
438     }
439
440     @Override
441     public void onError(String message) {
442         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
443     }
444
445     @Override
446     public void onItemStateEvent(String itemName, String stateType, String state, boolean onlyIfStateChanged) {
447         updateChannelState(itemName, stateType, state, onlyIfStateChanged);
448     }
449
450     @Override
451     public void onItemAdded(RemoteopenhabItem item) {
452         createChannels(List.of(item), false);
453     }
454
455     @Override
456     public void onItemRemoved(RemoteopenhabItem item) {
457         removeChannels(List.of(item));
458     }
459
460     @Override
461     public void onItemUpdated(RemoteopenhabItem newItem, RemoteopenhabItem oldItem) {
462         if (!newItem.type.equals(oldItem.type)) {
463             createChannels(List.of(newItem), false);
464         } else {
465             logger.trace("Updated remote item {} ignored because item type {} is unchanged", newItem.name,
466                     newItem.type);
467         }
468     }
469
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);
475             return;
476         }
477         String acceptedItemType = channel.getAcceptedItemType();
478         if (acceptedItemType == null) {
479             logger.trace("Channel without accepted item type for item {}", itemName);
480             return;
481         }
482         if (!isLinked(channel.getUID())) {
483             logger.trace("Unlinked channel {}", channel.getUID());
484             return;
485         }
486         State channelState = null;
487         try {
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)) {
493                 switch (state) {
494                     case "NULL":
495                         channelState = UnDefType.NULL;
496                         break;
497                     case "UNDEF":
498                         channelState = UnDefType.UNDEF;
499                         break;
500                     default:
501                         logger.debug("Invalid UnDef value {} for item {}", state, itemName);
502                         break;
503                 }
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);
511                 } else {
512                     logger.debug("Unexpected value type {} for item {}", stateType, itemName);
513                 }
514             } else {
515                 switch (acceptedItemType) {
516                     case CoreItemFactory.STRING:
517                         if (checkStateType(itemName, stateType, "String")) {
518                             channelState = new StringType(state);
519                         }
520                         break;
521                     case CoreItemFactory.NUMBER:
522                         if (checkStateType(itemName, stateType, "Decimal")) {
523                             channelState = new DecimalType(state);
524                         }
525                         break;
526                     case CoreItemFactory.SWITCH:
527                         if (checkStateType(itemName, stateType, "OnOff")) {
528                             channelState = "ON".equals(state) ? OnOffType.ON : OnOffType.OFF;
529                         }
530                         break;
531                     case CoreItemFactory.CONTACT:
532                         if (checkStateType(itemName, stateType, "OpenClosed")) {
533                             channelState = "OPEN".equals(state) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
534                         }
535                         break;
536                     case CoreItemFactory.DIMMER:
537                         if (checkStateType(itemName, stateType, "Percent")) {
538                             channelState = new PercentType(state);
539                         }
540                         break;
541                     case CoreItemFactory.COLOR:
542                         if (checkStateType(itemName, stateType, "HSB")) {
543                             channelState = HSBType.valueOf(state);
544                         }
545                         break;
546                     case CoreItemFactory.DATETIME:
547                         if (checkStateType(itemName, stateType, "DateTime")) {
548                             channelState = new DateTimeType(ZonedDateTime.parse(state, FORMATTER_DATE));
549                         }
550                         break;
551                     case CoreItemFactory.LOCATION:
552                         if (checkStateType(itemName, stateType, "Point")) {
553                             channelState = new PointType(state);
554                         }
555                         break;
556                     case CoreItemFactory.IMAGE:
557                         if (checkStateType(itemName, stateType, "Raw")) {
558                             channelState = RawType.valueOf(state);
559                         }
560                         break;
561                     case CoreItemFactory.PLAYER:
562                         if (checkStateType(itemName, stateType, "PlayPause")) {
563                             switch (state) {
564                                 case "PLAY":
565                                     channelState = PlayPauseType.PLAY;
566                                     break;
567                                 case "PAUSE":
568                                     channelState = PlayPauseType.PAUSE;
569                                     break;
570                                 default:
571                                     logger.debug("Unexpected value {} for item {}", state, itemName);
572                                     break;
573                             }
574                         }
575                         break;
576                     case CoreItemFactory.ROLLERSHUTTER:
577                         if (checkStateType(itemName, stateType, "Percent")) {
578                             channelState = new PercentType(state);
579                         }
580                         break;
581                     default:
582                         logger.debug("Item type {} is not yet supported", acceptedItemType);
583                         break;
584                 }
585             }
586         } catch (IllegalArgumentException | DateTimeException e) {
587             logger.warn("Failed to parse state \"{}\" for item {}: {}", state, itemName, e.getMessage());
588             channelState = UnDefType.UNDEF;
589         }
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",
593                         itemName);
594                 return;
595             }
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) + "...");
602         }
603     }
604
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);
608             return false;
609         } else {
610             return true;
611         }
612     }
613
614     @Override
615     public Collection<Class<? extends ThingHandlerService>> getServices() {
616         return Collections.singleton(RemoteopenhabDiscoveryService.class);
617     }
618 }