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 setThingOfflineAndDisconnect(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 profile.initFromThingType(thingType);
298 "{}: Start initializing for thing {}, type {}, Device address {}, Gen2: {}, isBlu: {}, alwaysOn: {}, hasBattery: {}, CoIoT: {}",
299 thingName, getThing().getLabel(), thingType, config.deviceAddress.toUpperCase(), gen2, profile.isBlu,
300 profile.alwaysOn, profile.hasBattery, config.eventsCoIoT);
301 if (config.deviceAddress.isEmpty()) {
302 setThingOfflineAndDisconnect(ThingStatusDetail.CONFIGURATION_ERROR,
303 "config-status.error.missing-device-address");
307 if (profile.alwaysOn || !profile.isInitialized()) {
308 ThingStatusDetail detail = getThingStatusDetail();
309 if (detail != ThingStatusDetail.DUTY_CYCLE) {
310 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
311 messages.get("status.config_pending"));
315 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
316 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
317 // Action URL does when enabled)
318 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
319 coap.start(thingName, config);
322 // Initialize API access, exceptions will be catched by initialize()
324 ShellySettingsDevice device = profile.device = api.getDeviceInfo();
325 if (getBool(device.auth) && config.password.isEmpty()) {
326 setThingOfflineAndDisconnect(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
329 if (config.serviceName.isEmpty()) {
330 config.serviceName = getString(device.hostname).toLowerCase();
333 api.setConfig(thingName, config);
334 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType, profile.device);
335 tmpPrf.initFromThingType(thingType);
336 String mode = getString(tmpPrf.device.mode);
337 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
338 changeThingType(thingName, mode);
339 return false; // force re-initialization
341 // Validate device mode
342 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
343 if (!reqMode.isEmpty() && !mode.equals(reqMode)) {
344 setThingOfflineAndDisconnect(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", mode,
348 if (!getString(tmpPrf.device.coiot).isEmpty()) {
349 // New Shelly devices might use a different endpoint for the CoAP listener
350 tmpPrf.coiotEndpoint = tmpPrf.device.coiot;
352 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
353 // Sensor, usually 12h, H&T in USB mode 10min
354 tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
355 ? tmpPrf.settings.sleepMode.period * 60 // minutes
356 : tmpPrf.settings.sleepMode.period * 3600; // hours
357 tmpPrf.updatePeriod += 60; // give 1min extra
358 } else if (tmpPrf.settings.coiot != null && tmpPrf.settings.coiot.updatePeriod != null) {
359 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
360 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
361 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
363 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
366 tmpPrf.status = api.getStatus(); // update thing properties
367 tmpPrf.updateFromStatus(tmpPrf.status);
368 addStateOptions(tmpPrf);
370 // update thing properties
371 updateProperties(tmpPrf, tmpPrf.status);
372 checkVersion(tmpPrf, tmpPrf.status);
374 // Check for Range Extender mode, add secondary device to Inbox
375 checkRangeExtender(tmpPrf);
377 startCoap(config, tmpPrf);
379 api.setActionURLs(); // register event urls
382 // All initialization done, so keep the profile and set Thing to ONLINE
383 fillDeviceStatus(tmpPrf.status, false);
384 postEvent(ALARM_TYPE_NONE, false);
387 showThingConfig(profile);
389 logger.debug("{}: Thing successfully initialized.", thingName);
390 updateProperties(profile, profile.status);
391 setThingOnline(); // if API call was successful the thing must be online
392 return true; // success
396 * Handle Channel Commands
399 public void handleCommand(ChannelUID channelUID, Command command) {
401 if (command instanceof RefreshType) {
402 String channelId = channelUID.getId();
403 State value = cache.getValue(channelId);
404 if (value != UnDefType.NULL) {
405 updateState(channelId, value);
410 if (!profile.isInitialized()) {
411 logger.debug("{}: {}", thingName, messages.get("command.init", command));
414 profile = getProfile(false);
417 boolean update = false;
418 switch (channelUID.getIdWithoutGroup()) {
419 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
420 logger.debug("{}: Send key {}", thingName, command);
421 api.sendIRKey(command.toString());
425 case CHANNEL_LED_STATUS_DISABLE:
426 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
427 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
429 case CHANNEL_LED_POWER_DISABLE:
430 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
431 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
434 case CHANNEL_SENSOR_SLEEPTIME:
435 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
436 int value = getNumber(command).intValue();
437 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
439 api.setSleepTime(value);
441 case CHANNEL_CONTROL_SCHEDULE:
443 logger.debug("{}: {} Valve schedule/profile", thingName,
444 command == OnOffType.ON ? "Enable" : "Disable");
445 api.setValveProfile(0,
446 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
449 case CHANNEL_CONTROL_PROFILE:
450 logger.debug("{}: Select profile {}", thingName, command);
452 if (command instanceof Number) {
453 id = getNumber(command).intValue();
455 String cmd = command.toString();
456 if (isDigit(cmd.charAt(0))) {
457 id = Integer.parseInt(cmd);
458 } else if (profile.settings.thermostats != null) {
459 ShellyThermnostat t = profile.settings.thermostats.get(0);
460 for (int i = 0; i < t.profileNames.length; i++) {
461 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
467 if (id < 0 || id > 5) {
468 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
471 api.setValveProfile(0, id);
473 case CHANNEL_CONTROL_MODE:
474 logger.debug("{}: Set mode to {}", thingName, command);
475 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
477 case CHANNEL_CONTROL_SETTEMP:
478 logger.debug("{}: Set temperature to {}", thingName, command);
479 api.setValveTemperature(0, getNumber(command).doubleValue());
481 case CHANNEL_CONTROL_POSITION:
482 logger.debug("{}: Set position to {}", thingName, command);
483 api.setValvePosition(0, getNumber(command));
485 case CHANNEL_CONTROL_BCONTROL:
486 logger.debug("{}: Set boost mode to {}", thingName, command);
487 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
489 case CHANNEL_CONTROL_BTIMER:
490 logger.debug("{}: Set boost timer to {}", thingName, command);
491 api.setValveBoostTime(0, getNumber(command).intValue());
493 case CHANNEL_SENSOR_MUTE:
494 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
495 logger.debug("{}: Mute Smoke Alarm", thingName);
496 api.muteSmokeAlarm(0);
497 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
501 update = handleDeviceCommand(channelUID, command);
506 if (update && !autoCoIoT && !isUpdateScheduled()) {
507 requestUpdates(1, false);
509 } catch (ShellyApiException e) {
510 if (!handleApiException(e)) {
514 ShellyApiResult res = e.getApiResult();
515 if (res.isNotCalibrtated()) {
516 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
518 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
522 String group = getString(channelUID.getGroupId());
523 String channel = getString(channelUID.getIdWithoutGroup());
524 State oldValue = getChannelValue(group, channel);
525 if (oldValue != UnDefType.NULL) {
526 logger.info("{}: Restore channel value to {}", thingName, oldValue);
527 updateChannel(group, channel, oldValue);
530 } catch (IllegalArgumentException e) {
531 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
536 * Update device status and channels
538 protected void refreshStatus() {
540 boolean updated = false;
542 if (vibrationFilter > 0) {
544 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
545 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
549 ThingStatus thingStatus = getThing().getStatus();
550 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
551 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
552 || (getThingStatusDetail() == ThingStatusDetail.CONFIGURATION_PENDING)) {
553 logger.debug("{}: Status update triggered thing initialization", thingName);
554 initializeThing(); // may fire an exception if initialization failed
556 ShellySettingsStatus status = api.getStatus();
557 boolean restarted = checkRestarted(status);
558 profile = getProfile(refreshSettings || restarted);
559 profile.status = status;
560 profile.updateFromStatus(status);
562 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
564 postEvent(ALARM_TYPE_RESTARTED, true);
567 // If status update was successful the thing must be online,
568 // but not while firmware update is in progress
569 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
573 // map status to channels
574 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
575 updated |= this.updateDeviceStatus(status);
576 updated |= ShellyComponents.updateDeviceStatus(this, status);
577 fillDeviceStatus(status, updated);
578 updated |= updateInputs(status);
579 updated |= updateMeters(this, status);
580 updated |= updateSensors(this, status);
582 // All channels must be created after the first cycle
583 channelsCreated = true;
585 } catch (ShellyApiException e) {
586 // http call failed: go offline except for battery devices, which might be in
587 // sleep mode. Once the next update is successful the device goes back online
588 handleApiException(e);
589 } catch (NullPointerException | IllegalArgumentException e) {
590 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
592 if (scheduledUpdates > 0) {
594 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
595 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
596 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
597 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
603 private void checkRangeExtender(ShellyDeviceProfile prf) {
604 if (getBool(prf.settings.rangeExtender) && config.enableRangeExtender && prf.status.rangeExtender != null
605 && prf.status.rangeExtender.apClients != null) {
606 for (Shelly2APClient client : profile.status.rangeExtender.apClients) {
607 String secondaryIp = config.deviceIp + ":" + client.mport.toString();
608 String name = "shellyplusrange-" + client.mac.replaceAll(":", "");
609 DiscoveryResult result = ShellyBasicDiscoveryService.createResult(true, name, secondaryIp,
610 bindingConfig, httpClient, messages);
611 if (result != null) {
612 thingTable.discoveredResult(result);
618 private void showThingConfig(ShellyDeviceProfile profile) {
619 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
620 profile.device.hostname, profile.device.type, profile.hwRev, profile.hwBatchId, profile.fwVersion,
622 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.device.hostname, profile.settingsJson);
623 logger.debug("{}: Device "
624 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
625 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
626 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
627 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
628 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
629 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
630 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
631 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
632 if (profile.status.extTemperature != null || profile.status.extHumidity != null
633 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
634 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
638 private void addStateOptions(ShellyDeviceProfile prf) {
640 String[] profileNames = prf.getValveProfileList(0);
641 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
642 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
643 channelDefinitions.clearStateOptions(channelId);
645 for (String name : profileNames) {
646 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
650 if (prf.isRoller && prf.settings.favorites != null) {
651 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
652 logger.debug("{}: Adding {} roler favorite(s) to channel description", thingName,
653 prf.settings.favorites.size());
654 channelDefinitions.clearStateOptions(channelId);
656 for (ShellyFavPos fav : prf.settings.favorites) {
657 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
664 public String getThingType() {
665 return thing.getThingTypeUID().getId();
669 public ThingStatus getThingStatus() {
670 return thing.getStatus();
674 public ThingStatusDetail getThingStatusDetail() {
675 return thing.getStatusInfo().getStatusDetail();
679 public boolean isThingOnline() {
680 return getThingStatus() == ThingStatus.ONLINE
681 && getThingStatusDetail() != ThingStatusDetail.CONFIGURATION_PENDING;
684 public boolean isThingOffline() {
685 return getThingStatus() == ThingStatus.OFFLINE;
689 public void setThingOnline() {
690 if (!isThingOnline()) {
691 updateStatus(ThingStatus.ONLINE);
693 // request 3 updates in a row (during the first 2+3*3 sec)
694 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
697 // Restart watchdog when status update was successful (no exception)
702 public void setThingOfflineAndDisconnect(ThingStatusDetail detail, String messageKey, Object... arguments) {
703 if (!isThingOffline()) {
704 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
706 api.close(); // Gen2: disconnect WS/close http sessions
708 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
712 public void setThingStatus(ThingStatus status, ThingStatusDetail detail, String messageKey, Object... arguments) {
713 updateStatus(status, detail, messages.get(messageKey, arguments));
717 public void restartWatchdog() {
719 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
720 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
723 private boolean isWatchdogExpired() {
724 long delta = now() - watchdog;
725 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
726 stats.remainingWatchdog = delta;
733 public void reinitializeThing() {
734 logger.debug("{}: Re-Initialize Thing", thingName);
736 logger.debug("{}: Handler is shutting down, ignore", thingName);
739 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.CONFIGURATION_PENDING,
740 messages.get("offline.status-error-restarted"));
741 requestUpdates(0, true);
745 public boolean isStopping() {
750 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
753 // Update uptime and WiFi, internal temp
754 ShellyComponents.updateDeviceStatus(this, status);
755 stats.wifiRssi = getInteger(status.wifiSta.rssi);
757 if (api.isInitialized()) {
758 stats.timeoutErrors = api.getTimeoutErrors();
759 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
761 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
763 // Check various device indicators like overheating
764 if (checkRestarted(status)) {
765 // Force re-initialization on next status update
767 } else if (getBool(status.overtemperature)) {
768 alarm = ALARM_TYPE_OVERTEMP;
769 } else if (getBool(status.overload)) {
770 alarm = ALARM_TYPE_OVERLOAD;
771 } else if (getBool(status.loaderror)) {
772 alarm = ALARM_TYPE_LOADERR;
774 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
775 if (internalTemp != UnDefType.NULL) {
776 int temp = ((Number) internalTemp).intValue();
777 if (temp > stats.maxInternalTemp) {
778 stats.maxInternalTemp = temp;
782 if (status.uptime != null) {
783 stats.lastUptime = getLong(status.uptime);
786 if (!alarm.isEmpty()) {
787 postEvent(alarm, false);
792 public void incProtMessages() {
793 stats.protocolMessages++;
797 public void incProtErrors() {
798 stats.protocolErrors++;
802 * Check if device has restarted and needs a new Thing initialization
804 * @return true: restart detected
807 private boolean checkRestarted(ShellySettingsStatus status) {
808 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
809 && (status.uptime != null && status.uptime < stats.lastUptime
810 || (profile.status.update != null && !getString(profile.status.update.oldVersion).isEmpty()
811 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
812 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
813 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
814 updateProperties(profile, status);
821 * Save alarm to the lastAlarm channel
823 * @param event Alarm Message
827 public void postEvent(String event, boolean force) {
828 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
829 State value = cache.getValue(channelId);
830 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
832 if (force || !lastAlarm.equals(event)
833 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
834 switch (event.toUpperCase()) {
837 case SHELLY_WAKEUPT_SENSOR:
838 case SHELLY_WAKEUPT_PERIODIC:
839 case SHELLY_WAKEUPT_BUTTON:
840 case SHELLY_WAKEUPT_POWERON:
841 case SHELLY_WAKEUPT_EXT_POWER:
842 case SHELLY_WAKEUPT_UNKNOWN:
843 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTASTART:
844 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTAPROGRESS:
845 case Shelly2ApiJsonDTO.SHELLY2_EVENT_OTADONE:
846 case SHELLY_EVENT_ROLLER_CALIB:
847 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
848 case ALARM_TYPE_NONE:
851 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
852 triggerChannel(channelId, event);
853 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
854 stats.lastAlarm = event;
855 stats.lastAlarmTs = now();
861 public boolean isUpdateScheduled() {
862 return scheduledUpdates > 0;
866 * Callback for device events
869 * @param deviceName device receiving the event
871 * @param type the HTML input data
872 * @param parameters parameters from the event URL
873 * @return true if event was processed
876 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
877 Map<String, String> parameters) {
878 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
879 || config.serviceName.equals(deviceName)) {
880 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
882 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
883 if (!profile.isInitialized()) {
884 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
885 requestUpdates(1, true);
887 String group = profile.getControlGroup(idx);
888 if (group.isEmpty()) {
889 logger.debug("{}: Unsupported event class: {}", thingName, type);
893 // map some of the events to system defined button triggers
897 String parmType = getString(parameters.get("type"));
898 String event = !parmType.isEmpty() ? parmType : type;
899 boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
901 case SHELLY_EVENT_SHORTPUSH:
902 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
903 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
904 case SHELLY_EVENT_LONGPUSH:
906 triggerButton(group, idx, mapButtonEvent(event));
907 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
908 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
910 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
914 case SHELLY_EVENT_BTN_ON:
915 case SHELLY_EVENT_BTN_OFF:
916 if (profile.isRGBW2) {
917 // RGBW2 has only one input, so not per channel
918 group = CHANNEL_GROUP_LIGHT_CONTROL;
920 onoff = CHANNEL_INPUT;
922 case SHELLY_EVENT_BTN1_ON:
923 case SHELLY_EVENT_BTN1_OFF:
924 onoff = CHANNEL_INPUT1;
926 case SHELLY_EVENT_BTN2_ON:
927 case SHELLY_EVENT_BTN2_OFF:
928 onoff = CHANNEL_INPUT2;
930 case SHELLY_EVENT_OUT_ON:
931 case SHELLY_EVENT_OUT_OFF:
932 onoff = CHANNEL_OUTPUT;
934 case SHELLY_EVENT_ROLLER_OPEN:
935 case SHELLY_EVENT_ROLLER_CLOSE:
936 case SHELLY_EVENT_ROLLER_STOP:
937 channel = CHANNEL_EVENT_TRIGGER;
940 case SHELLY_EVENT_SENSORREPORT:
941 // process sensor with next refresh
943 case SHELLY_EVENT_TEMP_OVER: // DW2
944 case SHELLY_EVENT_TEMP_UNDER:
945 channel = CHANNEL_EVENT_TRIGGER;
948 case SHELLY_EVENT_FLOOD_DETECTED:
949 case SHELLY_EVENT_FLOOD_GONE:
950 updateChannel(group, CHANNEL_SENSOR_FLOOD,
951 OnOffType.from(event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED)));
954 case SHELLY_EVENT_CLOSE: // DW 1.7
955 case SHELLY_EVENT_OPEN: // DW 1.7
956 updateChannel(group, CHANNEL_SENSOR_STATE,
957 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
958 : OpenClosedType.CLOSED);
961 case SHELLY_EVENT_DARK: // DW 1.7
962 case SHELLY_EVENT_TWILIGHT: // DW 1.7
963 case SHELLY_EVENT_BRIGHT: // DW 1.7
964 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
967 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
968 case SHELLY_EVENT_ALARM_HEAVY:
969 case SHELLY_EVENT_ALARM_OFF:
970 case SHELLY_EVENT_VIBRATION: // DW2
971 channel = CHANNEL_SENSOR_ALARM_STATE;
972 payload = event.toUpperCase();
976 // trigger will be provided by input/output channel or sensor channels
979 if (!onoff.isEmpty()) {
980 updateChannel(group, onoff, OnOffType.from(event.toLowerCase().contains("_on")));
982 if (!payload.isEmpty()) {
983 // Pass event to trigger channel
984 payload = payload.toUpperCase();
985 logger.debug("{}: Post event {}", thingName, payload);
986 triggerChannel(mkChannelId(group, channel), payload);
990 // request update on next interval (2x for non-battery devices)
992 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
999 * Initialize the binding's thing configuration, calc update counts
1001 protected boolean initializeThingConfig() {
1002 thingType = getThing().getThingTypeUID().getId();
1003 final Map<String, String> properties = getThing().getProperties();
1004 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
1005 if (thingName.isEmpty()) {
1006 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
1009 config = getConfigAs(ShellyThingConfiguration.class);
1010 if (config.deviceAddress.isEmpty()) {
1011 config.deviceAddress = config.deviceIp;
1013 if (config.deviceAddress.isEmpty()) {
1014 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
1019 config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
1020 // convert to lower case
1021 if (!config.deviceIp.isEmpty()) {
1023 String ip = config.deviceIp.contains(":") ? substringBefore(config.deviceIp, ":") : config.deviceIp;
1024 String port = config.deviceIp.contains(":") ? substringAfter(config.deviceIp, ":") : "";
1025 InetAddress addr = InetAddress.getByName(ip);
1026 String saddr = addr.getHostAddress();
1027 if (!ip.equals(saddr)) {
1028 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1029 config.deviceIp = saddr + (port.isEmpty() ? "" : ":" + port);
1031 } catch (UnknownHostException e) {
1032 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1036 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1037 config.localIp = bindingConfig.localIP;
1038 config.localPort = String.valueOf(bindingConfig.httpPort);
1039 if (config.localIp.startsWith("169.254")) {
1040 setThingOfflineAndDisconnect(ThingStatusDetail.COMMUNICATION_ERROR, "config-status.error.network-config",
1045 if (!profile.isGen2 && config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1046 // Gen2 has hard coded user "admin"
1047 config.userId = bindingConfig.defaultUserId;
1048 logger.debug("{}: Using default userId {} from binding config", thingName, config.userId);
1050 if (config.password.isEmpty() && !bindingConfig.defaultPassword.isEmpty()) {
1051 config.password = bindingConfig.defaultPassword;
1052 logger.debug("{}: Using default password from bindingConfig (userId={})", thingName, config.userId);
1055 if (config.updateInterval == 0) {
1056 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1058 if (config.updateInterval < UPDATE_MIN_DELAY) {
1059 config.updateInterval = UPDATE_MIN_DELAY;
1062 // Try to get updatePeriod from properties
1063 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1064 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1065 // initialized successfully by the REST call.
1066 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1067 if (!lastPeriod.isEmpty()) {
1068 int period = Integer.parseInt(lastPeriod);
1070 profile.updatePeriod = period;
1074 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1075 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1079 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1081 if (prf.fwVersion.isEmpty()) {
1082 // no fw version available (e.g. BLU device)
1085 ShellyVersionDTO version = new ShellyVersionDTO();
1086 if (version.checkBeta(getString(prf.fwVersion))) {
1087 logger.info("{}: {}", prf.device.hostname,
1088 messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1090 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1091 if (version.compare(prf.fwVersion, minVersion) < 0) {
1092 logger.warn("{}: {}", prf.device.hostname,
1093 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1096 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1097 || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
1098 if (!config.eventsCoIoT) {
1099 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1103 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1104 logger.info("{}: {}", thingName,
1105 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1107 } catch (NullPointerException e) { // could be inconsistant format of beta version
1108 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1112 public String checkForUpdate() {
1114 ShellyOtaCheckResult result = api.checkForUpdate();
1115 return result.status;
1116 } catch (ShellyApiException e) {
1121 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1122 if (coap == null || !config.eventsCoIoT) {
1125 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1126 String devpeer = getString(profile.settings.coiot.peer);
1127 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1128 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1130 api.setCoIoTPeer(ourpeer);
1131 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1132 } catch (ShellyApiException e) {
1133 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1135 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1136 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1140 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1141 config.eventsCoIoT = true;
1142 config.eventsSwitch = false;
1143 config.eventsButton = false;
1144 config.eventsPush = false;
1145 config.eventsRoller = false;
1146 config.eventsSensorReport = false;
1147 api.setConfig(thingName, config);
1150 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1152 coap.start(thingName, config);
1157 * Change type of this thing.
1159 * @param thingType thing type acc. to the xml definition
1160 * @param mode Device mode (e.g. relay, roller)
1162 protected void changeThingType(String thingType, String mode) {
1163 String deviceType = substringBefore(thingType, "-");
1164 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, deviceType, mode);
1165 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1166 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1167 Map<String, String> properties = editProperties();
1168 properties.replace(PROPERTY_DEV_TYPE, deviceType);
1169 properties.replace(PROPERTY_DEV_MODE, mode);
1170 updateProperties(properties);
1171 changeThingType(thingTypeUID, getConfig());
1173 logger.debug("{}: to {}", thingName, thingType);
1174 setThingOfflineAndDisconnect(ThingStatusDetail.CONFIGURATION_ERROR,
1175 "Unable to change thing type to " + thingType);
1180 public void thingUpdated(Thing thing) {
1181 logger.debug("{}: Channel definitions updated.", thingName);
1182 super.thingUpdated(thing);
1186 * Start the background updates
1188 protected void startUpdateJob() {
1189 ScheduledFuture<?> statusJob = this.statusJob;
1190 if ((statusJob == null) || statusJob.isCancelled()) {
1191 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1193 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1194 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1199 * Flag the status job to do an exceptional update (something happened) rather
1200 * than waiting until the next regular poll
1202 * @param requestCount number of polls to execute
1203 * @param refreshSettings true=force a /settings query
1204 * @return true=Update schedule, false=skipped (too many updates already
1208 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1209 this.refreshSettings |= refreshSettings;
1210 if (refreshSettings) {
1211 if (requestCount == 0) {
1212 logger.debug("{}: Request settings refresh", thingName);
1214 scheduledUpdates = 1;
1217 if (scheduledUpdates < 10) { // < 30s
1218 scheduledUpdates += requestCount;
1225 * Map input states to channels
1227 * @param status Shelly device status
1228 * @return true: one or more inputs were updated
1231 public boolean updateInputs(ShellySettingsStatus status) {
1232 boolean updated = false;
1234 if (status.inputs != null) {
1235 if (!areChannelsCreated()) {
1236 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1240 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1241 for (ShellyInputState input : status.inputs) {
1242 String group = profile.getInputGroup(idx);
1243 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1244 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1245 if (input.event != null) {
1246 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1247 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1252 if (status.input != null) {
1253 // RGBW2: a single int rather than an array
1254 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1255 OnOffType.from(getInteger(status.input) != 0));
1262 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1263 boolean changed = false;
1264 if (valueArray != null && !valueArray.isEmpty()) {
1265 String reason = getString((String) valueArray.get(0));
1266 String newVal = valueArray.toString();
1267 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1268 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1270 postEvent(reason.toUpperCase(), true);
1272 lastWakeupReason = newVal;
1278 public void triggerButton(String group, int idx, String value) {
1279 String trigger = mapButtonEvent(value);
1280 if (trigger.isEmpty()) {
1284 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1285 triggerChannel(group,
1286 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1288 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1289 if (profile.alwaysOn) {
1290 // refresh status of the input channel
1291 requestUpdates(1, false);
1296 public void publishState(String channelId, State value) {
1297 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1298 if (!stopping && isLinked(id)) {
1299 updateState(id, value);
1300 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1305 public boolean updateChannel(String group, String channel, State value) {
1306 return updateChannel(mkChannelId(group, channel), value, false);
1310 public boolean updateChannel(String channelId, State value, boolean force) {
1311 return !stopping && cache.updateChannel(channelId, value, force);
1315 public State getChannelValue(String group, String channel) {
1316 return cache.getValue(group, channel);
1320 public double getChannelDouble(String group, String channel) {
1321 State value = getChannelValue(group, channel);
1322 if (value != UnDefType.NULL) {
1323 if (value instanceof QuantityType<?> quantityCommand) {
1324 return quantityCommand.toBigDecimal().doubleValue();
1326 if (value instanceof DecimalType decimalCommand) {
1327 return decimalCommand.doubleValue();
1334 * Update Thing's channels according to available status information from the API
1336 * @param dynChannels
1339 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1340 if (channelsCreated) {
1341 return; // already done
1345 // Get subset of those channels that currently do not exist
1346 List<Channel> existingChannels = getThing().getChannels();
1347 for (Channel channel : existingChannels) {
1348 String id = channel.getUID().getId();
1349 if (dynChannels.containsKey(id)) {
1350 dynChannels.remove(id);
1354 if (!dynChannels.isEmpty()) {
1355 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1356 ThingBuilder thingBuilder = editThing();
1357 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1358 Channel c = channel.getValue();
1359 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1360 thingBuilder.withChannel(c);
1362 updateThing(thingBuilder.build());
1363 logger.debug("{}: Channel definitions updated", thingName);
1365 } catch (IllegalArgumentException e) {
1366 logger.debug("{}: Unable to update channel definitions", thingName, e);
1371 public boolean areChannelsCreated() {
1372 return channelsCreated;
1376 * Update thing properties with dynamic values
1378 * @param profile The device profile
1379 * @param status the /status result
1381 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1382 Map<String, Object> properties = fillDeviceProperties(profile);
1383 String deviceName = getString(profile.settings.name);
1384 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1385 properties.put(PROPERTY_DEV_AUTH, getBool(profile.device.auth) ? "yes" : "no");
1386 if (!deviceName.isEmpty()) {
1387 properties.put(PROPERTY_DEV_NAME, deviceName);
1390 // add status properties
1391 if (status.wifiSta != null) {
1392 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1394 if (status.update != null) {
1395 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1396 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1397 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1398 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1400 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1402 Map<String, String> thingProperties = new TreeMap<>();
1403 for (Map.Entry<String, Object> property : properties.entrySet()) {
1404 thingProperties.put(property.getKey(), (String) property.getValue());
1406 flushProperties(thingProperties);
1410 * Add one property to the Thing Properties
1412 * @param key Name of the property
1413 * @param value Value of the property
1416 public void updateProperties(String key, String value) {
1417 Map<String, String> thingProperties = editProperties();
1418 if (thingProperties.containsKey(key)) {
1419 thingProperties.replace(key, value);
1421 thingProperties.put(key, value);
1423 updateProperties(thingProperties);
1424 logger.trace("{}: Properties updated", thingName);
1427 public void flushProperties(Map<String, String> propertyUpdates) {
1428 Map<String, String> thingProperties = editProperties();
1429 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1430 if (thingProperties.containsKey(property.getKey())) {
1431 thingProperties.replace(property.getKey(), property.getValue());
1433 thingProperties.put(property.getKey(), property.getValue());
1436 updateProperties(thingProperties);
1440 * Get one property from the Thing Properties
1442 * @param key property name
1443 * @return property value or "" if property is not set
1446 public String getProperty(String key) {
1447 Map<String, String> thingProperties = getThing().getProperties();
1448 return getString(thingProperties.get(key));
1452 * Fill Thing Properties with device attributes
1454 * @param profile Property Map to full
1455 * @return a full property map
1457 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1458 Map<String, Object> properties = new TreeMap<>();
1459 properties.put(PROPERTY_VENDOR, VENDOR);
1460 if (profile.isInitialized()) {
1461 properties.put(PROPERTY_MODEL_ID, getString(profile.device.type));
1462 properties.put(PROPERTY_MAC_ADDRESS, profile.device.mac);
1463 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1464 properties.put(PROPERTY_DEV_MODE, profile.device.mode);
1465 if (profile.hasRelays) {
1466 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1467 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1468 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1470 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1471 if (!profile.hwRev.isEmpty()) {
1472 properties.put(PROPERTY_HWREV, profile.hwRev);
1473 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1480 * Return device profile.
1482 * @param forceRefresh true=force refresh before returning, false=return without
1484 * @return ShellyDeviceProfile instance
1485 * @throws ShellyApiException
1488 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1490 refreshSettings |= forceRefresh;
1491 if (refreshSettings) {
1492 profile = api.getDeviceProfile(thingType, null);
1493 if (!isThingOnline()) {
1494 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1497 } catch (ShellyApiException | RuntimeException e) {
1498 logger.debug("{}: Unable to initialize Device Profile", thingName, e);
1500 refreshSettings = false;
1506 public ShellyDeviceProfile getProfile() {
1511 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1512 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1513 if (!options.isEmpty()) {
1514 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1520 protected ShellyDeviceProfile getDeviceProfile() {
1525 public void triggerChannel(String group, String channel, String payload) {
1526 String triggerCh = mkChannelId(group, channel);
1527 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1528 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1529 if (vibrationFilter == 0) {
1530 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1531 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1532 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1534 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1535 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1540 triggerChannel(triggerCh, payload);
1543 public void stop() {
1544 logger.debug("{}: Shutting down", thingName);
1545 ScheduledFuture<?> job = this.initJob;
1550 job = this.statusJob;
1554 logger.debug("{}: Shelly statusJob stopped", thingName);
1557 profile.initialized = false;
1561 * Shutdown thing, make sure background jobs are canceled
1564 public void dispose() {
1565 logger.debug("{}: Stopping Thing", thingName);
1572 * Device specific command handlers are overriding this method to do additional stuff
1574 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1578 public String getUID() {
1579 return getThing().getUID().getAsString();
1583 * Device specific handlers are overriding this method to do additional stuff
1585 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1590 public String getThingName() {
1595 public void resetStats() {
1597 stats = new ShellyDeviceStats();
1601 public ShellyDeviceStats getStats() {
1606 public ShellyApiInterface getApi() {
1611 public long getScheduledUpdates() {
1612 return scheduledUpdates;
1615 public Map<String, String> getStatsProp() {
1616 return stats.asProperties();
1620 public void triggerUpdateFromCoap() {
1621 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1622 requestUpdates(1, false);