2 * Copyright (c) 2010-2024 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.Shelly2ApiJsonDTO;
49 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2APClientList.Shelly2APClient;
50 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
51 import org.openhab.binding.shelly.internal.api2.ShellyBluApi;
52 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
53 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
54 import org.openhab.binding.shelly.internal.discovery.ShellyBasicDiscoveryService;
55 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
56 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
57 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
58 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
59 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
60 import org.openhab.core.config.discovery.DiscoveryResult;
61 import org.openhab.core.library.types.DecimalType;
62 import org.openhab.core.library.types.OnOffType;
63 import org.openhab.core.library.types.OpenClosedType;
64 import org.openhab.core.library.types.QuantityType;
65 import org.openhab.core.thing.Channel;
66 import org.openhab.core.thing.ChannelUID;
67 import org.openhab.core.thing.Thing;
68 import org.openhab.core.thing.ThingStatus;
69 import org.openhab.core.thing.ThingStatusDetail;
70 import org.openhab.core.thing.ThingTypeUID;
71 import org.openhab.core.thing.binding.BaseThingHandler;
72 import org.openhab.core.thing.binding.builder.ThingBuilder;
73 import org.openhab.core.thing.type.ChannelTypeUID;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.State;
77 import org.openhab.core.types.StateOption;
78 import org.openhab.core.types.UnDefType;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
83 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
84 * sent to one of the channels.
86 * @author Markus Michels - Initial contribution
89 public abstract class ShellyBaseHandler extends BaseThingHandler
90 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
92 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
93 protected final ShellyChannelDefinitions channelDefinitions;
95 public String thingName = "";
96 public String thingType = "";
98 protected final ShellyApiInterface api;
99 private final HttpClient httpClient;
100 private final ShellyThingTable thingTable;
102 private ShellyBindingConfiguration bindingConfig;
103 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
104 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
105 private ShellyDeviceStats stats = new ShellyDeviceStats();
106 private @Nullable Shelly1CoapHandler coap;
108 private final ShellyTranslationProvider messages;
109 private final ShellyChannelCache cache;
110 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
112 private boolean gen2 = false;
113 private final boolean blu;
114 protected boolean autoCoIoT = false;
117 private boolean channelsCreated = false;
118 private boolean stopping = false;
119 private int vibrationFilter = 0;
120 private String lastWakeupReason = "";
123 private long watchdog = now();
124 protected int scheduledUpdates = 0;
125 private int skipCount = UPDATE_SKIP_COUNT;
126 private int skipUpdate = 0;
127 private boolean refreshSettings = false;
128 private @Nullable ScheduledFuture<?> statusJob;
129 private @Nullable ScheduledFuture<?> initJob;
134 * @param thing The Thing object
135 * @param translationProvider
136 * @param bindingConfig The binding configuration (beside thing
139 * @param coapServer coap server instance
140 * @param httpClient from httpService
142 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
143 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
144 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
147 this.thingTable = thingTable;
148 this.thingName = getString(thing.getLabel());
149 this.messages = translationProvider;
150 this.cache = new ShellyChannelCache(this);
151 this.channelDefinitions = new ShellyChannelDefinitions(messages);
152 this.bindingConfig = bindingConfig;
153 this.config = getConfigAs(ShellyThingConfiguration.class);
154 this.httpClient = httpClient;
156 Map<String, String> properties = thing.getProperties();
157 String gen = getString(properties.get(PROPERTY_DEV_GEN));
158 String thingType = getThingType();
159 gen2 = !"1".equals(gen) || ShellyDeviceProfile.isGeneration2(thingType);
160 blu = ShellyDeviceProfile.isBluSeries(thingType);
161 this.api = !blu ? !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this)
162 : new ShellyBluApi(thingName, thingTable, this);
164 config.eventsCoIoT = false;
166 if (config.eventsCoIoT) {
167 this.coap = new Shelly1CoapHandler(this, coapServer);
172 public boolean checkRepresentation(String key) {
173 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
174 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
178 * Schedule asynchronous Thing initialization, register thing to event dispatcher
181 public void initialize() {
182 // start background initialization:
183 initJob = scheduler.schedule(() -> {
184 boolean start = true;
186 if (initializeThingConfig()) {
187 logger.debug("{}: Config: {}", thingName, config);
188 start = initializeThing();
190 } catch (ShellyApiException e) {
191 start = handleApiException(e);
192 } catch (IllegalArgumentException e) {
193 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
195 // even this initialization failed we start the status update
196 // the updateJob will then try to auto-initialize the thing
197 // in this case the thing stays in status INITIALIZING
202 }, 2, TimeUnit.SECONDS);
205 private boolean handleApiException(ShellyApiException e) {
206 ShellyApiResult res = e.getApiResult();
207 ThingStatusDetail errorCode = ThingStatusDetail.COMMUNICATION_ERROR;
209 boolean retry = true;
210 if (e.isJsonError()) { // invalid JSON format
211 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
212 status = "offline.status-error-unexpected-error";
213 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
215 } else if (res.isHttpAccessUnauthorized()) {
216 status = "offline.conf-error-access-denied";
217 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
219 } else if (isWatchdogExpired()) {
220 status = "offline.status-error-watchdog";
221 } else if (res.httpCode >= 400) {
222 logger.debug("{}: Unexpected API result: {}/{}", thingName, res.httpCode, res.httpReason, e);
223 status = "offline.status-error-unexpected-api-result";
225 } else if (profile.alwaysOn && (e.isConnectionError() || res.isHttpTimeout())) {
226 status = "offline.status-error-connect";
229 if (!status.isEmpty()) {
230 setThingOffline(errorCode, status, e.toString());
232 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
243 public ShellyThingConfiguration getThingConfig() {
248 public HttpClient getHttpClient() {
253 public void startScan() {
254 if (api.isInitialized()) {
258 checkRangeExtender(profile);
262 * This routine is called every time the Thing configuration has been changed
265 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
266 super.handleConfigurationUpdate(configurationParameters);
267 logger.debug("{}: Thing config updated, re-initialize", thingName);
272 reinitializeThing();// force re-initialization
276 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
277 * If the device is password protected and the credentials are missing or don't match the API access will throw an
278 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
279 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
280 * credentials are correct and the API access is initialized successful.
282 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
284 public boolean initializeThing() throws ShellyApiException {
285 // Init from thing type to have a basic profile, gets updated when device info is received from API
286 refreshSettings = false;
287 lastWakeupReason = "";
288 cache.setThingName(thingName);
292 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
293 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
294 if (config.deviceAddress.isEmpty()) {
295 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
299 if (profile.alwaysOn || !profile.isInitialized()) {
300 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
301 messages.get("status.unknown.initializing"));
304 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
305 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
306 // Action URL does when enabled)
307 profile.initFromThingType(thingType);
308 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
309 coap.start(thingName, config);
312 // Initialize API access, exceptions will be catched by initialize()
314 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
315 if (getBool(device.auth) && config.password.isEmpty()) {
316 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
319 if (config.serviceName.isEmpty()) {
320 config.serviceName = getString(device.hostname).toLowerCase();
323 api.setConfig(thingName, config);
324 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
325 String mode = getString(tmpPrf.device.mode);
326 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
327 changeThingType(thingName, mode);
328 return false; // force re-initialization
330 // Validate device mode
331 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
332 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
333 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode, reqMode);
336 if (!getString(tmpPrf.device.coiot).isEmpty()) {
337 // New Shelly devices might use a different endpoint for the CoAP listener
338 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
340 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
341 // Sensor, usually 12h, H&T in USB mode 10min
342 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
343 ? tmpPrf.settings.sleepMode.period * 60 // minutes
344 : tmpPrf.settings.sleepMode.period * 3600; // hours
345 tmpPrf.updatePeriod += 60; // give 1min extra
346 } else if (tmpPrf.settings.coiot != null && tmpPrf.settings.coiot.updatePeriod != null) {
347 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
348 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
349 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
351 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
354 tmpPrf.status = api.getStatus(); // update thing properties
355 tmpPrf.updateFromStatus(tmpPrf.status);
356 addStateOptions(tmpPrf);
358 // update thing properties
359 updateProperties(tmpPrf, tmpPrf.status);
360 checkVersion(tmpPrf, tmpPrf.status);
362 // Check for Range Extender mode, add secondary device to Inbox
363 checkRangeExtender(tmpPrf);
365 startCoap(config, tmpPrf);
367 api.setActionURLs(); // register event urls
370 // All initialization done, so keep the profile and set Thing to ONLINE
371 fillDeviceStatus(tmpPrf.status, false);
372 postEvent(ALARM_TYPE_NONE, false);
375 showThingConfig(profile);
377 logger.debug("{}: Thing successfully initialized.", thingName);
378 updateProperties(profile, profile.status);
379 setThingOnline(); // if API call was successful the thing must be online
380 return true; // success
384 * Handle Channel Commands
387 public void handleCommand(ChannelUID channelUID, Command command) {
389 if (command instanceof RefreshType) {
390 String channelId = channelUID.getId();
391 State value = cache.getValue(channelId);
392 if (value != UnDefType.NULL) {
393 updateState(channelId, value);
398 if (!profile.isInitialized()) {
399 logger.debug("{}: {}", thingName, messages.get("command.init", command));
402 profile = getProfile(false);
405 boolean update = false;
406 switch (channelUID.getIdWithoutGroup()) {
407 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
408 logger.debug("{}: Send key {}", thingName, command);
409 api.sendIRKey(command.toString());
413 case CHANNEL_LED_STATUS_DISABLE:
414 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
415 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
417 case CHANNEL_LED_POWER_DISABLE:
418 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
419 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
422 case CHANNEL_SENSOR_SLEEPTIME:
423 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
424 int value = getNumber(command).intValue();
425 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
427 api.setSleepTime(value);
429 case CHANNEL_CONTROL_SCHEDULE:
431 logger.debug("{}: {} Valve schedule/profile", thingName,
432 command == OnOffType.ON ? "Enable" : "Disable");
433 api.setValveProfile(0,
434 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
437 case CHANNEL_CONTROL_PROFILE:
438 logger.debug("{}: Select profile {}", thingName, command);
440 if (command instanceof Number) {
441 id = getNumber(command).intValue();
443 String cmd = command.toString();
444 if (isDigit(cmd.charAt(0))) {
445 id = Integer.parseInt(cmd);
446 } else if (profile.settings.thermostats != null) {
447 ShellyThermnostat t = profile.settings.thermostats.get(0);
448 for (int i = 0; i < t.profileNames.length; i++) {
449 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
455 if (id < 0 || id > 5) {
456 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
459 api.setValveProfile(0, id);
461 case CHANNEL_CONTROL_MODE:
462 logger.debug("{}: Set mode to {}", thingName, command);
463 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
465 case CHANNEL_CONTROL_SETTEMP:
466 logger.debug("{}: Set temperature to {}", thingName, command);
467 api.setValveTemperature(0, getNumber(command).doubleValue());
469 case CHANNEL_CONTROL_POSITION:
470 logger.debug("{}: Set position to {}", thingName, command);
471 api.setValvePosition(0, getNumber(command));
473 case CHANNEL_CONTROL_BCONTROL:
474 logger.debug("{}: Set boost mode to {}", thingName, command);
475 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
477 case CHANNEL_CONTROL_BTIMER:
478 logger.debug("{}: Set boost timer to {}", thingName, command);
479 api.setValveBoostTime(0, getNumber(command).intValue());
481 case CHANNEL_SENSOR_MUTE:
482 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
483 logger.debug("{}: Mute Smoke Alarm", thingName);
484 api.muteSmokeAlarm(0);
485 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
489 update = handleDeviceCommand(channelUID, command);
494 if (update && !autoCoIoT && !isUpdateScheduled()) {
495 requestUpdates(1, false);
497 } catch (ShellyApiException e) {
498 if (!handleApiException(e)) {
502 ShellyApiResult res = e.getApiResult();
503 if (res.isNotCalibrtated()) {
504 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
506 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
510 String group = getString(channelUID.getGroupId());
511 String channel = getString(channelUID.getIdWithoutGroup());
512 State oldValue = getChannelValue(group, channel);
513 if (oldValue != UnDefType.NULL) {
514 logger.info("{}: Restore channel value to {}", thingName, oldValue);
515 updateChannel(group, channel, oldValue);
518 } catch (IllegalArgumentException e) {
519 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
524 * Update device status and channels
526 protected void refreshStatus() {
528 boolean updated = false;
530 if (vibrationFilter > 0) {
532 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
533 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
537 ThingStatus thingStatus = getThing().getStatus();
538 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
539 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
540 || (thingStatus == ThingStatus.UNKNOWN)) {
541 logger.debug("{}: Status update triggered thing initialization", thingName);
542 initializeThing(); // may fire an exception if initialization failed
544 ShellySettingsStatus status = api.getStatus();
545 boolean restarted = checkRestarted(status);
546 profile = getProfile(refreshSettings || restarted);
547 profile.status = status;
548 profile.updateFromStatus(status);
550 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
552 postEvent(ALARM_TYPE_RESTARTED, true);
555 // If status update was successful the thing must be online,
556 // but not while firmware update is in progress
557 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
561 // map status to channels
562 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
563 updated |= this.updateDeviceStatus(status);
564 updated |= ShellyComponents.updateDeviceStatus(this, status);
565 fillDeviceStatus(status, updated);
566 updated |= updateInputs(status);
567 updated |= updateMeters(this, status);
568 updated |= updateSensors(this, status);
570 // All channels must be created after the first cycle
571 channelsCreated = true;
573 } catch (ShellyApiException e) {
574 // http call failed: go offline except for battery devices, which might be in
575 // sleep mode. Once the next update is successful the device goes back online
576 handleApiException(e);
577 } catch (NullPointerException | IllegalArgumentException e) {
578 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
580 if (scheduledUpdates > 0) {
582 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
583 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
584 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
585 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
591 private void checkRangeExtender(ShellyDeviceProfile prf) {
592 if (getBool(prf.settings.rangeExtender) && config.enableRangeExtender && prf.status.rangeExtender != null
593 && prf.status.rangeExtender.apClients != null) {
594 for (Shelly2APClient client : profile.status.rangeExtender.apClients) {
595 String secondaryIp = config.deviceIp + ":" + client.mport.toString();
596 String name = "shellyplusrange-" + client.mac.replaceAll(":", "");
597 DiscoveryResult result = ShellyBasicDiscoveryService.createResult(true, name, secondaryIp,
598 bindingConfig, httpClient, messages);
599 if (result != null) {
600 thingTable.discoveredResult(result);
606 private void showThingConfig(ShellyDeviceProfile profile) {
607 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
608 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
610 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
611 logger.debug("{}: Device "
612 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
613 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
614 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
615 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
616 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
617 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
618 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
619 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
620 if (profile.status.extTemperature != null || profile.status.extHumidity != null
621 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
622 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
626 private void addStateOptions(ShellyDeviceProfile prf) {
628 String[] profileNames = prf.getValveProfileList(0);
629 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
630 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
631 channelDefinitions.clearStateOptions(channelId);
633 for (String name : profileNames) {
634 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
638 if (prf.isRoller && prf.settings.favorites != null) {
639 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
640 logger.debug("{}: Adding {} roler favorite(s) to channel description", thingName,
641 prf.settings.favorites.size());
642 channelDefinitions.clearStateOptions(channelId);
644 for (ShellyFavPos fav : prf.settings.favorites) {
645 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
652 public String getThingType() {
653 return thing.getThingTypeUID().getId();
657 public ThingStatus getThingStatus() {
658 return thing.getStatus();
662 public ThingStatusDetail getThingStatusDetail() {
663 return thing.getStatusInfo().getStatusDetail();
667 public boolean isThingOnline() {
668 return getThingStatus() == ThingStatus.ONLINE;
671 public boolean isThingOffline() {
672 return getThingStatus() == ThingStatus.OFFLINE;
676 public void setThingOnline() {
677 if (!isThingOnline()) {
678 updateStatus(ThingStatus.ONLINE);
680 // request 3 updates in a row (during the first 2+3*3 sec)
681 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
684 // Restart watchdog when status update was successful (no exception)
689 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
690 if (!isThingOffline()) {
691 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
692 api.close(); // Gen2: disconnect WS/close http sessions
694 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
699 public void restartWatchdog() {
701 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
702 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
705 private boolean isWatchdogExpired() {
706 long delta = now() - watchdog;
707 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
708 stats.remainingWatchdog = delta;
715 public void reinitializeThing() {
716 logger.debug("{}: Re-Initialize Thing", thingName);
718 logger.debug("{}: Handler is shutting down, ignore", thingName);
721 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
722 messages.get("offline.status-error-restarted"));
723 requestUpdates(0, true);
727 public boolean isStopping() {
732 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
735 // Update uptime and WiFi, internal temp
736 ShellyComponents.updateDeviceStatus(this, status);
737 stats.wifiRssi = getInteger(status.wifiSta.rssi);
739 if (api.isInitialized()) {
740 stats.timeoutErrors = api.getTimeoutErrors();
741 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
743 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
745 // Check various device indicators like overheating
746 if (checkRestarted(status)) {
747 // Force re-initialization on next status update
749 } else if (getBool(status.overtemperature)) {
750 alarm = ALARM_TYPE_OVERTEMP;
751 } else if (getBool(status.overload)) {
752 alarm = ALARM_TYPE_OVERLOAD;
753 } else if (getBool(status.loaderror)) {
754 alarm = ALARM_TYPE_LOADERR;
756 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
757 if (internalTemp != UnDefType.NULL) {
758 int temp = ((Number) internalTemp).intValue();
759 if (temp > stats.maxInternalTemp) {
760 stats.maxInternalTemp = temp;
764 if (status.uptime != null) {
765 stats.lastUptime = getLong(status.uptime);
768 if (!alarm.isEmpty()) {
769 postEvent(alarm, false);
774 public void incProtMessages() {
775 stats.protocolMessages++;
779 public void incProtErrors() {
780 stats.protocolErrors++;
784 * Check if device has restarted and needs a new Thing initialization
786 * @return true: restart detected
789 private boolean checkRestarted(ShellySettingsStatus status) {
790 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
791 && (status.uptime != null && status.uptime < stats.lastUptime
792 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
793 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
794 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
795 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
796 updateProperties(profile, status);
803 * Save alarm to the lastAlarm channel
805 * @param event Alarm Message
809 public void postEvent(String event, boolean force) {
810 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
811 State value = cache.getValue(channelId);
812 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
814 if (force || !lastAlarm.equals(event)
815 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
816 switch (event.toUpperCase()) {
819 case SHELLY_WAKEUPT_SENSOR:
820 case SHELLY_WAKEUPT_PERIODIC:
821 case SHELLY_WAKEUPT_BUTTON:
822 case SHELLY_WAKEUPT_POWERON:
823 case SHELLY_WAKEUPT_EXT_POWER:
824 case SHELLY_WAKEUPT_UNKNOWN:
825 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTASTART:
826 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTAPROGRESS:
827 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTADONE:
828 case SHELLY_EVENT_ROLLER_CALIB:
829 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
830 case ALARM_TYPE_NONE:
833 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
834 triggerChannel(channelId, event);
835 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
836 stats.lastAlarm = event;
837 stats.lastAlarmTs = now();
843 public boolean isUpdateScheduled() {
844 return scheduledUpdates > 0;
848 * Callback for device events
851 * @param deviceName device receiving the event
853 * @param type the HTML input data
854 * @param parameters parameters from the event URL
855 * @return true if event was processed
858 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
859 Map<String, String> parameters) {
860 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
861 || config.serviceName.equals(deviceName)) {
862 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
864 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
865 if (!profile.isInitialized()) {
866 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
867 requestUpdates(1, true);
869 String group = profile.getControlGroup(idx);
870 if (group.isEmpty()) {
871 logger.debug("{}: Unsupported event class: {}", thingName, type);
875 // map some of the events to system defined button triggers
879 String parmType = getString(parameters.get("type"));
880 String event = !parmType.isEmpty() ? parmType : type;
881 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
883 case SHELLY_EVENT_SHORTPUSH:
884 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
885 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
886 case SHELLY_EVENT_LONGPUSH:
888 triggerButton(group, idx, mapButtonEvent(event));
889 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
890 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
892 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
896 case SHELLY_EVENT_BTN_ON:
897 case SHELLY_EVENT_BTN_OFF:
898 if (profile.isRGBW2) {
899 // RGBW2 has only one input, so not per channel
900 group = CHANNEL_GROUP_LIGHT_CONTROL;
902 onoff = CHANNEL_INPUT;
904 case SHELLY_EVENT_BTN1_ON:
905 case SHELLY_EVENT_BTN1_OFF:
906 onoff = CHANNEL_INPUT1;
908 case SHELLY_EVENT_BTN2_ON:
909 case SHELLY_EVENT_BTN2_OFF:
910 onoff = CHANNEL_INPUT2;
912 case SHELLY_EVENT_OUT_ON:
913 case SHELLY_EVENT_OUT_OFF:
914 onoff = CHANNEL_OUTPUT;
916 case SHELLY_EVENT_ROLLER_OPEN:
917 case SHELLY_EVENT_ROLLER_CLOSE:
918 case SHELLY_EVENT_ROLLER_STOP:
919 channel = CHANNEL_EVENT_TRIGGER;
922 case SHELLY_EVENT_SENSORREPORT:
923 // process sensor with next refresh
925 case SHELLY_EVENT_TEMP_OVER: // DW2
926 case SHELLY_EVENT_TEMP_UNDER:
927 channel = CHANNEL_EVENT_TRIGGER;
930 case SHELLY_EVENT_FLOOD_DETECTED:
931 case SHELLY_EVENT_FLOOD_GONE:
932 updateChannel(group, CHANNEL_SENSOR_FLOOD,
933 OnOffType.from(event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED)));
936 case SHELLY_EVENT_CLOSE: // DW 1.7
937 case SHELLY_EVENT_OPEN: // DW 1.7
938 updateChannel(group, CHANNEL_SENSOR_STATE,
939 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
940 : OpenClosedType.CLOSED);
943 case SHELLY_EVENT_DARK: // DW 1.7
944 case SHELLY_EVENT_TWILIGHT: // DW 1.7
945 case SHELLY_EVENT_BRIGHT: // DW 1.7
946 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
949 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
950 case SHELLY_EVENT_ALARM_HEAVY:
951 case SHELLY_EVENT_ALARM_OFF:
952 case SHELLY_EVENT_VIBRATION: // DW2
953 channel = CHANNEL_SENSOR_ALARM_STATE;
954 payload = event.toUpperCase();
958 // trigger will be provided by input/output channel or sensor channels
961 if (!onoff.isEmpty()) {
962 updateChannel(group, onoff, OnOffType.from(event.toLowerCase().contains("_on")));
964 if (!payload.isEmpty()) {
965 // Pass event to trigger channel
966 payload = payload.toUpperCase();
967 logger.debug("{}: Post event {}", thingName, payload);
968 triggerChannel(mkChannelId(group, channel), payload);
972 // request update on next interval (2x for non-battery devices)
974 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
981 * Initialize the binding's thing configuration, calc update counts
983 protected boolean initializeThingConfig() {
984 thingType = getThing().getThingTypeUID().getId();
985 final Map<String, String> properties = getThing().getProperties();
986 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
987 if (thingName.isEmpty()) {
988 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
991 config = getConfigAs(ShellyThingConfiguration.class);
992 if (config.deviceAddress.isEmpty()) {
993 config.deviceAddress = config.deviceIp;
995 if (config.deviceAddress.isEmpty()) {
996 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
1001 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
1002 // convert to lower case
1003 if (!config.deviceIp.isEmpty()) {
1005 String ip = config.deviceIp.contains(":") ? substringBefore(config.deviceIp, ":") : config.deviceIp;
1006 String port = config.deviceIp.contains(":") ? substringAfter(config.deviceIp, ":") : "";
1007 InetAddress addr = InetAddress.getByName(ip);
1008 String saddr = addr.getHostAddress();
1009 if (!ip.equals(saddr)) {
1010 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1011 config.deviceIp = saddr + (port.isEmpty() ? "" : ":" + port);
1013 } catch (UnknownHostException e) {
1014 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1018 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1019 config.localIp = bindingConfig.localIP;
1020 config.localPort = String.valueOf(bindingConfig.httpPort);
1021 if (config.localIp.startsWith("169.254")) {
1022 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, "config-status.error.network-config",
1027 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1028 // Gen2 has hard coded user "admin"
1029 config.userId = bindingConfig.defaultUserId;
1030 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1032 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1033 config.password = bindingConfig.defaultPassword;
1034 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1037 if (config.updateInterval == 0) {
1038 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1040 if (config.updateInterval < UPDATE_MIN_DELAY) {
1041 config.updateInterval = UPDATE_MIN_DELAY;
1044 // Try to get updatePeriod from properties
1045 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1046 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1047 // initialized successfully by the REST call.
1048 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1049 if (!lastPeriod.isEmpty()) {
1050 int period = Integer.parseInt(lastPeriod);
1052 profile.updatePeriod = period;
1056 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1057 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1061 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1063 if (prf.fwVersion.isEmpty()) {
1064 // no fw version available (e.g. BLU device)
1067 ShellyVersionDTO version = new ShellyVersionDTO();
1068 if (version.checkBeta(getString(prf.fwVersion))) {
1069 logger.info("{}: {}", prf.device.hostname,
1070 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1072 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1073 if (version.compare(prf.fwVersion, minVersion) < 0) {
1074 logger.warn("{}: {}", prf.device.hostname,
1075 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1078 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1079 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1080 if (!config.eventsCoIoT) {
1081 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1085 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1086 logger.info("{}: {}", thingName,
1087 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1089 } catch (NullPointerException e) { // could be inconsistant format of beta version
1090 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1094 public String checkForUpdate() {
1096 ShellyOtaCheckResult result = api.checkForUpdate();
1097 return result.status;
1098 } catch (ShellyApiException e) {
1103 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1104 if (coap == null || !config.eventsCoIoT) {
1107 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1108 String devpeer = getString(profile.settings.coiot.peer);
1109 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1110 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1112 api.setCoIoTPeer(ourpeer);
1113 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1114 } catch (ShellyApiException e) {
1115 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1117 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1118 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1122 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1123 config.eventsCoIoT = true;
1124 config.eventsSwitch = false;
1125 config.eventsButton = false;
1126 config.eventsPush = false;
1127 config.eventsRoller = false;
1128 config.eventsSensorReport = false;
1129 api.setConfig(thingName, config);
1132 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1134 coap.start(thingName, config);
1139 * Change type of this thing.
1141 * @param thingType thing type acc. to the xml definition
1142 * @param mode Device mode (e.g. relay, roller)
1144 protected void changeThingType(String thingType, String mode) {
1145 String deviceType = substringBefore(thingType, "-");
1146 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1147 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1148 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1149 Map<String, String> properties = editProperties();
1150 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1151 properties.replace(PROPERTY_DEV_MODE, mode);
1152 updateProperties(properties);
1153 changeThingType(thingTypeUID, getConfig());
1155 logger.debug("{}: to {}", thingName, thingType);
1156 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Unable to change thing type to " + thingType);
1161 public void thingUpdated(Thing thing) {
1162 logger.debug("{}: Channel definitions updated.", thingName);
1163 super.thingUpdated(thing);
1167 * Start the background updates
1169 protected void startUpdateJob() {
1170 ScheduledFuture<?> statusJob = this.statusJob;
1171 if ((statusJob == null) || statusJob.isCancelled()) {
1172 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1174 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1175 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1180 * Flag the status job to do an exceptional update (something happened) rather
1181 * than waiting until the next regular poll
1183 * @param requestCount number of polls to execute
1184 * @param refreshSettings true=force a /settings query
1185 * @return true=Update schedule, false=skipped (too many updates already
1189 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1190 this.refreshSettings |= refreshSettings;
1191 if (refreshSettings) {
1192 if (requestCount == 0) {
1193 logger.debug("{}: Request settings refresh", thingName);
1195 scheduledUpdates = 1;
1198 if (scheduledUpdates < 10) { // < 30s
1199 scheduledUpdates += requestCount;
1206 * Map input states to channels
1208 * @param status Shelly device status
1209 * @return true: one or more inputs were updated
1212 public boolean updateInputs(ShellySettingsStatus status) {
1213 boolean updated = false;
1215 if (status.inputs != null) {
1216 if (!areChannelsCreated()) {
1217 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1221 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1222 for (ShellyInputState input : status.inputs) {
1223 String group = profile.getInputGroup(idx);
1224 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1225 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1226 if (input.event != null) {
1227 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1228 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1233 if (status.input != null) {
1234 // RGBW2: a single int rather than an array
1235 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1236 OnOffType.from(getInteger(status.input) != 0));
1243 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1244 boolean changed = false;
1245 if (valueArray != null && !valueArray.isEmpty()) {
1246 String reason = getString((String) valueArray.get(0));
1247 String newVal = valueArray.toString();
1248 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1249 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1251 postEvent(reason.toUpperCase(), true);
1253 lastWakeupReason = newVal;
1259 public void triggerButton(String group, int idx, String value) {
1260 String trigger = mapButtonEvent(value);
1261 if (trigger.isEmpty()) {
1265 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1266 triggerChannel(group,
1267 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1269 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1270 if (profile.alwaysOn) {
1271 // refresh status of the input channel
1272 requestUpdates(1, false);
1277 public void publishState(String channelId, State value) {
1278 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1279 if (!stopping && isLinked(id)) {
1280 updateState(id, value);
1281 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1286 public boolean updateChannel(String group, String channel, State value) {
1287 return updateChannel(mkChannelId(group, channel), value, false);
1291 public boolean updateChannel(String channelId, State value, boolean force) {
1292 return !stopping && cache.updateChannel(channelId, value, force);
1296 public State getChannelValue(String group, String channel) {
1297 return cache.getValue(group, channel);
1301 public double getChannelDouble(String group, String channel) {
1302 State value = getChannelValue(group, channel);
1303 if (value != UnDefType.NULL) {
1304 if (value instanceof QuantityType<?> quantityCommand) {
1305 return quantityCommand.toBigDecimal().doubleValue();
1307 if (value instanceof DecimalType decimalCommand) {
1308 return decimalCommand.doubleValue();
1315 * Update Thing's channels according to available status information from the API
1317 * @param dynChannels
1320 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1321 if (channelsCreated) {
1322 return; // already done
1326 // Get subset of those channels that currently do not exist
1327 List<Channel> existingChannels = getThing().getChannels();
1328 for (Channel channel : existingChannels) {
1329 String id = channel.getUID().getId();
1330 if (dynChannels.containsKey(id)) {
1331 dynChannels.remove(id);
1335 if (!dynChannels.isEmpty()) {
1336 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1337 ThingBuilder thingBuilder = editThing();
1338 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1339 Channel c = channel.getValue();
1340 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1341 thingBuilder.withChannel(c);
1343 updateThing(thingBuilder.build());
1344 logger.debug("{}: Channel definitions updated", thingName);
1346 } catch (IllegalArgumentException e) {
1347 logger.debug("{}: Unable to update channel definitions", thingName, e);
1352 public boolean areChannelsCreated() {
1353 return channelsCreated;
1357 * Update thing properties with dynamic values
1359 * @param profile The device profile
1360 * @param status the /status result
1362 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1363 Map<String, Object> properties = fillDeviceProperties(profile);
1364 String deviceName = getString(profile.settings.name);
1365 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1366 properties.put(PROPERTY_DEV_AUTH, getBool(profile.device.auth) ? "yes" : "no");
1367 if (!deviceName.isEmpty()) {
1368 properties.put(PROPERTY_DEV_NAME, deviceName);
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);