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 protected ShellyDeviceStats stats = new ShellyDeviceStats();
87 private final ShellyCoapHandler coap;
88 public boolean autoCoIoT = false;
90 public final ShellyTranslationProvider messages;
91 protected boolean stopping = false;
92 private boolean channelsCreated = false;
94 private long watchdog = now();
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 ShellyChannelDefinitions(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, ThingStatusDetail.CONFIGURATION_PENDING,
158 messages.get("status.unknown.initializing"));
159 start = initializeThing();
160 } catch (ShellyApiException e) {
161 ShellyApiResult res = e.getApiResult();
162 if (isAuthorizationFailed(res)) {
165 logger.debug("{}: Unable to initialize: {}, retrying later", thingName, e.toString());
166 } catch (IllegalArgumentException e) {
167 logger.debug("{}: Unable to initialize, retrying later", thingName, e);
169 // even this initialization failed we start the status update
170 // the updateJob will then try to auto-initialize the thing
171 // in this case the thing stays in status INITIALIZING
176 }, 2, TimeUnit.SECONDS);
180 * This routine is called every time the Thing configuration has been changed
183 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
184 super.handleConfigurationUpdate(configurationParameters);
185 logger.debug("{}: Thing config updated, re-initialize", thingName);
187 requestUpdates(1, true);// force re-initialization
191 * Initialize Thing: Initialize API access, get settings and initialize Device Profile
192 * If the device is password protected and the credentials are missing or don't match the API access will throw an
193 * Exception. In this case the thing type will be changed to shelly-unknown. The user has the option to edit the
194 * thing config and set the correct credentials. The thing type will be changed to the requested one if the
195 * credentials are correct and the API access is initialized successful.
197 * @throws ShellyApiException e.g. http returned non-ok response, check e.getMessage() for details.
199 private boolean initializeThing() throws ShellyApiException {
200 // Init from thing type to have a basic profile, gets updated when device info is received from API
202 refreshSettings = false;
203 lastWakeupReason = "";
204 profile.initFromThingType(thingType);
205 api.setConfig(thingName, config);
206 cache.setThingName(thingName);
209 logger.debug("{}: Start initializing thing {}, type {}, ip address {}, CoIoT: {}", thingName,
210 getThing().getLabel(), thingType, config.deviceIp, config.eventsCoIoT);
211 if (config.deviceIp.isEmpty()) {
212 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "config-status.error.missing-device-ip");
216 // Setup CoAP listener to we get the CoAP message, which triggers initialization even the thing could not be
217 // fully initialized here. In this case the CoAP messages triggers auto-initialization (like the Action URL does
219 if (config.eventsCoIoT && profile.hasBattery && !profile.isMotion && !profile.isSense) {
220 coap.start(thingName, config);
223 // Initialize API access, exceptions will be catched by initialize()
224 ShellySettingsDevice devInfo = api.getDevInfo();
225 if (devInfo.auth && config.userId.isEmpty()) {
226 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-no-credentials");
230 ShellyDeviceProfile tmpPrf = api.getDeviceProfile(thingType);
231 if (this.getThing().getThingTypeUID().equals(THING_TYPE_SHELLYPROTECTED)) {
232 changeThingType(thingName, tmpPrf.mode);
233 return false; // force re-initialization
235 // Validate device mode
236 String reqMode = thingType.contains("-") ? substringAfter(thingType, "-") : "";
237 if (!reqMode.isEmpty() && !tmpPrf.mode.equals(reqMode)) {
238 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-wrong-mode");
241 if (!getString(devInfo.coiot).isEmpty()) {
242 // New Shelly devices might use a different endpoint for the CoAP listener
243 tmpPrf.coiotEndpoint = devInfo.coiot;
246 logger.debug("{}: Initializing device {}, type {}, Hardware: Rev: {}, batch {}; Firmware: {} / {} ({})",
247 thingName, tmpPrf.hostname, tmpPrf.deviceType, tmpPrf.hwRev, tmpPrf.hwBatchId, tmpPrf.fwVersion,
248 tmpPrf.fwDate, tmpPrf.fwId);
249 logger.debug("{}: Shelly settings info for {}: {}", thingName, tmpPrf.hostname, tmpPrf.settingsJson);
250 logger.debug("{}: Device "
251 + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{})"
252 + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}"
253 + ",updatePeriod:{}sec", thingName, tmpPrf.hasRelays, tmpPrf.numRelays, tmpPrf.isRoller,
254 tmpPrf.numRollers, tmpPrf.isDimmer, tmpPrf.numMeters, tmpPrf.isEMeter, tmpPrf.isSensor, tmpPrf.isDW,
255 tmpPrf.hasBattery, tmpPrf.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
256 tmpPrf.isSense, tmpPrf.isLight, profile.isBulb, tmpPrf.isDuo, tmpPrf.isRGBW2, tmpPrf.inColor,
257 tmpPrf.updatePeriod);
259 // update thing properties
260 tmpPrf.status = api.getStatus();
261 tmpPrf.updateFromStatus(tmpPrf.status);
262 updateProperties(tmpPrf, tmpPrf.status);
263 checkVersion(tmpPrf, tmpPrf.status);
265 logger.debug("{}: Auto-CoIoT is enabled, disabling action urls", thingName);
266 config.eventsCoIoT = true;
267 config.eventsSwitch = false;
268 config.eventsButton = false;
269 config.eventsPush = false;
270 config.eventsRoller = false;
271 config.eventsSensorReport = false;
272 api.setConfig(thingName, config);
275 // All initialization done, so keep the profile and set Thing to ONLINE
276 fillDeviceStatus(tmpPrf.status, false);
277 postEvent(ALARM_TYPE_NONE, false);
278 api.setActionURLs(); // register event urls
279 if (config.eventsCoIoT) {
280 logger.debug("{}: Starting CoIoT (autoCoIoT={}/{})", thingName, bindingConfig.autoCoIoT, autoCoIoT);
281 coap.start(thingName, config);
284 logger.debug("{}: Thing successfully initialized.", thingName);
286 setThingOnline(); // if API call was successful the thing must be online
288 return true; // success
292 * Handle Channel Commands
295 public void handleCommand(ChannelUID channelUID, Command command) {
297 if (command instanceof RefreshType) {
298 String channelId = channelUID.getId();
299 State value = cache.getValue(channelId);
300 if (value != UnDefType.NULL) {
301 updateState(channelId, value);
306 if (!profile.isInitialized()) {
307 logger.debug("{}: {}", thingName, messages.get("command.init", command));
310 profile = getProfile(false);
313 boolean update = false;
314 switch (channelUID.getIdWithoutGroup()) {
315 case CHANNEL_SENSE_KEY: // Shelly Sense: Send Key
316 logger.debug("{}: Send key {}", thingName, command);
317 api.sendIRKey(command.toString());
321 case CHANNEL_LED_STATUS_DISABLE:
322 logger.debug("{}: Set STATUS LED disabled to {}", thingName, command);
323 api.setLedStatus(SHELLY_LED_STATUS_DISABLE, command == OnOffType.ON);
325 case CHANNEL_LED_POWER_DISABLE:
326 logger.debug("{}: Set POWER LED disabled to {}", thingName, command);
327 api.setLedStatus(SHELLY_LED_POWER_DISABLE, command == OnOffType.ON);
331 update = handleDeviceCommand(channelUID, command);
336 if (update && !autoCoIoT) {
337 requestUpdates(1, false);
339 } catch (ShellyApiException e) {
340 ShellyApiResult res = e.getApiResult();
341 if (isAuthorizationFailed(res)) {
344 if (res.isNotCalibrtated()) {
345 logger.warn("{}: {}", thingName, messages.get("roller.calibrating"));
347 logger.info("{}: {} - {}", thingName, messages.get("command.failed", command, channelUID),
350 } catch (IllegalArgumentException e) {
351 logger.debug("{}: {}", thingName, messages.get("command.failed", command, channelUID));
356 * Update device status and channels
358 protected void refreshStatus() {
360 boolean updated = false;
363 ThingStatus thingStatus = getThing().getStatus();
364 if (refreshSettings || (scheduledUpdates > 0) || (skipUpdate % skipCount == 0)) {
365 if (!profile.isInitialized() || ((thingStatus == ThingStatus.OFFLINE))
366 || (thingStatus == ThingStatus.UNKNOWN)) {
367 logger.debug("{}: Status update triggered thing initialization", thingName);
368 initializeThing(); // may fire an exception if initialization failed
370 // Get profile, if refreshSettings == true reload settings from device
371 profile = getProfile(refreshSettings);
373 logger.trace("{}: Updating status", thingName);
374 ShellySettingsStatus status = api.getStatus();
375 profile.status = status;
376 profile.updateFromStatus(status);
378 // If status update was successful the thing must be online
381 // map status to channels
382 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_NAME, getStringType(profile.settings.name));
383 updated |= this.updateDeviceStatus(status);
384 updated |= ShellyComponents.updateDeviceStatus(this, status);
385 fillDeviceStatus(status, updated);
386 updated |= updateInputs(status);
387 updated |= updateMeters(this, status);
388 updated |= updateSensors(this, status);
390 // All channels must be created after the first cycle
391 channelsCreated = true;
393 // Restart watchdog when status update was successful (no exception)
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 if (isThingOnline()) {
406 status = "offline.status-error-watchdog";
409 } else if (res.isHttpAccessUnauthorized()) {
410 status = "offline.conf-error-access-denied";
411 } else if (e.isJSONException()) {
412 status = "offline.status-error-unexpected-api-result";
413 logger.debug("{}: Unable to parse API response: {}; json={}", thingName, res.getUrl(), res.response, e);
414 } else if (res.isHttpTimeout()) {
415 // Watchdog not started, e.g. device in sleep mode
416 if (isThingOnline()) { // ignore when already offline
417 status = "offline.status-error-watchdog";
420 status = "offline.status-error-unexpected-api-result";
421 logger.debug("{}: Unexpected API result: {}", thingName, res.response, e);
424 if (!status.isEmpty()) {
425 setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, status);
427 } catch (NullPointerException | IllegalArgumentException e) {
428 logger.debug("{}: Unable to refresh status: {}", thingName, messages.get("statusupdate.failed"), e);
430 if (scheduledUpdates > 0) {
432 logger.trace("{}: {} more updates requested", thingName, scheduledUpdates);
433 } else if ((skipUpdate >= cacheCount) && !cache.isEnabled()) {
434 logger.debug("{}: Enabling channel cache ({} updates / {}s)", thingName, skipUpdate,
435 cacheCount * UPDATE_STATUS_INTERVAL_SECONDS);
441 public boolean isThingOnline() {
442 return getThing().getStatus() == ThingStatus.ONLINE;
445 public boolean isThingOffline() {
446 return getThing().getStatus() == ThingStatus.OFFLINE;
449 public void setThingOnline() {
450 if (!isThingOnline()) {
451 updateStatus(ThingStatus.ONLINE);
453 // request 3 updates in a row (during the first 2+3*3 sec)
454 requestUpdates(!profile.hasBattery ? 3 : 1, channelsCreated == false);
459 public void setThingOffline(ThingStatusDetail detail, String messageKey) {
460 if (!isThingOffline()) {
461 logger.info("{}: Thing goes OFFLINE: {}", thingName, messages.get(messageKey));
462 updateStatus(ThingStatus.OFFLINE, detail, "@text/" + messageKey);
464 channelsCreated = false; // check for new channels after devices gets re-initialized (e.g. new
468 public synchronized void restartWatchdog() {
470 updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_HEARTBEAT, getTimestamp());
471 logger.trace("{}: Watchdog restarted (expires in {} sec)", thingName, profile.updatePeriod);
474 private boolean isWatchdogExpired() {
475 long delta = now() - watchdog;
476 if ((watchdog > 0) && (delta > profile.updatePeriod)) {
477 stats.remainingWatchdog = delta;
483 private boolean isWatchdogStarted() {
487 public void reinitializeThing() {
488 updateStatus(ThingStatus.UNKNOWN);
489 requestUpdates(1, true);
492 private void fillDeviceStatus(ShellySettingsStatus status, boolean updated) {
494 boolean force = false;
496 // Update uptime and WiFi, internal temp
497 ShellyComponents.updateDeviceStatus(this, status);
499 if (api.isInitialized()) {
500 stats.timeoutErrors = api.getTimeoutErrors();
501 stats.timeoutsRecorvered = api.getTimeoutsRecovered();
503 stats.remainingWatchdog = watchdog > 0 ? now() - watchdog : 0;
505 // Check various device indicators like overheating
506 logger.debug("{}: status.update={}, lastUpdate={}", thingName, status.uptime, stats.lastUptime);
507 if ((status.uptime < stats.lastUptime) && profile.isInitialized()) {
508 alarm = ALARM_TYPE_RESTARTED;
510 stats.unexpectedRestarts++;
511 logger.debug("{}: Device restart #{} detected", thingName, stats.unexpectedRestarts);
513 // Force re-initialization on next status update
514 if (!profile.hasBattery || profile.isMotion) {
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 stats.lastUptime = getLong(status.uptime);
525 stats.coiotMessages = coap.getMessageCount();
526 stats.coiotErrors = coap.getErrorCount();
528 if (!alarm.isEmpty()) {
529 postEvent(alarm, force);
534 * Save alarm to the lastAlarm channel
536 * @param alarm Alarm Message
538 public void postEvent(String alarm, boolean force) {
539 String channelId = mkChannelId(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ALARM);
540 State value = cache.getValue(channelId);
541 String lastAlarm = value != UnDefType.NULL ? value.toString() : "";
543 if (force || !lastAlarm.equals(alarm) || (now() > (stats.lastAlarmTs + HEALTH_CHECK_INTERVAL_SEC))) {
544 if (alarm.isEmpty() || alarm.equals(ALARM_TYPE_NONE)) {
545 cache.updateChannel(channelId, getStringType(alarm));
547 logger.info("{}: {}", thingName, messages.get("event.triggered", alarm));
548 triggerChannel(channelId, alarm);
549 cache.updateChannel(channelId, getStringType(alarm));
550 stats.lastAlarm = alarm;
551 stats.lastAlarmTs = now();
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 || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
762 if (!config.eventsCoIoT) {
763 logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
767 if (status.update.hasUpdate && !version.checkBeta(getString(prf.fwVersion))) {
768 logger.info("{}: {}", thingName,
769 messages.get("versioncheck.update", status.update.oldVersion, status.update.newVersion));
771 } catch (NullPointerException e) { // could be inconsistant format of beta version
772 logger.debug("{}: {}", thingName, messages.get("versioncheck.failed", prf.fwVersion));
777 * Checks the http response for authorization error.
778 * If the authorization failed the binding can't access the device settings and determine the thing type. In this
779 * case the thing type shelly-unknown is set.
781 * @param response exception details including the http respone
782 * @return true if the authorization failed
784 private boolean isAuthorizationFailed(ShellyApiResult result) {
785 if (result.isHttpAccessUnauthorized()) {
786 // If the device is password protected the API doesn't provide settings to the device settings
787 logger.info("{}: {}", thingName, messages.get("init.protected"));
788 setThingOffline(ThingStatusDetail.CONFIGURATION_ERROR, "offline.conf-error-access-denied");
789 changeThingType(THING_TYPE_SHELLYPROTECTED_STR, "");
796 * Change type of this thing.
798 * @param thingType thing type acc. to the xml definition
799 * @param mode Device mode (e.g. relay, roller)
801 private void changeThingType(String thingType, String mode) {
802 ThingTypeUID thingTypeUID = ShellyThingCreator.getThingTypeUID(thingType, "", mode);
803 if (!thingTypeUID.equals(THING_TYPE_SHELLYUNKNOWN)) {
804 logger.debug("{}: Changing thing type to {}", getThing().getLabel(), thingTypeUID);
805 Map<String, String> properties = editProperties();
806 properties.replace(PROPERTY_DEV_TYPE, thingType);
807 properties.replace(PROPERTY_DEV_MODE, mode);
808 updateProperties(properties);
809 changeThingType(thingTypeUID, getConfig());
814 public void thingUpdated(Thing thing) {
815 logger.debug("{}: Channel definitions updated.", thingName);
816 super.thingUpdated(thing);
820 * Start the background updates
822 protected void startUpdateJob() {
823 ScheduledFuture<?> statusJob = this.statusJob;
824 if ((statusJob == null) || statusJob.isCancelled()) {
825 this.statusJob = scheduler.scheduleWithFixedDelay(this::refreshStatus, 2, UPDATE_STATUS_INTERVAL_SECONDS,
827 logger.debug("{}: Update status job started, interval={}*{}={}sec.", thingName, skipCount,
828 UPDATE_STATUS_INTERVAL_SECONDS, skipCount * UPDATE_STATUS_INTERVAL_SECONDS);
833 * Flag the status job to do an exceptional update (something happened) rather
834 * than waiting until the next regular poll
836 * @param requestCount number of polls to execute
837 * @param refreshSettings true=force a /settings query
838 * @return true=Update schedule, false=skipped (too many updates already
841 public boolean requestUpdates(int requestCount, boolean refreshSettings) {
842 this.refreshSettings |= refreshSettings;
843 if (refreshSettings) {
844 if (requestCount == 0) {
845 logger.debug("{}: Request settings refresh", thingName);
847 scheduledUpdates = requestCount;
850 if (scheduledUpdates < 10) { // < 30s
851 scheduledUpdates += requestCount;
858 * Map input states to channels
860 * @param groupName Channel Group (relay / relay1...)
862 * @param status Shelly device status
863 * @return true: one or more inputs were updated
865 public boolean updateInputs(ShellySettingsStatus status) {
866 boolean updated = false;
868 if (status.inputs != null) {
870 boolean multiInput = status.inputs.size() >= 2; // device has multiple SW (inputs)
871 for (ShellyInputState input : status.inputs) {
872 String group = profile.getControlGroup(idx);
873 String suffix = multiInput ? profile.getInputSuffix(idx) : "";
875 if (!areChannelsCreated()) {
876 updateChannelDefinitions(
877 ShellyChannelDefinitions.createInputChannels(thing, profile, status, group));
880 updated |= updateChannel(group, CHANNEL_INPUT + suffix, getOnOff(input.input));
881 if (input.event != null) {
882 updated |= updateChannel(group, CHANNEL_STATUS_EVENTTYPE + suffix, getStringType(input.event));
883 updated |= updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + suffix, getDecimal(input.eventCount));
888 if (status.input != null) {
889 // RGBW2: a single int rather than an array
890 return updateChannel(profile.getControlGroup(0), CHANNEL_INPUT,
891 getInteger(status.input) == 0 ? OnOffType.OFF : OnOffType.ON);
897 public boolean updateWakeupReason(@Nullable List<Object> valueArray) {
898 boolean changed = false;
899 if ((valueArray != null) && (valueArray.size() > 0)) {
900 String reason = getString((String) valueArray.get(0));
901 String newVal = valueArray.toString();
902 changed = updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_WAKEUP, getStringType(reason));
903 changed |= !lastWakeupReason.isEmpty() && !lastWakeupReason.equals(newVal);
905 postEvent(reason.toUpperCase(), true);
907 lastWakeupReason = newVal;
912 public void triggerButton(String group, int idx, String value) {
913 String trigger = mapButtonEvent(value);
914 if (trigger.isEmpty()) {
918 logger.debug("{}: Update button state with {}/{}", thingName, value, trigger);
919 triggerChannel(group,
920 profile.isRoller ? CHANNEL_EVENT_TRIGGER : CHANNEL_BUTTON_TRIGGER + profile.getInputSuffix(idx),
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) {
930 String id = channelId.contains("$") ? substringBefore(channelId, "$") : channelId;
931 if (!stopping && isLinked(id)) {
932 updateState(id, value);
936 public boolean updateChannel(String group, String channel, State value) {
937 return updateChannel(mkChannelId(group, channel), value, false);
940 public boolean updateChannel(String channelId, State value, boolean force) {
941 return !stopping && cache.updateChannel(channelId, value, force);
944 public State getChannelValue(String group, String channel) {
945 return cache.getValue(group, channel);
948 public double getChannelDouble(String group, String channel) {
949 State value = getChannelValue(group, channel);
950 if (value != UnDefType.NULL) {
951 if (value instanceof QuantityType) {
952 return ((QuantityType<?>) value).toBigDecimal().doubleValue();
954 if (value instanceof DecimalType) {
955 return ((DecimalType) value).doubleValue();
962 * Update Thing's channels according to available status information from the API
964 * @param thingHandler
966 protected void updateChannelDefinitions(Map<String, Channel> dynChannels) {
967 if (channelsCreated) {
968 return; // already done
972 // Get subset of those channels that currently do not exist
973 List<Channel> existingChannels = getThing().getChannels();
974 for (Channel channel : existingChannels) {
975 String id = channel.getUID().getId();
976 if (dynChannels.containsKey(id)) {
977 dynChannels.remove(id);
981 if (!dynChannels.isEmpty()) {
982 logger.debug("{}: Updating channel definitions, {} channels", thingName, dynChannels.size());
983 ThingBuilder thingBuilder = editThing();
984 for (Map.Entry<String, Channel> channel : dynChannels.entrySet()) {
985 Channel c = channel.getValue();
986 logger.debug("{}: Adding channel {}", thingName, c.getUID().getId());
987 thingBuilder.withChannel(c);
989 updateThing(thingBuilder.build());
990 logger.debug("{}: Channel definitions updated", thingName);
992 } catch (IllegalArgumentException e) {
993 logger.debug("{}: Unable to update channel definitions", thingName, e);
997 public boolean areChannelsCreated() {
998 return channelsCreated;
1002 * Update thing properties with dynamic values
1004 * @param profile The device profile
1005 * @param status the /status result
1007 protected void updateProperties(ShellyDeviceProfile profile, ShellySettingsStatus status) {
1008 Map<String, Object> properties = fillDeviceProperties(profile);
1009 String serviceName = getString(getThing().getProperties().get(PROPERTY_SERVICE_NAME));
1010 String hostname = getString(profile.settings.device.hostname).toLowerCase();
1011 if (serviceName.isEmpty()) {
1012 properties.put(PROPERTY_SERVICE_NAME, hostname);
1013 logger.trace("{}: Updated serrviceName to {}", thingName, hostname);
1015 String deviceName = getString(profile.settings.name);
1016 if (!deviceName.isEmpty()) {
1017 properties.put(PROPERTY_DEV_NAME, deviceName);
1020 // add status properties
1021 if (status.wifiSta != null) {
1022 properties.put(PROPERTY_WIFI_NETW, getString(status.wifiSta.ssid));
1024 if (status.update != null) {
1025 properties.put(PROPERTY_UPDATE_STATUS, getString(status.update.status));
1026 properties.put(PROPERTY_UPDATE_AVAILABLE, getBool(status.update.hasUpdate) ? "yes" : "no");
1027 properties.put(PROPERTY_UPDATE_CURR_VERS, getString(status.update.oldVersion));
1028 properties.put(PROPERTY_UPDATE_NEW_VERS, getString(status.update.newVersion));
1030 properties.put(PROPERTY_COIOTAUTO, String.valueOf(autoCoIoT));
1031 properties.put(PROPERTY_COIOTREFRESH, String.valueOf(autoCoIoT));
1033 Map<String, String> thingProperties = new TreeMap<>();
1034 for (Map.Entry<String, Object> property : properties.entrySet()) {
1035 thingProperties.put(property.getKey(), (String) property.getValue());
1037 flushProperties(thingProperties);
1041 * Add one property to the Thing Properties
1043 * @param key Name of the property
1044 * @param value Value of the property
1046 public void updateProperties(String key, String value) {
1047 Map<String, String> thingProperties = editProperties();
1048 if (thingProperties.containsKey(key)) {
1049 thingProperties.replace(key, value);
1051 thingProperties.put(key, value);
1053 updateProperties(thingProperties);
1054 logger.trace("{}: Properties updated", thingName);
1057 public void flushProperties(Map<String, String> propertyUpdates) {
1058 Map<String, String> thingProperties = editProperties();
1059 for (Map.Entry<String, String> property : propertyUpdates.entrySet()) {
1060 if (thingProperties.containsKey(property.getKey())) {
1061 thingProperties.replace(property.getKey(), property.getValue());
1063 thingProperties.put(property.getKey(), property.getValue());
1066 updateProperties(thingProperties);
1070 * Get one property from the Thing Properties
1072 * @param key property name
1073 * @return property value or "" if property is not set
1075 public String getProperty(String key) {
1076 Map<String, String> thingProperties = getThing().getProperties();
1077 return getString(thingProperties.get(key));
1081 * Fill Thing Properties with device attributes
1083 * @param profile Property Map to full
1084 * @return a full property map
1086 public static Map<String, Object> fillDeviceProperties(ShellyDeviceProfile profile) {
1087 Map<String, Object> properties = new TreeMap<>();
1088 properties.put(PROPERTY_VENDOR, VENDOR);
1089 if (profile.isInitialized()) {
1090 properties.put(PROPERTY_MODEL_ID, getString(profile.settings.device.type));
1091 properties.put(PROPERTY_MAC_ADDRESS, profile.mac);
1092 properties.put(PROPERTY_FIRMWARE_VERSION,
1093 profile.fwVersion + "/" + profile.fwDate + "(" + profile.fwId + ")");
1094 properties.put(PROPERTY_DEV_MODE, profile.mode);
1095 properties.put(PROPERTY_NUM_RELAYS, String.valueOf(profile.numRelays));
1096 properties.put(PROPERTY_NUM_ROLLERS, String.valueOf(profile.numRollers));
1097 properties.put(PROPERTY_NUM_METER, String.valueOf(profile.numMeters));
1098 properties.put(PROPERTY_UPDATE_PERIOD, String.valueOf(profile.updatePeriod));
1099 if (!profile.hwRev.isEmpty()) {
1100 properties.put(PROPERTY_HWREV, profile.hwRev);
1101 properties.put(PROPERTY_HWBATCH, profile.hwBatchId);
1108 * Return device profile.
1110 * @param ForceRefresh true=force refresh before returning, false=return without
1112 * @return ShellyDeviceProfile instance
1113 * @throws ShellyApiException
1115 public ShellyDeviceProfile getProfile(boolean forceRefresh) throws ShellyApiException {
1117 refreshSettings |= forceRefresh;
1118 if (refreshSettings) {
1119 profile = api.getDeviceProfile(thingType);
1120 if (!isThingOnline()) {
1121 logger.debug("{}:Device profile re-initialized (thingType={})", thingName, thingType);
1125 refreshSettings = false;
1130 public ShellyDeviceProfile getProfile() {
1134 protected ShellyHttpApi getShellyApi() {
1138 protected ShellyDeviceProfile getDeviceProfile() {
1142 public void triggerChannel(String group, String channel, String payload) {
1143 triggerChannel(mkChannelId(group, channel), payload);
1146 public void stop() {
1147 logger.debug("{}: Shutting down", thingName);
1148 ScheduledFuture<?> job = this.statusJob;
1152 logger.debug("{}: Shelly statusJob stopped", thingName);
1154 job = asyncButtonRelease;
1157 asyncButtonRelease = null;
1161 profile.initialized = false;
1165 * Shutdown thing, make sure background jobs are canceled
1168 public void dispose() {
1175 * Device specific command handlers are overriding this method to do additional stuff
1177 public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws ShellyApiException {
1182 * Device specific handlers are overriding this method to do additional stuff
1184 public boolean updateDeviceStatus(ShellySettingsStatus status) throws ShellyApiException {
1188 public ShellyDeviceStats getStats() {
1192 public Map<String, String> getStatsProp() {
1193 return stats.asProperties(getString(profile.settings.timezone));
1196 public void resetStats() {
1198 stats = new ShellyDeviceStats();