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