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.Shelly1CoapHandler;
43 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
45 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
46 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
47 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
48 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
49 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
50 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
51 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
52 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
53 import org.openhab.core.library.types.DecimalType;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.OpenClosedType;
56 import org.openhab.core.library.types.QuantityType;
57 import org.openhab.core.thing.Channel;
58 import org.openhab.core.thing.ChannelUID;
59 import org.openhab.core.thing.Thing;
60 import org.openhab.core.thing.ThingStatus;
61 import org.openhab.core.thing.ThingStatusDetail;
62 import org.openhab.core.thing.ThingTypeUID;
63 import org.openhab.core.thing.binding.BaseThingHandler;
64 import org.openhab.core.thing.binding.builder.ThingBuilder;
65 import org.openhab.core.types.Command;
66 import org.openhab.core.types.RefreshType;
67 import org.openhab.core.types.State;
68 import org.openhab.core.types.UnDefType;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
74 * sent to one of the channels.
76 * @author Markus Michels - Initial contribution
79 public class ShellyBaseHandler extends BaseThingHandler
80 implements ShellyDeviceListener, ShellyManagerInterface, ShellyThingInterface {
81 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
82 protected final ShellyChannelDefinitions channelDefinitions;
84 public String thingName = "";
85 public String thingType = "";
87 protected final ShellyApiInterface api;
88 private final HttpClient httpClient;
90 protected ShellyBindingConfiguration bindingConfig;
91 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
92 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
93 protected ShellyDeviceStats stats = new ShellyDeviceStats();
94 private final Shelly1CoapHandler coap;
95 public boolean autoCoIoT = false;
97 public final ShellyTranslationProvider messages;
98 protected boolean stopping = false;
99 private boolean channelsCreated = false;
101 private long watchdog = now();
103 private @Nullable ScheduledFuture<?> statusJob;
104 public int scheduledUpdates = 0;
105 private int skipCount = UPDATE_SKIP_COUNT;
106 private int skipUpdate = 0;
107 private boolean refreshSettings = false;
109 // delay before enabling channel
110 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
111 protected final ShellyChannelCache cache;
113 private String localIP = "";
114 private String localPort = "";
116 private String lastWakeupReason = "";
117 private int vibrationFilter = 0;
122 * @param thing The Thing object
123 * @param bindingConfig The binding configuration (beside thing
125 * @param coapServer coap server instance
126 * @param localIP local IP address from networkAddressService
127 * @param httpPort from httpService
129 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
130 final ShellyBindingConfiguration bindingConfig, final Shelly1CoapServer coapServer, final String localIP,
131 int httpPort, final HttpClient httpClient) {
134 this.thingName = getString(thing.getLabel());
135 this.messages = translationProvider;
136 this.cache = new ShellyChannelCache(this);
137 this.channelDefinitions = new ShellyChannelDefinitions(messages);
138 this.bindingConfig = bindingConfig;
139 this.config = getConfigAs(ShellyThingConfiguration.class);
141 this.httpClient = httpClient;
142 this.localIP = localIP;
143 this.localPort = String.valueOf(httpPort);
144 this.api = new Shelly1HttpApi(thingName, config, httpClient);
146 coap = new Shelly1CoapHandler(this, coapServer);
150 public boolean checkRepresentation(String key) {
151 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
152 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(thing.getUID().getAsString());
155 public String getUID() {
156 return getThing().getUID().getAsString();
160 * Schedule asynchronous Thing initialization, register thing to event dispatcher
163 public void initialize() {
164 // start background initialization:
165 scheduler.schedule(() -> {
166 boolean start = true;
168 initializeThingConfig();
169 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
170 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
171 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
173 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
174 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
175 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
176 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
177 messages.get("status.unknown.initializing"));
178 start = initializeThing();
179 } catch (ShellyApiException e) {
180 ShellyApiResult res = e.getApiResult();
181 if (isAuthorizationFailed(res)) {
184 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
185 } catch (IllegalArgumentException e) {
186 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
188 // even this initialization failed we start the status update
189 // the updateJob will then try to auto-initialize the thing
190 // in this case the thing stays in status INITIALIZING
195 }, 2, TimeUnit.SECONDS);
199 public ShellyThingConfiguration getThingConfig() {
204 public HttpClient getHttpClient() {
209 * This routine is called every time the Thing configuration has been changed
212 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
213 super.handleConfigurationUpdate(configurationParameters);
214 logger.debug("{}: Thing config updated, re-initialize", thingName);
216 requestUpdates(1, true);// force re-initialization
220 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
221 * If the device is password protected and the credentials are missing or don't match the API access will throw an
222 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
223 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
224 * credentials are correct and the API access is initialized successful.
226 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
228 private boolean initializeThing() throws ShellyApiException {
229 // Init from thing type to have a basic profile, gets updated when device info is received from API
231 refreshSettings = false;
232 lastWakeupReason = "";
233 profile.initFromThingType(thingType);
234 api.setConfig(thingName, config);
235 cache.setThingName(thingName);
238 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
239 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
240 if (config.deviceIp.isEmpty()) {
241 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
245 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
246 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
248 if (config.eventsCoIoT && !profile.alwaysOn) {
249 coap.start(thingName, config);
252 // Initialize API access, exceptions will be catched by initialize()
253 ShellySettingsDevice devInfo = api.getDeviceInfo();
254 if (getBool(devInfo.auth) && config.userId.isEmpty()) {
255 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
258 if (config.serviceName.isEmpty()) {
259 config.serviceName = getString(profile.hostname).toLowerCase();
262 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
263 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
264 changeThingType(thingName, tmpPrf.mode);
265 return false; // force re-initialization
267 // Validate device mode
268 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
269 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
270 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
273 if (!getString(devInfo.coiot).isEmpty()) {
274 // New Shelly devices might use a different endpoint for the CoAP listener
275 tmpPrf.coiotEndpoint = devInfo.coiot;
277 tmpPrf.auth = devInfo.auth; // missing in /settings
278 tmpPrf.status = api.getStatus();
279 tmpPrf.updateFromStatus(tmpPrf.status);
281 showThingConfig(tmpPrf);
282 checkVersion(tmpPrf, tmpPrf.status);
284 if (config.eventsCoIoT && (tmpPrf.settings.coiot != null) && (tmpPrf.settings.coiot.enabled != null)) {
285 String devpeer = getString(tmpPrf.settings.coiot.peer);
286 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
287 if (!tmpPrf.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
289 api.setCoIoTPeer(ourpeer);
290 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
291 } catch (ShellyApiException e) {
292 logger.warn("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
294 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
295 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
299 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
300 config.eventsCoIoT = true;
301 config.eventsSwitch = false;
302 config.eventsButton = false;
303 config.eventsPush = false;
304 config.eventsRoller = false;
305 config.eventsSensorReport = false;
306 api.setConfig(thingName, config);
309 // All initialization done, so keep the profile and set Thing to ONLINE
310 fillDeviceStatus(tmpPrf.status, false);
311 postEvent(ALARM_TYPE_NONE, false);
312 api.setActionURLs(); // register event urls
313 if (config.eventsCoIoT) {
314 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
315 coap.start(thingName, config);
318 logger.debug("{}: Thing successfully initialized.", thingName);
321 updateProperties(tmpPrf, tmpPrf.status);
322 setThingOnline(); // if API call was successful the thing must be online
323 return true; // success
326 private void showThingConfig(ShellyDeviceProfile profile) {
327 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
328 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
330 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
331 logger.debug("{}: Device "
332 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
333 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
334 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
335 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter, profile.isSensor,
336 profile.isDW, profile.hasBattery,
337 profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
338 profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
339 profile.alwaysOn, profile.updatePeriod);
343 * Handle Channel Commands
346 public void handleCommand(ChannelUID channelUID, Command command) {
348 if (command instanceof RefreshType) {
349 String channelId = channelUID.getId();
350 State value = cache.getValue(channelId);
351 if (value != UnDefType.NULL) {
352 updateState(channelId, value);
357 if (!profile.isInitialized()) {
358 logger.debug("{}: {}", thingName, messages.get("command.init", command));
361 profile = getProfile(false);
364 boolean update = false;
365 switch (channelUID.getIdWithoutGroup()) {
366 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
367 logger.debug("{}: Send key {}", thingName, command);
368 api.sendIRKey(command.toString());
372 case CHANNEL_LED_STATUS_DISABLE:
373 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
374 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
376 case CHANNEL_LED_POWER_DISABLE:
377 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
378 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
381 case CHANNEL_SENSOR_SLEEPTIME:
382 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
383 int value = (int) getNumber(command);
384 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
386 api.setSleepTime(value);
388 case CHANNEL_CONTROL_PROFILE:
389 logger.debug("{}: Select profile {}", thingName, command);
390 int profile = (int) getNumber(command);
391 if (profile < 0 || profile > 5) {
392 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
395 api.setValveProfile(0, profile);
397 case CHANNEL_CONTROL_MODE:
398 logger.debug("{}: Set mode to {}", thingName, command);
399 api.setValveMode(0, SHELLY_TRV_MODE_AUTO.equalsIgnoreCase(command.toString()));
401 case CHANNEL_CONTROL_SETTEMP:
402 logger.debug("{}: Set temperature to {}", thingName, command);
403 api.setValveTemperature(0, (int) getNumber(command));
405 case CHANNEL_CONTROL_POSITION:
406 logger.debug("{}: Set position to {}", thingName, command);
407 api.setValvePosition(0, getNumber(command));
409 case CHANNEL_CONTROL_BCONTROL:
410 logger.debug("{}: Set boost mode to {}", thingName, command);
411 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
413 case CHANNEL_CONTROL_BTIMER:
414 logger.debug("{}: Set boost timer to {}", thingName, command);
415 api.setValveBoostTime(0, (int) getNumber(command));
419 update = handleDeviceCommand(channelUID, command);
424 if (update && !autoCoIoT && !isUpdateScheduled()) {
425 logger.debug("{}: Command processed, request status update", thingName);
426 requestUpdates(1, false);
428 } catch (ShellyApiException e) {
429 ShellyApiResult res = e.getApiResult();
430 if (isAuthorizationFailed(res)) {
433 if (res.isNotCalibrtated()) {
434 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
436 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
439 } catch (IllegalArgumentException e) {
440 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
444 private double getNumber(Command command) {
445 if (command instanceof QuantityType) {
446 return ((QuantityType<?>) command).doubleValue();
448 if (command instanceof DecimalType) {
449 return ((DecimalType) command).doubleValue();
451 if (command instanceof Number) {
452 return ((Number) command).doubleValue();
454 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
458 * Update device status and channels
460 protected void refreshStatus() {
462 boolean updated = false;
464 if (vibrationFilter > 0) {
466 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
467 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
471 ThingStatus thingStatus = getThing().getStatus();
472 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
473 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
474 || (thingStatus == ThingStatus.UNKNOWN)) {
475 logger.debug("{}: Status update triggered thing initialization", thingName);
476 initializeThing(); // may fire an exception if initialization failed
478 // Get profile, if refreshSettings == true reload settings from device
479 logger.trace("{}: Updating status (scheduledUpdates={}, refreshSettings={})", thingName,
480 scheduledUpdates, refreshSettings);
481 ShellySettingsStatus status = api.getStatus();
482 boolean restarted = checkRestarted(status);
483 profile = getProfile(refreshSettings || restarted);
484 profile.status = status;
485 profile.updateFromStatus(status);
487 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
489 postEvent(ALARM_TYPE_RESTARTED, true);
492 // If status update was successful the thing must be online
495 // map status to channels
496 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
497 updated |= this.updateDeviceStatus(status);
498 updated |= ShellyComponents.updateDeviceStatus(this, status);
499 fillDeviceStatus(status, updated);
500 updated |= updateInputs(status);
501 updated |= updateMeters(this, status);
502 updated |= updateSensors(this, status);
504 // All channels must be created after the first cycle
505 channelsCreated = true;
507 } catch (ShellyApiException e) {
508 // http call failed: go offline except for battery devices, which might be in
509 // sleep mode. Once the next update is successful the device goes back online
511 ShellyApiResult res = e.getApiResult();
512 if (isWatchdogStarted()) {
513 if (!isWatchdogExpired()) {
514 logger.debug("{}: Ignore API Timeout, retry later", thingName);
516 if (isThingOnline()) {
517 status = "offline.status-error-watchdog";
520 } else if (res.isHttpAccessUnauthorized()) {
521 status = "offline.conf-error-access-denied";
522 } else if (e.isJSONException()) {
523 status = "offline.status-error-unexpected-api-result";
524 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
525 } else if (res.isHttpTimeout()) {
526 // Watchdog not started, e.g. device in sleep mode
527 if (isThingOnline()) { // ignore when already offline
528 status = "offline.status-error-watchdog";
531 status = "offline.status-error-unexpected-api-result";
532 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
535 if (!status.isEmpty()) {
536 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
538 } catch (NullPointerException | IllegalArgumentException e) {
539 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
541 if (scheduledUpdates > 0) {
543 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
544 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
545 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
546 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
552 public boolean isThingOnline() {
553 return getThing().getStatus() == ThingStatus.ONLINE;
556 public boolean isThingOffline() {
557 return getThing().getStatus() == ThingStatus.OFFLINE;
561 public void setThingOnline() {
563 logger.debug("{}: Thing should go ONLINE, but handler is shutting down, ignore!", thingName);
566 if (!isThingOnline()) {
567 updateStatus(ThingStatus.ONLINE);
569 // request 3 updates in a row (during the first 2+3*3 sec)
570 logger.debug("{}: Thing went online, request status update", thingName);
571 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
577 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
578 String message = messages.get(messageKey);
580 logger.debug("{}: Thing should go OFFLINE with status {}, but handler is shutting down -> ignore",
585 if (!isThingOffline()) {
586 updateStatus(ThingStatus.OFFLINE, detail, message);
588 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
593 public void restartWatchdog() {
595 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
596 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
599 private boolean isWatchdogExpired() {
600 long delta = now() - watchdog;
601 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
602 stats.remainingWatchdog = delta;
608 private boolean isWatchdogStarted() {
613 public void reinitializeThing() {
614 logger.debug("{}: Re-Initialize Thing", thingName);
616 logger.debug("{}: Handler is shutting down, ignore", thingName);
619 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
620 messages.get("offline.status-error-restarted"));
621 requestUpdates(0, true);
625 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
628 // Update uptime and WiFi, internal temp
629 ShellyComponents.updateDeviceStatus(this, status);
630 stats.wifiRssi = status.wifiSta.rssi;
632 if (api.isInitialized()) {
633 stats.timeoutErrors = api.getTimeoutErrors();
634 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
636 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
638 // Check various device indicators like overheating
639 if (checkRestarted(status)) {
640 // Force re-initialization on next status update
642 } else if (getBool(status.overtemperature)) {
643 alarm = ALARM_TYPE_OVERTEMP;
644 } else if (getBool(status.overload)) {
645 alarm = ALARM_TYPE_OVERLOAD;
646 } else if (getBool(status.loaderror)) {
647 alarm = ALARM_TYPE_LOADERR;
649 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
650 if (internalTemp != UnDefType.NULL) {
651 int temp = ((Number) internalTemp).intValue();
652 if (temp > stats.maxInternalTemp) {
653 stats.maxInternalTemp = temp;
657 if (status.uptime != null) {
658 stats.lastUptime = getLong(status.uptime);
660 stats.coiotMessages = coap.getMessageCount();
661 stats.coiotErrors = coap.getErrorCount();
663 if (!alarm.isEmpty()) {
664 postEvent(alarm, false);
669 * Check if device has restarted and needs a new Thing initialization
671 * @return true: restart detected
674 private boolean checkRestarted(ShellySettingsStatus status) {
675 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
676 && (status.uptime != null && status.uptime < stats.lastUptime
677 || !profile.status.update.oldVersion.isEmpty()
678 && !status.update.oldVersion.equals(profile.status.update.oldVersion))) {
679 updateProperties(profile, status);
686 * Save alarm to the lastAlarm channel
688 * @param alarm Alarm Message
691 public void postEvent(String event, boolean force) {
692 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
693 State value = cache.getValue(channelId);
694 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
696 if (force || !lastAlarm.equals(event)
697 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
701 case SHELLY_WAKEUPT_SENSOR:
702 case SHELLY_WAKEUPT_PERIODIC:
703 case SHELLY_WAKEUPT_BUTTON:
704 case SHELLY_WAKEUPT_POWERON:
705 case SHELLY_WAKEUPT_EXT_POWER:
706 case SHELLY_WAKEUPT_UNKNOWN:
707 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
708 case ALARM_TYPE_NONE:
711 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
712 triggerChannel(channelId, event);
713 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
714 stats.lastAlarm = event;
715 stats.lastAlarmTs = now();
722 * Callback for device events
724 * @param deviceName device receiving the event
725 * @param parameters parameters from the event URL
726 * @param data the HTML input data
727 * @return true if event was processed
730 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
731 Map<String, String> parameters) {
732 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
733 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
735 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
736 if (!profile.isInitialized()) {
737 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
738 requestUpdates(1, true);
740 String group = profile.getControlGroup(idx);
741 if (group.isEmpty()) {
742 logger.debug("{}: Unsupported event class: {}", thingName, type);
746 // map some of the events to system defined button triggers
750 String parmType = getString(parameters.get("type"));
751 String event = !parmType.isEmpty() ? parmType : type;
752 boolean isButton = profile.inButtonMode(idx - 1);
754 case SHELLY_EVENT_SHORTPUSH:
755 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
756 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
757 case SHELLY_EVENT_LONGPUSH:
759 triggerButton(group, idx, mapButtonEvent(event));
760 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
761 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
763 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
767 case SHELLY_EVENT_BTN_ON:
768 case SHELLY_EVENT_BTN_OFF:
769 if (profile.isRGBW2) {
770 // RGBW2 has only one input, so not per channel
771 group = CHANNEL_GROUP_LIGHT_CONTROL;
773 onoff = CHANNEL_INPUT;
775 case SHELLY_EVENT_BTN1_ON:
776 case SHELLY_EVENT_BTN1_OFF:
777 onoff = CHANNEL_INPUT1;
779 case SHELLY_EVENT_BTN2_ON:
780 case SHELLY_EVENT_BTN2_OFF:
781 onoff = CHANNEL_INPUT2;
783 case SHELLY_EVENT_OUT_ON:
784 case SHELLY_EVENT_OUT_OFF:
785 onoff = CHANNEL_OUTPUT;
787 case SHELLY_EVENT_ROLLER_OPEN:
788 case SHELLY_EVENT_ROLLER_CLOSE:
789 case SHELLY_EVENT_ROLLER_STOP:
790 channel = CHANNEL_EVENT_TRIGGER;
793 case SHELLY_EVENT_SENSORREPORT:
794 // process sensor with next refresh
796 case SHELLY_EVENT_TEMP_OVER: // DW2
797 case SHELLY_EVENT_TEMP_UNDER:
798 channel = CHANNEL_EVENT_TRIGGER;
801 case SHELLY_EVENT_FLOOD_DETECTED:
802 case SHELLY_EVENT_FLOOD_GONE:
803 updateChannel(group, CHANNEL_SENSOR_FLOOD,
804 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
807 case SHELLY_EVENT_CLOSE: // DW 1.7
808 case SHELLY_EVENT_OPEN: // DW 1.7
809 updateChannel(group, CHANNEL_SENSOR_STATE,
810 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
811 : OpenClosedType.CLOSED);
814 case SHELLY_EVENT_DARK: // DW 1.7
815 case SHELLY_EVENT_TWILIGHT: // DW 1.7
816 case SHELLY_EVENT_BRIGHT: // DW 1.7
817 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
820 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
821 case SHELLY_EVENT_ALARM_HEAVY:
822 case SHELLY_EVENT_ALARM_OFF:
823 case SHELLY_EVENT_VIBRATION: // DW2
824 channel = CHANNEL_SENSOR_ALARM_STATE;
825 payload = event.toUpperCase();
829 // trigger will be provided by input/output channel or sensor channels
832 if (!onoff.isEmpty()) {
833 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
835 if (!payload.isEmpty()) {
836 // Pass event to trigger channel
837 payload = payload.toUpperCase();
838 logger.debug("{}: Post event {}", thingName, payload);
839 triggerChannel(mkChannelId(group, channel), payload);
843 // request update on next interval (2x for non-battery devices)
845 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
852 * Initialize the binding's thing configuration, calc update counts
854 protected void initializeThingConfig() {
855 thingType = getThing().getThingTypeUID().getId();
856 final Map<String, String> properties = getThing().getProperties();
857 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
858 if (thingName.isEmpty()) {
859 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
860 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
863 config = getConfigAs(ShellyThingConfiguration.class);
864 if (config.deviceIp.isEmpty()) {
865 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
869 InetAddress addr = InetAddress.getByName(config.deviceIp);
870 String saddr = addr.getHostAddress();
871 if (!config.deviceIp.equals(saddr)) {
872 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
873 config.deviceIp = saddr;
875 } catch (UnknownHostException e) {
876 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
879 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
880 config.localIp = localIP;
881 config.localPort = localPort;
882 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
883 config.userId = bindingConfig.defaultUserId;
884 config.password = bindingConfig.defaultPassword;
885 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
887 if (config.updateInterval == 0) {
888 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
890 if (config.updateInterval < UPDATE_MIN_DELAY) {
891 config.updateInterval = UPDATE_MIN_DELAY;
894 // Try to get updatePeriod from properties
895 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
896 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
897 // initialized successfully by the REST call.
898 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
899 if (!lastPeriod.isEmpty()) {
900 int period = Integer.parseInt(lastPeriod);
902 profile.updatePeriod = period;
906 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
907 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
910 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
912 ShellyVersionDTO version = new ShellyVersionDTO();
913 if (version.checkBeta(getString(prf.fwVersion))) {
914 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
916 if ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) && !profile.isMotion) {
917 logger.warn("{}: {}", prf.hostname,
918 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, SHELLY_API_MIN_FWVERSION));
921 if (bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
922 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
923 if (!config.eventsCoIoT) {
924 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
928 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
929 logger.info("{}: {}", thingName,
930 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
932 } catch (NullPointerException e) { // could be inconsistant format of beta version
933 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
938 * Checks the http response for authorization error.
939 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
940 * case the thing type shelly-unknown is set.
942 * @param response exception details including the http respone
943 * @return true if the authorization failed
945 protected boolean isAuthorizationFailed(ShellyApiResult result) {
946 if (result.isHttpAccessUnauthorized()) {
947 // If the device is password protected the API doesn't provide settings to the device settings
948 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
955 * Change type of this thing.
957 * @param thingType thing type acc. to the xml definition
958 * @param mode Device mode (e.g. relay, roller)
960 private void changeThingType(String thingType, String mode) {
961 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
962 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
963 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
964 Map<String, String> properties = editProperties();
965 properties.replace(PROPERTY_DEV_TYPE, thingType);
966 properties.replace(PROPERTY_DEV_MODE, mode);
967 updateProperties(properties);
968 changeThingType(thingTypeUID, getConfig());
973 public void thingUpdated(Thing thing) {
974 logger.debug("{}: Channel definitions updated.", thingName);
975 super.thingUpdated(thing);
979 * Start the background updates
981 protected void startUpdateJob() {
982 ScheduledFuture<?> statusJob = this.statusJob;
983 if ((statusJob == null) || statusJob.isCancelled()) {
984 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
986 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
987 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
992 * Flag the status job to do an exceptional update (something happened) rather
993 * than waiting until the next regular poll
995 * @param requestCount number of polls to execute
996 * @param refreshSettings true=force a /settings query
997 * @return true=Update schedule, false=skipped (too many updates already
1001 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1002 this.refreshSettings |= refreshSettings;
1003 if (refreshSettings) {
1004 if (requestCount == 0) {
1005 logger.debug("{}: Request settings refresh", thingName);
1007 scheduledUpdates = 1;
1010 if (scheduledUpdates < 10) { // < 30s
1011 scheduledUpdates += requestCount;
1017 public boolean isUpdateScheduled() {
1018 return scheduledUpdates > 0;
1022 * Map input states to channels
1024 * @param groupName Channel Group (relay / relay1...)
1026 * @param status Shelly device status
1027 * @return true: one or more inputs were updated
1030 public boolean updateInputs(ShellySettingsStatus status) {
1031 boolean updated = false;
1033 if (status.inputs != null) {
1035 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
1036 for (ShellyInputState input : status.inputs) {
1037 String group = profile.getControlGroup(idx);
1038 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1040 if (!areChannelsCreated()) {
1041 updateChannelDefinitions(
1042 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
1045 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1046 if (input.event != null) {
1047 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1048 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1053 if (status.input != null) {
1054 // RGBW2: a single int rather than an array
1055 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1056 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1063 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1064 boolean changed = false;
1065 if (valueArray != null && !valueArray.isEmpty()) {
1066 String reason = getString((String) valueArray.get(0));
1067 String newVal = valueArray.toString();
1068 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1069 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1071 postEvent(reason.toUpperCase(), true);
1073 lastWakeupReason = newVal;
1079 public void triggerButton(String group, int idx, String value) {
1080 String trigger = mapButtonEvent(value);
1081 if (trigger.isEmpty()) {
1085 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1086 triggerChannel(group,
1087 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1089 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1090 if (profile.alwaysOn) {
1091 // refresh status of the input channel
1092 requestUpdates(1, false);
1097 public void publishState(String channelId, State value) {
1098 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1099 if (!stopping && isLinked(id)) {
1100 updateState(id, value);
1101 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1106 public boolean updateChannel(String group, String channel, State value) {
1107 return updateChannel(mkChannelId(group, channel), value, false);
1111 public boolean updateChannel(String channelId, State value, boolean force) {
1112 return !stopping && cache.updateChannel(channelId, value, force);
1116 public State getChannelValue(String group, String channel) {
1117 return cache.getValue(group, channel);
1121 public double getChannelDouble(String group, String channel) {
1122 State value = getChannelValue(group, channel);
1123 if (value != UnDefType.NULL) {
1124 if (value instanceof QuantityType) {
1125 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1127 if (value instanceof DecimalType) {
1128 return ((DecimalType) value).doubleValue();
1135 * Update Thing's channels according to available status information from the API
1137 * @param thingHandler
1140 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1141 if (channelsCreated) {
1142 return; // already done
1146 // Get subset of those channels that currently do not exist
1147 List<Channel> existingChannels = getThing().getChannels();
1148 for (Channel channel : existingChannels) {
1149 String id = channel.getUID().getId();
1150 if (dynChannels.containsKey(id)) {
1151 dynChannels.remove(id);
1155 if (!dynChannels.isEmpty()) {
1156 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1157 ThingBuilder thingBuilder = editThing();
1158 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1159 Channel c = channel.getValue();
1160 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1161 thingBuilder.withChannel(c);
1163 updateThing(thingBuilder.build());
1164 logger.debug("{}: Channel definitions updated", thingName);
1166 } catch (IllegalArgumentException e) {
1167 logger.debug("{}: Unable to update channel definitions", thingName, e);
1172 public boolean areChannelsCreated() {
1173 return channelsCreated;
1177 * Update thing properties with dynamic values
1179 * @param profile The device profile
1180 * @param status the /status result
1182 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1183 logger.debug("{}: Update properties", thingName);
1184 Map<String, Object> properties = fillDeviceProperties(profile);
1185 String deviceName = getString(profile.settings.name);
1186 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1187 properties.put(PROPERTY_DEV_GEN, "1");
1188 if (!deviceName.isEmpty()) {
1189 properties.put(PROPERTY_DEV_NAME, deviceName);
1192 // add status properties
1193 if (status.wifiSta != null) {
1194 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1196 if (status.update != null) {
1197 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1198 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1199 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1200 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1202 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1204 Map<String, String> thingProperties = new TreeMap<>();
1205 for (Map.Entry<String, Object> property : properties.entrySet()) {
1206 thingProperties.put(property.getKey(), (String) property.getValue());
1208 flushProperties(thingProperties);
1212 * Add one property to the Thing Properties
1214 * @param key Name of the property
1215 * @param value Value of the property
1218 public void updateProperties(String key, String value) {
1219 Map<String, String> thingProperties = editProperties();
1220 if (thingProperties.containsKey(key)) {
1221 thingProperties.replace(key, value);
1223 thingProperties.put(key, value);
1225 updateProperties(thingProperties);
1226 logger.trace("{}: Properties updated", thingName);
1229 public void flushProperties(Map<String, String> propertyUpdates) {
1230 Map<String, String> thingProperties = editProperties();
1231 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1232 if (thingProperties.containsKey(property.getKey())) {
1233 thingProperties.replace(property.getKey(), property.getValue());
1235 thingProperties.put(property.getKey(), property.getValue());
1238 updateProperties(thingProperties);
1242 * Get one property from the Thing Properties
1244 * @param key property name
1245 * @return property value or "" if property is not set
1248 public String getProperty(String key) {
1249 Map<String, String> thingProperties = getThing().getProperties();
1250 return getString(thingProperties.get(key));
1254 * Fill Thing Properties with device attributes
1256 * @param profile Property Map to full
1257 * @return a full property map
1259 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1260 Map<String, Object> properties = new TreeMap<>();
1261 properties.put(PROPERTY_VENDOR, VENDOR);
1262 if (profile.isInitialized()) {
1263 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1264 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1265 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1266 properties.put(PROPERTY_DEV_MODE, profile.mode);
1267 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1268 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1269 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1270 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1271 if (!profile.hwRev.isEmpty()) {
1272 properties.put(PROPERTY_HWREV, profile.hwRev);
1273 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1280 * Return device profile.
1282 * @param ForceRefresh true=force refresh before returning, false=return without
1284 * @return ShellyDeviceProfile instance
1285 * @throws ShellyApiException
1288 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1290 refreshSettings |= forceRefresh;
1291 if (refreshSettings) {
1292 profile = api.getDeviceProfile(thingType);
1293 if (!isThingOnline()) {
1294 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1298 refreshSettings = false;
1304 public ShellyDeviceProfile getProfile() {
1308 protected ShellyDeviceProfile getDeviceProfile() {
1313 public void triggerChannel(String group, String channel, String payload) {
1314 String triggerCh = mkChannelId(group, channel);
1315 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1316 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1317 if (vibrationFilter == 0) {
1318 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1319 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1320 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1322 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1323 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1328 triggerChannel(triggerCh, payload);
1331 public void stop() {
1332 logger.debug("{}: Shutting down", thingName);
1333 ScheduledFuture<?> job = this.statusJob;
1337 logger.debug("{}: Shelly statusJob stopped", thingName);
1341 profile.initialized = false;
1345 * Shutdown thing, make sure background jobs are canceled
1348 public void dispose() {
1355 * Device specific command handlers are overriding this method to do additional stuff
1357 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1362 * Device specific handlers are overriding this method to do additional stuff
1364 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1369 public String getThingName() {
1374 public void resetStats() {
1376 stats = new ShellyDeviceStats();
1380 public ShellyDeviceStats getStats() {
1385 public ShellyApiInterface getApi() {
1389 public Map<String, String> getStatsProp() {
1390 return stats.asProperties();
1394 public long getScheduledUpdates() {
1395 return scheduledUpdates;
1398 public String checkForUpdate() {
1400 ShellyOtaCheckResult result = api.checkForUpdate();
1401 return result.status;
1402 } catch (ShellyApiException e) {
1408 public void triggerUpdateFromCoap() {
1409 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1410 requestUpdates(1, false);