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