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.ArrayList;
25 import java.util.Collection;
26 import java.util.List;
29 import java.util.TreeMap;
30 import java.util.concurrent.CopyOnWriteArrayList;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.eclipse.jetty.client.HttpClient;
37 import org.openhab.binding.shelly.internal.api.ShellyApiException;
38 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
39 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
40 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
44 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
45 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
47 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
48 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
49 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
50 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
51 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
52 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
53 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
54 import org.openhab.binding.shelly.internal.provider.ShellyStateDescriptionProvider;
55 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
56 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
57 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
58 import org.openhab.core.library.types.DecimalType;
59 import org.openhab.core.library.types.OnOffType;
60 import org.openhab.core.library.types.OpenClosedType;
61 import org.openhab.core.library.types.QuantityType;
62 import org.openhab.core.thing.Channel;
63 import org.openhab.core.thing.ChannelUID;
64 import org.openhab.core.thing.Thing;
65 import org.openhab.core.thing.ThingStatus;
66 import org.openhab.core.thing.ThingStatusDetail;
67 import org.openhab.core.thing.ThingTypeUID;
68 import org.openhab.core.thing.binding.BaseThingHandler;
69 import org.openhab.core.thing.binding.ThingHandlerService;
70 import org.openhab.core.thing.binding.builder.ThingBuilder;
71 import org.openhab.core.thing.type.ChannelTypeUID;
72 import org.openhab.core.types.Command;
73 import org.openhab.core.types.RefreshType;
74 import org.openhab.core.types.State;
75 import org.openhab.core.types.StateOption;
76 import org.openhab.core.types.UnDefType;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
82 * sent to one of the channels.
84 * @author Markus Michels - Initial contribution
87 public class ShellyBaseHandler extends BaseThingHandler
88 implements ShellyDeviceListener, ShellyManagerInterface, ShellyThingInterface {
89 private class OptionEntry {
90 public ChannelTypeUID uid;
94 public OptionEntry(ChannelTypeUID uid, String key, String value) {
101 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
102 protected final ShellyChannelDefinitions channelDefinitions;
103 private final CopyOnWriteArrayList<OptionEntry> stateOptions = new CopyOnWriteArrayList<>();
105 public String thingName = "";
106 public String thingType = "";
108 protected final ShellyApiInterface api;
109 private final HttpClient httpClient;
111 private ShellyBindingConfiguration bindingConfig;
112 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
113 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
114 protected ShellyDeviceStats stats = new ShellyDeviceStats();
115 private final Shelly1CoapHandler coap;
116 public boolean autoCoIoT = false;
118 private final ShellyTranslationProvider messages;
119 protected boolean stopping = false;
120 private boolean channelsCreated = false;
122 private long watchdog = now();
124 private @Nullable ScheduledFuture<?> statusJob;
125 public int scheduledUpdates = 0;
126 private int skipCount = UPDATE_SKIP_COUNT;
127 private int skipUpdate = 0;
128 private boolean refreshSettings = false;
130 // delay before enabling channel
131 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
132 private final ShellyChannelCache cache;
134 private String lastWakeupReason = "";
135 private int vibrationFilter = 0;
140 * @param thing The Thing object
141 * @param bindingConfig The binding configuration (beside thing
143 * @param coapServer coap server instance
144 * @param localIP local IP address from networkAddressService
145 * @param httpPort from httpService
147 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
148 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
149 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
152 this.thingName = getString(thing.getLabel());
153 this.messages = translationProvider;
154 this.cache = new ShellyChannelCache(this);
155 this.channelDefinitions = new ShellyChannelDefinitions(messages);
156 this.bindingConfig = bindingConfig;
157 this.config = getConfigAs(ShellyThingConfiguration.class);
159 this.httpClient = httpClient;
160 this.api = new Shelly1HttpApi(thingName, config, httpClient);
162 coap = new Shelly1CoapHandler(this, coapServer);
166 public boolean checkRepresentation(String key) {
167 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
168 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(thing.getUID().getAsString());
172 public Collection<Class<? extends ThingHandlerService>> getServices() {
173 return Set.of(ShellyStateDescriptionProvider.class);
176 public String getUID() {
177 return getThing().getUID().getAsString();
181 * Schedule asynchronous Thing initialization, register thing to event dispatcher
184 public void initialize() {
185 // start background initialization:
186 scheduler.schedule(() -> {
187 boolean start = true;
189 initializeThingConfig();
190 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
191 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
192 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
194 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
195 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
196 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
197 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
198 messages.get("status.unknown.initializing"));
199 start = initializeThing();
200 } catch (ShellyApiException e) {
201 ShellyApiResult res = e.getApiResult();
202 if (isAuthorizationFailed(res)) {
205 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
206 } catch (IllegalArgumentException e) {
207 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
209 // even this initialization failed we start the status update
210 // the updateJob will then try to auto-initialize the thing
211 // in this case the thing stays in status INITIALIZING
216 }, 2, TimeUnit.SECONDS);
220 public ShellyThingConfiguration getThingConfig() {
225 public HttpClient getHttpClient() {
230 * This routine is called every time the Thing configuration has been changed
233 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
234 super.handleConfigurationUpdate(configurationParameters);
235 logger.debug("{}: Thing config updated, re-initialize", thingName);
239 requestUpdates(1, true);// force re-initialization
243 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
244 * If the device is password protected and the credentials are missing or don't match the API access will throw an
245 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
246 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
247 * credentials are correct and the API access is initialized successful.
249 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
251 public boolean initializeThing() throws ShellyApiException {
252 // Init from thing type to have a basic profile, gets updated when device info is received from API
254 refreshSettings = false;
255 lastWakeupReason = "";
256 cache.setThingName(thingName);
259 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
260 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
261 if (config.deviceIp.isEmpty()) {
262 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
266 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
267 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
269 if (config.eventsCoIoT && !profile.alwaysOn) {
270 coap.start(thingName, config);
273 // Initialize API access, exceptions will be catched by initialize()
274 ShellySettingsDevice devInfo = api.getDeviceInfo();
275 if (getBool(devInfo.auth) && config.password.isEmpty()) {
276 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
279 if (config.serviceName.isEmpty()) {
280 config.serviceName = getString(profile.hostname).toLowerCase();
283 api.setConfig(thingName, config);
285 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
286 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
287 changeThingType(thingName, tmpPrf.mode);
288 return false; // force re-initialization
290 // Validate device mode
291 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
292 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
293 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
296 if (!getString(devInfo.coiot).isEmpty()) {
297 // New Shelly devices might use a different endpoint for the CoAP listener
298 tmpPrf.coiotEndpoint = devInfo.coiot;
300 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
301 // Sensor, usually 12h, H&T in USB mode 10min
302 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
303 ? tmpPrf.settings.sleepMode.period * 60 // minutes
304 : tmpPrf.settings.sleepMode.period * 3600; // hours
305 tmpPrf.updatePeriod += 60; // give 1min extra
306 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
307 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
308 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
309 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
311 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
314 tmpPrf.auth = devInfo.auth; // missing in /settings
315 tmpPrf.status = api.getStatus();
316 tmpPrf.updateFromStatus(tmpPrf.status);
319 String[] profileNames = tmpPrf.getValveProfileList(0);
320 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
321 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
322 clearStateOptions(channelId);
323 addStateOption(channelId, "0", "DISABLED");
324 for (int i = 0; i < profileNames.length; i++) {
325 addStateOption(channelId, "" + (i + 1), profileNames[i]);
329 showThingConfig(tmpPrf);
330 checkVersion(tmpPrf, tmpPrf.status);
332 if (config.eventsCoIoT && (tmpPrf.settings.coiot != null) && (tmpPrf.settings.coiot.enabled != null)) {
333 String devpeer = getString(tmpPrf.settings.coiot.peer);
334 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
335 if (!tmpPrf.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
337 api.setCoIoTPeer(ourpeer);
338 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
339 } catch (ShellyApiException e) {
340 logger.warn("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
342 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
343 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
347 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
348 config.eventsCoIoT = true;
349 config.eventsSwitch = false;
350 config.eventsButton = false;
351 config.eventsPush = false;
352 config.eventsRoller = false;
353 config.eventsSensorReport = false;
354 api.setConfig(thingName, config);
357 // All initialization done, so keep the profile and set Thing to ONLINE
358 fillDeviceStatus(tmpPrf.status, false);
359 postEvent(ALARM_TYPE_NONE, false);
360 api.setActionURLs(); // register event urls
361 if (config.eventsCoIoT) {
362 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
363 coap.start(thingName, config);
366 logger.debug("{}: Thing successfully initialized.", thingName);
369 updateProperties(tmpPrf, tmpPrf.status);
370 setThingOnline(); // if API call was successful the thing must be online
371 return true; // success
374 private void showThingConfig(ShellyDeviceProfile profile) {
375 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
376 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
378 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
379 logger.debug("{}: Device "
380 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
381 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
382 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
383 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
384 profile.isDW, profile.hasBattery,
385 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
386 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
387 profile.alwaysOn, profile.updatePeriod);
391 * Handle Channel Commands
394 public void handleCommand(ChannelUID channelUID, Command command) {
396 if (command instanceof RefreshType) {
397 String channelId = channelUID.getId();
398 State value = cache.getValue(channelId);
399 if (value != UnDefType.NULL) {
400 updateState(channelId, value);
405 if (!profile.isInitialized()) {
406 logger.debug("{}: {}", thingName, messages.get("command.init", command));
409 profile = getProfile(false);
412 boolean update = false;
413 switch (channelUID.getIdWithoutGroup()) {
414 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
415 logger.debug("{}: Send key {}", thingName, command);
416 api.sendIRKey(command.toString());
420 case CHANNEL_LED_STATUS_DISABLE:
421 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
422 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
424 case CHANNEL_LED_POWER_DISABLE:
425 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
426 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
429 case CHANNEL_SENSOR_SLEEPTIME:
430 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
431 int value = (int) getNumber(command);
432 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
434 api.setSleepTime(value);
436 case CHANNEL_CONTROL_SCHEDULE:
438 logger.debug("{}: {} Valve schedule/profile", thingName,
439 command == OnOffType.ON ? "Enable" : "Disable");
440 api.setValveProfile(0,
441 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
444 case CHANNEL_CONTROL_PROFILE:
445 logger.debug("{}: Select profile {}", thingName, command);
446 String cmd = command.toString();
447 int id = Integer.parseInt(cmd);
448 if (id < 0 || id > 5) {
449 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
451 api.setValveProfile(0, id);
454 case CHANNEL_CONTROL_MODE:
455 logger.debug("{}: Set mode to {}", thingName, command);
456 api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
458 case CHANNEL_CONTROL_SETTEMP:
459 logger.debug("{}: Set temperature to {}", thingName, command);
460 api.setValveTemperature(0, (int) getNumber(command));
462 case CHANNEL_CONTROL_POSITION:
463 logger.debug("{}: Set position to {}", thingName, command);
464 api.setValvePosition(0, getNumber(command));
466 case CHANNEL_CONTROL_BCONTROL:
467 logger.debug("{}: Set boost mode to {}", thingName, command);
468 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
470 case CHANNEL_CONTROL_BTIMER:
471 logger.debug("{}: Set boost timer to {}", thingName, command);
472 api.setValveBoostTime(0, (int) getNumber(command));
476 update = handleDeviceCommand(channelUID, command);
481 if (update && !autoCoIoT && !isUpdateScheduled()) {
482 requestUpdates(1, false);
484 } catch (ShellyApiException e) {
485 ShellyApiResult res = e.getApiResult();
486 if (isAuthorizationFailed(res)) {
489 if (res.isNotCalibrtated()) {
490 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
492 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
495 } catch (IllegalArgumentException e) {
496 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
500 private double getNumber(Command command) {
501 if (command instanceof QuantityType) {
502 return ((QuantityType<?>) command).doubleValue();
504 if (command instanceof DecimalType) {
505 return ((DecimalType) command).doubleValue();
507 if (command instanceof Number) {
508 return ((Number) command).doubleValue();
510 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
514 * Update device status and channels
516 protected void refreshStatus() {
518 boolean updated = false;
520 if (vibrationFilter > 0) {
522 logger.debug("{}: Vibration events are absorbed for {}Â more seconds", thingName,
523 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
527 ThingStatus thingStatus = getThing().getStatus();
528 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
529 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
530 || (thingStatus == ThingStatus.UNKNOWN)) {
531 logger.debug("{}: Status update triggered thing initialization", thingName);
532 initializeThing(); // may fire an exception if initialization failed
534 // Get profile, if refreshSettings == true reload settings from device
535 ShellySettingsStatus status = api.getStatus();
536 boolean restarted = checkRestarted(status);
537 profile = getProfile(refreshSettings || restarted);
538 profile.status = status;
539 profile.updateFromStatus(status);
541 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
543 postEvent(ALARM_TYPE_RESTARTED, true);
546 // If status update was successful the thing must be online
549 // map status to channels
550 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
551 updated |= this.updateDeviceStatus(status);
552 updated |= ShellyComponents.updateDeviceStatus(this, status);
553 fillDeviceStatus(status, updated);
554 updated |= updateInputs(status);
555 updated |= updateMeters(this, status);
556 updated |= updateSensors(this, status);
558 // All channels must be created after the first cycle
559 channelsCreated = true;
561 } catch (ShellyApiException e) {
562 // http call failed: go offline except for battery devices, which might be in
563 // sleep mode. Once the next update is successful the device goes back online
565 ShellyApiResult res = e.getApiResult();
566 if (isWatchdogStarted()) {
567 if (!isWatchdogExpired()) {
568 logger.debug("{}: Ignore API Timeout, retry later", thingName);
570 if (isThingOnline()) {
571 status = "offline.status-error-watchdog";
574 } else if (res.isHttpAccessUnauthorized()) {
575 status = "offline.conf-error-access-denied";
576 } else if (e.isJSONException()) {
577 status = "offline.status-error-unexpected-api-result";
578 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
579 } else if (res.isHttpTimeout()) {
580 // Watchdog not started, e.g. device in sleep mode
581 if (isThingOnline()) { // ignore when already offline
582 status = "offline.status-error-watchdog";
585 status = "offline.status-error-unexpected-api-result";
586 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
589 if (!status.isEmpty()) {
590 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
592 } catch (NullPointerException | IllegalArgumentException e) {
593 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
595 if (scheduledUpdates > 0) {
597 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
598 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
599 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
600 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
607 public ThingStatus getThingStatus() {
608 return getThing().getStatus();
612 public ThingStatusDetail getThingStatusDetail() {
613 return getThing().getStatusInfo().getStatusDetail();
617 public boolean isThingOnline() {
618 return getThing().getStatus() == ThingStatus.ONLINE;
621 public boolean isThingOffline() {
622 return getThing().getStatus() == ThingStatus.OFFLINE;
626 public void setThingOnline() {
628 logger.debug("{}: Thing should go ONLINE, but handler is shutting down, ignore!", thingName);
631 if (!isThingOnline()) {
632 updateStatus(ThingStatus.ONLINE);
634 // request 3 updates in a row (during the first 2+3*3 sec)
635 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
638 // Restart watchdog when status update was successful (no exception)
643 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
644 String message = messages.get(messageKey);
646 logger.debug("{}: Thing should go OFFLINE with status {}, but handler is shutting down -> ignore",
651 if (!isThingOffline()) {
652 updateStatus(ThingStatus.OFFLINE, detail, message);
654 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
659 public void restartWatchdog() {
661 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
662 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
665 private boolean isWatchdogExpired() {
666 long delta = now() - watchdog;
667 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
668 stats.remainingWatchdog = delta;
674 private boolean isWatchdogStarted() {
679 public void reinitializeThing() {
680 logger.debug("{}: Re-Initialize Thing", thingName);
682 logger.debug("{}: Handler is shutting down, ignore", thingName);
685 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
686 messages.get("offline.status-error-restarted"));
687 requestUpdates(0, true);
691 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
694 // Update uptime and WiFi, internal temp
695 ShellyComponents.updateDeviceStatus(this, status);
696 stats.wifiRssi = status.wifiSta.rssi;
698 if (api.isInitialized()) {
699 stats.timeoutErrors = api.getTimeoutErrors();
700 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
702 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
704 // Check various device indicators like overheating
705 if (checkRestarted(status)) {
706 // Force re-initialization on next status update
708 } else if (getBool(status.overtemperature)) {
709 alarm = ALARM_TYPE_OVERTEMP;
710 } else if (getBool(status.overload)) {
711 alarm = ALARM_TYPE_OVERLOAD;
712 } else if (getBool(status.loaderror)) {
713 alarm = ALARM_TYPE_LOADERR;
715 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
716 if (internalTemp != UnDefType.NULL) {
717 int temp = ((Number) internalTemp).intValue();
718 if (temp > stats.maxInternalTemp) {
719 stats.maxInternalTemp = temp;
723 if (status.uptime != null) {
724 stats.lastUptime = getLong(status.uptime);
727 stats.coiotMessages = coap.getMessageCount();
728 stats.coiotErrors = coap.getErrorCount();
730 if (!alarm.isEmpty()) {
731 postEvent(alarm, false);
736 * Check if device has restarted and needs a new Thing initialization
738 * @return true: restart detected
741 private boolean checkRestarted(ShellySettingsStatus status) {
742 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
743 && (status.uptime != null && status.uptime < stats.lastUptime
744 || !profile.status.update.oldVersion.isEmpty()
745 && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
746 updateProperties(profile, status);
753 * Save alarm to the lastAlarm channel
755 * @param alarm Alarm Message
758 public void postEvent(String event, boolean force) {
759 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
760 State value = cache.getValue(channelId);
761 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
763 if (force || !lastAlarm.equals(event)
764 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
765 switch (event.toUpperCase()) {
768 case SHELLY_WAKEUPT_SENSOR:
769 case SHELLY_WAKEUPT_PERIODIC:
770 case SHELLY_WAKEUPT_BUTTON:
771 case SHELLY_WAKEUPT_POWERON:
772 case SHELLY_WAKEUPT_EXT_POWER:
773 case SHELLY_WAKEUPT_UNKNOWN:
774 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
775 case ALARM_TYPE_NONE:
778 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
779 triggerChannel(channelId, event);
780 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
781 stats.lastAlarm = event;
782 stats.lastAlarmTs = now();
789 * Callback for device events
791 * @param deviceName device receiving the event
792 * @param parameters parameters from the event URL
793 * @param data the HTML input data
794 * @return true if event was processed
797 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
798 Map<String, String> parameters) {
799 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
800 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
802 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
803 if (!profile.isInitialized()) {
804 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
805 requestUpdates(1, true);
807 String group = profile.getControlGroup(idx);
808 if (group.isEmpty()) {
809 logger.debug("{}: Unsupported event class: {}", thingName, type);
813 // map some of the events to system defined button triggers
817 String parmType = getString(parameters.get("type"));
818 String event = !parmType.isEmpty() ? parmType : type;
819 boolean isButton = profile.inButtonMode(idx - 1);
821 case SHELLY_EVENT_SHORTPUSH:
822 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
823 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
824 case SHELLY_EVENT_LONGPUSH:
826 triggerButton(group, idx, mapButtonEvent(event));
827 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
828 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
830 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
834 case SHELLY_EVENT_BTN_ON:
835 case SHELLY_EVENT_BTN_OFF:
836 if (profile.isRGBW2) {
837 // RGBW2 has only one input, so not per channel
838 group = CHANNEL_GROUP_LIGHT_CONTROL;
840 onoff = CHANNEL_INPUT;
842 case SHELLY_EVENT_BTN1_ON:
843 case SHELLY_EVENT_BTN1_OFF:
844 onoff = CHANNEL_INPUT1;
846 case SHELLY_EVENT_BTN2_ON:
847 case SHELLY_EVENT_BTN2_OFF:
848 onoff = CHANNEL_INPUT2;
850 case SHELLY_EVENT_OUT_ON:
851 case SHELLY_EVENT_OUT_OFF:
852 onoff = CHANNEL_OUTPUT;
854 case SHELLY_EVENT_ROLLER_OPEN:
855 case SHELLY_EVENT_ROLLER_CLOSE:
856 case SHELLY_EVENT_ROLLER_STOP:
857 channel = CHANNEL_EVENT_TRIGGER;
860 case SHELLY_EVENT_SENSORREPORT:
861 // process sensor with next refresh
863 case SHELLY_EVENT_TEMP_OVER: // DW2
864 case SHELLY_EVENT_TEMP_UNDER:
865 channel = CHANNEL_EVENT_TRIGGER;
868 case SHELLY_EVENT_FLOOD_DETECTED:
869 case SHELLY_EVENT_FLOOD_GONE:
870 updateChannel(group, CHANNEL_SENSOR_FLOOD,
871 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
874 case SHELLY_EVENT_CLOSE: // DW 1.7
875 case SHELLY_EVENT_OPEN: // DW 1.7
876 updateChannel(group, CHANNEL_SENSOR_STATE,
877 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
878 : OpenClosedType.CLOSED);
881 case SHELLY_EVENT_DARK: // DW 1.7
882 case SHELLY_EVENT_TWILIGHT: // DW 1.7
883 case SHELLY_EVENT_BRIGHT: // DW 1.7
884 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
887 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
888 case SHELLY_EVENT_ALARM_HEAVY:
889 case SHELLY_EVENT_ALARM_OFF:
890 case SHELLY_EVENT_VIBRATION: // DW2
891 channel = CHANNEL_SENSOR_ALARM_STATE;
892 payload = event.toUpperCase();
896 // trigger will be provided by input/output channel or sensor channels
899 if (!onoff.isEmpty()) {
900 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
902 if (!payload.isEmpty()) {
903 // Pass event to trigger channel
904 payload = payload.toUpperCase();
905 logger.debug("{}: Post event {}", thingName, payload);
906 triggerChannel(mkChannelId(group, channel), payload);
910 // request update on next interval (2x for non-battery devices)
912 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
919 * Initialize the binding's thing configuration, calc update counts
921 protected void initializeThingConfig() {
922 thingType = getThing().getThingTypeUID().getId();
923 final Map<String, String> properties = getThing().getProperties();
924 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
925 if (thingName.isEmpty()) {
926 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
927 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
930 config = getConfigAs(ShellyThingConfiguration.class);
931 if (config.deviceIp.isEmpty()) {
932 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
936 InetAddress addr = InetAddress.getByName(config.deviceIp);
937 String saddr = addr.getHostAddress();
938 if (!config.deviceIp.equals(saddr)) {
939 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
940 config.deviceIp = saddr;
942 } catch (UnknownHostException e) {
943 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
946 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
947 config.localIp = bindingConfig.localIP;
948 config.localPort = String.valueOf(bindingConfig.httpPort);
949 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
950 config.userId = bindingConfig.defaultUserId;
951 config.password = bindingConfig.defaultPassword;
952 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
954 if (config.updateInterval == 0) {
955 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
957 if (config.updateInterval < UPDATE_MIN_DELAY) {
958 config.updateInterval = UPDATE_MIN_DELAY;
961 // Try to get updatePeriod from properties
962 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
963 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
964 // initialized successfully by the REST call.
965 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
966 if (!lastPeriod.isEmpty()) {
967 int period = Integer.parseInt(lastPeriod);
969 profile.updatePeriod = period;
973 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
974 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
977 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
979 ShellyVersionDTO version = new ShellyVersionDTO();
980 if (version.checkBeta(getString(prf.fwVersion))) {
981 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
983 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
984 logger.warn("{}: {}", prf.hostname,
985 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
988 if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
989 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
990 if (!config.eventsCoIoT) {
991 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
995 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
996 logger.info("{}: {}", thingName,
997 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
999 } catch (NullPointerException e) { // could be inconsistant format of beta version
1000 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1005 * Checks the http response for authorization error.
1006 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1007 * case the thing type shelly-unknown is set.
1009 * @param response exception details including the http respone
1010 * @return true if the authorization failed
1012 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1013 if (result.isHttpAccessUnauthorized()) {
1014 // If the device is password protected the API doesn't provide settings to the device settings
1015 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1022 * Change type of this thing.
1024 * @param thingType thing type acc. to the xml definition
1025 * @param mode Device mode (e.g. relay, roller)
1027 protected void changeThingType(String thingType, String mode) {
1028 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1029 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1030 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1031 Map<String, String> properties = editProperties();
1032 properties.replace(PROPERTY_DEV_TYPE, thingType);
1033 properties.replace(PROPERTY_DEV_MODE, mode);
1034 updateProperties(properties);
1035 changeThingType(thingTypeUID, getConfig());
1040 public void thingUpdated(Thing thing) {
1041 logger.debug("{}: Channel definitions updated.", thingName);
1042 super.thingUpdated(thing);
1046 * Start the background updates
1048 protected void startUpdateJob() {
1049 ScheduledFuture<?> statusJob = this.statusJob;
1050 if ((statusJob == null) || statusJob.isCancelled()) {
1051 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1053 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1054 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1059 * Flag the status job to do an exceptional update (something happened) rather
1060 * than waiting until the next regular poll
1062 * @param requestCount number of polls to execute
1063 * @param refreshSettings true=force a /settings query
1064 * @return true=Update schedule, false=skipped (too many updates already
1068 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1069 this.refreshSettings |= refreshSettings;
1070 if (refreshSettings) {
1071 if (requestCount == 0) {
1072 logger.debug("{}: Request settings refresh", thingName);
1074 scheduledUpdates = 1;
1077 if (scheduledUpdates < 10) { // < 30s
1078 scheduledUpdates += requestCount;
1084 public boolean isUpdateScheduled() {
1085 return scheduledUpdates > 0;
1089 * Map input states to channels
1091 * @param groupName Channel Group (relay / relay1...)
1093 * @param status Shelly device status
1094 * @return true: one or more inputs were updated
1097 public boolean updateInputs(ShellySettingsStatus status) {
1098 boolean updated = false;
1100 if (status.inputs != null) {
1102 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
1103 for (ShellyInputState input : status.inputs) {
1104 String group = profile.getInputGroup(idx);
1105 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1107 if (!areChannelsCreated()) {
1108 updateChannelDefinitions(
1109 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
1112 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1113 if (input.event != null) {
1114 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1115 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1120 if (status.input != null) {
1121 // RGBW2: a single int rather than an array
1122 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1123 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1130 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1131 boolean changed = false;
1132 if (valueArray != null && !valueArray.isEmpty()) {
1133 String reason = getString((String) valueArray.get(0));
1134 String newVal = valueArray.toString();
1135 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1136 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1138 postEvent(reason.toUpperCase(), true);
1140 lastWakeupReason = newVal;
1146 public void triggerButton(String group, int idx, String value) {
1147 String trigger = mapButtonEvent(value);
1148 if (trigger.isEmpty()) {
1152 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1153 triggerChannel(group,
1154 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1156 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1157 if (profile.alwaysOn) {
1158 // refresh status of the input channel
1159 requestUpdates(1, false);
1164 public void publishState(String channelId, State value) {
1165 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1166 if (!stopping && isLinked(id)) {
1167 updateState(id, value);
1168 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1173 public boolean updateChannel(String group, String channel, State value) {
1174 return updateChannel(mkChannelId(group, channel), value, false);
1178 public boolean updateChannel(String channelId, State value, boolean force) {
1179 return !stopping && cache.updateChannel(channelId, value, force);
1183 public State getChannelValue(String group, String channel) {
1184 return cache.getValue(group, channel);
1188 public double getChannelDouble(String group, String channel) {
1189 State value = getChannelValue(group, channel);
1190 if (value != UnDefType.NULL) {
1191 if (value instanceof QuantityType) {
1192 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1194 if (value instanceof DecimalType) {
1195 return ((DecimalType) value).doubleValue();
1202 * Update Thing's channels according to available status information from the API
1204 * @param thingHandler
1207 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1208 if (channelsCreated) {
1209 return; // already done
1213 // Get subset of those channels that currently do not exist
1214 List<Channel> existingChannels = getThing().getChannels();
1215 for (Channel channel : existingChannels) {
1216 String id = channel.getUID().getId();
1217 if (dynChannels.containsKey(id)) {
1218 dynChannels.remove(id);
1222 if (!dynChannels.isEmpty()) {
1223 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1224 ThingBuilder thingBuilder = editThing();
1225 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1226 Channel c = channel.getValue();
1227 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1228 thingBuilder.withChannel(c);
1230 updateThing(thingBuilder.build());
1231 logger.debug("{}: Channel definitions updated", thingName);
1233 } catch (IllegalArgumentException e) {
1234 logger.debug("{}: Unable to update channel definitions", thingName, e);
1239 public boolean areChannelsCreated() {
1240 return channelsCreated;
1244 * Update thing properties with dynamic values
1246 * @param profile The device profile
1247 * @param status the /status result
1249 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1250 Map<String, Object> properties = fillDeviceProperties(profile);
1251 String deviceName = getString(profile.settings.name);
1252 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1253 properties.put(PROPERTY_DEV_GEN, "1");
1254 if (!deviceName.isEmpty()) {
1255 properties.put(PROPERTY_DEV_NAME, deviceName);
1258 // add status properties
1259 if (status.wifiSta != null) {
1260 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1262 if (status.update != null) {
1263 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1264 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1265 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1266 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1268 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1270 Map<String, String> thingProperties = new TreeMap<>();
1271 for (Map.Entry<String, Object> property : properties.entrySet()) {
1272 thingProperties.put(property.getKey(), (String) property.getValue());
1274 flushProperties(thingProperties);
1278 * Add one property to the Thing Properties
1280 * @param key Name of the property
1281 * @param value Value of the property
1284 public void updateProperties(String key, String value) {
1285 Map<String, String> thingProperties = editProperties();
1286 if (thingProperties.containsKey(key)) {
1287 thingProperties.replace(key, value);
1289 thingProperties.put(key, value);
1291 updateProperties(thingProperties);
1292 logger.trace("{}: Properties updated", thingName);
1295 public void flushProperties(Map<String, String> propertyUpdates) {
1296 Map<String, String> thingProperties = editProperties();
1297 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1298 if (thingProperties.containsKey(property.getKey())) {
1299 thingProperties.replace(property.getKey(), property.getValue());
1301 thingProperties.put(property.getKey(), property.getValue());
1304 updateProperties(thingProperties);
1308 * Get one property from the Thing Properties
1310 * @param key property name
1311 * @return property value or "" if property is not set
1314 public String getProperty(String key) {
1315 Map<String, String> thingProperties = getThing().getProperties();
1316 return getString(thingProperties.get(key));
1320 * Fill Thing Properties with device attributes
1322 * @param profile Property Map to full
1323 * @return a full property map
1325 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1326 Map<String, Object> properties = new TreeMap<>();
1327 properties.put(PROPERTY_VENDOR, VENDOR);
1328 if (profile.isInitialized()) {
1329 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1330 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1331 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1332 properties.put(PROPERTY_DEV_MODE, profile.mode);
1333 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1334 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1335 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1336 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1337 if (!profile.hwRev.isEmpty()) {
1338 properties.put(PROPERTY_HWREV, profile.hwRev);
1339 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1346 * Return device profile.
1348 * @param ForceRefresh true=force refresh before returning, false=return without
1350 * @return ShellyDeviceProfile instance
1351 * @throws ShellyApiException
1354 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1356 refreshSettings |= forceRefresh;
1357 if (refreshSettings) {
1358 profile = api.getDeviceProfile(thingType);
1359 if (!isThingOnline()) {
1360 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1364 refreshSettings = false;
1370 public ShellyDeviceProfile getProfile() {
1375 public List<StateOption> getStateOptions(ChannelTypeUID uid) {
1376 List<StateOption> options = new ArrayList<>();
1377 for (OptionEntry oe : stateOptions) {
1378 if (oe.uid.equals(uid)) {
1379 options.add(new StateOption(oe.key, oe.value));
1383 if (!options.isEmpty()) {
1384 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1389 private void addStateOption(String channelId, String key, String value) {
1390 ChannelTypeUID uid = channelDefinitions.getChannelTypeUID(channelId);
1391 stateOptions.addIfAbsent(new OptionEntry(uid, key, value));
1394 private void clearStateOptions(String channelId) {
1395 ChannelTypeUID uid = channelDefinitions.getChannelTypeUID(channelId);
1396 for (OptionEntry oe : stateOptions) {
1397 if (oe.uid.equals(uid)) {
1398 stateOptions.remove(oe);
1403 protected ShellyDeviceProfile getDeviceProfile() {
1408 public void triggerChannel(String group, String channel, String payload) {
1409 String triggerCh = mkChannelId(group, channel);
1410 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1411 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1412 if (vibrationFilter == 0) {
1413 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1414 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1415 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1417 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1418 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1423 triggerChannel(triggerCh, payload);
1426 public void stop() {
1427 logger.debug("{}: Shutting down", thingName);
1428 ScheduledFuture<?> job = this.statusJob;
1432 logger.debug("{}: Shelly statusJob stopped", thingName);
1438 profile.initialized = false;
1442 * Shutdown thing, make sure background jobs are canceled
1445 public void dispose() {
1452 * Device specific command handlers are overriding this method to do additional stuff
1454 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1459 * Device specific handlers are overriding this method to do additional stuff
1461 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1466 public String getThingName() {
1471 public void resetStats() {
1473 stats = new ShellyDeviceStats();
1477 public ShellyDeviceStats getStats() {
1482 public ShellyApiInterface getApi() {
1486 public Map<String, String> getStatsProp() {
1487 return stats.asProperties();
1491 public long getScheduledUpdates() {
1492 return scheduledUpdates;
1495 public String checkForUpdate() {
1497 ShellyOtaCheckResult result = api.checkForUpdate();
1498 return result.status;
1499 } catch (ShellyApiException e) {
1505 public void triggerUpdateFromCoap() {
1506 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1507 requestUpdates(1, false);