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.api.ShellyApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
18 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19 import static org.openhab.core.thing.Thing.*;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.List;
25 import java.util.TreeMap;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.openhab.binding.shelly.internal.api.ShellyApiException;
33 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
34 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO;
35 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyInputState;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyOtaCheckResult;
37 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
38 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
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.api.ShellyHttpApi;
42 import org.openhab.binding.shelly.internal.coap.ShellyCoapHandler;
43 import org.openhab.binding.shelly.internal.coap.ShellyCoapJSonDTO;
44 import org.openhab.binding.shelly.internal.coap.ShellyCoapServer;
45 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
46 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
47 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
48 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
49 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
50 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
51 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
52 import org.openhab.core.library.types.DecimalType;
53 import org.openhab.core.library.types.OnOffType;
54 import org.openhab.core.library.types.OpenClosedType;
55 import org.openhab.core.library.types.QuantityType;
56 import org.openhab.core.thing.Channel;
57 import org.openhab.core.thing.ChannelUID;
58 import org.openhab.core.thing.Thing;
59 import org.openhab.core.thing.ThingStatus;
60 import org.openhab.core.thing.ThingStatusDetail;
61 import org.openhab.core.thing.ThingTypeUID;
62 import org.openhab.core.thing.binding.BaseThingHandler;
63 import org.openhab.core.thing.binding.builder.ThingBuilder;
64 import org.openhab.core.types.Command;
65 import org.openhab.core.types.RefreshType;
66 import org.openhab.core.types.State;
67 import org.openhab.core.types.UnDefType;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
73 * sent to one of the channels.
75 * @author Markus Michels - Initial contribution
78 public class ShellyBaseHandler extends BaseThingHandler
79 implements ShellyDeviceListener, ShellyManagerInterface, ShellyThingInterface {
80 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
81 protected final ShellyChannelDefinitions channelDefinitions;
83 public String thingName = "";
84 public String thingType = "";
86 protected final ShellyApiInterface api;
87 protected ShellyBindingConfiguration bindingConfig;
88 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
89 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
90 protected ShellyDeviceStats stats = new ShellyDeviceStats();
91 private final ShellyCoapHandler coap;
92 public boolean autoCoIoT = false;
94 public final ShellyTranslationProvider messages;
95 protected boolean stopping = false;
96 private boolean channelsCreated = false;
98 private long watchdog = now();
100 private @Nullable ScheduledFuture<?> statusJob;
101 public int scheduledUpdates = 0;
102 private int skipCount = UPDATE_SKIP_COUNT;
103 private int skipUpdate = 0;
104 private boolean refreshSettings = false;
106 // delay before enabling channel
107 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
108 protected final ShellyChannelCache cache;
110 private String localIP = "";
111 private String localPort = "";
113 private String lastWakeupReason = "";
114 private int vibrationFilter = 0;
119 * @param thing The Thing object
120 * @param bindingConfig The binding configuration (beside thing
122 * @param coapServer coap server instance
123 * @param localIP local IP address from networkAddressService
124 * @param httpPort from httpService
126 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
127 final ShellyBindingConfiguration bindingConfig, final ShellyCoapServer coapServer, final String localIP,
128 int httpPort, final HttpClient httpClient) {
131 this.thingName = getString(thing.getLabel());
132 this.messages = translationProvider;
133 this.cache = new ShellyChannelCache(this);
134 this.channelDefinitions = new ShellyChannelDefinitions(messages);
135 this.bindingConfig = bindingConfig;
136 this.config = getConfigAs(ShellyThingConfiguration.class);
138 this.localIP = localIP;
139 this.localPort = String.valueOf(httpPort);
140 this.api = new ShellyHttpApi(thingName, config, httpClient);
142 coap = new ShellyCoapHandler(this, coapServer);
146 public boolean checkRepresentation(String key) {
147 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
148 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(thing.getUID().getAsString());
151 public String getUID() {
152 return getThing().getUID().getAsString();
156 * Schedule asynchronous Thing initialization, register thing to event dispatcher
159 public void initialize() {
160 // start background initialization:
161 scheduler.schedule(() -> {
162 boolean start = true;
164 initializeThingConfig();
165 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
166 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
167 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
169 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
170 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
171 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
172 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
173 messages.get("status.unknown.initializing"));
174 start = initializeThing();
175 } catch (ShellyApiException e) {
176 ShellyApiResult res = e.getApiResult();
177 if (isAuthorizationFailed(res)) {
180 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
181 } catch (IllegalArgumentException e) {
182 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
184 // even this initialization failed we start the status update
185 // the updateJob will then try to auto-initialize the thing
186 // in this case the thing stays in status INITIALIZING
191 }, 2, TimeUnit.SECONDS);
195 public ShellyThingConfiguration getThingConfig() {
200 * This routine is called every time the Thing configuration has been changed
203 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
204 super.handleConfigurationUpdate(configurationParameters);
205 logger.debug("{}: Thing config updated, re-initialize", thingName);
207 requestUpdates(1, true);// force re-initialization
211 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
212 * If the device is password protected and the credentials are missing or don't match the API access will throw an
213 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
214 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
215 * credentials are correct and the API access is initialized successful.
217 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
219 private boolean initializeThing() throws ShellyApiException {
220 // Init from thing type to have a basic profile, gets updated when device info is received from API
222 refreshSettings = false;
223 lastWakeupReason = "";
224 profile.initFromThingType(thingType);
225 api.setConfig(thingName, config);
226 cache.setThingName(thingName);
229 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
230 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
231 if (config.deviceIp.isEmpty()) {
232 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
236 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
237 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
239 if (config.eventsCoIoT && !profile.alwaysOn) {
240 coap.start(thingName, config);
243 // Initialize API access, exceptions will be catched by initialize()
244 ShellySettingsDevice devInfo = api.getDeviceInfo();
245 if (getBool(devInfo.auth) && config.userId.isEmpty()) {
246 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
249 if (config.serviceName.isEmpty()) {
250 config.serviceName = getString(profile.hostname).toLowerCase();
253 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
254 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
255 changeThingType(thingName, tmpPrf.mode);
256 return false; // force re-initialization
258 // Validate device mode
259 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
260 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
261 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
264 if (!getString(devInfo.coiot).isEmpty()) {
265 // New Shelly devices might use a different endpoint for the CoAP listener
266 tmpPrf.coiotEndpoint = devInfo.coiot;
268 tmpPrf.auth = devInfo.auth; // missing in /settings
269 tmpPrf.status = api.getStatus();
270 tmpPrf.updateFromStatus(tmpPrf.status);
272 showThingConfig(tmpPrf);
273 checkVersion(tmpPrf, tmpPrf.status);
275 if (config.eventsCoIoT && (tmpPrf.settings.coiot != null) && (tmpPrf.settings.coiot.enabled != null)) {
276 String devpeer = getString(tmpPrf.settings.coiot.peer);
277 String ourpeer = config.localIp + ":" + ShellyCoapJSonDTO.COIOT_PORT;
278 if (!tmpPrf.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
280 api.setCoIoTPeer(ourpeer);
281 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
282 } catch (ShellyApiException e) {
283 logger.warn("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
285 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
286 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
290 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
291 config.eventsCoIoT = true;
292 config.eventsSwitch = false;
293 config.eventsButton = false;
294 config.eventsPush = false;
295 config.eventsRoller = false;
296 config.eventsSensorReport = false;
297 api.setConfig(thingName, config);
300 // All initialization done, so keep the profile and set Thing to ONLINE
301 fillDeviceStatus(tmpPrf.status, false);
302 postEvent(ALARM_TYPE_NONE, false);
303 api.setActionURLs(); // register event urls
304 if (config.eventsCoIoT) {
305 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
306 coap.start(thingName, config);
309 logger.debug("{}: Thing successfully initialized.", thingName);
312 updateProperties(tmpPrf, tmpPrf.status);
313 setThingOnline(); // if API call was successful the thing must be online
314 return true; // success
317 private void showThingConfig(ShellyDeviceProfile profile) {
318 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
319 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
321 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
322 logger.debug("{}: Device "
323 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
324 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
325 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
326 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
327 profile.isDW, profile.hasBattery,
328 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
329 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
330 profile.alwaysOn, profile.updatePeriod);
334 * Handle Channel Commands
337 public void handleCommand(ChannelUID channelUID, Command command) {
339 if (command instanceof RefreshType) {
340 String channelId = channelUID.getId();
341 State value = cache.getValue(channelId);
342 if (value != UnDefType.NULL) {
343 updateState(channelId, value);
348 if (!profile.isInitialized()) {
349 logger.debug("{}: {}", thingName, messages.get("command.init", command));
352 profile = getProfile(false);
355 boolean update = false;
356 switch (channelUID.getIdWithoutGroup()) {
357 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
358 logger.debug("{}: Send key {}", thingName, command);
359 api.sendIRKey(command.toString());
363 case CHANNEL_LED_STATUS_DISABLE:
364 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
365 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
367 case CHANNEL_LED_POWER_DISABLE:
368 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
369 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
372 case CHANNEL_SENSOR_SLEEPTIME:
373 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
374 int value = (int) getNumber(command);
375 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
377 api.setSleepTime(value);
379 case CHANNEL_CONTROL_PROFILE:
380 logger.debug("{}: Select profile {}", thingName, command);
381 int profile = (int) getNumber(command);
382 if (profile < 0 || profile > 5) {
383 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
386 api.setValveProfile(0, profile);
388 case CHANNEL_CONTROL_MODE:
389 logger.debug("{}: Set mode to {}", thingName, command);
390 api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
392 case CHANNEL_CONTROL_SETTEMP:
393 logger.debug("{}: Set temperature to {}", thingName, command);
394 api.setValveTemperature(0, (int) getNumber(command));
396 case CHANNEL_CONTROL_POSITION:
397 logger.debug("{}: Set position to {}", thingName, command);
398 api.setValvePosition(0, getNumber(command));
400 case CHANNEL_CONTROL_BCONTROL:
401 logger.debug("{}: Set boost mode to {}", thingName, command);
402 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
404 case CHANNEL_CONTROL_BTIMER:
405 logger.debug("{}: Set boost timer to {}", thingName, command);
406 api.setValveBoostTime(0, (int) getNumber(command));
410 update = handleDeviceCommand(channelUID, command);
415 if (update && !autoCoIoT && !isUpdateScheduled()) {
416 logger.debug("{}: Command processed, request status update", thingName);
417 requestUpdates(1, false);
419 } catch (ShellyApiException e) {
420 ShellyApiResult res = e.getApiResult();
421 if (isAuthorizationFailed(res)) {
424 if (res.isNotCalibrtated()) {
425 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
427 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
430 } catch (IllegalArgumentException e) {
431 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
435 private double getNumber(Command command) {
436 if (command instanceof QuantityType) {
437 return ((QuantityType<?>) command).doubleValue();
439 if (command instanceof DecimalType) {
440 return ((DecimalType) command).doubleValue();
442 if (command instanceof Number) {
443 return ((Number) command).doubleValue();
445 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
449 * Update device status and channels
451 protected void refreshStatus() {
453 boolean updated = false;
455 if (vibrationFilter > 0) {
457 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
458 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
462 ThingStatus thingStatus = getThing().getStatus();
463 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
464 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
465 || (thingStatus == ThingStatus.UNKNOWN)) {
466 logger.debug("{}: Status update triggered thing initialization", thingName);
467 initializeThing(); // may fire an exception if initialization failed
469 // Get profile, if refreshSettings == true reload settings from device
470 logger.trace("{}: Updating status (scheduledUpdates={}, refreshSettings={})", thingName,
471 scheduledUpdates, refreshSettings);
472 ShellySettingsStatus status = api.getStatus();
473 boolean restarted = checkRestarted(status);
474 profile = getProfile(refreshSettings || restarted);
475 profile.status = status;
476 profile.updateFromStatus(status);
478 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
480 postEvent(ALARM_TYPE_RESTARTED, true);
483 // If status update was successful the thing must be online
486 // map status to channels
487 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
488 updated |= this.updateDeviceStatus(status);
489 updated |= ShellyComponents.updateDeviceStatus(this, status);
490 fillDeviceStatus(status, updated);
491 updated |= updateInputs(status);
492 updated |= updateMeters(this, status);
493 updated |= updateSensors(this, status);
495 // All channels must be created after the first cycle
496 channelsCreated = true;
498 } catch (ShellyApiException e) {
499 // http call failed: go offline except for battery devices, which might be in
500 // sleep mode. Once the next update is successful the device goes back online
502 ShellyApiResult res = e.getApiResult();
503 if (isWatchdogStarted()) {
504 if (!isWatchdogExpired()) {
505 logger.debug("{}: Ignore API Timeout, retry later", thingName);
507 if (isThingOnline()) {
508 status = "offline.status-error-watchdog";
511 } else if (res.isHttpAccessUnauthorized()) {
512 status = "offline.conf-error-access-denied";
513 } else if (e.isJSONException()) {
514 status = "offline.status-error-unexpected-api-result";
515 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
516 } else if (res.isHttpTimeout()) {
517 // Watchdog not started, e.g. device in sleep mode
518 if (isThingOnline()) { // ignore when already offline
519 status = "offline.status-error-watchdog";
522 status = "offline.status-error-unexpected-api-result";
523 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
526 if (!status.isEmpty()) {
527 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
529 } catch (NullPointerException | IllegalArgumentException e) {
530 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
532 if (scheduledUpdates > 0) {
534 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
535 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
536 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
537 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
543 public boolean isThingOnline() {
544 return getThing().getStatus() == ThingStatus.ONLINE;
547 public boolean isThingOffline() {
548 return getThing().getStatus() == ThingStatus.OFFLINE;
552 public void setThingOnline() {
554 logger.debug("{}: Thing should go ONLINE, but handler is shutting down, ignore!", thingName);
557 if (!isThingOnline()) {
558 updateStatus(ThingStatus.ONLINE);
560 // request 3 updates in a row (during the first 2+3*3 sec)
561 logger.debug("{}: Thing went online, request status update", thingName);
562 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
568 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
569 String message = messages.get(messageKey);
571 logger.debug("{}: Thing should go OFFLINE with status {}, but handler is shutting down -> ignore",
576 if (!isThingOffline()) {
577 updateStatus(ThingStatus.OFFLINE, detail, message);
579 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
584 public void restartWatchdog() {
586 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
587 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
590 private boolean isWatchdogExpired() {
591 long delta = now() - watchdog;
592 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
593 stats.remainingWatchdog = delta;
599 private boolean isWatchdogStarted() {
604 public void reinitializeThing() {
605 logger.debug("{}: Re-Initialize Thing", thingName);
607 logger.debug("{}: Handler is shutting down, ignore", thingName);
610 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
611 messages.get("offline.status-error-restarted"));
612 requestUpdates(0, true);
616 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
619 // Update uptime and WiFi, internal temp
620 ShellyComponents.updateDeviceStatus(this, status);
621 stats.wifiRssi = status.wifiSta.rssi;
623 if (api.isInitialized()) {
624 stats.timeoutErrors = api.getTimeoutErrors();
625 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
627 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
629 // Check various device indicators like overheating
630 if (checkRestarted(status)) {
631 // Force re-initialization on next status update
633 } else if (getBool(status.overtemperature)) {
634 alarm = ALARM_TYPE_OVERTEMP;
635 } else if (getBool(status.overload)) {
636 alarm = ALARM_TYPE_OVERLOAD;
637 } else if (getBool(status.loaderror)) {
638 alarm = ALARM_TYPE_LOADERR;
640 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
641 if (internalTemp != UnDefType.NULL) {
642 int temp = ((Number) internalTemp).intValue();
643 if (temp > stats.maxInternalTemp) {
644 stats.maxInternalTemp = temp;
648 if (status.uptime != null) {
649 stats.lastUptime = getLong(status.uptime);
651 stats.coiotMessages = coap.getMessageCount();
652 stats.coiotErrors = coap.getErrorCount();
654 if (!alarm.isEmpty()) {
655 postEvent(alarm, false);
660 * Check if device has restarted and needs a new Thing initialization
662 * @return true: restart detected
665 private boolean checkRestarted(ShellySettingsStatus status) {
666 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
667 && (status.uptime != null && status.uptime < stats.lastUptime
668 || !profile.status.update.oldVersion.isEmpty()
669 && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
670 updateProperties(profile, status);
677 * Save alarm to the lastAlarm channel
679 * @param alarm Alarm Message
682 public void postEvent(String event, boolean force) {
683 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
684 State value = cache.getValue(channelId);
685 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
687 if (force || !lastAlarm.equals(event)
688 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
692 case SHELLY_WAKEUPT_SENSOR:
693 case SHELLY_WAKEUPT_PERIODIC:
694 case SHELLY_WAKEUPT_BUTTON:
695 case SHELLY_WAKEUPT_POWERON:
696 case SHELLY_WAKEUPT_EXT_POWER:
697 case SHELLY_WAKEUPT_UNKNOWN:
698 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
699 case ALARM_TYPE_NONE:
702 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
703 triggerChannel(channelId, event);
704 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
705 stats.lastAlarm = event;
706 stats.lastAlarmTs = now();
713 * Callback for device events
715 * @param deviceName device receiving the event
716 * @param parameters parameters from the event URL
717 * @param data the HTML input data
718 * @return true if event was processed
721 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
722 Map<String, String> parameters) {
723 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
724 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
726 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
727 if (!profile.isInitialized()) {
728 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
729 requestUpdates(1, true);
731 String group = profile.getControlGroup(idx);
732 if (group.isEmpty()) {
733 logger.debug("{}: Unsupported event class: {}", thingName, type);
737 // map some of the events to system defined button triggers
741 String parmType = getString(parameters.get("type"));
742 String event = !parmType.isEmpty() ? parmType : type;
743 boolean isButton = profile.inButtonMode(idx - 1);
745 case SHELLY_EVENT_SHORTPUSH:
746 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
747 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
748 case SHELLY_EVENT_LONGPUSH:
750 triggerButton(group, idx, mapButtonEvent(event));
751 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
752 payload = ShellyApiJsonDTO.mapButtonEvent(event);
754 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
758 case SHELLY_EVENT_BTN_ON:
759 case SHELLY_EVENT_BTN_OFF:
760 if (profile.isRGBW2) {
761 // RGBW2 has only one input, so not per channel
762 group = CHANNEL_GROUP_LIGHT_CONTROL;
764 onoff = CHANNEL_INPUT;
766 case SHELLY_EVENT_BTN1_ON:
767 case SHELLY_EVENT_BTN1_OFF:
768 onoff = CHANNEL_INPUT1;
770 case SHELLY_EVENT_BTN2_ON:
771 case SHELLY_EVENT_BTN2_OFF:
772 onoff = CHANNEL_INPUT2;
774 case SHELLY_EVENT_OUT_ON:
775 case SHELLY_EVENT_OUT_OFF:
776 onoff = CHANNEL_OUTPUT;
778 case SHELLY_EVENT_ROLLER_OPEN:
779 case SHELLY_EVENT_ROLLER_CLOSE:
780 case SHELLY_EVENT_ROLLER_STOP:
781 channel = CHANNEL_EVENT_TRIGGER;
784 case SHELLY_EVENT_SENSORREPORT:
785 // process sensor with next refresh
787 case SHELLY_EVENT_TEMP_OVER: // DW2
788 case SHELLY_EVENT_TEMP_UNDER:
789 channel = CHANNEL_EVENT_TRIGGER;
792 case SHELLY_EVENT_FLOOD_DETECTED:
793 case SHELLY_EVENT_FLOOD_GONE:
794 updateChannel(group, CHANNEL_SENSOR_FLOOD,
795 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
798 case SHELLY_EVENT_CLOSE: // DW 1.7
799 case SHELLY_EVENT_OPEN: // DW 1.7
800 updateChannel(group, CHANNEL_SENSOR_STATE,
801 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
802 : OpenClosedType.CLOSED);
805 case SHELLY_EVENT_DARK: // DW 1.7
806 case SHELLY_EVENT_TWILIGHT: // DW 1.7
807 case SHELLY_EVENT_BRIGHT: // DW 1.7
808 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
811 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
812 case SHELLY_EVENT_ALARM_HEAVY:
813 case SHELLY_EVENT_ALARM_OFF:
814 case SHELLY_EVENT_VIBRATION: // DW2
815 channel = CHANNEL_SENSOR_ALARM_STATE;
816 payload = event.toUpperCase();
820 // trigger will be provided by input/output channel or sensor channels
823 if (!onoff.isEmpty()) {
824 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
826 if (!payload.isEmpty()) {
827 // Pass event to trigger channel
828 payload = payload.toUpperCase();
829 logger.debug("{}: Post event {}", thingName, payload);
830 triggerChannel(mkChannelId(group, channel), payload);
834 // request update on next interval (2x for non-battery devices)
836 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
843 * Initialize the binding's thing configuration, calc update counts
845 protected void initializeThingConfig() {
846 thingType = getThing().getThingTypeUID().getId();
847 final Map<String, String> properties = getThing().getProperties();
848 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
849 if (thingName.isEmpty()) {
850 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
851 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
854 config = getConfigAs(ShellyThingConfiguration.class);
855 if (config.deviceIp.isEmpty()) {
856 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
860 InetAddress addr = InetAddress.getByName(config.deviceIp);
861 String saddr = addr.getHostAddress();
862 if (!config.deviceIp.equals(saddr)) {
863 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
864 config.deviceIp = saddr;
866 } catch (UnknownHostException e) {
867 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
870 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
871 config.localIp = localIP;
872 config.localPort = localPort;
873 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
874 config.userId = bindingConfig.defaultUserId;
875 config.password = bindingConfig.defaultPassword;
876 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
878 if (config.updateInterval == 0) {
879 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
881 if (config.updateInterval < UPDATE_MIN_DELAY) {
882 config.updateInterval = UPDATE_MIN_DELAY;
885 // Try to get updatePeriod from properties
886 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
887 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
888 // initialized successfully by the REST call.
889 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
890 if (!lastPeriod.isEmpty()) {
891 int period = Integer.parseInt(lastPeriod);
893 profile.updatePeriod = period;
897 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
898 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
901 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
903 ShellyVersionDTO version = new ShellyVersionDTO();
904 if (version.checkBeta(getString(prf.fwVersion))) {
905 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
907 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
908 logger.warn("{}: {}", prf.hostname,
909 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
912 if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
913 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
914 if (!config.eventsCoIoT) {
915 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
919 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
920 logger.info("{}: {}", thingName,
921 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
923 } catch (NullPointerException e) { // could be inconsistant format of beta version
924 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
929 * Checks the http response for authorization error.
930 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
931 * case the thing type shelly-unknown is set.
933 * @param response exception details including the http respone
934 * @return true if the authorization failed
936 protected boolean isAuthorizationFailed(ShellyApiResult result) {
937 if (result.isHttpAccessUnauthorized()) {
938 // If the device is password protected the API doesn't provide settings to the device settings
939 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
946 * Change type of this thing.
948 * @param thingType thing type acc. to the xml definition
949 * @param mode Device mode (e.g. relay, roller)
951 private void changeThingType(String thingType, String mode) {
952 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
953 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
954 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
955 Map<String, String> properties = editProperties();
956 properties.replace(PROPERTY_DEV_TYPE, thingType);
957 properties.replace(PROPERTY_DEV_MODE, mode);
958 updateProperties(properties);
959 changeThingType(thingTypeUID, getConfig());
964 public void thingUpdated(Thing thing) {
965 logger.debug("{}: Channel definitions updated.", thingName);
966 super.thingUpdated(thing);
970 * Start the background updates
972 protected void startUpdateJob() {
973 ScheduledFuture<?> statusJob = this.statusJob;
974 if ((statusJob == null) || statusJob.isCancelled()) {
975 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
977 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
978 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
983 * Flag the status job to do an exceptional update (something happened) rather
984 * than waiting until the next regular poll
986 * @param requestCount number of polls to execute
987 * @param refreshSettings true=force a /settings query
988 * @return true=Update schedule, false=skipped (too many updates already
992 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
993 this.refreshSettings |= refreshSettings;
994 if (refreshSettings) {
995 if (requestCount == 0) {
996 logger.debug("{}: Request settings refresh", thingName);
998 scheduledUpdates = 1;
1001 if (scheduledUpdates < 10) { // < 30s
1002 scheduledUpdates += requestCount;
1008 public boolean isUpdateScheduled() {
1009 return scheduledUpdates > 0;
1013 * Map input states to channels
1015 * @param groupName Channel Group (relay / relay1...)
1017 * @param status Shelly device status
1018 * @return true: one or more inputs were updated
1021 public boolean updateInputs(ShellySettingsStatus status) {
1022 boolean updated = false;
1024 if (status.inputs != null) {
1026 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
1027 for (ShellyInputState input : status.inputs) {
1028 String group = profile.getControlGroup(idx);
1029 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1031 if (!areChannelsCreated()) {
1032 updateChannelDefinitions(
1033 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
1036 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1037 if (input.event != null) {
1038 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1039 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1044 if (status.input != null) {
1045 // RGBW2: a single int rather than an array
1046 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1047 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1054 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1055 boolean changed = false;
1056 if (valueArray != null && !valueArray.isEmpty()) {
1057 String reason = getString((String) valueArray.get(0));
1058 String newVal = valueArray.toString();
1059 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1060 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1062 postEvent(reason.toUpperCase(), true);
1064 lastWakeupReason = newVal;
1070 public void triggerButton(String group, int idx, String value) {
1071 String trigger = mapButtonEvent(value);
1072 if (trigger.isEmpty()) {
1076 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1077 triggerChannel(group,
1078 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1080 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1081 if (profile.alwaysOn) {
1082 // refresh status of the input channel
1083 requestUpdates(1, false);
1088 public void publishState(String channelId, State value) {
1089 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1090 if (!stopping && isLinked(id)) {
1091 updateState(id, value);
1092 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1097 public boolean updateChannel(String group, String channel, State value) {
1098 return updateChannel(mkChannelId(group, channel), value, false);
1102 public boolean updateChannel(String channelId, State value, boolean force) {
1103 return !stopping && cache.updateChannel(channelId, value, force);
1107 public State getChannelValue(String group, String channel) {
1108 return cache.getValue(group, channel);
1112 public double getChannelDouble(String group, String channel) {
1113 State value = getChannelValue(group, channel);
1114 if (value != UnDefType.NULL) {
1115 if (value instanceof QuantityType) {
1116 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1118 if (value instanceof DecimalType) {
1119 return ((DecimalType) value).doubleValue();
1126 * Update Thing's channels according to available status information from the API
1128 * @param thingHandler
1131 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1132 if (channelsCreated) {
1133 return; // already done
1137 // Get subset of those channels that currently do not exist
1138 List<Channel> existingChannels = getThing().getChannels();
1139 for (Channel channel : existingChannels) {
1140 String id = channel.getUID().getId();
1141 if (dynChannels.containsKey(id)) {
1142 dynChannels.remove(id);
1146 if (!dynChannels.isEmpty()) {
1147 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1148 ThingBuilder thingBuilder = editThing();
1149 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1150 Channel c = channel.getValue();
1151 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1152 thingBuilder.withChannel(c);
1154 updateThing(thingBuilder.build());
1155 logger.debug("{}: Channel definitions updated", thingName);
1157 } catch (IllegalArgumentException e) {
1158 logger.debug("{}: Unable to update channel definitions", thingName, e);
1163 public boolean areChannelsCreated() {
1164 return channelsCreated;
1168 * Update thing properties with dynamic values
1170 * @param profile The device profile
1171 * @param status the /status result
1173 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1174 logger.debug("{}: Update properties", thingName);
1175 Map<String, Object> properties = fillDeviceProperties(profile);
1176 String deviceName = getString(profile.settings.name);
1177 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1178 properties.put(PROPERTY_DEV_GEN, "1");
1179 if (!deviceName.isEmpty()) {
1180 properties.put(PROPERTY_DEV_NAME, deviceName);
1183 // add status properties
1184 if (status.wifiSta != null) {
1185 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1187 if (status.update != null) {
1188 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1189 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1190 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1191 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1193 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1195 Map<String, String> thingProperties = new TreeMap<>();
1196 for (Map.Entry<String, Object> property : properties.entrySet()) {
1197 thingProperties.put(property.getKey(), (String) property.getValue());
1199 flushProperties(thingProperties);
1203 * Add one property to the Thing Properties
1205 * @param key Name of the property
1206 * @param value Value of the property
1209 public void updateProperties(String key, String value) {
1210 Map<String, String> thingProperties = editProperties();
1211 if (thingProperties.containsKey(key)) {
1212 thingProperties.replace(key, value);
1214 thingProperties.put(key, value);
1216 updateProperties(thingProperties);
1217 logger.trace("{}: Properties updated", thingName);
1220 public void flushProperties(Map<String, String> propertyUpdates) {
1221 Map<String, String> thingProperties = editProperties();
1222 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1223 if (thingProperties.containsKey(property.getKey())) {
1224 thingProperties.replace(property.getKey(), property.getValue());
1226 thingProperties.put(property.getKey(), property.getValue());
1229 updateProperties(thingProperties);
1233 * Get one property from the Thing Properties
1235 * @param key property name
1236 * @return property value or "" if property is not set
1239 public String getProperty(String key) {
1240 Map<String, String> thingProperties = getThing().getProperties();
1241 return getString(thingProperties.get(key));
1245 * Fill Thing Properties with device attributes
1247 * @param profile Property Map to full
1248 * @return a full property map
1250 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1251 Map<String, Object> properties = new TreeMap<>();
1252 properties.put(PROPERTY_VENDOR, VENDOR);
1253 if (profile.isInitialized()) {
1254 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1255 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1256 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1257 properties.put(PROPERTY_DEV_MODE, profile.mode);
1258 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1259 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1260 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1261 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1262 if (!profile.hwRev.isEmpty()) {
1263 properties.put(PROPERTY_HWREV, profile.hwRev);
1264 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1271 * Return device profile.
1273 * @param ForceRefresh true=force refresh before returning, false=return without
1275 * @return ShellyDeviceProfile instance
1276 * @throws ShellyApiException
1279 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1281 refreshSettings |= forceRefresh;
1282 if (refreshSettings) {
1283 profile = api.getDeviceProfile(thingType);
1284 if (!isThingOnline()) {
1285 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1289 refreshSettings = false;
1295 public ShellyDeviceProfile getProfile() {
1299 protected ShellyDeviceProfile getDeviceProfile() {
1304 public void triggerChannel(String group, String channel, String payload) {
1305 String triggerCh = mkChannelId(group, channel);
1306 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1307 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1308 if (vibrationFilter == 0) {
1309 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1310 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1311 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1313 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1314 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1319 triggerChannel(triggerCh, payload);
1322 public void stop() {
1323 logger.debug("{}: Shutting down", thingName);
1324 ScheduledFuture<?> job = this.statusJob;
1328 logger.debug("{}: Shelly statusJob stopped", thingName);
1332 profile.initialized = false;
1336 * Shutdown thing, make sure background jobs are canceled
1339 public void dispose() {
1346 * Device specific command handlers are overriding this method to do additional stuff
1348 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1353 * Device specific handlers are overriding this method to do additional stuff
1355 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1360 public String getThingName() {
1365 public void resetStats() {
1367 stats = new ShellyDeviceStats();
1371 public ShellyDeviceStats getStats() {
1376 public ShellyApiInterface getApi() {
1380 public Map<String, String> getStatsProp() {
1381 return stats.asProperties();
1385 public long getScheduledUpdates() {
1386 return scheduledUpdates;
1389 public String checkForUpdate() {
1391 ShellyOtaCheckResult result = api.checkForUpdate();
1392 return result.status;
1393 } catch (ShellyApiException e) {
1399 public void triggerUpdateFromCoap() {
1400 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1401 requestUpdates(1, false);