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