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.api2.ShellyBluApi;
50 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
51 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
52 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
53 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
54 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
55 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
56 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
57 import org.openhab.core.library.types.DecimalType;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.library.types.OpenClosedType;
60 import org.openhab.core.library.types.QuantityType;
61 import org.openhab.core.thing.Channel;
62 import org.openhab.core.thing.ChannelUID;
63 import org.openhab.core.thing.Thing;
64 import org.openhab.core.thing.ThingStatus;
65 import org.openhab.core.thing.ThingStatusDetail;
66 import org.openhab.core.thing.ThingTypeUID;
67 import org.openhab.core.thing.binding.BaseThingHandler;
68 import org.openhab.core.thing.binding.builder.ThingBuilder;
69 import org.openhab.core.thing.type.ChannelTypeUID;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.openhab.core.types.State;
73 import org.openhab.core.types.StateOption;
74 import org.openhab.core.types.UnDefType;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
80 * sent to one of the channels.
82 * @author Markus Michels - Initial contribution
85 public abstract class ShellyBaseHandler extends BaseThingHandler
86 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
88 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
89 protected final ShellyChannelDefinitions channelDefinitions;
91 public String thingName = "";
92 public String thingType = "";
94 protected final ShellyApiInterface api;
95 private final HttpClient httpClient;
97 private ShellyBindingConfiguration bindingConfig;
98 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
99 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
100 private ShellyDeviceStats stats = new ShellyDeviceStats();
101 private @Nullable Shelly1CoapHandler coap;
103 private final ShellyTranslationProvider messages;
104 private final ShellyChannelCache cache;
105 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
107 private boolean gen2 = false;
108 private final boolean blu;
109 protected boolean autoCoIoT = false;
112 private boolean channelsCreated = false;
113 private boolean stopping = false;
114 private int vibrationFilter = 0;
115 private String lastWakeupReason = "";
118 private long watchdog = now();
119 protected int scheduledUpdates = 0;
120 private int skipCount = UPDATE_SKIP_COUNT;
121 private int skipUpdate = 0;
122 private boolean refreshSettings = false;
123 private @Nullable ScheduledFuture<?> statusJob;
124 private @Nullable ScheduledFuture<?> initJob;
129 * @param thing The Thing object
130 * @param translationProvider
131 * @param bindingConfig The binding configuration (beside thing
134 * @param coapServer coap server instance
135 * @param httpClient from httpService
137 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
138 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
139 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
142 this.thingName = getString(thing.getLabel());
143 this.messages = translationProvider;
144 this.cache = new ShellyChannelCache(this);
145 this.channelDefinitions = new ShellyChannelDefinitions(messages);
146 this.bindingConfig = bindingConfig;
147 this.config = getConfigAs(ShellyThingConfiguration.class);
148 this.httpClient = httpClient;
150 Map<String, String> properties = thing.getProperties();
151 String gen = getString(properties.get(PROPERTY_DEV_GEN));
152 String thingType = getThingType();
153 gen2 = "2".equals(gen) || ShellyDeviceProfile.isGeneration2(thingType);
154 blu = ShellyDeviceProfile.isBluSeries(thingType);
155 this.api = !blu ? !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this)
156 : new ShellyBluApi(thingName, thingTable, this);
158 config.eventsCoIoT = false;
160 if (config.eventsCoIoT) {
161 this.coap = new Shelly1CoapHandler(this, coapServer);
166 public boolean checkRepresentation(String key) {
167 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
168 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
172 * Schedule asynchronous Thing initialization, register thing to event dispatcher
175 public void initialize() {
176 // start background initialization:
177 initJob = scheduler.schedule(() -> {
178 boolean start = true;
180 initializeThingConfig();
181 logger.debug("{}: Device config: Device address={}, HTTP user/password={}/{}, update interval={}",
182 thingName, config.deviceAddress, config.userId.isEmpty() ? "<non>" : config.userId,
183 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
185 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
186 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
187 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
188 start = initializeThing();
189 } catch (ShellyApiException e) {
190 start = handleApiException(e);
191 } catch (IllegalArgumentException e) {
192 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
194 // even this initialization failed we start the status update
195 // the updateJob will then try to auto-initialize the thing
196 // in this case the thing stays in status INITIALIZING
201 }, 2, TimeUnit.SECONDS);
204 private boolean handleApiException(ShellyApiException e) {
205 ShellyApiResult res = e.getApiResult();
206 ThingStatusDetail errorCode = ThingStatusDetail.COMMUNICATION_ERROR;
208 boolean retry = true;
209 if (e.isJsonError()) { // invalid JSON format
210 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
211 status = "offline.status-error-unexpected-error";
212 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
214 } else if (res.isHttpAccessUnauthorized()) {
215 status = "offline.conf-error-access-denied";
216 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
218 } else if (isWatchdogExpired()) {
219 status = "offline.status-error-watchdog";
220 } else if (res.httpCode >= 400) {
221 logger.debug("{}: Unexpected API result: {}/{}", thingName, res.httpCode, res.httpReason, e);
222 status = "offline.status-error-unexpected-api-result";
224 } else if (profile.alwaysOn && (e.isConnectionError() || res.isHttpTimeout())) {
225 status = "offline.status-error-connect";
228 if (!status.isEmpty()) {
229 setThingOffline(errorCode, status, e.toString());
231 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
242 public ShellyThingConfiguration getThingConfig() {
247 public HttpClient getHttpClient() {
252 public void startScan() {
253 if (api.isInitialized()) {
259 * This routine is called every time the Thing configuration has been changed
262 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
263 super.handleConfigurationUpdate(configurationParameters);
264 logger.debug("{}: Thing config updated, re-initialize", thingName);
269 reinitializeThing();// force re-initialization
273 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
274 * If the device is password protected and the credentials are missing or don't match the API access will throw an
275 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
276 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
277 * credentials are correct and the API access is initialized successful.
279 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
281 public boolean initializeThing() throws ShellyApiException {
282 // Init from thing type to have a basic profile, gets updated when device info is received from API
283 refreshSettings = false;
284 lastWakeupReason = "";
285 cache.setThingName(thingName);
289 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
290 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
291 if (config.deviceAddress.isEmpty()) {
292 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
296 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
297 messages.get("status.unknown.initializing"));
299 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
300 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
301 // Action URL does when enabled)
302 profile.initFromThingType(thingType);
303 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
304 coap.start(thingName, config);
307 // Initialize API access, exceptions will be catched by initialize()
309 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
310 if (getBool(device.auth) && config.password.isEmpty()) {
311 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
314 if (config.serviceName.isEmpty()) {
315 config.serviceName = getString(device.hostname).toLowerCase();
318 api.setConfig(thingName, config);
319 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
320 String mode = getString(tmpPrf.device.mode);
321 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
322 changeThingType(thingName, mode);
323 return false; // force re-initialization
325 // Validate device mode
326 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
327 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
328 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode, reqMode);
331 if (!getString(tmpPrf.device.coiot).isEmpty()) {
332 // New Shelly devices might use a different endpoint for the CoAP listener
333 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
335 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
336 // Sensor, usually 12h, H&T in USB mode 10min
337 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
338 ? tmpPrf.settings.sleepMode.period * 60 // minutes
339 : tmpPrf.settings.sleepMode.period * 3600; // hours
340 tmpPrf.updatePeriod += 60; // give 1min extra
341 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
342 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
343 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
344 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
346 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
349 tmpPrf.status = api.getStatus(); // update thing properties
350 tmpPrf.updateFromStatus(tmpPrf.status);
351 addStateOptions(tmpPrf);
353 // update thing properties
354 updateProperties(tmpPrf, tmpPrf.status);
355 checkVersion(tmpPrf, tmpPrf.status);
357 startCoap(config, tmpPrf);
359 api.setActionURLs(); // register event urls
362 // All initialization done, so keep the profile and set Thing to ONLINE
363 fillDeviceStatus(tmpPrf.status, false);
364 postEvent(ALARM_TYPE_NONE, false);
367 showThingConfig(profile);
369 logger.debug("{}: Thing successfully initialized.", thingName);
370 updateProperties(profile, profile.status);
371 setThingOnline(); // if API call was successful the thing must be online
372 return true; // success
376 * Handle Channel Commands
379 public void handleCommand(ChannelUID channelUID, Command command) {
381 if (command instanceof RefreshType) {
382 String channelId = channelUID.getId();
383 State value = cache.getValue(channelId);
384 if (value != UnDefType.NULL) {
385 updateState(channelId, value);
390 if (!profile.isInitialized()) {
391 logger.debug("{}: {}", thingName, messages.get("command.init", command));
394 profile = getProfile(false);
397 boolean update = false;
398 switch (channelUID.getIdWithoutGroup()) {
399 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
400 logger.debug("{}: Send key {}", thingName, command);
401 api.sendIRKey(command.toString());
405 case CHANNEL_LED_STATUS_DISABLE:
406 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
407 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
409 case CHANNEL_LED_POWER_DISABLE:
410 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
411 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
414 case CHANNEL_SENSOR_SLEEPTIME:
415 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
416 int value = (int) getNumber(command);
417 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
419 api.setSleepTime(value);
421 case CHANNEL_CONTROL_SCHEDULE:
423 logger.debug("{}: {} Valve schedule/profile", thingName,
424 command == OnOffType.ON ? "Enable" : "Disable");
425 api.setValveProfile(0,
426 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
429 case CHANNEL_CONTROL_PROFILE:
430 logger.debug("{}: Select profile {}", thingName, command);
432 if (command instanceof Number) {
433 id = (int) getNumber(command);
435 String cmd = command.toString();
436 if (isDigit(cmd.charAt(0))) {
437 id = Integer.parseInt(cmd);
438 } else if (profile.settings.thermostats != null) {
439 ShellyThermnostat t = profile.settings.thermostats.get(0);
440 for (int i = 0; i < t.profileNames.length; i++) {
441 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
447 if (id < 0 || id > 5) {
448 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
451 api.setValveProfile(0, id);
453 case CHANNEL_CONTROL_MODE:
454 logger.debug("{}: Set mode to {}", thingName, command);
455 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
457 case CHANNEL_CONTROL_SETTEMP:
458 logger.debug("{}: Set temperature to {}", thingName, command);
459 api.setValveTemperature(0, (int) getNumber(command));
461 case CHANNEL_CONTROL_POSITION:
462 logger.debug("{}: Set position to {}", thingName, command);
463 api.setValvePosition(0, getNumber(command));
465 case CHANNEL_CONTROL_BCONTROL:
466 logger.debug("{}: Set boost mode to {}", thingName, command);
467 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
469 case CHANNEL_CONTROL_BTIMER:
470 logger.debug("{}: Set boost timer to {}", thingName, command);
471 api.setValveBoostTime(0, (int) getNumber(command));
473 case CHANNEL_SENSOR_MUTE:
474 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
475 logger.debug("{}: Mute Smoke Alarm", thingName);
476 api.muteSmokeAlarm(0);
477 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
481 update = handleDeviceCommand(channelUID, command);
486 if (update && !autoCoIoT && !isUpdateScheduled()) {
487 requestUpdates(1, false);
489 } catch (ShellyApiException e) {
490 if (!handleApiException(e)) {
494 ShellyApiResult res = e.getApiResult();
495 if (res.isNotCalibrtated()) {
496 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
498 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
502 String group = getString(channelUID.getGroupId());
503 String channel = getString(channelUID.getIdWithoutGroup());
504 State oldValue = getChannelValue(group, channel);
505 if (oldValue != UnDefType.NULL) {
506 logger.info("{}: Restore channel value to {}", thingName, oldValue);
507 updateChannel(group, channel, oldValue);
510 } catch (IllegalArgumentException e) {
511 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
515 private double getNumber(Command command) {
516 if (command instanceof QuantityType quantityCommand) {
517 return quantityCommand.doubleValue();
519 if (command instanceof DecimalType decimalCommand) {
520 return decimalCommand.doubleValue();
522 if (command instanceof Number numberCommand) {
523 return numberCommand.doubleValue();
525 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
529 * Update device status and channels
531 protected void refreshStatus() {
533 boolean updated = false;
535 if (vibrationFilter > 0) {
537 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
538 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
542 ThingStatus thingStatus = getThing().getStatus();
543 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
544 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
545 || (thingStatus == ThingStatus.UNKNOWN)) {
546 logger.debug("{}: Status update triggered thing initialization", thingName);
547 initializeThing(); // may fire an exception if initialization failed
549 ShellySettingsStatus status = api.getStatus();
550 boolean restarted = checkRestarted(status);
551 profile = getProfile(refreshSettings || restarted);
552 profile.status = status;
553 profile.updateFromStatus(status);
555 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
557 postEvent(ALARM_TYPE_RESTARTED, true);
560 // If status update was successful the thing must be online,
561 // but not while firmware update is in progress
562 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
566 // map status to channels
567 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
568 updated |= this.updateDeviceStatus(status);
569 updated |= ShellyComponents.updateDeviceStatus(this, status);
570 fillDeviceStatus(status, updated);
571 updated |= updateInputs(status);
572 updated |= updateMeters(this, status);
573 updated |= updateSensors(this, status);
575 // All channels must be created after the first cycle
576 channelsCreated = true;
578 } catch (ShellyApiException e) {
579 // http call failed: go offline except for battery devices, which might be in
580 // sleep mode. Once the next update is successful the device goes back online
581 handleApiException(e);
582 } catch (NullPointerException | IllegalArgumentException e) {
583 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
585 if (scheduledUpdates > 0) {
587 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
588 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
589 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
590 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
596 private void showThingConfig(ShellyDeviceProfile profile) {
597 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
598 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
600 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
601 logger.debug("{}: Device "
602 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
603 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
604 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
605 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
606 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
607 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
608 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
609 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
610 if (profile.status.extTemperature != null || profile.status.extHumidity != null
611 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
612 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
616 private void addStateOptions(ShellyDeviceProfile prf) {
618 String[] profileNames = prf.getValveProfileList(0);
619 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
620 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
621 channelDefinitions.clearStateOptions(channelId);
623 for (String name : profileNames) {
624 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
628 if (prf.isRoller && prf.settings.favorites != null) {
629 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
630 logger.debug("{}: Adding {} roler favorite(s) to channel description", thingName,
631 prf.settings.favorites.size());
632 channelDefinitions.clearStateOptions(channelId);
634 for (ShellyFavPos fav : prf.settings.favorites) {
635 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
642 public String getThingType() {
643 return thing.getThingTypeUID().getId();
647 public ThingStatus getThingStatus() {
648 return thing.getStatus();
652 public ThingStatusDetail getThingStatusDetail() {
653 return thing.getStatusInfo().getStatusDetail();
657 public boolean isThingOnline() {
658 return getThingStatus() == ThingStatus.ONLINE;
661 public boolean isThingOffline() {
662 return getThingStatus() == ThingStatus.OFFLINE;
666 public void setThingOnline() {
667 if (!isThingOnline()) {
668 updateStatus(ThingStatus.ONLINE);
670 // request 3 updates in a row (during the first 2+3*3 sec)
671 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
674 // Restart watchdog when status update was successful (no exception)
679 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
680 if (!isThingOffline()) {
681 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
682 api.close(); // Gen2: disconnect WS/close http sessions
684 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
689 public void restartWatchdog() {
691 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
692 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
695 private boolean isWatchdogExpired() {
696 long delta = now() - watchdog;
697 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
698 stats.remainingWatchdog = delta;
704 private boolean isWatchdogStarted() {
709 public void reinitializeThing() {
710 logger.debug("{}: Re-Initialize Thing", thingName);
712 logger.debug("{}: Handler is shutting down, ignore", thingName);
715 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
716 messages.get("offline.status-error-restarted"));
717 requestUpdates(0, true);
721 public boolean isStopping() {
726 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
729 // Update uptime and WiFi, internal temp
730 ShellyComponents.updateDeviceStatus(this, status);
731 stats.wifiRssi = getInteger(status.wifiSta.rssi);
733 if (api.isInitialized()) {
734 stats.timeoutErrors = api.getTimeoutErrors();
735 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
737 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
739 // Check various device indicators like overheating
740 if (checkRestarted(status)) {
741 // Force re-initialization on next status update
743 } else if (getBool(status.overtemperature)) {
744 alarm = ALARM_TYPE_OVERTEMP;
745 } else if (getBool(status.overload)) {
746 alarm = ALARM_TYPE_OVERLOAD;
747 } else if (getBool(status.loaderror)) {
748 alarm = ALARM_TYPE_LOADERR;
750 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
751 if (internalTemp != UnDefType.NULL) {
752 int temp = ((Number) internalTemp).intValue();
753 if (temp > stats.maxInternalTemp) {
754 stats.maxInternalTemp = temp;
758 if (status.uptime != null) {
759 stats.lastUptime = getLong(status.uptime);
762 if (!alarm.isEmpty()) {
763 postEvent(alarm, false);
768 public void incProtMessages() {
769 stats.protocolMessages++;
773 public void incProtErrors() {
774 stats.protocolErrors++;
778 * Check if device has restarted and needs a new Thing initialization
780 * @return true: restart detected
783 private boolean checkRestarted(ShellySettingsStatus status) {
784 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
785 && (status.uptime != null && status.uptime < stats.lastUptime
786 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
787 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
788 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
789 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
790 updateProperties(profile, status);
797 * Save alarm to the lastAlarm channel
799 * @param event Alarm Message
803 public void postEvent(String event, boolean force) {
804 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
805 State value = cache.getValue(channelId);
806 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
808 if (force || !lastAlarm.equals(event)
809 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
810 switch (event.toUpperCase()) {
813 case SHELLY_WAKEUPT_SENSOR:
814 case SHELLY_WAKEUPT_PERIODIC:
815 case SHELLY_WAKEUPT_BUTTON:
816 case SHELLY_WAKEUPT_POWERON:
817 case SHELLY_WAKEUPT_EXT_POWER:
818 case SHELLY_WAKEUPT_UNKNOWN:
819 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
820 case ALARM_TYPE_NONE:
823 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
824 triggerChannel(channelId, event);
825 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
826 stats.lastAlarm = event;
827 stats.lastAlarmTs = now();
833 public boolean isUpdateScheduled() {
834 return scheduledUpdates > 0;
838 * Callback for device events
841 * @param deviceName device receiving the event
843 * @param type the HTML input data
844 * @param parameters parameters from the event URL
845 * @return true if event was processed
848 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
849 Map<String, String> parameters) {
850 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
851 || config.serviceName.equals(deviceName)) {
852 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
854 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
855 if (!profile.isInitialized()) {
856 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
857 requestUpdates(1, true);
859 String group = profile.getControlGroup(idx);
860 if (group.isEmpty()) {
861 logger.debug("{}: Unsupported event class: {}", thingName, type);
865 // map some of the events to system defined button triggers
869 String parmType = getString(parameters.get("type"));
870 String event = !parmType.isEmpty() ? parmType : type;
871 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
873 case SHELLY_EVENT_SHORTPUSH:
874 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
875 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
876 case SHELLY_EVENT_LONGPUSH:
878 triggerButton(group, idx, mapButtonEvent(event));
879 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
880 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
882 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
886 case SHELLY_EVENT_BTN_ON:
887 case SHELLY_EVENT_BTN_OFF:
888 if (profile.isRGBW2) {
889 // RGBW2 has only one input, so not per channel
890 group = CHANNEL_GROUP_LIGHT_CONTROL;
892 onoff = CHANNEL_INPUT;
894 case SHELLY_EVENT_BTN1_ON:
895 case SHELLY_EVENT_BTN1_OFF:
896 onoff = CHANNEL_INPUT1;
898 case SHELLY_EVENT_BTN2_ON:
899 case SHELLY_EVENT_BTN2_OFF:
900 onoff = CHANNEL_INPUT2;
902 case SHELLY_EVENT_OUT_ON:
903 case SHELLY_EVENT_OUT_OFF:
904 onoff = CHANNEL_OUTPUT;
906 case SHELLY_EVENT_ROLLER_OPEN:
907 case SHELLY_EVENT_ROLLER_CLOSE:
908 case SHELLY_EVENT_ROLLER_STOP:
909 channel = CHANNEL_EVENT_TRIGGER;
912 case SHELLY_EVENT_SENSORREPORT:
913 // process sensor with next refresh
915 case SHELLY_EVENT_TEMP_OVER: // DW2
916 case SHELLY_EVENT_TEMP_UNDER:
917 channel = CHANNEL_EVENT_TRIGGER;
920 case SHELLY_EVENT_FLOOD_DETECTED:
921 case SHELLY_EVENT_FLOOD_GONE:
922 updateChannel(group, CHANNEL_SENSOR_FLOOD,
923 OnOffType.from(event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED)));
926 case SHELLY_EVENT_CLOSE: // DW 1.7
927 case SHELLY_EVENT_OPEN: // DW 1.7
928 updateChannel(group, CHANNEL_SENSOR_STATE,
929 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
930 : OpenClosedType.CLOSED);
933 case SHELLY_EVENT_DARK: // DW 1.7
934 case SHELLY_EVENT_TWILIGHT: // DW 1.7
935 case SHELLY_EVENT_BRIGHT: // DW 1.7
936 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
939 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
940 case SHELLY_EVENT_ALARM_HEAVY:
941 case SHELLY_EVENT_ALARM_OFF:
942 case SHELLY_EVENT_VIBRATION: // DW2
943 channel = CHANNEL_SENSOR_ALARM_STATE;
944 payload = event.toUpperCase();
948 // trigger will be provided by input/output channel or sensor channels
951 if (!onoff.isEmpty()) {
952 updateChannel(group, onoff, OnOffType.from(event.toLowerCase().contains("_on")));
954 if (!payload.isEmpty()) {
955 // Pass event to trigger channel
956 payload = payload.toUpperCase();
957 logger.debug("{}: Post event {}", thingName, payload);
958 triggerChannel(mkChannelId(group, channel), payload);
962 // request update on next interval (2x for non-battery devices)
964 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
971 * Initialize the binding's thing configuration, calc update counts
973 protected void initializeThingConfig() {
974 thingType = getThing().getThingTypeUID().getId();
975 final Map<String, String> properties = getThing().getProperties();
976 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
977 if (thingName.isEmpty()) {
978 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
981 config = getConfigAs(ShellyThingConfiguration.class);
982 if (config.deviceAddress.isEmpty()) {
983 config.deviceAddress = config.deviceIp;
985 if (config.deviceAddress.isEmpty()) {
986 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
991 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
992 // convert to lower case
993 if (!config.deviceIp.isEmpty()) {
995 InetAddress addr = InetAddress.getByName(config.deviceIp);
996 String saddr = addr.getHostAddress();
997 if (!config.deviceIp.equals(saddr)) {
998 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
999 config.deviceIp = saddr;
1001 } catch (UnknownHostException e) {
1002 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1006 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1007 config.localIp = bindingConfig.localIP;
1008 config.localPort = String.valueOf(bindingConfig.httpPort);
1009 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1010 // Gen2 has hard coded user "admin"
1011 config.userId = bindingConfig.defaultUserId;
1012 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1014 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1015 config.password = bindingConfig.defaultPassword;
1016 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1019 if (config.updateInterval == 0) {
1020 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1022 if (config.updateInterval < UPDATE_MIN_DELAY) {
1023 config.updateInterval = UPDATE_MIN_DELAY;
1026 // Try to get updatePeriod from properties
1027 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1028 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1029 // initialized successfully by the REST call.
1030 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1031 if (!lastPeriod.isEmpty()) {
1032 int period = Integer.parseInt(lastPeriod);
1034 profile.updatePeriod = period;
1038 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1039 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1042 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1044 if (prf.fwVersion.isEmpty()) {
1045 // no fw version available (e.g. BLU device)
1048 ShellyVersionDTO version = new ShellyVersionDTO();
1049 if (version.checkBeta(getString(prf.fwVersion))) {
1050 logger.info("{}: {}", prf.device.hostname,
1051 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1053 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1054 if (version.compare(prf.fwVersion, minVersion) < 0) {
1055 logger.warn("{}: {}", prf.device.hostname,
1056 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1059 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1060 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1061 if (!config.eventsCoIoT) {
1062 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1066 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1067 logger.info("{}: {}", thingName,
1068 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1070 } catch (NullPointerException e) { // could be inconsistant format of beta version
1071 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1075 public String checkForUpdate() {
1077 ShellyOtaCheckResult result = api.checkForUpdate();
1078 return result.status;
1079 } catch (ShellyApiException e) {
1084 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1085 if (coap == null || !config.eventsCoIoT) {
1088 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1089 String devpeer = getString(profile.settings.coiot.peer);
1090 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1091 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1093 api.setCoIoTPeer(ourpeer);
1094 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1095 } catch (ShellyApiException e) {
1096 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1098 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1099 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1103 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1104 config.eventsCoIoT = true;
1105 config.eventsSwitch = false;
1106 config.eventsButton = false;
1107 config.eventsPush = false;
1108 config.eventsRoller = false;
1109 config.eventsSensorReport = false;
1110 api.setConfig(thingName, config);
1113 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1115 coap.start(thingName, config);
1120 * Change type of this thing.
1122 * @param thingType thing type acc. to the xml definition
1123 * @param mode Device mode (e.g. relay, roller)
1125 protected void changeThingType(String thingType, String mode) {
1126 String deviceType = substringBefore(thingType, "-");
1127 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1128 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1129 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1130 Map<String, String> properties = editProperties();
1131 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1132 properties.replace(PROPERTY_DEV_MODE, mode);
1133 updateProperties(properties);
1134 changeThingType(thingTypeUID, getConfig());
1139 public void thingUpdated(Thing thing) {
1140 logger.debug("{}: Channel definitions updated.", thingName);
1141 super.thingUpdated(thing);
1145 * Start the background updates
1147 protected void startUpdateJob() {
1148 ScheduledFuture<?> statusJob = this.statusJob;
1149 if ((statusJob == null) || statusJob.isCancelled()) {
1150 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1152 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1153 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1158 * Flag the status job to do an exceptional update (something happened) rather
1159 * than waiting until the next regular poll
1161 * @param requestCount number of polls to execute
1162 * @param refreshSettings true=force a /settings query
1163 * @return true=Update schedule, false=skipped (too many updates already
1167 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1168 this.refreshSettings |= refreshSettings;
1169 if (refreshSettings) {
1170 if (requestCount == 0) {
1171 logger.debug("{}: Request settings refresh", thingName);
1173 scheduledUpdates = 1;
1176 if (scheduledUpdates < 10) { // < 30s
1177 scheduledUpdates += requestCount;
1184 * Map input states to channels
1186 * @param status Shelly device status
1187 * @return true: one or more inputs were updated
1190 public boolean updateInputs(ShellySettingsStatus status) {
1191 boolean updated = false;
1193 if (status.inputs != null) {
1194 if (!areChannelsCreated()) {
1195 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1199 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1200 for (ShellyInputState input : status.inputs) {
1201 String group = profile.getInputGroup(idx);
1202 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1203 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1204 if (input.event != null) {
1205 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1206 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1211 if (status.input != null) {
1212 // RGBW2: a single int rather than an array
1213 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1214 OnOffType.from(getInteger(status.input) != 0));
1221 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1222 boolean changed = false;
1223 if (valueArray != null && !valueArray.isEmpty()) {
1224 String reason = getString((String) valueArray.get(0));
1225 String newVal = valueArray.toString();
1226 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1227 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1229 postEvent(reason.toUpperCase(), true);
1231 lastWakeupReason = newVal;
1237 public void triggerButton(String group, int idx, String value) {
1238 String trigger = mapButtonEvent(value);
1239 if (trigger.isEmpty()) {
1243 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1244 triggerChannel(group,
1245 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1247 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1248 if (profile.alwaysOn) {
1249 // refresh status of the input channel
1250 requestUpdates(1, false);
1255 public void publishState(String channelId, State value) {
1256 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1257 if (!stopping && isLinked(id)) {
1258 updateState(id, value);
1259 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1264 public boolean updateChannel(String group, String channel, State value) {
1265 return updateChannel(mkChannelId(group, channel), value, false);
1269 public boolean updateChannel(String channelId, State value, boolean force) {
1270 return !stopping && cache.updateChannel(channelId, value, force);
1274 public State getChannelValue(String group, String channel) {
1275 return cache.getValue(group, channel);
1279 public double getChannelDouble(String group, String channel) {
1280 State value = getChannelValue(group, channel);
1281 if (value != UnDefType.NULL) {
1282 if (value instanceof QuantityType quantityCommand) {
1283 return quantityCommand.toBigDecimal().doubleValue();
1285 if (value instanceof DecimalType decimalCommand) {
1286 return decimalCommand.doubleValue();
1293 * Update Thing's channels according to available status information from the API
1295 * @param dynChannels
1298 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1299 if (channelsCreated) {
1300 return; // already done
1304 // Get subset of those channels that currently do not exist
1305 List<Channel> existingChannels = getThing().getChannels();
1306 for (Channel channel : existingChannels) {
1307 String id = channel.getUID().getId();
1308 if (dynChannels.containsKey(id)) {
1309 dynChannels.remove(id);
1313 if (!dynChannels.isEmpty()) {
1314 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1315 ThingBuilder thingBuilder = editThing();
1316 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1317 Channel c = channel.getValue();
1318 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1319 thingBuilder.withChannel(c);
1321 updateThing(thingBuilder.build());
1322 logger.debug("{}: Channel definitions updated", thingName);
1324 } catch (IllegalArgumentException e) {
1325 logger.debug("{}: Unable to update channel definitions", thingName, e);
1330 public boolean areChannelsCreated() {
1331 return channelsCreated;
1335 * Update thing properties with dynamic values
1337 * @param profile The device profile
1338 * @param status the /status result
1340 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1341 Map<String, Object> properties = fillDeviceProperties(profile);
1342 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1343 String deviceName = getString(profile.settings.name);
1344 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1345 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1346 properties.put(PROPERTY_DEV_AUTH, getBool(profile.device.auth) ? "yes" : "no");
1347 if (!deviceName.isEmpty()) {
1348 properties.put(PROPERTY_DEV_NAME, deviceName);
1351 // add status properties
1352 if (status.wifiSta != null) {
1353 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1355 if (status.update != null) {
1356 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1357 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1358 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1359 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1361 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1363 Map<String, String> thingProperties = new TreeMap<>();
1364 for (Map.Entry<String, Object> property : properties.entrySet()) {
1365 thingProperties.put(property.getKey(), (String) property.getValue());
1367 flushProperties(thingProperties);
1371 * Add one property to the Thing Properties
1373 * @param key Name of the property
1374 * @param value Value of the property
1377 public void updateProperties(String key, String value) {
1378 Map<String, String> thingProperties = editProperties();
1379 if (thingProperties.containsKey(key)) {
1380 thingProperties.replace(key, value);
1382 thingProperties.put(key, value);
1384 updateProperties(thingProperties);
1385 logger.trace("{}: Properties updated", thingName);
1388 public void flushProperties(Map<String, String> propertyUpdates) {
1389 Map<String, String> thingProperties = editProperties();
1390 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1391 if (thingProperties.containsKey(property.getKey())) {
1392 thingProperties.replace(property.getKey(), property.getValue());
1394 thingProperties.put(property.getKey(), property.getValue());
1397 updateProperties(thingProperties);
1401 * Get one property from the Thing Properties
1403 * @param key property name
1404 * @return property value or "" if property is not set
1407 public String getProperty(String key) {
1408 Map<String, String> thingProperties = getThing().getProperties();
1409 return getString(thingProperties.get(key));
1413 * Fill Thing Properties with device attributes
1415 * @param profile Property Map to full
1416 * @return a full property map
1418 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1419 Map<String, Object> properties = new TreeMap<>();
1420 properties.put(PROPERTY_VENDOR, VENDOR);
1421 if (profile.isInitialized()) {
1422 properties.put(PROPERTY_MODEL_ID, getString(profile.device.type));
1423 properties.put(PROPERTY_MAC_ADDRESS, profile.device.mac);
1424 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1425 properties.put(PROPERTY_DEV_MODE, profile.device.mode);
1426 if (profile.hasRelays) {
1427 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1428 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1429 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1431 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1432 if (!profile.hwRev.isEmpty()) {
1433 properties.put(PROPERTY_HWREV, profile.hwRev);
1434 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1441 * Return device profile.
1443 * @param forceRefresh true=force refresh before returning, false=return without
1445 * @return ShellyDeviceProfile instance
1446 * @throws ShellyApiException
1449 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1451 refreshSettings |= forceRefresh;
1452 if (refreshSettings) {
1453 profile = api.getDeviceProfile(thingType, null);
1454 if (!isThingOnline()) {
1455 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1459 refreshSettings = false;
1465 public ShellyDeviceProfile getProfile() {
1470 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1471 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1472 if (!options.isEmpty()) {
1473 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1479 protected ShellyDeviceProfile getDeviceProfile() {
1484 public void triggerChannel(String group, String channel, String payload) {
1485 String triggerCh = mkChannelId(group, channel);
1486 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1487 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1488 if (vibrationFilter == 0) {
1489 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1490 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1491 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1493 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1494 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1499 triggerChannel(triggerCh, payload);
1502 public void stop() {
1503 logger.debug("{}: Shutting down", thingName);
1504 ScheduledFuture<?> job = this.initJob;
1509 job = this.statusJob;
1513 logger.debug("{}: Shelly statusJob stopped", thingName);
1516 profile.initialized = false;
1520 * Shutdown thing, make sure background jobs are canceled
1523 public void dispose() {
1524 logger.debug("{}: Stopping Thing", thingName);
1531 * Device specific command handlers are overriding this method to do additional stuff
1533 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1537 public String getUID() {
1538 return getThing().getUID().getAsString();
1542 * Device specific handlers are overriding this method to do additional stuff
1544 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1549 public String getThingName() {
1554 public void resetStats() {
1556 stats = new ShellyDeviceStats();
1560 public ShellyDeviceStats getStats() {
1565 public ShellyApiInterface getApi() {
1570 public long getScheduledUpdates() {
1571 return scheduledUpdates;
1574 public Map<String, String> getStatsProp() {
1575 return stats.asProperties();
1579 public void triggerUpdateFromCoap() {
1580 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1581 requestUpdates(1, false);