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