2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.handler;
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.*;
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.util.List;
26 import java.util.TreeMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.shelly.internal.api.ShellyApiException;
34 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
35 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
36 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
47 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
48 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
49 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
50 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
51 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
52 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
53 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
54 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
55 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
56 import org.openhab.core.library.types.DecimalType;
57 import org.openhab.core.library.types.OnOffType;
58 import org.openhab.core.library.types.OpenClosedType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.thing.Channel;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.Thing;
63 import org.openhab.core.thing.ThingStatus;
64 import org.openhab.core.thing.ThingStatusDetail;
65 import org.openhab.core.thing.ThingTypeUID;
66 import org.openhab.core.thing.binding.BaseThingHandler;
67 import org.openhab.core.thing.binding.builder.ThingBuilder;
68 import org.openhab.core.thing.type.ChannelTypeUID;
69 import org.openhab.core.types.Command;
70 import org.openhab.core.types.RefreshType;
71 import org.openhab.core.types.State;
72 import org.openhab.core.types.StateOption;
73 import org.openhab.core.types.UnDefType;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
79 * sent to one of the channels.
81 * @author Markus Michels - Initial contribution
84 public abstract class ShellyBaseHandler extends BaseThingHandler
85 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
87 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
88 protected final ShellyChannelDefinitions channelDefinitions;
90 public String thingName = "";
91 public String thingType = "";
93 protected final ShellyApiInterface api;
94 private final HttpClient httpClient;
96 private ShellyBindingConfiguration bindingConfig;
97 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
98 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
99 private ShellyDeviceStats stats = new ShellyDeviceStats();
100 private @Nullable Shelly1CoapHandler coap;
102 private final ShellyTranslationProvider messages;
103 private final ShellyChannelCache cache;
104 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
106 private final boolean gen2;
107 protected boolean autoCoIoT = false;
110 private boolean channelsCreated = false;
111 private boolean stopping = false;
112 private int vibrationFilter = 0;
113 private String lastWakeupReason = "";
116 private long watchdog = now();
117 protected int scheduledUpdates = 0;
118 private int skipCount = UPDATE_SKIP_COUNT;
119 private int skipUpdate = 0;
120 private boolean refreshSettings = false;
121 private @Nullable ScheduledFuture<?> statusJob;
122 private @Nullable ScheduledFuture<?> initJob;
127 * @param thing The Thing object
128 * @param bindingConfig The binding configuration (beside thing
130 * @param coapServer coap server instance
131 * @param localIP local IP address from networkAddressService
132 * @param httpPort from httpService
134 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
135 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
136 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
139 this.thingName = getString(thing.getLabel());
140 this.messages = translationProvider;
141 this.cache = new ShellyChannelCache(this);
142 this.channelDefinitions = new ShellyChannelDefinitions(messages);
143 this.bindingConfig = bindingConfig;
144 this.config = getConfigAs(ShellyThingConfiguration.class);
145 this.httpClient = httpClient;
147 Map<String, String> properties = thing.getProperties();
148 String gen = getString(properties.get(PROPERTY_DEV_GEN));
149 String thingType = getThingType();
150 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
153 gen2 = "2".equals(gen);
154 this.api = !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this);
156 config.eventsCoIoT = false;
158 if (config.eventsCoIoT) {
159 this.coap = new Shelly1CoapHandler(this, coapServer);
164 public boolean checkRepresentation(String key) {
165 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
166 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
170 * Schedule asynchronous Thing initialization, register thing to event dispatcher
173 public void initialize() {
174 // start background initialization:
175 initJob = scheduler.schedule(() -> {
176 boolean start = true;
178 initializeThingConfig();
179 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
180 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
181 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
183 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
184 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
185 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
186 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
187 messages.get("status.unknown.initializing"));
188 start = initializeThing();
189 } catch (ShellyApiException e) {
190 ShellyApiResult res = e.getApiResult();
192 if (e.isJsonError()) { // invalid JSON format
193 mid = "offline.status-error-unexpected-error";
195 } else if (isAuthorizationFailed(res)) {
196 mid = "offline.conf-error-access-denied";
198 } else if (profile.alwaysOn && e.isConnectionError()) {
199 mid = "offline.status-error-connect";
201 if (!mid.isEmpty()) {
202 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
204 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
205 } catch (IllegalArgumentException e) {
206 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
208 // even this initialization failed we start the status update
209 // the updateJob will then try to auto-initialize the thing
210 // in this case the thing stays in status INITIALIZING
215 }, 2, TimeUnit.SECONDS);
219 public ShellyThingConfiguration getThingConfig() {
224 public HttpClient getHttpClient() {
229 * This routine is called every time the Thing configuration has been changed
232 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
233 super.handleConfigurationUpdate(configurationParameters);
234 logger.debug("{}: Thing config updated, re-initialize", thingName);
239 reinitializeThing();// force re-initialization
243 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
244 * If the device is password protected and the credentials are missing or don't match the API access will throw an
245 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
246 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
247 * credentials are correct and the API access is initialized successful.
249 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
251 public boolean initializeThing() throws ShellyApiException {
252 // Init from thing type to have a basic profile, gets updated when device info is received from API
253 refreshSettings = false;
254 lastWakeupReason = "";
255 cache.setThingName(thingName);
259 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
260 getThing().getLabel(), thingType, config.deviceIp, gen2, config.eventsCoIoT);
261 if (config.deviceIp.isEmpty()) {
262 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
266 profile.initFromThingType(thingType); // do some basic initialization
268 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
269 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
270 // Action URL does when enabled)
271 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
272 coap.start(thingName, config);
275 // Initialize API access, exceptions will be catched by initialize()
277 ShellySettingsDevice devInfo = api.getDeviceInfo();
278 if (getBool(devInfo.auth) && config.password.isEmpty()) {
279 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
282 if (config.serviceName.isEmpty()) {
283 config.serviceName = getString(profile.hostname).toLowerCase();
286 api.setConfig(thingName, config);
287 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
288 tmpPrf.isGen2 = gen2;
289 tmpPrf.auth = devInfo.auth; // missing in /settings
291 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
292 changeThingType(thingName, tmpPrf.mode);
293 return false; // force re-initialization
295 // Validate device mode
296 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
297 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
298 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
302 if (!getString(devInfo.coiot).isEmpty()) {
303 // New Shelly devices might use a different endpoint for the CoAP listener
304 tmpPrf.coiotEndpoint = devInfo.coiot;
306 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
307 // Sensor, usually 12h, H&T in USB mode 10min
308 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
309 ? tmpPrf.settings.sleepMode.period * 60 // minutes
310 : tmpPrf.settings.sleepMode.period * 3600; // hours
311 tmpPrf.updatePeriod += 60; // give 1min extra
312 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
313 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
314 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
315 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
317 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
320 tmpPrf.status = api.getStatus(); // update thing properties
321 tmpPrf.updateFromStatus(tmpPrf.status);
322 addStateOptions(tmpPrf);
324 // update thing properties
325 updateProperties(tmpPrf, tmpPrf.status);
326 checkVersion(tmpPrf, tmpPrf.status);
328 startCoap(config, tmpPrf);
330 api.setActionURLs(); // register event urls
333 // All initialization done, so keep the profile and set Thing to ONLINE
334 fillDeviceStatus(tmpPrf.status, false);
335 postEvent(ALARM_TYPE_NONE, false);
338 showThingConfig(profile);
340 logger.debug("{}: Thing successfully initialized.", thingName);
341 updateProperties(profile, profile.status);
342 setThingOnline(); // if API call was successful the thing must be online
343 return true; // success
347 * Handle Channel Commands
350 public void handleCommand(ChannelUID channelUID, Command command) {
352 if (command instanceof RefreshType) {
353 String channelId = channelUID.getId();
354 State value = cache.getValue(channelId);
355 if (value != UnDefType.NULL) {
356 updateState(channelId, value);
361 if (!profile.isInitialized() || (isThingOffline() && profile.alwaysOn)) {
362 logger.debug("{}: {}", thingName, messages.get("command.init", command));
365 profile = getProfile(false);
368 boolean update = false;
369 switch (channelUID.getIdWithoutGroup()) {
370 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
371 logger.debug("{}: Send key {}", thingName, command);
372 api.sendIRKey(command.toString());
376 case CHANNEL_LED_STATUS_DISABLE:
377 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
378 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
380 case CHANNEL_LED_POWER_DISABLE:
381 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
382 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
385 case CHANNEL_SENSOR_SLEEPTIME:
386 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
387 int value = (int) getNumber(command);
388 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
390 api.setSleepTime(value);
392 case CHANNEL_CONTROL_SCHEDULE:
394 logger.debug("{}: {} Valve schedule/profile", thingName,
395 command == OnOffType.ON ? "Enable" : "Disable");
396 api.setValveProfile(0,
397 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
400 case CHANNEL_CONTROL_PROFILE:
401 logger.debug("{}: Select profile {}", thingName, command);
403 if (command instanceof Number) {
404 id = (int) getNumber(command);
406 String cmd = command.toString();
407 if (isDigit(cmd.charAt(0))) {
408 id = Integer.parseInt(cmd);
409 } else if (profile.settings.thermostats != null) {
410 ShellyThermnostat t = profile.settings.thermostats.get(0);
411 for (int i = 0; i < t.profileNames.length; i++) {
412 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
418 if (id < 0 || id > 5) {
419 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
422 api.setValveProfile(0, id);
424 case CHANNEL_CONTROL_MODE:
425 logger.debug("{}: Set mode to {}", thingName, command);
426 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
428 case CHANNEL_CONTROL_SETTEMP:
429 logger.debug("{}: Set temperature to {}", thingName, command);
430 api.setValveTemperature(0, (int) getNumber(command));
432 case CHANNEL_CONTROL_POSITION:
433 logger.debug("{}: Set position to {}", thingName, command);
434 api.setValvePosition(0, getNumber(command));
436 case CHANNEL_CONTROL_BCONTROL:
437 logger.debug("{}: Set boost mode to {}", thingName, command);
438 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
440 case CHANNEL_CONTROL_BTIMER:
441 logger.debug("{}: Set boost timer to {}", thingName, command);
442 api.setValveBoostTime(0, (int) getNumber(command));
444 case CHANNEL_SENSOR_MUTE:
445 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
446 logger.debug("{}: Mute Smoke Alarm", thingName);
447 api.muteSmokeAlarm(0);
448 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
452 update = handleDeviceCommand(channelUID, command);
457 if (update && !autoCoIoT && !isUpdateScheduled()) {
458 requestUpdates(1, false);
460 } catch (ShellyApiException e) {
461 ShellyApiResult res = e.getApiResult();
462 if (isAuthorizationFailed(res)) {
465 if (res.isNotCalibrtated()) {
466 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
468 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
471 } catch (IllegalArgumentException e) {
472 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
476 private double getNumber(Command command) {
477 if (command instanceof QuantityType) {
478 return ((QuantityType<?>) command).doubleValue();
480 if (command instanceof DecimalType) {
481 return ((DecimalType) command).doubleValue();
483 if (command instanceof Number) {
484 return ((Number) command).doubleValue();
486 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
490 * Update device status and channels
492 protected void refreshStatus() {
494 boolean updated = false;
496 if (vibrationFilter > 0) {
498 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
499 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
503 ThingStatus thingStatus = getThing().getStatus();
504 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
505 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
506 || (thingStatus == ThingStatus.UNKNOWN)) {
507 logger.debug("{}: Status update triggered thing initialization", thingName);
508 initializeThing(); // may fire an exception if initialization failed
510 ShellySettingsStatus status = api.getStatus();
511 boolean restarted = checkRestarted(status);
512 profile = getProfile(refreshSettings || restarted);
513 profile.status = status;
514 profile.updateFromStatus(status);
516 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
518 postEvent(ALARM_TYPE_RESTARTED, true);
521 // If status update was successful the thing must be online
524 // map status to channels
525 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
526 updated |= this.updateDeviceStatus(status);
527 updated |= ShellyComponents.updateDeviceStatus(this, status);
528 fillDeviceStatus(status, updated);
529 updated |= updateInputs(status);
530 updated |= updateMeters(this, status);
531 updated |= updateSensors(this, status);
533 // All channels must be created after the first cycle
534 channelsCreated = true;
536 } catch (ShellyApiException e) {
537 // http call failed: go offline except for battery devices, which might be in
538 // sleep mode. Once the next update is successful the device goes back online
540 ShellyApiResult res = e.getApiResult();
541 if (profile.alwaysOn && e.isConnectionError()) {
542 status = "offline.status-error-connect";
543 } else if (res.isHttpAccessUnauthorized()) {
544 status = "offline.conf-error-access-denied";
545 } else if (isWatchdogStarted()) {
546 if (!isWatchdogExpired()) {
547 logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
549 if (isThingOnline()) {
550 status = "offline.status-error-watchdog";
553 } else if (e.isJSONException()) {
554 status = "offline.status-error-unexpected-api-result";
555 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
556 } else if (res.isHttpTimeout()) {
557 // Watchdog not started, e.g. device in sleep mode
558 if (isThingOnline()) { // ignore when already offline
559 status = "offline.status-error-watchdog";
562 status = "offline.status-error-unexpected-api-result";
563 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
566 if (!status.isEmpty()) {
567 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
569 } catch (NullPointerException | IllegalArgumentException e) {
570 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
572 if (scheduledUpdates > 0) {
574 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
575 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
576 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
577 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
583 private void showThingConfig(ShellyDeviceProfile profile) {
584 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
585 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
587 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
588 logger.debug("{}: Device "
589 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
590 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
591 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
592 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
593 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
594 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
595 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
596 profile.inColor, profile.alwaysOn, profile.updatePeriod);
597 if (profile.status.extTemperature != null || profile.status.extHumidity != null
598 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
599 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
603 private void addStateOptions(ShellyDeviceProfile prf) {
605 String[] profileNames = prf.getValveProfileList(0);
606 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
607 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
608 channelDefinitions.clearStateOptions(channelId);
610 for (String name : profileNames) {
611 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
615 if (prf.isRoller && prf.settings.favorites != null) {
616 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
617 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
618 prf.settings.favorites.size());
619 channelDefinitions.clearStateOptions(channelId);
621 for (ShellyFavPos fav : prf.settings.favorites) {
622 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
629 public String getThingType() {
630 return thing.getThingTypeUID().getId();
634 public ThingStatus getThingStatus() {
635 return thing.getStatus();
639 public ThingStatusDetail getThingStatusDetail() {
640 return thing.getStatusInfo().getStatusDetail();
644 public boolean isThingOnline() {
645 return getThingStatus() == ThingStatus.ONLINE;
648 public boolean isThingOffline() {
649 return getThingStatus() == ThingStatus.OFFLINE;
653 public void setThingOnline() {
654 if (!isThingOnline()) {
655 updateStatus(ThingStatus.ONLINE);
657 // request 3 updates in a row (during the first 2+3*3 sec)
658 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
661 // Restart watchdog when status update was successful (no exception)
666 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
667 if (!isThingOffline()) {
668 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
669 api.close(); // Gen2: disconnect WS/close http sessions
671 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
676 public void restartWatchdog() {
678 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
679 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
682 private boolean isWatchdogExpired() {
683 long delta = now() - watchdog;
684 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
685 stats.remainingWatchdog = delta;
691 private boolean isWatchdogStarted() {
696 public void reinitializeThing() {
697 logger.debug("{}: Re-Initialize Thing", thingName);
699 logger.debug("{}: Handler is shutting down, ignore", thingName);
702 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
703 messages.get("offline.status-error-restarted"));
704 requestUpdates(0, true);
708 public boolean isStopping() {
713 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
716 // Update uptime and WiFi, internal temp
717 ShellyComponents.updateDeviceStatus(this, status);
718 stats.wifiRssi = status.wifiSta.rssi;
720 if (api.isInitialized()) {
721 stats.timeoutErrors = api.getTimeoutErrors();
722 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
724 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
726 // Check various device indicators like overheating
727 if (checkRestarted(status)) {
728 // Force re-initialization on next status update
730 } else if (getBool(status.overtemperature)) {
731 alarm = ALARM_TYPE_OVERTEMP;
732 } else if (getBool(status.overload)) {
733 alarm = ALARM_TYPE_OVERLOAD;
734 } else if (getBool(status.loaderror)) {
735 alarm = ALARM_TYPE_LOADERR;
737 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
738 if (internalTemp != UnDefType.NULL) {
739 int temp = ((Number) internalTemp).intValue();
740 if (temp > stats.maxInternalTemp) {
741 stats.maxInternalTemp = temp;
745 if (status.uptime != null) {
746 stats.lastUptime = getLong(status.uptime);
749 if (!alarm.isEmpty()) {
750 postEvent(alarm, false);
755 public void incProtMessages() {
756 stats.protocolMessages++;
760 public void incProtErrors() {
761 stats.protocolErrors++;
765 * Check if device has restarted and needs a new Thing initialization
767 * @return true: restart detected
770 private boolean checkRestarted(ShellySettingsStatus status) {
771 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
772 && (status.uptime != null && status.uptime < stats.lastUptime
773 || (!profile.status.update.oldVersion.isEmpty()
774 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
775 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
776 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
777 updateProperties(profile, status);
784 * Save alarm to the lastAlarm channel
786 * @param alarm Alarm Message
789 public void postEvent(String event, boolean force) {
790 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
791 State value = cache.getValue(channelId);
792 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
794 if (force || !lastAlarm.equals(event)
795 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
796 switch (event.toUpperCase()) {
799 case SHELLY_WAKEUPT_SENSOR:
800 case SHELLY_WAKEUPT_PERIODIC:
801 case SHELLY_WAKEUPT_BUTTON:
802 case SHELLY_WAKEUPT_POWERON:
803 case SHELLY_WAKEUPT_EXT_POWER:
804 case SHELLY_WAKEUPT_UNKNOWN:
805 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
806 case ALARM_TYPE_NONE:
809 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
810 triggerChannel(channelId, event);
811 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
812 stats.lastAlarm = event;
813 stats.lastAlarmTs = now();
819 public boolean isUpdateScheduled() {
820 return scheduledUpdates > 0;
824 * Callback for device events
826 * @param deviceName device receiving the event
827 * @param parameters parameters from the event URL
828 * @param data the HTML input data
829 * @return true if event was processed
832 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
833 Map<String, String> parameters) {
834 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
835 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
837 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
838 if (!profile.isInitialized()) {
839 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
840 requestUpdates(1, true);
842 String group = profile.getControlGroup(idx);
843 if (group.isEmpty()) {
844 logger.debug("{}: Unsupported event class: {}", thingName, type);
848 // map some of the events to system defined button triggers
852 String parmType = getString(parameters.get("type"));
853 String event = !parmType.isEmpty() ? parmType : type;
854 boolean isButton = profile.inButtonMode(idx - 1);
856 case SHELLY_EVENT_SHORTPUSH:
857 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
858 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
859 case SHELLY_EVENT_LONGPUSH:
861 triggerButton(group, idx, mapButtonEvent(event));
862 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
863 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
865 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
869 case SHELLY_EVENT_BTN_ON:
870 case SHELLY_EVENT_BTN_OFF:
871 if (profile.isRGBW2) {
872 // RGBW2 has only one input, so not per channel
873 group = CHANNEL_GROUP_LIGHT_CONTROL;
875 onoff = CHANNEL_INPUT;
877 case SHELLY_EVENT_BTN1_ON:
878 case SHELLY_EVENT_BTN1_OFF:
879 onoff = CHANNEL_INPUT1;
881 case SHELLY_EVENT_BTN2_ON:
882 case SHELLY_EVENT_BTN2_OFF:
883 onoff = CHANNEL_INPUT2;
885 case SHELLY_EVENT_OUT_ON:
886 case SHELLY_EVENT_OUT_OFF:
887 onoff = CHANNEL_OUTPUT;
889 case SHELLY_EVENT_ROLLER_OPEN:
890 case SHELLY_EVENT_ROLLER_CLOSE:
891 case SHELLY_EVENT_ROLLER_STOP:
892 channel = CHANNEL_EVENT_TRIGGER;
895 case SHELLY_EVENT_SENSORREPORT:
896 // process sensor with next refresh
898 case SHELLY_EVENT_TEMP_OVER: // DW2
899 case SHELLY_EVENT_TEMP_UNDER:
900 channel = CHANNEL_EVENT_TRIGGER;
903 case SHELLY_EVENT_FLOOD_DETECTED:
904 case SHELLY_EVENT_FLOOD_GONE:
905 updateChannel(group, CHANNEL_SENSOR_FLOOD,
906 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
909 case SHELLY_EVENT_CLOSE: // DW 1.7
910 case SHELLY_EVENT_OPEN: // DW 1.7
911 updateChannel(group, CHANNEL_SENSOR_STATE,
912 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
913 : OpenClosedType.CLOSED);
916 case SHELLY_EVENT_DARK: // DW 1.7
917 case SHELLY_EVENT_TWILIGHT: // DW 1.7
918 case SHELLY_EVENT_BRIGHT: // DW 1.7
919 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
922 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
923 case SHELLY_EVENT_ALARM_HEAVY:
924 case SHELLY_EVENT_ALARM_OFF:
925 case SHELLY_EVENT_VIBRATION: // DW2
926 channel = CHANNEL_SENSOR_ALARM_STATE;
927 payload = event.toUpperCase();
931 // trigger will be provided by input/output channel or sensor channels
934 if (!onoff.isEmpty()) {
935 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
937 if (!payload.isEmpty()) {
938 // Pass event to trigger channel
939 payload = payload.toUpperCase();
940 logger.debug("{}: Post event {}", thingName, payload);
941 triggerChannel(mkChannelId(group, channel), payload);
945 // request update on next interval (2x for non-battery devices)
947 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
954 * Initialize the binding's thing configuration, calc update counts
956 protected void initializeThingConfig() {
957 thingType = getThing().getThingTypeUID().getId();
958 final Map<String, String> properties = getThing().getProperties();
959 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
960 if (thingName.isEmpty()) {
961 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
962 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
965 config = getConfigAs(ShellyThingConfiguration.class);
966 if (config.deviceIp.isEmpty()) {
967 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
971 InetAddress addr = InetAddress.getByName(config.deviceIp);
972 String saddr = addr.getHostAddress();
973 if (!config.deviceIp.equals(saddr)) {
974 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
975 config.deviceIp = saddr;
977 } catch (UnknownHostException e) {
978 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
981 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
982 config.localIp = bindingConfig.localIP;
983 config.localPort = String.valueOf(bindingConfig.httpPort);
984 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
985 config.userId = bindingConfig.defaultUserId;
986 config.password = bindingConfig.defaultPassword;
987 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
989 if (config.updateInterval == 0) {
990 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
992 if (config.updateInterval < UPDATE_MIN_DELAY) {
993 config.updateInterval = UPDATE_MIN_DELAY;
996 // Try to get updatePeriod from properties
997 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
998 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
999 // initialized successfully by the REST call.
1000 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1001 if (!lastPeriod.isEmpty()) {
1002 int period = Integer.parseInt(lastPeriod);
1004 profile.updatePeriod = period;
1008 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1009 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1012 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1014 ShellyVersionDTO version = new ShellyVersionDTO();
1015 if (version.checkBeta(getString(prf.fwVersion))) {
1016 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1018 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1019 if (version.compare(prf.fwVersion, minVersion) < 0) {
1020 logger.warn("{}: {}", prf.hostname,
1021 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1024 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1025 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
1026 if (!config.eventsCoIoT) {
1027 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1031 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1032 logger.info("{}: {}", thingName,
1033 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1035 } catch (NullPointerException e) { // could be inconsistant format of beta version
1036 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1040 public String checkForUpdate() {
1042 ShellyOtaCheckResult result = api.checkForUpdate();
1043 return result.status;
1044 } catch (ShellyApiException e) {
1049 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1050 if (coap == null || !config.eventsCoIoT) {
1053 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1054 String devpeer = getString(profile.settings.coiot.peer);
1055 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1056 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1058 api.setCoIoTPeer(ourpeer);
1059 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1060 } catch (ShellyApiException e) {
1061 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1063 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1064 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1068 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1069 config.eventsCoIoT = true;
1070 config.eventsSwitch = false;
1071 config.eventsButton = false;
1072 config.eventsPush = false;
1073 config.eventsRoller = false;
1074 config.eventsSensorReport = false;
1075 api.setConfig(thingName, config);
1078 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1080 coap.start(thingName, config);
1085 * Checks the http response for authorization error.
1086 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1087 * case the thing type shelly-unknown is set.
1089 * @param response exception details including the http respone
1090 * @return true if the authorization failed
1092 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1093 if (result.isHttpAccessUnauthorized()) {
1094 // If the device is password protected the API doesn't provide settings to the device settings
1095 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1102 * Change type of this thing.
1104 * @param thingType thing type acc. to the xml definition
1105 * @param mode Device mode (e.g. relay, roller)
1107 protected void changeThingType(String thingType, String mode) {
1108 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1109 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1110 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1111 Map<String, String> properties = editProperties();
1112 properties.replace(PROPERTY_DEV_TYPE, thingType);
1113 properties.replace(PROPERTY_DEV_MODE, mode);
1114 updateProperties(properties);
1115 changeThingType(thingTypeUID, getConfig());
1120 public void thingUpdated(Thing thing) {
1121 logger.debug("{}: Channel definitions updated.", thingName);
1122 super.thingUpdated(thing);
1126 * Start the background updates
1128 protected void startUpdateJob() {
1129 ScheduledFuture<?> statusJob = this.statusJob;
1130 if ((statusJob == null) || statusJob.isCancelled()) {
1131 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1133 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1134 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1139 * Flag the status job to do an exceptional update (something happened) rather
1140 * than waiting until the next regular poll
1142 * @param requestCount number of polls to execute
1143 * @param refreshSettings true=force a /settings query
1144 * @return true=Update schedule, false=skipped (too many updates already
1148 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1149 this.refreshSettings |= refreshSettings;
1150 if (refreshSettings) {
1151 if (requestCount == 0) {
1152 logger.debug("{}: Request settings refresh", thingName);
1154 scheduledUpdates = 1;
1157 if (scheduledUpdates < 10) { // < 30s
1158 scheduledUpdates += requestCount;
1165 * Map input states to channels
1167 * @param groupName Channel Group (relay / relay1...)
1169 * @param status Shelly device status
1170 * @return true: one or more inputs were updated
1173 public boolean updateInputs(ShellySettingsStatus status) {
1174 boolean updated = false;
1176 if (status.inputs != null) {
1177 if (!areChannelsCreated()) {
1178 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1182 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1183 for (ShellyInputState input : status.inputs) {
1184 String group = profile.getInputGroup(idx);
1185 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1186 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1187 if (input.event != null) {
1188 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1189 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1194 if (status.input != null) {
1195 // RGBW2: a single int rather than an array
1196 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1197 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1204 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1205 boolean changed = false;
1206 if (valueArray != null && !valueArray.isEmpty()) {
1207 String reason = getString((String) valueArray.get(0));
1208 String newVal = valueArray.toString();
1209 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1210 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1212 postEvent(reason.toUpperCase(), true);
1214 lastWakeupReason = newVal;
1220 public void triggerButton(String group, int idx, String value) {
1221 String trigger = mapButtonEvent(value);
1222 if (trigger.isEmpty()) {
1226 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1227 triggerChannel(group,
1228 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1230 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1231 if (profile.alwaysOn) {
1232 // refresh status of the input channel
1233 requestUpdates(1, false);
1238 public void publishState(String channelId, State value) {
1239 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1240 if (!stopping && isLinked(id)) {
1241 updateState(id, value);
1242 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1247 public boolean updateChannel(String group, String channel, State value) {
1248 return updateChannel(mkChannelId(group, channel), value, false);
1252 public boolean updateChannel(String channelId, State value, boolean force) {
1253 return !stopping && cache.updateChannel(channelId, value, force);
1257 public State getChannelValue(String group, String channel) {
1258 return cache.getValue(group, channel);
1262 public double getChannelDouble(String group, String channel) {
1263 State value = getChannelValue(group, channel);
1264 if (value != UnDefType.NULL) {
1265 if (value instanceof QuantityType) {
1266 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1268 if (value instanceof DecimalType) {
1269 return ((DecimalType) value).doubleValue();
1276 * Update Thing's channels according to available status information from the API
1278 * @param thingHandler
1281 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1282 if (channelsCreated) {
1283 return; // already done
1287 // Get subset of those channels that currently do not exist
1288 List<Channel> existingChannels = getThing().getChannels();
1289 for (Channel channel : existingChannels) {
1290 String id = channel.getUID().getId();
1291 if (dynChannels.containsKey(id)) {
1292 dynChannels.remove(id);
1296 if (!dynChannels.isEmpty()) {
1297 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1298 ThingBuilder thingBuilder = editThing();
1299 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1300 Channel c = channel.getValue();
1301 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1302 thingBuilder.withChannel(c);
1304 updateThing(thingBuilder.build());
1305 logger.debug("{}: Channel definitions updated", thingName);
1307 } catch (IllegalArgumentException e) {
1308 logger.debug("{}: Unable to update channel definitions", thingName, e);
1313 public boolean areChannelsCreated() {
1314 return channelsCreated;
1318 * Update thing properties with dynamic values
1320 * @param profile The device profile
1321 * @param status the /status result
1323 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1324 Map<String, Object> properties = fillDeviceProperties(profile);
1325 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1326 String deviceName = getString(profile.settings.name);
1327 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1328 properties.put(PROPERTY_DEV_GEN, "1");
1329 if (!deviceName.isEmpty()) {
1330 properties.put(PROPERTY_DEV_NAME, deviceName);
1332 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1334 // add status properties
1335 if (status.wifiSta != null) {
1336 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1338 if (status.update != null) {
1339 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1340 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1341 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1342 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1344 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1346 Map<String, String> thingProperties = new TreeMap<>();
1347 for (Map.Entry<String, Object> property : properties.entrySet()) {
1348 thingProperties.put(property.getKey(), (String) property.getValue());
1350 flushProperties(thingProperties);
1354 * Add one property to the Thing Properties
1356 * @param key Name of the property
1357 * @param value Value of the property
1360 public void updateProperties(String key, String value) {
1361 Map<String, String> thingProperties = editProperties();
1362 if (thingProperties.containsKey(key)) {
1363 thingProperties.replace(key, value);
1365 thingProperties.put(key, value);
1367 updateProperties(thingProperties);
1368 logger.trace("{}: Properties updated", thingName);
1371 public void flushProperties(Map<String, String> propertyUpdates) {
1372 Map<String, String> thingProperties = editProperties();
1373 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1374 if (thingProperties.containsKey(property.getKey())) {
1375 thingProperties.replace(property.getKey(), property.getValue());
1377 thingProperties.put(property.getKey(), property.getValue());
1380 updateProperties(thingProperties);
1384 * Get one property from the Thing Properties
1386 * @param key property name
1387 * @return property value or "" if property is not set
1390 public String getProperty(String key) {
1391 Map<String, String> thingProperties = getThing().getProperties();
1392 return getString(thingProperties.get(key));
1396 * Fill Thing Properties with device attributes
1398 * @param profile Property Map to full
1399 * @return a full property map
1401 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1402 Map<String, Object> properties = new TreeMap<>();
1403 properties.put(PROPERTY_VENDOR, VENDOR);
1404 if (profile.isInitialized()) {
1405 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1406 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1407 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1408 properties.put(PROPERTY_DEV_MODE, profile.mode);
1409 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1410 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1411 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1412 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1413 if (!profile.hwRev.isEmpty()) {
1414 properties.put(PROPERTY_HWREV, profile.hwRev);
1415 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1422 * Return device profile.
1424 * @param ForceRefresh true=force refresh before returning, false=return without
1426 * @return ShellyDeviceProfile instance
1427 * @throws ShellyApiException
1430 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1432 refreshSettings |= forceRefresh;
1433 if (refreshSettings) {
1434 profile = api.getDeviceProfile(thingType);
1435 if (!isThingOnline()) {
1436 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1440 refreshSettings = false;
1446 public ShellyDeviceProfile getProfile() {
1451 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1452 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1453 if (!options.isEmpty()) {
1454 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1460 protected ShellyDeviceProfile getDeviceProfile() {
1465 public void triggerChannel(String group, String channel, String payload) {
1466 String triggerCh = mkChannelId(group, channel);
1467 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1468 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1469 if (vibrationFilter == 0) {
1470 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1471 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1472 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1474 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1475 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1480 triggerChannel(triggerCh, payload);
1483 public void stop() {
1484 logger.debug("{}: Shutting down", thingName);
1485 ScheduledFuture<?> job = this.initJob;
1490 job = this.statusJob;
1494 logger.debug("{}: Shelly statusJob stopped", thingName);
1497 profile.initialized = false;
1501 * Shutdown thing, make sure background jobs are canceled
1504 public void dispose() {
1505 logger.debug("{}: Stopping Thing", thingName);
1512 * Device specific command handlers are overriding this method to do additional stuff
1514 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1518 public String getUID() {
1519 return getThing().getUID().getAsString();
1523 * Device specific handlers are overriding this method to do additional stuff
1525 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1530 public String getThingName() {
1535 public void resetStats() {
1537 stats = new ShellyDeviceStats();
1541 public ShellyDeviceStats getStats() {
1546 public ShellyApiInterface getApi() {
1551 public long getScheduledUpdates() {
1552 return scheduledUpdates;
1555 public Map<String, String> getStatsProp() {
1556 return stats.asProperties();
1560 public void triggerUpdateFromCoap() {
1561 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1562 requestUpdates(1, false);