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