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