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