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