2 * Copyright (c) 2010-2024 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) || "3".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 if (profile.alwaysOn || !profile.isInitialized()) {
297 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
298 messages.get("status.unknown.initializing"));
301 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
302 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
303 // Action URL does when enabled)
304 profile.initFromThingType(thingType);
305 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
306 coap.start(thingName, config);
309 // Initialize API access, exceptions will be catched by initialize()
311 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
312 if (getBool(device.auth) && config.password.isEmpty()) {
313 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
316 if (config.serviceName.isEmpty()) {
317 config.serviceName = getString(device.hostname).toLowerCase();
320 api.setConfig(thingName, config);
321 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
322 String mode = getString(tmpPrf.device.mode);
323 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
324 changeThingType(thingName, mode);
325 return false; // force re-initialization
327 // Validate device mode
328 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
329 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
330 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode, reqMode);
333 if (!getString(tmpPrf.device.coiot).isEmpty()) {
334 // New Shelly devices might use a different endpoint for the CoAP listener
335 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
337 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
338 // Sensor, usually 12h, H&T in USB mode 10min
339 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
340 ? tmpPrf.settings.sleepMode.period * 60 // minutes
341 : tmpPrf.settings.sleepMode.period * 3600; // hours
342 tmpPrf.updatePeriod += 60; // give 1min extra
343 } else if (tmpPrf.settings.coiot != null && tmpPrf.settings.coiot.updatePeriod != null) {
344 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
345 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
346 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
348 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
351 tmpPrf.status = api.getStatus(); // update thing properties
352 tmpPrf.updateFromStatus(tmpPrf.status);
353 addStateOptions(tmpPrf);
355 // update thing properties
356 updateProperties(tmpPrf, tmpPrf.status);
357 checkVersion(tmpPrf, tmpPrf.status);
359 startCoap(config, tmpPrf);
361 api.setActionURLs(); // register event urls
364 // All initialization done, so keep the profile and set Thing to ONLINE
365 fillDeviceStatus(tmpPrf.status, false);
366 postEvent(ALARM_TYPE_NONE, false);
369 showThingConfig(profile);
371 logger.debug("{}: Thing successfully initialized.", thingName);
372 updateProperties(profile, profile.status);
373 setThingOnline(); // if API call was successful the thing must be online
374 return true; // success
378 * Handle Channel Commands
381 public void handleCommand(ChannelUID channelUID, Command command) {
383 if (command instanceof RefreshType) {
384 String channelId = channelUID.getId();
385 State value = cache.getValue(channelId);
386 if (value != UnDefType.NULL) {
387 updateState(channelId, value);
392 if (!profile.isInitialized()) {
393 logger.debug("{}: {}", thingName, messages.get("command.init", command));
396 profile = getProfile(false);
399 boolean update = false;
400 switch (channelUID.getIdWithoutGroup()) {
401 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
402 logger.debug("{}: Send key {}", thingName, command);
403 api.sendIRKey(command.toString());
407 case CHANNEL_LED_STATUS_DISABLE:
408 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
409 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
411 case CHANNEL_LED_POWER_DISABLE:
412 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
413 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
416 case CHANNEL_SENSOR_SLEEPTIME:
417 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
418 int value = getNumber(command).intValue();
419 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
421 api.setSleepTime(value);
423 case CHANNEL_CONTROL_SCHEDULE:
425 logger.debug("{}: {} Valve schedule/profile", thingName,
426 command == OnOffType.ON ? "Enable" : "Disable");
427 api.setValveProfile(0,
428 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
431 case CHANNEL_CONTROL_PROFILE:
432 logger.debug("{}: Select profile {}", thingName, command);
434 if (command instanceof Number) {
435 id = getNumber(command).intValue();
437 String cmd = command.toString();
438 if (isDigit(cmd.charAt(0))) {
439 id = Integer.parseInt(cmd);
440 } else if (profile.settings.thermostats != null) {
441 ShellyThermnostat t = profile.settings.thermostats.get(0);
442 for (int i = 0; i < t.profileNames.length; i++) {
443 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
449 if (id < 0 || id > 5) {
450 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
453 api.setValveProfile(0, id);
455 case CHANNEL_CONTROL_MODE:
456 logger.debug("{}: Set mode to {}", thingName, command);
457 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
459 case CHANNEL_CONTROL_SETTEMP:
460 logger.debug("{}: Set temperature to {}", thingName, command);
461 api.setValveTemperature(0, getNumber(command).intValue());
463 case CHANNEL_CONTROL_POSITION:
464 logger.debug("{}: Set position to {}", thingName, command);
465 api.setValvePosition(0, getNumber(command));
467 case CHANNEL_CONTROL_BCONTROL:
468 logger.debug("{}: Set boost mode to {}", thingName, command);
469 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
471 case CHANNEL_CONTROL_BTIMER:
472 logger.debug("{}: Set boost timer to {}", thingName, command);
473 api.setValveBoostTime(0, getNumber(command).intValue());
475 case CHANNEL_SENSOR_MUTE:
476 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
477 logger.debug("{}: Mute Smoke Alarm", thingName);
478 api.muteSmokeAlarm(0);
479 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
483 update = handleDeviceCommand(channelUID, command);
488 if (update && !autoCoIoT && !isUpdateScheduled()) {
489 requestUpdates(1, false);
491 } catch (ShellyApiException e) {
492 if (!handleApiException(e)) {
496 ShellyApiResult res = e.getApiResult();
497 if (res.isNotCalibrtated()) {
498 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
500 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
504 String group = getString(channelUID.getGroupId());
505 String channel = getString(channelUID.getIdWithoutGroup());
506 State oldValue = getChannelValue(group, channel);
507 if (oldValue != UnDefType.NULL) {
508 logger.info("{}: Restore channel value to {}", thingName, oldValue);
509 updateChannel(group, channel, oldValue);
512 } catch (IllegalArgumentException e) {
513 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
518 * Update device status and channels
520 protected void refreshStatus() {
522 boolean updated = false;
524 if (vibrationFilter > 0) {
526 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
527 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
531 ThingStatus thingStatus = getThing().getStatus();
532 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
533 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
534 || (thingStatus == ThingStatus.UNKNOWN)) {
535 logger.debug("{}: Status update triggered thing initialization", thingName);
536 initializeThing(); // may fire an exception if initialization failed
538 ShellySettingsStatus status = api.getStatus();
539 boolean restarted = checkRestarted(status);
540 profile = getProfile(refreshSettings || restarted);
541 profile.status = status;
542 profile.updateFromStatus(status);
544 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
546 postEvent(ALARM_TYPE_RESTARTED, true);
549 // If status update was successful the thing must be online,
550 // but not while firmware update is in progress
551 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
555 // map status to channels
556 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
557 updated |= this.updateDeviceStatus(status);
558 updated |= ShellyComponents.updateDeviceStatus(this, status);
559 fillDeviceStatus(status, updated);
560 updated |= updateInputs(status);
561 updated |= updateMeters(this, status);
562 updated |= updateSensors(this, status);
564 // All channels must be created after the first cycle
565 channelsCreated = true;
567 } catch (ShellyApiException e) {
568 // http call failed: go offline except for battery devices, which might be in
569 // sleep mode. Once the next update is successful the device goes back online
570 handleApiException(e);
571 } catch (NullPointerException | IllegalArgumentException e) {
572 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
574 if (scheduledUpdates > 0) {
576 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
577 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
578 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
579 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
585 private void showThingConfig(ShellyDeviceProfile profile) {
586 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
587 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
589 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
590 logger.debug("{}: Device "
591 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
592 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
593 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
594 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
595 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
596 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
597 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
598 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
599 if (profile.status.extTemperature != null || profile.status.extHumidity != null
600 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
601 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
605 private void addStateOptions(ShellyDeviceProfile prf) {
607 String[] profileNames = prf.getValveProfileList(0);
608 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
609 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
610 channelDefinitions.clearStateOptions(channelId);
612 for (String name : profileNames) {
613 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
617 if (prf.isRoller && prf.settings.favorites != null) {
618 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
619 logger.debug("{}: Adding {} roler favorite(s) to channel description", thingName,
620 prf.settings.favorites.size());
621 channelDefinitions.clearStateOptions(channelId);
623 for (ShellyFavPos fav : prf.settings.favorites) {
624 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
631 public String getThingType() {
632 return thing.getThingTypeUID().getId();
636 public ThingStatus getThingStatus() {
637 return thing.getStatus();
641 public ThingStatusDetail getThingStatusDetail() {
642 return thing.getStatusInfo().getStatusDetail();
646 public boolean isThingOnline() {
647 return getThingStatus() == ThingStatus.ONLINE;
650 public boolean isThingOffline() {
651 return getThingStatus() == ThingStatus.OFFLINE;
655 public void setThingOnline() {
656 if (!isThingOnline()) {
657 updateStatus(ThingStatus.ONLINE);
659 // request 3 updates in a row (during the first 2+3*3 sec)
660 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
663 // Restart watchdog when status update was successful (no exception)
668 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
669 if (!isThingOffline()) {
670 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
671 api.close(); // Gen2: disconnect WS/close http sessions
673 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
678 public void restartWatchdog() {
680 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
681 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
684 private boolean isWatchdogExpired() {
685 long delta = now() - watchdog;
686 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
687 stats.remainingWatchdog = delta;
694 public void reinitializeThing() {
695 logger.debug("{}: Re-Initialize Thing", thingName);
697 logger.debug("{}: Handler is shutting down, ignore", thingName);
700 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
701 messages.get("offline.status-error-restarted"));
702 requestUpdates(0, true);
706 public boolean isStopping() {
711 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
714 // Update uptime and WiFi, internal temp
715 ShellyComponents.updateDeviceStatus(this, status);
716 stats.wifiRssi = getInteger(status.wifiSta.rssi);
718 if (api.isInitialized()) {
719 stats.timeoutErrors = api.getTimeoutErrors();
720 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
722 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
724 // Check various device indicators like overheating
725 if (checkRestarted(status)) {
726 // Force re-initialization on next status update
728 } else if (getBool(status.overtemperature)) {
729 alarm = ALARM_TYPE_OVERTEMP;
730 } else if (getBool(status.overload)) {
731 alarm = ALARM_TYPE_OVERLOAD;
732 } else if (getBool(status.loaderror)) {
733 alarm = ALARM_TYPE_LOADERR;
735 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
736 if (internalTemp != UnDefType.NULL) {
737 int temp = ((Number) internalTemp).intValue();
738 if (temp > stats.maxInternalTemp) {
739 stats.maxInternalTemp = temp;
743 if (status.uptime != null) {
744 stats.lastUptime = getLong(status.uptime);
747 if (!alarm.isEmpty()) {
748 postEvent(alarm, false);
753 public void incProtMessages() {
754 stats.protocolMessages++;
758 public void incProtErrors() {
759 stats.protocolErrors++;
763 * Check if device has restarted and needs a new Thing initialization
765 * @return true: restart detected
768 private boolean checkRestarted(ShellySettingsStatus status) {
769 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
770 && (status.uptime != null && status.uptime < stats.lastUptime
771 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
772 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
773 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
774 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
775 updateProperties(profile, status);
782 * Save alarm to the lastAlarm channel
784 * @param event Alarm Message
788 public void postEvent(String event, boolean force) {
789 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
790 State value = cache.getValue(channelId);
791 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
793 if (force || !lastAlarm.equals(event)
794 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
795 switch (event.toUpperCase()) {
798 case SHELLY_WAKEUPT_SENSOR:
799 case SHELLY_WAKEUPT_PERIODIC:
800 case SHELLY_WAKEUPT_BUTTON:
801 case SHELLY_WAKEUPT_POWERON:
802 case SHELLY_WAKEUPT_EXT_POWER:
803 case SHELLY_WAKEUPT_UNKNOWN:
804 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
805 case ALARM_TYPE_NONE:
808 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
809 triggerChannel(channelId, event);
810 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
811 stats.lastAlarm = event;
812 stats.lastAlarmTs = now();
818 public boolean isUpdateScheduled() {
819 return scheduledUpdates > 0;
823 * Callback for device events
826 * @param deviceName device receiving the event
828 * @param type the HTML input data
829 * @param parameters parameters from the event URL
830 * @return true if event was processed
833 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
834 Map<String, String> parameters) {
835 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
836 || config.serviceName.equals(deviceName)) {
837 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
839 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
840 if (!profile.isInitialized()) {
841 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
842 requestUpdates(1, true);
844 String group = profile.getControlGroup(idx);
845 if (group.isEmpty()) {
846 logger.debug("{}: Unsupported event class: {}", thingName, type);
850 // map some of the events to system defined button triggers
854 String parmType = getString(parameters.get("type"));
855 String event = !parmType.isEmpty() ? parmType : type;
856 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
858 case SHELLY_EVENT_SHORTPUSH:
859 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
860 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
861 case SHELLY_EVENT_LONGPUSH:
863 triggerButton(group, idx, mapButtonEvent(event));
864 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
865 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
867 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
871 case SHELLY_EVENT_BTN_ON:
872 case SHELLY_EVENT_BTN_OFF:
873 if (profile.isRGBW2) {
874 // RGBW2 has only one input, so not per channel
875 group = CHANNEL_GROUP_LIGHT_CONTROL;
877 onoff = CHANNEL_INPUT;
879 case SHELLY_EVENT_BTN1_ON:
880 case SHELLY_EVENT_BTN1_OFF:
881 onoff = CHANNEL_INPUT1;
883 case SHELLY_EVENT_BTN2_ON:
884 case SHELLY_EVENT_BTN2_OFF:
885 onoff = CHANNEL_INPUT2;
887 case SHELLY_EVENT_OUT_ON:
888 case SHELLY_EVENT_OUT_OFF:
889 onoff = CHANNEL_OUTPUT;
891 case SHELLY_EVENT_ROLLER_OPEN:
892 case SHELLY_EVENT_ROLLER_CLOSE:
893 case SHELLY_EVENT_ROLLER_STOP:
894 channel = CHANNEL_EVENT_TRIGGER;
897 case SHELLY_EVENT_SENSORREPORT:
898 // process sensor with next refresh
900 case SHELLY_EVENT_TEMP_OVER: // DW2
901 case SHELLY_EVENT_TEMP_UNDER:
902 channel = CHANNEL_EVENT_TRIGGER;
905 case SHELLY_EVENT_FLOOD_DETECTED:
906 case SHELLY_EVENT_FLOOD_GONE:
907 updateChannel(group, CHANNEL_SENSOR_FLOOD,
908 OnOffType.from(event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED)));
911 case SHELLY_EVENT_CLOSE: // DW 1.7
912 case SHELLY_EVENT_OPEN: // DW 1.7
913 updateChannel(group, CHANNEL_SENSOR_STATE,
914 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
915 : OpenClosedType.CLOSED);
918 case SHELLY_EVENT_DARK: // DW 1.7
919 case SHELLY_EVENT_TWILIGHT: // DW 1.7
920 case SHELLY_EVENT_BRIGHT: // DW 1.7
921 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
924 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
925 case SHELLY_EVENT_ALARM_HEAVY:
926 case SHELLY_EVENT_ALARM_OFF:
927 case SHELLY_EVENT_VIBRATION: // DW2
928 channel = CHANNEL_SENSOR_ALARM_STATE;
929 payload = event.toUpperCase();
933 // trigger will be provided by input/output channel or sensor channels
936 if (!onoff.isEmpty()) {
937 updateChannel(group, onoff, OnOffType.from(event.toLowerCase().contains("_on")));
939 if (!payload.isEmpty()) {
940 // Pass event to trigger channel
941 payload = payload.toUpperCase();
942 logger.debug("{}: Post event {}", thingName, payload);
943 triggerChannel(mkChannelId(group, channel), payload);
947 // request update on next interval (2x for non-battery devices)
949 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
956 * Initialize the binding's thing configuration, calc update counts
958 protected void initializeThingConfig() {
959 thingType = getThing().getThingTypeUID().getId();
960 final Map<String, String> properties = getThing().getProperties();
961 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
962 if (thingName.isEmpty()) {
963 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
966 config = getConfigAs(ShellyThingConfiguration.class);
967 if (config.deviceAddress.isEmpty()) {
968 config.deviceAddress = config.deviceIp;
970 if (config.deviceAddress.isEmpty()) {
971 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
976 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
977 // convert to lower case
978 if (!config.deviceIp.isEmpty()) {
980 InetAddress addr = InetAddress.getByName(config.deviceIp);
981 String saddr = addr.getHostAddress();
982 if (!config.deviceIp.equals(saddr)) {
983 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
984 config.deviceIp = saddr;
986 } catch (UnknownHostException e) {
987 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
991 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
992 config.localIp = bindingConfig.localIP;
993 config.localPort = String.valueOf(bindingConfig.httpPort);
994 if (config.localIp.startsWith("169.254")) {
995 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, "config-status.error.network-config",
1000 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1001 // Gen2 has hard coded user "admin"
1002 config.userId = bindingConfig.defaultUserId;
1003 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1005 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1006 config.password = bindingConfig.defaultPassword;
1007 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1010 if (config.updateInterval == 0) {
1011 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1013 if (config.updateInterval < UPDATE_MIN_DELAY) {
1014 config.updateInterval = UPDATE_MIN_DELAY;
1017 // Try to get updatePeriod from properties
1018 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1019 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1020 // initialized successfully by the REST call.
1021 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1022 if (!lastPeriod.isEmpty()) {
1023 int period = Integer.parseInt(lastPeriod);
1025 profile.updatePeriod = period;
1029 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1030 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1033 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1035 if (prf.fwVersion.isEmpty()) {
1036 // no fw version available (e.g. BLU device)
1039 ShellyVersionDTO version = new ShellyVersionDTO();
1040 if (version.checkBeta(getString(prf.fwVersion))) {
1041 logger.info("{}: {}", prf.device.hostname,
1042 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1044 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1045 if (version.compare(prf.fwVersion, minVersion) < 0) {
1046 logger.warn("{}: {}", prf.device.hostname,
1047 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1050 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1051 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1052 if (!config.eventsCoIoT) {
1053 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1057 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1058 logger.info("{}: {}", thingName,
1059 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1061 } catch (NullPointerException e) { // could be inconsistant format of beta version
1062 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1066 public String checkForUpdate() {
1068 ShellyOtaCheckResult result = api.checkForUpdate();
1069 return result.status;
1070 } catch (ShellyApiException e) {
1075 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1076 if (coap == null || !config.eventsCoIoT) {
1079 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1080 String devpeer = getString(profile.settings.coiot.peer);
1081 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1082 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1084 api.setCoIoTPeer(ourpeer);
1085 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1086 } catch (ShellyApiException e) {
1087 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1089 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1090 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1094 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1095 config.eventsCoIoT = true;
1096 config.eventsSwitch = false;
1097 config.eventsButton = false;
1098 config.eventsPush = false;
1099 config.eventsRoller = false;
1100 config.eventsSensorReport = false;
1101 api.setConfig(thingName, config);
1104 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1106 coap.start(thingName, config);
1111 * Change type of this thing.
1113 * @param thingType thing type acc. to the xml definition
1114 * @param mode Device mode (e.g. relay, roller)
1116 protected void changeThingType(String thingType, String mode) {
1117 String deviceType = substringBefore(thingType, "-");
1118 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1119 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1120 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1121 Map<String, String> properties = editProperties();
1122 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1123 properties.replace(PROPERTY_DEV_MODE, mode);
1124 updateProperties(properties);
1125 changeThingType(thingTypeUID, getConfig());
1130 public void thingUpdated(Thing thing) {
1131 logger.debug("{}: Channel definitions updated.", thingName);
1132 super.thingUpdated(thing);
1136 * Start the background updates
1138 protected void startUpdateJob() {
1139 ScheduledFuture<?> statusJob = this.statusJob;
1140 if ((statusJob == null) || statusJob.isCancelled()) {
1141 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1143 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1144 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1149 * Flag the status job to do an exceptional update (something happened) rather
1150 * than waiting until the next regular poll
1152 * @param requestCount number of polls to execute
1153 * @param refreshSettings true=force a /settings query
1154 * @return true=Update schedule, false=skipped (too many updates already
1158 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1159 this.refreshSettings |= refreshSettings;
1160 if (refreshSettings) {
1161 if (requestCount == 0) {
1162 logger.debug("{}: Request settings refresh", thingName);
1164 scheduledUpdates = 1;
1167 if (scheduledUpdates < 10) { // < 30s
1168 scheduledUpdates += requestCount;
1175 * Map input states to channels
1177 * @param status Shelly device status
1178 * @return true: one or more inputs were updated
1181 public boolean updateInputs(ShellySettingsStatus status) {
1182 boolean updated = false;
1184 if (status.inputs != null) {
1185 if (!areChannelsCreated()) {
1186 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1190 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1191 for (ShellyInputState input : status.inputs) {
1192 String group = profile.getInputGroup(idx);
1193 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1194 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1195 if (input.event != null) {
1196 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1197 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1202 if (status.input != null) {
1203 // RGBW2: a single int rather than an array
1204 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1205 OnOffType.from(getInteger(status.input) != 0));
1212 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1213 boolean changed = false;
1214 if (valueArray != null && !valueArray.isEmpty()) {
1215 String reason = getString((String) valueArray.get(0));
1216 String newVal = valueArray.toString();
1217 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1218 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1220 postEvent(reason.toUpperCase(), true);
1222 lastWakeupReason = newVal;
1228 public void triggerButton(String group, int idx, String value) {
1229 String trigger = mapButtonEvent(value);
1230 if (trigger.isEmpty()) {
1234 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1235 triggerChannel(group,
1236 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1238 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1239 if (profile.alwaysOn) {
1240 // refresh status of the input channel
1241 requestUpdates(1, false);
1246 public void publishState(String channelId, State value) {
1247 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1248 if (!stopping && isLinked(id)) {
1249 updateState(id, value);
1250 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1255 public boolean updateChannel(String group, String channel, State value) {
1256 return updateChannel(mkChannelId(group, channel), value, false);
1260 public boolean updateChannel(String channelId, State value, boolean force) {
1261 return !stopping && cache.updateChannel(channelId, value, force);
1265 public State getChannelValue(String group, String channel) {
1266 return cache.getValue(group, channel);
1270 public double getChannelDouble(String group, String channel) {
1271 State value = getChannelValue(group, channel);
1272 if (value != UnDefType.NULL) {
1273 if (value instanceof QuantityType<?> quantityCommand) {
1274 return quantityCommand.toBigDecimal().doubleValue();
1276 if (value instanceof DecimalType decimalCommand) {
1277 return decimalCommand.doubleValue();
1284 * Update Thing's channels according to available status information from the API
1286 * @param dynChannels
1289 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1290 if (channelsCreated) {
1291 return; // already done
1295 // Get subset of those channels that currently do not exist
1296 List<Channel> existingChannels = getThing().getChannels();
1297 for (Channel channel : existingChannels) {
1298 String id = channel.getUID().getId();
1299 if (dynChannels.containsKey(id)) {
1300 dynChannels.remove(id);
1304 if (!dynChannels.isEmpty()) {
1305 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1306 ThingBuilder thingBuilder = editThing();
1307 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1308 Channel c = channel.getValue();
1309 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1310 thingBuilder.withChannel(c);
1312 updateThing(thingBuilder.build());
1313 logger.debug("{}: Channel definitions updated", thingName);
1315 } catch (IllegalArgumentException e) {
1316 logger.debug("{}: Unable to update channel definitions", thingName, e);
1321 public boolean areChannelsCreated() {
1322 return channelsCreated;
1326 * Update thing properties with dynamic values
1328 * @param profile The device profile
1329 * @param status the /status result
1331 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1332 Map<String, Object> properties = fillDeviceProperties(profile);
1333 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1334 String deviceName = getString(profile.settings.name);
1335 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1336 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1337 properties.put(PROPERTY_DEV_AUTH, getBool(profile.device.auth) ? "yes" : "no");
1338 if (!deviceName.isEmpty()) {
1339 properties.put(PROPERTY_DEV_NAME, deviceName);
1342 // add status properties
1343 if (status.wifiSta != null) {
1344 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1346 if (status.update != null) {
1347 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1348 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1349 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1350 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1352 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1354 Map<String, String> thingProperties = new TreeMap<>();
1355 for (Map.Entry<String, Object> property : properties.entrySet()) {
1356 thingProperties.put(property.getKey(), (String) property.getValue());
1358 flushProperties(thingProperties);
1362 * Add one property to the Thing Properties
1364 * @param key Name of the property
1365 * @param value Value of the property
1368 public void updateProperties(String key, String value) {
1369 Map<String, String> thingProperties = editProperties();
1370 if (thingProperties.containsKey(key)) {
1371 thingProperties.replace(key, value);
1373 thingProperties.put(key, value);
1375 updateProperties(thingProperties);
1376 logger.trace("{}: Properties updated", thingName);
1379 public void flushProperties(Map<String, String> propertyUpdates) {
1380 Map<String, String> thingProperties = editProperties();
1381 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1382 if (thingProperties.containsKey(property.getKey())) {
1383 thingProperties.replace(property.getKey(), property.getValue());
1385 thingProperties.put(property.getKey(), property.getValue());
1388 updateProperties(thingProperties);
1392 * Get one property from the Thing Properties
1394 * @param key property name
1395 * @return property value or "" if property is not set
1398 public String getProperty(String key) {
1399 Map<String, String> thingProperties = getThing().getProperties();
1400 return getString(thingProperties.get(key));
1404 * Fill Thing Properties with device attributes
1406 * @param profile Property Map to full
1407 * @return a full property map
1409 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1410 Map<String, Object> properties = new TreeMap<>();
1411 properties.put(PROPERTY_VENDOR, VENDOR);
1412 if (profile.isInitialized()) {
1413 properties.put(PROPERTY_MODEL_ID, getString(profile.device.type));
1414 properties.put(PROPERTY_MAC_ADDRESS, profile.device.mac);
1415 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1416 properties.put(PROPERTY_DEV_MODE, profile.device.mode);
1417 if (profile.hasRelays) {
1418 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1419 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1420 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1422 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1423 if (!profile.hwRev.isEmpty()) {
1424 properties.put(PROPERTY_HWREV, profile.hwRev);
1425 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1432 * Return device profile.
1434 * @param forceRefresh true=force refresh before returning, false=return without
1436 * @return ShellyDeviceProfile instance
1437 * @throws ShellyApiException
1440 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1442 refreshSettings |= forceRefresh;
1443 if (refreshSettings) {
1444 profile = api.getDeviceProfile(thingType, null);
1445 if (!isThingOnline()) {
1446 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1450 refreshSettings = false;
1456 public ShellyDeviceProfile getProfile() {
1461 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1462 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1463 if (!options.isEmpty()) {
1464 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1470 protected ShellyDeviceProfile getDeviceProfile() {
1475 public void triggerChannel(String group, String channel, String payload) {
1476 String triggerCh = mkChannelId(group, channel);
1477 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1478 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1479 if (vibrationFilter == 0) {
1480 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1481 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1482 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1484 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1485 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1490 triggerChannel(triggerCh, payload);
1493 public void stop() {
1494 logger.debug("{}: Shutting down", thingName);
1495 ScheduledFuture<?> job = this.initJob;
1500 job = this.statusJob;
1504 logger.debug("{}: Shelly statusJob stopped", thingName);
1507 profile.initialized = false;
1511 * Shutdown thing, make sure background jobs are canceled
1514 public void dispose() {
1515 logger.debug("{}: Stopping Thing", thingName);
1522 * Device specific command handlers are overriding this method to do additional stuff
1524 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1528 public String getUID() {
1529 return getThing().getUID().getAsString();
1533 * Device specific handlers are overriding this method to do additional stuff
1535 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1540 public String getThingName() {
1545 public void resetStats() {
1547 stats = new ShellyDeviceStats();
1551 public ShellyDeviceStats getStats() {
1556 public ShellyApiInterface getApi() {
1561 public long getScheduledUpdates() {
1562 return scheduledUpdates;
1565 public Map<String, String> getStatsProp() {
1566 return stats.asProperties();
1570 public void triggerUpdateFromCoap() {
1571 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1572 requestUpdates(1, false);