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