2 * Copyright (c) 2010-2022 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;
126 * @param thing The Thing object
127 * @param bindingConfig The binding configuration (beside thing
129 * @param coapServer coap server instance
130 * @param localIP local IP address from networkAddressService
131 * @param httpPort from httpService
133 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
134 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
135 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
138 this.thingName = getString(thing.getLabel());
139 this.messages = translationProvider;
140 this.cache = new ShellyChannelCache(this);
141 this.channelDefinitions = new ShellyChannelDefinitions(messages);
142 this.bindingConfig = bindingConfig;
143 this.config = getConfigAs(ShellyThingConfiguration.class);
144 this.httpClient = httpClient;
146 Map<String, String> properties = thing.getProperties();
147 String gen = getString(properties.get(PROPERTY_DEV_GEN));
148 String thingType = getThingType();
149 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
152 gen2 = "2".equals(gen);
153 this.api = !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this);
155 config.eventsCoIoT = false;
157 if (config.eventsCoIoT) {
158 this.coap = new Shelly1CoapHandler(this, coapServer);
163 public boolean checkRepresentation(String key) {
164 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
165 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
169 * Schedule asynchronous Thing initialization, register thing to event dispatcher
172 public void initialize() {
173 // start background initialization:
174 scheduler.schedule(() -> {
175 boolean start = true;
177 initializeThingConfig();
178 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
179 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
180 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
182 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
183 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
184 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
185 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
186 messages.get("status.unknown.initializing"));
187 start = initializeThing();
188 } catch (ShellyApiException e) {
189 ShellyApiResult res = e.getApiResult();
190 if (profile.alwaysOn && e.isConnectionError()) {
191 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, "offline.status-error-connect",
194 if (isAuthorizationFailed(res)) {
197 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
198 } catch (IllegalArgumentException e) {
199 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
201 // even this initialization failed we start the status update
202 // the updateJob will then try to auto-initialize the thing
203 // in this case the thing stays in status INITIALIZING
208 }, 2, TimeUnit.SECONDS);
212 public ShellyThingConfiguration getThingConfig() {
217 public HttpClient getHttpClient() {
222 * This routine is called every time the Thing configuration has been changed
225 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
226 super.handleConfigurationUpdate(configurationParameters);
227 logger.debug("{}: Thing config updated, re-initialize", thingName);
231 requestUpdates(1, true);// force re-initialization
235 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
236 * If the device is password protected and the credentials are missing or don't match the API access will throw an
237 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
238 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
239 * credentials are correct and the API access is initialized successful.
241 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
243 public boolean initializeThing() throws ShellyApiException {
244 // Init from thing type to have a basic profile, gets updated when device info is received from API
246 refreshSettings = false;
247 lastWakeupReason = "";
248 cache.setThingName(thingName);
252 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
253 getThing().getLabel(), thingType, config.deviceIp, gen2, config.eventsCoIoT);
254 if (config.deviceIp.isEmpty()) {
255 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
259 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
260 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
261 // Action URL does when enabled)
262 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
263 coap.start(thingName, config);
266 // Initialize API access, exceptions will be catched by initialize()
268 profile.initFromThingType(thingType);
269 ShellySettingsDevice devInfo = api.getDeviceInfo();
270 if (getBool(devInfo.auth) && config.password.isEmpty()) {
271 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
274 if (config.serviceName.isEmpty()) {
275 config.serviceName = getString(profile.hostname).toLowerCase();
278 api.setConfig(thingName, config);
279 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
280 tmpPrf.isGen2 = gen2;
281 tmpPrf.auth = devInfo.auth; // missing in /settings
283 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
284 changeThingType(thingName, tmpPrf.mode);
285 return false; // force re-initialization
287 // Validate device mode
288 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
289 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
290 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
294 if (!getString(devInfo.coiot).isEmpty()) {
295 // New Shelly devices might use a different endpoint for the CoAP listener
296 tmpPrf.coiotEndpoint = devInfo.coiot;
298 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
299 // Sensor, usually 12h, H&T in USB mode 10min
300 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
301 ? tmpPrf.settings.sleepMode.period * 60 // minutes
302 : tmpPrf.settings.sleepMode.period * 3600; // hours
303 tmpPrf.updatePeriod += 60; // give 1min extra
304 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
305 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
306 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
307 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
309 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
312 tmpPrf.status = api.getStatus(); // update thing properties
313 tmpPrf.updateFromStatus(tmpPrf.status);
314 addStateOptions(tmpPrf);
316 // update thing properties
317 updateProperties(tmpPrf, tmpPrf.status);
318 checkVersion(tmpPrf, tmpPrf.status);
320 startCoap(config, tmpPrf);
322 api.setActionURLs(); // register event urls
325 // All initialization done, so keep the profile and set Thing to ONLINE
326 fillDeviceStatus(tmpPrf.status, false);
327 postEvent(ALARM_TYPE_NONE, false);
330 showThingConfig(profile);
332 logger.debug("{}: Thing successfully initialized.", thingName);
333 updateProperties(profile, profile.status);
334 setThingOnline(); // if API call was successful the thing must be online
335 return true; // success
339 * Handle Channel Commands
342 public void handleCommand(ChannelUID channelUID, Command command) {
344 if (command instanceof RefreshType) {
345 String channelId = channelUID.getId();
346 State value = cache.getValue(channelId);
347 if (value != UnDefType.NULL) {
348 updateState(channelId, value);
353 if (!profile.isInitialized()) {
354 logger.debug("{}: {}", thingName, messages.get("command.init", command));
357 profile = getProfile(false);
360 boolean update = false;
361 switch (channelUID.getIdWithoutGroup()) {
362 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
363 logger.debug("{}: Send key {}", thingName, command);
364 api.sendIRKey(command.toString());
368 case CHANNEL_LED_STATUS_DISABLE:
369 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
370 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
372 case CHANNEL_LED_POWER_DISABLE:
373 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
374 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
377 case CHANNEL_SENSOR_SLEEPTIME:
378 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
379 int value = (int) getNumber(command);
380 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
382 api.setSleepTime(value);
384 case CHANNEL_CONTROL_SCHEDULE:
386 logger.debug("{}: {} Valve schedule/profile", thingName,
387 command == OnOffType.ON ? "Enable" : "Disable");
388 api.setValveProfile(0,
389 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
392 case CHANNEL_CONTROL_PROFILE:
393 logger.debug("{}: Select profile {}", thingName, command);
395 if (command instanceof Number) {
396 id = (int) getNumber(command);
398 String cmd = command.toString();
399 if (isDigit(cmd.charAt(0))) {
400 id = Integer.parseInt(cmd);
401 } else if (profile.settings.thermostats != null) {
402 ShellyThermnostat t = profile.settings.thermostats.get(0);
403 for (int i = 0; i < t.profileNames.length; i++) {
404 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
410 if (id < 0 || id > 5) {
411 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
414 api.setValveProfile(0, id);
416 case CHANNEL_CONTROL_MODE:
417 logger.debug("{}: Set mode to {}", thingName, command);
418 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
420 case CHANNEL_CONTROL_SETTEMP:
421 logger.debug("{}: Set temperature to {}", thingName, command);
422 api.setValveTemperature(0, (int) getNumber(command));
424 case CHANNEL_CONTROL_POSITION:
425 logger.debug("{}: Set position to {}", thingName, command);
426 api.setValvePosition(0, getNumber(command));
428 case CHANNEL_CONTROL_BCONTROL:
429 logger.debug("{}: Set boost mode to {}", thingName, command);
430 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
432 case CHANNEL_CONTROL_BTIMER:
433 logger.debug("{}: Set boost timer to {}", thingName, command);
434 api.setValveBoostTime(0, (int) getNumber(command));
438 update = handleDeviceCommand(channelUID, command);
443 if (update && !autoCoIoT && !isUpdateScheduled()) {
444 requestUpdates(1, false);
446 } catch (ShellyApiException e) {
447 ShellyApiResult res = e.getApiResult();
448 if (isAuthorizationFailed(res)) {
451 if (res.isNotCalibrtated()) {
452 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
454 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
457 } catch (IllegalArgumentException e) {
458 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
462 private double getNumber(Command command) {
463 if (command instanceof QuantityType) {
464 return ((QuantityType<?>) command).doubleValue();
466 if (command instanceof DecimalType) {
467 return ((DecimalType) command).doubleValue();
469 if (command instanceof Number) {
470 return ((Number) command).doubleValue();
472 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
476 * Update device status and channels
478 protected void refreshStatus() {
480 boolean updated = false;
482 if (vibrationFilter > 0) {
484 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
485 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
489 ThingStatus thingStatus = getThing().getStatus();
490 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
491 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
492 || (thingStatus == ThingStatus.UNKNOWN)) {
493 logger.debug("{}: Status update triggered thing initialization", thingName);
494 initializeThing(); // may fire an exception if initialization failed
496 // Get profile, if refreshSettings == true reload settings from device
497 ShellySettingsStatus status = api.getStatus();
498 if (status.uptime != null && status.uptime == 0 && profile.alwaysOn) {
499 status = api.getStatus();
501 boolean restarted = checkRestarted(status);
502 profile = getProfile(refreshSettings || restarted);
503 profile.status = status;
504 profile.updateFromStatus(status);
506 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
508 postEvent(ALARM_TYPE_RESTARTED, true);
511 // If status update was successful the thing must be online
514 // map status to channels
515 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
516 updated |= this.updateDeviceStatus(status);
517 updated |= ShellyComponents.updateDeviceStatus(this, status);
518 fillDeviceStatus(status, updated);
519 updated |= updateInputs(status);
520 updated |= updateMeters(this, status);
521 updated |= updateSensors(this, status);
523 // All channels must be created after the first cycle
524 channelsCreated = true;
526 } catch (ShellyApiException e) {
527 // http call failed: go offline except for battery devices, which might be in
528 // sleep mode. Once the next update is successful the device goes back online
530 ShellyApiResult res = e.getApiResult();
531 if (profile.alwaysOn && e.isConnectionError()) {
532 status = "offline.status-error-connect";
533 } else if (res.isHttpAccessUnauthorized()) {
534 status = "offline.conf-error-access-denied";
535 } else if (isWatchdogStarted()) {
536 if (!isWatchdogExpired()) {
537 logger.debug("{}: Ignore API Timeout, retry later", thingName);
539 if (isThingOnline()) {
540 status = "offline.status-error-watchdog";
543 } else if (e.isJSONException()) {
544 status = "offline.status-error-unexpected-api-result";
545 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
546 } else if (res.isHttpTimeout()) {
547 // Watchdog not started, e.g. device in sleep mode
548 if (isThingOnline()) { // ignore when already offline
549 status = "offline.status-error-watchdog";
552 status = "offline.status-error-unexpected-api-result";
553 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
556 if (!status.isEmpty()) {
557 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
559 } catch (NullPointerException | IllegalArgumentException e) {
560 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
562 if (scheduledUpdates > 0) {
564 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
565 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
566 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
567 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
573 private void showThingConfig(ShellyDeviceProfile profile) {
574 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
575 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
577 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
578 logger.debug("{}: Device "
579 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
580 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
581 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
582 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
583 profile.isDW, profile.hasBattery,
584 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
585 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
586 profile.alwaysOn, profile.updatePeriod);
589 private void addStateOptions(ShellyDeviceProfile prf) {
591 String[] profileNames = prf.getValveProfileList(0);
592 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
593 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
594 channelDefinitions.clearStateOptions(channelId);
596 for (String name : profileNames) {
597 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
601 if (prf.isRoller && prf.settings.favorites != null) {
602 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
603 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
604 prf.settings.favorites.size());
605 channelDefinitions.clearStateOptions(channelId);
607 for (ShellyFavPos fav : prf.settings.favorites) {
608 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
615 public String getThingType() {
616 return thing.getThingTypeUID().getId();
620 public ThingStatus getThingStatus() {
621 return thing.getStatus();
625 public ThingStatusDetail getThingStatusDetail() {
626 return thing.getStatusInfo().getStatusDetail();
630 public boolean isThingOnline() {
631 return getThingStatus() == ThingStatus.ONLINE;
634 public boolean isThingOffline() {
635 return getThingStatus() == ThingStatus.OFFLINE;
639 public void setThingOnline() {
640 if (!isThingOnline()) {
641 updateStatus(ThingStatus.ONLINE);
643 // request 3 updates in a row (during the first 2+3*3 sec)
644 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
647 // Restart watchdog when status update was successful (no exception)
652 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
653 if (!isThingOffline()) {
654 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
655 api.close(); // Gen2: disconnect WS/close http sessions
657 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
662 public void restartWatchdog() {
664 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
665 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
668 private boolean isWatchdogExpired() {
669 long delta = now() - watchdog;
670 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
671 stats.remainingWatchdog = delta;
677 private boolean isWatchdogStarted() {
682 public void reinitializeThing() {
683 logger.debug("{}: Re-Initialize Thing", thingName);
685 logger.debug("{}: Handler is shutting down, ignore", thingName);
688 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
689 messages.get("offline.status-error-restarted"));
690 requestUpdates(0, true);
694 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
697 // Update uptime and WiFi, internal temp
698 ShellyComponents.updateDeviceStatus(this, status);
699 stats.wifiRssi = status.wifiSta.rssi;
701 if (api.isInitialized()) {
702 stats.timeoutErrors = api.getTimeoutErrors();
703 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
705 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
707 // Check various device indicators like overheating
708 if (checkRestarted(status)) {
709 // Force re-initialization on next status update
711 } else if (getBool(status.overtemperature)) {
712 alarm = ALARM_TYPE_OVERTEMP;
713 } else if (getBool(status.overload)) {
714 alarm = ALARM_TYPE_OVERLOAD;
715 } else if (getBool(status.loaderror)) {
716 alarm = ALARM_TYPE_LOADERR;
718 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
719 if (internalTemp != UnDefType.NULL) {
720 int temp = ((Number) internalTemp).intValue();
721 if (temp > stats.maxInternalTemp) {
722 stats.maxInternalTemp = temp;
726 if (status.uptime != null) {
727 stats.lastUptime = getLong(status.uptime);
730 if (!alarm.isEmpty()) {
731 postEvent(alarm, false);
736 public void incProtMessages() {
737 stats.protocolMessages++;
741 public void incProtErrors() {
742 stats.protocolErrors++;
746 * Check if device has restarted and needs a new Thing initialization
748 * @return true: restart detected
751 private boolean checkRestarted(ShellySettingsStatus status) {
752 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
753 && (status.uptime != null && status.uptime < stats.lastUptime
754 || (!profile.status.update.oldVersion.isEmpty()
755 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
756 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
757 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
758 updateProperties(profile, status);
765 * Save alarm to the lastAlarm channel
767 * @param alarm Alarm Message
770 public void postEvent(String event, boolean force) {
771 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
772 State value = cache.getValue(channelId);
773 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
775 if (force || !lastAlarm.equals(event)
776 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
777 switch (event.toUpperCase()) {
780 case SHELLY_WAKEUPT_SENSOR:
781 case SHELLY_WAKEUPT_PERIODIC:
782 case SHELLY_WAKEUPT_BUTTON:
783 case SHELLY_WAKEUPT_POWERON:
784 case SHELLY_WAKEUPT_EXT_POWER:
785 case SHELLY_WAKEUPT_UNKNOWN:
786 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
787 case ALARM_TYPE_NONE:
790 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
791 triggerChannel(channelId, event);
792 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
793 stats.lastAlarm = event;
794 stats.lastAlarmTs = now();
800 public boolean isUpdateScheduled() {
801 return scheduledUpdates > 0;
805 * Callback for device events
807 * @param deviceName device receiving the event
808 * @param parameters parameters from the event URL
809 * @param data the HTML input data
810 * @return true if event was processed
813 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
814 Map<String, String> parameters) {
815 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
816 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
818 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
819 if (!profile.isInitialized()) {
820 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
821 requestUpdates(1, true);
823 String group = profile.getControlGroup(idx);
824 if (group.isEmpty()) {
825 logger.debug("{}: Unsupported event class: {}", thingName, type);
829 // map some of the events to system defined button triggers
833 String parmType = getString(parameters.get("type"));
834 String event = !parmType.isEmpty() ? parmType : type;
835 boolean isButton = profile.inButtonMode(idx - 1);
837 case SHELLY_EVENT_SHORTPUSH:
838 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
839 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
840 case SHELLY_EVENT_LONGPUSH:
842 triggerButton(group, idx, mapButtonEvent(event));
843 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
844 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
846 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
850 case SHELLY_EVENT_BTN_ON:
851 case SHELLY_EVENT_BTN_OFF:
852 if (profile.isRGBW2) {
853 // RGBW2 has only one input, so not per channel
854 group = CHANNEL_GROUP_LIGHT_CONTROL;
856 onoff = CHANNEL_INPUT;
858 case SHELLY_EVENT_BTN1_ON:
859 case SHELLY_EVENT_BTN1_OFF:
860 onoff = CHANNEL_INPUT1;
862 case SHELLY_EVENT_BTN2_ON:
863 case SHELLY_EVENT_BTN2_OFF:
864 onoff = CHANNEL_INPUT2;
866 case SHELLY_EVENT_OUT_ON:
867 case SHELLY_EVENT_OUT_OFF:
868 onoff = CHANNEL_OUTPUT;
870 case SHELLY_EVENT_ROLLER_OPEN:
871 case SHELLY_EVENT_ROLLER_CLOSE:
872 case SHELLY_EVENT_ROLLER_STOP:
873 channel = CHANNEL_EVENT_TRIGGER;
876 case SHELLY_EVENT_SENSORREPORT:
877 // process sensor with next refresh
879 case SHELLY_EVENT_TEMP_OVER: // DW2
880 case SHELLY_EVENT_TEMP_UNDER:
881 channel = CHANNEL_EVENT_TRIGGER;
884 case SHELLY_EVENT_FLOOD_DETECTED:
885 case SHELLY_EVENT_FLOOD_GONE:
886 updateChannel(group, CHANNEL_SENSOR_FLOOD,
887 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
890 case SHELLY_EVENT_CLOSE: // DW 1.7
891 case SHELLY_EVENT_OPEN: // DW 1.7
892 updateChannel(group, CHANNEL_SENSOR_STATE,
893 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
894 : OpenClosedType.CLOSED);
897 case SHELLY_EVENT_DARK: // DW 1.7
898 case SHELLY_EVENT_TWILIGHT: // DW 1.7
899 case SHELLY_EVENT_BRIGHT: // DW 1.7
900 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
903 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
904 case SHELLY_EVENT_ALARM_HEAVY:
905 case SHELLY_EVENT_ALARM_OFF:
906 case SHELLY_EVENT_VIBRATION: // DW2
907 channel = CHANNEL_SENSOR_ALARM_STATE;
908 payload = event.toUpperCase();
912 // trigger will be provided by input/output channel or sensor channels
915 if (!onoff.isEmpty()) {
916 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
918 if (!payload.isEmpty()) {
919 // Pass event to trigger channel
920 payload = payload.toUpperCase();
921 logger.debug("{}: Post event {}", thingName, payload);
922 triggerChannel(mkChannelId(group, channel), payload);
926 // request update on next interval (2x for non-battery devices)
928 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
935 * Initialize the binding's thing configuration, calc update counts
937 protected void initializeThingConfig() {
938 thingType = getThing().getThingTypeUID().getId();
939 final Map<String, String> properties = getThing().getProperties();
940 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
941 if (thingName.isEmpty()) {
942 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
943 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
946 config = getConfigAs(ShellyThingConfiguration.class);
947 if (config.deviceIp.isEmpty()) {
948 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
952 InetAddress addr = InetAddress.getByName(config.deviceIp);
953 String saddr = addr.getHostAddress();
954 if (!config.deviceIp.equals(saddr)) {
955 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
956 config.deviceIp = saddr;
958 } catch (UnknownHostException e) {
959 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
962 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
963 config.localIp = bindingConfig.localIP;
964 config.localPort = String.valueOf(bindingConfig.httpPort);
965 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
966 config.userId = bindingConfig.defaultUserId;
967 config.password = bindingConfig.defaultPassword;
968 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
970 if (config.updateInterval == 0) {
971 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
973 if (config.updateInterval < UPDATE_MIN_DELAY) {
974 config.updateInterval = UPDATE_MIN_DELAY;
977 // Try to get updatePeriod from properties
978 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
979 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
980 // initialized successfully by the REST call.
981 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
982 if (!lastPeriod.isEmpty()) {
983 int period = Integer.parseInt(lastPeriod);
985 profile.updatePeriod = period;
989 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
990 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
993 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
995 ShellyVersionDTO version = new ShellyVersionDTO();
996 if (version.checkBeta(getString(prf.fwVersion))) {
997 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
999 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1000 if (version.compare(prf.fwVersion, minVersion) < 0) {
1001 logger.warn("{}: {}", prf.hostname,
1002 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1005 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1006 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
1007 if (!config.eventsCoIoT) {
1008 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1012 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1013 logger.info("{}: {}", thingName,
1014 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1016 } catch (NullPointerException e) { // could be inconsistant format of beta version
1017 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1021 public String checkForUpdate() {
1023 ShellyOtaCheckResult result = api.checkForUpdate();
1024 return result.status;
1025 } catch (ShellyApiException e) {
1030 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1031 if (coap == null || !config.eventsCoIoT) {
1034 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1035 String devpeer = getString(profile.settings.coiot.peer);
1036 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1037 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1039 api.setCoIoTPeer(ourpeer);
1040 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1041 } catch (ShellyApiException e) {
1042 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1044 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1045 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1049 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1050 config.eventsCoIoT = true;
1051 config.eventsSwitch = false;
1052 config.eventsButton = false;
1053 config.eventsPush = false;
1054 config.eventsRoller = false;
1055 config.eventsSensorReport = false;
1056 api.setConfig(thingName, config);
1059 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1061 coap.start(thingName, config);
1066 * Checks the http response for authorization error.
1067 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1068 * case the thing type shelly-unknown is set.
1070 * @param response exception details including the http respone
1071 * @return true if the authorization failed
1073 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1074 if (result.isHttpAccessUnauthorized()) {
1075 // If the device is password protected the API doesn't provide settings to the device settings
1076 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1083 * Change type of this thing.
1085 * @param thingType thing type acc. to the xml definition
1086 * @param mode Device mode (e.g. relay, roller)
1088 protected void changeThingType(String thingType, String mode) {
1089 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1090 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1091 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1092 Map<String, String> properties = editProperties();
1093 properties.replace(PROPERTY_DEV_TYPE, thingType);
1094 properties.replace(PROPERTY_DEV_MODE, mode);
1095 updateProperties(properties);
1096 changeThingType(thingTypeUID, getConfig());
1101 public void thingUpdated(Thing thing) {
1102 logger.debug("{}: Channel definitions updated.", thingName);
1103 super.thingUpdated(thing);
1107 * Start the background updates
1109 protected void startUpdateJob() {
1110 ScheduledFuture<?> statusJob = this.statusJob;
1111 if ((statusJob == null) || statusJob.isCancelled()) {
1112 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1114 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1115 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1120 * Flag the status job to do an exceptional update (something happened) rather
1121 * than waiting until the next regular poll
1123 * @param requestCount number of polls to execute
1124 * @param refreshSettings true=force a /settings query
1125 * @return true=Update schedule, false=skipped (too many updates already
1129 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1130 this.refreshSettings |= refreshSettings;
1131 if (refreshSettings) {
1132 if (requestCount == 0) {
1133 logger.debug("{}: Request settings refresh", thingName);
1135 scheduledUpdates = 1;
1138 if (scheduledUpdates < 10) { // < 30s
1139 scheduledUpdates += requestCount;
1146 * Map input states to channels
1148 * @param groupName Channel Group (relay / relay1...)
1150 * @param status Shelly device status
1151 * @return true: one or more inputs were updated
1154 public boolean updateInputs(ShellySettingsStatus status) {
1155 boolean updated = false;
1157 if (status.inputs != null) {
1158 if (!areChannelsCreated()) {
1159 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1163 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1164 for (ShellyInputState input : status.inputs) {
1165 String group = profile.getInputGroup(idx);
1166 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1167 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1168 if (input.event != null) {
1169 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1170 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1175 if (status.input != null) {
1176 // RGBW2: a single int rather than an array
1177 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1178 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1185 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1186 boolean changed = false;
1187 if (valueArray != null && !valueArray.isEmpty()) {
1188 String reason = getString((String) valueArray.get(0));
1189 String newVal = valueArray.toString();
1190 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1191 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1193 postEvent(reason.toUpperCase(), true);
1195 lastWakeupReason = newVal;
1201 public void triggerButton(String group, int idx, String value) {
1202 String trigger = mapButtonEvent(value);
1203 if (trigger.isEmpty()) {
1207 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1208 triggerChannel(group,
1209 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1211 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1212 if (profile.alwaysOn) {
1213 // refresh status of the input channel
1214 requestUpdates(1, false);
1219 public void publishState(String channelId, State value) {
1220 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1221 if (!stopping && isLinked(id)) {
1222 updateState(id, value);
1223 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1228 public boolean updateChannel(String group, String channel, State value) {
1229 return updateChannel(mkChannelId(group, channel), value, false);
1233 public boolean updateChannel(String channelId, State value, boolean force) {
1234 return !stopping && cache.updateChannel(channelId, value, force);
1238 public State getChannelValue(String group, String channel) {
1239 return cache.getValue(group, channel);
1243 public double getChannelDouble(String group, String channel) {
1244 State value = getChannelValue(group, channel);
1245 if (value != UnDefType.NULL) {
1246 if (value instanceof QuantityType) {
1247 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1249 if (value instanceof DecimalType) {
1250 return ((DecimalType) value).doubleValue();
1257 * Update Thing's channels according to available status information from the API
1259 * @param thingHandler
1262 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1263 if (channelsCreated) {
1264 return; // already done
1268 // Get subset of those channels that currently do not exist
1269 List<Channel> existingChannels = getThing().getChannels();
1270 for (Channel channel : existingChannels) {
1271 String id = channel.getUID().getId();
1272 if (dynChannels.containsKey(id)) {
1273 dynChannels.remove(id);
1277 if (!dynChannels.isEmpty()) {
1278 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1279 ThingBuilder thingBuilder = editThing();
1280 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1281 Channel c = channel.getValue();
1282 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1283 thingBuilder.withChannel(c);
1285 updateThing(thingBuilder.build());
1286 logger.debug("{}: Channel definitions updated", thingName);
1288 } catch (IllegalArgumentException e) {
1289 logger.debug("{}: Unable to update channel definitions", thingName, e);
1294 public boolean areChannelsCreated() {
1295 return channelsCreated;
1299 * Update thing properties with dynamic values
1301 * @param profile The device profile
1302 * @param status the /status result
1304 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1305 Map<String, Object> properties = fillDeviceProperties(profile);
1306 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1307 String deviceName = getString(profile.settings.name);
1308 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1309 properties.put(PROPERTY_DEV_GEN, "1");
1310 if (!deviceName.isEmpty()) {
1311 properties.put(PROPERTY_DEV_NAME, deviceName);
1313 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1315 // add status properties
1316 if (status.wifiSta != null) {
1317 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1319 if (status.update != null) {
1320 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1321 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1322 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1323 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1325 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1327 Map<String, String> thingProperties = new TreeMap<>();
1328 for (Map.Entry<String, Object> property : properties.entrySet()) {
1329 thingProperties.put(property.getKey(), (String) property.getValue());
1331 flushProperties(thingProperties);
1335 * Add one property to the Thing Properties
1337 * @param key Name of the property
1338 * @param value Value of the property
1341 public void updateProperties(String key, String value) {
1342 Map<String, String> thingProperties = editProperties();
1343 if (thingProperties.containsKey(key)) {
1344 thingProperties.replace(key, value);
1346 thingProperties.put(key, value);
1348 updateProperties(thingProperties);
1349 logger.trace("{}: Properties updated", thingName);
1352 public void flushProperties(Map<String, String> propertyUpdates) {
1353 Map<String, String> thingProperties = editProperties();
1354 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1355 if (thingProperties.containsKey(property.getKey())) {
1356 thingProperties.replace(property.getKey(), property.getValue());
1358 thingProperties.put(property.getKey(), property.getValue());
1361 updateProperties(thingProperties);
1365 * Get one property from the Thing Properties
1367 * @param key property name
1368 * @return property value or "" if property is not set
1371 public String getProperty(String key) {
1372 Map<String, String> thingProperties = getThing().getProperties();
1373 return getString(thingProperties.get(key));
1377 * Fill Thing Properties with device attributes
1379 * @param profile Property Map to full
1380 * @return a full property map
1382 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1383 Map<String, Object> properties = new TreeMap<>();
1384 properties.put(PROPERTY_VENDOR, VENDOR);
1385 if (profile.isInitialized()) {
1386 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1387 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1388 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1389 properties.put(PROPERTY_DEV_MODE, profile.mode);
1390 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1391 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1392 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1393 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1394 if (!profile.hwRev.isEmpty()) {
1395 properties.put(PROPERTY_HWREV, profile.hwRev);
1396 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1403 * Return device profile.
1405 * @param ForceRefresh true=force refresh before returning, false=return without
1407 * @return ShellyDeviceProfile instance
1408 * @throws ShellyApiException
1411 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1413 refreshSettings |= forceRefresh;
1414 if (refreshSettings) {
1415 profile = api.getDeviceProfile(thingType);
1416 if (!isThingOnline()) {
1417 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1421 refreshSettings = false;
1427 public ShellyDeviceProfile getProfile() {
1432 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1433 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1434 if (!options.isEmpty()) {
1435 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1441 protected ShellyDeviceProfile getDeviceProfile() {
1446 public void triggerChannel(String group, String channel, String payload) {
1447 String triggerCh = mkChannelId(group, channel);
1448 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1449 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1450 if (vibrationFilter == 0) {
1451 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1452 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1453 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1455 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1456 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1461 triggerChannel(triggerCh, payload);
1464 public void stop() {
1465 logger.debug("{}: Shutting down", thingName);
1466 ScheduledFuture<?> job = this.statusJob;
1470 logger.debug("{}: Shelly statusJob stopped", thingName);
1473 profile.initialized = false;
1477 * Shutdown thing, make sure background jobs are canceled
1480 public void dispose() {
1481 logger.debug("{}: Stopping Thing", thingName);
1488 * Device specific command handlers are overriding this method to do additional stuff
1490 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1494 public String getUID() {
1495 return getThing().getUID().getAsString();
1499 * Device specific handlers are overriding this method to do additional stuff
1501 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1506 public String getThingName() {
1511 public void resetStats() {
1513 stats = new ShellyDeviceStats();
1517 public ShellyDeviceStats getStats() {
1522 public ShellyApiInterface getApi() {
1527 public long getScheduledUpdates() {
1528 return scheduledUpdates;
1531 public Map<String, String> getStatsProp() {
1532 return stats.asProperties();
1536 public void triggerUpdateFromCoap() {
1537 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1538 requestUpdates(1, false);