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.apache.commons.lang.time.StopWatch;
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.ShellyApiJsonDTO;
35 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyInputState;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
37 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
38 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
39 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
40 import org.openhab.binding.shelly.internal.api.ShellyHttpApi;
41 import org.openhab.binding.shelly.internal.coap.ShellyCoapHandler;
42 import org.openhab.binding.shelly.internal.coap.ShellyCoapServer;
43 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
44 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
45 import org.openhab.binding.shelly.internal.discovery.ShellyThingCreator;
46 import org.openhab.binding.shelly.internal.util.ShellyChannelCache;
47 import org.openhab.binding.shelly.internal.util.ShellyTranslationProvider;
48 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
49 import org.openhab.core.library.types.OnOffType;
50 import org.openhab.core.library.types.OpenClosedType;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.ThingTypeUID;
57 import org.openhab.core.thing.binding.BaseThingHandler;
58 import org.openhab.core.thing.binding.builder.ThingBuilder;
59 import org.openhab.core.types.Command;
60 import org.openhab.core.types.RefreshType;
61 import org.openhab.core.types.State;
62 import org.openhab.core.types.UnDefType;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
67 * The {@link ShellyBaseHandler} is responsible for handling commands, which are
68 * sent to one of the channels.
70 * @author Markus Michels - Initial contribution
73 public class ShellyBaseHandler extends BaseThingHandler implements ShellyDeviceListener {
74 protected final Logger logger = LoggerFactory.getLogger(ShellyBaseHandler.class);
75 protected final ShellyChannelDefinitionsDTO channelDefinitions;
77 public String thingName = "";
78 public String thingType = "";
80 protected final ShellyHttpApi api;
81 protected ShellyBindingConfiguration bindingConfig;
82 protected ShellyThingConfiguration config = new ShellyThingConfiguration();
83 protected ShellyDeviceProfile profile = new ShellyDeviceProfile(); // init empty profile to avoid NPE
84 private final ShellyCoapHandler coap;
85 public boolean autoCoIoT = false;
87 private final ShellyTranslationProvider messages;
88 protected boolean stopping = false;
89 private boolean channelsCreated = false;
91 private long lastUptime = 0;
92 private long lastAlarmTs = 0;
93 private long lastTimeoutErros = -1;
94 private final StopWatch watchdog = new StopWatch();
96 private @Nullable ScheduledFuture<?> statusJob;
97 public int scheduledUpdates = 0;
98 private int skipCount = UPDATE_SKIP_COUNT;
99 private int skipUpdate = 0;
100 private boolean refreshSettings = false;
102 private @Nullable ScheduledFuture<?> asyncButtonRelease;
104 // delay before enabling channel
105 private final int cacheCount = UPDATE_SETTINGS_INTERVAL_SECONDS / UPDATE_STATUS_INTERVAL_SECONDS;
106 protected final ShellyChannelCache cache;
108 private String localIP = "";
109 private String localPort = "";
111 private String lastWakeupReason = "";
116 * @param thing The Thing object
117 * @param bindingConfig The binding configuration (beside thing
119 * @param coapServer coap server instance
120 * @param localIP local IP address from networkAddressService
121 * @param httpPort from httpService
123 public ShellyBaseHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
124 final ShellyBindingConfiguration bindingConfig, final ShellyCoapServer coapServer, final String localIP,
125 int httpPort, final HttpClient httpClient) {
128 this.messages = translationProvider;
129 this.cache = new ShellyChannelCache(this);
130 this.channelDefinitions = new ShellyChannelDefinitionsDTO(messages);
131 this.bindingConfig = bindingConfig;
133 this.localIP = localIP;
134 this.localPort = String.valueOf(httpPort);
135 this.api = new ShellyHttpApi(thingName, config, httpClient);
137 coap = new ShellyCoapHandler(this, coapServer);
141 * Schedule asynchronous Thing initialization, register thing to event dispatcher
144 public void initialize() {
145 // start background initialization:
146 scheduler.schedule(() -> {
147 boolean start = true;
149 initializeThingConfig();
150 logger.debug("{}: Device config: IP address={}, HTTP user/password={}/{}, update interval={}",
151 thingName, config.deviceIp, config.userId.isEmpty() ? "<non>" : config.userId,
152 config.password.isEmpty() ? "<none>" : "***", config.updateInterval);
154 "{}: Configured Events: Button: {}, Switch (on/off): {}, Push: {}, Roller: {}, Sensor: {}, CoIoT: {}, Enable AutoCoIoT: {}",
155 thingName, config.eventsButton, config.eventsSwitch, config.eventsPush, config.eventsRoller,
156 config.eventsSensorReport, config.eventsCoIoT, bindingConfig.autoCoIoT);
157 updateStatus(ThingStatus.UNKNOWN);
158 start = initializeThing();
159 } catch (ShellyApiException e) {
160 ShellyApiResult res = e.getApiResult();
161 if (isAuthorizationFailed(res)) {
164 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
165 } catch (IllegalArgumentException e) {
166 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
168 // even this initialization failed we start the status update
169 // the updateJob will then try to auto-initialize the thing
170 // in this case the thing stays in status INITIALIZING
175 }, 2, TimeUnit.SECONDS);
179 * This routine is called every time the Thing configuration has been changed (e.g. PaperUI)
182 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
183 super.handleConfigurationUpdate(configurationParameters);
184 logger.debug("{}: Thing config updated, re-initialize", thingName);
186 requestUpdates(1, true);// force re-initialization
190 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
191 * If the device is password protected and the credentials are missing or don't match the API access will throw an
192 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
193 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
194 * credentials are correct and the API access is initialized successful.
196 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
198 private boolean initializeThing() throws ShellyApiException {
199 // Init from thing type to have a basic profile, gets updated when device info is received from API
201 refreshSettings = false;
202 lastWakeupReason = "";
203 profile.initFromThingType(thingType);
204 api.setConfig(thingName, config);
205 cache.setThingName(thingName);
208 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
209 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
210 if (config.deviceIp.isEmpty()) {
211 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
215 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
216 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
218 if (config.eventsCoIoT && profile.hasBattery && !profile.isSense) {
219 coap.start(thingName, config);
222 // Initialize API access, exceptions will be catched by initialize()
223 ShellySettingsDevice devInfo = api.getDevInfo();
224 if (devInfo.auth && config.userId.isEmpty()) {
225 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
229 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
230 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
231 changeThingType(thingName, tmpPrf.mode);
232 return false; // force re-initialization
234 // Validate device mode
235 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
236 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
237 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
241 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {} ({})",
242 thingName, tmpPrf.hostname, tmpPrf.deviceType, tmpPrf.hwRev, tmpPrf.hwBatchId, tmpPrf.fwVersion,
243 tmpPrf.fwDate, tmpPrf.fwId);
244 logger.debug("{}: Shelly settings info for {}: {}", thingName, tmpPrf.hostname, tmpPrf.settingsJson);
245 logger.debug("{}: Device "
246 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
247 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
248 + ",updatePeriod:{}sec", thingName, tmpPrf.hasRelays, tmpPrf.numRelays, tmpPrf.isRoller,
249 tmpPrf.numRollers, tmpPrf.isDimmer, tmpPrf.numMeters, tmpPrf.isEMeter, tmpPrf.isSensor, tmpPrf.isDW,
250 tmpPrf.hasBattery, tmpPrf.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
251 tmpPrf.isSense, tmpPrf.isLight, profile.isBulb, tmpPrf.isDuo, tmpPrf.isRGBW2, tmpPrf.inColor,
252 tmpPrf.updatePeriod);
254 // update thing properties
255 ShellySettingsStatus status = api.getStatus();
256 updateProperties(tmpPrf, status);
257 checkVersion(tmpPrf, status);
259 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
260 config.eventsCoIoT = true;
261 config.eventsSwitch = false;
262 config.eventsButton = false;
263 config.eventsPush = false;
264 config.eventsRoller = false;
265 config.eventsSensorReport = false;
266 api.setConfig(thingName, config);
269 // All initialization done, so keep the profile and set Thing to ONLINE
271 fillDeviceStatus(status, false);
272 postEvent(ALARM_TYPE_NONE, false);
273 api.setActionURLs(); // register event urls
274 if (config.eventsCoIoT) {
275 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
276 coap.start(thingName, config);
279 logger.debug("{}: Thing successfully initialized.", thingName);
280 setThingOnline(); // if API call was successful the thing must be online
282 return true; // success
286 * Handle Channel Commands
289 public void handleCommand(ChannelUID channelUID, Command command) {
291 if (command instanceof RefreshType) {
295 if (!profile.isInitialized()) {
296 logger.debug("{}: {}", thingName, messages.get("message.command.init", command));
299 profile = getProfile(false);
302 boolean update = false;
303 switch (channelUID.getIdWithoutGroup()) {
304 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
305 logger.debug("{}: Send key {}", thingName, command);
306 api.sendIRKey(command.toString());
310 case CHANNEL_LED_STATUS_DISABLE:
311 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
312 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
314 case CHANNEL_LED_POWER_DISABLE:
315 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
316 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
320 update = handleDeviceCommand(channelUID, command);
325 if (update && !autoCoIoT) {
326 requestUpdates(1, false);
328 } catch (ShellyApiException e) {
329 ShellyApiResult res = e.getApiResult();
330 if (isAuthorizationFailed(res)) {
333 if (res.isNotCalibrtated()) {
334 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
336 logger.info("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
339 } catch (IllegalArgumentException e) {
340 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
345 * Update device status and channels
347 protected void refreshStatus() {
349 boolean updated = false;
352 ThingStatus thingStatus = getThing().getStatus();
354 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
355 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
356 || (thingStatus == ThingStatus.UNKNOWN)) {
357 logger.debug("{}: Status update triggered thing initialization", thingName);
358 initializeThing(); // may fire an exception if initialization failed
360 // Get profile, if refreshSettings == true reload settings from device
361 profile = getProfile(refreshSettings);
363 logger.trace("{}: Updating status", thingName);
364 ShellySettingsStatus status = api.getStatus();
366 // If status update was successful the thing must be online
369 // map status to channels
370 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
371 updated |= this.updateDeviceStatus(status);
372 updated |= ShellyComponents.updateDeviceStatus(this, status);
373 // if (!channelsCreated || !cache.isEnabled() || (coap.getVersion() <
374 // ShellyCoapJSonDTO.COIOT_VERSION_2)) {
375 updated |= updateMeters(this, status);
376 updated |= updateSensors(this, status);
377 updated |= updateInputs(status);
379 // logger.debug("Skipping Meter/Sensor/Input updates, because device is running CoIoT version 2");
382 // All channels must be created after the first cycle
383 channelsCreated = true;
385 // Restart watchdog when status update was successful (no exception)
388 if (scheduledUpdates <= 1) {
389 fillDeviceStatus(status, updated);
392 } catch (ShellyApiException e) {
393 // http call failed: go offline except for battery devices, which might be in
394 // sleep mode. Once the next update is successful the device goes back online
396 ShellyApiResult res = e.getApiResult();
397 if (isWatchdogStarted()) {
398 if (!isWatchdogExpired()) {
399 logger.debug("{}: Ignore API Timeout, retry later", thingName);
400 } else if (profile.hasBattery) {
401 logger.debug("{}: Ignore API Timeout for battery powered device", thingName);
403 logger.debug("{}: Watchdog expired after {}sec,", thingName, profile.updatePeriod);
404 if (isThingOnline()) {
405 status = "offline.status-error-watchdog";
408 } else if (res.isHttpAccessUnauthorized()) {
409 status = "offline.conf-error-access-denied";
410 } else if (e.isJSONException()) {
411 status = "offline.status-error-unexpected-api-result";
412 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
414 status = "offline.status-error-unexpected-api-result";
415 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
418 if (!status.isEmpty()) {
419 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
421 } catch (NullPointerException | IllegalArgumentException e) {
422 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
424 if (scheduledUpdates > 0) {
426 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
427 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
428 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
429 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
435 public boolean isThingOnline() {
436 return getThing().getStatus() == ThingStatus.ONLINE;
439 public boolean isThingOffline() {
440 return getThing().getStatus() == ThingStatus.OFFLINE;
443 public void setThingOnline() {
444 if (!isThingOnline()) {
445 updateStatus(ThingStatus.ONLINE);
447 // request 3 updates in a row (during the first 2+3*3 sec)
448 requestUpdates(!profile.hasBattery ? 3 : 1, channelsCreated == false);
453 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
454 if (!isThingOffline()) {
455 logger.info("{}: Thing goes OFFLINE: {}", thingName, messages.get(messageKey));
456 updateStatus(ThingStatus.OFFLINE, detail, "@text/" + messageKey);
458 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
462 public synchronized void restartWatchdog() {
463 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
468 private boolean isWatchdogExpired() {
469 return watchdog.getTime() > profile.updatePeriod;
472 private boolean isWatchdogStarted() {
474 if (isThingOnline()) {
475 watchdog.getStartTime();
478 } catch (IllegalStateException e) {
483 public void reinitializeThing() {
484 updateStatus(ThingStatus.UNKNOWN);
485 requestUpdates(1, true);
488 private void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
490 boolean force = false;
491 Map<String, String> propertyUpdates = new TreeMap<>();
493 // Update uptime and WiFi, internal temp
494 ShellyComponents.updateDeviceStatus(this, status);
496 if (api.isInitialized() && (lastTimeoutErros != api.getTimeoutErrors())) {
497 propertyUpdates.put(PROPERTY_STATS_TIMEOUTS, new Integer(api.getTimeoutErrors()).toString());
498 propertyUpdates.put(PROPERTY_STATS_TRECOVERED, new Integer(api.getTimeoutsRecovered()).toString());
499 lastTimeoutErros = api.getTimeoutErrors();
502 // Check various device indicators like overheating
503 if ((status.uptime < lastUptime) && (profile.isInitialized()) && !profile.hasBattery) {
504 alarm = ALARM_TYPE_RESTARTED;
506 // Force re-initialization on next status update
507 if (!profile.hasBattery) {
510 } else if (getBool(status.overtemperature)) {
511 alarm = ALARM_TYPE_OVERTEMP;
512 } else if (getBool(status.overload)) {
513 alarm = ALARM_TYPE_OVERLOAD;
514 } else if (getBool(status.loaderror)) {
515 alarm = ALARM_TYPE_LOADERR;
517 lastUptime = getLong(status.uptime);
519 if (!alarm.isEmpty()) {
520 postEvent(alarm, force);
523 if (!propertyUpdates.isEmpty()) {
524 flushProperties(propertyUpdates);
529 * Save alarm to the lastAlarm channel
531 * @param alarm Alarm Message
533 public void postEvent(String alarm, boolean force) {
534 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
535 State value = cache.getValue(channelId);
536 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
538 if (force || !lastAlarm.equals(alarm) || (now() > (lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC))) {
539 if (alarm.equals(ALARM_TYPE_NONE)) {
540 cache.updateChannel(channelId, getStringType(alarm));
542 logger.info("{}: {}", thingName, messages.get("event.triggered", alarm));
543 triggerChannel(channelId, alarm);
544 cache.updateChannel(channelId, getStringType(alarm));
551 * Callback for device events
553 * @param deviceName device receiving the event
554 * @param parameters parameters from the event URL
555 * @param data the HTML input data
556 * @return true if event was processed
559 public boolean onEvent(String ipAddress, String deviceName, String deviceIndex, String type,
560 Map<String, String> parameters) {
561 if (thingName.equalsIgnoreCase(deviceName) || config.deviceIp.equals(ipAddress)) {
562 logger.debug("{}: Event received: class={}, index={}, parameters={}", deviceName, type, deviceIndex,
564 int idx = !deviceIndex.isEmpty() ? Integer.parseInt(deviceIndex) : 1;
565 if (!profile.isInitialized()) {
566 logger.debug("{}: Device is not yet initialized, event triggers initialization", deviceName);
567 requestUpdates(1, true);
569 String group = profile.getControlGroup(idx);
570 if (group.isEmpty()) {
571 logger.debug("{}: Unsupported event class: {}", thingName, type);
575 // map some of the events to system defined button triggers
579 String parmType = getString(parameters.get("type"));
580 String event = !parmType.isEmpty() ? parmType : type;
581 boolean isButton = profile.inButtonMode(idx - 1);
583 case SHELLY_EVENT_SHORTPUSH:
584 case SHELLY_EVENT_DOUBLE_SHORTPUSH:
585 case SHELLY_EVENT_TRIPLE_SHORTPUSH:
586 case SHELLY_EVENT_LONGPUSH:
588 triggerButton(group, mapButtonEvent(event));
589 channel = CHANNEL_BUTTON_TRIGGER;
590 payload = ShellyApiJsonDTO.mapButtonEvent(event);
592 logger.debug("{}: Relay button is not in memontary or detached mode, ignore SHORT/LONGPUSH",
596 case SHELLY_EVENT_BTN_ON:
597 case SHELLY_EVENT_BTN_OFF:
598 if (profile.isRGBW2) {
599 // RGBW2 has only one input, so not per channel
600 group = CHANNEL_GROUP_LIGHT_CONTROL;
602 onoff = CHANNEL_INPUT;
604 case SHELLY_EVENT_BTN1_ON:
605 case SHELLY_EVENT_BTN1_OFF:
606 onoff = CHANNEL_INPUT1;
608 case SHELLY_EVENT_BTN2_ON:
609 case SHELLY_EVENT_BTN2_OFF:
610 onoff = CHANNEL_INPUT2;
612 case SHELLY_EVENT_OUT_ON:
613 case SHELLY_EVENT_OUT_OFF:
614 onoff = CHANNEL_OUTPUT;
616 case SHELLY_EVENT_ROLLER_OPEN:
617 case SHELLY_EVENT_ROLLER_CLOSE:
618 case SHELLY_EVENT_ROLLER_STOP:
619 channel = CHANNEL_EVENT_TRIGGER;
622 case SHELLY_EVENT_SENSORREPORT:
623 // process sensor with next refresh
625 case SHELLY_EVENT_TEMP_OVER: // DW2
626 case SHELLY_EVENT_TEMP_UNDER:
627 channel = CHANNEL_EVENT_TRIGGER;
630 case SHELLY_EVENT_FLOOD_DETECTED:
631 case SHELLY_EVENT_FLOOD_GONE:
632 updateChannel(group, CHANNEL_SENSOR_FLOOD,
633 event.equalsIgnoreCase(SHELLY_EVENT_FLOOD_DETECTED) ? OnOffType.ON : OnOffType.OFF);
636 case SHELLY_EVENT_CLOSE: // DW 1.7
637 case SHELLY_EVENT_OPEN: // DW 1.7
638 updateChannel(group, CHANNEL_SENSOR_CONTACT,
639 event.equalsIgnoreCase(SHELLY_API_DWSTATE_OPEN) ? OpenClosedType.OPEN
640 : OpenClosedType.CLOSED);
643 case SHELLY_EVENT_DARK: // DW 1.7
644 case SHELLY_EVENT_TWILIGHT: // DW 1.7
645 case SHELLY_EVENT_BRIGHT: // DW 1.7
646 updateChannel(group, CHANNEL_SENSOR_ILLUM, getStringType(event));
649 case SHELLY_EVENT_VIBRATION:
650 updateChannel(group, CHANNEL_SENSOR_VIBRATION, OnOffType.ON);
653 case SHELLY_EVENT_ALARM_MILD: // Shelly Gas
654 case SHELLY_EVENT_ALARM_HEAVY:
655 case SHELLY_EVENT_ALARM_OFF:
656 channel = CHANNEL_SENSOR_ALARM_STATE;
657 payload = event.toUpperCase();
661 // trigger will be provided by input/output channel or sensor channels
664 if (!onoff.isEmpty()) {
665 updateChannel(group, onoff, event.toLowerCase().contains("_on") ? OnOffType.ON : OnOffType.OFF);
667 if (!payload.isEmpty()) {
668 // Pass event to trigger channel
669 payload = payload.toUpperCase();
670 logger.debug("{}: Post event {}", thingName, payload);
671 triggerChannel(mkChannelId(group, channel), payload);
675 // request update on next interval (2x for non-battery devices)
677 requestUpdates(scheduledUpdates >= 2 ? 0 : !profile.hasBattery ? 2 : 1, true);
684 * Initialize the binding's thing configuration, calc update counts
686 protected void initializeThingConfig() {
687 thingType = getThing().getThingTypeUID().getId();
688 final Map<String, String> properties = getThing().getProperties();
689 thingName = getString(properties.get(PROPERTY_SERVICE_NAME));
690 if (thingName.isEmpty()) {
691 thingName = getString(thingType + "-" + getString(getThing().getUID().getId())).toLowerCase();
692 logger.debug("{}: Thing name derived from UID {}", thingName, getString(getThing().getUID().toString()));
695 config = getConfigAs(ShellyThingConfiguration.class);
696 if (config.deviceIp.isEmpty()) {
697 logger.info("{}: IP address for the device must not be empty", thingName); // may not set in .things file
701 InetAddress addr = InetAddress.getByName(config.deviceIp);
702 String saddr = addr.getHostAddress();
703 if (!config.deviceIp.equals(saddr)) {
704 logger.debug("{}: hostname {}Â resolved to IP address {}", thingName, config.deviceIp, saddr);
705 config.deviceIp = saddr;
707 } catch (UnknownHostException e) {
708 logger.debug("{}: Unable to resolehostname {}", thingName, config.deviceIp);
711 config.localIp = localIP;
712 config.localPort = localPort;
713 if (config.userId.isEmpty() && !bindingConfig.defaultUserId.isEmpty()) {
714 config.userId = bindingConfig.defaultUserId;
715 config.password = bindingConfig.defaultPassword;
716 logger.debug("{}: Using userId {} from bindingConfig", thingName, config.userId);
718 if (config.updateInterval == 0) {
719 config.updateInterval = UPDATE_STATUS_INTERVAL_SECONDS * UPDATE_SKIP_COUNT;
721 if (config.updateInterval < UPDATE_MIN_DELAY) {
722 config.updateInterval = UPDATE_MIN_DELAY;
725 skipCount = config.updateInterval / UPDATE_STATUS_INTERVAL_SECONDS;
728 private void checkVersion(ShellyDeviceProfile prf, ShellySettingsStatus status) {
730 ShellyVersionDTO version = new ShellyVersionDTO();
731 if (version.checkBeta(getString(prf.fwVersion))) {
732 logger.info("{}: {}", prf.hostname, messages.get("versioncheck.beta", prf.fwVersion, prf.fwDate,
733 prf.fwId, SHELLY_API_MIN_FWVERSION));
735 if (version.compare(prf.fwVersion, SHELLY_API_MIN_FWVERSION) < 0) {
736 logger.warn("{}: {}", prf.hostname, messages.get("versioncheck.tooold", prf.fwVersion, prf.fwDate,
737 prf.fwId, SHELLY_API_MIN_FWVERSION));
740 if (bindingConfig.autoCoIoT && (version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT) >= 0)) {
741 if (!config.eventsCoIoT) {
742 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
746 } catch (NullPointerException e) { // could be inconsistant format of beta version
747 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
749 if (status.update.hasUpdate) {
750 logger.info("{}: {}", thingName,
751 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
756 * Checks the http response for authorization error.
757 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
758 * case the thing type shelly-unknown is set.
760 * @param response exception details including the http respone
761 * @return true if the authorization failed
763 private boolean isAuthorizationFailed(ShellyApiResult result) {
764 if (result.isHttpAccessUnauthorized()) {
765 // If the device is password protected the API doesn't provide settings to the device settings
766 logger.info("{}: {}", thingName, messages.get("init.protected"));
767 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
768 changeThingType(THING_TYPE_SHELLYPROTECTED_STR, "");
775 * Change type of this thing.
777 * @param thingType thing type acc. to the xml definition
778 * @param mode Device mode (e.g. relay, roller)
780 private void changeThingType(String thingType, String mode) {
781 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
782 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
783 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
784 Map<String, String> properties = editProperties();
785 properties.replace(PROPERTY_DEV_TYPE, thingType);
786 properties.replace(PROPERTY_DEV_MODE, mode);
787 updateProperties(properties);
788 changeThingType(thingTypeUID, getConfig());
793 public void thingUpdated(Thing thing) {
794 logger.debug("{}: Channel definitions updated.", thingName);
795 super.thingUpdated(thing);
799 * Start the background updates
801 protected void startUpdateJob() {
802 ScheduledFuture<?> statusJob = this.statusJob;
803 if ((statusJob == null) || statusJob.isCancelled()) {
804 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
806 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
807 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
812 * Flag the status job to do an exceptional update (something happened) rather
813 * than waiting until the next regular poll
815 * @param requestCount number of polls to execute
816 * @param refreshSettings true=force a /settings query
817 * @return true=Update schedule, false=skipped (too many updates already
820 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
821 this.refreshSettings |= refreshSettings;
822 if (refreshSettings) {
823 if (requestCount == 0) {
824 logger.debug("{}: Request settings refresh", thingName);
826 scheduledUpdates = requestCount;
829 if (scheduledUpdates < 10) { // < 30s
830 scheduledUpdates += requestCount;
837 * Map input states to channels
839 * @param groupName Channel Group (relay / relay1...)
841 * @param status Shelly device status
842 * @return true: one or more inputs were updated
844 public boolean updateInputs(String groupName, ShellySettingsStatus status, int index) {
845 if ((status.input == null)) {
849 boolean updated = false;
851 // RGBW2: a single int rather than an array
852 updated |= updateChannel(groupName, CHANNEL_INPUT,
853 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
855 if (profile.isDimmer || profile.isRoller) {
856 ShellyInputState state1 = status.inputs.get(0);
857 ShellyInputState state2 = status.inputs.get(1);
858 logger.trace("{}: Updating {}#input1 with {}, input2 with {}", thingName, groupName,
859 getOnOff(state1.input), getOnOff(state2.input));
860 updated |= updateChannel(groupName, CHANNEL_INPUT + "1", getOnOff(state1.input));
861 updated |= updateChannel(groupName, CHANNEL_INPUT + "2", getOnOff(state2.input));
863 if (index < status.inputs.size()) {
864 ShellyInputState state = status.inputs.get(index);
865 updated |= updateChannel(groupName, CHANNEL_INPUT, getOnOff(state.input));
867 logger.debug("{}: Unable to update input, index is out of range ({}/{}", thingName, index,
868 status.inputs.size());
875 public boolean updateInputs(ShellySettingsStatus status) {
876 boolean updated = false;
877 String groupName = "";
879 if (status.input != null) {
880 // RGBW2: a single int rather than an array
881 return updateChannel(groupName, CHANNEL_INPUT,
882 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
884 if (status.inputs != null) {
886 for (ShellyInputState input : status.inputs) {
887 String group = profile.getControlGroup(idx);
888 updated |= updateChannel(group, CHANNEL_INPUT, getOnOff(input.input));
889 if (input.event != null) {
890 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE, getStringType(input.event));
891 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT, getDecimal(input.eventCount));
899 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
900 boolean changed = false;
901 if ((valueArray != null) && (valueArray.size() > 0)) {
902 String reason = getString((String) valueArray.get(0));
903 String newVal = valueArray.toString();
904 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
905 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
907 postEvent(reason.toUpperCase(), true);
909 lastWakeupReason = newVal;
914 public void triggerButton(String group, String value) {
915 String trigger = mapButtonEvent(value);
916 if (trigger.isEmpty()) {
920 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
921 triggerChannel(group, CHANNEL_BUTTON_TRIGGER, trigger);
922 updateChannel(group, CHANNEL_LAST_UPDATE, getTimestamp());
923 if (!profile.hasBattery) {
924 // refresh status of the input channel
925 requestUpdates(1, false);
929 public void publishState(String channelId, State value) {
931 updateState(channelId.contains("$") ? substringBefore(channelId, "$") : channelId, 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 && (channelId.contains("$") || isLinked(channelId))
941 && cache.updateChannel(channelId, value, force);
944 public State getChannelValue(String group, String channel) {
945 return cache.getValue(group, channel);
949 * Update Thing's channels according to available status information from the API
951 * @param thingHandler
953 protected void updateChannelDefinitions(Map<String, Channel> dynChannels) {
954 if (channelsCreated) {
955 return; // already done
959 // Get subset of those channels that currently do not exist
960 List<Channel> existingChannels = getThing().getChannels();
961 for (Channel channel : existingChannels) {
962 String id = channel.getUID().getId();
963 if (dynChannels.containsKey(id)) {
964 dynChannels.remove(id);
968 if (!dynChannels.isEmpty()) {
969 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
970 ThingBuilder thingBuilder = editThing();
971 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
972 Channel c = channel.getValue();
973 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
974 thingBuilder.withChannel(c);
976 updateThing(thingBuilder.build());
977 logger.debug("{}: Channel definitions updated", thingName);
979 } catch (IllegalArgumentException e) {
980 logger.debug("{}: Unable to update channel definitions", thingName, e);
984 public boolean areChannelsCreated() {
985 return channelsCreated;
989 * Update thing properties with dynamic values
991 * @param profile The device profile
992 * @param status the /status result
994 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
995 Map<String, Object> properties = fillDeviceProperties(profile);
996 String serviceName = getString(getThing().getProperties().get(PROPERTY_SERVICE_NAME));
997 String hostname = getString(profile.settings.device.hostname).toLowerCase();
998 if (serviceName.isEmpty()) {
999 properties.put(PROPERTY_SERVICE_NAME, hostname);
1000 logger.trace("{}: Updated serrviceName to {}", thingName, hostname);
1003 // add status properties
1004 if (status.wifiSta != null) {
1005 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1007 if (status.update != null) {
1008 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1009 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1010 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1011 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1013 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1014 properties.put(PROPERTY_COIOTREFRESH, String.valueOf(autoCoIoT));
1016 Map<String, String> thingProperties = new TreeMap<>();
1017 for (Map.Entry<String, Object> property : properties.entrySet()) {
1018 thingProperties.put(property.getKey(), (String) property.getValue());
1020 flushProperties(thingProperties);
1024 * Add one property to the Thing Properties
1026 * @param key Name of the property
1027 * @param value Value of the property
1029 public void updateProperties(String key, String value) {
1030 Map<String, String> thingProperties = editProperties();
1031 if (thingProperties.containsKey(key)) {
1032 thingProperties.replace(key, value);
1034 thingProperties.put(key, value);
1036 updateProperties(thingProperties);
1037 logger.trace("{}: Properties updated", thingName);
1040 public void flushProperties(Map<String, String> propertyUpdates) {
1041 Map<String, String> thingProperties = editProperties();
1042 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1043 if (thingProperties.containsKey(property.getKey())) {
1044 thingProperties.replace(property.getKey(), property.getValue());
1046 thingProperties.put(property.getKey(), property.getValue());
1049 updateProperties(thingProperties);
1053 * Get one property from the Thing Properties
1055 * @param key property name
1056 * @return property value or "" if property is not set
1058 public String getProperty(String key) {
1059 Map<String, String> thingProperties = getThing().getProperties();
1060 return getString(thingProperties.get(key));
1064 * Fill Thing Properties with device attributes
1066 * @param profile Property Map to full
1067 * @return a full property map
1069 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1070 Map<String, Object> properties = new TreeMap<>();
1071 properties.put(PROPERTY_VENDOR, VENDOR);
1072 if (profile.isInitialized()) {
1073 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1074 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1075 properties.put(PROPERTY_FIRMWARE_VERSION,
1076 profile.fwVersion + "/" + profile.fwDate + "(" + profile.fwId + ")");
1077 properties.put(PROPERTY_DEV_MODE, profile.mode);
1078 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1079 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1080 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1081 if (!profile.hwRev.isEmpty()) {
1082 properties.put(PROPERTY_HWREV, profile.hwRev);
1083 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1086 if (profile.updatePeriod >= 0) {
1087 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1094 * Return device profile.
1096 * @param ForceRefresh true=force refresh before returning, false=return without
1098 * @return ShellyDeviceProfile instance
1099 * @throws ShellyApiException
1101 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1103 refreshSettings |= forceRefresh;
1104 if (refreshSettings) {
1105 profile = api.getDeviceProfile(thingType);
1106 if (!isThingOnline()) {
1107 logger.debug("{}:Device profile re-initialized (thingType={})", thingName, thingType);
1111 refreshSettings = false;
1116 public ShellyDeviceProfile getProfile() {
1120 protected ShellyHttpApi getShellyApi() {
1124 protected ShellyDeviceProfile getDeviceProfile() {
1128 public void triggerChannel(String group, String channel, String payload) {
1129 triggerChannel(mkChannelId(group, channel), payload);
1132 public void stop() {
1133 logger.debug("{}: Shutting down", thingName);
1134 ScheduledFuture<?> job = this.statusJob;
1138 logger.debug("{}: Shelly statusJob stopped", thingName);
1140 job = asyncButtonRelease;
1143 asyncButtonRelease = null;
1147 profile.initialized = false;
1151 * Shutdown thing, make sure background jobs are canceled
1154 public void dispose() {
1161 * Device specific command handlers are overriding this method to do additional stuff
1163 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1168 * Device specific handlers are overriding this method to do additional stuff
1170 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {