]> git.basschouten.com Git - openhab-addons.git/blob
4c8e0d3705051e92714f8b5e9c4f187c1b8f23ba
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.shelly.internal.handler;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
19 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
20 import static org.openhab.core.thing.Thing.*;
21
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.TreeMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.shelly.internal.api.ShellyApiException;
34 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
35 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
36 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
42 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
43 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
45 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
46 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
47 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
48 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
49 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
50 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
51 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
52 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
53 import org.openhab.core.library.types.DecimalType;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.OpenClosedType;
56 import org.openhab.core.library.types.QuantityType;
57 import org.openhab.core.thing.Channel;
58 import org.openhab.core.thing.ChannelUID;
59 import org.openhab.core.thing.Thing;
60 import org.openhab.core.thing.ThingStatus;
61 import org.openhab.core.thing.ThingStatusDetail;
62 import org.openhab.core.thing.ThingTypeUID;
63 import org.openhab.core.thing.binding.BaseThingHandler;
64 import org.openhab.core.thing.binding.builder.ThingBuilder;
65 import org.openhab.core.types.Command;
66 import org.openhab.core.types.RefreshType;
67 import org.openhab.core.types.State;
68 import org.openhab.core.types.UnDefType;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 /**
73  * The {@link ShellyBaseHandler} is responsible for handling commands, which are
74  * sent to one of the channels.
75  *
76  * @author Markus Michels - Initial contribution
77  */
78 @NonNullByDefault
79 public class ShellyBaseHandler extends BaseThingHandler
80         implements ShellyDeviceListener, ShellyManagerInterface, ShellyThingInterface {
81     protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
82     protected final ShellyChannelDefinitions channelDefinitions;
83
84     public String thingName = "";
85     public String thingType = "";
86
87     protected final ShellyApiInterface api;
88     private final HttpClient httpClient;
89
90     protected ShellyBindingConfiguration bindingConfig;
91     protected ShellyThingConfiguration config = new ShellyThingConfiguration();
92     protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
93     protected ShellyDeviceStats stats = new ShellyDeviceStats();
94     private final Shelly1CoapHandler coap;
95     public boolean autoCoIoT = false;
96
97     public final ShellyTranslationProvider messages;
98     protected boolean stopping = false;
99     private boolean channelsCreated = false;
100
101     private long watchdog = now();
102
103     private @Nullable ScheduledFuture<?> statusJob;
104     public int scheduledUpdates = 0;
105     private int skipCount = UPDATE_SKIP_COUNT;
106     private int skipUpdate = 0;
107     private boolean refreshSettings = false;
108
109     // delay before enabling channel
110     private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
111     protected final ShellyChannelCache cache;
112
113     private String localIP = "";
114     private String localPort = "";
115
116     private String lastWakeupReason = "";
117     private int vibrationFilter = 0;
118
119     /**
120      * Constructor
121      *
122      * @param thing The Thing object
123      * @param bindingConfig The binding configuration (beside thing
124      *            configuration)
125      * @param coapServer coap server instance
126      * @param localIP local IP address from networkAddressService
127      * @param httpPort from httpService
128      */
129     public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
130             final ShellyBindingConfiguration bindingConfig, final Shelly1CoapServer coapServer, final String localIP,
131             int httpPort, final HttpClient httpClient) {
132         super(thing);
133
134         this.thingName = getString(thing.getLabel());
135         this.messages = translationProvider;
136         this.cache = new ShellyChannelCache(this);
137         this.channelDefinitions = new ShellyChannelDefinitions(messages);
138         this.bindingConfig = bindingConfig;
139         this.config = getConfigAs(ShellyThingConfiguration.class);
140
141         this.httpClient = httpClient;
142         this.localIP = localIP;
143         this.localPort = String.valueOf(httpPort);
144         this.api = new Shelly1HttpApi(thingName, config, httpClient);
145
146         coap = new Shelly1CoapHandler(this, coapServer);
147     }
148
149     @Override
150     public boolean checkRepresentation(String key) {
151         return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
152                 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(thing.getUID().getAsString());
153     }
154
155     public String getUID() {
156         return getThing().getUID().getAsString();
157     }
158
159     /**
160      * Schedule asynchronous Thing initialization, register thing to event dispatcher
161      */
162     @Override
163     public void initialize() {
164         // start background initialization:
165         scheduler.schedule(() -> {
166             boolean start = true;
167             try {
168                 initializeThingConfig();
169                 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
170                         thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
171                         config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
172                 logger.debug(
173                         "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
174                         thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
175                         config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
176                 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
177                         messages.get("status.unknown.initializing"));
178                 start = initializeThing();
179             } catch (ShellyApiException e) {
180                 ShellyApiResult res = e.getApiResult();
181                 if (isAuthorizationFailed(res)) {
182                     start = false;
183                 }
184                 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
185             } catch (IllegalArgumentException e) {
186                 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
187             } finally {
188                 // even this initialization failed we start the status update
189                 // the updateJob will then try to auto-initialize the thing
190                 // in this case the thing stays in status INITIALIZING
191                 if (start) {
192                     startUpdateJob();
193                 }
194             }
195         }, 2, TimeUnit.SECONDS);
196     }
197
198     @Override
199     public ShellyThingConfiguration getThingConfig() {
200         return config;
201     }
202
203     @Override
204     public HttpClient getHttpClient() {
205         return httpClient;
206     }
207
208     /**
209      * This routine is called every time the Thing configuration has been changed
210      */
211     @Override
212     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
213         super.handleConfigurationUpdate(configurationParameters);
214         logger.debug("{}: Thing config updated, re-initialize", thingName);
215         coap.stop();
216         requestUpdates(1, true);// force re-initialization
217     }
218
219     /**
220      * Initialize Thing: Initialize API access, get settings and initialize Device Profile
221      * If the device is password protected and the credentials are missing or don't match the API access will throw an
222      * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
223      * thing config and set the correct credentials. The thing type will be changed to the requested one if the
224      * credentials are correct and the API access is initialized successful.
225      *
226      * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
227      */
228     private boolean initializeThing() throws ShellyApiException {
229         // Init from thing type to have a basic profile, gets updated when device info is received from API
230         stopping = false;
231         refreshSettings = false;
232         lastWakeupReason = "";
233         profile.initFromThingType(thingType);
234         api.setConfig(thingName, config);
235         cache.setThingName(thingName);
236         cache.clear();
237
238         logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
239                 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
240         if (config.deviceIp.isEmpty()) {
241             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
242             return false;
243         }
244
245         // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
246         // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
247         // when enabled)
248         if (config.eventsCoIoT && !profile.alwaysOn) {
249             coap.start(thingName, config);
250         }
251
252         // Initialize API access, exceptions will be catched by initialize()
253         ShellySettingsDevice devInfo = api.getDeviceInfo();
254         if (getBool(devInfo.auth) && config.userId.isEmpty()) {
255             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
256             return false;
257         }
258         if (config.serviceName.isEmpty()) {
259             config.serviceName = getString(profile.hostname).toLowerCase();
260         }
261
262         ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
263         if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
264             changeThingType(thingName, tmpPrf.mode);
265             return false; // force re-initialization
266         }
267         // Validate device mode
268         String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
269         if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
270             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
271             return false;
272         }
273         if (!getString(devInfo.coiot).isEmpty()) {
274             // New Shelly devices might use a different endpoint for the CoAP listener
275             tmpPrf.coiotEndpoint = devInfo.coiot;
276         }
277         tmpPrf.auth = devInfo.auth; // missing in /settings
278         tmpPrf.status = api.getStatus();
279         tmpPrf.updateFromStatus(tmpPrf.status);
280
281         showThingConfig(tmpPrf);
282         checkVersion(tmpPrf, tmpPrf.status);
283
284         if (config.eventsCoIoT && (tmpPrf.settings.coiot != null) && (tmpPrf.settings.coiot.enabled != null)) {
285             String devpeer = getString(tmpPrf.settings.coiot.peer);
286             String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
287             if (!tmpPrf.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
288                 try {
289                     api.setCoIoTPeer(ourpeer);
290                     logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
291                 } catch (ShellyApiException e) {
292                     logger.warn("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
293                 }
294             } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
295                 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
296             }
297         }
298         if (autoCoIoT) {
299             logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
300             config.eventsCoIoT = true;
301             config.eventsSwitch = false;
302             config.eventsButton = false;
303             config.eventsPush = false;
304             config.eventsRoller = false;
305             config.eventsSensorReport = false;
306             api.setConfig(thingName, config);
307         }
308
309         // All initialization done, so keep the profile and set Thing to ONLINE
310         fillDeviceStatus(tmpPrf.status, false);
311         postEvent(ALARM_TYPE_NONE, false);
312         api.setActionURLs(); // register event urls
313         if (config.eventsCoIoT) {
314             logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
315             coap.start(thingName, config);
316         }
317
318         logger.debug("{}: Thing successfully initialized.", thingName);
319         profile = tmpPrf;
320
321         updateProperties(tmpPrf, tmpPrf.status);
322         setThingOnline(); // if API call was successful the thing must be online
323         return true; // success
324     }
325
326     private void showThingConfig(ShellyDeviceProfile profile) {
327         logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
328                 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
329                 profile.fwDate);
330         logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
331         logger.debug("{}: Device "
332                 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
333                 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
334                 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
335                 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
336                 profile.isDW, profile.hasBattery,
337                 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
338                 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
339                 profile.alwaysOn, profile.updatePeriod);
340     }
341
342     /**
343      * Handle Channel Commands
344      */
345     @Override
346     public void handleCommand(ChannelUID channelUID, Command command) {
347         try {
348             if (command instanceof RefreshType) {
349                 String channelId = channelUID.getId();
350                 State value = cache.getValue(channelId);
351                 if (value != UnDefType.NULL) {
352                     updateState(channelId, value);
353                 }
354                 return;
355             }
356
357             if (!profile.isInitialized()) {
358                 logger.debug("{}: {}", thingName, messages.get("command.init", command));
359                 initializeThing();
360             } else {
361                 profile = getProfile(false);
362             }
363
364             boolean update = false;
365             switch (channelUID.getIdWithoutGroup()) {
366                 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
367                     logger.debug("{}: Send key {}", thingName, command);
368                     api.sendIRKey(command.toString());
369                     update = true;
370                     break;
371
372                 case CHANNEL_LED_STATUS_DISABLE:
373                     logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
374                     api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
375                     break;
376                 case CHANNEL_LED_POWER_DISABLE:
377                     logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
378                     api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
379                     break;
380
381                 case CHANNEL_SENSOR_SLEEPTIME:
382                     logger.debug("{}: Set sensor sleep time to {}", thingName, command);
383                     int value = (int) getNumber(command);
384                     value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
385                             : 0;
386                     api.setSleepTime(value);
387                     break;
388                 case CHANNEL_CONTROL_PROFILE:
389                     logger.debug("{}: Select profile {}", thingName, command);
390                     int profile = (int) getNumber(command);
391                     if (profile < 0 || profile > 5) {
392                         logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
393                         break;
394                     }
395                     api.setValveProfile(0, profile);
396                     break;
397                 case CHANNEL_CONTROL_MODE:
398                     logger.debug("{}: Set mode to {}", thingName, command);
399                     api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
400                     break;
401                 case CHANNEL_CONTROL_SETTEMP:
402                     logger.debug("{}: Set temperature to {}", thingName, command);
403                     api.setValveTemperature(0, (int) getNumber(command));
404                     break;
405                 case CHANNEL_CONTROL_POSITION:
406                     logger.debug("{}: Set position to {}", thingName, command);
407                     api.setValvePosition(0, getNumber(command));
408                     break;
409                 case CHANNEL_CONTROL_BCONTROL:
410                     logger.debug("{}: Set boost mode to {}", thingName, command);
411                     api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
412                     break;
413                 case CHANNEL_CONTROL_BTIMER:
414                     logger.debug("{}: Set boost timer to {}", thingName, command);
415                     api.setValveBoostTime(0, (int) getNumber(command));
416                     break;
417
418                 default:
419                     update = handleDeviceCommand(channelUID, command);
420                     break;
421             }
422
423             restartWatchdog();
424             if (update && !autoCoIoT && !isUpdateScheduled()) {
425                 logger.debug("{}: Command processed, request status update", thingName);
426                 requestUpdates(1, false);
427             }
428         } catch (ShellyApiException e) {
429             ShellyApiResult res = e.getApiResult();
430             if (isAuthorizationFailed(res)) {
431                 return;
432             }
433             if (res.isNotCalibrtated()) {
434                 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
435             } else {
436                 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
437                         e.toString());
438             }
439         } catch (IllegalArgumentException e) {
440             logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
441         }
442     }
443
444     private double getNumber(Command command) {
445         if (command instanceof QuantityType) {
446             return ((QuantityType<?>) command).doubleValue();
447         }
448         if (command instanceof DecimalType) {
449             return ((DecimalType) command).doubleValue();
450         }
451         if (command instanceof Number) {
452             return ((Number) command).doubleValue();
453         }
454         throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
455     }
456
457     /**
458      * Update device status and channels
459      */
460     protected void refreshStatus() {
461         try {
462             boolean updated = false;
463
464             if (vibrationFilter > 0) {
465                 vibrationFilter--;
466                 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
467                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
468             }
469
470             skipUpdate++;
471             ThingStatus thingStatus = getThing().getStatus();
472             if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
473                 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
474                         || (thingStatus == ThingStatus.UNKNOWN)) {
475                     logger.debug("{}: Status update triggered thing initialization", thingName);
476                     initializeThing(); // may fire an exception if initialization failed
477                 }
478                 // Get profile, if refreshSettings == true reload settings from device
479                 logger.trace("{}: Updating status (scheduledUpdates={}, refreshSettings={})", thingName,
480                         scheduledUpdates, refreshSettings);
481                 ShellySettingsStatus status = api.getStatus();
482                 boolean restarted = checkRestarted(status);
483                 profile = getProfile(refreshSettings || restarted);
484                 profile.status = status;
485                 profile.updateFromStatus(status);
486                 if (restarted) {
487                     logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
488                     stats.restarts++;
489                     postEvent(ALARM_TYPE_RESTARTED, true);
490                 }
491
492                 // If status update was successful the thing must be online
493                 setThingOnline();
494
495                 // map status to channels
496                 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
497                 updated |= this.updateDeviceStatus(status);
498                 updated |= ShellyComponents.updateDeviceStatus(this, status);
499                 fillDeviceStatus(status, updated);
500                 updated |= updateInputs(status);
501                 updated |= updateMeters(this, status);
502                 updated |= updateSensors(this, status);
503
504                 // All channels must be created after the first cycle
505                 channelsCreated = true;
506             }
507         } catch (ShellyApiException e) {
508             // http call failed: go offline except for battery devices, which might be in
509             // sleep mode. Once the next update is successful the device goes back online
510             String status = "";
511             ShellyApiResult res = e.getApiResult();
512             if (isWatchdogStarted()) {
513                 if (!isWatchdogExpired()) {
514                     logger.debug("{}: Ignore API Timeout, retry later", thingName);
515                 } else {
516                     if (isThingOnline()) {
517                         status = "offline.status-error-watchdog";
518                     }
519                 }
520             } else if (res.isHttpAccessUnauthorized()) {
521                 status = "offline.conf-error-access-denied";
522             } else if (e.isJSONException()) {
523                 status = "offline.status-error-unexpected-api-result";
524                 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
525             } else if (res.isHttpTimeout()) {
526                 // Watchdog not started, e.g. device in sleep mode
527                 if (isThingOnline()) { // ignore when already offline
528                     status = "offline.status-error-watchdog";
529                 }
530             } else {
531                 status = "offline.status-error-unexpected-api-result";
532                 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
533             }
534
535             if (!status.isEmpty()) {
536                 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
537             }
538         } catch (NullPointerException | IllegalArgumentException e) {
539             logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
540         } finally {
541             if (scheduledUpdates > 0) {
542                 --scheduledUpdates;
543                 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
544             } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
545                 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
546                         cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
547                 cache.enable();
548             }
549         }
550     }
551
552     public boolean isThingOnline() {
553         return getThing().getStatus() == ThingStatus.ONLINE;
554     }
555
556     public boolean isThingOffline() {
557         return getThing().getStatus() == ThingStatus.OFFLINE;
558     }
559
560     @Override
561     public void setThingOnline() {
562         if (stopping) {
563             logger.debug("{}: Thing should go ONLINE, but handler is shutting down, ignore!", thingName);
564             return;
565         }
566         if (!isThingOnline()) {
567             updateStatus(ThingStatus.ONLINE);
568
569             // request 3 updates in a row (during the first 2+3*3 sec)
570             logger.debug("{}: Thing went online, request status update", thingName);
571             requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
572         }
573         restartWatchdog();
574     }
575
576     @Override
577     public void setThingOffline(ThingStatusDetail detail, String messageKey) {
578         String message = messages.get(messageKey);
579         if (stopping) {
580             logger.debug("{}: Thing should go OFFLINE with status {}, but handler is shutting down -> ignore",
581                     thingName, message);
582             return;
583         }
584
585         if (!isThingOffline()) {
586             updateStatus(ThingStatus.OFFLINE, detail, message);
587             watchdog = 0;
588             channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
589         }
590     }
591
592     @Override
593     public void restartWatchdog() {
594         watchdog = now();
595         updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
596         logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
597     }
598
599     private boolean isWatchdogExpired() {
600         long delta = now() - watchdog;
601         if ((watchdog > 0) && (delta > profile.updatePeriod)) {
602             stats.remainingWatchdog = delta;
603             return true;
604         }
605         return false;
606     }
607
608     private boolean isWatchdogStarted() {
609         return watchdog > 0;
610     }
611
612     @Override
613     public void reinitializeThing() {
614         logger.debug("{}: Re-Initialize Thing", thingName);
615         if (stopping) {
616             logger.debug("{}: Handler is shutting down, ignore", thingName);
617             return;
618         }
619         updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
620                 messages.get("offline.status-error-restarted"));
621         requestUpdates(0, true);
622     }
623
624     @Override
625     public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
626         String alarm = "";
627
628         // Update uptime and WiFi, internal temp
629         ShellyComponents.updateDeviceStatus(this, status);
630         stats.wifiRssi = status.wifiSta.rssi;
631
632         if (api.isInitialized()) {
633             stats.timeoutErrors = api.getTimeoutErrors();
634             stats.timeoutsRecorvered = api.getTimeoutsRecovered();
635         }
636         stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
637
638         // Check various device indicators like overheating
639         if (checkRestarted(status)) {
640             // Force re-initialization on next status update
641             reinitializeThing();
642         } else if (getBool(status.overtemperature)) {
643             alarm = ALARM_TYPE_OVERTEMP;
644         } else if (getBool(status.overload)) {
645             alarm = ALARM_TYPE_OVERLOAD;
646         } else if (getBool(status.loaderror)) {
647             alarm = ALARM_TYPE_LOADERR;
648         }
649         State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
650         if (internalTemp != UnDefType.NULL) {
651             int temp = ((Number) internalTemp).intValue();
652             if (temp > stats.maxInternalTemp) {
653                 stats.maxInternalTemp = temp;
654             }
655         }
656
657         if (status.uptime != null) {
658             stats.lastUptime = getLong(status.uptime);
659         }
660         stats.coiotMessages = coap.getMessageCount();
661         stats.coiotErrors = coap.getErrorCount();
662
663         if (!alarm.isEmpty()) {
664             postEvent(alarm, false);
665         }
666     }
667
668     /**
669      * Check if device has restarted and needs a new Thing initialization
670      *
671      * @return true: restart detected
672      */
673
674     private boolean checkRestarted(ShellySettingsStatus status) {
675         if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
676                 && (status.uptime != null && status.uptime < stats.lastUptime
677                         || !profile.status.update.oldVersion.isEmpty()
678                                 && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
679             updateProperties(profile, status);
680             return true;
681         }
682         return false;
683     }
684
685     /**
686      * Save alarm to the lastAlarm channel
687      *
688      * @param alarm Alarm Message
689      */
690     @Override
691     public void postEvent(String event, boolean force) {
692         String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
693         State value = cache.getValue(channelId);
694         String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
695
696         if (force || !lastAlarm.equals(event)
697                 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
698             switch (event) {
699                 case "":
700                 case "0": // DW2 1.8
701                 case SHELLY_WAKEUPT_SENSOR:
702                 case SHELLY_WAKEUPT_PERIODIC:
703                 case SHELLY_WAKEUPT_BUTTON:
704                 case SHELLY_WAKEUPT_POWERON:
705                 case SHELLY_WAKEUPT_EXT_POWER:
706                 case SHELLY_WAKEUPT_UNKNOWN:
707                     logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
708                 case ALARM_TYPE_NONE:
709                     break;
710                 default:
711                     logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
712                     triggerChannel(channelId, event);
713                     cache.updateChannel(channelId, getStringType(event.toUpperCase()));
714                     stats.lastAlarm = event;
715                     stats.lastAlarmTs = now();
716                     stats.alarms++;
717             }
718         }
719     }
720
721     /**
722      * Callback for device events
723      *
724      * @param deviceName device receiving the event
725      * @param parameters parameters from the event URL
726      * @param data the HTML input data
727      * @return true if event was processed
728      */
729     @Override
730     public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
731             Map<String, String> parameters) {
732         if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
733             logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
734                     parameters);
735             int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
736             if (!profile.isInitialized()) {
737                 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
738                 requestUpdates(1, true);
739             } else {
740                 String group = profile.getControlGroup(idx);
741                 if (group.isEmpty()) {
742                     logger.debug("{}: Unsupported event class: {}", thingName, type);
743                     return false;
744                 }
745
746                 // map some of the events to system defined button triggers
747                 String channel = "";
748                 String onoff = "";
749                 String payload = "";
750                 String parmType = getString(parameters.get("type"));
751                 String event = !parmType.isEmpty() ? parmType : type;
752                 boolean isButton = profile.inButtonMode(idx - 1);
753                 switch (event) {
754                     case SHELLY_EVENT_SHORTPUSH:
755                     case SHELLY_EVENT_DOUBLE_SHORTPUSH:
756                     case SHELLY_EVENT_TRIPLE_SHORTPUSH:
757                     case SHELLY_EVENT_LONGPUSH:
758                         if (isButton) {
759                             triggerButton(group, idx, mapButtonEvent(event));
760                             channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
761                             payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
762                         } else {
763                             logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
764                                     thingName);
765                         }
766                         break;
767                     case SHELLY_EVENT_BTN_ON:
768                     case SHELLY_EVENT_BTN_OFF:
769                         if (profile.isRGBW2) {
770                             // RGBW2 has only one input, so not per channel
771                             group = CHANNEL_GROUP_LIGHT_CONTROL;
772                         }
773                         onoff = CHANNEL_INPUT;
774                         break;
775                     case SHELLY_EVENT_BTN1_ON:
776                     case SHELLY_EVENT_BTN1_OFF:
777                         onoff = CHANNEL_INPUT1;
778                         break;
779                     case SHELLY_EVENT_BTN2_ON:
780                     case SHELLY_EVENT_BTN2_OFF:
781                         onoff = CHANNEL_INPUT2;
782                         break;
783                     case SHELLY_EVENT_OUT_ON:
784                     case SHELLY_EVENT_OUT_OFF:
785                         onoff = CHANNEL_OUTPUT;
786                         break;
787                     case SHELLY_EVENT_ROLLER_OPEN:
788                     case SHELLY_EVENT_ROLLER_CLOSE:
789                     case SHELLY_EVENT_ROLLER_STOP:
790                         channel = CHANNEL_EVENT_TRIGGER;
791                         payload = event;
792                         break;
793                     case SHELLY_EVENT_SENSORREPORT:
794                         // process sensor with next refresh
795                         break;
796                     case SHELLY_EVENT_TEMP_OVER: // DW2
797                     case SHELLY_EVENT_TEMP_UNDER:
798                         channel = CHANNEL_EVENT_TRIGGER;
799                         payload = event;
800                         break;
801                     case SHELLY_EVENT_FLOOD_DETECTED:
802                     case SHELLY_EVENT_FLOOD_GONE:
803                         updateChannel(group, CHANNEL_SENSOR_FLOOD,
804                                 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
805                         break;
806
807                     case SHELLY_EVENT_CLOSE: // DW 1.7
808                     case SHELLY_EVENT_OPEN: // DW 1.7
809                         updateChannel(group, CHANNEL_SENSOR_STATE,
810                                 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
811                                         : OpenClosedType.CLOSED);
812                         break;
813
814                     case SHELLY_EVENT_DARK: // DW 1.7
815                     case SHELLY_EVENT_TWILIGHT: // DW 1.7
816                     case SHELLY_EVENT_BRIGHT: // DW 1.7
817                         updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
818                         break;
819
820                     case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
821                     case SHELLY_EVENT_ALARM_HEAVY:
822                     case SHELLY_EVENT_ALARM_OFF:
823                     case SHELLY_EVENT_VIBRATION: // DW2
824                         channel = CHANNEL_SENSOR_ALARM_STATE;
825                         payload = event.toUpperCase();
826                         break;
827
828                     default:
829                         // trigger will be provided by input/output channel or sensor channels
830                 }
831
832                 if (!onoff.isEmpty()) {
833                     updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
834                 }
835                 if (!payload.isEmpty()) {
836                     // Pass event to trigger channel
837                     payload = payload.toUpperCase();
838                     logger.debug("{}: Post event {}", thingName, payload);
839                     triggerChannel(mkChannelId(group, channel), payload);
840                 }
841             }
842
843             // request update on next interval (2x for non-battery devices)
844             restartWatchdog();
845             requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
846             return true;
847         }
848         return false;
849     }
850
851     /**
852      * Initialize the binding's thing configuration, calc update counts
853      */
854     protected void initializeThingConfig() {
855         thingType = getThing().getThingTypeUID().getId();
856         final Map<String, String> properties = getThing().getProperties();
857         thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
858         if (thingName.isEmpty()) {
859             thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
860             logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
861         }
862
863         config = getConfigAs(ShellyThingConfiguration.class);
864         if (config.deviceIp.isEmpty()) {
865             logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
866             return;
867         }
868         try {
869             InetAddress addr = InetAddress.getByName(config.deviceIp);
870             String saddr = addr.getHostAddress();
871             if (!config.deviceIp.equals(saddr)) {
872                 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
873                 config.deviceIp = saddr;
874             }
875         } catch (UnknownHostException e) {
876             logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
877         }
878
879         config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
880         config.localIp = localIP;
881         config.localPort = localPort;
882         if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
883             config.userId = bindingConfig.defaultUserId;
884             config.password = bindingConfig.defaultPassword;
885             logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
886         }
887         if (config.updateInterval == 0) {
888             config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
889         }
890         if (config.updateInterval < UPDATE_MIN_DELAY) {
891             config.updateInterval = UPDATE_MIN_DELAY;
892         }
893
894         // Try to get updatePeriod from properties
895         // For battery devinities the REST call to get the settings will most likely fail, because the device is in
896         // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
897         // initialized successfully by the REST call.
898         String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
899         if (!lastPeriod.isEmpty()) {
900             int period = Integer.parseInt(lastPeriod);
901             if (period > 0) {
902                 profile.updatePeriod = period;
903             }
904         }
905
906         skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
907         logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
908     }
909
910     private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
911         try {
912             ShellyVersionDTO version = new ShellyVersionDTO();
913             if (version.checkBeta(getString(prf.fwVersion))) {
914                 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
915             } else {
916                 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
917                     logger.warn("{}: {}", prf.hostname,
918                             messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
919                 }
920             }
921             if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
922                     || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
923                 if (!config.eventsCoIoT) {
924                     logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
925                 }
926                 autoCoIoT = true;
927             }
928             if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
929                 logger.info("{}: {}", thingName,
930                         messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
931             }
932         } catch (NullPointerException e) { // could be inconsistant format of beta version
933             logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
934         }
935     }
936
937     /**
938      * Checks the http response for authorization error.
939      * If the authorization failed the binding can't access the device settings and determine the thing type. In this
940      * case the thing type shelly-unknown is set.
941      *
942      * @param response exception details including the http respone
943      * @return true if the authorization failed
944      */
945     protected boolean isAuthorizationFailed(ShellyApiResult result) {
946         if (result.isHttpAccessUnauthorized()) {
947             // If the device is password protected the API doesn't provide settings to the device settings
948             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
949             return true;
950         }
951         return false;
952     }
953
954     /**
955      * Change type of this thing.
956      *
957      * @param thingType thing type acc. to the xml definition
958      * @param mode Device mode (e.g. relay, roller)
959      */
960     private void changeThingType(String thingType, String mode) {
961         ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
962         if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
963             logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
964             Map<String, String> properties = editProperties();
965             properties.replace(PROPERTY_DEV_TYPE, thingType);
966             properties.replace(PROPERTY_DEV_MODE, mode);
967             updateProperties(properties);
968             changeThingType(thingTypeUID, getConfig());
969         }
970     }
971
972     @Override
973     public void thingUpdated(Thing thing) {
974         logger.debug("{}: Channel definitions updated.", thingName);
975         super.thingUpdated(thing);
976     }
977
978     /**
979      * Start the background updates
980      */
981     protected void startUpdateJob() {
982         ScheduledFuture<?> statusJob = this.statusJob;
983         if ((statusJob == null) || statusJob.isCancelled()) {
984             this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
985                     TimeUnit.SECONDS);
986             logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
987                     UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
988         }
989     }
990
991     /**
992      * Flag the status job to do an exceptional update (something happened) rather
993      * than waiting until the next regular poll
994      *
995      * @param requestCount number of polls to execute
996      * @param refreshSettings true=force a /settings query
997      * @return true=Update schedule, false=skipped (too many updates already
998      *         scheduled)
999      */
1000     @Override
1001     public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1002         this.refreshSettings |= refreshSettings;
1003         if (refreshSettings) {
1004             if (requestCount == 0) {
1005                 logger.debug("{}: Request settings refresh", thingName);
1006             }
1007             scheduledUpdates = 1;
1008             return true;
1009         }
1010         if (scheduledUpdates < 10) { // < 30s
1011             scheduledUpdates += requestCount;
1012             return true;
1013         }
1014         return false;
1015     }
1016
1017     public boolean isUpdateScheduled() {
1018         return scheduledUpdates > 0;
1019     }
1020
1021     /**
1022      * Map input states to channels
1023      *
1024      * @param groupName Channel Group (relay / relay1...)
1025      *
1026      * @param status Shelly device status
1027      * @return true: one or more inputs were updated
1028      */
1029     @Override
1030     public boolean updateInputs(ShellySettingsStatus status) {
1031         boolean updated = false;
1032
1033         if (status.inputs != null) {
1034             int idx = 0;
1035             boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
1036             for (ShellyInputState input : status.inputs) {
1037                 String group = profile.getControlGroup(idx);
1038                 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1039
1040                 if (!areChannelsCreated()) {
1041                     updateChannelDefinitions(
1042                             ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
1043                 }
1044
1045                 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1046                 if (input.event != null) {
1047                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1048                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1049                 }
1050                 idx++;
1051             }
1052         } else {
1053             if (status.input != null) {
1054                 // RGBW2: a single int rather than an array
1055                 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1056                         getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1057             }
1058         }
1059         return updated;
1060     }
1061
1062     @Override
1063     public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1064         boolean changed = false;
1065         if (valueArray != null && !valueArray.isEmpty()) {
1066             String reason = getString((String) valueArray.get(0));
1067             String newVal = valueArray.toString();
1068             changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1069             changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1070             if (changed) {
1071                 postEvent(reason.toUpperCase(), true);
1072             }
1073             lastWakeupReason = newVal;
1074         }
1075         return changed;
1076     }
1077
1078     @Override
1079     public void triggerButton(String group, int idx, String value) {
1080         String trigger = mapButtonEvent(value);
1081         if (trigger.isEmpty()) {
1082             return;
1083         }
1084
1085         logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1086         triggerChannel(group,
1087                 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1088                 trigger);
1089         updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1090         if (profile.alwaysOn) {
1091             // refresh status of the input channel
1092             requestUpdates(1, false);
1093         }
1094     }
1095
1096     @Override
1097     public void publishState(String channelId, State value) {
1098         String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1099         if (!stopping && isLinked(id)) {
1100             updateState(id, value);
1101             logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1102         }
1103     }
1104
1105     @Override
1106     public boolean updateChannel(String group, String channel, State value) {
1107         return updateChannel(mkChannelId(group, channel), value, false);
1108     }
1109
1110     @Override
1111     public boolean updateChannel(String channelId, State value, boolean force) {
1112         return !stopping && cache.updateChannel(channelId, value, force);
1113     }
1114
1115     @Override
1116     public State getChannelValue(String group, String channel) {
1117         return cache.getValue(group, channel);
1118     }
1119
1120     @Override
1121     public double getChannelDouble(String group, String channel) {
1122         State value = getChannelValue(group, channel);
1123         if (value != UnDefType.NULL) {
1124             if (value instanceof QuantityType) {
1125                 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1126             }
1127             if (value instanceof DecimalType) {
1128                 return ((DecimalType) value).doubleValue();
1129             }
1130         }
1131         return -1;
1132     }
1133
1134     /**
1135      * Update Thing's channels according to available status information from the API
1136      *
1137      * @param thingHandler
1138      */
1139     @Override
1140     public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1141         if (channelsCreated) {
1142             return; // already done
1143         }
1144
1145         try {
1146             // Get subset of those channels that currently do not exist
1147             List<Channel> existingChannels = getThing().getChannels();
1148             for (Channel channel : existingChannels) {
1149                 String id = channel.getUID().getId();
1150                 if (dynChannels.containsKey(id)) {
1151                     dynChannels.remove(id);
1152                 }
1153             }
1154
1155             if (!dynChannels.isEmpty()) {
1156                 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1157                 ThingBuilder thingBuilder = editThing();
1158                 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1159                     Channel c = channel.getValue();
1160                     logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1161                     thingBuilder.withChannel(c);
1162                 }
1163                 updateThing(thingBuilder.build());
1164                 logger.debug("{}: Channel definitions updated", thingName);
1165             }
1166         } catch (IllegalArgumentException e) {
1167             logger.debug("{}: Unable to update channel definitions", thingName, e);
1168         }
1169     }
1170
1171     @Override
1172     public boolean areChannelsCreated() {
1173         return channelsCreated;
1174     }
1175
1176     /**
1177      * Update thing properties with dynamic values
1178      *
1179      * @param profile The device profile
1180      * @param status the /status result
1181      */
1182     protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1183         logger.debug("{}: Update properties", thingName);
1184         Map<String, Object> properties = fillDeviceProperties(profile);
1185         String deviceName = getString(profile.settings.name);
1186         properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1187         properties.put(PROPERTY_DEV_GEN, "1");
1188         if (!deviceName.isEmpty()) {
1189             properties.put(PROPERTY_DEV_NAME, deviceName);
1190         }
1191
1192         // add status properties
1193         if (status.wifiSta != null) {
1194             properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1195         }
1196         if (status.update != null) {
1197             properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1198             properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1199             properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1200             properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1201         }
1202         properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1203
1204         Map<String, String> thingProperties = new TreeMap<>();
1205         for (Map.Entry<String, Object> property : properties.entrySet()) {
1206             thingProperties.put(property.getKey(), (String) property.getValue());
1207         }
1208         flushProperties(thingProperties);
1209     }
1210
1211     /**
1212      * Add one property to the Thing Properties
1213      *
1214      * @param key Name of the property
1215      * @param value Value of the property
1216      */
1217     @Override
1218     public void updateProperties(String key, String value) {
1219         Map<String, String> thingProperties = editProperties();
1220         if (thingProperties.containsKey(key)) {
1221             thingProperties.replace(key, value);
1222         } else {
1223             thingProperties.put(key, value);
1224         }
1225         updateProperties(thingProperties);
1226         logger.trace("{}: Properties updated", thingName);
1227     }
1228
1229     public void flushProperties(Map<String, String> propertyUpdates) {
1230         Map<String, String> thingProperties = editProperties();
1231         for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1232             if (thingProperties.containsKey(property.getKey())) {
1233                 thingProperties.replace(property.getKey(), property.getValue());
1234             } else {
1235                 thingProperties.put(property.getKey(), property.getValue());
1236             }
1237         }
1238         updateProperties(thingProperties);
1239     }
1240
1241     /**
1242      * Get one property from the Thing Properties
1243      *
1244      * @param key property name
1245      * @return property value or "" if property is not set
1246      */
1247     @Override
1248     public String getProperty(String key) {
1249         Map<String, String> thingProperties = getThing().getProperties();
1250         return getString(thingProperties.get(key));
1251     }
1252
1253     /**
1254      * Fill Thing Properties with device attributes
1255      *
1256      * @param profile Property Map to full
1257      * @return a full property map
1258      */
1259     public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1260         Map<String, Object> properties = new TreeMap<>();
1261         properties.put(PROPERTY_VENDOR, VENDOR);
1262         if (profile.isInitialized()) {
1263             properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1264             properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1265             properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1266             properties.put(PROPERTY_DEV_MODE, profile.mode);
1267             properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1268             properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1269             properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1270             properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1271             if (!profile.hwRev.isEmpty()) {
1272                 properties.put(PROPERTY_HWREV, profile.hwRev);
1273                 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1274             }
1275         }
1276         return properties;
1277     }
1278
1279     /**
1280      * Return device profile.
1281      *
1282      * @param ForceRefresh true=force refresh before returning, false=return without
1283      *            refresh
1284      * @return ShellyDeviceProfile instance
1285      * @throws ShellyApiException
1286      */
1287     @Override
1288     public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1289         try {
1290             refreshSettings |= forceRefresh;
1291             if (refreshSettings) {
1292                 profile = api.getDeviceProfile(thingType);
1293                 if (!isThingOnline()) {
1294                     logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1295                 }
1296             }
1297         } finally {
1298             refreshSettings = false;
1299         }
1300         return profile;
1301     }
1302
1303     @Override
1304     public ShellyDeviceProfile getProfile() {
1305         return profile;
1306     }
1307
1308     protected ShellyDeviceProfile getDeviceProfile() {
1309         return profile;
1310     }
1311
1312     @Override
1313     public void triggerChannel(String group, String channel, String payload) {
1314         String triggerCh = mkChannelId(group, channel);
1315         logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1316         if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1317             if (vibrationFilter == 0) {
1318                 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1319                 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1320                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1321             } else {
1322                 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1323                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1324                 return;
1325             }
1326         }
1327
1328         triggerChannel(triggerCh, payload);
1329     }
1330
1331     public void stop() {
1332         logger.debug("{}: Shutting down", thingName);
1333         ScheduledFuture<?> job = this.statusJob;
1334         if (job != null) {
1335             job.cancel(true);
1336             statusJob = null;
1337             logger.debug("{}: Shelly statusJob stopped", thingName);
1338         }
1339
1340         coap.stop();
1341         profile.initialized = false;
1342     }
1343
1344     /**
1345      * Shutdown thing, make sure background jobs are canceled
1346      */
1347     @Override
1348     public void dispose() {
1349         stopping = true;
1350         stop();
1351         super.dispose();
1352     }
1353
1354     /**
1355      * Device specific command handlers are overriding this method to do additional stuff
1356      */
1357     public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1358         return false;
1359     }
1360
1361     /**
1362      * Device specific handlers are overriding this method to do additional stuff
1363      */
1364     public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1365         return false;
1366     }
1367
1368     @Override
1369     public String getThingName() {
1370         return thingName;
1371     }
1372
1373     @Override
1374     public void resetStats() {
1375         // reset statistics
1376         stats = new ShellyDeviceStats();
1377     }
1378
1379     @Override
1380     public ShellyDeviceStats getStats() {
1381         return stats;
1382     }
1383
1384     @Override
1385     public ShellyApiInterface getApi() {
1386         return api;
1387     }
1388
1389     public Map<String, String> getStatsProp() {
1390         return stats.asProperties();
1391     }
1392
1393     @Override
1394     public long getScheduledUpdates() {
1395         return scheduledUpdates;
1396     }
1397
1398     public String checkForUpdate() {
1399         try {
1400             ShellyOtaCheckResult result = api.checkForUpdate();
1401             return result.status;
1402         } catch (ShellyApiException e) {
1403             return "";
1404         }
1405     }
1406
1407     @Override
1408     public void triggerUpdateFromCoap() {
1409         if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1410             requestUpdates(1, false);
1411         }
1412     }
1413 }