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