]> git.basschouten.com Git - openhab-addons.git/blob
db02cc289059a56a7f79a7ab6bfc12161f08a003
[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     protected ShellyDeviceStats stats = new ShellyDeviceStats();
87     private final ShellyCoapHandler coap;
88     public boolean autoCoIoT = false;
89
90     public final ShellyTranslationProvider messages;
91     protected boolean stopping = false;
92     private boolean channelsCreated = false;
93
94     private long watchdog = now();
95
96     private @Nullable ScheduledFuture<?> statusJob;
97     public int scheduledUpdates = 0;
98     private int skipCount = UPDATE_SKIP_COUNT;
99     private int skipUpdate = 0;
100     private boolean refreshSettings = false;
101
102     private @Nullable ScheduledFuture<?> asyncButtonRelease;
103
104     // delay before enabling channel
105     private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
106     protected final ShellyChannelCache cache;
107
108     private String localIP = "";
109     private String localPort = "";
110
111     private String lastWakeupReason = "";
112
113     /**
114      * Constructor
115      *
116      * @param thing The Thing object
117      * @param bindingConfig The binding configuration (beside thing
118      *            configuration)
119      * @param coapServer coap server instance
120      * @param localIP local IP address from networkAddressService
121      * @param httpPort from httpService
122      */
123     public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
124             final ShellyBindingConfiguration bindingConfig, final ShellyCoapServer coapServer, final String localIP,
125             int httpPort, final HttpClient httpClient) {
126         super(thing);
127
128         this.messages = translationProvider;
129         this.cache = new ShellyChannelCache(this);
130         this.channelDefinitions = new ShellyChannelDefinitions(messages);
131         this.bindingConfig = bindingConfig;
132
133         this.localIP = localIP;
134         this.localPort = String.valueOf(httpPort);
135         this.api = new ShellyHttpApi(thingName, config, httpClient);
136
137         coap = new ShellyCoapHandler(this, coapServer);
138     }
139
140     /**
141      * Schedule asynchronous Thing initialization, register thing to event dispatcher
142      */
143     @Override
144     public void initialize() {
145         // start background initialization:
146         scheduler.schedule(() -> {
147             boolean start = true;
148             try {
149                 initializeThingConfig();
150                 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
151                         thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
152                         config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
153                 logger.debug(
154                         "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
155                         thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
156                         config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
157                 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
158                         messages.get("status.unknown.initializing"));
159                 start = initializeThing();
160             } catch (ShellyApiException e) {
161                 ShellyApiResult res = e.getApiResult();
162                 if (isAuthorizationFailed(res)) {
163                     start = false;
164                 }
165                 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
166             } catch (IllegalArgumentException e) {
167                 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
168             } finally {
169                 // even this initialization failed we start the status update
170                 // the updateJob will then try to auto-initialize the thing
171                 // in this case the thing stays in status INITIALIZING
172                 if (start) {
173                     startUpdateJob();
174                 }
175             }
176         }, 2, TimeUnit.SECONDS);
177     }
178
179     /**
180      * This routine is called every time the Thing configuration has been changed
181      */
182     @Override
183     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
184         super.handleConfigurationUpdate(configurationParameters);
185         logger.debug("{}: Thing config updated, re-initialize", thingName);
186         coap.stop();
187         requestUpdates(1, true);// force re-initialization
188     }
189
190     /**
191      * Initialize Thing: Initialize API access, get settings and initialize Device Profile
192      * If the device is password protected and the credentials are missing or don't match the API access will throw an
193      * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
194      * thing config and set the correct credentials. The thing type will be changed to the requested one if the
195      * credentials are correct and the API access is initialized successful.
196      *
197      * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
198      */
199     private boolean initializeThing() throws ShellyApiException {
200         // Init from thing type to have a basic profile, gets updated when device info is received from API
201         stopping = false;
202         refreshSettings = false;
203         lastWakeupReason = "";
204         profile.initFromThingType(thingType);
205         api.setConfig(thingName, config);
206         cache.setThingName(thingName);
207         cache.clear();
208
209         logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
210                 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
211         if (config.deviceIp.isEmpty()) {
212             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
213             return false;
214         }
215
216         // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
217         // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
218         // when enabled)
219         if (config.eventsCoIoT && profile.hasBattery && !profile.isMotion && !profile.isSense) {
220             coap.start(thingName, config);
221         }
222
223         // Initialize API access, exceptions will be catched by initialize()
224         ShellySettingsDevice devInfo = api.getDevInfo();
225         if (devInfo.auth && config.userId.isEmpty()) {
226             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
227             return false;
228         }
229
230         ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
231         if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
232             changeThingType(thingName, tmpPrf.mode);
233             return false; // force re-initialization
234         }
235         // Validate device mode
236         String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
237         if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
238             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
239             return false;
240         }
241         if (!getString(devInfo.coiot).isEmpty()) {
242             // New Shelly devices might use a different endpoint for the CoAP listener
243             tmpPrf.coiotEndpoint = devInfo.coiot;
244         }
245
246         logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {} ({})",
247                 thingName, tmpPrf.hostname, tmpPrf.deviceType, tmpPrf.hwRev, tmpPrf.hwBatchId, tmpPrf.fwVersion,
248                 tmpPrf.fwDate, tmpPrf.fwId);
249         logger.debug("{}: Shelly settings info for {}: {}", thingName, tmpPrf.hostname, tmpPrf.settingsJson);
250         logger.debug("{}: Device "
251                 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
252                 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
253                 + ",updatePeriod:{}sec", thingName, tmpPrf.hasRelays, tmpPrf.numRelays, tmpPrf.isRoller,
254                 tmpPrf.numRollers, tmpPrf.isDimmer, tmpPrf.numMeters, tmpPrf.isEMeter, tmpPrf.isSensor, tmpPrf.isDW,
255                 tmpPrf.hasBattery, tmpPrf.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
256                 tmpPrf.isSense, tmpPrf.isLight, profile.isBulb, tmpPrf.isDuo, tmpPrf.isRGBW2, tmpPrf.inColor,
257                 tmpPrf.updatePeriod);
258
259         // update thing properties
260         tmpPrf.status = api.getStatus();
261         tmpPrf.updateFromStatus(tmpPrf.status);
262         updateProperties(tmpPrf, tmpPrf.status);
263         checkVersion(tmpPrf, tmpPrf.status);
264         if (autoCoIoT) {
265             logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
266             config.eventsCoIoT = true;
267             config.eventsSwitch = false;
268             config.eventsButton = false;
269             config.eventsPush = false;
270             config.eventsRoller = false;
271             config.eventsSensorReport = false;
272             api.setConfig(thingName, config);
273         }
274
275         // All initialization done, so keep the profile and set Thing to ONLINE
276         fillDeviceStatus(tmpPrf.status, false);
277         postEvent(ALARM_TYPE_NONE, false);
278         api.setActionURLs(); // register event urls
279         if (config.eventsCoIoT) {
280             logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
281             coap.start(thingName, config);
282         }
283
284         logger.debug("{}: Thing successfully initialized.", thingName);
285         profile = tmpPrf;
286         setThingOnline(); // if API call was successful the thing must be online
287
288         return true; // success
289     }
290
291     /**
292      * Handle Channel Commands
293      */
294     @Override
295     public void handleCommand(ChannelUID channelUID, Command command) {
296         try {
297             if (command instanceof RefreshType) {
298                 String channelId = channelUID.getId();
299                 State value = cache.getValue(channelId);
300                 if (value != UnDefType.NULL) {
301                     updateState(channelId, value);
302                 }
303                 return;
304             }
305
306             if (!profile.isInitialized()) {
307                 logger.debug("{}: {}", thingName, messages.get("command.init", command));
308                 initializeThing();
309             } else {
310                 profile = getProfile(false);
311             }
312
313             boolean update = false;
314             switch (channelUID.getIdWithoutGroup()) {
315                 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
316                     logger.debug("{}: Send key {}", thingName, command);
317                     api.sendIRKey(command.toString());
318                     update = true;
319                     break;
320
321                 case CHANNEL_LED_STATUS_DISABLE:
322                     logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
323                     api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
324                     break;
325                 case CHANNEL_LED_POWER_DISABLE:
326                     logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
327                     api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
328                     break;
329
330                 default:
331                     update = handleDeviceCommand(channelUID, command);
332                     break;
333             }
334
335             restartWatchdog();
336             if (update && !autoCoIoT) {
337                 requestUpdates(1, false);
338             }
339         } catch (ShellyApiException e) {
340             ShellyApiResult res = e.getApiResult();
341             if (isAuthorizationFailed(res)) {
342                 return;
343             }
344             if (res.isNotCalibrtated()) {
345                 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
346             } else {
347                 logger.info("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
348                         e.toString());
349             }
350         } catch (IllegalArgumentException e) {
351             logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
352         }
353     }
354
355     /**
356      * Update device status and channels
357      */
358     protected void refreshStatus() {
359         try {
360             boolean updated = false;
361
362             skipUpdate++;
363             ThingStatus thingStatus = getThing().getStatus();
364             if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
365                 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
366                         || (thingStatus == ThingStatus.UNKNOWN)) {
367                     logger.debug("{}: Status update triggered thing initialization", thingName);
368                     initializeThing(); // may fire an exception if initialization failed
369                 }
370                 // Get profile, if refreshSettings == true reload settings from device
371                 profile = getProfile(refreshSettings);
372
373                 logger.trace("{}: Updating status", thingName);
374                 ShellySettingsStatus status = api.getStatus();
375                 profile.status = status;
376                 profile.updateFromStatus(status);
377
378                 // If status update was successful the thing must be online
379                 setThingOnline();
380
381                 // map status to channels
382                 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
383                 updated |= this.updateDeviceStatus(status);
384                 updated |= ShellyComponents.updateDeviceStatus(this, status);
385                 fillDeviceStatus(status, updated);
386                 updated |= updateInputs(status);
387                 updated |= updateMeters(this, status);
388                 updated |= updateSensors(this, status);
389
390                 // All channels must be created after the first cycle
391                 channelsCreated = true;
392
393                 // Restart watchdog when status update was successful (no exception)
394                 restartWatchdog();
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                     if (isThingOnline()) {
406                         status = "offline.status-error-watchdog";
407                     }
408                 }
409             } else if (res.isHttpAccessUnauthorized()) {
410                 status = "offline.conf-error-access-denied";
411             } else if (e.isJSONException()) {
412                 status = "offline.status-error-unexpected-api-result";
413                 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
414             } else if (res.isHttpTimeout()) {
415                 // Watchdog not started, e.g. device in sleep mode
416                 if (isThingOnline()) { // ignore when already offline
417                     status = "offline.status-error-watchdog";
418                 }
419             } else {
420                 status = "offline.status-error-unexpected-api-result";
421                 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
422             }
423
424             if (!status.isEmpty()) {
425                 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
426             }
427         } catch (NullPointerException | IllegalArgumentException e) {
428             logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
429         } finally {
430             if (scheduledUpdates > 0) {
431                 --scheduledUpdates;
432                 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
433             } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
434                 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
435                         cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
436                 cache.enable();
437             }
438         }
439     }
440
441     public boolean isThingOnline() {
442         return getThing().getStatus() == ThingStatus.ONLINE;
443     }
444
445     public boolean isThingOffline() {
446         return getThing().getStatus() == ThingStatus.OFFLINE;
447     }
448
449     public void setThingOnline() {
450         if (!isThingOnline()) {
451             updateStatus(ThingStatus.ONLINE);
452
453             // request 3 updates in a row (during the first 2+3*3 sec)
454             requestUpdates(!profile.hasBattery ? 3 : 1, channelsCreated == false);
455         }
456         restartWatchdog();
457     }
458
459     public void setThingOffline(ThingStatusDetail detail, String messageKey) {
460         if (!isThingOffline()) {
461             logger.info("{}: Thing goes OFFLINE: {}", thingName, messages.get(messageKey));
462             updateStatus(ThingStatus.OFFLINE, detail, "@text/" + messageKey);
463             watchdog = 0;
464             channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
465         }
466     }
467
468     public synchronized void restartWatchdog() {
469         watchdog = now();
470         updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
471         logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
472     }
473
474     private boolean isWatchdogExpired() {
475         long delta = now() - watchdog;
476         if ((watchdog > 0) && (delta > profile.updatePeriod)) {
477             stats.remainingWatchdog = delta;
478             return true;
479         }
480         return false;
481     }
482
483     private boolean isWatchdogStarted() {
484         return watchdog > 0;
485     }
486
487     public void reinitializeThing() {
488         updateStatus(ThingStatus.UNKNOWN);
489         requestUpdates(1, true);
490     }
491
492     private void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
493         String alarm = "";
494         boolean force = false;
495
496         // Update uptime and WiFi, internal temp
497         ShellyComponents.updateDeviceStatus(this, status);
498
499         if (api.isInitialized()) {
500             stats.timeoutErrors = api.getTimeoutErrors();
501             stats.timeoutsRecorvered = api.getTimeoutsRecovered();
502         }
503         stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
504
505         // Check various device indicators like overheating
506         logger.debug("{}: status.update={}, lastUpdate={}", thingName, status.uptime, stats.lastUptime);
507         if ((status.uptime < stats.lastUptime) && profile.isInitialized()) {
508             alarm = ALARM_TYPE_RESTARTED;
509             force = true;
510             stats.unexpectedRestarts++;
511             logger.debug("{}: Device restart #{} detected", thingName, stats.unexpectedRestarts);
512
513             // Force re-initialization on next status update
514             if (!profile.hasBattery || profile.isMotion) {
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         stats.lastUptime = getLong(status.uptime);
525         stats.coiotMessages = coap.getMessageCount();
526         stats.coiotErrors = coap.getErrorCount();
527
528         if (!alarm.isEmpty()) {
529             postEvent(alarm, force);
530         }
531     }
532
533     /**
534      * Save alarm to the lastAlarm channel
535      *
536      * @param alarm Alarm Message
537      */
538     public void postEvent(String alarm, boolean force) {
539         String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
540         State value = cache.getValue(channelId);
541         String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
542
543         if (force || !lastAlarm.equals(alarm) || (now() > (stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC))) {
544             if (alarm.isEmpty() || alarm.equals(ALARM_TYPE_NONE)) {
545                 cache.updateChannel(channelId, getStringType(alarm));
546             } else {
547                 logger.info("{}: {}", thingName, messages.get("event.triggered", alarm));
548                 triggerChannel(channelId, alarm);
549                 cache.updateChannel(channelId, getStringType(alarm));
550                 stats.lastAlarm = alarm;
551                 stats.lastAlarmTs = now();
552                 stats.alarms++;
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                     || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
762                 if (!config.eventsCoIoT) {
763                     logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
764                 }
765                 autoCoIoT = true;
766             }
767             if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
768                 logger.info("{}: {}", thingName,
769                         messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
770             }
771         } catch (NullPointerException e) { // could be inconsistant format of beta version
772             logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
773         }
774     }
775
776     /**
777      * Checks the http response for authorization error.
778      * If the authorization failed the binding can't access the device settings and determine the thing type. In this
779      * case the thing type shelly-unknown is set.
780      *
781      * @param response exception details including the http respone
782      * @return true if the authorization failed
783      */
784     private boolean isAuthorizationFailed(ShellyApiResult result) {
785         if (result.isHttpAccessUnauthorized()) {
786             // If the device is password protected the API doesn't provide settings to the device settings
787             logger.info("{}: {}", thingName, messages.get("init.protected"));
788             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
789             changeThingType(THING_TYPE_SHELLYPROTECTED_STR, "");
790             return true;
791         }
792         return false;
793     }
794
795     /**
796      * Change type of this thing.
797      *
798      * @param thingType thing type acc. to the xml definition
799      * @param mode Device mode (e.g. relay, roller)
800      */
801     private void changeThingType(String thingType, String mode) {
802         ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
803         if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
804             logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
805             Map<String, String> properties = editProperties();
806             properties.replace(PROPERTY_DEV_TYPE, thingType);
807             properties.replace(PROPERTY_DEV_MODE, mode);
808             updateProperties(properties);
809             changeThingType(thingTypeUID, getConfig());
810         }
811     }
812
813     @Override
814     public void thingUpdated(Thing thing) {
815         logger.debug("{}: Channel definitions updated.", thingName);
816         super.thingUpdated(thing);
817     }
818
819     /**
820      * Start the background updates
821      */
822     protected void startUpdateJob() {
823         ScheduledFuture<?> statusJob = this.statusJob;
824         if ((statusJob == null) || statusJob.isCancelled()) {
825             this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
826                     TimeUnit.SECONDS);
827             logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
828                     UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
829         }
830     }
831
832     /**
833      * Flag the status job to do an exceptional update (something happened) rather
834      * than waiting until the next regular poll
835      *
836      * @param requestCount number of polls to execute
837      * @param refreshSettings true=force a /settings query
838      * @return true=Update schedule, false=skipped (too many updates already
839      *         scheduled)
840      */
841     public boolean requestUpdates(int requestCount, boolean refreshSettings) {
842         this.refreshSettings |= refreshSettings;
843         if (refreshSettings) {
844             if (requestCount == 0) {
845                 logger.debug("{}: Request settings refresh", thingName);
846             }
847             scheduledUpdates = requestCount;
848             return true;
849         }
850         if (scheduledUpdates < 10) { // < 30s
851             scheduledUpdates += requestCount;
852             return true;
853         }
854         return false;
855     }
856
857     /**
858      * Map input states to channels
859      *
860      * @param groupName Channel Group (relay / relay1...)
861      *
862      * @param status Shelly device status
863      * @return true: one or more inputs were updated
864      */
865     public boolean updateInputs(ShellySettingsStatus status) {
866         boolean updated = false;
867
868         if (status.inputs != null) {
869             int idx = 0;
870             boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
871             for (ShellyInputState input : status.inputs) {
872                 String group = profile.getControlGroup(idx);
873                 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
874
875                 if (!areChannelsCreated()) {
876                     updateChannelDefinitions(
877                             ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
878                 }
879
880                 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
881                 if (input.event != null) {
882                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
883                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
884                 }
885                 idx++;
886             }
887         } else {
888             if (status.input != null) {
889                 // RGBW2: a single int rather than an array
890                 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
891                         getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
892             }
893         }
894         return updated;
895     }
896
897     public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
898         boolean changed = false;
899         if ((valueArray != null) && (valueArray.size() > 0)) {
900             String reason = getString((String) valueArray.get(0));
901             String newVal = valueArray.toString();
902             changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
903             changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
904             if (changed) {
905                 postEvent(reason.toUpperCase(), true);
906             }
907             lastWakeupReason = newVal;
908         }
909         return changed;
910     }
911
912     public void triggerButton(String group, int idx, String value) {
913         String trigger = mapButtonEvent(value);
914         if (trigger.isEmpty()) {
915             return;
916         }
917
918         logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
919         triggerChannel(group,
920                 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
921                 trigger);
922         updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
923         if (!profile.hasBattery) {
924             // refresh status of the input channel
925             requestUpdates(1, false);
926         }
927     }
928
929     public void publishState(String channelId, State value) {
930         String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
931         if (!stopping && isLinked(id)) {
932             updateState(id, value);
933         }
934     }
935
936     public boolean updateChannel(String group, String channel, State value) {
937         return updateChannel(mkChannelId(group, channel), value, false);
938     }
939
940     public boolean updateChannel(String channelId, State value, boolean force) {
941         return !stopping && cache.updateChannel(channelId, value, force);
942     }
943
944     public State getChannelValue(String group, String channel) {
945         return cache.getValue(group, channel);
946     }
947
948     public double getChannelDouble(String group, String channel) {
949         State value = getChannelValue(group, channel);
950         if (value != UnDefType.NULL) {
951             if (value instanceof QuantityType) {
952                 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
953             }
954             if (value instanceof DecimalType) {
955                 return ((DecimalType) value).doubleValue();
956             }
957         }
958         return -1;
959     }
960
961     /**
962      * Update Thing's channels according to available status information from the API
963      *
964      * @param thingHandler
965      */
966     protected void updateChannelDefinitions(Map<String, Channel> dynChannels) {
967         if (channelsCreated) {
968             return; // already done
969         }
970
971         try {
972             // Get subset of those channels that currently do not exist
973             List<Channel> existingChannels = getThing().getChannels();
974             for (Channel channel : existingChannels) {
975                 String id = channel.getUID().getId();
976                 if (dynChannels.containsKey(id)) {
977                     dynChannels.remove(id);
978                 }
979             }
980
981             if (!dynChannels.isEmpty()) {
982                 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
983                 ThingBuilder thingBuilder = editThing();
984                 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
985                     Channel c = channel.getValue();
986                     logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
987                     thingBuilder.withChannel(c);
988                 }
989                 updateThing(thingBuilder.build());
990                 logger.debug("{}: Channel definitions updated", thingName);
991             }
992         } catch (IllegalArgumentException e) {
993             logger.debug("{}: Unable to update channel definitions", thingName, e);
994         }
995     }
996
997     public boolean areChannelsCreated() {
998         return channelsCreated;
999     }
1000
1001     /**
1002      * Update thing properties with dynamic values
1003      *
1004      * @param profile The device profile
1005      * @param status the /status result
1006      */
1007     protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1008         Map<String, Object> properties = fillDeviceProperties(profile);
1009         String serviceName = getString(getThing().getProperties().get(PROPERTY_SERVICE_NAME));
1010         String hostname = getString(profile.settings.device.hostname).toLowerCase();
1011         if (serviceName.isEmpty()) {
1012             properties.put(PROPERTY_SERVICE_NAME, hostname);
1013             logger.trace("{}: Updated serrviceName to {}", thingName, hostname);
1014         }
1015         String deviceName = getString(profile.settings.name);
1016         if (!deviceName.isEmpty()) {
1017             properties.put(PROPERTY_DEV_NAME, deviceName);
1018         }
1019
1020         // add status properties
1021         if (status.wifiSta != null) {
1022             properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1023         }
1024         if (status.update != null) {
1025             properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1026             properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1027             properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1028             properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1029         }
1030         properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1031         properties.put(PROPERTY_COIOTREFRESH, String.valueOf(autoCoIoT));
1032
1033         Map<String, String> thingProperties = new TreeMap<>();
1034         for (Map.Entry<String, Object> property : properties.entrySet()) {
1035             thingProperties.put(property.getKey(), (String) property.getValue());
1036         }
1037         flushProperties(thingProperties);
1038     }
1039
1040     /**
1041      * Add one property to the Thing Properties
1042      *
1043      * @param key Name of the property
1044      * @param value Value of the property
1045      */
1046     public void updateProperties(String key, String value) {
1047         Map<String, String> thingProperties = editProperties();
1048         if (thingProperties.containsKey(key)) {
1049             thingProperties.replace(key, value);
1050         } else {
1051             thingProperties.put(key, value);
1052         }
1053         updateProperties(thingProperties);
1054         logger.trace("{}: Properties updated", thingName);
1055     }
1056
1057     public void flushProperties(Map<String, String> propertyUpdates) {
1058         Map<String, String> thingProperties = editProperties();
1059         for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1060             if (thingProperties.containsKey(property.getKey())) {
1061                 thingProperties.replace(property.getKey(), property.getValue());
1062             } else {
1063                 thingProperties.put(property.getKey(), property.getValue());
1064             }
1065         }
1066         updateProperties(thingProperties);
1067     }
1068
1069     /**
1070      * Get one property from the Thing Properties
1071      *
1072      * @param key property name
1073      * @return property value or "" if property is not set
1074      */
1075     public String getProperty(String key) {
1076         Map<String, String> thingProperties = getThing().getProperties();
1077         return getString(thingProperties.get(key));
1078     }
1079
1080     /**
1081      * Fill Thing Properties with device attributes
1082      *
1083      * @param profile Property Map to full
1084      * @return a full property map
1085      */
1086     public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1087         Map<String, Object> properties = new TreeMap<>();
1088         properties.put(PROPERTY_VENDOR, VENDOR);
1089         if (profile.isInitialized()) {
1090             properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1091             properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1092             properties.put(PROPERTY_FIRMWARE_VERSION,
1093                     profile.fwVersion + "/" + profile.fwDate + "(" + profile.fwId + ")");
1094             properties.put(PROPERTY_DEV_MODE, profile.mode);
1095             properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1096             properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1097             properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1098             properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1099             if (!profile.hwRev.isEmpty()) {
1100                 properties.put(PROPERTY_HWREV, profile.hwRev);
1101                 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1102             }
1103         }
1104         return properties;
1105     }
1106
1107     /**
1108      * Return device profile.
1109      *
1110      * @param ForceRefresh true=force refresh before returning, false=return without
1111      *            refresh
1112      * @return ShellyDeviceProfile instance
1113      * @throws ShellyApiException
1114      */
1115     public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1116         try {
1117             refreshSettings |= forceRefresh;
1118             if (refreshSettings) {
1119                 profile = api.getDeviceProfile(thingType);
1120                 if (!isThingOnline()) {
1121                     logger.debug("{}:Device profile re-initialized (thingType={})", thingName, thingType);
1122                 }
1123             }
1124         } finally {
1125             refreshSettings = false;
1126         }
1127         return profile;
1128     }
1129
1130     public ShellyDeviceProfile getProfile() {
1131         return profile;
1132     }
1133
1134     protected ShellyHttpApi getShellyApi() {
1135         return api;
1136     }
1137
1138     protected ShellyDeviceProfile getDeviceProfile() {
1139         return profile;
1140     }
1141
1142     public void triggerChannel(String group, String channel, String payload) {
1143         triggerChannel(mkChannelId(group, channel), payload);
1144     }
1145
1146     public void stop() {
1147         logger.debug("{}: Shutting down", thingName);
1148         ScheduledFuture<?> job = this.statusJob;
1149         if (job != null) {
1150             job.cancel(true);
1151             statusJob = null;
1152             logger.debug("{}: Shelly statusJob stopped", thingName);
1153         }
1154         job = asyncButtonRelease;
1155         if (job != null) {
1156             job.cancel(true);
1157             asyncButtonRelease = null;
1158         }
1159
1160         coap.stop();
1161         profile.initialized = false;
1162     }
1163
1164     /**
1165      * Shutdown thing, make sure background jobs are canceled
1166      */
1167     @Override
1168     public void dispose() {
1169         stopping = true;
1170         stop();
1171         super.dispose();
1172     }
1173
1174     /**
1175      * Device specific command handlers are overriding this method to do additional stuff
1176      */
1177     public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1178         return false;
1179     }
1180
1181     /**
1182      * Device specific handlers are overriding this method to do additional stuff
1183      */
1184     public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1185         return false;
1186     }
1187
1188     public ShellyDeviceStats getStats() {
1189         return stats;
1190     }
1191
1192     public Map<String, String> getStatsProp() {
1193         return stats.asProperties(getString(profile.settings.timezone));
1194     }
1195
1196     public void resetStats() {
1197         // reset statistics
1198         stats = new ShellyDeviceStats();
1199     }
1200 }