2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.handler;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
19 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
20 import static org.openhab.core.thing.Thing.*;
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 import java.util.List;
26 import java.util.TreeMap;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.shelly.internal.api.ShellyApiException;
34 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
35 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
36 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
37 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO;
38 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyFavPos;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapHandler;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
47 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
48 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
49 import org.openhab.binding.shelly.internal.api2.ShellyBluApi;
50 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
51 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
52 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
53 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
54 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
55 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
56 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
57 import org.openhab.core.library.types.DecimalType;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.library.types.OpenClosedType;
60 import org.openhab.core.library.types.QuantityType;
61 import org.openhab.core.thing.Channel;
62 import org.openhab.core.thing.ChannelUID;
63 import org.openhab.core.thing.Thing;
64 import org.openhab.core.thing.ThingStatus;
65 import org.openhab.core.thing.ThingStatusDetail;
66 import org.openhab.core.thing.ThingTypeUID;
67 import org.openhab.core.thing.binding.BaseThingHandler;
68 import org.openhab.core.thing.binding.builder.ThingBuilder;
69 import org.openhab.core.thing.type.ChannelTypeUID;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.openhab.core.types.State;
73 import org.openhab.core.types.StateOption;
74 import org.openhab.core.types.UnDefType;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
80 * sent to one of the channels.
82 * @author Markus Michels - Initial contribution
85 public abstract class ShellyBaseHandler extends BaseThingHandler
86 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
88 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
89 protected final ShellyChannelDefinitions channelDefinitions;
91 public String thingName = "";
92 public String thingType = "";
94 protected final ShellyApiInterface api;
95 private final HttpClient httpClient;
97 private ShellyBindingConfiguration bindingConfig;
98 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
99 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
100 private ShellyDeviceStats stats = new ShellyDeviceStats();
101 private @Nullable Shelly1CoapHandler coap;
103 private final ShellyTranslationProvider messages;
104 private final ShellyChannelCache cache;
105 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
107 private final boolean gen2;
108 private final boolean blu;
109 protected boolean autoCoIoT = false;
112 private boolean channelsCreated = false;
113 private boolean stopping = false;
114 private int vibrationFilter = 0;
115 private String lastWakeupReason = "";
118 private long watchdog = now();
119 protected int scheduledUpdates = 0;
120 private int skipCount = UPDATE_SKIP_COUNT;
121 private int skipUpdate = 0;
122 private boolean refreshSettings = false;
123 private @Nullable ScheduledFuture<?> statusJob;
124 private @Nullable ScheduledFuture<?> initJob;
129 * @param thing The Thing object
130 * @param bindingConfig The binding configuration (beside thing
132 * @param coapServer coap server instance
133 * @param localIP local IP address from networkAddressService
134 * @param httpPort from httpService
136 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
137 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
138 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
141 this.thingName = getString(thing.getLabel());
142 this.messages = translationProvider;
143 this.cache = new ShellyChannelCache(this);
144 this.channelDefinitions = new ShellyChannelDefinitions(messages);
145 this.bindingConfig = bindingConfig;
146 this.config = getConfigAs(ShellyThingConfiguration.class);
147 this.httpClient = httpClient;
149 Map<String, String> properties = thing.getProperties();
150 String gen = getString(properties.get(PROPERTY_DEV_GEN));
151 String thingType = getThingType();
152 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
155 gen2 = "2".equals(gen);
156 blu = thingType.startsWith("shellyblu");
157 this.api = !blu ? !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this)
158 : new ShellyBluApi(thingName, thingTable, this);
160 config.eventsCoIoT = false;
162 if (config.eventsCoIoT) {
163 this.coap = new Shelly1CoapHandler(this, coapServer);
168 public boolean checkRepresentation(String key) {
169 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceAddress)
170 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
174 * Schedule asynchronous Thing initialization, register thing to event dispatcher
177 public void initialize() {
178 // start background initialization:
179 initJob = scheduler.schedule(() -> {
180 boolean start = true;
182 initializeThingConfig();
183 logger.debug("{}: Device config: Device address={}, HTTP user/password={}/{}, update interval={}",
184 thingName, config.deviceAddress, config.userId.isEmpty() ? "<non>" : config.userId,
185 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
187 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
188 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
189 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
190 start = initializeThing();
191 } catch (ShellyApiException e) {
192 ShellyApiResult res = e.getApiResult();
194 if (e.isJsonError()) { // invalid JSON format
195 mid = "offline.status-error-unexpected-error";
197 } else if (isAuthorizationFailed(res)) {
198 mid = "offline.conf-error-access-denied";
200 } else if (profile.alwaysOn && e.isConnectionError()) {
201 mid = "offline.status-error-connect";
203 if (!mid.isEmpty()) {
204 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
206 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
207 } catch (IllegalArgumentException e) {
208 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
210 // even this initialization failed we start the status update
211 // the updateJob will then try to auto-initialize the thing
212 // in this case the thing stays in status INITIALIZING
217 }, 2, TimeUnit.SECONDS);
221 public ShellyThingConfiguration getThingConfig() {
226 public HttpClient getHttpClient() {
231 public void startScan() {
232 if (api.isInitialized()) {
238 * This routine is called every time the Thing configuration has been changed
241 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
242 super.handleConfigurationUpdate(configurationParameters);
243 logger.debug("{}: Thing config updated, re-initialize", thingName);
248 reinitializeThing();// force re-initialization
252 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
253 * If the device is password protected and the credentials are missing or don't match the API access will throw an
254 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
255 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
256 * credentials are correct and the API access is initialized successful.
258 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
260 public boolean initializeThing() throws ShellyApiException {
261 // Init from thing type to have a basic profile, gets updated when device info is received from API
262 refreshSettings = false;
263 lastWakeupReason = "";
264 cache.setThingName(thingName);
268 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
269 getThing().getLabel(), thingType, config.deviceAddress, gen2, config.eventsCoIoT);
270 if (config.deviceAddress.isEmpty()) {
271 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-address");
275 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
276 messages.get("status.unknown.initializing"));
278 profile.initFromThingType(thingType); // do some basic initialization
280 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
281 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
282 // Action URL does when enabled)
283 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
284 coap.start(thingName, config);
287 // Initialize API access, exceptions will be catched by initialize()
289 ShellySettingsDevice devInfo = api.getDeviceInfo();
290 if (getBool(devInfo.auth) && config.password.isEmpty()) {
291 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
294 if (config.serviceName.isEmpty()) {
295 config.serviceName = getString(profile.hostname).toLowerCase();
298 api.setConfig(thingName, config);
299 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
300 tmpPrf.isGen2 = gen2;
301 tmpPrf.auth = devInfo.auth; // missing in /settings
303 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
304 changeThingType(thingName, tmpPrf.mode);
305 return false; // force re-initialization
307 // Validate device mode
308 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
309 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
310 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
314 if (!getString(devInfo.coiot).isEmpty()) {
315 // New Shelly devices might use a different endpoint for the CoAP listener
316 tmpPrf.coiotEndpoint = devInfo.coiot;
318 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
319 // Sensor, usually 12h, H&T in USB mode 10min
320 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
321 ? tmpPrf.settings.sleepMode.period * 60 // minutes
322 : tmpPrf.settings.sleepMode.period * 3600; // hours
323 tmpPrf.updatePeriod += 60; // give 1min extra
324 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
325 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
326 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
327 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
329 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
332 tmpPrf.status = api.getStatus(); // update thing properties
333 tmpPrf.updateFromStatus(tmpPrf.status);
334 addStateOptions(tmpPrf);
336 // update thing properties
337 updateProperties(tmpPrf, tmpPrf.status);
338 checkVersion(tmpPrf, tmpPrf.status);
340 startCoap(config, tmpPrf);
342 api.setActionURLs(); // register event urls
345 // All initialization done, so keep the profile and set Thing to ONLINE
346 fillDeviceStatus(tmpPrf.status, false);
347 postEvent(ALARM_TYPE_NONE, false);
350 showThingConfig(profile);
352 logger.debug("{}: Thing successfully initialized.", thingName);
353 updateProperties(profile, profile.status);
354 setThingOnline(); // if API call was successful the thing must be online
355 return true; // success
359 * Handle Channel Commands
362 public void handleCommand(ChannelUID channelUID, Command command) {
364 if (command instanceof RefreshType) {
365 String channelId = channelUID.getId();
366 State value = cache.getValue(channelId);
367 if (value != UnDefType.NULL) {
368 updateState(channelId, value);
373 if (!profile.isInitialized()) {
374 logger.debug("{}: {}", thingName, messages.get("command.init", command));
377 profile = getProfile(false);
380 boolean update = false;
381 switch (channelUID.getIdWithoutGroup()) {
382 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
383 logger.debug("{}: Send key {}", thingName, command);
384 api.sendIRKey(command.toString());
388 case CHANNEL_LED_STATUS_DISABLE:
389 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
390 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
392 case CHANNEL_LED_POWER_DISABLE:
393 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
394 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
397 case CHANNEL_SENSOR_SLEEPTIME:
398 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
399 int value = (int) getNumber(command);
400 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
402 api.setSleepTime(value);
404 case CHANNEL_CONTROL_SCHEDULE:
406 logger.debug("{}: {} Valve schedule/profile", thingName,
407 command == OnOffType.ON ? "Enable" : "Disable");
408 api.setValveProfile(0,
409 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
412 case CHANNEL_CONTROL_PROFILE:
413 logger.debug("{}: Select profile {}", thingName, command);
415 if (command instanceof Number) {
416 id = (int) getNumber(command);
418 String cmd = command.toString();
419 if (isDigit(cmd.charAt(0))) {
420 id = Integer.parseInt(cmd);
421 } else if (profile.settings.thermostats != null) {
422 ShellyThermnostat t = profile.settings.thermostats.get(0);
423 for (int i = 0; i < t.profileNames.length; i++) {
424 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
430 if (id < 0 || id > 5) {
431 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
434 api.setValveProfile(0, id);
436 case CHANNEL_CONTROL_MODE:
437 logger.debug("{}: Set mode to {}", thingName, command);
438 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
440 case CHANNEL_CONTROL_SETTEMP:
441 logger.debug("{}: Set temperature to {}", thingName, command);
442 api.setValveTemperature(0, (int) getNumber(command));
444 case CHANNEL_CONTROL_POSITION:
445 logger.debug("{}: Set position to {}", thingName, command);
446 api.setValvePosition(0, getNumber(command));
448 case CHANNEL_CONTROL_BCONTROL:
449 logger.debug("{}: Set boost mode to {}", thingName, command);
450 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
452 case CHANNEL_CONTROL_BTIMER:
453 logger.debug("{}: Set boost timer to {}", thingName, command);
454 api.setValveBoostTime(0, (int) getNumber(command));
456 case CHANNEL_SENSOR_MUTE:
457 if (profile.isSmoke && ((OnOffType) command) == OnOffType.ON) {
458 logger.debug("{}: Mute Smoke Alarm", thingName);
459 api.muteSmokeAlarm(0);
460 updateChannel(getString(channelUID.getGroupId()), CHANNEL_SENSOR_MUTE, OnOffType.OFF);
464 update = handleDeviceCommand(channelUID, command);
469 if (update && !autoCoIoT && !isUpdateScheduled()) {
470 requestUpdates(1, false);
472 } catch (ShellyApiException e) {
473 ShellyApiResult res = e.getApiResult();
474 if (isAuthorizationFailed(res)) {
477 if (res.isNotCalibrtated()) {
478 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
480 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
484 String group = getString(channelUID.getGroupId());
485 String channel = getString(channelUID.getIdWithoutGroup());
486 State oldValue = getChannelValue(group, channel);
487 if (oldValue != UnDefType.NULL) {
488 logger.info("{}: Restore channel value to {}", thingName, oldValue);
489 updateChannel(group, channel, oldValue);
492 } catch (IllegalArgumentException e) {
493 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
497 private double getNumber(Command command) {
498 if (command instanceof QuantityType) {
499 return ((QuantityType<?>) command).doubleValue();
501 if (command instanceof DecimalType) {
502 return ((DecimalType) command).doubleValue();
504 if (command instanceof Number) {
505 return ((Number) command).doubleValue();
507 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
511 * Update device status and channels
513 protected void refreshStatus() {
515 boolean updated = false;
517 if (vibrationFilter > 0) {
519 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
520 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
524 ThingStatus thingStatus = getThing().getStatus();
525 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
526 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
527 || (thingStatus == ThingStatus.UNKNOWN)) {
528 logger.debug("{}: Status update triggered thing initialization", thingName);
529 initializeThing(); // may fire an exception if initialization failed
531 ShellySettingsStatus status = api.getStatus();
532 boolean restarted = checkRestarted(status);
533 profile = getProfile(refreshSettings || restarted);
534 profile.status = status;
535 profile.updateFromStatus(status);
537 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
539 postEvent(ALARM_TYPE_RESTARTED, true);
542 // If status update was successful the thing must be online,
543 // but not while firmware update is in progress
544 if (getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
548 // map status to channels
549 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
550 updated |= this.updateDeviceStatus(status);
551 updated |= ShellyComponents.updateDeviceStatus(this, status);
552 fillDeviceStatus(status, updated);
553 updated |= updateInputs(status);
554 updated |= updateMeters(this, status);
555 updated |= updateSensors(this, status);
557 // All channels must be created after the first cycle
558 channelsCreated = true;
560 } catch (ShellyApiException e) {
561 // http call failed: go offline except for battery devices, which might be in
562 // sleep mode. Once the next update is successful the device goes back online
564 ShellyApiResult res = e.getApiResult();
565 if (profile.alwaysOn && e.isConnectionError()) {
566 status = "offline.status-error-connect";
567 } else if (res.isHttpAccessUnauthorized()) {
568 status = "offline.conf-error-access-denied";
569 } else if (isWatchdogStarted()) {
570 if (!isWatchdogExpired()) {
571 logger.debug("{}: Ignore API Timeout on {} {}, retry later", thingName, res.method, res.url);
573 if (isThingOnline()) {
574 status = "offline.status-error-watchdog";
577 } else if (e.isJSONException()) {
578 status = "offline.status-error-unexpected-api-result";
579 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
580 } else if (res.isHttpTimeout()) {
581 // Watchdog not started, e.g. device in sleep mode
582 if (isThingOnline()) { // ignore when already offline
583 status = "offline.status-error-watchdog";
586 status = "offline.status-error-unexpected-api-result";
587 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
590 if (!status.isEmpty()) {
591 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
593 } catch (NullPointerException | IllegalArgumentException e) {
594 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
596 if (scheduledUpdates > 0) {
598 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
599 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
600 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
601 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
607 private void showThingConfig(ShellyDeviceProfile profile) {
608 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
609 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
611 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
612 logger.debug("{}: Device "
613 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
614 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
615 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
616 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
617 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
618 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
619 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
620 profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
621 if (profile.status.extTemperature != null || profile.status.extHumidity != null
622 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
623 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
627 private void addStateOptions(ShellyDeviceProfile prf) {
629 String[] profileNames = prf.getValveProfileList(0);
630 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
631 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
632 channelDefinitions.clearStateOptions(channelId);
634 for (String name : profileNames) {
635 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
639 if (prf.isRoller && prf.settings.favorites != null) {
640 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
641 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
642 prf.settings.favorites.size());
643 channelDefinitions.clearStateOptions(channelId);
645 for (ShellyFavPos fav : prf.settings.favorites) {
646 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
653 public String getThingType() {
654 return thing.getThingTypeUID().getId();
658 public ThingStatus getThingStatus() {
659 return thing.getStatus();
663 public ThingStatusDetail getThingStatusDetail() {
664 return thing.getStatusInfo().getStatusDetail();
668 public boolean isThingOnline() {
669 return getThingStatus() == ThingStatus.ONLINE;
672 public boolean isThingOffline() {
673 return getThingStatus() == ThingStatus.OFFLINE;
677 public void setThingOnline() {
678 if (!isThingOnline()) {
679 updateStatus(ThingStatus.ONLINE);
681 // request 3 updates in a row (during the first 2+3*3 sec)
682 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
685 // Restart watchdog when status update was successful (no exception)
690 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
691 if (!isThingOffline()) {
692 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
693 api.close(); // Gen2: disconnect WS/close http sessions
695 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
700 public void restartWatchdog() {
702 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
703 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
706 private boolean isWatchdogExpired() {
707 long delta = now() - watchdog;
708 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
709 stats.remainingWatchdog = delta;
715 private boolean isWatchdogStarted() {
720 public void reinitializeThing() {
721 logger.debug("{}: Re-Initialize Thing", thingName);
723 logger.debug("{}: Handler is shutting down, ignore", thingName);
726 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
727 messages.get("offline.status-error-restarted"));
728 requestUpdates(0, true);
732 public boolean isStopping() {
737 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
740 // Update uptime and WiFi, internal temp
741 ShellyComponents.updateDeviceStatus(this, status);
742 stats.wifiRssi = getInteger(status.wifiSta.rssi);
744 if (api.isInitialized()) {
745 stats.timeoutErrors = api.getTimeoutErrors();
746 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
748 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
750 // Check various device indicators like overheating
751 if (checkRestarted(status)) {
752 // Force re-initialization on next status update
754 } else if (getBool(status.overtemperature)) {
755 alarm = ALARM_TYPE_OVERTEMP;
756 } else if (getBool(status.overload)) {
757 alarm = ALARM_TYPE_OVERLOAD;
758 } else if (getBool(status.loaderror)) {
759 alarm = ALARM_TYPE_LOADERR;
761 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
762 if (internalTemp != UnDefType.NULL) {
763 int temp = ((Number) internalTemp).intValue();
764 if (temp > stats.maxInternalTemp) {
765 stats.maxInternalTemp = temp;
769 if (status.uptime != null) {
770 stats.lastUptime = getLong(status.uptime);
773 if (!alarm.isEmpty()) {
774 postEvent(alarm, false);
779 public void incProtMessages() {
780 stats.protocolMessages++;
784 public void incProtErrors() {
785 stats.protocolErrors++;
789 * Check if device has restarted and needs a new Thing initialization
791 * @return true: restart detected
794 private boolean checkRestarted(ShellySettingsStatus status) {
795 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
796 && (status.uptime != null && status.uptime < stats.lastUptime
797 || (!profile.status.update.oldVersion.isEmpty()
798 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
799 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
800 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
801 updateProperties(profile, status);
808 * Save alarm to the lastAlarm channel
810 * @param alarm 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 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
830 case ALARM_TYPE_NONE:
833 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
834 triggerChannel(channelId, event);
835 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
836 stats.lastAlarm = event;
837 stats.lastAlarmTs = now();
843 public boolean isUpdateScheduled() {
844 return scheduledUpdates > 0;
848 * Callback for device events
850 * @param deviceName device receiving the event
851 * @param parameters parameters from the event URL
852 * @param data the HTML input data
853 * @return true if event was processed
856 public boolean onEvent(String address, String deviceName, String deviceIndex, String type,
857 Map<String, String> parameters) {
858 if (thingName.equalsIgnoreCase(deviceName) || config.deviceAddress.equals(address)
859 || config.serviceName.equals(deviceName)) {
860 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
862 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
863 if (!profile.isInitialized()) {
864 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
865 requestUpdates(1, true);
867 String group = profile.getControlGroup(idx);
868 if (group.isEmpty()) {
869 logger.debug("{}: Unsupported event class: {}", thingName, type);
873 // map some of the events to system defined button triggers
877 String parmType = getString(parameters.get("type"));
878 String event = !parmType.isEmpty() ? parmType : type;
879 boolean isButton = profile.inButtonMode(idx - 1) || type.equals("button");
881 case SHELLY_EVENT_SHORTPUSH:
882 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
883 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
884 case SHELLY_EVENT_LONGPUSH:
886 triggerButton(group, idx, mapButtonEvent(event));
887 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
888 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
890 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
894 case SHELLY_EVENT_BTN_ON:
895 case SHELLY_EVENT_BTN_OFF:
896 if (profile.isRGBW2) {
897 // RGBW2 has only one input, so not per channel
898 group = CHANNEL_GROUP_LIGHT_CONTROL;
900 onoff = CHANNEL_INPUT;
902 case SHELLY_EVENT_BTN1_ON:
903 case SHELLY_EVENT_BTN1_OFF:
904 onoff = CHANNEL_INPUT1;
906 case SHELLY_EVENT_BTN2_ON:
907 case SHELLY_EVENT_BTN2_OFF:
908 onoff = CHANNEL_INPUT2;
910 case SHELLY_EVENT_OUT_ON:
911 case SHELLY_EVENT_OUT_OFF:
912 onoff = CHANNEL_OUTPUT;
914 case SHELLY_EVENT_ROLLER_OPEN:
915 case SHELLY_EVENT_ROLLER_CLOSE:
916 case SHELLY_EVENT_ROLLER_STOP:
917 channel = CHANNEL_EVENT_TRIGGER;
920 case SHELLY_EVENT_SENSORREPORT:
921 // process sensor with next refresh
923 case SHELLY_EVENT_TEMP_OVER: // DW2
924 case SHELLY_EVENT_TEMP_UNDER:
925 channel = CHANNEL_EVENT_TRIGGER;
928 case SHELLY_EVENT_FLOOD_DETECTED:
929 case SHELLY_EVENT_FLOOD_GONE:
930 updateChannel(group, CHANNEL_SENSOR_FLOOD,
931 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
934 case SHELLY_EVENT_CLOSE: // DW 1.7
935 case SHELLY_EVENT_OPEN: // DW 1.7
936 updateChannel(group, CHANNEL_SENSOR_STATE,
937 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
938 : OpenClosedType.CLOSED);
941 case SHELLY_EVENT_DARK: // DW 1.7
942 case SHELLY_EVENT_TWILIGHT: // DW 1.7
943 case SHELLY_EVENT_BRIGHT: // DW 1.7
944 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
947 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
948 case SHELLY_EVENT_ALARM_HEAVY:
949 case SHELLY_EVENT_ALARM_OFF:
950 case SHELLY_EVENT_VIBRATION: // DW2
951 channel = CHANNEL_SENSOR_ALARM_STATE;
952 payload = event.toUpperCase();
956 // trigger will be provided by input/output channel or sensor channels
959 if (!onoff.isEmpty()) {
960 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
962 if (!payload.isEmpty()) {
963 // Pass event to trigger channel
964 payload = payload.toUpperCase();
965 logger.debug("{}: Post event {}", thingName, payload);
966 triggerChannel(mkChannelId(group, channel), payload);
970 // request update on next interval (2x for non-battery devices)
972 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
979 * Initialize the binding's thing configuration, calc update counts
981 protected void initializeThingConfig() {
982 thingType = getThing().getThingTypeUID().getId();
983 final Map<String, String> properties = getThing().getProperties();
984 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
985 if (thingName.isEmpty()) {
986 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
989 config = getConfigAs(ShellyThingConfiguration.class);
990 if (config.deviceAddress.isEmpty()) {
991 config.deviceAddress = config.deviceIp;
993 if (config.deviceAddress.isEmpty()) {
994 logger.debug("{}: IP/MAC address for the device must not be empty", thingName); // may not set in .things
999 config.deviceAddress = config.deviceAddress.toLowerCase().replaceAll(":", ""); // remove : from MAC address and
1000 // convert to lower case
1001 if (!config.deviceIp.isEmpty()) {
1003 InetAddress addr = InetAddress.getByName(config.deviceIp);
1004 String saddr = addr.getHostAddress();
1005 if (!config.deviceIp.equals(saddr)) {
1006 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
1007 config.deviceIp = saddr;
1009 } catch (UnknownHostException e) {
1010 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
1014 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
1015 config.localIp = bindingConfig.localIP;
1016 config.localPort = String.valueOf(bindingConfig.httpPort);
1017 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
1018 config.userId = bindingConfig.defaultUserId;
1019 config.password = bindingConfig.defaultPassword;
1020 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
1022 if (config.updateInterval == 0) {
1023 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
1025 if (config.updateInterval < UPDATE_MIN_DELAY) {
1026 config.updateInterval = UPDATE_MIN_DELAY;
1029 // Try to get updatePeriod from properties
1030 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
1031 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
1032 // initialized successfully by the REST call.
1033 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
1034 if (!lastPeriod.isEmpty()) {
1035 int period = Integer.parseInt(lastPeriod);
1037 profile.updatePeriod = period;
1041 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1042 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1045 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1047 ShellyVersionDTO version = new ShellyVersionDTO();
1048 if (version.checkBeta(getString(prf.fwVersion))) {
1049 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1051 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1052 if (version.compare(prf.fwVersion, minVersion) < 0) {
1053 logger.warn("{}: {}", prf.hostname,
1054 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1057 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1058 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
1059 if (!config.eventsCoIoT) {
1060 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1064 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1065 logger.info("{}: {}", thingName,
1066 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1068 } catch (NullPointerException e) { // could be inconsistant format of beta version
1069 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1073 public String checkForUpdate() {
1075 ShellyOtaCheckResult result = api.checkForUpdate();
1076 return result.status;
1077 } catch (ShellyApiException e) {
1082 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1083 if (coap == null || !config.eventsCoIoT) {
1086 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1087 String devpeer = getString(profile.settings.coiot.peer);
1088 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1089 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1091 api.setCoIoTPeer(ourpeer);
1092 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1093 } catch (ShellyApiException e) {
1094 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1096 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1097 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1101 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1102 config.eventsCoIoT = true;
1103 config.eventsSwitch = false;
1104 config.eventsButton = false;
1105 config.eventsPush = false;
1106 config.eventsRoller = false;
1107 config.eventsSensorReport = false;
1108 api.setConfig(thingName, config);
1111 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1113 coap.start(thingName, config);
1118 * Checks the http response for authorization error.
1119 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1120 * case the thing type shelly-unknown is set.
1122 * @param response exception details including the http respone
1123 * @return true if the authorization failed
1125 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1126 if (result.isHttpAccessUnauthorized()) {
1127 // If the device is password protected the API doesn't provide settings to the device settings
1128 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1135 * Change type of this thing.
1137 * @param thingType thing type acc. to the xml definition
1138 * @param mode Device mode (e.g. relay, roller)
1140 protected void changeThingType(String thingType, String mode) {
1141 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1142 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1143 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1144 Map<String, String> properties = editProperties();
1145 properties.replace(PROPERTY_DEV_TYPE, thingType);
1146 properties.replace(PROPERTY_DEV_MODE, mode);
1147 updateProperties(properties);
1148 changeThingType(thingTypeUID, getConfig());
1153 public void thingUpdated(Thing thing) {
1154 logger.debug("{}: Channel definitions updated.", thingName);
1155 super.thingUpdated(thing);
1159 * Start the background updates
1161 protected void startUpdateJob() {
1162 ScheduledFuture<?> statusJob = this.statusJob;
1163 if ((statusJob == null) || statusJob.isCancelled()) {
1164 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1166 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1167 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1172 * Flag the status job to do an exceptional update (something happened) rather
1173 * than waiting until the next regular poll
1175 * @param requestCount number of polls to execute
1176 * @param refreshSettings true=force a /settings query
1177 * @return true=Update schedule, false=skipped (too many updates already
1181 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1182 this.refreshSettings |= refreshSettings;
1183 if (refreshSettings) {
1184 if (requestCount == 0) {
1185 logger.debug("{}: Request settings refresh", thingName);
1187 scheduledUpdates = 1;
1190 if (scheduledUpdates < 10) { // < 30s
1191 scheduledUpdates += requestCount;
1198 * Map input states to channels
1200 * @param groupName Channel Group (relay / relay1...)
1202 * @param status Shelly device status
1203 * @return true: one or more inputs were updated
1206 public boolean updateInputs(ShellySettingsStatus status) {
1207 boolean updated = false;
1209 if (status.inputs != null) {
1210 if (!areChannelsCreated()) {
1211 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1215 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1216 for (ShellyInputState input : status.inputs) {
1217 String group = profile.getInputGroup(idx);
1218 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1219 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1220 if (input.event != null) {
1221 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1222 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1227 if (status.input != null) {
1228 // RGBW2: a single int rather than an array
1229 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1230 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1237 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1238 boolean changed = false;
1239 if (valueArray != null && !valueArray.isEmpty()) {
1240 String reason = getString((String) valueArray.get(0));
1241 String newVal = valueArray.toString();
1242 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1243 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1245 postEvent(reason.toUpperCase(), true);
1247 lastWakeupReason = newVal;
1253 public void triggerButton(String group, int idx, String value) {
1254 String trigger = mapButtonEvent(value);
1255 if (trigger.isEmpty()) {
1259 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1260 triggerChannel(group,
1261 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1263 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1264 if (profile.alwaysOn) {
1265 // refresh status of the input channel
1266 requestUpdates(1, false);
1271 public void publishState(String channelId, State value) {
1272 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1273 if (!stopping && isLinked(id)) {
1274 updateState(id, value);
1275 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1280 public boolean updateChannel(String group, String channel, State value) {
1281 return updateChannel(mkChannelId(group, channel), value, false);
1285 public boolean updateChannel(String channelId, State value, boolean force) {
1286 return !stopping && cache.updateChannel(channelId, value, force);
1290 public State getChannelValue(String group, String channel) {
1291 return cache.getValue(group, channel);
1295 public double getChannelDouble(String group, String channel) {
1296 State value = getChannelValue(group, channel);
1297 if (value != UnDefType.NULL) {
1298 if (value instanceof QuantityType) {
1299 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1301 if (value instanceof DecimalType) {
1302 return ((DecimalType) value).doubleValue();
1309 * Update Thing's channels according to available status information from the API
1311 * @param thingHandler
1314 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1315 if (channelsCreated) {
1316 return; // already done
1320 // Get subset of those channels that currently do not exist
1321 List<Channel> existingChannels = getThing().getChannels();
1322 for (Channel channel : existingChannels) {
1323 String id = channel.getUID().getId();
1324 if (dynChannels.containsKey(id)) {
1325 dynChannels.remove(id);
1329 if (!dynChannels.isEmpty()) {
1330 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1331 ThingBuilder thingBuilder = editThing();
1332 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1333 Channel c = channel.getValue();
1334 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1335 thingBuilder.withChannel(c);
1337 updateThing(thingBuilder.build());
1338 logger.debug("{}: Channel definitions updated", thingName);
1340 } catch (IllegalArgumentException e) {
1341 logger.debug("{}: Unable to update channel definitions", thingName, e);
1346 public boolean areChannelsCreated() {
1347 return channelsCreated;
1351 * Update thing properties with dynamic values
1353 * @param profile The device profile
1354 * @param status the /status result
1356 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1357 Map<String, Object> properties = fillDeviceProperties(profile);
1358 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1359 String deviceName = getString(profile.settings.name);
1360 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1361 properties.put(PROPERTY_DEV_GEN, "1");
1362 if (!deviceName.isEmpty()) {
1363 properties.put(PROPERTY_DEV_NAME, deviceName);
1365 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1367 // add status properties
1368 if (status.wifiSta != null) {
1369 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1371 if (status.update != null) {
1372 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1373 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1374 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1375 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1377 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1379 Map<String, String> thingProperties = new TreeMap<>();
1380 for (Map.Entry<String, Object> property : properties.entrySet()) {
1381 thingProperties.put(property.getKey(), (String) property.getValue());
1383 flushProperties(thingProperties);
1387 * Add one property to the Thing Properties
1389 * @param key Name of the property
1390 * @param value Value of the property
1393 public void updateProperties(String key, String value) {
1394 Map<String, String> thingProperties = editProperties();
1395 if (thingProperties.containsKey(key)) {
1396 thingProperties.replace(key, value);
1398 thingProperties.put(key, value);
1400 updateProperties(thingProperties);
1401 logger.trace("{}: Properties updated", thingName);
1404 public void flushProperties(Map<String, String> propertyUpdates) {
1405 Map<String, String> thingProperties = editProperties();
1406 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1407 if (thingProperties.containsKey(property.getKey())) {
1408 thingProperties.replace(property.getKey(), property.getValue());
1410 thingProperties.put(property.getKey(), property.getValue());
1413 updateProperties(thingProperties);
1417 * Get one property from the Thing Properties
1419 * @param key property name
1420 * @return property value or "" if property is not set
1423 public String getProperty(String key) {
1424 Map<String, String> thingProperties = getThing().getProperties();
1425 return getString(thingProperties.get(key));
1429 * Fill Thing Properties with device attributes
1431 * @param profile Property Map to full
1432 * @return a full property map
1434 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1435 Map<String, Object> properties = new TreeMap<>();
1436 properties.put(PROPERTY_VENDOR, VENDOR);
1437 if (profile.isInitialized()) {
1438 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1439 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1440 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1441 properties.put(PROPERTY_DEV_MODE, profile.mode);
1442 if (profile.hasRelays) {
1443 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1444 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1445 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1447 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1448 if (!profile.hwRev.isEmpty()) {
1449 properties.put(PROPERTY_HWREV, profile.hwRev);
1450 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1457 * Return device profile.
1459 * @param ForceRefresh true=force refresh before returning, false=return without
1461 * @return ShellyDeviceProfile instance
1462 * @throws ShellyApiException
1465 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1467 refreshSettings |= forceRefresh;
1468 if (refreshSettings) {
1469 profile = api.getDeviceProfile(thingType);
1470 if (!isThingOnline()) {
1471 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1475 refreshSettings = false;
1481 public ShellyDeviceProfile getProfile() {
1486 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1487 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1488 if (!options.isEmpty()) {
1489 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1495 protected ShellyDeviceProfile getDeviceProfile() {
1500 public void triggerChannel(String group, String channel, String payload) {
1501 String triggerCh = mkChannelId(group, channel);
1502 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1503 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1504 if (vibrationFilter == 0) {
1505 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1506 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1507 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1509 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1510 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1515 triggerChannel(triggerCh, payload);
1518 public void stop() {
1519 logger.debug("{}: Shutting down", thingName);
1520 ScheduledFuture<?> job = this.initJob;
1525 job = this.statusJob;
1529 logger.debug("{}: Shelly statusJob stopped", thingName);
1532 profile.initialized = false;
1536 * Shutdown thing, make sure background jobs are canceled
1539 public void dispose() {
1540 logger.debug("{}: Stopping Thing", thingName);
1547 * Device specific command handlers are overriding this method to do additional stuff
1549 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1553 public String getUID() {
1554 return getThing().getUID().getAsString();
1558 * Device specific handlers are overriding this method to do additional stuff
1560 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1565 public String getThingName() {
1570 public void resetStats() {
1572 stats = new ShellyDeviceStats();
1576 public ShellyDeviceStats getStats() {
1581 public ShellyApiInterface getApi() {
1586 public long getScheduledUpdates() {
1587 return scheduledUpdates;
1590 public Map<String, String> getStatsProp() {
1591 return stats.asProperties();
1595 public void triggerUpdateFromCoap() {
1596 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1597 requestUpdates(1, false);