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.config.ShellyBindingConfiguration;
50 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
51 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
52 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
53 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
54 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
55 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
56 import org.openhab.core.library.types.DecimalType;
57 import org.openhab.core.library.types.OnOffType;
58 import org.openhab.core.library.types.OpenClosedType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.thing.Channel;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.Thing;
63 import org.openhab.core.thing.ThingStatus;
64 import org.openhab.core.thing.ThingStatusDetail;
65 import org.openhab.core.thing.ThingTypeUID;
66 import org.openhab.core.thing.binding.BaseThingHandler;
67 import org.openhab.core.thing.binding.builder.ThingBuilder;
68 import org.openhab.core.thing.type.ChannelTypeUID;
69 import org.openhab.core.types.Command;
70 import org.openhab.core.types.RefreshType;
71 import org.openhab.core.types.State;
72 import org.openhab.core.types.StateOption;
73 import org.openhab.core.types.UnDefType;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
79 * sent to one of the channels.
81 * @author Markus Michels - Initial contribution
84 public abstract class ShellyBaseHandler extends BaseThingHandler
85 implements ShellyThingInterface, ShellyDeviceListener, ShellyManagerInterface {
87 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
88 protected final ShellyChannelDefinitions channelDefinitions;
90 public String thingName = "";
91 public String thingType = "";
93 protected final ShellyApiInterface api;
94 private final HttpClient httpClient;
96 private ShellyBindingConfiguration bindingConfig;
97 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
98 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
99 private ShellyDeviceStats stats = new ShellyDeviceStats();
100 private @Nullable Shelly1CoapHandler coap;
102 private final ShellyTranslationProvider messages;
103 private final ShellyChannelCache cache;
104 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
106 private final boolean gen2;
107 protected boolean autoCoIoT = false;
110 private boolean channelsCreated = false;
111 private boolean stopping = false;
112 private int vibrationFilter = 0;
113 private String lastWakeupReason = "";
116 private long watchdog = now();
117 protected int scheduledUpdates = 0;
118 private int skipCount = UPDATE_SKIP_COUNT;
119 private int skipUpdate = 0;
120 private boolean refreshSettings = false;
121 private @Nullable ScheduledFuture<?> statusJob;
126 * @param thing The Thing object
127 * @param bindingConfig The binding configuration (beside thing
129 * @param coapServer coap server instance
130 * @param localIP local IP address from networkAddressService
131 * @param httpPort from httpService
133 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
134 final ShellyBindingConfiguration bindingConfig, ShellyThingTable thingTable,
135 final Shelly1CoapServer coapServer, final HttpClient httpClient) {
138 this.thingName = getString(thing.getLabel());
139 this.messages = translationProvider;
140 this.cache = new ShellyChannelCache(this);
141 this.channelDefinitions = new ShellyChannelDefinitions(messages);
142 this.bindingConfig = bindingConfig;
143 this.config = getConfigAs(ShellyThingConfiguration.class);
144 this.httpClient = httpClient;
146 Map<String, String> properties = thing.getProperties();
147 String gen = getString(properties.get(PROPERTY_DEV_GEN));
148 String thingType = getThingType();
149 if (gen.isEmpty() && thingType.startsWith("shellyplus") || thingType.startsWith("shellypro")) {
152 gen2 = "2".equals(gen);
153 this.api = !gen2 ? new Shelly1HttpApi(thingName, this) : new Shelly2ApiRpc(thingName, thingTable, this);
155 config.eventsCoIoT = false;
157 if (config.eventsCoIoT) {
158 this.coap = new Shelly1CoapHandler(this, coapServer);
163 public boolean checkRepresentation(String key) {
164 return key.equalsIgnoreCase(getUID()) || key.equalsIgnoreCase(config.deviceIp)
165 || key.equalsIgnoreCase(config.serviceName) || key.equalsIgnoreCase(getThingName());
169 * Schedule asynchronous Thing initialization, register thing to event dispatcher
172 public void initialize() {
173 // start background initialization:
174 scheduler.schedule(() -> {
175 boolean start = true;
177 initializeThingConfig();
178 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
179 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
180 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
182 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
183 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
184 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
185 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
186 messages.get("status.unknown.initializing"));
187 start = initializeThing();
188 } catch (ShellyApiException e) {
189 ShellyApiResult res = e.getApiResult();
191 if (e.isJsonError()) { // invalid JSON format
192 mid = "offline.status-error-unexpected-error";
194 } else if (isAuthorizationFailed(res)) {
195 mid = "offline.conf-error-access-denied";
197 } else if (profile.alwaysOn && e.isConnectionError()) {
198 mid = "offline.status-error-connect";
200 if (!mid.isEmpty()) {
201 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, mid, e.toString());
203 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
204 } catch (IllegalArgumentException e) {
205 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
207 // even this initialization failed we start the status update
208 // the updateJob will then try to auto-initialize the thing
209 // in this case the thing stays in status INITIALIZING
214 }, 2, TimeUnit.SECONDS);
218 public ShellyThingConfiguration getThingConfig() {
223 public HttpClient getHttpClient() {
228 * This routine is called every time the Thing configuration has been changed
231 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
232 super.handleConfigurationUpdate(configurationParameters);
233 logger.debug("{}: Thing config updated, re-initialize", thingName);
237 requestUpdates(1, true);// force re-initialization
241 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
242 * If the device is password protected and the credentials are missing or don't match the API access will throw an
243 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
244 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
245 * credentials are correct and the API access is initialized successful.
247 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
249 public boolean initializeThing() throws ShellyApiException {
250 // Init from thing type to have a basic profile, gets updated when device info is received from API
252 refreshSettings = false;
253 lastWakeupReason = "";
254 cache.setThingName(thingName);
258 logger.debug("{}: Start initializing for thing {}, type {}, IP address {}, Gen2: {}, CoIoT: {}", thingName,
259 getThing().getLabel(), thingType, config.deviceIp, gen2, config.eventsCoIoT);
260 if (config.deviceIp.isEmpty()) {
261 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
265 // Gen 1 only: Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing
266 // could not be fully initialized here. In this case the CoAP messages triggers auto-initialization (like the
267 // Action URL does when enabled)
268 if (coap != null && config.eventsCoIoT && !profile.alwaysOn) {
269 coap.start(thingName, config);
272 // Initialize API access, exceptions will be catched by initialize()
274 profile.initFromThingType(thingType);
275 ShellySettingsDevice devInfo = api.getDeviceInfo();
276 if (getBool(devInfo.auth) && config.password.isEmpty()) {
277 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
280 if (config.serviceName.isEmpty()) {
281 config.serviceName = getString(profile.hostname).toLowerCase();
284 api.setConfig(thingName, config);
285 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
286 tmpPrf.isGen2 = gen2;
287 tmpPrf.auth = devInfo.auth; // missing in /settings
289 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
290 changeThingType(thingName, tmpPrf.mode);
291 return false; // force re-initialization
293 // Validate device mode
294 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
295 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
296 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode", tmpPrf.mode,
300 if (!getString(devInfo.coiot).isEmpty()) {
301 // New Shelly devices might use a different endpoint for the CoAP listener
302 tmpPrf.coiotEndpoint = devInfo.coiot;
304 if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
305 // Sensor, usually 12h, H&T in USB mode 10min
306 tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
307 ? tmpPrf.settings.sleepMode.period * 60 // minutes
308 : tmpPrf.settings.sleepMode.period * 3600; // hours
309 tmpPrf.updatePeriod += 60; // give 1min extra
310 } else if ((tmpPrf.settings.coiot != null) && tmpPrf.settings.coiot.updatePeriod != null) {
311 // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
312 tmpPrf.updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS,
313 2 * getInteger(tmpPrf.settings.coiot.updatePeriod)) + 10;
315 tmpPrf.updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
318 tmpPrf.status = api.getStatus(); // update thing properties
319 tmpPrf.updateFromStatus(tmpPrf.status);
320 addStateOptions(tmpPrf);
322 // update thing properties
323 updateProperties(tmpPrf, tmpPrf.status);
324 checkVersion(tmpPrf, tmpPrf.status);
326 startCoap(config, tmpPrf);
328 api.setActionURLs(); // register event urls
331 // All initialization done, so keep the profile and set Thing to ONLINE
332 fillDeviceStatus(tmpPrf.status, false);
333 postEvent(ALARM_TYPE_NONE, false);
336 showThingConfig(profile);
338 logger.debug("{}: Thing successfully initialized.", thingName);
339 updateProperties(profile, profile.status);
340 setThingOnline(); // if API call was successful the thing must be online
341 return true; // success
345 * Handle Channel Commands
348 public void handleCommand(ChannelUID channelUID, Command command) {
350 if (command instanceof RefreshType) {
351 String channelId = channelUID.getId();
352 State value = cache.getValue(channelId);
353 if (value != UnDefType.NULL) {
354 updateState(channelId, value);
359 if (!profile.isInitialized()) {
360 logger.debug("{}: {}", thingName, messages.get("command.init", command));
363 profile = getProfile(false);
366 boolean update = false;
367 switch (channelUID.getIdWithoutGroup()) {
368 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
369 logger.debug("{}: Send key {}", thingName, command);
370 api.sendIRKey(command.toString());
374 case CHANNEL_LED_STATUS_DISABLE:
375 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
376 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
378 case CHANNEL_LED_POWER_DISABLE:
379 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
380 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
383 case CHANNEL_SENSOR_SLEEPTIME:
384 logger.debug("{}: Set sensor sleep time to {}", thingName, command);
385 int value = (int) getNumber(command);
386 value = value > 0 ? Math.max(SHELLY_MOTION_SLEEPTIME_OFFSET, value - SHELLY_MOTION_SLEEPTIME_OFFSET)
388 api.setSleepTime(value);
390 case CHANNEL_CONTROL_SCHEDULE:
392 logger.debug("{}: {} Valve schedule/profile", thingName,
393 command == OnOffType.ON ? "Enable" : "Disable");
394 api.setValveProfile(0,
395 command == OnOffType.OFF ? 0 : profile.status.thermostats.get(0).profile);
398 case CHANNEL_CONTROL_PROFILE:
399 logger.debug("{}: Select profile {}", thingName, command);
401 if (command instanceof Number) {
402 id = (int) getNumber(command);
404 String cmd = command.toString();
405 if (isDigit(cmd.charAt(0))) {
406 id = Integer.parseInt(cmd);
407 } else if (profile.settings.thermostats != null) {
408 ShellyThermnostat t = profile.settings.thermostats.get(0);
409 for (int i = 0; i < t.profileNames.length; i++) {
410 if (t.profileNames[i].equalsIgnoreCase(cmd)) {
416 if (id < 0 || id > 5) {
417 logger.warn("{}: Invalid profile Id {} requested", thingName, profile);
420 api.setValveProfile(0, id);
422 case CHANNEL_CONTROL_MODE:
423 logger.debug("{}: Set mode to {}", thingName, command);
424 api.setValveMode(0, CHANNEL_CONTROL_MODE.equalsIgnoreCase(command.toString()));
426 case CHANNEL_CONTROL_SETTEMP:
427 logger.debug("{}: Set temperature to {}", thingName, command);
428 api.setValveTemperature(0, (int) getNumber(command));
430 case CHANNEL_CONTROL_POSITION:
431 logger.debug("{}: Set position to {}", thingName, command);
432 api.setValvePosition(0, getNumber(command));
434 case CHANNEL_CONTROL_BCONTROL:
435 logger.debug("{}: Set boost mode to {}", thingName, command);
436 api.startValveBoost(0, command == OnOffType.ON ? -1 : 0);
438 case CHANNEL_CONTROL_BTIMER:
439 logger.debug("{}: Set boost timer to {}", thingName, command);
440 api.setValveBoostTime(0, (int) getNumber(command));
444 update = handleDeviceCommand(channelUID, command);
449 if (update && !autoCoIoT && !isUpdateScheduled()) {
450 requestUpdates(1, false);
452 } catch (ShellyApiException e) {
453 ShellyApiResult res = e.getApiResult();
454 if (isAuthorizationFailed(res)) {
457 if (res.isNotCalibrtated()) {
458 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
460 logger.warn("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
463 } catch (IllegalArgumentException e) {
464 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
468 private double getNumber(Command command) {
469 if (command instanceof QuantityType) {
470 return ((QuantityType<?>) command).doubleValue();
472 if (command instanceof DecimalType) {
473 return ((DecimalType) command).doubleValue();
475 if (command instanceof Number) {
476 return ((Number) command).doubleValue();
478 throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
482 * Update device status and channels
484 protected void refreshStatus() {
486 boolean updated = false;
488 if (vibrationFilter > 0) {
490 logger.debug("{}: Vibration events are absorbed for {} more seconds", thingName,
491 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
495 ThingStatus thingStatus = getThing().getStatus();
496 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
497 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
498 || (thingStatus == ThingStatus.UNKNOWN)) {
499 logger.debug("{}: Status update triggered thing initialization", thingName);
500 initializeThing(); // may fire an exception if initialization failed
502 // Get profile, if refreshSettings == true reload settings from device
503 ShellySettingsStatus status = api.getStatus();
504 if (status.uptime != null && status.uptime == 0 && profile.alwaysOn) {
505 status = api.getStatus();
507 boolean restarted = checkRestarted(status);
508 profile = getProfile(refreshSettings || restarted);
509 profile.status = status;
510 profile.updateFromStatus(status);
512 logger.debug("{}: Device restart #{} detected", thingName, stats.restarts);
514 postEvent(ALARM_TYPE_RESTARTED, true);
517 // If status update was successful the thing must be online
520 // map status to channels
521 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
522 updated |= this.updateDeviceStatus(status);
523 updated |= ShellyComponents.updateDeviceStatus(this, status);
524 fillDeviceStatus(status, updated);
525 updated |= updateInputs(status);
526 updated |= updateMeters(this, status);
527 updated |= updateSensors(this, status);
529 // All channels must be created after the first cycle
530 channelsCreated = true;
532 } catch (ShellyApiException e) {
533 // http call failed: go offline except for battery devices, which might be in
534 // sleep mode. Once the next update is successful the device goes back online
536 ShellyApiResult res = e.getApiResult();
537 if (profile.alwaysOn && e.isConnectionError()) {
538 status = "offline.status-error-connect";
539 } else if (res.isHttpAccessUnauthorized()) {
540 status = "offline.conf-error-access-denied";
541 } else if (isWatchdogStarted()) {
542 if (!isWatchdogExpired()) {
543 logger.debug("{}: Ignore API Timeout, retry later", thingName);
545 if (isThingOnline()) {
546 status = "offline.status-error-watchdog";
549 } else if (e.isJSONException()) {
550 status = "offline.status-error-unexpected-api-result";
551 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
552 } else if (res.isHttpTimeout()) {
553 // Watchdog not started, e.g. device in sleep mode
554 if (isThingOnline()) { // ignore when already offline
555 status = "offline.status-error-watchdog";
558 status = "offline.status-error-unexpected-api-result";
559 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
562 if (!status.isEmpty()) {
563 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
565 } catch (NullPointerException | IllegalArgumentException e) {
566 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
568 if (scheduledUpdates > 0) {
570 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
571 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
572 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
573 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
579 private void showThingConfig(ShellyDeviceProfile profile) {
580 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {}", thingName,
581 profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
583 logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
584 logger.debug("{}: Device "
585 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
586 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
587 + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
588 profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
589 profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
590 profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
591 profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
592 profile.inColor, profile.alwaysOn, profile.updatePeriod);
593 if (profile.status.extTemperature != null || profile.status.extHumidity != null
594 || profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
595 logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
599 private void addStateOptions(ShellyDeviceProfile prf) {
601 String[] profileNames = prf.getValveProfileList(0);
602 String channelId = mkChannelId(CHANNEL_GROUP_CONTROL, CHANNEL_CONTROL_PROFILE);
603 logger.debug("{}: Adding TRV profile names to channel description: {}", thingName, profileNames);
604 channelDefinitions.clearStateOptions(channelId);
606 for (String name : profileNames) {
607 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + name);
611 if (prf.isRoller && prf.settings.favorites != null) {
612 String channelId = mkChannelId(CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_FAV);
613 logger.debug("{}: Adding {}Â roler favorite(s) to channel description", thingName,
614 prf.settings.favorites.size());
615 channelDefinitions.clearStateOptions(channelId);
617 for (ShellyFavPos fav : prf.settings.favorites) {
618 channelDefinitions.addStateOption(channelId, "" + fid, fid + ": " + fav.name);
625 public String getThingType() {
626 return thing.getThingTypeUID().getId();
630 public ThingStatus getThingStatus() {
631 return thing.getStatus();
635 public ThingStatusDetail getThingStatusDetail() {
636 return thing.getStatusInfo().getStatusDetail();
640 public boolean isThingOnline() {
641 return getThingStatus() == ThingStatus.ONLINE;
644 public boolean isThingOffline() {
645 return getThingStatus() == ThingStatus.OFFLINE;
649 public void setThingOnline() {
650 if (!isThingOnline()) {
651 updateStatus(ThingStatus.ONLINE);
653 // request 3 updates in a row (during the first 2+3*3 sec)
654 requestUpdates(profile.alwaysOn ? 3 : 1, !channelsCreated);
657 // Restart watchdog when status update was successful (no exception)
662 public void setThingOffline(ThingStatusDetail detail, String messageKey, Object... arguments) {
663 if (!isThingOffline()) {
664 updateStatus(ThingStatus.OFFLINE, detail, messages.get(messageKey, arguments));
665 api.close(); // Gen2: disconnect WS/close http sessions
667 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
672 public void restartWatchdog() {
674 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
675 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
678 private boolean isWatchdogExpired() {
679 long delta = now() - watchdog;
680 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
681 stats.remainingWatchdog = delta;
687 private boolean isWatchdogStarted() {
692 public void reinitializeThing() {
693 logger.debug("{}: Re-Initialize Thing", thingName);
695 logger.debug("{}: Handler is shutting down, ignore", thingName);
698 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
699 messages.get("offline.status-error-restarted"));
700 requestUpdates(0, true);
704 public void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
707 // Update uptime and WiFi, internal temp
708 ShellyComponents.updateDeviceStatus(this, status);
709 stats.wifiRssi = status.wifiSta.rssi;
711 if (api.isInitialized()) {
712 stats.timeoutErrors = api.getTimeoutErrors();
713 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
715 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
717 // Check various device indicators like overheating
718 if (checkRestarted(status)) {
719 // Force re-initialization on next status update
721 } else if (getBool(status.overtemperature)) {
722 alarm = ALARM_TYPE_OVERTEMP;
723 } else if (getBool(status.overload)) {
724 alarm = ALARM_TYPE_OVERLOAD;
725 } else if (getBool(status.loaderror)) {
726 alarm = ALARM_TYPE_LOADERR;
728 State internalTemp = getChannelValue(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP);
729 if (internalTemp != UnDefType.NULL) {
730 int temp = ((Number) internalTemp).intValue();
731 if (temp > stats.maxInternalTemp) {
732 stats.maxInternalTemp = temp;
736 if (status.uptime != null) {
737 stats.lastUptime = getLong(status.uptime);
740 if (!alarm.isEmpty()) {
741 postEvent(alarm, false);
746 public void incProtMessages() {
747 stats.protocolMessages++;
751 public void incProtErrors() {
752 stats.protocolErrors++;
756 * Check if device has restarted and needs a new Thing initialization
758 * @return true: restart detected
761 private boolean checkRestarted(ShellySettingsStatus status) {
762 if (profile.isInitialized() && profile.alwaysOn /* exclude battery powered devices */
763 && (status.uptime != null && status.uptime < stats.lastUptime
764 || (!profile.status.update.oldVersion.isEmpty()
765 && !status.update.oldVersion.equals(profile.status.update.oldVersion)))) {
766 logger.debug("{}: Device has been restarted, uptime={}/{}, firmware={}/{}", thingName, stats.lastUptime,
767 getLong(status.uptime), profile.status.update.oldVersion, status.update.oldVersion);
768 updateProperties(profile, status);
775 * Save alarm to the lastAlarm channel
777 * @param alarm Alarm Message
780 public void postEvent(String event, boolean force) {
781 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
782 State value = cache.getValue(channelId);
783 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
785 if (force || !lastAlarm.equals(event)
786 || (lastAlarm.equals(event) && now() > stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC)) {
787 switch (event.toUpperCase()) {
790 case SHELLY_WAKEUPT_SENSOR:
791 case SHELLY_WAKEUPT_PERIODIC:
792 case SHELLY_WAKEUPT_BUTTON:
793 case SHELLY_WAKEUPT_POWERON:
794 case SHELLY_WAKEUPT_EXT_POWER:
795 case SHELLY_WAKEUPT_UNKNOWN:
796 logger.debug("{}: {}", thingName, messages.get("event.filtered", event));
797 case ALARM_TYPE_NONE:
800 logger.debug("{}: {}", thingName, messages.get("event.triggered", event));
801 triggerChannel(channelId, event);
802 cache.updateChannel(channelId, getStringType(event.toUpperCase()));
803 stats.lastAlarm = event;
804 stats.lastAlarmTs = now();
810 public boolean isUpdateScheduled() {
811 return scheduledUpdates > 0;
815 * Callback for device events
817 * @param deviceName device receiving the event
818 * @param parameters parameters from the event URL
819 * @param data the HTML input data
820 * @return true if event was processed
823 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
824 Map<String, String> parameters) {
825 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
826 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
828 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
829 if (!profile.isInitialized()) {
830 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
831 requestUpdates(1, true);
833 String group = profile.getControlGroup(idx);
834 if (group.isEmpty()) {
835 logger.debug("{}: Unsupported event class: {}", thingName, type);
839 // map some of the events to system defined button triggers
843 String parmType = getString(parameters.get("type"));
844 String event = !parmType.isEmpty() ? parmType : type;
845 boolean isButton = profile.inButtonMode(idx - 1);
847 case SHELLY_EVENT_SHORTPUSH:
848 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
849 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
850 case SHELLY_EVENT_LONGPUSH:
852 triggerButton(group, idx, mapButtonEvent(event));
853 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
854 payload = Shelly1ApiJsonDTO.mapButtonEvent(event);
856 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
860 case SHELLY_EVENT_BTN_ON:
861 case SHELLY_EVENT_BTN_OFF:
862 if (profile.isRGBW2) {
863 // RGBW2 has only one input, so not per channel
864 group = CHANNEL_GROUP_LIGHT_CONTROL;
866 onoff = CHANNEL_INPUT;
868 case SHELLY_EVENT_BTN1_ON:
869 case SHELLY_EVENT_BTN1_OFF:
870 onoff = CHANNEL_INPUT1;
872 case SHELLY_EVENT_BTN2_ON:
873 case SHELLY_EVENT_BTN2_OFF:
874 onoff = CHANNEL_INPUT2;
876 case SHELLY_EVENT_OUT_ON:
877 case SHELLY_EVENT_OUT_OFF:
878 onoff = CHANNEL_OUTPUT;
880 case SHELLY_EVENT_ROLLER_OPEN:
881 case SHELLY_EVENT_ROLLER_CLOSE:
882 case SHELLY_EVENT_ROLLER_STOP:
883 channel = CHANNEL_EVENT_TRIGGER;
886 case SHELLY_EVENT_SENSORREPORT:
887 // process sensor with next refresh
889 case SHELLY_EVENT_TEMP_OVER: // DW2
890 case SHELLY_EVENT_TEMP_UNDER:
891 channel = CHANNEL_EVENT_TRIGGER;
894 case SHELLY_EVENT_FLOOD_DETECTED:
895 case SHELLY_EVENT_FLOOD_GONE:
896 updateChannel(group, CHANNEL_SENSOR_FLOOD,
897 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
900 case SHELLY_EVENT_CLOSE: // DW 1.7
901 case SHELLY_EVENT_OPEN: // DW 1.7
902 updateChannel(group, CHANNEL_SENSOR_STATE,
903 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
904 : OpenClosedType.CLOSED);
907 case SHELLY_EVENT_DARK: // DW 1.7
908 case SHELLY_EVENT_TWILIGHT: // DW 1.7
909 case SHELLY_EVENT_BRIGHT: // DW 1.7
910 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
913 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
914 case SHELLY_EVENT_ALARM_HEAVY:
915 case SHELLY_EVENT_ALARM_OFF:
916 case SHELLY_EVENT_VIBRATION: // DW2
917 channel = CHANNEL_SENSOR_ALARM_STATE;
918 payload = event.toUpperCase();
922 // trigger will be provided by input/output channel or sensor channels
925 if (!onoff.isEmpty()) {
926 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
928 if (!payload.isEmpty()) {
929 // Pass event to trigger channel
930 payload = payload.toUpperCase();
931 logger.debug("{}: Post event {}", thingName, payload);
932 triggerChannel(mkChannelId(group, channel), payload);
936 // request update on next interval (2x for non-battery devices)
938 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
945 * Initialize the binding's thing configuration, calc update counts
947 protected void initializeThingConfig() {
948 thingType = getThing().getThingTypeUID().getId();
949 final Map<String, String> properties = getThing().getProperties();
950 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
951 if (thingName.isEmpty()) {
952 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
953 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
956 config = getConfigAs(ShellyThingConfiguration.class);
957 if (config.deviceIp.isEmpty()) {
958 logger.debug("{}: IP address for the device must not be empty", thingName); // may not set in .things file
962 InetAddress addr = InetAddress.getByName(config.deviceIp);
963 String saddr = addr.getHostAddress();
964 if (!config.deviceIp.equals(saddr)) {
965 logger.debug("{}: hostname {} resolved to IP address {}", thingName, config.deviceIp, saddr);
966 config.deviceIp = saddr;
968 } catch (UnknownHostException e) {
969 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
972 config.serviceName = getString(properties.get(PROPERTY_SERVICE_NAME));
973 config.localIp = bindingConfig.localIP;
974 config.localPort = String.valueOf(bindingConfig.httpPort);
975 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
976 config.userId = bindingConfig.defaultUserId;
977 config.password = bindingConfig.defaultPassword;
978 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
980 if (config.updateInterval == 0) {
981 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
983 if (config.updateInterval < UPDATE_MIN_DELAY) {
984 config.updateInterval = UPDATE_MIN_DELAY;
987 // Try to get updatePeriod from properties
988 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
989 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
990 // initialized successfully by the REST call.
991 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
992 if (!lastPeriod.isEmpty()) {
993 int period = Integer.parseInt(lastPeriod);
995 profile.updatePeriod = period;
999 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
1000 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
1003 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
1005 ShellyVersionDTO version = new ShellyVersionDTO();
1006 if (version.checkBeta(getString(prf.fwVersion))) {
1007 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate));
1009 String minVersion = !gen2 ? SHELLY_API_MIN_FWVERSION : SHELLY2_API_MIN_FWVERSION;
1010 if (version.compare(prf.fwVersion, minVersion) < 0) {
1011 logger.warn("{}: {}", prf.hostname,
1012 messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate, minVersion));
1015 if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
1016 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
1017 if (!config.eventsCoIoT) {
1018 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
1022 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
1023 logger.info("{}: {}", thingName,
1024 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
1026 } catch (NullPointerException e) { // could be inconsistant format of beta version
1027 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
1031 public String checkForUpdate() {
1033 ShellyOtaCheckResult result = api.checkForUpdate();
1034 return result.status;
1035 } catch (ShellyApiException e) {
1040 public void startCoap(ShellyThingConfiguration config, ShellyDeviceProfile profile) throws ShellyApiException {
1041 if (coap == null || !config.eventsCoIoT) {
1044 if (profile.settings.coiot != null && profile.settings.coiot.enabled != null) {
1045 String devpeer = getString(profile.settings.coiot.peer);
1046 String ourpeer = config.localIp + ":" + Shelly1CoapJSonDTO.COIOT_PORT;
1047 if (!profile.settings.coiot.enabled || (profile.isMotion && devpeer.isEmpty())) {
1049 api.setCoIoTPeer(ourpeer);
1050 logger.info("{}: CoIoT peer updated to {}", thingName, ourpeer);
1051 } catch (ShellyApiException e) {
1052 logger.debug("{}: Unable to set CoIoT peer: {}", thingName, e.toString());
1054 } else if (!devpeer.isEmpty() && !devpeer.equals(ourpeer)) {
1055 logger.warn("{}: CoIoT peer in device settings does not point this to this host", thingName);
1059 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
1060 config.eventsCoIoT = true;
1061 config.eventsSwitch = false;
1062 config.eventsButton = false;
1063 config.eventsPush = false;
1064 config.eventsRoller = false;
1065 config.eventsSensorReport = false;
1066 api.setConfig(thingName, config);
1069 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
1071 coap.start(thingName, config);
1076 * Checks the http response for authorization error.
1077 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
1078 * case the thing type shelly-unknown is set.
1080 * @param response exception details including the http respone
1081 * @return true if the authorization failed
1083 protected boolean isAuthorizationFailed(ShellyApiResult result) {
1084 if (result.isHttpAccessUnauthorized()) {
1085 // If the device is password protected the API doesn't provide settings to the device settings
1086 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
1093 * Change type of this thing.
1095 * @param thingType thing type acc. to the xml definition
1096 * @param mode Device mode (e.g. relay, roller)
1098 protected void changeThingType(String thingType, String mode) {
1099 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
1100 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
1101 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
1102 Map<String, String> properties = editProperties();
1103 properties.replace(PROPERTY_DEV_TYPE, thingType);
1104 properties.replace(PROPERTY_DEV_MODE, mode);
1105 updateProperties(properties);
1106 changeThingType(thingTypeUID, getConfig());
1111 public void thingUpdated(Thing thing) {
1112 logger.debug("{}: Channel definitions updated.", thingName);
1113 super.thingUpdated(thing);
1117 * Start the background updates
1119 protected void startUpdateJob() {
1120 ScheduledFuture<?> statusJob = this.statusJob;
1121 if ((statusJob == null) || statusJob.isCancelled()) {
1122 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
1124 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
1125 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
1130 * Flag the status job to do an exceptional update (something happened) rather
1131 * than waiting until the next regular poll
1133 * @param requestCount number of polls to execute
1134 * @param refreshSettings true=force a /settings query
1135 * @return true=Update schedule, false=skipped (too many updates already
1139 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
1140 this.refreshSettings |= refreshSettings;
1141 if (refreshSettings) {
1142 if (requestCount == 0) {
1143 logger.debug("{}: Request settings refresh", thingName);
1145 scheduledUpdates = 1;
1148 if (scheduledUpdates < 10) { // < 30s
1149 scheduledUpdates += requestCount;
1156 * Map input states to channels
1158 * @param groupName Channel Group (relay / relay1...)
1160 * @param status Shelly device status
1161 * @return true: one or more inputs were updated
1164 public boolean updateInputs(ShellySettingsStatus status) {
1165 boolean updated = false;
1167 if (status.inputs != null) {
1168 if (!areChannelsCreated()) {
1169 updateChannelDefinitions(ShellyChannelDefinitions.createInputChannels(thing, profile, status));
1173 boolean multiInput = !profile.isIX && status.inputs.size() >= 2; // device has multiple SW (inputs)
1174 for (ShellyInputState input : status.inputs) {
1175 String group = profile.getInputGroup(idx);
1176 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
1177 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
1178 if (input.event != null) {
1179 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
1180 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
1185 if (status.input != null) {
1186 // RGBW2: a single int rather than an array
1187 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
1188 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
1195 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
1196 boolean changed = false;
1197 if (valueArray != null && !valueArray.isEmpty()) {
1198 String reason = getString((String) valueArray.get(0));
1199 String newVal = valueArray.toString();
1200 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
1201 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
1203 postEvent(reason.toUpperCase(), true);
1205 lastWakeupReason = newVal;
1211 public void triggerButton(String group, int idx, String value) {
1212 String trigger = mapButtonEvent(value);
1213 if (trigger.isEmpty()) {
1217 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
1218 triggerChannel(group,
1219 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
1221 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
1222 if (profile.alwaysOn) {
1223 // refresh status of the input channel
1224 requestUpdates(1, false);
1229 public void publishState(String channelId, State value) {
1230 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
1231 if (!stopping && isLinked(id)) {
1232 updateState(id, value);
1233 logger.debug("{}: Channel {} updated with {} (type {}).", thingName, channelId, value, value.getClass());
1238 public boolean updateChannel(String group, String channel, State value) {
1239 return updateChannel(mkChannelId(group, channel), value, false);
1243 public boolean updateChannel(String channelId, State value, boolean force) {
1244 return !stopping && cache.updateChannel(channelId, value, force);
1248 public State getChannelValue(String group, String channel) {
1249 return cache.getValue(group, channel);
1253 public double getChannelDouble(String group, String channel) {
1254 State value = getChannelValue(group, channel);
1255 if (value != UnDefType.NULL) {
1256 if (value instanceof QuantityType) {
1257 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
1259 if (value instanceof DecimalType) {
1260 return ((DecimalType) value).doubleValue();
1267 * Update Thing's channels according to available status information from the API
1269 * @param thingHandler
1272 public void updateChannelDefinitions(Map<String, Channel> dynChannels) {
1273 if (channelsCreated) {
1274 return; // already done
1278 // Get subset of those channels that currently do not exist
1279 List<Channel> existingChannels = getThing().getChannels();
1280 for (Channel channel : existingChannels) {
1281 String id = channel.getUID().getId();
1282 if (dynChannels.containsKey(id)) {
1283 dynChannels.remove(id);
1287 if (!dynChannels.isEmpty()) {
1288 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
1289 ThingBuilder thingBuilder = editThing();
1290 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
1291 Channel c = channel.getValue();
1292 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
1293 thingBuilder.withChannel(c);
1295 updateThing(thingBuilder.build());
1296 logger.debug("{}: Channel definitions updated", thingName);
1298 } catch (IllegalArgumentException e) {
1299 logger.debug("{}: Unable to update channel definitions", thingName, e);
1304 public boolean areChannelsCreated() {
1305 return channelsCreated;
1309 * Update thing properties with dynamic values
1311 * @param profile The device profile
1312 * @param status the /status result
1314 public void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1315 Map<String, Object> properties = fillDeviceProperties(profile);
1316 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1317 String deviceName = getString(profile.settings.name);
1318 properties.put(PROPERTY_SERVICE_NAME, config.serviceName);
1319 properties.put(PROPERTY_DEV_GEN, "1");
1320 if (!deviceName.isEmpty()) {
1321 properties.put(PROPERTY_DEV_NAME, deviceName);
1323 properties.put(PROPERTY_DEV_GEN, !profile.isGen2 ? "1" : "2");
1325 // add status properties
1326 if (status.wifiSta != null) {
1327 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1329 if (status.update != null) {
1330 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1331 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1332 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1333 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1335 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1337 Map<String, String> thingProperties = new TreeMap<>();
1338 for (Map.Entry<String, Object> property : properties.entrySet()) {
1339 thingProperties.put(property.getKey(), (String) property.getValue());
1341 flushProperties(thingProperties);
1345 * Add one property to the Thing Properties
1347 * @param key Name of the property
1348 * @param value Value of the property
1351 public void updateProperties(String key, String value) {
1352 Map<String, String> thingProperties = editProperties();
1353 if (thingProperties.containsKey(key)) {
1354 thingProperties.replace(key, value);
1356 thingProperties.put(key, value);
1358 updateProperties(thingProperties);
1359 logger.trace("{}: Properties updated", thingName);
1362 public void flushProperties(Map<String, String> propertyUpdates) {
1363 Map<String, String> thingProperties = editProperties();
1364 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1365 if (thingProperties.containsKey(property.getKey())) {
1366 thingProperties.replace(property.getKey(), property.getValue());
1368 thingProperties.put(property.getKey(), property.getValue());
1371 updateProperties(thingProperties);
1375 * Get one property from the Thing Properties
1377 * @param key property name
1378 * @return property value or "" if property is not set
1381 public String getProperty(String key) {
1382 Map<String, String> thingProperties = getThing().getProperties();
1383 return getString(thingProperties.get(key));
1387 * Fill Thing Properties with device attributes
1389 * @param profile Property Map to full
1390 * @return a full property map
1392 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1393 Map<String, Object> properties = new TreeMap<>();
1394 properties.put(PROPERTY_VENDOR, VENDOR);
1395 if (profile.isInitialized()) {
1396 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1397 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1398 properties.put(PROPERTY_FIRMWARE_VERSION, profile.fwVersion + "/" + profile.fwDate);
1399 properties.put(PROPERTY_DEV_MODE, profile.mode);
1400 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1401 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1402 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1403 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1404 if (!profile.hwRev.isEmpty()) {
1405 properties.put(PROPERTY_HWREV, profile.hwRev);
1406 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1413 * Return device profile.
1415 * @param ForceRefresh true=force refresh before returning, false=return without
1417 * @return ShellyDeviceProfile instance
1418 * @throws ShellyApiException
1421 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1423 refreshSettings |= forceRefresh;
1424 if (refreshSettings) {
1425 profile = api.getDeviceProfile(thingType);
1426 if (!isThingOnline()) {
1427 logger.debug("{}: Device profile re-initialized (thingType={})", thingName, thingType);
1431 refreshSettings = false;
1437 public ShellyDeviceProfile getProfile() {
1442 public @Nullable List<StateOption> getStateOptions(ChannelTypeUID uid) {
1443 List<StateOption> options = channelDefinitions.getStateOptions(uid);
1444 if (!options.isEmpty()) {
1445 logger.debug("{}: Return {} state options for channel uid {}", thingName, options.size(), uid.getId());
1451 protected ShellyDeviceProfile getDeviceProfile() {
1456 public void triggerChannel(String group, String channel, String payload) {
1457 String triggerCh = mkChannelId(group, channel);
1458 logger.debug("{}: Send event {} to channel {}", thingName, triggerCh, payload);
1459 if (EVENT_TYPE_VIBRATION.contentEquals(payload)) {
1460 if (vibrationFilter == 0) {
1461 vibrationFilter = VIBRATION_FILTER_SEC / UPDATE_STATUS_INTERVAL_SECONDS + 1;
1462 logger.debug("{}: Duplicate vibration events will be absorbed for the next {} sec", thingName,
1463 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1465 logger.debug("{}: Vibration event absorbed, {} sec remaining", thingName,
1466 vibrationFilter * UPDATE_STATUS_INTERVAL_SECONDS);
1471 triggerChannel(triggerCh, payload);
1474 public void stop() {
1475 logger.debug("{}: Shutting down", thingName);
1476 ScheduledFuture<?> job = this.statusJob;
1480 logger.debug("{}: Shelly statusJob stopped", thingName);
1483 profile.initialized = false;
1487 * Shutdown thing, make sure background jobs are canceled
1490 public void dispose() {
1491 logger.debug("{}: Stopping Thing", thingName);
1498 * Device specific command handlers are overriding this method to do additional stuff
1500 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1504 public String getUID() {
1505 return getThing().getUID().getAsString();
1509 * Device specific handlers are overriding this method to do additional stuff
1511 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1516 public String getThingName() {
1521 public void resetStats() {
1523 stats = new ShellyDeviceStats();
1527 public ShellyDeviceStats getStats() {
1532 public ShellyApiInterface getApi() {
1537 public long getScheduledUpdates() {
1538 return scheduledUpdates;
1541 public Map<String, String> getStatsProp() {
1542 return stats.asProperties();
1546 public void triggerUpdateFromCoap() {
1547 if ((!autoCoIoT && (getScheduledUpdates() < 1)) || (autoCoIoT && !profile.isLight && !profile.hasBattery)) {
1548 requestUpdates(1, false);