2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.handler;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
19 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
20 import static org.openhab.core.thing.Thing.*;
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.util.List;
26 import java.util.TreeMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.shelly.internal.api.ShellyApiException;
34 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
35 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
36 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
47 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
48 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
49 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
50 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
51 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
52 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
53 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
54 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
55 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
56 import org.openhab.core.library.types.DecimalType;
57 import org.openhab.core.library.types.OnOffType;
58 import org.openhab.core.library.types.OpenClosedType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.thing.Channel;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.Thing;
63 import org.openhab.core.thing.ThingStatus;
64 import org.openhab.core.thing.ThingStatusDetail;
65 import org.openhab.core.thing.ThingTypeUID;
66 import org.openhab.core.thing.binding.BaseThingHandler;
67 import org.openhab.core.thing.binding.builder.ThingBuilder;
68 import org.openhab.core.thing.type.ChannelTypeUID;
69 import org.openhab.core.types.Command;
70 import org.openhab.core.types.RefreshType;
71 import org.openhab.core.types.State;
72 import org.openhab.core.types.StateOption;
73 import org.openhab.core.types.UnDefType;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
79 * sent to one of the channels.
81 * @author Markus Michels - Initial contribution
84 public abstract class ShellyBaseHandler extends BaseThingHandler
85 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
87 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
88 protected final ShellyChannelDefinitions channelDefinitions;
90 public String thingName = "";
91 public String thingType = "";
93 protected final ShellyApiInterface api;
94 private final HttpClient httpClient;
96 private ShellyBindingConfiguration bindingConfig;
97 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
98 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
99 private ShellyDeviceStats stats = new ShellyDeviceStats();
100 private @Nullable Shelly1CoapHandler coap;
102 private final ShellyTranslationProvider messages;
103 private final ShellyChannelCache cache;
104 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
106 private final boolean gen2;
107 protected boolean autoCoIoT = false;
110 private boolean channelsCreated = false;
111 private boolean stopping = false;
112 private int vibrationFilter = 0;
113 private String lastWakeupReason = "";
116 private long watchdog = now();
117 protected int scheduledUpdates = 0;
118 private int skipCount = UPDATE_SKIP_COUNT;
119 private int skipUpdate = 0;
120 private boolean refreshSettings = false;
121 private @Nullable ScheduledFuture<?> statusJob;
122 private @Nullable ScheduledFuture<?> initJob;
127 * @param thing The Thing object
128 * @param bindingConfig The binding configuration (beside thing
130 * @param coapServer coap server instance
131 * @param localIP local IP address from networkAddressService
132 * @param httpPort from httpService
134 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
135 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
136 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
139 this.thingName = getString(thing.getLabel());
140 this.messages = translationProvider;
141 this.cache = new ShellyChannelCache(this);
142 this.channelDefinitions = new ShellyChannelDefinitions(messages);
143 this.bindingConfig = bindingConfig;
144 this.config = getConfigAs(ShellyThingConfiguration.class);
145 this.httpClient = httpClient;
147 Map<String, String> properties = thing.getProperties();
148 String gen = getString(properties.get(PROPERTY_DEV_GEN));
149 String thingType = getThingType();
150 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
153 gen2 = "2".equals(gen);
154 this.api = !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this);
156 config.eventsCoIoT = false;
158 if (config.eventsCoIoT) {
159 this.coap = new Shelly1CoapHandler(this, coapServer);
164 public boolean checkRepresentation(String key) {
165 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
166 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
170 * Schedule asynchronous Thing initialization, register thing to event dispatcher
173 public void initialize() {
174 // start background initialization:
175 initJob = scheduler.schedule(() -> {
176 boolean start = true;
178 initializeThingConfig();
179 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
180 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
181 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
183 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
184 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
185 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
186 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
187 messages.get("status.unknown.initializing"));
188 start = initializeThing();
189 } catch (ShellyApiException e) {
190 ShellyApiResult res = e.getApiResult();
192 if (e.isJsonError()) { // invalid JSON format
193 mid = "offline.status-error-unexpected-error";
195 } else if (isAuthorizationFailed(res)) {
196 mid = "offline.conf-error-access-denied";
198 } else if (profile.alwaysOn && e.isConnectionError()) {
199 mid = "offline.status-error-connect";
201 if (!mid.isEmpty()) {
202 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
204 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
205 } catch (IllegalArgumentException e) {
206 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
208 // even this initialization failed we start the status update
209 // the updateJob will then try to auto-initialize the thing
210 // in this case the thing stays in status INITIALIZING
215 }, 2, TimeUnit.SECONDS);
219 public ShellyThingConfiguration getThingConfig() {
224 public HttpClient getHttpClient() {
229 * This routine is called every time the Thing configuration has been changed
232 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
233 super.handleConfigurationUpdate(configurationParameters);
234 logger.debug("{}: Thing config updated, re-initialize", thingName);
238 requestUpdates(1, true);// force re-initialization
242 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
243 * If the device is password protected and the credentials are missing or don't match the API access will throw an
244 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
245 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
246 * credentials are correct and the API access is initialized successful.
248 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
250 public boolean initializeThing() throws ShellyApiException {
251 // Init from thing type to have a basic profile, gets updated when device info is received from API
253 refreshSettings = false;
254 lastWakeupReason = "";
255 cache.setThingName(thingName);
259 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
260 getThing().getLabel(), thingType, config.deviceIp, gen2, config.eventsCoIoT);
261 if (config.deviceIp.isEmpty()) {
262 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
266 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
267 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
268 // Action URL does when enabled)
269 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
270 coap.start(thingName, config);
273 // Initialize API access, exceptions will be catched by initialize()
275 profile.initFromThingType(thingType);
276 ShellySettingsDevice devInfo = api.getDeviceInfo();
277 if (getBool(devInfo.auth) && config.password.isEmpty()) {
278 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
281 if (config.serviceName.isEmpty()) {
282 config.serviceName = getString(profile.hostname).toLowerCase();
285 api.setConfig(thingName, config);
286 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
287 tmpPrf.isGen2 = gen2;
288 tmpPrf.auth = devInfo.auth; // missing in /settings
290 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
291 changeThingType(thingName, tmpPrf.mode);
292 return false; // force re-initialization
294 // Validate device mode
295 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
296 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
297 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
301 if (!getString(devInfo.coiot).isEmpty()) {
302 // New Shelly devices might use a different endpoint for the CoAP listener
303 tmpPrf.coiotEndpoint = devInfo.coiot;
305 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
306 // Sensor, usually 12h, H&T in USB mode 10min
307 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
308 ? tmpPrf.settings.sleepMode.period * 60 // minutes
309 : tmpPrf.settings.sleepMode.period * 3600; // hours
310 tmpPrf.updatePeriod += 60; // give 1min extra
311 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
312 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
313 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
314 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
316 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
319 tmpPrf.status = api.getStatus(); // update thing properties
320 tmpPrf.updateFromStatus(tmpPrf.status);
321 addStateOptions(tmpPrf);
323 // update thing properties
324 updateProperties(tmpPrf, tmpPrf.status);
325 checkVersion(tmpPrf, tmpPrf.status);
327 startCoap(config, tmpPrf);
329 api.setActionURLs(); // register event urls
332 // All initialization done, so keep the profile and set Thing to ONLINE
333 fillDeviceStatus(tmpPrf.status, false);
334 postEvent(ALARM_TYPE_NONE, false);
337 showThingConfig(profile);
339 logger.debug("{}: Thing successfully initialized.", thingName);
340 updateProperties(profile, profile.status);
341 setThingOnline(); // if API call was successful the thing must be online
342 return true; // success
346 * Handle Channel Commands
349 public void handleCommand(ChannelUID channelUID, Command command) {
351 if (command instanceof RefreshType) {
352 String channelId = channelUID.getId();
353 State value = cache.getValue(channelId);
354 if (value != UnDefType.NULL) {
355 updateState(channelId, value);
360 if (!profile.isInitialized()) {
361 logger.debug("{}: {}", thingName, messages.get("command.init", command));
364 profile = getProfile(false);
367 boolean update = false;
368 switch (channelUID.getIdWithoutGroup()) {
369 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
370 logger.debug("{}: Send key {}", thingName, command);
371 api.sendIRKey(command.toString());
375 case CHANNEL_LED_STATUS_DISABLE:
376 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
377 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
379 case CHANNEL_LED_POWER_DISABLE:
380 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
381 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
384 case CHANNEL_SENSOR_SLEEPTIME:
385 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
386 int value = (int) getNumber(command);
387 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
389 api.setSleepTime(value);
391 case CHANNEL_CONTROL_SCHEDULE:
393 logger.debug("{}: {} Valve schedule/profile", thingName,
394 command == OnOffType.ON ? "Enable" : "Disable");
395 api.setValveProfile(0,
396 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
399 case CHANNEL_CONTROL_PROFILE:
400 logger.debug("{}: Select profile {}", thingName, command);
402 if (command instanceof Number) {
403 id = (int) getNumber(command);
405 String cmd = command.toString();
406 if (isDigit(cmd.charAt(0))) {
407 id = Integer.parseInt(cmd);
408 } else if (profile.settings.thermostats != null) {
409 ShellyThermnostat t = profile.settings.thermostats.get(0);
410 for (int i = 0; i < t.profileNames.length; i++) {
411 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
417 if (id < 0 || id > 5) {
418 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
421 api.setValveProfile(0, id);
423 case CHANNEL_CONTROL_MODE:
424 logger.debug("{}: Set mode to {}", thingName, command);
425 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
427 case CHANNEL_CONTROL_SETTEMP:
428 logger.debug("{}: Set temperature to {}", thingName, command);
429 api.setValveTemperature(0, (int) getNumber(command));
431 case CHANNEL_CONTROL_POSITION:
432 logger.debug("{}: Set position to {}", thingName, command);
433 api.setValvePosition(0, getNumber(command));
435 case CHANNEL_CONTROL_BCONTROL:
436 logger.debug("{}: Set boost mode to {}", thingName, command);
437 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
439 case CHANNEL_CONTROL_BTIMER:
440 logger.debug("{}: Set boost timer to {}", thingName, command);
441 api.setValveBoostTime(0, (int) getNumber(command));
445 update = handleDeviceCommand(channelUID, command);
450 if (update && !autoCoIoT && !isUpdateScheduled()) {
451 requestUpdates(1, false);
453 } catch (ShellyApiException e) {
454 ShellyApiResult res = e.getApiResult();
455 if (isAuthorizationFailed(res)) {
458 if (res.isNotCalibrtated()) {
459 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
461 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
464 } catch (IllegalArgumentException e) {
465 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
469 private double getNumber(Command command) {
470 if (command instanceof QuantityType) {
471 return ((QuantityType<?>) command).doubleValue();
473 if (command instanceof DecimalType) {
474 return ((DecimalType) command).doubleValue();
476 if (command instanceof Number) {
477 return ((Number) command).doubleValue();
479 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
483 * Update device status and channels
485 protected void refreshStatus() {
487 boolean updated = false;
489 if (vibrationFilter > 0) {
491 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
492 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
496 ThingStatus thingStatus = getThing().getStatus();
497 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
498 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
499 || (thingStatus == ThingStatus.UNKNOWN)) {
500 logger.debug("{}: Status update triggered thing initialization", thingName);
501 initializeThing(); // may fire an exception if initialization failed
503 // Get profile, if refreshSettings == true reload settings from device
504 ShellySettingsStatus status = api.getStatus();
505 if (status.uptime != null && status.uptime == 0 && profile.alwaysOn) {
506 status = api.getStatus();
508 boolean restarted = checkRestarted(status);
509 profile = getProfile(refreshSettings || restarted);
510 profile.status = status;
511 profile.updateFromStatus(status);
513 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
515 postEvent(ALARM_TYPE_RESTARTED, true);
518 // If status update was successful the thing must be online
521 // map status to channels
522 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
523 updated |= this.updateDeviceStatus(status);
524 updated |= ShellyComponents.updateDeviceStatus(this, status);
525 fillDeviceStatus(status, updated);
526 updated |= updateInputs(status);
527 updated |= updateMeters(this, status);
528 updated |= updateSensors(this, status);
530 // All channels must be created after the first cycle
531 channelsCreated = true;
533 } catch (ShellyApiException e) {
534 // http call failed: go offline except for battery devices, which might be in
535 // sleep mode. Once the next update is successful the device goes back online
537 ShellyApiResult res = e.getApiResult();
538 if (profile.alwaysOn && e.isConnectionError()) {
539 status = "offline.status-error-connect";
540 } else if (res.isHttpAccessUnauthorized()) {
541 status = "offline.conf-error-access-denied";
542 } else if (isWatchdogStarted()) {
543 if (!isWatchdogExpired()) {
544 logger.debug("{}: Ignore API Timeout, retry later", thingName);
546 if (isThingOnline()) {
547 status = "offline.status-error-watchdog";
550 } else if (e.isJSONException()) {
551 status = "offline.status-error-unexpected-api-result";
552 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
553 } else if (res.isHttpTimeout()) {
554 // Watchdog not started, e.g. device in sleep mode
555 if (isThingOnline()) { // ignore when already offline
556 status = "offline.status-error-watchdog";
559 status = "offline.status-error-unexpected-api-result";
560 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
563 if (!status.isEmpty()) {
564 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
566 } catch (NullPointerException | IllegalArgumentException e) {
567 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
569 if (scheduledUpdates > 0) {
571 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
572 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
573 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
574 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
580 private void showThingConfig(ShellyDeviceProfile profile) {
581 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
582 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
584 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
585 logger.debug("{}: Device "
586 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
587 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
588 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
589 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
590 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
591 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
592 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
593 profile.inColor, profile.alwaysOn, profile.updatePeriod);
594 if (profile.status.extTemperature != null || profile.status.extHumidity != null
595 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
596 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
600 private void addStateOptions(ShellyDeviceProfile prf) {
602 String[] profileNames = prf.getValveProfileList(0);
603 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
604 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
605 channelDefinitions.clearStateOptions(channelId);
607 for (String name : profileNames) {
608 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
612 if (prf.isRoller && prf.settings.favorites != null) {
613 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
614 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
615 prf.settings.favorites.size());
616 channelDefinitions.clearStateOptions(channelId);
618 for (ShellyFavPos fav : prf.settings.favorites) {
619 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
626 public String getThingType() {
627 return thing.getThingTypeUID().getId();
631 public ThingStatus getThingStatus() {
632 return thing.getStatus();
636 public ThingStatusDetail getThingStatusDetail() {
637 return thing.getStatusInfo().getStatusDetail();
641 public boolean isThingOnline() {
642 return getThingStatus() == ThingStatus.ONLINE;
645 public boolean isThingOffline() {
646 return getThingStatus() == ThingStatus.OFFLINE;
650 public void setThingOnline() {
651 if (!isThingOnline()) {
652 updateStatus(ThingStatus.ONLINE);
654 // request 3 updates in a row (during the first 2+3*3 sec)
655 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
658 // Restart watchdog when status update was successful (no exception)
663 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
664 if (!isThingOffline()) {
665 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
666 api.close(); // Gen2: disconnect WS/close http sessions
668 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
673 public void restartWatchdog() {
675 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
676 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
679 private boolean isWatchdogExpired() {
680 long delta = now() - watchdog;
681 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
682 stats.remainingWatchdog = delta;
688 private boolean isWatchdogStarted() {
693 public void reinitializeThing() {
694 logger.debug("{}: Re-Initialize Thing", thingName);
696 logger.debug("{}: Handler is shutting down, ignore", thingName);
699 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
700 messages.get("offline.status-error-restarted"));
701 requestUpdates(0, true);
705 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
708 // Update uptime and WiFi, internal temp
709 ShellyComponents.updateDeviceStatus(this, status);
710 stats.wifiRssi = status.wifiSta.rssi;
712 if (api.isInitialized()) {
713 stats.timeoutErrors = api.getTimeoutErrors();
714 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
716 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
718 // Check various device indicators like overheating
719 if (checkRestarted(status)) {
720 // Force re-initialization on next status update
722 } else if (getBool(status.overtemperature)) {
723 alarm = ALARM_TYPE_OVERTEMP;
724 } else if (getBool(status.overload)) {
725 alarm = ALARM_TYPE_OVERLOAD;
726 } else if (getBool(status.loaderror)) {
727 alarm = ALARM_TYPE_LOADERR;
729 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
730 if (internalTemp != UnDefType.NULL) {
731 int temp = ((Number) internalTemp).intValue();
732 if (temp > stats.maxInternalTemp) {
733 stats.maxInternalTemp = temp;
737 if (status.uptime != null) {
738 stats.lastUptime = getLong(status.uptime);
741 if (!alarm.isEmpty()) {
742 postEvent(alarm, false);
747 public void incProtMessages() {
748 stats.protocolMessages++;
752 public void incProtErrors() {
753 stats.protocolErrors++;
757 * Check if device has restarted and needs a new Thing initialization
759 * @return true: restart detected
762 private boolean checkRestarted(ShellySettingsStatus status) {
763 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
764 && (status.uptime != null && status.uptime < stats.lastUptime
765 || (!profile.status.update.oldVersion.isEmpty()
766 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
767 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
768 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
769 updateProperties(profile, status);
776 * Save alarm to the lastAlarm channel
778 * @param alarm Alarm Message
781 public void postEvent(String event, boolean force) {
782 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
783 State value = cache.getValue(channelId);
784 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
786 if (force || !lastAlarm.equals(event)
787 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
788 switch (event.toUpperCase()) {
791 case SHELLY_WAKEUPT_SENSOR:
792 case SHELLY_WAKEUPT_PERIODIC:
793 case SHELLY_WAKEUPT_BUTTON:
794 case SHELLY_WAKEUPT_POWERON:
795 case SHELLY_WAKEUPT_EXT_POWER:
796 case SHELLY_WAKEUPT_UNKNOWN:
797 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
798 case ALARM_TYPE_NONE:
801 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
802 triggerChannel(channelId, event);
803 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
804 stats.lastAlarm = event;
805 stats.lastAlarmTs = now();
811 public boolean isUpdateScheduled() {
812 return scheduledUpdates > 0;
816 * Callback for device events
818 * @param deviceName device receiving the event
819 * @param parameters parameters from the event URL
820 * @param data the HTML input data
821 * @return true if event was processed
824 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
825 Map<String, String> parameters) {
826 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
827 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
829 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
830 if (!profile.isInitialized()) {
831 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
832 requestUpdates(1, true);
834 String group = profile.getControlGroup(idx);
835 if (group.isEmpty()) {
836 logger.debug("{}: Unsupported event class: {}", thingName, type);
840 // map some of the events to system defined button triggers
844 String parmType = getString(parameters.get("type"));
845 String event = !parmType.isEmpty() ? parmType : type;
846 boolean isButton = profile.inButtonMode(idx - 1);
848 case SHELLY_EVENT_SHORTPUSH:
849 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
850 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
851 case SHELLY_EVENT_LONGPUSH:
853 triggerButton(group, idx, mapButtonEvent(event));
854 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
855 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
857 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
861 case SHELLY_EVENT_BTN_ON:
862 case SHELLY_EVENT_BTN_OFF:
863 if (profile.isRGBW2) {
864 // RGBW2 has only one input, so not per channel
865 group = CHANNEL_GROUP_LIGHT_CONTROL;
867 onoff = CHANNEL_INPUT;
869 case SHELLY_EVENT_BTN1_ON:
870 case SHELLY_EVENT_BTN1_OFF:
871 onoff = CHANNEL_INPUT1;
873 case SHELLY_EVENT_BTN2_ON:
874 case SHELLY_EVENT_BTN2_OFF:
875 onoff = CHANNEL_INPUT2;
877 case SHELLY_EVENT_OUT_ON:
878 case SHELLY_EVENT_OUT_OFF:
879 onoff = CHANNEL_OUTPUT;
881 case SHELLY_EVENT_ROLLER_OPEN:
882 case SHELLY_EVENT_ROLLER_CLOSE:
883 case SHELLY_EVENT_ROLLER_STOP:
884 channel = CHANNEL_EVENT_TRIGGER;
887 case SHELLY_EVENT_SENSORREPORT:
888 // process sensor with next refresh
890 case SHELLY_EVENT_TEMP_OVER: // DW2
891 case SHELLY_EVENT_TEMP_UNDER:
892 channel = CHANNEL_EVENT_TRIGGER;
895 case SHELLY_EVENT_FLOOD_DETECTED:
896 case SHELLY_EVENT_FLOOD_GONE:
897 updateChannel(group, CHANNEL_SENSOR_FLOOD,
898 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
901 case SHELLY_EVENT_CLOSE: // DW 1.7
902 case SHELLY_EVENT_OPEN: // DW 1.7
903 updateChannel(group, CHANNEL_SENSOR_STATE,
904 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
905 : OpenClosedType.CLOSED);
908 case SHELLY_EVENT_DARK: // DW 1.7
909 case SHELLY_EVENT_TWILIGHT: // DW 1.7
910 case SHELLY_EVENT_BRIGHT: // DW 1.7
911 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
914 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
915 case SHELLY_EVENT_ALARM_HEAVY:
916 case SHELLY_EVENT_ALARM_OFF:
917 case SHELLY_EVENT_VIBRATION: // DW2
918 channel = CHANNEL_SENSOR_ALARM_STATE;
919 payload = event.toUpperCase();
923 // trigger will be provided by input/output channel or sensor channels
926 if (!onoff.isEmpty()) {
927 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
929 if (!payload.isEmpty()) {
930 // Pass event to trigger channel
931 payload = payload.toUpperCase();
932 logger.debug("{}: Post event {}", thingName, payload);
933 triggerChannel(mkChannelId(group, channel), payload);
937 // request update on next interval (2x for non-battery devices)
939 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
946 * Initialize the binding's thing configuration, calc update counts
948 protected void initializeThingConfig() {
949 thingType = getThing().getThingTypeUID().getId();
950 final Map<String, String> properties = getThing().getProperties();
951 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
952 if (thingName.isEmpty()) {
953 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
954 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
957 config = getConfigAs(ShellyThingConfiguration.class);
958 if (config.deviceIp.isEmpty()) {
959 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
963 InetAddress addr = InetAddress.getByName(config.deviceIp);
964 String saddr = addr.getHostAddress();
965 if (!config.deviceIp.equals(saddr)) {
966 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
967 config.deviceIp = saddr;
969 } catch (UnknownHostException e) {
970 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
973 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
974 config.localIp = bindingConfig.localIP;
975 config.localPort = String.valueOf(bindingConfig.httpPort);
976 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
977 config.userId = bindingConfig.defaultUserId;
978 config.password = bindingConfig.defaultPassword;
979 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
981 if (config.updateInterval == 0) {
982 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
984 if (config.updateInterval < UPDATE_MIN_DELAY) {
985 config.updateInterval = UPDATE_MIN_DELAY;
988 // Try to get updatePeriod from properties
989 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
990 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
991 // initialized successfully by the REST call.
992 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
993 if (!lastPeriod.isEmpty()) {
994 int period = Integer.parseInt(lastPeriod);
996 profile.updatePeriod = period;
1000 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1001 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1004 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1006 ShellyVersionDTO version = new ShellyVersionDTO();
1007 if (version.checkBeta(getString(prf.fwVersion))) {
1008 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1010 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1011 if (version.compare(prf.fwVersion, minVersion) < 0) {
1012 logger.warn("{}: {}", prf.hostname,
1013 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1016 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1017 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
1018 if (!config.eventsCoIoT) {
1019 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1023 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1024 logger.info("{}: {}", thingName,
1025 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1027 } catch (NullPointerException e) { // could be inconsistant format of beta version
1028 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1032 public String checkForUpdate() {
1034 ShellyOtaCheckResult result = api.checkForUpdate();
1035 return result.status;
1036 } catch (ShellyApiException e) {
1041 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1042 if (coap == null || !config.eventsCoIoT) {
1045 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1046 String devpeer = getString(profile.settings.coiot.peer);
1047 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1048 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1050 api.setCoIoTPeer(ourpeer);
1051 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1052 } catch (ShellyApiException e) {
1053 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1055 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1056 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1060 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1061 config.eventsCoIoT = true;
1062 config.eventsSwitch = false;
1063 config.eventsButton = false;
1064 config.eventsPush = false;
1065 config.eventsRoller = false;
1066 config.eventsSensorReport = false;
1067 api.setConfig(thingName, config);
1070 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1072 coap.start(thingName, config);
1077 * Checks the http response for authorization error.
1078 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1079 * case the thing type shelly-unknown is set.
1081 * @param response exception details including the http respone
1082 * @return true if the authorization failed
1084 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1085 if (result.isHttpAccessUnauthorized()) {
1086 // If the device is password protected the API doesn't provide settings to the device settings
1087 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1094 * Change type of this thing.
1096 * @param thingType thing type acc. to the xml definition
1097 * @param mode Device mode (e.g. relay, roller)
1099 protected void changeThingType(String thingType, String mode) {
1100 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1101 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1102 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1103 Map<String, String> properties = editProperties();
1104 properties.replace(PROPERTY_DEV_TYPE, thingType);
1105 properties.replace(PROPERTY_DEV_MODE, mode);
1106 updateProperties(properties);
1107 changeThingType(thingTypeUID, getConfig());
1112 public void thingUpdated(Thing thing) {
1113 logger.debug("{}: Channel definitions updated.", thingName);
1114 super.thingUpdated(thing);
1118 * Start the background updates
1120 protected void startUpdateJob() {
1121 ScheduledFuture<?> statusJob = this.statusJob;
1122 if ((statusJob == null) || statusJob.isCancelled()) {
1123 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1125 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1126 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1131 * Flag the status job to do an exceptional update (something happened) rather
1132 * than waiting until the next regular poll
1134 * @param requestCount number of polls to execute
1135 * @param refreshSettings true=force a /settings query
1136 * @return true=Update schedule, false=skipped (too many updates already
1140 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1141 this.refreshSettings |= refreshSettings;
1142 if (refreshSettings) {
1143 if (requestCount == 0) {
1144 logger.debug("{}: Request settings refresh", thingName);
1146 scheduledUpdates = 1;
1149 if (scheduledUpdates < 10) { // < 30s
1150 scheduledUpdates += requestCount;
1157 * Map input states to channels
1159 * @param groupName Channel Group (relay / relay1...)
1161 * @param status Shelly device status
1162 * @return true: one or more inputs were updated
1165 public boolean updateInputs(ShellySettingsStatus status) {
1166 boolean updated = false;
1168 if (status.inputs != null) {
1169 if (!areChannelsCreated()) {
1170 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1174 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1175 for (ShellyInputState input : status.inputs) {
1176 String group = profile.getInputGroup(idx);
1177 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1178 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1179 if (input.event != null) {
1180 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1181 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1186 if (status.input != null) {
1187 // RGBW2: a single int rather than an array
1188 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1189 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1196 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1197 boolean changed = false;
1198 if (valueArray != null && !valueArray.isEmpty()) {
1199 String reason = getString((String) valueArray.get(0));
1200 String newVal = valueArray.toString();
1201 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1202 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1204 postEvent(reason.toUpperCase(), true);
1206 lastWakeupReason = newVal;
1212 public void triggerButton(String group, int idx, String value) {
1213 String trigger = mapButtonEvent(value);
1214 if (trigger.isEmpty()) {
1218 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1219 triggerChannel(group,
1220 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1222 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1223 if (profile.alwaysOn) {
1224 // refresh status of the input channel
1225 requestUpdates(1, false);
1230 public void publishState(String channelId, State value) {
1231 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1232 if (!stopping && isLinked(id)) {
1233 updateState(id, value);
1234 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1239 public boolean updateChannel(String group, String channel, State value) {
1240 return updateChannel(mkChannelId(group, channel), value, false);
1244 public boolean updateChannel(String channelId, State value, boolean force) {
1245 return !stopping && cache.updateChannel(channelId, value, force);
1249 public State getChannelValue(String group, String channel) {
1250 return cache.getValue(group, channel);
1254 public double getChannelDouble(String group, String channel) {
1255 State value = getChannelValue(group, channel);
1256 if (value != UnDefType.NULL) {
1257 if (value instanceof QuantityType) {
1258 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1260 if (value instanceof DecimalType) {
1261 return ((DecimalType) value).doubleValue();
1268 * Update Thing's channels according to available status information from the API
1270 * @param thingHandler
1273 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1274 if (channelsCreated) {
1275 return; // already done
1279 // Get subset of those channels that currently do not exist
1280 List<Channel> existingChannels = getThing().getChannels();
1281 for (Channel channel : existingChannels) {
1282 String id = channel.getUID().getId();
1283 if (dynChannels.containsKey(id)) {
1284 dynChannels.remove(id);
1288 if (!dynChannels.isEmpty()) {
1289 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1290 ThingBuilder thingBuilder = editThing();
1291 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1292 Channel c = channel.getValue();
1293 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1294 thingBuilder.withChannel(c);
1296 updateThing(thingBuilder.build());
1297 logger.debug("{}: Channel definitions updated", thingName);
1299 } catch (IllegalArgumentException e) {
1300 logger.debug("{}: Unable to update channel definitions", thingName, e);
1305 public boolean areChannelsCreated() {
1306 return channelsCreated;
1310 * Update thing properties with dynamic values
1312 * @param profile The device profile
1313 * @param status the /status result
1315 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1316 Map<String, Object> properties = fillDeviceProperties(profile);
1317 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1318 String deviceName = getString(profile.settings.name);
1319 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1320 properties.put(PROPERTY_DEV_GEN, "1");
1321 if (!deviceName.isEmpty()) {
1322 properties.put(PROPERTY_DEV_NAME, deviceName);
1324 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1326 // add status properties
1327 if (status.wifiSta != null) {
1328 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1330 if (status.update != null) {
1331 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1332 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1333 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1334 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1336 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1338 Map<String, String> thingProperties = new TreeMap<>();
1339 for (Map.Entry<String, Object> property : properties.entrySet()) {
1340 thingProperties.put(property.getKey(), (String) property.getValue());
1342 flushProperties(thingProperties);
1346 * Add one property to the Thing Properties
1348 * @param key Name of the property
1349 * @param value Value of the property
1352 public void updateProperties(String key, String value) {
1353 Map<String, String> thingProperties = editProperties();
1354 if (thingProperties.containsKey(key)) {
1355 thingProperties.replace(key, value);
1357 thingProperties.put(key, value);
1359 updateProperties(thingProperties);
1360 logger.trace("{}: Properties updated", thingName);
1363 public void flushProperties(Map<String, String> propertyUpdates) {
1364 Map<String, String> thingProperties = editProperties();
1365 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1366 if (thingProperties.containsKey(property.getKey())) {
1367 thingProperties.replace(property.getKey(), property.getValue());
1369 thingProperties.put(property.getKey(), property.getValue());
1372 updateProperties(thingProperties);
1376 * Get one property from the Thing Properties
1378 * @param key property name
1379 * @return property value or "" if property is not set
1382 public String getProperty(String key) {
1383 Map<String, String> thingProperties = getThing().getProperties();
1384 return getString(thingProperties.get(key));
1388 * Fill Thing Properties with device attributes
1390 * @param profile Property Map to full
1391 * @return a full property map
1393 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1394 Map<String, Object> properties = new TreeMap<>();
1395 properties.put(PROPERTY_VENDOR, VENDOR);
1396 if (profile.isInitialized()) {
1397 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1398 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1399 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1400 properties.put(PROPERTY_DEV_MODE, profile.mode);
1401 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1402 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1403 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1404 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1405 if (!profile.hwRev.isEmpty()) {
1406 properties.put(PROPERTY_HWREV, profile.hwRev);
1407 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1414 * Return device profile.
1416 * @param ForceRefresh true=force refresh before returning, false=return without
1418 * @return ShellyDeviceProfile instance
1419 * @throws ShellyApiException
1422 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1424 refreshSettings |= forceRefresh;
1425 if (refreshSettings) {
1426 profile = api.getDeviceProfile(thingType);
1427 if (!isThingOnline()) {
1428 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1432 refreshSettings = false;
1438 public ShellyDeviceProfile getProfile() {
1443 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1444 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1445 if (!options.isEmpty()) {
1446 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1452 protected ShellyDeviceProfile getDeviceProfile() {
1457 public void triggerChannel(String group, String channel, String payload) {
1458 String triggerCh = mkChannelId(group, channel);
1459 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1460 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1461 if (vibrationFilter == 0) {
1462 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1463 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1464 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1466 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1467 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1472 triggerChannel(triggerCh, payload);
1475 public void stop() {
1476 logger.debug("{}: Shutting down", thingName);
1477 ScheduledFuture<?> job = this.initJob;
1482 job = this.statusJob;
1486 logger.debug("{}: Shelly statusJob stopped", thingName);
1489 profile.initialized = false;
1493 * Shutdown thing, make sure background jobs are canceled
1496 public void dispose() {
1497 logger.debug("{}: Stopping Thing", thingName);
1504 * Device specific command handlers are overriding this method to do additional stuff
1506 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1510 public String getUID() {
1511 return getThing().getUID().getAsString();
1515 * Device specific handlers are overriding this method to do additional stuff
1517 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1522 public String getThingName() {
1527 public void resetStats() {
1529 stats = new ShellyDeviceStats();
1533 public ShellyDeviceStats getStats() {
1538 public ShellyApiInterface getApi() {
1543 public long getScheduledUpdates() {
1544 return scheduledUpdates;
1547 public Map<String, String> getStatsProp() {
1548 return stats.asProperties();
1552 public void triggerUpdateFromCoap() {
1553 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1554 requestUpdates(1, false);