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