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