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 // Create thing handler depending on device generation
157 String thingType = getThingType();
158 blu = ShellyDeviceProfile.isBluSeries(thingType);
159 gen2 = ShellyDeviceProfile.isGeneration2(thingType);
161 this.api = new ShellyBluApi(thingName, thingTable, this);
163 this.api = new Shelly2ApiRpc(thingName, thingTable, this);
165 this.api = new Shelly1HttpApi(thingName, this);
168 config.eventsCoIoT = false;
170 if (config.eventsCoIoT) {
171 this.coap = new Shelly1CoapHandler(this, coapServer);
176 public boolean checkRepresentation(String key) {
177 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
178 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
182 * Schedule asynchronous Thing initialization, register thing to event dispatcher
185 public void initialize() {
186 // start background initialization:
187 initJob = scheduler.schedule(() -> {
188 boolean start = true;
190 if (initializeThingConfig()) {
191 logger.debug("{}: Config: {}", thingName, config);
192 start = initializeThing();
194 } catch (ShellyApiException e) {
195 start = handleApiException(e);
196 } catch (IllegalArgumentException e) {
197 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
199 // even this initialization failed we start the status update
200 // the updateJob will then try to auto-initialize the thing
201 // in this case the thing stays in status INITIALIZING
206 }, 2, TimeUnit.SECONDS);
209 private boolean handleApiException(ShellyApiException e) {
210 ShellyApiResult res = e.getApiResult();
211 ThingStatusDetail errorCode = ThingStatusDetail.COMMUNICATION_ERROR;
213 boolean retry = true;
214 if (e.isJsonError()) { // invalid JSON format
215 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
216 status = "offline.status-error-unexpected-error";
217 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
219 } else if (res.isHttpAccessUnauthorized()) {
220 status = "offline.conf-error-access-denied";
221 errorCode = ThingStatusDetail.CONFIGURATION_ERROR;
223 } else if (isWatchdogExpired()) {
224 status = "offline.status-error-watchdog";
225 } else if (res.httpCode >= 400) {
226 logger.debug("{}: Unexpected API result: {}/{}", thingName, res.httpCode, res.httpReason, e);
227 status = "offline.status-error-unexpected-api-result";
229 } else if (profile.alwaysOn && (e.isConnectionError() || res.isHttpTimeout())) {
230 status = "offline.status-error-connect";
233 if (!status.isEmpty()) {
234 setThingOffline(errorCode, status, e.toString());
236 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
247 public ShellyThingConfiguration getThingConfig() {
252 public HttpClient getHttpClient() {
257 public void startScan() {
258 if (api.isInitialized()) {
262 checkRangeExtender(profile);
266 * This routine is called every time the Thing configuration has been changed
269 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
270 super.handleConfigurationUpdate(configurationParameters);
271 logger.debug("{}: Thing config updated, re-initialize", thingName);
276 reinitializeThing();// force re-initialization
280 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
281 * If the device is password protected and the credentials are missing or don't match the API access will throw an
282 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
283 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
284 * credentials are correct and the API access is initialized successful.
286 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
288 public boolean initializeThing() throws ShellyApiException {
289 // Init from thing type to have a basic profile, gets updated when device info is received from API
290 refreshSettings = false;
291 lastWakeupReason = "";
292 cache.setThingName(thingName);
296 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
297 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
298 if (config.deviceAddress.isEmpty()) {
299 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
303 if (profile.alwaysOn || !profile.isInitialized()) {
304 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
305 messages.get("status.unknown.initializing"));
308 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
309 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
310 // Action URL does when enabled)
311 profile.initFromThingType(thingType);
312 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
313 coap.start(thingName, config);
316 // Initialize API access, exceptions will be catched by initialize()
318 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
319 if (getBool(device.auth) && config.password.isEmpty()) {
320 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
323 if (config.serviceName.isEmpty()) {
324 config.serviceName = getString(device.hostname).toLowerCase();
327 api.setConfig(thingName, config);
328 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
329 String mode = getString(tmpPrf.device.mode);
330 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
331 changeThingType(thingName, mode);
332 return false; // force re-initialization
334 // Validate device mode
335 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
336 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
337 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode, reqMode);
340 if (!getString(tmpPrf.device.coiot).isEmpty()) {
341 // New Shelly devices might use a different endpoint for the CoAP listener
342 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
344 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
345 // Sensor, usually 12h, H&T in USB mode 10min
346 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
347 ? tmpPrf.settings.sleepMode.period * 60 // minutes
348 : tmpPrf.settings.sleepMode.period * 3600; // hours
349 tmpPrf.updatePeriod += 60; // give 1min extra
350 } else if (tmpPrf.settings.coiot != null && tmpPrf.settings.coiot.updatePeriod != null) {
351 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
352 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
353 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
355 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
358 tmpPrf.status = api.getStatus(); // update thing properties
359 tmpPrf.updateFromStatus(tmpPrf.status);
360 addStateOptions(tmpPrf);
362 // update thing properties
363 updateProperties(tmpPrf, tmpPrf.status);
364 checkVersion(tmpPrf, tmpPrf.status);
366 // Check for Range Extender mode, add secondary device to Inbox
367 checkRangeExtender(tmpPrf);
369 startCoap(config, tmpPrf);
371 api.setActionURLs(); // register event urls
374 // All initialization done, so keep the profile and set Thing to ONLINE
375 fillDeviceStatus(tmpPrf.status, false);
376 postEvent(ALARM_TYPE_NONE, false);
379 showThingConfig(profile);
381 logger.debug("{}: Thing successfully initialized.", thingName);
382 updateProperties(profile, profile.status);
383 setThingOnline(); // if API call was successful the thing must be online
384 return true; // success
388 * Handle Channel Commands
391 public void handleCommand(ChannelUID channelUID, Command command) {
393 if (command instanceof RefreshType) {
394 String channelId = channelUID.getId();
395 State value = cache.getValue(channelId);
396 if (value != UnDefType.NULL) {
397 updateState(channelId, value);
402 if (!profile.isInitialized()) {
403 logger.debug("{}: {}", thingName, messages.get("command.init", command));
406 profile = getProfile(false);
409 boolean update = false;
410 switch (channelUID.getIdWithoutGroup()) {
411 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
412 logger.debug("{}: Send key {}", thingName, command);
413 api.sendIRKey(command.toString());
417 case CHANNEL_LED_STATUS_DISABLE:
418 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
419 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
421 case CHANNEL_LED_POWER_DISABLE:
422 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
423 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
426 case CHANNEL_SENSOR_SLEEPTIME:
427 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
428 int value = getNumber(command).intValue();
429 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
431 api.setSleepTime(value);
433 case CHANNEL_CONTROL_SCHEDULE:
435 logger.debug("{}: {} Valve schedule/profile", thingName,
436 command == OnOffType.ON ? "Enable" : "Disable");
437 api.setValveProfile(0,
438 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
441 case CHANNEL_CONTROL_PROFILE:
442 logger.debug("{}: Select profile {}", thingName, command);
444 if (command instanceof Number) {
445 id = getNumber(command).intValue();
447 String cmd = command.toString();
448 if (isDigit(cmd.charAt(0))) {
449 id = Integer.parseInt(cmd);
450 } else if (profile.settings.thermostats != null) {
451 ShellyThermnostat t = profile.settings.thermostats.get(0);
452 for (int i = 0; i < t.profileNames.length; i++) {
453 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
459 if (id < 0 || id > 5) {
460 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
463 api.setValveProfile(0, id);
465 case CHANNEL_CONTROL_MODE:
466 logger.debug("{}: Set mode to {}", thingName, command);
467 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
469 case CHANNEL_CONTROL_SETTEMP:
470 logger.debug("{}: Set temperature to {}", thingName, command);
471 api.setValveTemperature(0, getNumber(command).doubleValue());
473 case CHANNEL_CONTROL_POSITION:
474 logger.debug("{}: Set position to {}", thingName, command);
475 api.setValvePosition(0, getNumber(command));
477 case CHANNEL_CONTROL_BCONTROL:
478 logger.debug("{}: Set boost mode to {}", thingName, command);
479 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
481 case CHANNEL_CONTROL_BTIMER:
482 logger.debug("{}: Set boost timer to {}", thingName, command);
483 api.setValveBoostTime(0, getNumber(command).intValue());
485 case CHANNEL_SENSOR_MUTE:
486 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
487 logger.debug("{}: Mute Smoke Alarm", thingName);
488 api.muteSmokeAlarm(0);
489 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
493 update = handleDeviceCommand(channelUID, command);
498 if (update && !autoCoIoT && !isUpdateScheduled()) {
499 requestUpdates(1, false);
501 } catch (ShellyApiException e) {
502 if (!handleApiException(e)) {
506 ShellyApiResult res = e.getApiResult();
507 if (res.isNotCalibrtated()) {
508 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
510 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
514 String group = getString(channelUID.getGroupId());
515 String channel = getString(channelUID.getIdWithoutGroup());
516 State oldValue = getChannelValue(group, channel);
517 if (oldValue != UnDefType.NULL) {
518 logger.info("{}: Restore channel value to {}", thingName, oldValue);
519 updateChannel(group, channel, oldValue);
522 } catch (IllegalArgumentException e) {
523 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
528 * Update device status and channels
530 protected void refreshStatus() {
532 boolean updated = false;
534 if (vibrationFilter > 0) {
536 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
537 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
541 ThingStatus thingStatus = getThing().getStatus();
542 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
543 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
544 || (thingStatus == ThingStatus.UNKNOWN)) {
545 logger.debug("{}: Status update triggered thing initialization", thingName);
546 initializeThing(); // may fire an exception if initialization failed
548 ShellySettingsStatus status = api.getStatus();
549 boolean restarted = checkRestarted(status);
550 profile = getProfile(refreshSettings || restarted);
551 profile.status = status;
552 profile.updateFromStatus(status);
554 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
556 postEvent(ALARM_TYPE_RESTARTED, true);
559 // If status update was successful the thing must be online,
560 // but not while firmware update is in progress
561 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
565 // map status to channels
566 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
567 updated |= this.updateDeviceStatus(status);
568 updated |= ShellyComponents.updateDeviceStatus(this, status);
569 fillDeviceStatus(status, updated);
570 updated |= updateInputs(status);
571 updated |= updateMeters(this, status);
572 updated |= updateSensors(this, status);
574 // All channels must be created after the first cycle
575 channelsCreated = true;
577 } catch (ShellyApiException e) {
578 // http call failed: go offline except for battery devices, which might be in
579 // sleep mode. Once the next update is successful the device goes back online
580 handleApiException(e);
581 } catch (NullPointerException | IllegalArgumentException e) {
582 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
584 if (scheduledUpdates > 0) {
586 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
587 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
588 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
589 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
595 private void checkRangeExtender(ShellyDeviceProfile prf) {
596 if (getBool(prf.settings.rangeExtender) && config.enableRangeExtender && prf.status.rangeExtender != null
597 && prf.status.rangeExtender.apClients != null) {
598 for (Shelly2APClient client : profile.status.rangeExtender.apClients) {
599 String secondaryIp = config.deviceIp + ":" + client.mport.toString();
600 String name = "shellyplusrange-" + client.mac.replaceAll(":", "");
601 DiscoveryResult result = ShellyBasicDiscoveryService.createResult(true, name, secondaryIp,
602 bindingConfig, httpClient, messages);
603 if (result != null) {
604 thingTable.discoveredResult(result);
610 private void showThingConfig(ShellyDeviceProfile profile) {
611 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
612 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
614 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
615 logger.debug("{}: Device "
616 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
617 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
618 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
619 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
620 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
621 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
622 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
623 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
624 if (profile.status.extTemperature != null || profile.status.extHumidity != null
625 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
626 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
630 private void addStateOptions(ShellyDeviceProfile prf) {
632 String[] profileNames = prf.getValveProfileList(0);
633 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
634 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
635 channelDefinitions.clearStateOptions(channelId);
637 for (String name : profileNames) {
638 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
642 if (prf.isRoller && prf.settings.favorites != null) {
643 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
644 logger.debug("{}: Adding {} roler favorite(s) to channel description", thingName,
645 prf.settings.favorites.size());
646 channelDefinitions.clearStateOptions(channelId);
648 for (ShellyFavPos fav : prf.settings.favorites) {
649 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
656 public String getThingType() {
657 return thing.getThingTypeUID().getId();
661 public ThingStatus getThingStatus() {
662 return thing.getStatus();
666 public ThingStatusDetail getThingStatusDetail() {
667 return thing.getStatusInfo().getStatusDetail();
671 public boolean isThingOnline() {
672 return getThingStatus() == ThingStatus.ONLINE;
675 public boolean isThingOffline() {
676 return getThingStatus() == ThingStatus.OFFLINE;
680 public void setThingOnline() {
681 if (!isThingOnline()) {
682 updateStatus(ThingStatus.ONLINE);
684 // request 3 updates in a row (during the first 2+3*3 sec)
685 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
688 // Restart watchdog when status update was successful (no exception)
693 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
694 if (!isThingOffline()) {
695 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
696 api.close(); // Gen2: disconnect WS/close http sessions
698 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
703 public void restartWatchdog() {
705 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
706 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
709 private boolean isWatchdogExpired() {
710 long delta = now() - watchdog;
711 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
712 stats.remainingWatchdog = delta;
719 public void reinitializeThing() {
720 logger.debug("{}: Re-Initialize Thing", thingName);
722 logger.debug("{}: Handler is shutting down, ignore", thingName);
725 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
726 messages.get("offline.status-error-restarted"));
727 requestUpdates(0, true);
731 public boolean isStopping() {
736 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
739 // Update uptime and WiFi, internal temp
740 ShellyComponents.updateDeviceStatus(this, status);
741 stats.wifiRssi = getInteger(status.wifiSta.rssi);
743 if (api.isInitialized()) {
744 stats.timeoutErrors = api.getTimeoutErrors();
745 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
747 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
749 // Check various device indicators like overheating
750 if (checkRestarted(status)) {
751 // Force re-initialization on next status update
753 } else if (getBool(status.overtemperature)) {
754 alarm = ALARM_TYPE_OVERTEMP;
755 } else if (getBool(status.overload)) {
756 alarm = ALARM_TYPE_OVERLOAD;
757 } else if (getBool(status.loaderror)) {
758 alarm = ALARM_TYPE_LOADERR;
760 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
761 if (internalTemp != UnDefType.NULL) {
762 int temp = ((Number) internalTemp).intValue();
763 if (temp > stats.maxInternalTemp) {
764 stats.maxInternalTemp = temp;
768 if (status.uptime != null) {
769 stats.lastUptime = getLong(status.uptime);
772 if (!alarm.isEmpty()) {
773 postEvent(alarm, false);
778 public void incProtMessages() {
779 stats.protocolMessages++;
783 public void incProtErrors() {
784 stats.protocolErrors++;
788 * Check if device has restarted and needs a new Thing initialization
790 * @return true: restart detected
793 private boolean checkRestarted(ShellySettingsStatus status) {
794 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
795 && (status.uptime != null && status.uptime < stats.lastUptime
796 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
797 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
798 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
799 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
800 updateProperties(profile, status);
807 * Save alarm to the lastAlarm channel
809 * @param event Alarm Message
813 public void postEvent(String event, boolean force) {
814 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
815 State value = cache.getValue(channelId);
816 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
818 if (force || !lastAlarm.equals(event)
819 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
820 switch (event.toUpperCase()) {
823 case SHELLY_WAKEUPT_SENSOR:
824 case SHELLY_WAKEUPT_PERIODIC:
825 case SHELLY_WAKEUPT_BUTTON:
826 case SHELLY_WAKEUPT_POWERON:
827 case SHELLY_WAKEUPT_EXT_POWER:
828 case SHELLY_WAKEUPT_UNKNOWN:
829 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTASTART:
830 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTAPROGRESS:
831 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTADONE:
832 case SHELLY_EVENT_ROLLER_CALIB:
833 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
834 case ALARM_TYPE_NONE:
837 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
838 triggerChannel(channelId, event);
839 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
840 stats.lastAlarm = event;
841 stats.lastAlarmTs = now();
847 public boolean isUpdateScheduled() {
848 return scheduledUpdates > 0;
852 * Callback for device events
855 * @param deviceName device receiving the event
857 * @param type the HTML input data
858 * @param parameters parameters from the event URL
859 * @return true if event was processed
862 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
863 Map<String, String> parameters) {
864 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
865 || config.serviceName.equals(deviceName)) {
866 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
868 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
869 if (!profile.isInitialized()) {
870 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
871 requestUpdates(1, true);
873 String group = profile.getControlGroup(idx);
874 if (group.isEmpty()) {
875 logger.debug("{}: Unsupported event class: {}", thingName, type);
879 // map some of the events to system defined button triggers
883 String parmType = getString(parameters.get("type"));
884 String event = !parmType.isEmpty() ? parmType : type;
885 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
887 case SHELLY_EVENT_SHORTPUSH:
888 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
889 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
890 case SHELLY_EVENT_LONGPUSH:
892 triggerButton(group, idx, mapButtonEvent(event));
893 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
894 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
896 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
900 case SHELLY_EVENT_BTN_ON:
901 case SHELLY_EVENT_BTN_OFF:
902 if (profile.isRGBW2) {
903 // RGBW2 has only one input, so not per channel
904 group = CHANNEL_GROUP_LIGHT_CONTROL;
906 onoff = CHANNEL_INPUT;
908 case SHELLY_EVENT_BTN1_ON:
909 case SHELLY_EVENT_BTN1_OFF:
910 onoff = CHANNEL_INPUT1;
912 case SHELLY_EVENT_BTN2_ON:
913 case SHELLY_EVENT_BTN2_OFF:
914 onoff = CHANNEL_INPUT2;
916 case SHELLY_EVENT_OUT_ON:
917 case SHELLY_EVENT_OUT_OFF:
918 onoff = CHANNEL_OUTPUT;
920 case SHELLY_EVENT_ROLLER_OPEN:
921 case SHELLY_EVENT_ROLLER_CLOSE:
922 case SHELLY_EVENT_ROLLER_STOP:
923 channel = CHANNEL_EVENT_TRIGGER;
926 case SHELLY_EVENT_SENSORREPORT:
927 // process sensor with next refresh
929 case SHELLY_EVENT_TEMP_OVER: // DW2
930 case SHELLY_EVENT_TEMP_UNDER:
931 channel = CHANNEL_EVENT_TRIGGER;
934 case SHELLY_EVENT_FLOOD_DETECTED:
935 case SHELLY_EVENT_FLOOD_GONE:
936 updateChannel(group, CHANNEL_SENSOR_FLOOD,
937 OnOffType.from(event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED)));
940 case SHELLY_EVENT_CLOSE: // DW 1.7
941 case SHELLY_EVENT_OPEN: // DW 1.7
942 updateChannel(group, CHANNEL_SENSOR_STATE,
943 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
944 : OpenClosedType.CLOSED);
947 case SHELLY_EVENT_DARK: // DW 1.7
948 case SHELLY_EVENT_TWILIGHT: // DW 1.7
949 case SHELLY_EVENT_BRIGHT: // DW 1.7
950 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
953 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
954 case SHELLY_EVENT_ALARM_HEAVY:
955 case SHELLY_EVENT_ALARM_OFF:
956 case SHELLY_EVENT_VIBRATION: // DW2
957 channel = CHANNEL_SENSOR_ALARM_STATE;
958 payload = event.toUpperCase();
962 // trigger will be provided by input/output channel or sensor channels
965 if (!onoff.isEmpty()) {
966 updateChannel(group, onoff, OnOffType.from(event.toLowerCase().contains("_on")));
968 if (!payload.isEmpty()) {
969 // Pass event to trigger channel
970 payload = payload.toUpperCase();
971 logger.debug("{}: Post event {}", thingName, payload);
972 triggerChannel(mkChannelId(group, channel), payload);
976 // request update on next interval (2x for non-battery devices)
978 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
985 * Initialize the binding's thing configuration, calc update counts
987 protected boolean initializeThingConfig() {
988 thingType = getThing().getThingTypeUID().getId();
989 final Map<String, String> properties = getThing().getProperties();
990 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
991 if (thingName.isEmpty()) {
992 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
995 config = getConfigAs(ShellyThingConfiguration.class);
996 if (config.deviceAddress.isEmpty()) {
997 config.deviceAddress = config.deviceIp;
999 if (config.deviceAddress.isEmpty()) {
1000 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
1005 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
1006 // convert to lower case
1007 if (!config.deviceIp.isEmpty()) {
1009 String ip = config.deviceIp.contains(":") ? substringBefore(config.deviceIp, ":") : config.deviceIp;
1010 String port = config.deviceIp.contains(":") ? substringAfter(config.deviceIp, ":") : "";
1011 InetAddress addr = InetAddress.getByName(ip);
1012 String saddr = addr.getHostAddress();
1013 if (!ip.equals(saddr)) {
1014 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1015 config.deviceIp = saddr + (port.isEmpty() ? "" : ":" + port);
1017 } catch (UnknownHostException e) {
1018 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1022 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1023 config.localIp = bindingConfig.localIP;
1024 config.localPort = String.valueOf(bindingConfig.httpPort);
1025 if (config.localIp.startsWith("169.254")) {
1026 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, "config-status.error.network-config",
1031 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1032 // Gen2 has hard coded user "admin"
1033 config.userId = bindingConfig.defaultUserId;
1034 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1036 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1037 config.password = bindingConfig.defaultPassword;
1038 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1041 if (config.updateInterval == 0) {
1042 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1044 if (config.updateInterval < UPDATE_MIN_DELAY) {
1045 config.updateInterval = UPDATE_MIN_DELAY;
1048 // Try to get updatePeriod from properties
1049 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1050 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1051 // initialized successfully by the REST call.
1052 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1053 if (!lastPeriod.isEmpty()) {
1054 int period = Integer.parseInt(lastPeriod);
1056 profile.updatePeriod = period;
1060 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1061 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1065 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1067 if (prf.fwVersion.isEmpty()) {
1068 // no fw version available (e.g. BLU device)
1071 ShellyVersionDTO version = new ShellyVersionDTO();
1072 if (version.checkBeta(getString(prf.fwVersion))) {
1073 logger.info("{}: {}", prf.device.hostname,
1074 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1076 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1077 if (version.compare(prf.fwVersion, minVersion) < 0) {
1078 logger.warn("{}: {}", prf.device.hostname,
1079 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1082 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1083 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1084 if (!config.eventsCoIoT) {
1085 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1089 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1090 logger.info("{}: {}", thingName,
1091 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1093 } catch (NullPointerException e) { // could be inconsistant format of beta version
1094 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1098 public String checkForUpdate() {
1100 ShellyOtaCheckResult result = api.checkForUpdate();
1101 return result.status;
1102 } catch (ShellyApiException e) {
1107 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1108 if (coap == null || !config.eventsCoIoT) {
1111 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1112 String devpeer = getString(profile.settings.coiot.peer);
1113 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1114 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1116 api.setCoIoTPeer(ourpeer);
1117 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1118 } catch (ShellyApiException e) {
1119 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1121 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1122 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1126 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1127 config.eventsCoIoT = true;
1128 config.eventsSwitch = false;
1129 config.eventsButton = false;
1130 config.eventsPush = false;
1131 config.eventsRoller = false;
1132 config.eventsSensorReport = false;
1133 api.setConfig(thingName, config);
1136 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1138 coap.start(thingName, config);
1143 * Change type of this thing.
1145 * @param thingType thing type acc. to the xml definition
1146 * @param mode Device mode (e.g. relay, roller)
1148 protected void changeThingType(String thingType, String mode) {
1149 String deviceType = substringBefore(thingType, "-");
1150 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1151 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1152 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1153 Map<String, String> properties = editProperties();
1154 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1155 properties.replace(PROPERTY_DEV_MODE, mode);
1156 updateProperties(properties);
1157 changeThingType(thingTypeUID, getConfig());
1159 logger.debug("{}: to {}", thingName, thingType);
1160 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "Unable to change thing type to " + thingType);
1165 public void thingUpdated(Thing thing) {
1166 logger.debug("{}: Channel definitions updated.", thingName);
1167 super.thingUpdated(thing);
1171 * Start the background updates
1173 protected void startUpdateJob() {
1174 ScheduledFuture<?> statusJob = this.statusJob;
1175 if ((statusJob == null) || statusJob.isCancelled()) {
1176 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1178 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1179 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1184 * Flag the status job to do an exceptional update (something happened) rather
1185 * than waiting until the next regular poll
1187 * @param requestCount number of polls to execute
1188 * @param refreshSettings true=force a /settings query
1189 * @return true=Update schedule, false=skipped (too many updates already
1193 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1194 this.refreshSettings |= refreshSettings;
1195 if (refreshSettings) {
1196 if (requestCount == 0) {
1197 logger.debug("{}: Request settings refresh", thingName);
1199 scheduledUpdates = 1;
1202 if (scheduledUpdates < 10) { // < 30s
1203 scheduledUpdates += requestCount;
1210 * Map input states to channels
1212 * @param status Shelly device status
1213 * @return true: one or more inputs were updated
1216 public boolean updateInputs(ShellySettingsStatus status) {
1217 boolean updated = false;
1219 if (status.inputs != null) {
1220 if (!areChannelsCreated()) {
1221 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1225 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1226 for (ShellyInputState input : status.inputs) {
1227 String group = profile.getInputGroup(idx);
1228 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1229 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1230 if (input.event != null) {
1231 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1232 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1237 if (status.input != null) {
1238 // RGBW2: a single int rather than an array
1239 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1240 OnOffType.from(getInteger(status.input) != 0));
1247 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1248 boolean changed = false;
1249 if (valueArray != null && !valueArray.isEmpty()) {
1250 String reason = getString((String) valueArray.get(0));
1251 String newVal = valueArray.toString();
1252 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1253 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1255 postEvent(reason.toUpperCase(), true);
1257 lastWakeupReason = newVal;
1263 public void triggerButton(String group, int idx, String value) {
1264 String trigger = mapButtonEvent(value);
1265 if (trigger.isEmpty()) {
1269 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1270 triggerChannel(group,
1271 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1273 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1274 if (profile.alwaysOn) {
1275 // refresh status of the input channel
1276 requestUpdates(1, false);
1281 public void publishState(String channelId, State value) {
1282 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1283 if (!stopping && isLinked(id)) {
1284 updateState(id, value);
1285 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1290 public boolean updateChannel(String group, String channel, State value) {
1291 return updateChannel(mkChannelId(group, channel), value, false);
1295 public boolean updateChannel(String channelId, State value, boolean force) {
1296 return !stopping && cache.updateChannel(channelId, value, force);
1300 public State getChannelValue(String group, String channel) {
1301 return cache.getValue(group, channel);
1305 public double getChannelDouble(String group, String channel) {
1306 State value = getChannelValue(group, channel);
1307 if (value != UnDefType.NULL) {
1308 if (value instanceof QuantityType<?> quantityCommand) {
1309 return quantityCommand.toBigDecimal().doubleValue();
1311 if (value instanceof DecimalType decimalCommand) {
1312 return decimalCommand.doubleValue();
1319 * Update Thing's channels according to available status information from the API
1321 * @param dynChannels
1324 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1325 if (channelsCreated) {
1326 return; // already done
1330 // Get subset of those channels that currently do not exist
1331 List<Channel> existingChannels = getThing().getChannels();
1332 for (Channel channel : existingChannels) {
1333 String id = channel.getUID().getId();
1334 if (dynChannels.containsKey(id)) {
1335 dynChannels.remove(id);
1339 if (!dynChannels.isEmpty()) {
1340 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1341 ThingBuilder thingBuilder = editThing();
1342 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1343 Channel c = channel.getValue();
1344 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1345 thingBuilder.withChannel(c);
1347 updateThing(thingBuilder.build());
1348 logger.debug("{}: Channel definitions updated", thingName);
1350 } catch (IllegalArgumentException e) {
1351 logger.debug("{}: Unable to update channel definitions", thingName, e);
1356 public boolean areChannelsCreated() {
1357 return channelsCreated;
1361 * Update thing properties with dynamic values
1363 * @param profile The device profile
1364 * @param status the /status result
1366 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1367 Map<String, Object> properties = fillDeviceProperties(profile);
1368 String deviceName = getString(profile.settings.name);
1369 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1370 properties.put(PROPERTY_DEV_AUTH, getBool(profile.device.auth) ? "yes" : "no");
1371 if (!deviceName.isEmpty()) {
1372 properties.put(PROPERTY_DEV_NAME, deviceName);
1375 // add status properties
1376 if (status.wifiSta != null) {
1377 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1379 if (status.update != null) {
1380 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1381 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1382 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1383 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1385 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1387 Map<String, String> thingProperties = new TreeMap<>();
1388 for (Map.Entry<String, Object> property : properties.entrySet()) {
1389 thingProperties.put(property.getKey(), (String) property.getValue());
1391 flushProperties(thingProperties);
1395 * Add one property to the Thing Properties
1397 * @param key Name of the property
1398 * @param value Value of the property
1401 public void updateProperties(String key, String value) {
1402 Map<String, String> thingProperties = editProperties();
1403 if (thingProperties.containsKey(key)) {
1404 thingProperties.replace(key, value);
1406 thingProperties.put(key, value);
1408 updateProperties(thingProperties);
1409 logger.trace("{}: Properties updated", thingName);
1412 public void flushProperties(Map<String, String> propertyUpdates) {
1413 Map<String, String> thingProperties = editProperties();
1414 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1415 if (thingProperties.containsKey(property.getKey())) {
1416 thingProperties.replace(property.getKey(), property.getValue());
1418 thingProperties.put(property.getKey(), property.getValue());
1421 updateProperties(thingProperties);
1425 * Get one property from the Thing Properties
1427 * @param key property name
1428 * @return property value or "" if property is not set
1431 public String getProperty(String key) {
1432 Map<String, String> thingProperties = getThing().getProperties();
1433 return getString(thingProperties.get(key));
1437 * Fill Thing Properties with device attributes
1439 * @param profile Property Map to full
1440 * @return a full property map
1442 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1443 Map<String, Object> properties = new TreeMap<>();
1444 properties.put(PROPERTY_VENDOR, VENDOR);
1445 if (profile.isInitialized()) {
1446 properties.put(PROPERTY_MODEL_ID, getString(profile.device.type));
1447 properties.put(PROPERTY_MAC_ADDRESS, profile.device.mac);
1448 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1449 properties.put(PROPERTY_DEV_MODE, profile.device.mode);
1450 if (profile.hasRelays) {
1451 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1452 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1453 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1455 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1456 if (!profile.hwRev.isEmpty()) {
1457 properties.put(PROPERTY_HWREV, profile.hwRev);
1458 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1465 * Return device profile.
1467 * @param forceRefresh true=force refresh before returning, false=return without
1469 * @return ShellyDeviceProfile instance
1470 * @throws ShellyApiException
1473 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1475 refreshSettings |= forceRefresh;
1476 if (refreshSettings) {
1477 profile = api.getDeviceProfile(thingType, null);
1478 if (!isThingOnline()) {
1479 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1483 refreshSettings = false;
1489 public ShellyDeviceProfile getProfile() {
1494 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1495 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1496 if (!options.isEmpty()) {
1497 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1503 protected ShellyDeviceProfile getDeviceProfile() {
1508 public void triggerChannel(String group, String channel, String payload) {
1509 String triggerCh = mkChannelId(group, channel);
1510 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1511 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1512 if (vibrationFilter == 0) {
1513 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1514 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1515 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1517 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1518 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1523 triggerChannel(triggerCh, payload);
1526 public void stop() {
1527 logger.debug("{}: Shutting down", thingName);
1528 ScheduledFuture<?> job = this.initJob;
1533 job = this.statusJob;
1537 logger.debug("{}: Shelly statusJob stopped", thingName);
1540 profile.initialized = false;
1544 * Shutdown thing, make sure background jobs are canceled
1547 public void dispose() {
1548 logger.debug("{}: Stopping Thing", thingName);
1555 * Device specific command handlers are overriding this method to do additional stuff
1557 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1561 public String getUID() {
1562 return getThing().getUID().getAsString();
1566 * Device specific handlers are overriding this method to do additional stuff
1568 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1573 public String getThingName() {
1578 public void resetStats() {
1580 stats = new ShellyDeviceStats();
1584 public ShellyDeviceStats getStats() {
1589 public ShellyApiInterface getApi() {
1594 public long getScheduledUpdates() {
1595 return scheduledUpdates;
1598 public Map<String, String> getStatsProp() {
1599 return stats.asProperties();
1603 public void triggerUpdateFromCoap() {
1604 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1605 requestUpdates(1, false);