2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.handler;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
19 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
20 import static org.openhab.core.thing.Thing.*;
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.util.List;
26 import java.util.TreeMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.shelly.internal.api.ShellyApiException;
34 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
35 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
36 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
47 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
48 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
49 import org.openhab.binding.shelly.internal.api2.ShellyBluApi;
50 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
51 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
52 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
53 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
54 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
55 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
56 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
57 import org.openhab.core.library.types.DecimalType;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.library.types.OpenClosedType;
60 import org.openhab.core.library.types.QuantityType;
61 import org.openhab.core.thing.Channel;
62 import org.openhab.core.thing.ChannelUID;
63 import org.openhab.core.thing.Thing;
64 import org.openhab.core.thing.ThingStatus;
65 import org.openhab.core.thing.ThingStatusDetail;
66 import org.openhab.core.thing.ThingTypeUID;
67 import org.openhab.core.thing.binding.BaseThingHandler;
68 import org.openhab.core.thing.binding.builder.ThingBuilder;
69 import org.openhab.core.thing.type.ChannelTypeUID;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.openhab.core.types.State;
73 import org.openhab.core.types.StateOption;
74 import org.openhab.core.types.UnDefType;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
80 * sent to one of the channels.
82 * @author Markus Michels - Initial contribution
85 public abstract class ShellyBaseHandler extends BaseThingHandler
86 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
88 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
89 protected final ShellyChannelDefinitions channelDefinitions;
91 public String thingName = "";
92 public String thingType = "";
94 protected final ShellyApiInterface api;
95 private final HttpClient httpClient;
97 private ShellyBindingConfiguration bindingConfig;
98 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
99 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
100 private ShellyDeviceStats stats = new ShellyDeviceStats();
101 private @Nullable Shelly1CoapHandler coap;
103 private final ShellyTranslationProvider messages;
104 private final ShellyChannelCache cache;
105 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
107 private boolean gen2 = false;
108 private final boolean blu;
109 protected boolean autoCoIoT = false;
112 private boolean channelsCreated = false;
113 private boolean stopping = false;
114 private int vibrationFilter = 0;
115 private String lastWakeupReason = "";
118 private long watchdog = now();
119 protected int scheduledUpdates = 0;
120 private int skipCount = UPDATE_SKIP_COUNT;
121 private int skipUpdate = 0;
122 private boolean refreshSettings = false;
123 private @Nullable ScheduledFuture<?> statusJob;
124 private @Nullable ScheduledFuture<?> initJob;
129 * @param thing The Thing object
130 * @param translationProvider
131 * @param bindingConfig The binding configuration (beside thing
134 * @param coapServer coap server instance
135 * @param httpClient from httpService
137 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
138 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
139 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
142 this.thingName = getString(thing.getLabel());
143 this.messages = translationProvider;
144 this.cache = new ShellyChannelCache(this);
145 this.channelDefinitions = new ShellyChannelDefinitions(messages);
146 this.bindingConfig = bindingConfig;
147 this.config = getConfigAs(ShellyThingConfiguration.class);
148 this.httpClient = httpClient;
150 Map<String, String> properties = thing.getProperties();
151 String gen = getString(properties.get(PROPERTY_DEV_GEN));
152 String thingType = getThingType();
153 gen2 = "2".equals(gen) || ShellyDeviceProfile.isGeneration2(thingType);
154 blu = ShellyDeviceProfile.isBluSeries(thingType);
155 this.api = !blu ? !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this)
156 : new ShellyBluApi(thingName, thingTable, this);
158 config.eventsCoIoT = false;
160 if (config.eventsCoIoT) {
161 this.coap = new Shelly1CoapHandler(this, coapServer);
166 public boolean checkRepresentation(String key) {
167 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
168 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
172 * Schedule asynchronous Thing initialization, register thing to event dispatcher
175 public void initialize() {
176 // start background initialization:
177 initJob = scheduler.schedule(() -> {
178 boolean start = true;
180 initializeThingConfig();
181 logger.debug("{}: Device config: Device address={}, HTTP user/password={}/{}, update interval={}",
182 thingName, config.deviceAddress, config.userId.isEmpty() ? "<non>" : config.userId,
183 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
185 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
186 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
187 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
188 start = initializeThing();
189 } catch (ShellyApiException e) {
190 ShellyApiResult res = e.getApiResult();
192 if (e.isJsonError()) { // invalid JSON format
193 mid = "offline.status-error-unexpected-error";
195 } else if (isAuthorizationFailed(res)) {
196 mid = "offline.conf-error-access-denied";
198 } else if (profile.alwaysOn && e.isConnectionError()) {
199 mid = "offline.status-error-connect";
201 if (!mid.isEmpty()) {
202 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
204 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
205 } catch (IllegalArgumentException e) {
206 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
208 // even this initialization failed we start the status update
209 // the updateJob will then try to auto-initialize the thing
210 // in this case the thing stays in status INITIALIZING
215 }, 2, TimeUnit.SECONDS);
219 public ShellyThingConfiguration getThingConfig() {
224 public HttpClient getHttpClient() {
229 public void startScan() {
230 if (api.isInitialized()) {
236 * This routine is called every time the Thing configuration has been changed
239 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
240 super.handleConfigurationUpdate(configurationParameters);
241 logger.debug("{}: Thing config updated, re-initialize", thingName);
246 reinitializeThing();// force re-initialization
250 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
251 * If the device is password protected and the credentials are missing or don't match the API access will throw an
252 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
253 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
254 * credentials are correct and the API access is initialized successful.
256 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
258 public boolean initializeThing() throws ShellyApiException {
259 // Init from thing type to have a basic profile, gets updated when device info is received from API
260 refreshSettings = false;
261 lastWakeupReason = "";
262 cache.setThingName(thingName);
266 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
267 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
268 if (config.deviceAddress.isEmpty()) {
269 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
273 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
274 messages.get("status.unknown.initializing"));
276 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
277 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
278 // Action URL does when enabled)
279 profile.initFromThingType(thingType);
280 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
281 coap.start(thingName, config);
284 // Initialize API access, exceptions will be catched by initialize()
286 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
287 if (getBool(device.auth) && config.password.isEmpty()) {
288 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
291 if (config.serviceName.isEmpty()) {
292 config.serviceName = getString(device.hostname).toLowerCase();
295 api.setConfig(thingName, config);
296 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
297 String mode = getString(tmpPrf.device.mode);
298 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
299 changeThingType(thingName, mode);
300 return false; // force re-initialization
302 // Validate device mode
303 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
304 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
305 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode, reqMode);
308 if (!getString(tmpPrf.device.coiot).isEmpty()) {
309 // New Shelly devices might use a different endpoint for the CoAP listener
310 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
312 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
313 // Sensor, usually 12h, H&T in USB mode 10min
314 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
315 ? tmpPrf.settings.sleepMode.period * 60 // minutes
316 : tmpPrf.settings.sleepMode.period * 3600; // hours
317 tmpPrf.updatePeriod += 60; // give 1min extra
318 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
319 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
320 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
321 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
323 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
326 tmpPrf.status = api.getStatus(); // update thing properties
327 tmpPrf.updateFromStatus(tmpPrf.status);
328 addStateOptions(tmpPrf);
330 // update thing properties
331 updateProperties(tmpPrf, tmpPrf.status);
332 checkVersion(tmpPrf, tmpPrf.status);
334 startCoap(config, tmpPrf);
336 api.setActionURLs(); // register event urls
339 // All initialization done, so keep the profile and set Thing to ONLINE
340 fillDeviceStatus(tmpPrf.status, false);
341 postEvent(ALARM_TYPE_NONE, false);
344 showThingConfig(profile);
346 logger.debug("{}: Thing successfully initialized.", thingName);
347 updateProperties(profile, profile.status);
348 setThingOnline(); // if API call was successful the thing must be online
349 return true; // success
353 * Handle Channel Commands
356 public void handleCommand(ChannelUID channelUID, Command command) {
358 if (command instanceof RefreshType) {
359 String channelId = channelUID.getId();
360 State value = cache.getValue(channelId);
361 if (value != UnDefType.NULL) {
362 updateState(channelId, value);
367 if (!profile.isInitialized()) {
368 logger.debug("{}: {}", thingName, messages.get("command.init", command));
371 profile = getProfile(false);
374 boolean update = false;
375 switch (channelUID.getIdWithoutGroup()) {
376 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
377 logger.debug("{}: Send key {}", thingName, command);
378 api.sendIRKey(command.toString());
382 case CHANNEL_LED_STATUS_DISABLE:
383 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
384 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
386 case CHANNEL_LED_POWER_DISABLE:
387 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
388 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
391 case CHANNEL_SENSOR_SLEEPTIME:
392 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
393 int value = (int) getNumber(command);
394 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
396 api.setSleepTime(value);
398 case CHANNEL_CONTROL_SCHEDULE:
400 logger.debug("{}: {} Valve schedule/profile", thingName,
401 command == OnOffType.ON ? "Enable" : "Disable");
402 api.setValveProfile(0,
403 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
406 case CHANNEL_CONTROL_PROFILE:
407 logger.debug("{}: Select profile {}", thingName, command);
409 if (command instanceof Number) {
410 id = (int) getNumber(command);
412 String cmd = command.toString();
413 if (isDigit(cmd.charAt(0))) {
414 id = Integer.parseInt(cmd);
415 } else if (profile.settings.thermostats != null) {
416 ShellyThermnostat t = profile.settings.thermostats.get(0);
417 for (int i = 0; i < t.profileNames.length; i++) {
418 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
424 if (id < 0 || id > 5) {
425 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
428 api.setValveProfile(0, id);
430 case CHANNEL_CONTROL_MODE:
431 logger.debug("{}: Set mode to {}", thingName, command);
432 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
434 case CHANNEL_CONTROL_SETTEMP:
435 logger.debug("{}: Set temperature to {}", thingName, command);
436 api.setValveTemperature(0, (int) getNumber(command));
438 case CHANNEL_CONTROL_POSITION:
439 logger.debug("{}: Set position to {}", thingName, command);
440 api.setValvePosition(0, getNumber(command));
442 case CHANNEL_CONTROL_BCONTROL:
443 logger.debug("{}: Set boost mode to {}", thingName, command);
444 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
446 case CHANNEL_CONTROL_BTIMER:
447 logger.debug("{}: Set boost timer to {}", thingName, command);
448 api.setValveBoostTime(0, (int) getNumber(command));
450 case CHANNEL_SENSOR_MUTE:
451 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
452 logger.debug("{}: Mute Smoke Alarm", thingName);
453 api.muteSmokeAlarm(0);
454 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
458 update = handleDeviceCommand(channelUID, command);
463 if (update && !autoCoIoT && !isUpdateScheduled()) {
464 requestUpdates(1, false);
466 } catch (ShellyApiException e) {
467 ShellyApiResult res = e.getApiResult();
468 if (isAuthorizationFailed(res)) {
471 if (res.isNotCalibrtated()) {
472 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
474 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
478 String group = getString(channelUID.getGroupId());
479 String channel = getString(channelUID.getIdWithoutGroup());
480 State oldValue = getChannelValue(group, channel);
481 if (oldValue != UnDefType.NULL) {
482 logger.info("{}: Restore channel value to {}", thingName, oldValue);
483 updateChannel(group, channel, oldValue);
486 } catch (IllegalArgumentException e) {
487 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
491 private double getNumber(Command command) {
492 if (command instanceof QuantityType quantityCommand) {
493 return quantityCommand.doubleValue();
495 if (command instanceof DecimalType decimalCommand) {
496 return decimalCommand.doubleValue();
498 if (command instanceof Number numberCommand) {
499 return numberCommand.doubleValue();
501 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
505 * Update device status and channels
507 protected void refreshStatus() {
509 boolean updated = false;
511 if (vibrationFilter > 0) {
513 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
514 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
518 ThingStatus thingStatus = getThing().getStatus();
519 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
520 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
521 || (thingStatus == ThingStatus.UNKNOWN)) {
522 logger.debug("{}: Status update triggered thing initialization", thingName);
523 initializeThing(); // may fire an exception if initialization failed
525 ShellySettingsStatus status = api.getStatus();
526 boolean restarted = checkRestarted(status);
527 profile = getProfile(refreshSettings || restarted);
528 profile.status = status;
529 profile.updateFromStatus(status);
531 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
533 postEvent(ALARM_TYPE_RESTARTED, true);
536 // If status update was successful the thing must be online,
537 // but not while firmware update is in progress
538 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
542 // map status to channels
543 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
544 updated |= this.updateDeviceStatus(status);
545 updated |= ShellyComponents.updateDeviceStatus(this, status);
546 fillDeviceStatus(status, updated);
547 updated |= updateInputs(status);
548 updated |= updateMeters(this, status);
549 updated |= updateSensors(this, status);
551 // All channels must be created after the first cycle
552 channelsCreated = true;
554 } catch (ShellyApiException e) {
555 // http call failed: go offline except for battery devices, which might be in
556 // sleep mode. Once the next update is successful the device goes back online
558 ShellyApiResult res = e.getApiResult();
559 if (profile.alwaysOn && e.isConnectionError()) {
560 status = "offline.status-error-connect";
561 } else if (res.isHttpAccessUnauthorized()) {
562 status = "offline.conf-error-access-denied";
563 } else if (isWatchdogStarted()) {
564 if (!isWatchdogExpired()) {
565 logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
566 if (profile.alwaysOn) { // suppress for battery powered sensors
567 logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
570 } else if (e.isJSONException()) {
571 status = "offline.status-error-unexpected-api-result";
572 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
573 } else if (res.isHttpTimeout()) {
574 // Watchdog not started, e.g. device in sleep mode
575 if (isThingOnline()) { // ignore when already offline
576 status = "offline.status-error-watchdog";
579 status = "offline.status-error-unexpected-api-result";
580 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
583 if (!status.isEmpty()) {
584 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
586 } catch (NullPointerException | IllegalArgumentException e) {
587 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
589 if (scheduledUpdates > 0) {
591 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
592 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
593 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
594 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
600 private void showThingConfig(ShellyDeviceProfile profile) {
601 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
602 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
604 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
605 logger.debug("{}: Device "
606 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
607 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
608 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
609 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
610 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
611 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
612 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
613 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
614 if (profile.status.extTemperature != null || profile.status.extHumidity != null
615 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
616 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
620 private void addStateOptions(ShellyDeviceProfile prf) {
622 String[] profileNames = prf.getValveProfileList(0);
623 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
624 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
625 channelDefinitions.clearStateOptions(channelId);
627 for (String name : profileNames) {
628 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
632 if (prf.isRoller && prf.settings.favorites != null) {
633 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
634 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
635 prf.settings.favorites.size());
636 channelDefinitions.clearStateOptions(channelId);
638 for (ShellyFavPos fav : prf.settings.favorites) {
639 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
646 public String getThingType() {
647 return thing.getThingTypeUID().getId();
651 public ThingStatus getThingStatus() {
652 return thing.getStatus();
656 public ThingStatusDetail getThingStatusDetail() {
657 return thing.getStatusInfo().getStatusDetail();
661 public boolean isThingOnline() {
662 return getThingStatus() == ThingStatus.ONLINE;
665 public boolean isThingOffline() {
666 return getThingStatus() == ThingStatus.OFFLINE;
670 public void setThingOnline() {
671 if (!isThingOnline()) {
672 updateStatus(ThingStatus.ONLINE);
674 // request 3 updates in a row (during the first 2+3*3 sec)
675 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
678 // Restart watchdog when status update was successful (no exception)
683 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
684 if (!isThingOffline()) {
685 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
686 api.close(); // Gen2: disconnect WS/close http sessions
688 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
693 public void restartWatchdog() {
695 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
696 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
699 private boolean isWatchdogExpired() {
700 long delta = now() - watchdog;
701 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
702 stats.remainingWatchdog = delta;
708 private boolean isWatchdogStarted() {
713 public void reinitializeThing() {
714 logger.debug("{}: Re-Initialize Thing", thingName);
716 logger.debug("{}: Handler is shutting down, ignore", thingName);
719 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
720 messages.get("offline.status-error-restarted"));
721 requestUpdates(0, true);
725 public boolean isStopping() {
730 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
733 // Update uptime and WiFi, internal temp
734 ShellyComponents.updateDeviceStatus(this, status);
735 stats.wifiRssi = getInteger(status.wifiSta.rssi);
737 if (api.isInitialized()) {
738 stats.timeoutErrors = api.getTimeoutErrors();
739 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
741 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
743 // Check various device indicators like overheating
744 if (checkRestarted(status)) {
745 // Force re-initialization on next status update
747 } else if (getBool(status.overtemperature)) {
748 alarm = ALARM_TYPE_OVERTEMP;
749 } else if (getBool(status.overload)) {
750 alarm = ALARM_TYPE_OVERLOAD;
751 } else if (getBool(status.loaderror)) {
752 alarm = ALARM_TYPE_LOADERR;
754 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
755 if (internalTemp != UnDefType.NULL) {
756 int temp = ((Number) internalTemp).intValue();
757 if (temp > stats.maxInternalTemp) {
758 stats.maxInternalTemp = temp;
762 if (status.uptime != null) {
763 stats.lastUptime = getLong(status.uptime);
766 if (!alarm.isEmpty()) {
767 postEvent(alarm, false);
772 public void incProtMessages() {
773 stats.protocolMessages++;
777 public void incProtErrors() {
778 stats.protocolErrors++;
782 * Check if device has restarted and needs a new Thing initialization
784 * @return true: restart detected
787 private boolean checkRestarted(ShellySettingsStatus status) {
788 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
789 && (status.uptime != null && status.uptime < stats.lastUptime
790 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
791 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
792 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
793 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
794 updateProperties(profile, status);
801 * Save alarm to the lastAlarm channel
803 * @param event Alarm Message
807 public void postEvent(String event, boolean force) {
808 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
809 State value = cache.getValue(channelId);
810 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
812 if (force || !lastAlarm.equals(event)
813 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
814 switch (event.toUpperCase()) {
817 case SHELLY_WAKEUPT_SENSOR:
818 case SHELLY_WAKEUPT_PERIODIC:
819 case SHELLY_WAKEUPT_BUTTON:
820 case SHELLY_WAKEUPT_POWERON:
821 case SHELLY_WAKEUPT_EXT_POWER:
822 case SHELLY_WAKEUPT_UNKNOWN:
823 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
824 case ALARM_TYPE_NONE:
827 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
828 triggerChannel(channelId, event);
829 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
830 stats.lastAlarm = event;
831 stats.lastAlarmTs = now();
837 public boolean isUpdateScheduled() {
838 return scheduledUpdates > 0;
842 * Callback for device events
845 * @param deviceName device receiving the event
847 * @param type the HTML input data
848 * @param parameters parameters from the event URL
849 * @return true if event was processed
852 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
853 Map<String, String> parameters) {
854 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
855 || config.serviceName.equals(deviceName)) {
856 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
858 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
859 if (!profile.isInitialized()) {
860 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
861 requestUpdates(1, true);
863 String group = profile.getControlGroup(idx);
864 if (group.isEmpty()) {
865 logger.debug("{}: Unsupported event class: {}", thingName, type);
869 // map some of the events to system defined button triggers
873 String parmType = getString(parameters.get("type"));
874 String event = !parmType.isEmpty() ? parmType : type;
875 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
877 case SHELLY_EVENT_SHORTPUSH:
878 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
879 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
880 case SHELLY_EVENT_LONGPUSH:
882 triggerButton(group, idx, mapButtonEvent(event));
883 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
884 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
886 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
890 case SHELLY_EVENT_BTN_ON:
891 case SHELLY_EVENT_BTN_OFF:
892 if (profile.isRGBW2) {
893 // RGBW2 has only one input, so not per channel
894 group = CHANNEL_GROUP_LIGHT_CONTROL;
896 onoff = CHANNEL_INPUT;
898 case SHELLY_EVENT_BTN1_ON:
899 case SHELLY_EVENT_BTN1_OFF:
900 onoff = CHANNEL_INPUT1;
902 case SHELLY_EVENT_BTN2_ON:
903 case SHELLY_EVENT_BTN2_OFF:
904 onoff = CHANNEL_INPUT2;
906 case SHELLY_EVENT_OUT_ON:
907 case SHELLY_EVENT_OUT_OFF:
908 onoff = CHANNEL_OUTPUT;
910 case SHELLY_EVENT_ROLLER_OPEN:
911 case SHELLY_EVENT_ROLLER_CLOSE:
912 case SHELLY_EVENT_ROLLER_STOP:
913 channel = CHANNEL_EVENT_TRIGGER;
916 case SHELLY_EVENT_SENSORREPORT:
917 // process sensor with next refresh
919 case SHELLY_EVENT_TEMP_OVER: // DW2
920 case SHELLY_EVENT_TEMP_UNDER:
921 channel = CHANNEL_EVENT_TRIGGER;
924 case SHELLY_EVENT_FLOOD_DETECTED:
925 case SHELLY_EVENT_FLOOD_GONE:
926 updateChannel(group, CHANNEL_SENSOR_FLOOD,
927 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
930 case SHELLY_EVENT_CLOSE: // DW 1.7
931 case SHELLY_EVENT_OPEN: // DW 1.7
932 updateChannel(group, CHANNEL_SENSOR_STATE,
933 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
934 : OpenClosedType.CLOSED);
937 case SHELLY_EVENT_DARK: // DW 1.7
938 case SHELLY_EVENT_TWILIGHT: // DW 1.7
939 case SHELLY_EVENT_BRIGHT: // DW 1.7
940 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
943 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
944 case SHELLY_EVENT_ALARM_HEAVY:
945 case SHELLY_EVENT_ALARM_OFF:
946 case SHELLY_EVENT_VIBRATION: // DW2
947 channel = CHANNEL_SENSOR_ALARM_STATE;
948 payload = event.toUpperCase();
952 // trigger will be provided by input/output channel or sensor channels
955 if (!onoff.isEmpty()) {
956 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
958 if (!payload.isEmpty()) {
959 // Pass event to trigger channel
960 payload = payload.toUpperCase();
961 logger.debug("{}: Post event {}", thingName, payload);
962 triggerChannel(mkChannelId(group, channel), payload);
966 // request update on next interval (2x for non-battery devices)
968 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
975 * Initialize the binding's thing configuration, calc update counts
977 protected void initializeThingConfig() {
978 thingType = getThing().getThingTypeUID().getId();
979 final Map<String, String> properties = getThing().getProperties();
980 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
981 if (thingName.isEmpty()) {
982 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
985 config = getConfigAs(ShellyThingConfiguration.class);
986 if (config.deviceAddress.isEmpty()) {
987 config.deviceAddress = config.deviceIp;
989 if (config.deviceAddress.isEmpty()) {
990 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
995 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
996 // convert to lower case
997 if (!config.deviceIp.isEmpty()) {
999 InetAddress addr = InetAddress.getByName(config.deviceIp);
1000 String saddr = addr.getHostAddress();
1001 if (!config.deviceIp.equals(saddr)) {
1002 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1003 config.deviceIp = saddr;
1005 } catch (UnknownHostException e) {
1006 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1010 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1011 config.localIp = bindingConfig.localIP;
1012 config.localPort = String.valueOf(bindingConfig.httpPort);
1013 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1014 // Gen2 has hard coded user "admin"
1015 config.userId = bindingConfig.defaultUserId;
1016 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1018 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1019 config.password = bindingConfig.defaultPassword;
1020 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1022 if (config.updateInterval == 0) {
1023 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1025 if (config.updateInterval < UPDATE_MIN_DELAY) {
1026 config.updateInterval = UPDATE_MIN_DELAY;
1029 // Try to get updatePeriod from properties
1030 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1031 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1032 // initialized successfully by the REST call.
1033 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1034 if (!lastPeriod.isEmpty()) {
1035 int period = Integer.parseInt(lastPeriod);
1037 profile.updatePeriod = period;
1041 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1042 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1045 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1047 if (prf.fwVersion.isEmpty()) {
1048 // no fw version available (e.g. BLU device)
1051 ShellyVersionDTO version = new ShellyVersionDTO();
1052 if (version.checkBeta(getString(prf.fwVersion))) {
1053 logger.info("{}: {}", prf.device.hostname,
1054 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1056 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1057 if (version.compare(prf.fwVersion, minVersion) < 0) {
1058 logger.warn("{}: {}", prf.device.hostname,
1059 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1062 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1063 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1064 if (!config.eventsCoIoT) {
1065 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1069 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1070 logger.info("{}: {}", thingName,
1071 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1073 } catch (NullPointerException e) { // could be inconsistant format of beta version
1074 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1078 public String checkForUpdate() {
1080 ShellyOtaCheckResult result = api.checkForUpdate();
1081 return result.status;
1082 } catch (ShellyApiException e) {
1087 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1088 if (coap == null || !config.eventsCoIoT) {
1091 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1092 String devpeer = getString(profile.settings.coiot.peer);
1093 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1094 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1096 api.setCoIoTPeer(ourpeer);
1097 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1098 } catch (ShellyApiException e) {
1099 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1101 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1102 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1106 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1107 config.eventsCoIoT = true;
1108 config.eventsSwitch = false;
1109 config.eventsButton = false;
1110 config.eventsPush = false;
1111 config.eventsRoller = false;
1112 config.eventsSensorReport = false;
1113 api.setConfig(thingName, config);
1116 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1118 coap.start(thingName, config);
1123 * Checks the http response for authorization error.
1124 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1125 * case the thing type shelly-unknown is set.
1127 * @param result exception details including the http respone
1128 * @return true if the authorization failed
1130 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1131 if (result.isHttpAccessUnauthorized()) {
1132 // If the device is password protected the API doesn't provide settings to the device settings
1133 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1140 * Change type of this thing.
1142 * @param thingType thing type acc. to the xml definition
1143 * @param mode Device mode (e.g. relay, roller)
1145 protected void changeThingType(String thingType, String mode) {
1146 String deviceType = substringBefore(thingType, "-");
1147 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1148 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1149 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1150 Map<String, String> properties = editProperties();
1151 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1152 properties.replace(PROPERTY_DEV_MODE, mode);
1153 updateProperties(properties);
1154 changeThingType(thingTypeUID, getConfig());
1159 public void thingUpdated(Thing thing) {
1160 logger.debug("{}: Channel definitions updated.", thingName);
1161 super.thingUpdated(thing);
1165 * Start the background updates
1167 protected void startUpdateJob() {
1168 ScheduledFuture<?> statusJob = this.statusJob;
1169 if ((statusJob == null) || statusJob.isCancelled()) {
1170 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1172 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1173 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1178 * Flag the status job to do an exceptional update (something happened) rather
1179 * than waiting until the next regular poll
1181 * @param requestCount number of polls to execute
1182 * @param refreshSettings true=force a /settings query
1183 * @return true=Update schedule, false=skipped (too many updates already
1187 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1188 this.refreshSettings |= refreshSettings;
1189 if (refreshSettings) {
1190 if (requestCount == 0) {
1191 logger.debug("{}: Request settings refresh", thingName);
1193 scheduledUpdates = 1;
1196 if (scheduledUpdates < 10) { // < 30s
1197 scheduledUpdates += requestCount;
1204 * Map input states to channels
1206 * @param status Shelly device status
1207 * @return true: one or more inputs were updated
1210 public boolean updateInputs(ShellySettingsStatus status) {
1211 boolean updated = false;
1213 if (status.inputs != null) {
1214 if (!areChannelsCreated()) {
1215 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1219 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1220 for (ShellyInputState input : status.inputs) {
1221 String group = profile.getInputGroup(idx);
1222 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1223 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1224 if (input.event != null) {
1225 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1226 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1231 if (status.input != null) {
1232 // RGBW2: a single int rather than an array
1233 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1234 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1241 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1242 boolean changed = false;
1243 if (valueArray != null && !valueArray.isEmpty()) {
1244 String reason = getString((String) valueArray.get(0));
1245 String newVal = valueArray.toString();
1246 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1247 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1249 postEvent(reason.toUpperCase(), true);
1251 lastWakeupReason = newVal;
1257 public void triggerButton(String group, int idx, String value) {
1258 String trigger = mapButtonEvent(value);
1259 if (trigger.isEmpty()) {
1263 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1264 triggerChannel(group,
1265 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1267 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1268 if (profile.alwaysOn) {
1269 // refresh status of the input channel
1270 requestUpdates(1, false);
1275 public void publishState(String channelId, State value) {
1276 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1277 if (!stopping && isLinked(id)) {
1278 updateState(id, value);
1279 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1284 public boolean updateChannel(String group, String channel, State value) {
1285 return updateChannel(mkChannelId(group, channel), value, false);
1289 public boolean updateChannel(String channelId, State value, boolean force) {
1290 return !stopping && cache.updateChannel(channelId, value, force);
1294 public State getChannelValue(String group, String channel) {
1295 return cache.getValue(group, channel);
1299 public double getChannelDouble(String group, String channel) {
1300 State value = getChannelValue(group, channel);
1301 if (value != UnDefType.NULL) {
1302 if (value instanceof QuantityType quantityCommand) {
1303 return quantityCommand.toBigDecimal().doubleValue();
1305 if (value instanceof DecimalType decimalCommand) {
1306 return decimalCommand.doubleValue();
1313 * Update Thing's channels according to available status information from the API
1315 * @param dynChannels
1318 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1319 if (channelsCreated) {
1320 return; // already done
1324 // Get subset of those channels that currently do not exist
1325 List<Channel> existingChannels = getThing().getChannels();
1326 for (Channel channel : existingChannels) {
1327 String id = channel.getUID().getId();
1328 if (dynChannels.containsKey(id)) {
1329 dynChannels.remove(id);
1333 if (!dynChannels.isEmpty()) {
1334 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1335 ThingBuilder thingBuilder = editThing();
1336 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1337 Channel c = channel.getValue();
1338 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1339 thingBuilder.withChannel(c);
1341 updateThing(thingBuilder.build());
1342 logger.debug("{}: Channel definitions updated", thingName);
1344 } catch (IllegalArgumentException e) {
1345 logger.debug("{}: Unable to update channel definitions", thingName, e);
1350 public boolean areChannelsCreated() {
1351 return channelsCreated;
1355 * Update thing properties with dynamic values
1357 * @param profile The device profile
1358 * @param status the /status result
1360 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1361 Map<String, Object> properties = fillDeviceProperties(profile);
1362 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1363 String deviceName = getString(profile.settings.name);
1364 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1365 properties.put(PROPERTY_DEV_GEN, "1");
1366 if (!deviceName.isEmpty()) {
1367 properties.put(PROPERTY_DEV_NAME, deviceName);
1369 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1371 // add status properties
1372 if (status.wifiSta != null) {
1373 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1375 if (status.update != null) {
1376 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1377 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1378 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1379 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1381 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1383 Map<String, String> thingProperties = new TreeMap<>();
1384 for (Map.Entry<String, Object> property : properties.entrySet()) {
1385 thingProperties.put(property.getKey(), (String) property.getValue());
1387 flushProperties(thingProperties);
1391 * Add one property to the Thing Properties
1393 * @param key Name of the property
1394 * @param value Value of the property
1397 public void updateProperties(String key, String value) {
1398 Map<String, String> thingProperties = editProperties();
1399 if (thingProperties.containsKey(key)) {
1400 thingProperties.replace(key, value);
1402 thingProperties.put(key, value);
1404 updateProperties(thingProperties);
1405 logger.trace("{}: Properties updated", thingName);
1408 public void flushProperties(Map<String, String> propertyUpdates) {
1409 Map<String, String> thingProperties = editProperties();
1410 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1411 if (thingProperties.containsKey(property.getKey())) {
1412 thingProperties.replace(property.getKey(), property.getValue());
1414 thingProperties.put(property.getKey(), property.getValue());
1417 updateProperties(thingProperties);
1421 * Get one property from the Thing Properties
1423 * @param key property name
1424 * @return property value or "" if property is not set
1427 public String getProperty(String key) {
1428 Map<String, String> thingProperties = getThing().getProperties();
1429 return getString(thingProperties.get(key));
1433 * Fill Thing Properties with device attributes
1435 * @param profile Property Map to full
1436 * @return a full property map
1438 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1439 Map<String, Object> properties = new TreeMap<>();
1440 properties.put(PROPERTY_VENDOR, VENDOR);
1441 if (profile.isInitialized()) {
1442 properties.put(PROPERTY_MODEL_ID, getString(profile.device.type));
1443 properties.put(PROPERTY_MAC_ADDRESS, profile.device.mac);
1444 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1445 properties.put(PROPERTY_DEV_MODE, profile.device.mode);
1446 if (profile.hasRelays) {
1447 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1448 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1449 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1451 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1452 if (!profile.hwRev.isEmpty()) {
1453 properties.put(PROPERTY_HWREV, profile.hwRev);
1454 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1461 * Return device profile.
1463 * @param forceRefresh true=force refresh before returning, false=return without
1465 * @return ShellyDeviceProfile instance
1466 * @throws ShellyApiException
1469 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1471 refreshSettings |= forceRefresh;
1472 if (refreshSettings) {
1473 profile = api.getDeviceProfile(thingType, null);
1474 if (!isThingOnline()) {
1475 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1479 refreshSettings = false;
1485 public ShellyDeviceProfile getProfile() {
1490 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1491 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1492 if (!options.isEmpty()) {
1493 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1499 protected ShellyDeviceProfile getDeviceProfile() {
1504 public void triggerChannel(String group, String channel, String payload) {
1505 String triggerCh = mkChannelId(group, channel);
1506 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1507 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1508 if (vibrationFilter == 0) {
1509 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1510 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1511 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1513 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1514 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1519 triggerChannel(triggerCh, payload);
1522 public void stop() {
1523 logger.debug("{}: Shutting down", thingName);
1524 ScheduledFuture<?> job = this.initJob;
1529 job = this.statusJob;
1533 logger.debug("{}: Shelly statusJob stopped", thingName);
1536 profile.initialized = false;
1540 * Shutdown thing, make sure background jobs are canceled
1543 public void dispose() {
1544 logger.debug("{}: Stopping Thing", thingName);
1551 * Device specific command handlers are overriding this method to do additional stuff
1553 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1557 public String getUID() {
1558 return getThing().getUID().getAsString();
1562 * Device specific handlers are overriding this method to do additional stuff
1564 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1569 public String getThingName() {
1574 public void resetStats() {
1576 stats = new ShellyDeviceStats();
1580 public ShellyDeviceStats getStats() {
1585 public ShellyApiInterface getApi() {
1590 public long getScheduledUpdates() {
1591 return scheduledUpdates;
1594 public Map<String, String> getStatsProp() {
1595 return stats.asProperties();
1599 public void triggerUpdateFromCoap() {
1600 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1601 requestUpdates(1, false);