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