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