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.ShellyInputState;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
43 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
46 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
47 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
48 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
49 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
50 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
51 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
52 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
53 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
54 import org.openhab.core.library.types.DecimalType;
55 import org.openhab.core.library.types.OnOffType;
56 import org.openhab.core.library.types.OpenClosedType;
57 import org.openhab.core.library.types.QuantityType;
58 import org.openhab.core.thing.Channel;
59 import org.openhab.core.thing.ChannelUID;
60 import org.openhab.core.thing.Thing;
61 import org.openhab.core.thing.ThingStatus;
62 import org.openhab.core.thing.ThingStatusDetail;
63 import org.openhab.core.thing.ThingTypeUID;
64 import org.openhab.core.thing.binding.BaseThingHandler;
65 import org.openhab.core.thing.binding.builder.ThingBuilder;
66 import org.openhab.core.types.Command;
67 import org.openhab.core.types.RefreshType;
68 import org.openhab.core.types.State;
69 import org.openhab.core.types.UnDefType;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
75 * sent to one of the channels.
77 * @author Markus Michels - Initial contribution
80 public class ShellyBaseHandler extends BaseThingHandler
81 implements ShellyDeviceListener, ShellyManagerInterface, ShellyThingInterface {
82 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
83 protected final ShellyChannelDefinitions channelDefinitions;
85 public String thingName = "";
86 public String thingType = "";
88 protected final ShellyApiInterface api;
89 private final HttpClient httpClient;
91 private ShellyBindingConfiguration bindingConfig;
92 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
93 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
94 protected ShellyDeviceStats stats = new ShellyDeviceStats();
95 private final Shelly1CoapHandler coap;
96 public boolean autoCoIoT = false;
98 private final ShellyTranslationProvider messages;
99 protected boolean stopping = false;
100 private boolean channelsCreated = false;
102 private long watchdog = now();
104 private @Nullable ScheduledFuture<?> statusJob;
105 public int scheduledUpdates = 0;
106 private int skipCount = UPDATE_SKIP_COUNT;
107 private int skipUpdate = 0;
108 private boolean refreshSettings = false;
110 // delay before enabling channel
111 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
112 private final ShellyChannelCache cache;
114 private String localIP = "";
115 private String localPort = "";
117 private String lastWakeupReason = "";
118 private int vibrationFilter = 0;
123 * @param thing The Thing object
124 * @param bindingConfig The binding configuration (beside thing
126 * @param coapServer coap server instance
127 * @param localIP local IP address from networkAddressService
128 * @param httpPort from httpService
130 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
131 final ShellyBindingConfiguration bindingConfig, final Shelly1CoapServer coapServer, final String localIP,
132 int httpPort, final HttpClient httpClient) {
135 this.thingName = getString(thing.getLabel());
136 this.messages = translationProvider;
137 this.cache = new ShellyChannelCache(this);
138 this.channelDefinitions = new ShellyChannelDefinitions(messages);
139 this.bindingConfig = bindingConfig;
140 this.config = getConfigAs(ShellyThingConfiguration.class);
142 this.httpClient = httpClient;
143 this.localIP = localIP;
144 this.localPort = String.valueOf(httpPort);
145 this.api = new Shelly1HttpApi(thingName, config, httpClient);
147 coap = new Shelly1CoapHandler(this, coapServer);
151 public boolean checkRepresentation(String key) {
152 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
153 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(thing.getUID().getAsString());
156 public String getUID() {
157 return getThing().getUID().getAsString();
161 * Schedule asynchronous Thing initialization, register thing to event dispatcher
164 public void initialize() {
165 // start background initialization:
166 scheduler.schedule(() -> {
167 boolean start = true;
169 initializeThingConfig();
170 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
171 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
172 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
174 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
175 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
176 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
177 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
178 messages.get("status.unknown.initializing"));
179 start = initializeThing();
180 } catch (ShellyApiException e) {
181 ShellyApiResult res = e.getApiResult();
182 if (isAuthorizationFailed(res)) {
185 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
186 } catch (IllegalArgumentException e) {
187 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
189 // even this initialization failed we start the status update
190 // the updateJob will then try to auto-initialize the thing
191 // in this case the thing stays in status INITIALIZING
196 }, 2, TimeUnit.SECONDS);
200 public ShellyThingConfiguration getThingConfig() {
205 public HttpClient getHttpClient() {
210 * This routine is called every time the Thing configuration has been changed
213 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
214 super.handleConfigurationUpdate(configurationParameters);
215 logger.debug("{}: Thing config updated, re-initialize", thingName);
217 requestUpdates(1, true);// force re-initialization
221 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
222 * If the device is password protected and the credentials are missing or don't match the API access will throw an
223 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
224 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
225 * credentials are correct and the API access is initialized successful.
227 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
229 public boolean initializeThing() throws ShellyApiException {
230 // Init from thing type to have a basic profile, gets updated when device info is received from API
232 refreshSettings = false;
233 lastWakeupReason = "";
234 profile.initFromThingType(thingType);
235 api.setConfig(thingName, config);
236 cache.setThingName(thingName);
239 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
240 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
241 if (config.deviceIp.isEmpty()) {
242 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
246 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
247 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
249 if (config.eventsCoIoT && !profile.alwaysOn) {
250 coap.start(thingName, config);
253 // Initialize API access, exceptions will be catched by initialize()
254 ShellySettingsDevice devInfo = api.getDeviceInfo();
255 if (getBool(devInfo.auth) && config.password.isEmpty()) {
256 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
259 if (config.serviceName.isEmpty()) {
260 config.serviceName = getString(profile.hostname).toLowerCase();
263 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
264 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
265 changeThingType(thingName, tmpPrf.mode);
266 return false; // force re-initialization
268 // Validate device mode
269 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
270 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
271 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
274 if (!getString(devInfo.coiot).isEmpty()) {
275 // New Shelly devices might use a different endpoint for the CoAP listener
276 tmpPrf.coiotEndpoint = devInfo.coiot;
278 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
279 // Sensor, usually 12h, H&T in USB mode 10min
280 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
281 ? tmpPrf.settings.sleepMode.period * 60 // minutes
282 : tmpPrf.settings.sleepMode.period * 3600; // hours
283 tmpPrf.updatePeriod += 60; // give 1min extra
284 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
285 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
286 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
287 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
289 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
292 tmpPrf.auth = devInfo.auth; // missing in /settings
293 tmpPrf.status = api.getStatus();
294 tmpPrf.updateFromStatus(tmpPrf.status);
296 showThingConfig(tmpPrf);
297 // update thing properties
298 checkVersion(tmpPrf, tmpPrf.status);
300 if (config.eventsCoIoT && (tmpPrf.settings.coiot != null) && (tmpPrf.settings.coiot.enabled != null)) {
301 String devpeer = getString(tmpPrf.settings.coiot.peer);
302 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
303 if (!tmpPrf.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
305 api.setCoIoTPeer(ourpeer);
306 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
307 } catch (ShellyApiException e) {
308 logger.warn("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
310 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
311 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
315 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
316 config.eventsCoIoT = true;
317 config.eventsSwitch = false;
318 config.eventsButton = false;
319 config.eventsPush = false;
320 config.eventsRoller = false;
321 config.eventsSensorReport = false;
322 api.setConfig(thingName, config);
325 // All initialization done, so keep the profile and set Thing to ONLINE
326 fillDeviceStatus(tmpPrf.status, false);
327 postEvent(ALARM_TYPE_NONE, false);
328 api.setActionURLs(); // register event urls
329 if (config.eventsCoIoT) {
330 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
331 coap.start(thingName, config);
334 logger.debug("{}: Thing successfully initialized.", thingName);
337 updateProperties(tmpPrf, tmpPrf.status);
338 setThingOnline(); // if API call was successful the thing must be online
339 return true; // success
342 private void showThingConfig(ShellyDeviceProfile profile) {
343 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
344 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
346 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
347 logger.debug("{}: Device "
348 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
349 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
350 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
351 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
352 profile.isDW, profile.hasBattery,
353 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
354 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
355 profile.alwaysOn, profile.updatePeriod);
359 * Handle Channel Commands
362 public void handleCommand(ChannelUID channelUID, Command command) {
364 if (command instanceof RefreshType) {
365 String channelId = channelUID.getId();
366 State value = cache.getValue(channelId);
367 if (value != UnDefType.NULL) {
368 updateState(channelId, value);
373 if (!profile.isInitialized()) {
374 logger.debug("{}: {}", thingName, messages.get("command.init", command));
377 profile = getProfile(false);
380 boolean update = false;
381 switch (channelUID.getIdWithoutGroup()) {
382 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
383 logger.debug("{}: Send key {}", thingName, command);
384 api.sendIRKey(command.toString());
388 case CHANNEL_LED_STATUS_DISABLE:
389 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
390 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
392 case CHANNEL_LED_POWER_DISABLE:
393 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
394 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
397 case CHANNEL_SENSOR_SLEEPTIME:
398 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
399 int value = (int) getNumber(command);
400 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
402 api.setSleepTime(value);
404 case CHANNEL_CONTROL_SCHEDULE:
406 logger.debug("{}: {} Valve schedule/profile", thingName,
407 command == OnOffType.ON ? "Enable" : "Disable");
408 api.setValveProfile(0,
409 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
412 case CHANNEL_CONTROL_PROFILE:
413 logger.debug("{}: Select profile {}", thingName, command);
415 if (command instanceof Number) {
416 id = (int) getNumber(command);
418 String cmd = command.toString();
419 if (isDigit(cmd.charAt(0))) {
420 id = Integer.parseInt(cmd);
421 } else if (cmd.equalsIgnoreCase("DISABLED")) {
423 } else if (profile.settings.thermostats != null) {
424 ShellyThermnostat t = profile.settings.thermostats.get(0);
425 for (int i = 0; i < t.profileNames.length; i++) {
426 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
432 if (id < 0 || id > 5) {
433 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
435 api.setValveProfile(0, id);
438 case CHANNEL_CONTROL_MODE:
439 logger.debug("{}: Set mode to {}", thingName, command);
440 api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
442 case CHANNEL_CONTROL_SETTEMP:
443 logger.debug("{}: Set temperature to {}", thingName, command);
444 api.setValveTemperature(0, (int) getNumber(command));
446 case CHANNEL_CONTROL_POSITION:
447 logger.debug("{}: Set position to {}", thingName, command);
448 api.setValvePosition(0, getNumber(command));
450 case CHANNEL_CONTROL_BCONTROL:
451 logger.debug("{}: Set boost mode to {}", thingName, command);
452 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
454 case CHANNEL_CONTROL_BTIMER:
455 logger.debug("{}: Set boost timer to {}", thingName, command);
456 api.setValveBoostTime(0, (int) getNumber(command));
460 update = handleDeviceCommand(channelUID, command);
465 if (update && !autoCoIoT && !isUpdateScheduled()) {
466 logger.debug("{}: Command processed, request status update", thingName);
467 requestUpdates(1, false);
469 } catch (ShellyApiException e) {
470 ShellyApiResult res = e.getApiResult();
471 if (isAuthorizationFailed(res)) {
474 if (res.isNotCalibrtated()) {
475 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
477 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
480 } catch (IllegalArgumentException e) {
481 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
485 private double getNumber(Command command) {
486 if (command instanceof QuantityType) {
487 return ((QuantityType<?>) command).doubleValue();
489 if (command instanceof DecimalType) {
490 return ((DecimalType) command).doubleValue();
492 if (command instanceof Number) {
493 return ((Number) command).doubleValue();
495 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
499 * Update device status and channels
501 protected void refreshStatus() {
503 boolean updated = false;
505 if (vibrationFilter > 0) {
507 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
508 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
512 ThingStatus thingStatus = getThing().getStatus();
513 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
514 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
515 || (thingStatus == ThingStatus.UNKNOWN)) {
516 logger.debug("{}: Status update triggered thing initialization", thingName);
517 initializeThing(); // may fire an exception if initialization failed
519 // Get profile, if refreshSettings == true reload settings from device
520 logger.trace("{}: Updating status (scheduledUpdates={}, refreshSettings={})", thingName,
521 scheduledUpdates, refreshSettings);
522 ShellySettingsStatus status = api.getStatus();
523 boolean restarted = checkRestarted(status);
524 profile = getProfile(refreshSettings || restarted);
525 profile.status = status;
526 profile.updateFromStatus(status);
528 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
530 postEvent(ALARM_TYPE_RESTARTED, true);
533 // If status update was successful the thing must be online
536 // map status to channels
537 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
538 updated |= this.updateDeviceStatus(status);
539 updated |= ShellyComponents.updateDeviceStatus(this, status);
540 fillDeviceStatus(status, updated);
541 updated |= updateInputs(status);
542 updated |= updateMeters(this, status);
543 updated |= updateSensors(this, status);
545 // All channels must be created after the first cycle
546 channelsCreated = true;
548 } catch (ShellyApiException e) {
549 // http call failed: go offline except for battery devices, which might be in
550 // sleep mode. Once the next update is successful the device goes back online
552 ShellyApiResult res = e.getApiResult();
553 if (isWatchdogStarted()) {
554 if (!isWatchdogExpired()) {
555 logger.debug("{}: Ignore API Timeout, retry later", thingName);
557 if (isThingOnline()) {
558 status = "offline.status-error-watchdog";
561 } else if (res.isHttpAccessUnauthorized()) {
562 status = "offline.conf-error-access-denied";
563 } else if (e.isJSONException()) {
564 status = "offline.status-error-unexpected-api-result";
565 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
566 } else if (res.isHttpTimeout()) {
567 // Watchdog not started, e.g. device in sleep mode
568 if (isThingOnline()) { // ignore when already offline
569 status = "offline.status-error-watchdog";
572 status = "offline.status-error-unexpected-api-result";
573 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
576 if (!status.isEmpty()) {
577 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
579 } catch (NullPointerException | IllegalArgumentException e) {
580 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
582 if (scheduledUpdates > 0) {
584 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
585 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
586 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
587 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
593 public boolean isThingOnline() {
594 return getThing().getStatus() == ThingStatus.ONLINE;
597 public boolean isThingOffline() {
598 return getThing().getStatus() == ThingStatus.OFFLINE;
602 public void setThingOnline() {
604 logger.debug("{}: Thing should go ONLINE, but handler is shutting down, ignore!", thingName);
607 if (!isThingOnline()) {
608 updateStatus(ThingStatus.ONLINE);
610 // request 3 updates in a row (during the first 2+3*3 sec)
611 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
614 // Restart watchdog when status update was successful (no exception)
619 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
620 String message = messages.get(messageKey);
622 logger.debug("{}: Thing should go OFFLINE with status {}, but handler is shutting down -> ignore",
627 if (!isThingOffline()) {
628 updateStatus(ThingStatus.OFFLINE, detail, message);
630 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
635 public void restartWatchdog() {
637 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
638 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
641 private boolean isWatchdogExpired() {
642 long delta = now() - watchdog;
643 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
644 stats.remainingWatchdog = delta;
650 private boolean isWatchdogStarted() {
655 public void reinitializeThing() {
656 logger.debug("{}: Re-Initialize Thing", thingName);
658 logger.debug("{}: Handler is shutting down, ignore", thingName);
661 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
662 messages.get("offline.status-error-restarted"));
663 requestUpdates(0, true);
667 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
670 // Update uptime and WiFi, internal temp
671 ShellyComponents.updateDeviceStatus(this, status);
672 stats.wifiRssi = status.wifiSta.rssi;
674 if (api.isInitialized()) {
675 stats.timeoutErrors = api.getTimeoutErrors();
676 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
678 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
680 // Check various device indicators like overheating
681 if (checkRestarted(status)) {
682 // Force re-initialization on next status update
684 } else if (getBool(status.overtemperature)) {
685 alarm = ALARM_TYPE_OVERTEMP;
686 } else if (getBool(status.overload)) {
687 alarm = ALARM_TYPE_OVERLOAD;
688 } else if (getBool(status.loaderror)) {
689 alarm = ALARM_TYPE_LOADERR;
691 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
692 if (internalTemp != UnDefType.NULL) {
693 int temp = ((Number) internalTemp).intValue();
694 if (temp > stats.maxInternalTemp) {
695 stats.maxInternalTemp = temp;
699 if (status.uptime != null) {
700 stats.lastUptime = getLong(status.uptime);
702 stats.coiotMessages = coap.getMessageCount();
703 stats.coiotErrors = coap.getErrorCount();
705 if (!alarm.isEmpty()) {
706 postEvent(alarm, false);
711 * Check if device has restarted and needs a new Thing initialization
713 * @return true: restart detected
716 private boolean checkRestarted(ShellySettingsStatus status) {
717 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
718 && (status.uptime != null && status.uptime < stats.lastUptime
719 || !profile.status.update.oldVersion.isEmpty()
720 && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
721 updateProperties(profile, status);
728 * Save alarm to the lastAlarm channel
730 * @param alarm Alarm Message
733 public void postEvent(String event, boolean force) {
734 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
735 State value = cache.getValue(channelId);
736 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
738 if (force || !lastAlarm.equals(event)
739 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
740 switch (event.toUpperCase()) {
743 case SHELLY_WAKEUPT_SENSOR:
744 case SHELLY_WAKEUPT_PERIODIC:
745 case SHELLY_WAKEUPT_BUTTON:
746 case SHELLY_WAKEUPT_POWERON:
747 case SHELLY_WAKEUPT_EXT_POWER:
748 case SHELLY_WAKEUPT_UNKNOWN:
749 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
750 case ALARM_TYPE_NONE:
753 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
754 triggerChannel(channelId, event);
755 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
756 stats.lastAlarm = event;
757 stats.lastAlarmTs = now();
764 * Callback for device events
766 * @param deviceName device receiving the event
767 * @param parameters parameters from the event URL
768 * @param data the HTML input data
769 * @return true if event was processed
772 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
773 Map<String, String> parameters) {
774 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
775 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
777 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
778 if (!profile.isInitialized()) {
779 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
780 requestUpdates(1, true);
782 String group = profile.getControlGroup(idx);
783 if (group.isEmpty()) {
784 logger.debug("{}: Unsupported event class: {}", thingName, type);
788 // map some of the events to system defined button triggers
792 String parmType = getString(parameters.get("type"));
793 String event = !parmType.isEmpty() ? parmType : type;
794 boolean isButton = profile.inButtonMode(idx - 1);
796 case SHELLY_EVENT_SHORTPUSH:
797 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
798 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
799 case SHELLY_EVENT_LONGPUSH:
801 triggerButton(group, idx, mapButtonEvent(event));
802 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
803 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
805 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
809 case SHELLY_EVENT_BTN_ON:
810 case SHELLY_EVENT_BTN_OFF:
811 if (profile.isRGBW2) {
812 // RGBW2 has only one input, so not per channel
813 group = CHANNEL_GROUP_LIGHT_CONTROL;
815 onoff = CHANNEL_INPUT;
817 case SHELLY_EVENT_BTN1_ON:
818 case SHELLY_EVENT_BTN1_OFF:
819 onoff = CHANNEL_INPUT1;
821 case SHELLY_EVENT_BTN2_ON:
822 case SHELLY_EVENT_BTN2_OFF:
823 onoff = CHANNEL_INPUT2;
825 case SHELLY_EVENT_OUT_ON:
826 case SHELLY_EVENT_OUT_OFF:
827 onoff = CHANNEL_OUTPUT;
829 case SHELLY_EVENT_ROLLER_OPEN:
830 case SHELLY_EVENT_ROLLER_CLOSE:
831 case SHELLY_EVENT_ROLLER_STOP:
832 channel = CHANNEL_EVENT_TRIGGER;
835 case SHELLY_EVENT_SENSORREPORT:
836 // process sensor with next refresh
838 case SHELLY_EVENT_TEMP_OVER: // DW2
839 case SHELLY_EVENT_TEMP_UNDER:
840 channel = CHANNEL_EVENT_TRIGGER;
843 case SHELLY_EVENT_FLOOD_DETECTED:
844 case SHELLY_EVENT_FLOOD_GONE:
845 updateChannel(group, CHANNEL_SENSOR_FLOOD,
846 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
849 case SHELLY_EVENT_CLOSE: // DW 1.7
850 case SHELLY_EVENT_OPEN: // DW 1.7
851 updateChannel(group, CHANNEL_SENSOR_STATE,
852 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
853 : OpenClosedType.CLOSED);
856 case SHELLY_EVENT_DARK: // DW 1.7
857 case SHELLY_EVENT_TWILIGHT: // DW 1.7
858 case SHELLY_EVENT_BRIGHT: // DW 1.7
859 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
862 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
863 case SHELLY_EVENT_ALARM_HEAVY:
864 case SHELLY_EVENT_ALARM_OFF:
865 case SHELLY_EVENT_VIBRATION: // DW2
866 channel = CHANNEL_SENSOR_ALARM_STATE;
867 payload = event.toUpperCase();
871 // trigger will be provided by input/output channel or sensor channels
874 if (!onoff.isEmpty()) {
875 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
877 if (!payload.isEmpty()) {
878 // Pass event to trigger channel
879 payload = payload.toUpperCase();
880 logger.debug("{}: Post event {}", thingName, payload);
881 triggerChannel(mkChannelId(group, channel), payload);
885 // request update on next interval (2x for non-battery devices)
887 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
894 * Initialize the binding's thing configuration, calc update counts
896 protected void initializeThingConfig() {
897 thingType = getThing().getThingTypeUID().getId();
898 final Map<String, String> properties = getThing().getProperties();
899 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
900 if (thingName.isEmpty()) {
901 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
902 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
905 config = getConfigAs(ShellyThingConfiguration.class);
906 if (config.deviceIp.isEmpty()) {
907 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
911 InetAddress addr = InetAddress.getByName(config.deviceIp);
912 String saddr = addr.getHostAddress();
913 if (!config.deviceIp.equals(saddr)) {
914 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
915 config.deviceIp = saddr;
917 } catch (UnknownHostException e) {
918 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
921 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
922 config.localIp = localIP;
923 config.localPort = localPort;
924 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
925 config.userId = bindingConfig.defaultUserId;
926 config.password = bindingConfig.defaultPassword;
927 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
929 if (config.updateInterval == 0) {
930 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
932 if (config.updateInterval < UPDATE_MIN_DELAY) {
933 config.updateInterval = UPDATE_MIN_DELAY;
936 // Try to get updatePeriod from properties
937 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
938 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
939 // initialized successfully by the REST call.
940 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
941 if (!lastPeriod.isEmpty()) {
942 int period = Integer.parseInt(lastPeriod);
944 profile.updatePeriod = period;
948 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
949 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
952 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
954 ShellyVersionDTO version = new ShellyVersionDTO();
955 if (version.checkBeta(getString(prf.fwVersion))) {
956 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
958 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
959 logger.warn("{}: {}", prf.hostname,
960 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
963 if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
964 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
965 if (!config.eventsCoIoT) {
966 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
970 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
971 logger.info("{}: {}", thingName,
972 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
974 } catch (NullPointerException e) { // could be inconsistant format of beta version
975 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
980 * Checks the http response for authorization error.
981 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
982 * case the thing type shelly-unknown is set.
984 * @param response exception details including the http respone
985 * @return true if the authorization failed
987 protected boolean isAuthorizationFailed(ShellyApiResult result) {
988 if (result.isHttpAccessUnauthorized()) {
989 // If the device is password protected the API doesn't provide settings to the device settings
990 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
997 * Change type of this thing.
999 * @param thingType thing type acc. to the xml definition
1000 * @param mode Device mode (e.g. relay, roller)
1002 protected void changeThingType(String thingType, String mode) {
1003 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1004 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1005 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1006 Map<String, String> properties = editProperties();
1007 properties.replace(PROPERTY_DEV_TYPE, thingType);
1008 properties.replace(PROPERTY_DEV_MODE, mode);
1009 updateProperties(properties);
1010 changeThingType(thingTypeUID, getConfig());
1015 public void thingUpdated(Thing thing) {
1016 logger.debug("{}: Channel definitions updated.", thingName);
1017 super.thingUpdated(thing);
1021 * Start the background updates
1023 protected void startUpdateJob() {
1024 ScheduledFuture<?> statusJob = this.statusJob;
1025 if ((statusJob == null) || statusJob.isCancelled()) {
1026 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1028 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1029 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1034 * Flag the status job to do an exceptional update (something happened) rather
1035 * than waiting until the next regular poll
1037 * @param requestCount number of polls to execute
1038 * @param refreshSettings true=force a /settings query
1039 * @return true=Update schedule, false=skipped (too many updates already
1043 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1044 this.refreshSettings |= refreshSettings;
1045 if (refreshSettings) {
1046 if (requestCount == 0) {
1047 logger.debug("{}: Request settings refresh", thingName);
1049 scheduledUpdates = 1;
1052 if (scheduledUpdates < 10) { // < 30s
1053 scheduledUpdates += requestCount;
1059 public boolean isUpdateScheduled() {
1060 return scheduledUpdates > 0;
1064 * Map input states to channels
1066 * @param groupName Channel Group (relay / relay1...)
1068 * @param status Shelly device status
1069 * @return true: one or more inputs were updated
1072 public boolean updateInputs(ShellySettingsStatus status) {
1073 boolean updated = false;
1075 if (status.inputs != null) {
1077 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
1078 for (ShellyInputState input : status.inputs) {
1079 String group = profile.getInputGroup(idx);
1080 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1082 if (!areChannelsCreated()) {
1083 updateChannelDefinitions(
1084 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
1087 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1088 if (input.event != null) {
1089 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1090 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1095 if (status.input != null) {
1096 // RGBW2: a single int rather than an array
1097 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1098 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1105 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1106 boolean changed = false;
1107 if (valueArray != null && !valueArray.isEmpty()) {
1108 String reason = getString((String) valueArray.get(0));
1109 String newVal = valueArray.toString();
1110 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1111 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1113 postEvent(reason.toUpperCase(), true);
1115 lastWakeupReason = newVal;
1121 public void triggerButton(String group, int idx, String value) {
1122 String trigger = mapButtonEvent(value);
1123 if (trigger.isEmpty()) {
1127 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1128 triggerChannel(group,
1129 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1131 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1132 if (profile.alwaysOn) {
1133 // refresh status of the input channel
1134 requestUpdates(1, false);
1139 public void publishState(String channelId, State value) {
1140 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1141 if (!stopping && isLinked(id)) {
1142 updateState(id, value);
1143 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1148 public boolean updateChannel(String group, String channel, State value) {
1149 return updateChannel(mkChannelId(group, channel), value, false);
1153 public boolean updateChannel(String channelId, State value, boolean force) {
1154 return !stopping && cache.updateChannel(channelId, value, force);
1158 public State getChannelValue(String group, String channel) {
1159 return cache.getValue(group, channel);
1163 public double getChannelDouble(String group, String channel) {
1164 State value = getChannelValue(group, channel);
1165 if (value != UnDefType.NULL) {
1166 if (value instanceof QuantityType) {
1167 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1169 if (value instanceof DecimalType) {
1170 return ((DecimalType) value).doubleValue();
1177 * Update Thing's channels according to available status information from the API
1179 * @param thingHandler
1182 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1183 if (channelsCreated) {
1184 return; // already done
1188 // Get subset of those channels that currently do not exist
1189 List<Channel> existingChannels = getThing().getChannels();
1190 for (Channel channel : existingChannels) {
1191 String id = channel.getUID().getId();
1192 if (dynChannels.containsKey(id)) {
1193 dynChannels.remove(id);
1197 if (!dynChannels.isEmpty()) {
1198 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1199 ThingBuilder thingBuilder = editThing();
1200 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1201 Channel c = channel.getValue();
1202 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1203 thingBuilder.withChannel(c);
1205 updateThing(thingBuilder.build());
1206 logger.debug("{}: Channel definitions updated", thingName);
1208 } catch (IllegalArgumentException e) {
1209 logger.debug("{}: Unable to update channel definitions", thingName, e);
1214 public boolean areChannelsCreated() {
1215 return channelsCreated;
1219 * Update thing properties with dynamic values
1221 * @param profile The device profile
1222 * @param status the /status result
1224 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1225 logger.debug("{}: Update properties", thingName);
1226 Map<String, Object> properties = fillDeviceProperties(profile);
1227 String deviceName = getString(profile.settings.name);
1228 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1229 properties.put(PROPERTY_DEV_GEN, "1");
1230 if (!deviceName.isEmpty()) {
1231 properties.put(PROPERTY_DEV_NAME, deviceName);
1234 // add status properties
1235 if (status.wifiSta != null) {
1236 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1238 if (status.update != null) {
1239 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1240 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1241 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1242 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1244 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1246 Map<String, String> thingProperties = new TreeMap<>();
1247 for (Map.Entry<String, Object> property : properties.entrySet()) {
1248 thingProperties.put(property.getKey(), (String) property.getValue());
1250 flushProperties(thingProperties);
1254 * Add one property to the Thing Properties
1256 * @param key Name of the property
1257 * @param value Value of the property
1260 public void updateProperties(String key, String value) {
1261 Map<String, String> thingProperties = editProperties();
1262 if (thingProperties.containsKey(key)) {
1263 thingProperties.replace(key, value);
1265 thingProperties.put(key, value);
1267 updateProperties(thingProperties);
1268 logger.trace("{}: Properties updated", thingName);
1271 public void flushProperties(Map<String, String> propertyUpdates) {
1272 Map<String, String> thingProperties = editProperties();
1273 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1274 if (thingProperties.containsKey(property.getKey())) {
1275 thingProperties.replace(property.getKey(), property.getValue());
1277 thingProperties.put(property.getKey(), property.getValue());
1280 updateProperties(thingProperties);
1284 * Get one property from the Thing Properties
1286 * @param key property name
1287 * @return property value or "" if property is not set
1290 public String getProperty(String key) {
1291 Map<String, String> thingProperties = getThing().getProperties();
1292 return getString(thingProperties.get(key));
1296 * Fill Thing Properties with device attributes
1298 * @param profile Property Map to full
1299 * @return a full property map
1301 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1302 Map<String, Object> properties = new TreeMap<>();
1303 properties.put(PROPERTY_VENDOR, VENDOR);
1304 if (profile.isInitialized()) {
1305 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1306 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1307 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1308 properties.put(PROPERTY_DEV_MODE, profile.mode);
1309 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1310 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1311 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1312 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1313 if (!profile.hwRev.isEmpty()) {
1314 properties.put(PROPERTY_HWREV, profile.hwRev);
1315 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1322 * Return device profile.
1324 * @param ForceRefresh true=force refresh before returning, false=return without
1326 * @return ShellyDeviceProfile instance
1327 * @throws ShellyApiException
1330 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1332 refreshSettings |= forceRefresh;
1333 if (refreshSettings) {
1334 profile = api.getDeviceProfile(thingType);
1335 if (!isThingOnline()) {
1336 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1340 refreshSettings = false;
1346 public ShellyDeviceProfile getProfile() {
1350 protected ShellyDeviceProfile getDeviceProfile() {
1355 public void triggerChannel(String group, String channel, String payload) {
1356 String triggerCh = mkChannelId(group, channel);
1357 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1358 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1359 if (vibrationFilter == 0) {
1360 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1361 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1362 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1364 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1365 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1370 triggerChannel(triggerCh, payload);
1373 public void stop() {
1374 logger.debug("{}: Shutting down", thingName);
1375 ScheduledFuture<?> job = this.statusJob;
1379 logger.debug("{}: Shelly statusJob stopped", thingName);
1383 profile.initialized = false;
1387 * Shutdown thing, make sure background jobs are canceled
1390 public void dispose() {
1397 * Device specific command handlers are overriding this method to do additional stuff
1399 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1404 * Device specific handlers are overriding this method to do additional stuff
1406 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1411 public String getThingName() {
1416 public void resetStats() {
1418 stats = new ShellyDeviceStats();
1422 public ShellyDeviceStats getStats() {
1427 public ShellyApiInterface getApi() {
1431 public Map<String, String> getStatsProp() {
1432 return stats.asProperties();
1436 public long getScheduledUpdates() {
1437 return scheduledUpdates;
1440 public String checkForUpdate() {
1442 ShellyOtaCheckResult result = api.checkForUpdate();
1443 return result.status;
1444 } catch (ShellyApiException e) {
1450 public void triggerUpdateFromCoap() {
1451 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1452 requestUpdates(1, false);