]> git.basschouten.com Git - openhab-addons.git/blob
c76a181e45876651431176afeacf150c3075088b
[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         profile.initFromThingType(thingType); // do some basic initialization
277
278         // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
279         // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
280         // Action URL does when enabled)
281         if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
282             coap.start(thingName, config);
283         }
284
285         // Initialize API access, exceptions will be catched by initialize()
286         api.initialize();
287         ShellySettingsDevice devInfo = api.getDeviceInfo();
288         if (getBool(devInfo.auth) && config.password.isEmpty()) {
289             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
290             return false;
291         }
292         if (config.serviceName.isEmpty()) {
293             config.serviceName = getString(profile.hostname).toLowerCase();
294         }
295
296         api.setConfig(thingName, config);
297         ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
298         tmpPrf.isGen2 = gen2;
299         tmpPrf.auth = devInfo.auth; // missing in /settings
300
301         if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
302             changeThingType(thingName, tmpPrf.mode);
303             return false; // force re-initialization
304         }
305         // Validate device mode
306         String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
307         if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
308             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
309                     reqMode);
310             return false;
311         }
312         if (!getString(devInfo.coiot).isEmpty()) {
313             // New Shelly devices might use a different endpoint for the CoAP listener
314             tmpPrf.coiotEndpoint = devInfo.coiot;
315         }
316         if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
317             // Sensor, usually 12h, H&T in USB mode 10min
318             tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
319                     ? tmpPrf.settings.sleepMode.period * 60 // minutes
320                     : tmpPrf.settings.sleepMode.period * 3600; // hours
321             tmpPrf.updatePeriod += 60; // give 1min extra
322         } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
323             // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
324             tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
325                     2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
326         } else {
327             tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
328         }
329
330         tmpPrf.status = api.getStatus(); // update thing properties
331         tmpPrf.updateFromStatus(tmpPrf.status);
332         addStateOptions(tmpPrf);
333
334         // update thing properties
335         updateProperties(tmpPrf, tmpPrf.status);
336         checkVersion(tmpPrf, tmpPrf.status);
337
338         startCoap(config, tmpPrf);
339         if (!gen2 && !blu) {
340             api.setActionURLs(); // register event urls
341         }
342
343         // All initialization done, so keep the profile and set Thing to ONLINE
344         fillDeviceStatus(tmpPrf.status, false);
345         postEvent(ALARM_TYPE_NONE, false);
346
347         profile = tmpPrf;
348         showThingConfig(profile);
349
350         logger.debug("{}: Thing successfully initialized.", thingName);
351         updateProperties(profile, profile.status);
352         setThingOnline(); // if API call was successful the thing must be online
353         return true; // success
354     }
355
356     /**
357      * Handle Channel Commands
358      */
359     @Override
360     public void handleCommand(ChannelUID channelUID, Command command) {
361         try {
362             if (command instanceof RefreshType) {
363                 String channelId = channelUID.getId();
364                 State value = cache.getValue(channelId);
365                 if (value != UnDefType.NULL) {
366                     updateState(channelId, value);
367                 }
368                 return;
369             }
370
371             if (!profile.isInitialized()) {
372                 logger.debug("{}: {}", thingName, messages.get("command.init", command));
373                 initializeThing();
374             } else {
375                 profile = getProfile(false);
376             }
377
378             boolean update = false;
379             switch (channelUID.getIdWithoutGroup()) {
380                 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
381                     logger.debug("{}: Send key {}", thingName, command);
382                     api.sendIRKey(command.toString());
383                     update = true;
384                     break;
385
386                 case CHANNEL_LED_STATUS_DISABLE:
387                     logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
388                     api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
389                     break;
390                 case CHANNEL_LED_POWER_DISABLE:
391                     logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
392                     api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
393                     break;
394
395                 case CHANNEL_SENSOR_SLEEPTIME:
396                     logger.debug("{}: Set sensor sleep time to {}", thingName, command);
397                     int value = (int) getNumber(command);
398                     value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
399                             : 0;
400                     api.setSleepTime(value);
401                     break;
402                 case CHANNEL_CONTROL_SCHEDULE:
403                     if (profile.isTRV) {
404                         logger.debug("{}: {} Valve schedule/profile", thingName,
405                                 command == OnOffType.ON ? "Enable" : "Disable");
406                         api.setValveProfile(0,
407                                 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
408                     }
409                     break;
410                 case CHANNEL_CONTROL_PROFILE:
411                     logger.debug("{}: Select profile {}", thingName, command);
412                     int id = -1;
413                     if (command instanceof Number) {
414                         id = (int) getNumber(command);
415                     } else {
416                         String cmd = command.toString();
417                         if (isDigit(cmd.charAt(0))) {
418                             id = Integer.parseInt(cmd);
419                         } else if (profile.settings.thermostats != null) {
420                             ShellyThermnostat t = profile.settings.thermostats.get(0);
421                             for (int i = 0; i < t.profileNames.length; i++) {
422                                 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
423                                     id = i + 1;
424                                 }
425                             }
426                         }
427                     }
428                     if (id < 0 || id > 5) {
429                         logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
430                         break;
431                     }
432                     api.setValveProfile(0, id);
433                     break;
434                 case CHANNEL_CONTROL_MODE:
435                     logger.debug("{}: Set mode to {}", thingName, command);
436                     api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
437                     break;
438                 case CHANNEL_CONTROL_SETTEMP:
439                     logger.debug("{}: Set temperature to {}", thingName, command);
440                     api.setValveTemperature(0, (int) getNumber(command));
441                     break;
442                 case CHANNEL_CONTROL_POSITION:
443                     logger.debug("{}: Set position to {}", thingName, command);
444                     api.setValvePosition(0, getNumber(command));
445                     break;
446                 case CHANNEL_CONTROL_BCONTROL:
447                     logger.debug("{}: Set boost mode to {}", thingName, command);
448                     api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
449                     break;
450                 case CHANNEL_CONTROL_BTIMER:
451                     logger.debug("{}: Set boost timer to {}", thingName, command);
452                     api.setValveBoostTime(0, (int) getNumber(command));
453                     break;
454                 case CHANNEL_SENSOR_MUTE:
455                     if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
456                         logger.debug("{}: Mute Smoke Alarm", thingName);
457                         api.muteSmokeAlarm(0);
458                         updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
459                     }
460                     break;
461                 default:
462                     update = handleDeviceCommand(channelUID, command);
463                     break;
464             }
465
466             restartWatchdog();
467             if (update && !autoCoIoT && !isUpdateScheduled()) {
468                 requestUpdates(1, false);
469             }
470         } catch (ShellyApiException e) {
471             ShellyApiResult res = e.getApiResult();
472             if (isAuthorizationFailed(res)) {
473                 return;
474             }
475             if (res.isNotCalibrtated()) {
476                 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
477             } else {
478                 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
479                         e.toString());
480             }
481
482             String group = getString(channelUID.getGroupId());
483             String channel = getString(channelUID.getIdWithoutGroup());
484             State oldValue = getChannelValue(group, channel);
485             if (oldValue != UnDefType.NULL) {
486                 logger.info("{}: Restore channel value to {}", thingName, oldValue);
487                 updateChannel(group, channel, oldValue);
488             }
489
490         } catch (IllegalArgumentException e) {
491             logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
492         }
493     }
494
495     private double getNumber(Command command) {
496         if (command instanceof QuantityType quantityCommand) {
497             return quantityCommand.doubleValue();
498         }
499         if (command instanceof DecimalType decimalCommand) {
500             return decimalCommand.doubleValue();
501         }
502         if (command instanceof Number numberCommand) {
503             return numberCommand.doubleValue();
504         }
505         throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
506     }
507
508     /**
509      * Update device status and channels
510      */
511     protected void refreshStatus() {
512         try {
513             boolean updated = false;
514
515             if (vibrationFilter > 0) {
516                 vibrationFilter--;
517                 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
518                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
519             }
520
521             skipUpdate++;
522             ThingStatus thingStatus = getThing().getStatus();
523             if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
524                 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
525                         || (thingStatus == ThingStatus.UNKNOWN)) {
526                     logger.debug("{}: Status update triggered thing initialization", thingName);
527                     initializeThing(); // may fire an exception if initialization failed
528                 }
529                 ShellySettingsStatus status = api.getStatus();
530                 boolean restarted = checkRestarted(status);
531                 profile = getProfile(refreshSettings || restarted);
532                 profile.status = status;
533                 profile.updateFromStatus(status);
534                 if (restarted) {
535                     logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
536                     stats.restarts++;
537                     postEvent(ALARM_TYPE_RESTARTED, true);
538                 }
539
540                 // If status update was successful the thing must be online,
541                 // but not while firmware update is in progress
542                 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
543                     setThingOnline();
544                 }
545
546                 // map status to channels
547                 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
548                 updated |= this.updateDeviceStatus(status);
549                 updated |= ShellyComponents.updateDeviceStatus(this, status);
550                 fillDeviceStatus(status, updated);
551                 updated |= updateInputs(status);
552                 updated |= updateMeters(this, status);
553                 updated |= updateSensors(this, status);
554
555                 // All channels must be created after the first cycle
556                 channelsCreated = true;
557             }
558         } catch (ShellyApiException e) {
559             // http call failed: go offline except for battery devices, which might be in
560             // sleep mode. Once the next update is successful the device goes back online
561             String status = "";
562             ShellyApiResult res = e.getApiResult();
563             if (profile.alwaysOn && e.isConnectionError()) {
564                 status = "offline.status-error-connect";
565             } else if (res.isHttpAccessUnauthorized()) {
566                 status = "offline.conf-error-access-denied";
567             } else if (isWatchdogStarted()) {
568                 if (!isWatchdogExpired()) {
569                     if (profile.alwaysOn) { // suppress for battery powered sensors
570                         logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
571                     }
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 != null && !getString(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 event Alarm Message
815      * @param force
816      */
817     @Override
818     public void postEvent(String event, boolean force) {
819         String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
820         State value = cache.getValue(channelId);
821         String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
822
823         if (force || !lastAlarm.equals(event)
824                 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
825             switch (event.toUpperCase()) {
826                 case "":
827                 case "0": // DW2 1.8
828                 case SHELLY_WAKEUPT_SENSOR:
829                 case SHELLY_WAKEUPT_PERIODIC:
830                 case SHELLY_WAKEUPT_BUTTON:
831                 case SHELLY_WAKEUPT_POWERON:
832                 case SHELLY_WAKEUPT_EXT_POWER:
833                 case SHELLY_WAKEUPT_UNKNOWN:
834                     logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
835                 case ALARM_TYPE_NONE:
836                     break;
837                 default:
838                     logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
839                     triggerChannel(channelId, event);
840                     cache.updateChannel(channelId, getStringType(event.toUpperCase()));
841                     stats.lastAlarm = event;
842                     stats.lastAlarmTs = now();
843                     stats.alarms++;
844             }
845         }
846     }
847
848     public boolean isUpdateScheduled() {
849         return scheduledUpdates > 0;
850     }
851
852     /**
853      * Callback for device events
854      *
855      * @param address
856      * @param deviceName device receiving the event
857      * @param deviceIndex
858      * @param type the HTML input data
859      * @param parameters parameters from the event URL
860      * @return true if event was processed
861      */
862     @Override
863     public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
864             Map<String, String> parameters) {
865         if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
866                 || config.serviceName.equals(deviceName)) {
867             logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
868                     parameters);
869             int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
870             if (!profile.isInitialized()) {
871                 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
872                 requestUpdates(1, true);
873             } else {
874                 String group = profile.getControlGroup(idx);
875                 if (group.isEmpty()) {
876                     logger.debug("{}: Unsupported event class: {}", thingName, type);
877                     return false;
878                 }
879
880                 // map some of the events to system defined button triggers
881                 String channel = "";
882                 String onoff = "";
883                 String payload = "";
884                 String parmType = getString(parameters.get("type"));
885                 String event = !parmType.isEmpty() ? parmType : type;
886                 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
887                 switch (event) {
888                     case SHELLY_EVENT_SHORTPUSH:
889                     case SHELLY_EVENT_DOUBLE_SHORTPUSH:
890                     case SHELLY_EVENT_TRIPLE_SHORTPUSH:
891                     case SHELLY_EVENT_LONGPUSH:
892                         if (isButton) {
893                             triggerButton(group, idx, mapButtonEvent(event));
894                             channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
895                             payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
896                         } else {
897                             logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
898                                     thingName);
899                         }
900                         break;
901                     case SHELLY_EVENT_BTN_ON:
902                     case SHELLY_EVENT_BTN_OFF:
903                         if (profile.isRGBW2) {
904                             // RGBW2 has only one input, so not per channel
905                             group = CHANNEL_GROUP_LIGHT_CONTROL;
906                         }
907                         onoff = CHANNEL_INPUT;
908                         break;
909                     case SHELLY_EVENT_BTN1_ON:
910                     case SHELLY_EVENT_BTN1_OFF:
911                         onoff = CHANNEL_INPUT1;
912                         break;
913                     case SHELLY_EVENT_BTN2_ON:
914                     case SHELLY_EVENT_BTN2_OFF:
915                         onoff = CHANNEL_INPUT2;
916                         break;
917                     case SHELLY_EVENT_OUT_ON:
918                     case SHELLY_EVENT_OUT_OFF:
919                         onoff = CHANNEL_OUTPUT;
920                         break;
921                     case SHELLY_EVENT_ROLLER_OPEN:
922                     case SHELLY_EVENT_ROLLER_CLOSE:
923                     case SHELLY_EVENT_ROLLER_STOP:
924                         channel = CHANNEL_EVENT_TRIGGER;
925                         payload = event;
926                         break;
927                     case SHELLY_EVENT_SENSORREPORT:
928                         // process sensor with next refresh
929                         break;
930                     case SHELLY_EVENT_TEMP_OVER: // DW2
931                     case SHELLY_EVENT_TEMP_UNDER:
932                         channel = CHANNEL_EVENT_TRIGGER;
933                         payload = event;
934                         break;
935                     case SHELLY_EVENT_FLOOD_DETECTED:
936                     case SHELLY_EVENT_FLOOD_GONE:
937                         updateChannel(group, CHANNEL_SENSOR_FLOOD,
938                                 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
939                         break;
940
941                     case SHELLY_EVENT_CLOSE: // DW 1.7
942                     case SHELLY_EVENT_OPEN: // DW 1.7
943                         updateChannel(group, CHANNEL_SENSOR_STATE,
944                                 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
945                                         : OpenClosedType.CLOSED);
946                         break;
947
948                     case SHELLY_EVENT_DARK: // DW 1.7
949                     case SHELLY_EVENT_TWILIGHT: // DW 1.7
950                     case SHELLY_EVENT_BRIGHT: // DW 1.7
951                         updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
952                         break;
953
954                     case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
955                     case SHELLY_EVENT_ALARM_HEAVY:
956                     case SHELLY_EVENT_ALARM_OFF:
957                     case SHELLY_EVENT_VIBRATION: // DW2
958                         channel = CHANNEL_SENSOR_ALARM_STATE;
959                         payload = event.toUpperCase();
960                         break;
961
962                     default:
963                         // trigger will be provided by input/output channel or sensor channels
964                 }
965
966                 if (!onoff.isEmpty()) {
967                     updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
968                 }
969                 if (!payload.isEmpty()) {
970                     // Pass event to trigger channel
971                     payload = payload.toUpperCase();
972                     logger.debug("{}: Post event {}", thingName, payload);
973                     triggerChannel(mkChannelId(group, channel), payload);
974                 }
975             }
976
977             // request update on next interval (2x for non-battery devices)
978             restartWatchdog();
979             requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
980             return true;
981         }
982         return false;
983     }
984
985     /**
986      * Initialize the binding's thing configuration, calc update counts
987      */
988     protected void initializeThingConfig() {
989         thingType = getThing().getThingTypeUID().getId();
990         final Map<String, String> properties = getThing().getProperties();
991         thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
992         if (thingName.isEmpty()) {
993             thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
994         }
995
996         config = getConfigAs(ShellyThingConfiguration.class);
997         if (config.deviceAddress.isEmpty()) {
998             config.deviceAddress = config.deviceIp;
999         }
1000         if (config.deviceAddress.isEmpty()) {
1001             logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
1002                                                                                             // file
1003             return;
1004         }
1005
1006         config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
1007                                                                                     // convert to lower case
1008         if (!config.deviceIp.isEmpty()) {
1009             try {
1010                 InetAddress addr = InetAddress.getByName(config.deviceIp);
1011                 String saddr = addr.getHostAddress();
1012                 if (!config.deviceIp.equals(saddr)) {
1013                     logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1014                     config.deviceIp = saddr;
1015                 }
1016             } catch (UnknownHostException e) {
1017                 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1018             }
1019         }
1020
1021         config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1022         config.localIp = bindingConfig.localIP;
1023         config.localPort = String.valueOf(bindingConfig.httpPort);
1024         if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1025             // Gen2 has hard coded user "admin"
1026             config.userId = bindingConfig.defaultUserId;
1027             logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1028         }
1029         if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1030             config.password = bindingConfig.defaultPassword;
1031             logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1032         }
1033         if (config.updateInterval == 0) {
1034             config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1035         }
1036         if (config.updateInterval < UPDATE_MIN_DELAY) {
1037             config.updateInterval = UPDATE_MIN_DELAY;
1038         }
1039
1040         // Try to get updatePeriod from properties
1041         // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1042         // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1043         // initialized successfully by the REST call.
1044         String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1045         if (!lastPeriod.isEmpty()) {
1046             int period = Integer.parseInt(lastPeriod);
1047             if (period > 0) {
1048                 profile.updatePeriod = period;
1049             }
1050         }
1051
1052         skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1053         logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1054     }
1055
1056     private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1057         try {
1058             if (prf.fwVersion.isEmpty()) {
1059                 // no fw version available (e.g. BLU device)
1060                 return;
1061             }
1062
1063             ShellyVersionDTO version = new ShellyVersionDTO();
1064             if (version.checkBeta(getString(prf.fwVersion))) {
1065                 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1066             } else {
1067                 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1068                 if (version.compare(prf.fwVersion, minVersion) < 0) {
1069                     logger.warn("{}: {}", prf.hostname,
1070                             messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1071                 }
1072             }
1073             if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1074                     || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1075                 if (!config.eventsCoIoT) {
1076                     logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1077                 }
1078                 autoCoIoT = true;
1079             }
1080             if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1081                 logger.info("{}: {}", thingName,
1082                         messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1083             }
1084         } catch (NullPointerException e) { // could be inconsistant format of beta version
1085             logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1086         }
1087     }
1088
1089     public String checkForUpdate() {
1090         try {
1091             ShellyOtaCheckResult result = api.checkForUpdate();
1092             return result.status;
1093         } catch (ShellyApiException e) {
1094             return "";
1095         }
1096     }
1097
1098     public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1099         if (coap == null || !config.eventsCoIoT) {
1100             return;
1101         }
1102         if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1103             String devpeer = getString(profile.settings.coiot.peer);
1104             String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1105             if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1106                 try {
1107                     api.setCoIoTPeer(ourpeer);
1108                     logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1109                 } catch (ShellyApiException e) {
1110                     logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1111                 }
1112             } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1113                 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1114             }
1115         }
1116         if (autoCoIoT) {
1117             logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1118             config.eventsCoIoT = true;
1119             config.eventsSwitch = false;
1120             config.eventsButton = false;
1121             config.eventsPush = false;
1122             config.eventsRoller = false;
1123             config.eventsSensorReport = false;
1124             api.setConfig(thingName, config);
1125         }
1126
1127         logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1128         if (coap != null) {
1129             coap.start(thingName, config);
1130         }
1131     }
1132
1133     /**
1134      * Checks the http response for authorization error.
1135      * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1136      * case the thing type shelly-unknown is set.
1137      *
1138      * @param result exception details including the http respone
1139      * @return true if the authorization failed
1140      */
1141     protected boolean isAuthorizationFailed(ShellyApiResult result) {
1142         if (result.isHttpAccessUnauthorized()) {
1143             // If the device is password protected the API doesn't provide settings to the device settings
1144             setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1145             return true;
1146         }
1147         return false;
1148     }
1149
1150     /**
1151      * Change type of this thing.
1152      *
1153      * @param thingType thing type acc. to the xml definition
1154      * @param mode Device mode (e.g. relay, roller)
1155      */
1156     protected void changeThingType(String thingType, String mode) {
1157         String deviceType = substringBefore(thingType, "-");
1158         ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1159         if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1160             logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1161             Map<String, String> properties = editProperties();
1162             properties.replace(PROPERTY_DEV_TYPE, deviceType);
1163             properties.replace(PROPERTY_DEV_MODE, mode);
1164             updateProperties(properties);
1165             changeThingType(thingTypeUID, getConfig());
1166         }
1167     }
1168
1169     @Override
1170     public void thingUpdated(Thing thing) {
1171         logger.debug("{}: Channel definitions updated.", thingName);
1172         super.thingUpdated(thing);
1173     }
1174
1175     /**
1176      * Start the background updates
1177      */
1178     protected void startUpdateJob() {
1179         ScheduledFuture<?> statusJob = this.statusJob;
1180         if ((statusJob == null) || statusJob.isCancelled()) {
1181             this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1182                     TimeUnit.SECONDS);
1183             logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1184                     UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1185         }
1186     }
1187
1188     /**
1189      * Flag the status job to do an exceptional update (something happened) rather
1190      * than waiting until the next regular poll
1191      *
1192      * @param requestCount number of polls to execute
1193      * @param refreshSettings true=force a /settings query
1194      * @return true=Update schedule, false=skipped (too many updates already
1195      *         scheduled)
1196      */
1197     @Override
1198     public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1199         this.refreshSettings |= refreshSettings;
1200         if (refreshSettings) {
1201             if (requestCount == 0) {
1202                 logger.debug("{}: Request settings refresh", thingName);
1203             }
1204             scheduledUpdates = 1;
1205             return true;
1206         }
1207         if (scheduledUpdates < 10) { // < 30s
1208             scheduledUpdates += requestCount;
1209             return true;
1210         }
1211         return false;
1212     }
1213
1214     /**
1215      * Map input states to channels
1216      *
1217      * @param status Shelly device status
1218      * @return true: one or more inputs were updated
1219      */
1220     @Override
1221     public boolean updateInputs(ShellySettingsStatus status) {
1222         boolean updated = false;
1223
1224         if (status.inputs != null) {
1225             if (!areChannelsCreated()) {
1226                 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1227             }
1228
1229             int idx = 0;
1230             boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1231             for (ShellyInputState input : status.inputs) {
1232                 String group = profile.getInputGroup(idx);
1233                 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1234                 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1235                 if (input.event != null) {
1236                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1237                     updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1238                 }
1239                 idx++;
1240             }
1241         } else {
1242             if (status.input != null) {
1243                 // RGBW2: a single int rather than an array
1244                 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1245                         getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1246             }
1247         }
1248         return updated;
1249     }
1250
1251     @Override
1252     public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1253         boolean changed = false;
1254         if (valueArray != null && !valueArray.isEmpty()) {
1255             String reason = getString((String) valueArray.get(0));
1256             String newVal = valueArray.toString();
1257             changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1258             changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1259             if (changed) {
1260                 postEvent(reason.toUpperCase(), true);
1261             }
1262             lastWakeupReason = newVal;
1263         }
1264         return changed;
1265     }
1266
1267     @Override
1268     public void triggerButton(String group, int idx, String value) {
1269         String trigger = mapButtonEvent(value);
1270         if (trigger.isEmpty()) {
1271             return;
1272         }
1273
1274         logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1275         triggerChannel(group,
1276                 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1277                 trigger);
1278         updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1279         if (profile.alwaysOn) {
1280             // refresh status of the input channel
1281             requestUpdates(1, false);
1282         }
1283     }
1284
1285     @Override
1286     public void publishState(String channelId, State value) {
1287         String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1288         if (!stopping && isLinked(id)) {
1289             updateState(id, value);
1290             logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1291         }
1292     }
1293
1294     @Override
1295     public boolean updateChannel(String group, String channel, State value) {
1296         return updateChannel(mkChannelId(group, channel), value, false);
1297     }
1298
1299     @Override
1300     public boolean updateChannel(String channelId, State value, boolean force) {
1301         return !stopping && cache.updateChannel(channelId, value, force);
1302     }
1303
1304     @Override
1305     public State getChannelValue(String group, String channel) {
1306         return cache.getValue(group, channel);
1307     }
1308
1309     @Override
1310     public double getChannelDouble(String group, String channel) {
1311         State value = getChannelValue(group, channel);
1312         if (value != UnDefType.NULL) {
1313             if (value instanceof QuantityType quantityCommand) {
1314                 return quantityCommand.toBigDecimal().doubleValue();
1315             }
1316             if (value instanceof DecimalType decimalCommand) {
1317                 return decimalCommand.doubleValue();
1318             }
1319         }
1320         return -1;
1321     }
1322
1323     /**
1324      * Update Thing's channels according to available status information from the API
1325      *
1326      * @param dynChannels
1327      */
1328     @Override
1329     public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1330         if (channelsCreated) {
1331             return; // already done
1332         }
1333
1334         try {
1335             // Get subset of those channels that currently do not exist
1336             List<Channel> existingChannels = getThing().getChannels();
1337             for (Channel channel : existingChannels) {
1338                 String id = channel.getUID().getId();
1339                 if (dynChannels.containsKey(id)) {
1340                     dynChannels.remove(id);
1341                 }
1342             }
1343
1344             if (!dynChannels.isEmpty()) {
1345                 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1346                 ThingBuilder thingBuilder = editThing();
1347                 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1348                     Channel c = channel.getValue();
1349                     logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1350                     thingBuilder.withChannel(c);
1351                 }
1352                 updateThing(thingBuilder.build());
1353                 logger.debug("{}: Channel definitions updated", thingName);
1354             }
1355         } catch (IllegalArgumentException e) {
1356             logger.debug("{}: Unable to update channel definitions", thingName, e);
1357         }
1358     }
1359
1360     @Override
1361     public boolean areChannelsCreated() {
1362         return channelsCreated;
1363     }
1364
1365     /**
1366      * Update thing properties with dynamic values
1367      *
1368      * @param profile The device profile
1369      * @param status the /status result
1370      */
1371     public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1372         Map<String, Object> properties = fillDeviceProperties(profile);
1373         properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1374         String deviceName = getString(profile.settings.name);
1375         properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1376         properties.put(PROPERTY_DEV_GEN, "1");
1377         if (!deviceName.isEmpty()) {
1378             properties.put(PROPERTY_DEV_NAME, deviceName);
1379         }
1380         properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1381
1382         // add status properties
1383         if (status.wifiSta != null) {
1384             properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1385         }
1386         if (status.update != null) {
1387             properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1388             properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1389             properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1390             properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1391         }
1392         properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1393
1394         Map<String, String> thingProperties = new TreeMap<>();
1395         for (Map.Entry<String, Object> property : properties.entrySet()) {
1396             thingProperties.put(property.getKey(), (String) property.getValue());
1397         }
1398         flushProperties(thingProperties);
1399     }
1400
1401     /**
1402      * Add one property to the Thing Properties
1403      *
1404      * @param key Name of the property
1405      * @param value Value of the property
1406      */
1407     @Override
1408     public void updateProperties(String key, String value) {
1409         Map<String, String> thingProperties = editProperties();
1410         if (thingProperties.containsKey(key)) {
1411             thingProperties.replace(key, value);
1412         } else {
1413             thingProperties.put(key, value);
1414         }
1415         updateProperties(thingProperties);
1416         logger.trace("{}: Properties updated", thingName);
1417     }
1418
1419     public void flushProperties(Map<String, String> propertyUpdates) {
1420         Map<String, String> thingProperties = editProperties();
1421         for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1422             if (thingProperties.containsKey(property.getKey())) {
1423                 thingProperties.replace(property.getKey(), property.getValue());
1424             } else {
1425                 thingProperties.put(property.getKey(), property.getValue());
1426             }
1427         }
1428         updateProperties(thingProperties);
1429     }
1430
1431     /**
1432      * Get one property from the Thing Properties
1433      *
1434      * @param key property name
1435      * @return property value or "" if property is not set
1436      */
1437     @Override
1438     public String getProperty(String key) {
1439         Map<String, String> thingProperties = getThing().getProperties();
1440         return getString(thingProperties.get(key));
1441     }
1442
1443     /**
1444      * Fill Thing Properties with device attributes
1445      *
1446      * @param profile Property Map to full
1447      * @return a full property map
1448      */
1449     public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1450         Map<String, Object> properties = new TreeMap<>();
1451         properties.put(PROPERTY_VENDOR, VENDOR);
1452         if (profile.isInitialized()) {
1453             properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1454             properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1455             properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1456             properties.put(PROPERTY_DEV_MODE, profile.mode);
1457             if (profile.hasRelays) {
1458                 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1459                 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1460                 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1461             }
1462             properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1463             if (!profile.hwRev.isEmpty()) {
1464                 properties.put(PROPERTY_HWREV, profile.hwRev);
1465                 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1466             }
1467         }
1468         return properties;
1469     }
1470
1471     /**
1472      * Return device profile.
1473      *
1474      * @param forceRefresh true=force refresh before returning, false=return without
1475      *            refresh
1476      * @return ShellyDeviceProfile instance
1477      * @throws ShellyApiException
1478      */
1479     @Override
1480     public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1481         try {
1482             refreshSettings |= forceRefresh;
1483             if (refreshSettings) {
1484                 profile = api.getDeviceProfile(thingType);
1485                 if (!isThingOnline()) {
1486                     logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1487                 }
1488             }
1489         } finally {
1490             refreshSettings = false;
1491         }
1492         return profile;
1493     }
1494
1495     @Override
1496     public ShellyDeviceProfile getProfile() {
1497         return profile;
1498     }
1499
1500     @Override
1501     public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1502         List<StateOption> options = channelDefinitions.getStateOptions(uid);
1503         if (!options.isEmpty()) {
1504             logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1505             return options;
1506         }
1507         return null;
1508     }
1509
1510     protected ShellyDeviceProfile getDeviceProfile() {
1511         return profile;
1512     }
1513
1514     @Override
1515     public void triggerChannel(String group, String channel, String payload) {
1516         String triggerCh = mkChannelId(group, channel);
1517         logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1518         if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1519             if (vibrationFilter == 0) {
1520                 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1521                 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1522                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1523             } else {
1524                 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1525                         vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1526                 return;
1527             }
1528         }
1529
1530         triggerChannel(triggerCh, payload);
1531     }
1532
1533     public void stop() {
1534         logger.debug("{}: Shutting down", thingName);
1535         ScheduledFuture<?> job = this.initJob;
1536         if (job != null) {
1537             job.cancel(true);
1538             initJob = null;
1539         }
1540         job = this.statusJob;
1541         if (job != null) {
1542             job.cancel(true);
1543             statusJob = null;
1544             logger.debug("{}: Shelly statusJob stopped", thingName);
1545         }
1546         api.close();
1547         profile.initialized = false;
1548     }
1549
1550     /**
1551      * Shutdown thing, make sure background jobs are canceled
1552      */
1553     @Override
1554     public void dispose() {
1555         logger.debug("{}: Stopping Thing", thingName);
1556         stopping = true;
1557         stop();
1558         super.dispose();
1559     }
1560
1561     /**
1562      * Device specific command handlers are overriding this method to do additional stuff
1563      */
1564     public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1565         return false;
1566     }
1567
1568     public String getUID() {
1569         return getThing().getUID().getAsString();
1570     }
1571
1572     /**
1573      * Device specific handlers are overriding this method to do additional stuff
1574      */
1575     public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1576         return false;
1577     }
1578
1579     @Override
1580     public String getThingName() {
1581         return thingName;
1582     }
1583
1584     @Override
1585     public void resetStats() {
1586         // reset statistics
1587         stats = new ShellyDeviceStats();
1588     }
1589
1590     @Override
1591     public ShellyDeviceStats getStats() {
1592         return stats;
1593     }
1594
1595     @Override
1596     public ShellyApiInterface getApi() {
1597         return api;
1598     }
1599
1600     @Override
1601     public long getScheduledUpdates() {
1602         return scheduledUpdates;
1603     }
1604
1605     public Map<String, String> getStatsProp() {
1606         return stats.asProperties();
1607     }
1608
1609     @Override
1610     public void triggerUpdateFromCoap() {
1611         if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1612             requestUpdates(1, false);
1613         }
1614     }
1615 }