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 bindingConfig The binding configuration (beside thing
132 * @param coapServer coap server instance
133 * @param localIP local IP address from networkAddressService
134 * @param httpPort from httpService
136 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
137 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
138 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
141 this.thingName = getString(thing.getLabel());
142 this.messages = translationProvider;
143 this.cache = new ShellyChannelCache(this);
144 this.channelDefinitions = new ShellyChannelDefinitions(messages);
145 this.bindingConfig = bindingConfig;
146 this.config = getConfigAs(ShellyThingConfiguration.class);
147 this.httpClient = httpClient;
149 Map<String, String> properties = thing.getProperties();
150 String gen = getString(properties.get(PROPERTY_DEV_GEN));
151 String thingType = getThingType();
152 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
155 gen2 = "2".equals(gen);
156 blu = thingType.startsWith("shellyblu");
157 this.api = !blu ? !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this)
158 : new ShellyBluApi(thingName, thingTable, this);
160 config.eventsCoIoT = false;
162 if (config.eventsCoIoT) {
163 this.coap = new Shelly1CoapHandler(this, coapServer);
168 public boolean checkRepresentation(String key) {
169 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
170 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
174 * Schedule asynchronous Thing initialization, register thing to event dispatcher
177 public void initialize() {
178 // start background initialization:
179 initJob = scheduler.schedule(() -> {
180 boolean start = true;
182 initializeThingConfig();
183 logger.debug("{}: Device config: Device address={}, HTTP user/password={}/{}, update interval={}",
184 thingName, config.deviceAddress, config.userId.isEmpty() ? "<non>" : config.userId,
185 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
187 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
188 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
189 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
190 start = initializeThing();
191 } catch (ShellyApiException e) {
192 ShellyApiResult res = e.getApiResult();
194 if (e.isJsonError()) { // invalid JSON format
195 mid = "offline.status-error-unexpected-error";
197 } else if (isAuthorizationFailed(res)) {
198 mid = "offline.conf-error-access-denied";
200 } else if (profile.alwaysOn && e.isConnectionError()) {
201 mid = "offline.status-error-connect";
203 if (!mid.isEmpty()) {
204 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
206 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
207 } catch (IllegalArgumentException e) {
208 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
210 // even this initialization failed we start the status update
211 // the updateJob will then try to auto-initialize the thing
212 // in this case the thing stays in status INITIALIZING
217 }, 2, TimeUnit.SECONDS);
221 public ShellyThingConfiguration getThingConfig() {
226 public HttpClient getHttpClient() {
231 public void startScan() {
232 if (api.isInitialized()) {
238 * This routine is called every time the Thing configuration has been changed
241 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
242 super.handleConfigurationUpdate(configurationParameters);
243 logger.debug("{}: Thing config updated, re-initialize", thingName);
248 reinitializeThing();// force re-initialization
252 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
253 * If the device is password protected and the credentials are missing or don't match the API access will throw an
254 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
255 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
256 * credentials are correct and the API access is initialized successful.
258 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
260 public boolean initializeThing() throws ShellyApiException {
261 // Init from thing type to have a basic profile, gets updated when device info is received from API
262 refreshSettings = false;
263 lastWakeupReason = "";
264 cache.setThingName(thingName);
268 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
269 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
270 if (config.deviceAddress.isEmpty()) {
271 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
275 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
276 messages.get("status.unknown.initializing"));
278 profile.initFromThingType(thingType); // do some basic initialization
280 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
281 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
282 // Action URL does when enabled)
283 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
284 coap.start(thingName, config);
287 // Initialize API access, exceptions will be catched by initialize()
289 ShellySettingsDevice devInfo = api.getDeviceInfo();
290 if (getBool(devInfo.auth) && config.password.isEmpty()) {
291 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
294 if (config.serviceName.isEmpty()) {
295 config.serviceName = getString(profile.hostname).toLowerCase();
298 api.setConfig(thingName, config);
299 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
300 tmpPrf.isGen2 = gen2;
301 tmpPrf.auth = devInfo.auth; // missing in /settings
303 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
304 changeThingType(thingName, tmpPrf.mode);
305 return false; // force re-initialization
307 // Validate device mode
308 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
309 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
310 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
314 if (!getString(devInfo.coiot).isEmpty()) {
315 // New Shelly devices might use a different endpoint for the CoAP listener
316 tmpPrf.coiotEndpoint = devInfo.coiot;
318 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
319 // Sensor, usually 12h, H&T in USB mode 10min
320 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
321 ? tmpPrf.settings.sleepMode.period * 60 // minutes
322 : tmpPrf.settings.sleepMode.period * 3600; // hours
323 tmpPrf.updatePeriod += 60; // give 1min extra
324 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
325 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
326 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
327 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
329 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
332 tmpPrf.status = api.getStatus(); // update thing properties
333 tmpPrf.updateFromStatus(tmpPrf.status);
334 addStateOptions(tmpPrf);
336 // update thing properties
337 updateProperties(tmpPrf, tmpPrf.status);
338 checkVersion(tmpPrf, tmpPrf.status);
340 startCoap(config, tmpPrf);
342 api.setActionURLs(); // register event urls
345 // All initialization done, so keep the profile and set Thing to ONLINE
346 fillDeviceStatus(tmpPrf.status, false);
347 postEvent(ALARM_TYPE_NONE, false);
350 showThingConfig(profile);
352 logger.debug("{}: Thing successfully initialized.", thingName);
353 updateProperties(profile, profile.status);
354 setThingOnline(); // if API call was successful the thing must be online
355 return true; // success
359 * Handle Channel Commands
362 public void handleCommand(ChannelUID channelUID, Command command) {
364 if (command instanceof RefreshType) {
365 String channelId = channelUID.getId();
366 State value = cache.getValue(channelId);
367 if (value != UnDefType.NULL) {
368 updateState(channelId, value);
373 if (!profile.isInitialized()) {
374 logger.debug("{}: {}", thingName, messages.get("command.init", command));
377 profile = getProfile(false);
380 boolean update = false;
381 switch (channelUID.getIdWithoutGroup()) {
382 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
383 logger.debug("{}: Send key {}", thingName, command);
384 api.sendIRKey(command.toString());
388 case CHANNEL_LED_STATUS_DISABLE:
389 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
390 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
392 case CHANNEL_LED_POWER_DISABLE:
393 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
394 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
397 case CHANNEL_SENSOR_SLEEPTIME:
398 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
399 int value = (int) getNumber(command);
400 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
402 api.setSleepTime(value);
404 case CHANNEL_CONTROL_SCHEDULE:
406 logger.debug("{}: {} Valve schedule/profile", thingName,
407 command == OnOffType.ON ? "Enable" : "Disable");
408 api.setValveProfile(0,
409 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
412 case CHANNEL_CONTROL_PROFILE:
413 logger.debug("{}: Select profile {}", thingName, command);
415 if (command instanceof Number) {
416 id = (int) getNumber(command);
418 String cmd = command.toString();
419 if (isDigit(cmd.charAt(0))) {
420 id = Integer.parseInt(cmd);
421 } else if (profile.settings.thermostats != null) {
422 ShellyThermnostat t = profile.settings.thermostats.get(0);
423 for (int i = 0; i < t.profileNames.length; i++) {
424 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
430 if (id < 0 || id > 5) {
431 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
434 api.setValveProfile(0, id);
436 case CHANNEL_CONTROL_MODE:
437 logger.debug("{}: Set mode to {}", thingName, command);
438 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
440 case CHANNEL_CONTROL_SETTEMP:
441 logger.debug("{}: Set temperature to {}", thingName, command);
442 api.setValveTemperature(0, (int) getNumber(command));
444 case CHANNEL_CONTROL_POSITION:
445 logger.debug("{}: Set position to {}", thingName, command);
446 api.setValvePosition(0, getNumber(command));
448 case CHANNEL_CONTROL_BCONTROL:
449 logger.debug("{}: Set boost mode to {}", thingName, command);
450 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
452 case CHANNEL_CONTROL_BTIMER:
453 logger.debug("{}: Set boost timer to {}", thingName, command);
454 api.setValveBoostTime(0, (int) getNumber(command));
456 case CHANNEL_SENSOR_MUTE:
457 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
458 logger.debug("{}: Mute Smoke Alarm", thingName);
459 api.muteSmokeAlarm(0);
460 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
464 update = handleDeviceCommand(channelUID, command);
469 if (update && !autoCoIoT && !isUpdateScheduled()) {
470 requestUpdates(1, false);
472 } catch (ShellyApiException e) {
473 ShellyApiResult res = e.getApiResult();
474 if (isAuthorizationFailed(res)) {
477 if (res.isNotCalibrtated()) {
478 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
480 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
484 String group = getString(channelUID.getGroupId());
485 String channel = getString(channelUID.getIdWithoutGroup());
486 State oldValue = getChannelValue(group, channel);
487 if (oldValue != UnDefType.NULL) {
488 logger.info("{}: Restore channel value to {}", thingName, oldValue);
489 updateChannel(group, channel, oldValue);
492 } catch (IllegalArgumentException e) {
493 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
497 private double getNumber(Command command) {
498 if (command instanceof QuantityType quantityCommand) {
499 return quantityCommand.doubleValue();
501 if (command instanceof DecimalType decimalCommand) {
502 return decimalCommand.doubleValue();
504 if (command instanceof Number numberCommand) {
505 return numberCommand.doubleValue();
507 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
511 * Update device status and channels
513 protected void refreshStatus() {
515 boolean updated = false;
517 if (vibrationFilter > 0) {
519 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
520 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
524 ThingStatus thingStatus = getThing().getStatus();
525 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
526 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
527 || (thingStatus == ThingStatus.UNKNOWN)) {
528 logger.debug("{}: Status update triggered thing initialization", thingName);
529 initializeThing(); // may fire an exception if initialization failed
531 ShellySettingsStatus status = api.getStatus();
532 boolean restarted = checkRestarted(status);
533 profile = getProfile(refreshSettings || restarted);
534 profile.status = status;
535 profile.updateFromStatus(status);
537 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
539 postEvent(ALARM_TYPE_RESTARTED, true);
542 // If status update was successful the thing must be online,
543 // but not while firmware update is in progress
544 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
548 // map status to channels
549 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
550 updated |= this.updateDeviceStatus(status);
551 updated |= ShellyComponents.updateDeviceStatus(this, status);
552 fillDeviceStatus(status, updated);
553 updated |= updateInputs(status);
554 updated |= updateMeters(this, status);
555 updated |= updateSensors(this, status);
557 // All channels must be created after the first cycle
558 channelsCreated = true;
560 } catch (ShellyApiException e) {
561 // http call failed: go offline except for battery devices, which might be in
562 // sleep mode. Once the next update is successful the device goes back online
564 ShellyApiResult res = e.getApiResult();
565 if (profile.alwaysOn && e.isConnectionError()) {
566 status = "offline.status-error-connect";
567 } else if (res.isHttpAccessUnauthorized()) {
568 status = "offline.conf-error-access-denied";
569 } else if (isWatchdogStarted()) {
570 if (!isWatchdogExpired()) {
571 logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
573 if (isThingOnline()) {
574 status = "offline.status-error-watchdog";
577 } else if (e.isJSONException()) {
578 status = "offline.status-error-unexpected-api-result";
579 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
580 } else if (res.isHttpTimeout()) {
581 // Watchdog not started, e.g. device in sleep mode
582 if (isThingOnline()) { // ignore when already offline
583 status = "offline.status-error-watchdog";
586 status = "offline.status-error-unexpected-api-result";
587 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
590 if (!status.isEmpty()) {
591 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
593 } catch (NullPointerException | IllegalArgumentException e) {
594 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
596 if (scheduledUpdates > 0) {
598 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
599 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
600 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
601 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
607 private void showThingConfig(ShellyDeviceProfile profile) {
608 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
609 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
611 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
615 hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}\
616 ,isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}\
617 ,alwaysOn:{}, updatePeriod:{}sec\
619 thingName, profile.hasRelays, profile.numRelays, profile.isRoller, profile.numRollers, profile.isDimmer,
620 profile.numMeters, profile.isEMeter, profile.settings.extSwitch != null ? "installed" : "n/a",
621 profile.isSensor, profile.isDW, profile.hasBattery,
622 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
623 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
624 profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
625 if (profile.status.extTemperature != null || profile.status.extHumidity != null
626 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
627 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
631 private void addStateOptions(ShellyDeviceProfile prf) {
633 String[] profileNames = prf.getValveProfileList(0);
634 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
635 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
636 channelDefinitions.clearStateOptions(channelId);
638 for (String name : profileNames) {
639 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
643 if (prf.isRoller && prf.settings.favorites != null) {
644 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
645 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
646 prf.settings.favorites.size());
647 channelDefinitions.clearStateOptions(channelId);
649 for (ShellyFavPos fav : prf.settings.favorites) {
650 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
657 public String getThingType() {
658 return thing.getThingTypeUID().getId();
662 public ThingStatus getThingStatus() {
663 return thing.getStatus();
667 public ThingStatusDetail getThingStatusDetail() {
668 return thing.getStatusInfo().getStatusDetail();
672 public boolean isThingOnline() {
673 return getThingStatus() == ThingStatus.ONLINE;
676 public boolean isThingOffline() {
677 return getThingStatus() == ThingStatus.OFFLINE;
681 public void setThingOnline() {
682 if (!isThingOnline()) {
683 updateStatus(ThingStatus.ONLINE);
685 // request 3 updates in a row (during the first 2+3*3 sec)
686 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
689 // Restart watchdog when status update was successful (no exception)
694 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
695 if (!isThingOffline()) {
696 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
697 api.close(); // Gen2: disconnect WS/close http sessions
699 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
704 public void restartWatchdog() {
706 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
707 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
710 private boolean isWatchdogExpired() {
711 long delta = now() - watchdog;
712 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
713 stats.remainingWatchdog = delta;
719 private boolean isWatchdogStarted() {
724 public void reinitializeThing() {
725 logger.debug("{}: Re-Initialize Thing", thingName);
727 logger.debug("{}: Handler is shutting down, ignore", thingName);
730 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
731 messages.get("offline.status-error-restarted"));
732 requestUpdates(0, true);
736 public boolean isStopping() {
741 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
744 // Update uptime and WiFi, internal temp
745 ShellyComponents.updateDeviceStatus(this, status);
746 stats.wifiRssi = getInteger(status.wifiSta.rssi);
748 if (api.isInitialized()) {
749 stats.timeoutErrors = api.getTimeoutErrors();
750 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
752 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
754 // Check various device indicators like overheating
755 if (checkRestarted(status)) {
756 // Force re-initialization on next status update
758 } else if (getBool(status.overtemperature)) {
759 alarm = ALARM_TYPE_OVERTEMP;
760 } else if (getBool(status.overload)) {
761 alarm = ALARM_TYPE_OVERLOAD;
762 } else if (getBool(status.loaderror)) {
763 alarm = ALARM_TYPE_LOADERR;
765 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
766 if (internalTemp != UnDefType.NULL) {
767 int temp = ((Number) internalTemp).intValue();
768 if (temp > stats.maxInternalTemp) {
769 stats.maxInternalTemp = temp;
773 if (status.uptime != null) {
774 stats.lastUptime = getLong(status.uptime);
777 if (!alarm.isEmpty()) {
778 postEvent(alarm, false);
783 public void incProtMessages() {
784 stats.protocolMessages++;
788 public void incProtErrors() {
789 stats.protocolErrors++;
793 * Check if device has restarted and needs a new Thing initialization
795 * @return true: restart detected
798 private boolean checkRestarted(ShellySettingsStatus status) {
799 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
800 && (status.uptime != null && status.uptime < stats.lastUptime
801 || (!profile.status.update.oldVersion.isEmpty()
802 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
803 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
804 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
805 updateProperties(profile, status);
812 * Save alarm to the lastAlarm channel
814 * @param alarm Alarm Message
817 public void postEvent(String event, boolean force) {
818 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
819 State value = cache.getValue(channelId);
820 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
822 if (force || !lastAlarm.equals(event)
823 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
824 switch (event.toUpperCase()) {
827 case SHELLY_WAKEUPT_SENSOR:
828 case SHELLY_WAKEUPT_PERIODIC:
829 case SHELLY_WAKEUPT_BUTTON:
830 case SHELLY_WAKEUPT_POWERON:
831 case SHELLY_WAKEUPT_EXT_POWER:
832 case SHELLY_WAKEUPT_UNKNOWN:
833 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
834 case ALARM_TYPE_NONE:
837 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
838 triggerChannel(channelId, event);
839 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
840 stats.lastAlarm = event;
841 stats.lastAlarmTs = now();
847 public boolean isUpdateScheduled() {
848 return scheduledUpdates > 0;
852 * Callback for device events
854 * @param deviceName device receiving the event
855 * @param parameters parameters from the event URL
856 * @param data the HTML input data
857 * @return true if event was processed
860 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
861 Map<String, String> parameters) {
862 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
863 || config.serviceName.equals(deviceName)) {
864 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
866 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
867 if (!profile.isInitialized()) {
868 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
869 requestUpdates(1, true);
871 String group = profile.getControlGroup(idx);
872 if (group.isEmpty()) {
873 logger.debug("{}: Unsupported event class: {}", thingName, type);
877 // map some of the events to system defined button triggers
881 String parmType = getString(parameters.get("type"));
882 String event = !parmType.isEmpty() ? parmType : type;
883 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
885 case SHELLY_EVENT_SHORTPUSH:
886 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
887 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
888 case SHELLY_EVENT_LONGPUSH:
890 triggerButton(group, idx, mapButtonEvent(event));
891 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
892 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
894 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
898 case SHELLY_EVENT_BTN_ON:
899 case SHELLY_EVENT_BTN_OFF:
900 if (profile.isRGBW2) {
901 // RGBW2 has only one input, so not per channel
902 group = CHANNEL_GROUP_LIGHT_CONTROL;
904 onoff = CHANNEL_INPUT;
906 case SHELLY_EVENT_BTN1_ON:
907 case SHELLY_EVENT_BTN1_OFF:
908 onoff = CHANNEL_INPUT1;
910 case SHELLY_EVENT_BTN2_ON:
911 case SHELLY_EVENT_BTN2_OFF:
912 onoff = CHANNEL_INPUT2;
914 case SHELLY_EVENT_OUT_ON:
915 case SHELLY_EVENT_OUT_OFF:
916 onoff = CHANNEL_OUTPUT;
918 case SHELLY_EVENT_ROLLER_OPEN:
919 case SHELLY_EVENT_ROLLER_CLOSE:
920 case SHELLY_EVENT_ROLLER_STOP:
921 channel = CHANNEL_EVENT_TRIGGER;
924 case SHELLY_EVENT_SENSORREPORT:
925 // process sensor with next refresh
927 case SHELLY_EVENT_TEMP_OVER: // DW2
928 case SHELLY_EVENT_TEMP_UNDER:
929 channel = CHANNEL_EVENT_TRIGGER;
932 case SHELLY_EVENT_FLOOD_DETECTED:
933 case SHELLY_EVENT_FLOOD_GONE:
934 updateChannel(group, CHANNEL_SENSOR_FLOOD,
935 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
938 case SHELLY_EVENT_CLOSE: // DW 1.7
939 case SHELLY_EVENT_OPEN: // DW 1.7
940 updateChannel(group, CHANNEL_SENSOR_STATE,
941 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
942 : OpenClosedType.CLOSED);
945 case SHELLY_EVENT_DARK: // DW 1.7
946 case SHELLY_EVENT_TWILIGHT: // DW 1.7
947 case SHELLY_EVENT_BRIGHT: // DW 1.7
948 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
951 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
952 case SHELLY_EVENT_ALARM_HEAVY:
953 case SHELLY_EVENT_ALARM_OFF:
954 case SHELLY_EVENT_VIBRATION: // DW2
955 channel = CHANNEL_SENSOR_ALARM_STATE;
956 payload = event.toUpperCase();
960 // trigger will be provided by input/output channel or sensor channels
963 if (!onoff.isEmpty()) {
964 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
966 if (!payload.isEmpty()) {
967 // Pass event to trigger channel
968 payload = payload.toUpperCase();
969 logger.debug("{}: Post event {}", thingName, payload);
970 triggerChannel(mkChannelId(group, channel), payload);
974 // request update on next interval (2x for non-battery devices)
976 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
983 * Initialize the binding's thing configuration, calc update counts
985 protected void initializeThingConfig() {
986 thingType = getThing().getThingTypeUID().getId();
987 final Map<String, String> properties = getThing().getProperties();
988 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
989 if (thingName.isEmpty()) {
990 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
993 config = getConfigAs(ShellyThingConfiguration.class);
994 if (config.deviceAddress.isEmpty()) {
995 config.deviceAddress = config.deviceIp;
997 if (config.deviceAddress.isEmpty()) {
998 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
1003 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
1004 // convert to lower case
1005 if (!config.deviceIp.isEmpty()) {
1007 InetAddress addr = InetAddress.getByName(config.deviceIp);
1008 String saddr = addr.getHostAddress();
1009 if (!config.deviceIp.equals(saddr)) {
1010 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1011 config.deviceIp = saddr;
1013 } catch (UnknownHostException e) {
1014 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1018 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1019 config.localIp = bindingConfig.localIP;
1020 config.localPort = String.valueOf(bindingConfig.httpPort);
1021 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1022 config.userId = bindingConfig.defaultUserId;
1023 config.password = bindingConfig.defaultPassword;
1024 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
1026 if (config.updateInterval == 0) {
1027 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1029 if (config.updateInterval < UPDATE_MIN_DELAY) {
1030 config.updateInterval = UPDATE_MIN_DELAY;
1033 // Try to get updatePeriod from properties
1034 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1035 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1036 // initialized successfully by the REST call.
1037 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1038 if (!lastPeriod.isEmpty()) {
1039 int period = Integer.parseInt(lastPeriod);
1041 profile.updatePeriod = period;
1045 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1046 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1049 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1051 ShellyVersionDTO version = new ShellyVersionDTO();
1052 if (version.checkBeta(getString(prf.fwVersion))) {
1053 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1055 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1056 if (version.compare(prf.fwVersion, minVersion) < 0) {
1057 logger.warn("{}: {}", prf.hostname,
1058 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1061 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1062 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1063 if (!config.eventsCoIoT) {
1064 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1068 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1069 logger.info("{}: {}", thingName,
1070 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1072 } catch (NullPointerException e) { // could be inconsistant format of beta version
1073 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1077 public String checkForUpdate() {
1079 ShellyOtaCheckResult result = api.checkForUpdate();
1080 return result.status;
1081 } catch (ShellyApiException e) {
1086 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1087 if (coap == null || !config.eventsCoIoT) {
1090 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1091 String devpeer = getString(profile.settings.coiot.peer);
1092 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1093 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1095 api.setCoIoTPeer(ourpeer);
1096 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1097 } catch (ShellyApiException e) {
1098 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1100 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1101 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1105 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1106 config.eventsCoIoT = true;
1107 config.eventsSwitch = false;
1108 config.eventsButton = false;
1109 config.eventsPush = false;
1110 config.eventsRoller = false;
1111 config.eventsSensorReport = false;
1112 api.setConfig(thingName, config);
1115 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1117 coap.start(thingName, config);
1122 * Checks the http response for authorization error.
1123 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1124 * case the thing type shelly-unknown is set.
1126 * @param response exception details including the http respone
1127 * @return true if the authorization failed
1129 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1130 if (result.isHttpAccessUnauthorized()) {
1131 // If the device is password protected the API doesn't provide settings to the device settings
1132 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1139 * Change type of this thing.
1141 * @param thingType thing type acc. to the xml definition
1142 * @param mode Device mode (e.g. relay, roller)
1144 protected void changeThingType(String thingType, String mode) {
1145 String deviceType = substringBefore(thingType, "-");
1146 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1147 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1148 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1149 Map<String, String> properties = editProperties();
1150 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1151 properties.replace(PROPERTY_DEV_MODE, mode);
1152 updateProperties(properties);
1153 changeThingType(thingTypeUID, getConfig());
1158 public void thingUpdated(Thing thing) {
1159 logger.debug("{}: Channel definitions updated.", thingName);
1160 super.thingUpdated(thing);
1164 * Start the background updates
1166 protected void startUpdateJob() {
1167 ScheduledFuture<?> statusJob = this.statusJob;
1168 if ((statusJob == null) || statusJob.isCancelled()) {
1169 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1171 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1172 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1177 * Flag the status job to do an exceptional update (something happened) rather
1178 * than waiting until the next regular poll
1180 * @param requestCount number of polls to execute
1181 * @param refreshSettings true=force a /settings query
1182 * @return true=Update schedule, false=skipped (too many updates already
1186 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1187 this.refreshSettings |= refreshSettings;
1188 if (refreshSettings) {
1189 if (requestCount == 0) {
1190 logger.debug("{}: Request settings refresh", thingName);
1192 scheduledUpdates = 1;
1195 if (scheduledUpdates < 10) { // < 30s
1196 scheduledUpdates += requestCount;
1203 * Map input states to channels
1205 * @param groupName Channel Group (relay / relay1...)
1207 * @param status Shelly device status
1208 * @return true: one or more inputs were updated
1211 public boolean updateInputs(ShellySettingsStatus status) {
1212 boolean updated = false;
1214 if (status.inputs != null) {
1215 if (!areChannelsCreated()) {
1216 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1220 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1221 for (ShellyInputState input : status.inputs) {
1222 String group = profile.getInputGroup(idx);
1223 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1224 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1225 if (input.event != null) {
1226 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1227 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1232 if (status.input != null) {
1233 // RGBW2: a single int rather than an array
1234 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1235 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1242 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1243 boolean changed = false;
1244 if (valueArray != null && !valueArray.isEmpty()) {
1245 String reason = getString((String) valueArray.get(0));
1246 String newVal = valueArray.toString();
1247 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1248 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1250 postEvent(reason.toUpperCase(), true);
1252 lastWakeupReason = newVal;
1258 public void triggerButton(String group, int idx, String value) {
1259 String trigger = mapButtonEvent(value);
1260 if (trigger.isEmpty()) {
1264 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1265 triggerChannel(group,
1266 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1268 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1269 if (profile.alwaysOn) {
1270 // refresh status of the input channel
1271 requestUpdates(1, false);
1276 public void publishState(String channelId, State value) {
1277 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1278 if (!stopping && isLinked(id)) {
1279 updateState(id, value);
1280 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1285 public boolean updateChannel(String group, String channel, State value) {
1286 return updateChannel(mkChannelId(group, channel), value, false);
1290 public boolean updateChannel(String channelId, State value, boolean force) {
1291 return !stopping && cache.updateChannel(channelId, value, force);
1295 public State getChannelValue(String group, String channel) {
1296 return cache.getValue(group, channel);
1300 public double getChannelDouble(String group, String channel) {
1301 State value = getChannelValue(group, channel);
1302 if (value != UnDefType.NULL) {
1303 if (value instanceof QuantityType quantityCommand) {
1304 return quantityCommand.toBigDecimal().doubleValue();
1306 if (value instanceof DecimalType decimalCommand) {
1307 return decimalCommand.doubleValue();
1314 * Update Thing's channels according to available status information from the API
1316 * @param thingHandler
1319 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1320 if (channelsCreated) {
1321 return; // already done
1325 // Get subset of those channels that currently do not exist
1326 List<Channel> existingChannels = getThing().getChannels();
1327 for (Channel channel : existingChannels) {
1328 String id = channel.getUID().getId();
1329 if (dynChannels.containsKey(id)) {
1330 dynChannels.remove(id);
1334 if (!dynChannels.isEmpty()) {
1335 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1336 ThingBuilder thingBuilder = editThing();
1337 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1338 Channel c = channel.getValue();
1339 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1340 thingBuilder.withChannel(c);
1342 updateThing(thingBuilder.build());
1343 logger.debug("{}: Channel definitions updated", thingName);
1345 } catch (IllegalArgumentException e) {
1346 logger.debug("{}: Unable to update channel definitions", thingName, e);
1351 public boolean areChannelsCreated() {
1352 return channelsCreated;
1356 * Update thing properties with dynamic values
1358 * @param profile The device profile
1359 * @param status the /status result
1361 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1362 Map<String, Object> properties = fillDeviceProperties(profile);
1363 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1364 String deviceName = getString(profile.settings.name);
1365 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1366 properties.put(PROPERTY_DEV_GEN, "1");
1367 if (!deviceName.isEmpty()) {
1368 properties.put(PROPERTY_DEV_NAME, deviceName);
1370 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1372 // add status properties
1373 if (status.wifiSta != null) {
1374 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1376 if (status.update != null) {
1377 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1378 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1379 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1380 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1382 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1384 Map<String, String> thingProperties = new TreeMap<>();
1385 for (Map.Entry<String, Object> property : properties.entrySet()) {
1386 thingProperties.put(property.getKey(), (String) property.getValue());
1388 flushProperties(thingProperties);
1392 * Add one property to the Thing Properties
1394 * @param key Name of the property
1395 * @param value Value of the property
1398 public void updateProperties(String key, String value) {
1399 Map<String, String> thingProperties = editProperties();
1400 if (thingProperties.containsKey(key)) {
1401 thingProperties.replace(key, value);
1403 thingProperties.put(key, value);
1405 updateProperties(thingProperties);
1406 logger.trace("{}: Properties updated", thingName);
1409 public void flushProperties(Map<String, String> propertyUpdates) {
1410 Map<String, String> thingProperties = editProperties();
1411 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1412 if (thingProperties.containsKey(property.getKey())) {
1413 thingProperties.replace(property.getKey(), property.getValue());
1415 thingProperties.put(property.getKey(), property.getValue());
1418 updateProperties(thingProperties);
1422 * Get one property from the Thing Properties
1424 * @param key property name
1425 * @return property value or "" if property is not set
1428 public String getProperty(String key) {
1429 Map<String, String> thingProperties = getThing().getProperties();
1430 return getString(thingProperties.get(key));
1434 * Fill Thing Properties with device attributes
1436 * @param profile Property Map to full
1437 * @return a full property map
1439 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1440 Map<String, Object> properties = new TreeMap<>();
1441 properties.put(PROPERTY_VENDOR, VENDOR);
1442 if (profile.isInitialized()) {
1443 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1444 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1445 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1446 properties.put(PROPERTY_DEV_MODE, profile.mode);
1447 if (profile.hasRelays) {
1448 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1449 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1450 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1452 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1453 if (!profile.hwRev.isEmpty()) {
1454 properties.put(PROPERTY_HWREV, profile.hwRev);
1455 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1462 * Return device profile.
1464 * @param ForceRefresh true=force refresh before returning, false=return without
1466 * @return ShellyDeviceProfile instance
1467 * @throws ShellyApiException
1470 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1472 refreshSettings |= forceRefresh;
1473 if (refreshSettings) {
1474 profile = api.getDeviceProfile(thingType);
1475 if (!isThingOnline()) {
1476 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1480 refreshSettings = false;
1486 public ShellyDeviceProfile getProfile() {
1491 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1492 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1493 if (!options.isEmpty()) {
1494 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1500 protected ShellyDeviceProfile getDeviceProfile() {
1505 public void triggerChannel(String group, String channel, String payload) {
1506 String triggerCh = mkChannelId(group, channel);
1507 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1508 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1509 if (vibrationFilter == 0) {
1510 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1511 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1512 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1514 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1515 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1520 triggerChannel(triggerCh, payload);
1523 public void stop() {
1524 logger.debug("{}: Shutting down", thingName);
1525 ScheduledFuture<?> job = this.initJob;
1530 job = this.statusJob;
1534 logger.debug("{}: Shelly statusJob stopped", thingName);
1537 profile.initialized = false;
1541 * Shutdown thing, make sure background jobs are canceled
1544 public void dispose() {
1545 logger.debug("{}: Stopping Thing", thingName);
1552 * Device specific command handlers are overriding this method to do additional stuff
1554 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1558 public String getUID() {
1559 return getThing().getUID().getAsString();
1563 * Device specific handlers are overriding this method to do additional stuff
1565 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1570 public String getThingName() {
1575 public void resetStats() {
1577 stats = new ShellyDeviceStats();
1581 public ShellyDeviceStats getStats() {
1586 public ShellyApiInterface getApi() {
1591 public long getScheduledUpdates() {
1592 return scheduledUpdates;
1595 public Map<String, String> getStatsProp() {
1596 return stats.asProperties();
1600 public void triggerUpdateFromCoap() {
1601 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1602 requestUpdates(1, false);