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