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