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