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