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