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