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