2 * Copyright (c) 2010-2021 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.api.ShellyApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.handler.ShellyComponents.*;
18 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19 import static org.openhab.core.thing.Thing.*;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.List;
25 import java.util.TreeMap;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.openhab.binding.shelly.internal.api.ShellyApiException;
33 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO;
34 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyInputState;
35 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
37 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
38 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
39 import org.openhab.binding.shelly.internal.api.ShellyHttpApi;
40 import org.openhab.binding.shelly.internal.coap.ShellyCoapHandler;
41 import org.openhab.binding.shelly.internal.coap.ShellyCoapServer;
42 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
43 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
44 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
45 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
46 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
47 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
48 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
49 import org.openhab.core.library.types.DecimalType;
50 import org.openhab.core.library.types.OnOffType;
51 import org.openhab.core.library.types.OpenClosedType;
52 import org.openhab.core.library.types.QuantityType;
53 import org.openhab.core.thing.Channel;
54 import org.openhab.core.thing.ChannelUID;
55 import org.openhab.core.thing.Thing;
56 import org.openhab.core.thing.ThingStatus;
57 import org.openhab.core.thing.ThingStatusDetail;
58 import org.openhab.core.thing.ThingTypeUID;
59 import org.openhab.core.thing.binding.BaseThingHandler;
60 import org.openhab.core.thing.binding.builder.ThingBuilder;
61 import org.openhab.core.types.Command;
62 import org.openhab.core.types.RefreshType;
63 import org.openhab.core.types.State;
64 import org.openhab.core.types.UnDefType;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
69 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Markus Michels - Initial contribution
75 public class ShellyBaseHandler extends BaseThingHandler implements ShellyDeviceListener {
76 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
77 protected final ShellyChannelDefinitions channelDefinitions;
79 public String thingName = "";
80 public String thingType = "";
82 protected final ShellyHttpApi api;
83 protected ShellyBindingConfiguration bindingConfig;
84 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
85 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
86 private final ShellyCoapHandler coap;
87 public boolean autoCoIoT = false;
89 public final ShellyTranslationProvider messages;
90 protected boolean stopping = false;
91 private boolean channelsCreated = false;
93 private long lastUptime = 0;
94 private long lastAlarmTs = 0;
95 private long lastTimeoutErros = -1;
96 private long watchdog = now();
98 private @Nullable ScheduledFuture<?> statusJob;
99 public int scheduledUpdates = 0;
100 private int skipCount = UPDATE_SKIP_COUNT;
101 private int skipUpdate = 0;
102 private boolean refreshSettings = false;
104 private @Nullable ScheduledFuture<?> asyncButtonRelease;
106 // delay before enabling channel
107 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
108 protected final ShellyChannelCache cache;
110 private String localIP = "";
111 private String localPort = "";
113 private String lastWakeupReason = "";
118 * @param thing The Thing object
119 * @param bindingConfig The binding configuration (beside thing
121 * @param coapServer coap server instance
122 * @param localIP local IP address from networkAddressService
123 * @param httpPort from httpService
125 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
126 final ShellyBindingConfiguration bindingConfig, final ShellyCoapServer coapServer, final String localIP,
127 int httpPort, final HttpClient httpClient) {
130 this.messages = translationProvider;
131 this.cache = new ShellyChannelCache(this);
132 this.channelDefinitions = new ShellyChannelDefinitions(messages);
133 this.bindingConfig = bindingConfig;
135 this.localIP = localIP;
136 this.localPort = String.valueOf(httpPort);
137 this.api = new ShellyHttpApi(thingName, config, httpClient);
139 coap = new ShellyCoapHandler(this, coapServer);
143 * Schedule asynchronous Thing initialization, register thing to event dispatcher
146 public void initialize() {
147 // start background initialization:
148 scheduler.schedule(() -> {
149 boolean start = true;
151 initializeThingConfig();
152 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
153 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
154 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
156 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
157 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
158 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
159 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.CONFIGURATION_PENDING,
160 messages.get("status.unknown.initializing"));
161 start = initializeThing();
162 } catch (ShellyApiException e) {
163 ShellyApiResult res = e.getApiResult();
164 if (isAuthorizationFailed(res)) {
167 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
168 } catch (IllegalArgumentException e) {
169 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
171 // even this initialization failed we start the status update
172 // the updateJob will then try to auto-initialize the thing
173 // in this case the thing stays in status INITIALIZING
178 }, 2, TimeUnit.SECONDS);
182 * This routine is called every time the Thing configuration has been changed.
185 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
186 super.handleConfigurationUpdate(configurationParameters);
187 logger.debug("{}: Thing config updated, re-initialize", thingName);
189 requestUpdates(1, true);// force re-initialization
193 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
194 * If the device is password protected and the credentials are missing or don't match the API access will throw an
195 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
196 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
197 * credentials are correct and the API access is initialized successful.
199 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
201 private boolean initializeThing() throws ShellyApiException {
202 // Init from thing type to have a basic profile, gets updated when device info is received from API
204 refreshSettings = false;
205 lastWakeupReason = "";
206 profile.initFromThingType(thingType);
207 api.setConfig(thingName, config);
208 cache.setThingName(thingName);
211 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
212 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
213 if (config.deviceIp.isEmpty()) {
214 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
218 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
219 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
221 if (config.eventsCoIoT && profile.hasBattery && !profile.isSense) {
222 coap.start(thingName, config);
225 // Initialize API access, exceptions will be catched by initialize()
226 ShellySettingsDevice devInfo = api.getDevInfo();
227 if (devInfo.auth && config.userId.isEmpty()) {
228 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
232 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
233 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
234 changeThingType(thingName, tmpPrf.mode);
235 return false; // force re-initialization
237 // Validate device mode
238 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
239 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
240 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
244 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {} ({})",
245 thingName, tmpPrf.hostname, tmpPrf.deviceType, tmpPrf.hwRev, tmpPrf.hwBatchId, tmpPrf.fwVersion,
246 tmpPrf.fwDate, tmpPrf.fwId);
247 logger.debug("{}: Shelly settings info for {}: {}", thingName, tmpPrf.hostname, tmpPrf.settingsJson);
248 logger.debug("{}: Device "
249 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
250 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
251 + ",updatePeriod:{}sec", thingName, tmpPrf.hasRelays, tmpPrf.numRelays, tmpPrf.isRoller,
252 tmpPrf.numRollers, tmpPrf.isDimmer, tmpPrf.numMeters, tmpPrf.isEMeter, tmpPrf.isSensor, tmpPrf.isDW,
253 tmpPrf.hasBattery, tmpPrf.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
254 tmpPrf.isSense, tmpPrf.isLight, profile.isBulb, tmpPrf.isDuo, tmpPrf.isRGBW2, tmpPrf.inColor,
255 tmpPrf.updatePeriod);
257 // update thing properties
258 ShellySettingsStatus status = api.getStatus();
259 tmpPrf.updateFromStatus(status);
260 updateProperties(tmpPrf, status);
261 checkVersion(tmpPrf, status);
263 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
264 config.eventsCoIoT = true;
265 config.eventsSwitch = false;
266 config.eventsButton = false;
267 config.eventsPush = false;
268 config.eventsRoller = false;
269 config.eventsSensorReport = false;
270 api.setConfig(thingName, config);
273 // All initialization done, so keep the profile and set Thing to ONLINE
275 fillDeviceStatus(status, false);
276 postEvent(ALARM_TYPE_NONE, false);
277 api.setActionURLs(); // register event urls
278 if (config.eventsCoIoT) {
279 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
280 coap.start(thingName, config);
283 logger.debug("{}: Thing successfully initialized.", thingName);
284 setThingOnline(); // if API call was successful the thing must be online
286 return true; // success
290 * Handle Channel Commands
293 public void handleCommand(ChannelUID channelUID, Command command) {
295 if (command instanceof RefreshType) {
296 String channelId = channelUID.getId();
297 State value = cache.getValue(channelId);
298 if (value != UnDefType.NULL) {
299 updateState(channelId, value);
304 if (!profile.isInitialized()) {
305 logger.debug("{}: {}", thingName, messages.get("command.init", command));
308 profile = getProfile(false);
311 boolean update = false;
312 switch (channelUID.getIdWithoutGroup()) {
313 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
314 logger.debug("{}: Send key {}", thingName, command);
315 api.sendIRKey(command.toString());
319 case CHANNEL_LED_STATUS_DISABLE:
320 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
321 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
323 case CHANNEL_LED_POWER_DISABLE:
324 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
325 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
329 update = handleDeviceCommand(channelUID, command);
334 if (update && !autoCoIoT) {
335 requestUpdates(1, false);
337 } catch (ShellyApiException e) {
338 ShellyApiResult res = e.getApiResult();
339 if (isAuthorizationFailed(res)) {
342 if (res.isNotCalibrtated()) {
343 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
345 logger.info("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
348 } catch (IllegalArgumentException e) {
349 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
354 * Update device status and channels
356 protected void refreshStatus() {
358 boolean updated = false;
361 ThingStatus thingStatus = getThing().getStatus();
362 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
363 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
364 || (thingStatus == ThingStatus.UNKNOWN)) {
365 logger.debug("{}: Status update triggered thing initialization", thingName);
366 initializeThing(); // may fire an exception if initialization failed
368 // Get profile, if refreshSettings == true reload settings from device
369 profile = getProfile(refreshSettings);
371 logger.trace("{}: Updating status", thingName);
372 ShellySettingsStatus status = api.getStatus();
373 profile.updateFromStatus(status);
375 // If status update was successful the thing must be online
378 // map status to channels
379 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
380 updated |= this.updateDeviceStatus(status);
381 updated |= ShellyComponents.updateDeviceStatus(this, status);
382 updated |= updateInputs(status);
383 updated |= updateMeters(this, status);
384 updated |= updateSensors(this, status);
386 // All channels must be created after the first cycle
387 channelsCreated = true;
389 // Restart watchdog when status update was successful (no exception)
392 if (scheduledUpdates <= 1) {
393 fillDeviceStatus(status, updated);
396 } catch (ShellyApiException e) {
397 // http call failed: go offline except for battery devices, which might be in
398 // sleep mode. Once the next update is successful the device goes back online
400 ShellyApiResult res = e.getApiResult();
401 if (isWatchdogStarted()) {
402 if (!isWatchdogExpired()) {
403 logger.debug("{}: Ignore API Timeout, retry later", thingName);
405 logger.debug("{}: Watchdog expired after {}sec,", thingName, profile.updatePeriod);
406 if (isThingOnline()) {
407 status = "offline.status-error-watchdog";
410 } else if (res.isHttpAccessUnauthorized()) {
411 status = "offline.conf-error-access-denied";
412 } else if (e.isJSONException()) {
413 status = "offline.status-error-unexpected-api-result";
414 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
415 } else if (res.isHttpTimeout()) {
416 // Watchdog not started, e.g. device in sleep mode
417 if (isThingOnline()) { // ignore when already offline
418 status = "offline.status-error-watchdog";
421 status = "offline.status-error-unexpected-api-result";
422 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
425 if (!status.isEmpty()) {
426 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
428 } catch (NullPointerException | IllegalArgumentException e) {
429 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
431 if (scheduledUpdates > 0) {
433 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
434 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
435 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
436 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
442 public boolean isThingOnline() {
443 return getThing().getStatus() == ThingStatus.ONLINE;
446 public boolean isThingOffline() {
447 return getThing().getStatus() == ThingStatus.OFFLINE;
450 public void setThingOnline() {
451 if (!isThingOnline()) {
452 updateStatus(ThingStatus.ONLINE);
454 // request 3 updates in a row (during the first 2+3*3 sec)
455 requestUpdates(!profile.hasBattery ? 3 : 1, channelsCreated == false);
460 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
461 if (!isThingOffline()) {
462 logger.info("{}: Thing goes OFFLINE: {}", thingName, messages.get(messageKey));
463 updateStatus(ThingStatus.OFFLINE, detail, "@text/" + messageKey);
465 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
469 public synchronized void restartWatchdog() {
471 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
472 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
475 private boolean isWatchdogExpired() {
476 long timeout = profile.hasBattery ? profile.updatePeriod : profile.updatePeriod;
477 long delta = now() - watchdog;
478 if ((watchdog > 0) && (delta > timeout)) {
479 logger.trace("{}: Watchdog expired after {}sec (started={}, now={}", thingName, delta, watchdog, now());
485 private boolean isWatchdogStarted() {
486 logger.trace("{}: Watchdog is {}", thingName, watchdog > 0 ? "started" : "inactive");
490 public void reinitializeThing() {
491 updateStatus(ThingStatus.UNKNOWN);
492 requestUpdates(1, true);
495 private void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
497 boolean force = false;
498 Map<String, String> propertyUpdates = new TreeMap<>();
500 // Update uptime and WiFi, internal temp
501 ShellyComponents.updateDeviceStatus(this, status);
503 if (api.isInitialized() && (lastTimeoutErros != api.getTimeoutErrors())) {
504 propertyUpdates.put(PROPERTY_STATS_TIMEOUTS, String.valueOf(api.getTimeoutErrors()));
505 propertyUpdates.put(PROPERTY_STATS_TRECOVERED, String.valueOf(api.getTimeoutsRecovered()));
506 lastTimeoutErros = api.getTimeoutErrors();
509 // Check various device indicators like overheating
510 if ((status.uptime < lastUptime) && (profile.isInitialized()) && !profile.hasBattery) {
511 alarm = ALARM_TYPE_RESTARTED;
513 // Force re-initialization on next status update
514 if (!profile.hasBattery) {
517 } else if (getBool(status.overtemperature)) {
518 alarm = ALARM_TYPE_OVERTEMP;
519 } else if (getBool(status.overload)) {
520 alarm = ALARM_TYPE_OVERLOAD;
521 } else if (getBool(status.loaderror)) {
522 alarm = ALARM_TYPE_LOADERR;
524 lastUptime = getLong(status.uptime);
526 if (!alarm.isEmpty()) {
527 postEvent(alarm, force);
530 if (!propertyUpdates.isEmpty()) {
531 flushProperties(propertyUpdates);
536 * Save alarm to the lastAlarm channel
538 * @param alarm Alarm Message
540 public void postEvent(String alarm, boolean force) {
541 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
542 State value = cache.getValue(channelId);
543 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
545 if (force || !lastAlarm.equals(alarm) || (now() > (lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC))) {
546 if (alarm.equals(ALARM_TYPE_NONE)) {
547 cache.updateChannel(channelId, getStringType(alarm));
549 logger.info("{}: {}", thingName, messages.get("event.triggered", alarm));
550 triggerChannel(channelId, alarm);
551 cache.updateChannel(channelId, getStringType(alarm));
558 * Callback for device events
560 * @param deviceName device receiving the event
561 * @param parameters parameters from the event URL
562 * @param data the HTML input data
563 * @return true if event was processed
566 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
567 Map<String, String> parameters) {
568 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
569 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
571 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
572 if (!profile.isInitialized()) {
573 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
574 requestUpdates(1, true);
576 String group = profile.getControlGroup(idx);
577 if (group.isEmpty()) {
578 logger.debug("{}: Unsupported event class: {}", thingName, type);
582 // map some of the events to system defined button triggers
586 String parmType = getString(parameters.get("type"));
587 String event = !parmType.isEmpty() ? parmType : type;
588 boolean isButton = profile.inButtonMode(idx - 1);
590 case SHELLY_EVENT_SHORTPUSH:
591 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
592 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
593 case SHELLY_EVENT_LONGPUSH:
595 triggerButton(group, idx, mapButtonEvent(event));
596 channel = CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx);
597 payload = ShellyApiJsonDTO.mapButtonEvent(event);
599 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
603 case SHELLY_EVENT_BTN_ON:
604 case SHELLY_EVENT_BTN_OFF:
605 if (profile.isRGBW2) {
606 // RGBW2 has only one input, so not per channel
607 group = CHANNEL_GROUP_LIGHT_CONTROL;
609 onoff = CHANNEL_INPUT;
611 case SHELLY_EVENT_BTN1_ON:
612 case SHELLY_EVENT_BTN1_OFF:
613 onoff = CHANNEL_INPUT1;
615 case SHELLY_EVENT_BTN2_ON:
616 case SHELLY_EVENT_BTN2_OFF:
617 onoff = CHANNEL_INPUT2;
619 case SHELLY_EVENT_OUT_ON:
620 case SHELLY_EVENT_OUT_OFF:
621 onoff = CHANNEL_OUTPUT;
623 case SHELLY_EVENT_ROLLER_OPEN:
624 case SHELLY_EVENT_ROLLER_CLOSE:
625 case SHELLY_EVENT_ROLLER_STOP:
626 channel = CHANNEL_EVENT_TRIGGER;
629 case SHELLY_EVENT_SENSORREPORT:
630 // process sensor with next refresh
632 case SHELLY_EVENT_TEMP_OVER: // DW2
633 case SHELLY_EVENT_TEMP_UNDER:
634 channel = CHANNEL_EVENT_TRIGGER;
637 case SHELLY_EVENT_FLOOD_DETECTED:
638 case SHELLY_EVENT_FLOOD_GONE:
639 updateChannel(group, CHANNEL_SENSOR_FLOOD,
640 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
643 case SHELLY_EVENT_CLOSE: // DW 1.7
644 case SHELLY_EVENT_OPEN: // DW 1.7
645 updateChannel(group, CHANNEL_SENSOR_CONTACT,
646 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
647 : OpenClosedType.CLOSED);
650 case SHELLY_EVENT_DARK: // DW 1.7
651 case SHELLY_EVENT_TWILIGHT: // DW 1.7
652 case SHELLY_EVENT_BRIGHT: // DW 1.7
653 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
656 case SHELLY_EVENT_VIBRATION:
657 updateChannel(group, CHANNEL_SENSOR_VIBRATION, OnOffType.ON);
660 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
661 case SHELLY_EVENT_ALARM_HEAVY:
662 case SHELLY_EVENT_ALARM_OFF:
663 channel = CHANNEL_SENSOR_ALARM_STATE;
664 payload = event.toUpperCase();
668 // trigger will be provided by input/output channel or sensor channels
671 if (!onoff.isEmpty()) {
672 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
674 if (!payload.isEmpty()) {
675 // Pass event to trigger channel
676 payload = payload.toUpperCase();
677 logger.debug("{}: Post event {}", thingName, payload);
678 triggerChannel(mkChannelId(group, channel), payload);
682 // request update on next interval (2x for non-battery devices)
684 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
691 * Initialize the binding's thing configuration, calc update counts
693 protected void initializeThingConfig() {
694 thingType = getThing().getThingTypeUID().getId();
695 final Map<String, String> properties = getThing().getProperties();
696 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
697 if (thingName.isEmpty()) {
698 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
699 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
702 config = getConfigAs(ShellyThingConfiguration.class);
703 if (config.deviceIp.isEmpty()) {
704 logger.info("{}: IP address for the device must not be empty", thingName); // may not set in .things file
708 InetAddress addr = InetAddress.getByName(config.deviceIp);
709 String saddr = addr.getHostAddress();
710 if (!config.deviceIp.equals(saddr)) {
711 logger.debug("{}: hostname {}Â resolved to IP address {}", thingName, config.deviceIp, saddr);
712 config.deviceIp = saddr;
714 } catch (UnknownHostException e) {
715 logger.debug("{}: Unable to resolve hostname {}", thingName, config.deviceIp);
718 config.localIp = localIP;
719 config.localPort = localPort;
720 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
721 config.userId = bindingConfig.defaultUserId;
722 config.password = bindingConfig.defaultPassword;
723 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
725 if (config.updateInterval == 0) {
726 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
728 if (config.updateInterval < UPDATE_MIN_DELAY) {
729 config.updateInterval = UPDATE_MIN_DELAY;
732 // Try to get updatePeriod from properties
733 // For battery devinities the REST call to get the settings will most likely fail, because the device is in
734 // sleep mode. Therefore we use the last saved property value as default. Will be overwritten, when device is
735 // initialized successfully by the REST call.
736 String lastPeriod = getString(properties.get(PROPERTY_UPDATE_PERIOD));
737 if (!lastPeriod.isEmpty()) {
738 int period = Integer.parseInt(lastPeriod);
740 profile.updatePeriod = period;
744 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
745 logger.trace("{}: updateInterval = {}s -> skipCount = {}", thingName, config.updateInterval, skipCount);
748 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
750 ShellyVersionDTO version = new ShellyVersionDTO();
751 if (version.checkBeta(getString(prf.fwVersion))) {
752 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate,
753 prf.fwId, SHELLY_API_MIN_FWVERSION));
755 if (version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) {
756 logger.warn("{}: {}", prf.hostname, messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate,
757 prf.fwId, SHELLY_API_MIN_FWVERSION));
760 if (bindingConfig.autoCoIoT && (version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT) >= 0)) {
761 if (!config.eventsCoIoT) {
762 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
766 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
767 logger.info("{}: {}", thingName,
768 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
770 } catch (NullPointerException e) { // could be inconsistant format of beta version
771 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
776 * Checks the http response for authorization error.
777 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
778 * case the thing type shelly-unknown is set.
780 * @param response exception details including the http respone
781 * @return true if the authorization failed
783 private boolean isAuthorizationFailed(ShellyApiResult result) {
784 if (result.isHttpAccessUnauthorized()) {
785 // If the device is password protected the API doesn't provide settings to the device settings
786 logger.info("{}: {}", thingName, messages.get("init.protected"));
787 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
788 changeThingType(THING_TYPE_SHELLYPROTECTED_STR, "");
795 * Change type of this thing.
797 * @param thingType thing type acc. to the xml definition
798 * @param mode Device mode (e.g. relay, roller)
800 private void changeThingType(String thingType, String mode) {
801 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
802 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
803 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
804 Map<String, String> properties = editProperties();
805 properties.replace(PROPERTY_DEV_TYPE, thingType);
806 properties.replace(PROPERTY_DEV_MODE, mode);
807 updateProperties(properties);
808 changeThingType(thingTypeUID, getConfig());
813 public void thingUpdated(Thing thing) {
814 logger.debug("{}: Channel definitions updated.", thingName);
815 super.thingUpdated(thing);
819 * Start the background updates
821 protected void startUpdateJob() {
822 ScheduledFuture<?> statusJob = this.statusJob;
823 if ((statusJob == null) || statusJob.isCancelled()) {
824 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
826 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
827 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
832 * Flag the status job to do an exceptional update (something happened) rather
833 * than waiting until the next regular poll
835 * @param requestCount number of polls to execute
836 * @param refreshSettings true=force a /settings query
837 * @return true=Update schedule, false=skipped (too many updates already
840 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
841 this.refreshSettings |= refreshSettings;
842 if (refreshSettings) {
843 if (requestCount == 0) {
844 logger.debug("{}: Request settings refresh", thingName);
846 scheduledUpdates = requestCount;
849 if (scheduledUpdates < 10) { // < 30s
850 scheduledUpdates += requestCount;
857 * Map input states to channels
859 * @param groupName Channel Group (relay / relay1...)
861 * @param status Shelly device status
862 * @return true: one or more inputs were updated
864 public boolean updateInputs(ShellySettingsStatus status) {
865 boolean updated = false;
867 if (status.inputs != null) {
869 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
870 for (ShellyInputState input : status.inputs) {
871 String group = profile.getControlGroup(idx);
872 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
874 if (!areChannelsCreated()) {
875 updateChannelDefinitions(
876 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
879 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
880 if (input.event != null) {
881 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
882 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
887 if (status.input != null) {
888 // RGBW2: a single int rather than an array
889 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
890 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
896 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
897 boolean changed = false;
898 if ((valueArray != null) && (valueArray.size() > 0)) {
899 String reason = getString((String) valueArray.get(0));
900 String newVal = valueArray.toString();
901 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
902 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
904 postEvent(reason.toUpperCase(), true);
906 lastWakeupReason = newVal;
911 public void triggerButton(String group, int idx, String value) {
912 String trigger = mapButtonEvent(value);
913 if (trigger.isEmpty()) {
917 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
918 triggerChannel(group,
919 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
921 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
922 if (!profile.hasBattery) {
923 // refresh status of the input channel
924 requestUpdates(1, false);
928 public void publishState(String channelId, State value) {
929 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
930 if (!stopping && isLinked(id)) {
931 updateState(id, value);
935 public boolean updateChannel(String group, String channel, State value) {
936 return updateChannel(mkChannelId(group, channel), value, false);
939 public boolean updateChannel(String channelId, State value, boolean force) {
940 return !stopping && cache.updateChannel(channelId, value, force);
943 public State getChannelValue(String group, String channel) {
944 return cache.getValue(group, channel);
947 public double getChannelDouble(String group, String channel) {
948 State value = getChannelValue(group, channel);
949 if (value != UnDefType.NULL) {
950 if (value instanceof QuantityType) {
951 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
953 if (value instanceof DecimalType) {
954 return ((DecimalType) value).doubleValue();
961 * Update Thing's channels according to available status information from the API
963 * @param thingHandler
965 protected void updateChannelDefinitions(Map<String, Channel> dynChannels) {
966 if (channelsCreated) {
967 return; // already done
971 // Get subset of those channels that currently do not exist
972 List<Channel> existingChannels = getThing().getChannels();
973 for (Channel channel : existingChannels) {
974 String id = channel.getUID().getId();
975 if (dynChannels.containsKey(id)) {
976 dynChannels.remove(id);
980 if (!dynChannels.isEmpty()) {
981 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
982 ThingBuilder thingBuilder = editThing();
983 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
984 Channel c = channel.getValue();
985 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
986 thingBuilder.withChannel(c);
988 updateThing(thingBuilder.build());
989 logger.debug("{}: Channel definitions updated", thingName);
991 } catch (IllegalArgumentException e) {
992 logger.debug("{}: Unable to update channel definitions", thingName, e);
996 public boolean areChannelsCreated() {
997 return channelsCreated;
1001 * Update thing properties with dynamic values
1003 * @param profile The device profile
1004 * @param status the /status result
1006 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1007 Map<String, Object> properties = fillDeviceProperties(profile);
1008 String serviceName = getString(getThing().getProperties().get(PROPERTY_SERVICE_NAME));
1009 String hostname = getString(profile.settings.device.hostname).toLowerCase();
1010 if (serviceName.isEmpty()) {
1011 properties.put(PROPERTY_SERVICE_NAME, hostname);
1012 logger.trace("{}: Updated serrviceName to {}", thingName, hostname);
1015 // add status properties
1016 if (status.wifiSta != null) {
1017 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1019 if (status.update != null) {
1020 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1021 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1022 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1023 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1025 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1026 properties.put(PROPERTY_COIOTREFRESH, String.valueOf(autoCoIoT));
1028 Map<String, String> thingProperties = new TreeMap<>();
1029 for (Map.Entry<String, Object> property : properties.entrySet()) {
1030 thingProperties.put(property.getKey(), (String) property.getValue());
1032 flushProperties(thingProperties);
1036 * Add one property to the Thing Properties
1038 * @param key Name of the property
1039 * @param value Value of the property
1041 public void updateProperties(String key, String value) {
1042 Map<String, String> thingProperties = editProperties();
1043 if (thingProperties.containsKey(key)) {
1044 thingProperties.replace(key, value);
1046 thingProperties.put(key, value);
1048 updateProperties(thingProperties);
1049 logger.trace("{}: Properties updated", thingName);
1052 public void flushProperties(Map<String, String> propertyUpdates) {
1053 Map<String, String> thingProperties = editProperties();
1054 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1055 if (thingProperties.containsKey(property.getKey())) {
1056 thingProperties.replace(property.getKey(), property.getValue());
1058 thingProperties.put(property.getKey(), property.getValue());
1061 updateProperties(thingProperties);
1065 * Get one property from the Thing Properties
1067 * @param key property name
1068 * @return property value or "" if property is not set
1070 public String getProperty(String key) {
1071 Map<String, String> thingProperties = getThing().getProperties();
1072 return getString(thingProperties.get(key));
1076 * Fill Thing Properties with device attributes
1078 * @param profile Property Map to full
1079 * @return a full property map
1081 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1082 Map<String, Object> properties = new TreeMap<>();
1083 properties.put(PROPERTY_VENDOR, VENDOR);
1084 if (profile.isInitialized()) {
1085 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1086 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1087 properties.put(PROPERTY_FIRMWARE_VERSION,
1088 profile.fwVersion + "/" + profile.fwDate + "(" + profile.fwId + ")");
1089 properties.put(PROPERTY_DEV_MODE, profile.mode);
1090 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1091 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1092 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1093 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1094 if (!profile.hwRev.isEmpty()) {
1095 properties.put(PROPERTY_HWREV, profile.hwRev);
1096 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1103 * Return device profile.
1105 * @param ForceRefresh true=force refresh before returning, false=return without
1107 * @return ShellyDeviceProfile instance
1108 * @throws ShellyApiException
1110 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1112 refreshSettings |= forceRefresh;
1113 if (refreshSettings) {
1114 profile = api.getDeviceProfile(thingType);
1115 if (!isThingOnline()) {
1116 logger.debug("{}:Device profile re-initialized (thingType={})", thingName, thingType);
1120 refreshSettings = false;
1125 public ShellyDeviceProfile getProfile() {
1129 protected ShellyHttpApi getShellyApi() {
1133 protected ShellyDeviceProfile getDeviceProfile() {
1137 public void triggerChannel(String group, String channel, String payload) {
1138 triggerChannel(mkChannelId(group, channel), payload);
1141 public void stop() {
1142 logger.debug("{}: Shutting down", thingName);
1143 ScheduledFuture<?> job = this.statusJob;
1147 logger.debug("{}: Shelly statusJob stopped", thingName);
1149 job = asyncButtonRelease;
1152 asyncButtonRelease = null;
1156 profile.initialized = false;
1160 * Shutdown thing, make sure background jobs are canceled
1163 public void dispose() {
1170 * Device specific command handlers are overriding this method to do additional stuff
1172 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1177 * Device specific handlers are overriding this method to do additional stuff
1179 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {