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