]> git.basschouten.com Git - openhab-addons.git/blob
ab4b2024ac2f1c8e8e6d28c79fb7c78a873eed04
[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.warn("{}: 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 = (int) getNumber(command);
348                     value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
349                             : 0;
350                     api.setSleepTime(value);
351                     break;
352                 case CHANNEL_CONTROL_PROFILE:
353                     logger.debug("{}: Select profile {}", thingName, command);
354                     int profile = (int) getNumber(command);
355                     if (profile < 0 || profile > 5) {
356                         logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
357                         break;
358                     }
359                     api.setProfile(0, profile);
360                     break;
361                 case CHANNEL_CONTROL_MODE:
362                     logger.debug("{}: Set mode to {}", thingName, command);
363                     api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
364                     break;
365                 case CHANNEL_CONTROL_SETTEMP:
366                     logger.debug("{}: Set temperature to {}", thingName, command);
367                     api.setTemperature(0, (int) getNumber(command));
368                     break;
369                 case CHANNEL_CONTROL_POSITION:
370                     logger.debug("{}: Set position to {}", thingName, command);
371                     api.setValvePosition(0, getNumber(command));
372                     break;
373                 case CHANNEL_CONTROL_BCONTROL:
374                     logger.debug("{}: Set boost mode to {}", thingName, command);
375                     api.startBoost(0, command == OnOffType.ON ? -1 : 0);
376                     break;
377                 case CHANNEL_CONTROL_BTIMER:
378                     logger.debug("{}: Set boost timer to {}", thingName, command);
379                     api.setBoostTime(0, (int) getNumber(command));
380                     break;
381
382                 default:
383                     update = handleDeviceCommand(channelUID, command);
384                     break;
385             }
386
387             restartWatchdog();
388             if (update && !autoCoIoT && !isUpdateScheduled()) {
389                 logger.debug("{}: Command process, request status update", thingName);
390                 requestUpdates(1, false);
391             }
392         } catch (ShellyApiException e) {
393             ShellyApiResult res = e.getApiResult();
394             if (isAuthorizationFailed(res)) {
395                 return;
396             }
397             if (res.isNotCalibrtated()) {
398                 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
399             } else {
400                 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
401                         e.toString());
402             }
403         } catch (IllegalArgumentException e) {
404             logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
405         }
406     }
407
408     private double getNumber(Command command) {
409         if (command instanceof QuantityType) {
410             return ((QuantityType<?>) command).doubleValue();
411         }
412         if (command instanceof DecimalType) {
413             return ((DecimalType) command).doubleValue();
414         }
415         if (command instanceof Number) {
416             return ((Number) command).doubleValue();
417         }
418         throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
419     }
420
421     /**
422      * Update device status and channels
423      */
424     protected void refreshStatus() {
425         try {
426             boolean updated = false;
427
428             if (vibrationFilter > 0) {
429                 vibrationFilter--;
430                 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
431                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
432             }
433
434             skipUpdate++;
435             ThingStatus thingStatus = getThing().getStatus();
436             if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
437                 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
438                         || (thingStatus == ThingStatus.UNKNOWN)) {
439                     logger.debug("{}: Status update triggered thing initialization", thingName);
440                     initializeThing(); // may fire an exception if initialization failed
441                 }
442                 // Get profile, if refreshSettings == true reload settings from device
443                 logger.trace("{}: Updating status (scheduledUpdates={}, refreshSettings={})", thingName,
444                         scheduledUpdates, refreshSettings);
445                 ShellySettingsStatus status = api.getStatus();
446                 boolean restarted = checkRestarted(status);
447                 profile = getProfile(refreshSettings || restarted);
448                 profile.status = status;
449                 profile.updateFromStatus(status);
450                 if (restarted) {
451                     logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
452                     stats.restarts++;
453                     postEvent(ALARM_TYPE_RESTARTED, true);
454                 }
455
456                 // If status update was successful the thing must be online
457                 setThingOnline();
458
459                 // map status to channels
460                 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
461                 updated |= this.updateDeviceStatus(status);
462                 updated |= ShellyComponents.updateDeviceStatus(this, status);
463                 fillDeviceStatus(status, updated);
464                 updated |= updateInputs(status);
465                 updated |= updateMeters(this, status);
466                 updated |= updateSensors(this, status);
467
468                 // All channels must be created after the first cycle
469                 channelsCreated = true;
470
471                 // Restart watchdog when status update was successful (no exception)
472                 restartWatchdog();
473             }
474         } catch (ShellyApiException e) {
475             // http call failed: go offline except for battery devices, which might be in
476             // sleep mode. Once the next update is successful the device goes back online
477             String status = "";
478             ShellyApiResult res = e.getApiResult();
479             if (isWatchdogStarted()) {
480                 if (!isWatchdogExpired()) {
481                     logger.debug("{}: Ignore API Timeout, retry later", thingName);
482                 } else {
483                     if (isThingOnline()) {
484                         status = "offline.status-error-watchdog";
485                     }
486                 }
487             } else if (res.isHttpAccessUnauthorized()) {
488                 status = "offline.conf-error-access-denied";
489             } else if (e.isJSONException()) {
490                 status = "offline.status-error-unexpected-api-result";
491                 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
492             } else if (res.isHttpTimeout()) {
493                 // Watchdog not started, e.g. device in sleep mode
494                 if (isThingOnline()) { // ignore when already offline
495                     status = "offline.status-error-watchdog";
496                 }
497             } else {
498                 status = "offline.status-error-unexpected-api-result";
499                 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
500             }
501
502             if (!status.isEmpty()) {
503                 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
504             }
505         } catch (NullPointerException | IllegalArgumentException e) {
506             logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
507         } finally {
508             if (scheduledUpdates > 0) {
509                 --scheduledUpdates;
510                 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
511             } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
512                 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
513                         cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
514                 cache.enable();
515             }
516         }
517     }
518
519     public boolean isThingOnline() {
520         return getThing().getStatus() == ThingStatus.ONLINE;
521     }
522
523     public boolean isThingOffline() {
524         return getThing().getStatus() == ThingStatus.OFFLINE;
525     }
526
527     @Override
528     public void setThingOnline() {
529         if (!isThingOnline()) {
530             updateStatus(ThingStatus.ONLINE);
531
532             // request 3 updates in a row (during the first 2+3*3 sec)
533             logger.debug("{}: Thing went online, request status update", thingName);
534             requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
535         }
536         restartWatchdog();
537     }
538
539     @Override
540     public void setThingOffline(ThingStatusDetail detail, String messageKey) {
541         if (!isThingOffline()) {
542             updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey));
543             watchdog = 0;
544             channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
545         }
546     }
547
548     public synchronized void restartWatchdog() {
549         watchdog = now();
550         updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
551         logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
552     }
553
554     private boolean isWatchdogExpired() {
555         long delta = now() - watchdog;
556         if ((watchdog > 0) && (delta > profile.updatePeriod)) {
557             stats.remainingWatchdog = delta;
558             return true;
559         }
560         return false;
561     }
562
563     private boolean isWatchdogStarted() {
564         return watchdog > 0;
565     }
566
567     public void reinitializeThing() {
568         logger.debug("{}: Re-Initialize Thing", thingName);
569         updateStatus(ThingStatus.UNKNOWN);
570         requestUpdates(0, true);
571     }
572
573     private void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
574         String alarm = "";
575
576         // Update uptime and WiFi, internal temp
577         ShellyComponents.updateDeviceStatus(this, status);
578         stats.wifiRssi = status.wifiSta.rssi;
579
580         if (api.isInitialized()) {
581             stats.timeoutErrors = api.getTimeoutErrors();
582             stats.timeoutsRecorvered = api.getTimeoutsRecovered();
583         }
584         stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
585
586         // Check various device indicators like overheating
587         if (checkRestarted(status)) {
588             // Force re-initialization on next status update
589             if (profile.alwaysOn) {
590                 reinitializeThing();
591             }
592         } else if (getBool(status.overtemperature)) {
593             alarm = ALARM_TYPE_OVERTEMP;
594         } else if (getBool(status.overload)) {
595             alarm = ALARM_TYPE_OVERLOAD;
596         } else if (getBool(status.loaderror)) {
597             alarm = ALARM_TYPE_LOADERR;
598         }
599         State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
600         if (internalTemp != UnDefType.NULL) {
601             int temp = ((Number) internalTemp).intValue();
602             if (temp > stats.maxInternalTemp) {
603                 logger.debug("{}: Max Internal Temp for device changed to {}", thingName, temp);
604                 stats.maxInternalTemp = temp;
605             }
606         }
607
608         stats.lastUptime = getLong(status.uptime);
609         stats.coiotMessages = coap.getMessageCount();
610         stats.coiotErrors = coap.getErrorCount();
611
612         if (!alarm.isEmpty()) {
613             postEvent(alarm, false);
614         }
615     }
616
617     /**
618      * Check if device has restarted and needs a new Thing initialization
619      *
620      * @return true: restart detected
621      */
622
623     private boolean checkRestarted(ShellySettingsStatus status) {
624         if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
625                 && (status.uptime < stats.lastUptime || !profile.status.update.oldVersion.isEmpty()
626                         && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
627             updateProperties(profile, status);
628             return true;
629         }
630         return false;
631     }
632
633     /**
634      * Save alarm to the lastAlarm channel
635      *
636      * @param alarm Alarm Message
637      */
638     public void postEvent(String event, boolean force) {
639         String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
640         State value = cache.getValue(channelId);
641         String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
642
643         if (force || !lastAlarm.equals(event)
644                 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
645             switch (event) {
646                 case "0": // DW2 1.8
647                 case SHELLY_WAKEUPT_SENSOR:
648                 case SHELLY_WAKEUPT_PERIODIC:
649                 case SHELLY_WAKEUPT_BUTTON:
650                 case SHELLY_WAKEUPT_POWERON:
651                 case SHELLY_WAKEUPT_UNKNOWN:
652                     logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
653                 case "":
654                 case ALARM_TYPE_NONE:
655                     break;
656                 default:
657                     logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
658                     triggerChannel(channelId, event);
659                     cache.updateChannel(channelId, getStringType(event));
660                     stats.lastAlarm = event;
661                     stats.lastAlarmTs = now();
662                     stats.alarms++;
663             }
664         }
665     }
666
667     /**
668      * Callback for device events
669      *
670      * @param deviceName device receiving the event
671      * @param parameters parameters from the event URL
672      * @param data the HTML input data
673      * @return true if event was processed
674      */
675     @Override
676     public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
677             Map<String, String> parameters) {
678         if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
679             logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
680                     parameters);
681             int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
682             if (!profile.isInitialized()) {
683                 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
684                 requestUpdates(1, true);
685             } else {
686                 String group = profile.getControlGroup(idx);
687                 if (group.isEmpty()) {
688                     logger.debug("{}: Unsupported event class: {}", thingName, type);
689                     return false;
690                 }
691
692                 // map some of the events to system defined button triggers
693                 String channel = "";
694                 String onoff = "";
695                 String payload = "";
696                 String parmType = getString(parameters.get("type"));
697                 String event = !parmType.isEmpty() ? parmType : type;
698                 boolean isButton = profile.inButtonMode(idx - 1);
699                 switch (event) {
700                     case SHELLY_EVENT_SHORTPUSH:
701                     case SHELLY_EVENT_DOUBLE_SHORTPUSH:
702                     case SHELLY_EVENT_TRIPLE_SHORTPUSH:
703                     case SHELLY_EVENT_LONGPUSH:
704                         if (isButton) {
705                             triggerButton(group, idx, mapButtonEvent(event));
706                             channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
707                             payload = ShellyApiJsonDTO.mapButtonEvent(event);
708                         } else {
709                             logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
710                                     thingName);
711                         }
712                         break;
713                     case SHELLY_EVENT_BTN_ON:
714                     case SHELLY_EVENT_BTN_OFF:
715                         if (profile.isRGBW2) {
716                             // RGBW2 has only one input, so not per channel
717                             group = CHANNEL_GROUP_LIGHT_CONTROL;
718                         }
719                         onoff = CHANNEL_INPUT;
720                         break;
721                     case SHELLY_EVENT_BTN1_ON:
722                     case SHELLY_EVENT_BTN1_OFF:
723                         onoff = CHANNEL_INPUT1;
724                         break;
725                     case SHELLY_EVENT_BTN2_ON:
726                     case SHELLY_EVENT_BTN2_OFF:
727                         onoff = CHANNEL_INPUT2;
728                         break;
729                     case SHELLY_EVENT_OUT_ON:
730                     case SHELLY_EVENT_OUT_OFF:
731                         onoff = CHANNEL_OUTPUT;
732                         break;
733                     case SHELLY_EVENT_ROLLER_OPEN:
734                     case SHELLY_EVENT_ROLLER_CLOSE:
735                     case SHELLY_EVENT_ROLLER_STOP:
736                         channel = CHANNEL_EVENT_TRIGGER;
737                         payload = event;
738                         break;
739                     case SHELLY_EVENT_SENSORREPORT:
740                         // process sensor with next refresh
741                         break;
742                     case SHELLY_EVENT_TEMP_OVER: // DW2
743                     case SHELLY_EVENT_TEMP_UNDER:
744                         channel = CHANNEL_EVENT_TRIGGER;
745                         payload = event;
746                         break;
747                     case SHELLY_EVENT_FLOOD_DETECTED:
748                     case SHELLY_EVENT_FLOOD_GONE:
749                         updateChannel(group, CHANNEL_SENSOR_FLOOD,
750                                 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
751                         break;
752
753                     case SHELLY_EVENT_CLOSE: // DW 1.7
754                     case SHELLY_EVENT_OPEN: // DW 1.7
755                         updateChannel(group, CHANNEL_SENSOR_STATE,
756                                 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
757                                         : OpenClosedType.CLOSED);
758                         break;
759
760                     case SHELLY_EVENT_DARK: // DW 1.7
761                     case SHELLY_EVENT_TWILIGHT: // DW 1.7
762                     case SHELLY_EVENT_BRIGHT: // DW 1.7
763                         updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
764                         break;
765
766                     case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
767                     case SHELLY_EVENT_ALARM_HEAVY:
768                     case SHELLY_EVENT_ALARM_OFF:
769                     case SHELLY_EVENT_VIBRATION: // DW2
770                         channel = CHANNEL_SENSOR_ALARM_STATE;
771                         payload = event.toUpperCase();
772                         break;
773
774                     default:
775                         // trigger will be provided by input/output channel or sensor channels
776                 }
777
778                 if (!onoff.isEmpty()) {
779                     updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
780                 }
781                 if (!payload.isEmpty()) {
782                     // Pass event to trigger channel
783                     payload = payload.toUpperCase();
784                     logger.debug("{}: Post event {}", thingName, payload);
785                     triggerChannel(mkChannelId(group, channel), payload);
786                 }
787             }
788
789             // request update on next interval (2x for non-battery devices)
790             restartWatchdog();
791             requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
792             return true;
793         }
794         return false;
795     }
796
797     /**
798      * Initialize the binding's thing configuration, calc update counts
799      */
800     protected void initializeThingConfig() {
801         thingType = getThing().getThingTypeUID().getId();
802         final Map<String, String> properties = getThing().getProperties();
803         thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
804         if (thingName.isEmpty()) {
805             thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
806             logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
807         }
808
809         config = getConfigAs(ShellyThingConfiguration.class);
810         if (config.deviceIp.isEmpty()) {
811             logger.warn("{}: IP address for the device must not be empty", thingName); // may not set in .things file
812             return;
813         }
814         try {
815             InetAddress addr = InetAddress.getByName(config.deviceIp);
816             String saddr = addr.getHostAddress();
817             if (!config.deviceIp.equals(saddr)) {
818                 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
819                 config.deviceIp = saddr;
820             }
821         } catch (UnknownHostException e) {
822             logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
823         }
824
825         config.localIp = localIP;
826         config.localPort = localPort;
827         if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
828             config.userId = bindingConfig.defaultUserId;
829             config.password = bindingConfig.defaultPassword;
830             logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
831         }
832         if (config.updateInterval == 0) {
833             config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
834         }
835         if (config.updateInterval < UPDATE_MIN_DELAY) {
836             config.updateInterval = UPDATE_MIN_DELAY;
837         }
838
839         // Try to get updatePeriod from properties
840         // For battery devinities the REST call to get the settings will most likely fail, because the device is in
841         // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
842         // initialized successfully by the REST call.
843         String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
844         if (!lastPeriod.isEmpty()) {
845             int period = Integer.parseInt(lastPeriod);
846             if (period > 0) {
847                 profile.updatePeriod = period;
848             }
849         }
850
851         skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
852         logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
853     }
854
855     private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
856         try {
857             ShellyVersionDTO version = new ShellyVersionDTO();
858             if (version.checkBeta(getString(prf.fwVersion))) {
859                 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
860             } else {
861                 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
862                     logger.warn("{}: {}", prf.hostname,
863                             messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
864                 }
865             }
866             if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
867                     || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
868                 if (!config.eventsCoIoT) {
869                     logger.debug("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
870                 }
871                 autoCoIoT = true;
872             }
873             if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
874                 logger.info("{}: {}", thingName,
875                         messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
876             }
877         } catch (NullPointerException e) { // could be inconsistant format of beta version
878             logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
879         }
880     }
881
882     /**
883      * Checks the http response for authorization error.
884      * If the authorization failed the binding can't access the device settings and determine the thing type. In this
885      * case the thing type shelly-unknown is set.
886      *
887      * @param response exception details including the http respone
888      * @return true if the authorization failed
889      */
890     private boolean isAuthorizationFailed(ShellyApiResult result) {
891         if (result.isHttpAccessUnauthorized()) {
892             // If the device is password protected the API doesn't provide settings to the device settings
893             logger.warn("{}: {}", thingName, messages.get("init.protected"));
894             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
895             return true;
896         }
897         return false;
898     }
899
900     /**
901      * Change type of this thing.
902      *
903      * @param thingType thing type acc. to the xml definition
904      * @param mode Device mode (e.g. relay, roller)
905      */
906     private void changeThingType(String thingType, String mode) {
907         ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
908         if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
909             logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
910             Map<String, String> properties = editProperties();
911             properties.replace(PROPERTY_DEV_TYPE, thingType);
912             properties.replace(PROPERTY_DEV_MODE, mode);
913             updateProperties(properties);
914             changeThingType(thingTypeUID, getConfig());
915         }
916     }
917
918     @Override
919     public void thingUpdated(Thing thing) {
920         logger.debug("{}: Channel definitions updated.", thingName);
921         super.thingUpdated(thing);
922     }
923
924     /**
925      * Start the background updates
926      */
927     protected void startUpdateJob() {
928         ScheduledFuture<?> statusJob = this.statusJob;
929         if ((statusJob == null) || statusJob.isCancelled()) {
930             this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
931                     TimeUnit.SECONDS);
932             logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
933                     UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
934         }
935     }
936
937     /**
938      * Flag the status job to do an exceptional update (something happened) rather
939      * than waiting until the next regular poll
940      *
941      * @param requestCount number of polls to execute
942      * @param refreshSettings true=force a /settings query
943      * @return true=Update schedule, false=skipped (too many updates already
944      *         scheduled)
945      */
946     @Override
947     public boolean requestUpdates(int requestCount, boolean refreshSettings) {
948         this.refreshSettings |= refreshSettings;
949         if (refreshSettings) {
950             if (requestCount == 0) {
951                 logger.debug("{}: Request settings refresh", thingName);
952             }
953             scheduledUpdates = 1;
954             return true;
955         }
956         if (scheduledUpdates < 10) { // < 30s
957             scheduledUpdates += requestCount;
958             return true;
959         }
960         return false;
961     }
962
963     public boolean isUpdateScheduled() {
964         return scheduledUpdates > 0;
965     }
966
967     /**
968      * Map input states to channels
969      *
970      * @param groupName Channel Group (relay / relay1...)
971      *
972      * @param status Shelly device status
973      * @return true: one or more inputs were updated
974      */
975     public boolean updateInputs(ShellySettingsStatus status) {
976         boolean updated = false;
977
978         if (status.inputs != null) {
979             int idx = 0;
980             boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
981             for (ShellyInputState input : status.inputs) {
982                 String group = profile.getControlGroup(idx);
983                 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
984
985                 if (!areChannelsCreated()) {
986                     updateChannelDefinitions(
987                             ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
988                 }
989
990                 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
991                 if (input.event != null) {
992                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
993                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
994                 }
995                 idx++;
996             }
997         } else {
998             if (status.input != null) {
999                 // RGBW2: a single int rather than an array
1000                 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1001                         getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1002             }
1003         }
1004         return updated;
1005     }
1006
1007     public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1008         boolean changed = false;
1009         if (valueArray != null && !valueArray.isEmpty()) {
1010             String reason = getString((String) valueArray.get(0));
1011             String newVal = valueArray.toString();
1012             changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1013             changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1014             if (changed) {
1015                 postEvent(reason.toUpperCase(), true);
1016             }
1017             lastWakeupReason = newVal;
1018         }
1019         return changed;
1020     }
1021
1022     public void triggerButton(String group, int idx, String value) {
1023         String trigger = mapButtonEvent(value);
1024         if (trigger.isEmpty()) {
1025             return;
1026         }
1027
1028         logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1029         triggerChannel(group,
1030                 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1031                 trigger);
1032         updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1033         if (profile.alwaysOn) {
1034             // refresh status of the input channel
1035             requestUpdates(1, false);
1036         }
1037     }
1038
1039     public void publishState(String channelId, State value) {
1040         String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1041         if (!stopping && isLinked(id)) {
1042             updateState(id, value);
1043             logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1044         }
1045     }
1046
1047     public boolean updateChannel(String group, String channel, State value) {
1048         return updateChannel(mkChannelId(group, channel), value, false);
1049     }
1050
1051     public boolean updateChannel(String channelId, State value, boolean force) {
1052         return !stopping && cache.updateChannel(channelId, value, force);
1053     }
1054
1055     @Override
1056     public State getChannelValue(String group, String channel) {
1057         return cache.getValue(group, channel);
1058     }
1059
1060     public double getChannelDouble(String group, String channel) {
1061         State value = getChannelValue(group, channel);
1062         if (value != UnDefType.NULL) {
1063             if (value instanceof QuantityType) {
1064                 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1065             }
1066             if (value instanceof DecimalType) {
1067                 return ((DecimalType) value).doubleValue();
1068             }
1069         }
1070         return -1;
1071     }
1072
1073     /**
1074      * Update Thing's channels according to available status information from the API
1075      *
1076      * @param thingHandler
1077      */
1078     protected void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1079         if (channelsCreated) {
1080             return; // already done
1081         }
1082
1083         try {
1084             // Get subset of those channels that currently do not exist
1085             List<Channel> existingChannels = getThing().getChannels();
1086             for (Channel channel : existingChannels) {
1087                 String id = channel.getUID().getId();
1088                 if (dynChannels.containsKey(id)) {
1089                     dynChannels.remove(id);
1090                 }
1091             }
1092
1093             if (!dynChannels.isEmpty()) {
1094                 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1095                 ThingBuilder thingBuilder = editThing();
1096                 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1097                     Channel c = channel.getValue();
1098                     logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1099                     thingBuilder.withChannel(c);
1100                 }
1101                 updateThing(thingBuilder.build());
1102                 logger.debug("{}: Channel definitions updated", thingName);
1103             }
1104         } catch (IllegalArgumentException e) {
1105             logger.debug("{}: Unable to update channel definitions", thingName, e);
1106         }
1107     }
1108
1109     public boolean areChannelsCreated() {
1110         return channelsCreated;
1111     }
1112
1113     /**
1114      * Update thing properties with dynamic values
1115      *
1116      * @param profile The device profile
1117      * @param status the /status result
1118      */
1119     protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1120         logger.debug("{}: Update properties", thingName);
1121         Map<String, Object> properties = fillDeviceProperties(profile);
1122         String serviceName = getString(getThing().getProperties().get(PROPERTY_SERVICE_NAME));
1123         String hostname = getString(profile.settings.device.hostname).toLowerCase();
1124         if (serviceName.isEmpty()) {
1125             properties.put(PROPERTY_SERVICE_NAME, hostname);
1126             logger.trace("{}: Updated serrviceName to {}", thingName, hostname);
1127         }
1128         String deviceName = getString(profile.settings.name);
1129         if (!deviceName.isEmpty()) {
1130             properties.put(PROPERTY_DEV_NAME, deviceName);
1131         }
1132
1133         // add status properties
1134         if (status.wifiSta != null) {
1135             properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1136         }
1137         if (status.update != null) {
1138             properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1139             properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1140             properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1141             properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1142         }
1143         properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1144
1145         Map<String, String> thingProperties = new TreeMap<>();
1146         for (Map.Entry<String, Object> property : properties.entrySet()) {
1147             thingProperties.put(property.getKey(), (String) property.getValue());
1148         }
1149         flushProperties(thingProperties);
1150     }
1151
1152     /**
1153      * Add one property to the Thing Properties
1154      *
1155      * @param key Name of the property
1156      * @param value Value of the property
1157      */
1158     public void updateProperties(String key, String value) {
1159         Map<String, String> thingProperties = editProperties();
1160         if (thingProperties.containsKey(key)) {
1161             thingProperties.replace(key, value);
1162         } else {
1163             thingProperties.put(key, value);
1164         }
1165         updateProperties(thingProperties);
1166         logger.trace("{}: Properties updated", thingName);
1167     }
1168
1169     public void flushProperties(Map<String, String> propertyUpdates) {
1170         Map<String, String> thingProperties = editProperties();
1171         for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1172             if (thingProperties.containsKey(property.getKey())) {
1173                 thingProperties.replace(property.getKey(), property.getValue());
1174             } else {
1175                 thingProperties.put(property.getKey(), property.getValue());
1176             }
1177         }
1178         updateProperties(thingProperties);
1179     }
1180
1181     /**
1182      * Get one property from the Thing Properties
1183      *
1184      * @param key property name
1185      * @return property value or "" if property is not set
1186      */
1187     public String getProperty(String key) {
1188         Map<String, String> thingProperties = getThing().getProperties();
1189         return getString(thingProperties.get(key));
1190     }
1191
1192     /**
1193      * Fill Thing Properties with device attributes
1194      *
1195      * @param profile Property Map to full
1196      * @return a full property map
1197      */
1198     public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1199         Map<String, Object> properties = new TreeMap<>();
1200         properties.put(PROPERTY_VENDOR, VENDOR);
1201         if (profile.isInitialized()) {
1202             properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1203             properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1204             properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1205             properties.put(PROPERTY_DEV_MODE, profile.mode);
1206             properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1207             properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1208             properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1209             properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1210             if (!profile.hwRev.isEmpty()) {
1211                 properties.put(PROPERTY_HWREV, profile.hwRev);
1212                 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1213             }
1214         }
1215         return properties;
1216     }
1217
1218     /**
1219      * Return device profile.
1220      *
1221      * @param ForceRefresh true=force refresh before returning, false=return without
1222      *            refresh
1223      * @return ShellyDeviceProfile instance
1224      * @throws ShellyApiException
1225      */
1226     @Override
1227     public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1228         try {
1229             refreshSettings |= forceRefresh;
1230             if (refreshSettings) {
1231                 profile = api.getDeviceProfile(thingType);
1232                 if (!isThingOnline()) {
1233                     logger.debug("{}:Device profile re-initialized (thingType={})", thingName, thingType);
1234                 }
1235             }
1236         } finally {
1237             refreshSettings = false;
1238         }
1239         return profile;
1240     }
1241
1242     @Override
1243     public ShellyDeviceProfile getProfile() {
1244         return profile;
1245     }
1246
1247     protected ShellyHttpApi getShellyApi() {
1248         return api;
1249     }
1250
1251     protected ShellyDeviceProfile getDeviceProfile() {
1252         return profile;
1253     }
1254
1255     public void triggerChannel(String group, String channel, String payload) {
1256         String triggerCh = mkChannelId(group, channel);
1257         logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1258         if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1259             if (vibrationFilter == 0) {
1260                 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1261                 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1262                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1263             } else {
1264                 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1265                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1266                 return;
1267             }
1268         }
1269
1270         triggerChannel(triggerCh, payload);
1271     }
1272
1273     public void stop() {
1274         logger.debug("{}: Shutting down", thingName);
1275         ScheduledFuture<?> job = this.statusJob;
1276         if (job != null) {
1277             job.cancel(true);
1278             statusJob = null;
1279             logger.debug("{}: Shelly statusJob stopped", thingName);
1280         }
1281
1282         coap.stop();
1283         profile.initialized = false;
1284     }
1285
1286     /**
1287      * Shutdown thing, make sure background jobs are canceled
1288      */
1289     @Override
1290     public void dispose() {
1291         stopping = true;
1292         stop();
1293         super.dispose();
1294     }
1295
1296     /**
1297      * Device specific command handlers are overriding this method to do additional stuff
1298      */
1299     public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1300         return false;
1301     }
1302
1303     /**
1304      * Device specific handlers are overriding this method to do additional stuff
1305      */
1306     public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1307         return false;
1308     }
1309
1310     @Override
1311     public String getThingName() {
1312         return thingName;
1313     }
1314
1315     @Override
1316     public void resetStats() {
1317         // reset statistics
1318         stats = new ShellyDeviceStats();
1319     }
1320
1321     @Override
1322     public ShellyDeviceStats getStats() {
1323         return stats;
1324     }
1325
1326     @Override
1327     public ShellyHttpApi getApi() {
1328         return api;
1329     }
1330
1331     public Map<String, String> getStatsProp() {
1332         return stats.asProperties();
1333     }
1334
1335     public String checkForUpdate() {
1336         try {
1337             ShellyOtaCheckResult result = api.checkForUpdate();
1338             return result.status;
1339         } catch (ShellyApiException e) {
1340             return "";
1341         }
1342     }
1343 }