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