2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.api1;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19 import java.util.List;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
25 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
26 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrBlk;
27 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrSen;
28 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensor;
29 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
30 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.library.types.OpenClosedType;
33 import org.openhab.core.library.types.StringType;
34 import org.openhab.core.library.unit.Units;
35 import org.openhab.core.types.State;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import com.google.gson.Gson;
40 import com.google.gson.GsonBuilder;
41 import com.google.gson.JsonSyntaxException;
44 * The {@link Shelly1CoIoTProtocol} implements common functions for the CoIoT implementations
46 * @author Markus Michels - Initial contribution
49 public class Shelly1CoIoTProtocol {
50 private final Logger logger = LoggerFactory.getLogger(Shelly1CoIoTProtocol.class);
51 protected final String thingName;
52 protected final ShellyThingInterface thingHandler;
53 protected final ShellyDeviceProfile profile;
54 protected final ShellyApiInterface api;
55 protected final Map<String, CoIotDescrBlk> blkMap;
56 protected final Map<String, CoIotDescrSen> sensorMap;
57 private final Gson gson = new GsonBuilder().create();
59 // Due to the fact that the device reports only the current/last status, but no real events, we need to distinguish
60 // between a real update or just a repeated status on periodic updates
61 protected int[] lastEventCount = { -1, -1, -1, -1, -1, -1, -1, -1 }; // 4Pro has 4 relays, so 8 should be fine
62 protected String[] inputEvent = { "", "", "", "", "", "", "", "" };
63 protected String lastWakeup = "";
65 public Shelly1CoIoTProtocol(String thingName, ShellyThingInterface thingHandler, Map<String, CoIotDescrBlk> blkMap,
66 Map<String, CoIotDescrSen> sensorMap) {
67 this.thingName = thingName;
68 this.thingHandler = thingHandler;
70 this.sensorMap = sensorMap;
71 this.profile = thingHandler.getProfile();
72 this.api = thingHandler.getApi();
75 protected boolean handleStatusUpdate(List<CoIotSensor> sensorUpdates, CoIotDescrSen sen, CoIotSensor s,
76 Map<String, State> updates, ShellyColorUtils col) {
77 // Process status information and convert into channel updates
78 int rIndex = getIdFromBlk(sen);
79 String rGroup = getProfile().numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL
80 : CHANNEL_GROUP_RELAY_CONTROL + rIndex;
82 switch (sen.type.toLowerCase()) {
83 case "b": // BatteryLevel +
84 updateChannel(updates, CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
85 toQuantityType(s.value, 0, Units.PERCENT));
87 case "h" /* Humidity */:
88 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
89 toQuantityType(s.value, DIGITS_PERCENT, Units.PERCENT));
91 case "m" /* Motion */:
92 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION, OnOffType.from(s.value == 1));
94 case "l": // Luminosity +
95 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
96 toQuantityType(s.value, DIGITS_LUX, Units.LUX));
99 switch (sen.desc.toLowerCase()) {
100 case "state": // Relay status +
102 updatePower(profile, updates, rIndex, sen, s, sensorUpdates);
105 handleInput(sen, s, rGroup, updates);
108 // already handled by state/output
110 case "overtemp": // ++
112 thingHandler.postEvent(ALARM_TYPE_OVERTEMP, true);
116 // work around: Roller reports 101% instead max 100
117 double pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(s.value, SHELLY_MAX_ROLLER_POS));
118 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
119 toQuantityType(SHELLY_MAX_ROLLER_POS - pos, Units.PERCENT));
120 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
121 toQuantityType(pos, Units.PERCENT));
124 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
125 OnOffType.from(s.value == 1));
127 case "vibration": // DW with FW1.6.5+
128 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION,
129 OnOffType.from(s.value == 1));
131 thingHandler.triggerChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
132 EVENT_TYPE_VIBRATION);
135 case "luminositylevel": // +
136 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM, getStringType(s.valueStr));
138 case "charger": // Sense
139 updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
140 OnOffType.from(s.value == 1));
144 col.setRed((int) s.value);
145 updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_RED,
146 ShellyColorUtils.toPercent((int) s.value));
149 col.setGreen((int) s.value);
150 updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GREEN,
151 ShellyColorUtils.toPercent((int) s.value));
154 col.setBlue((int) s.value);
155 updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_BLUE,
156 ShellyColorUtils.toPercent((int) s.value));
159 col.setWhite((int) s.value);
160 updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_WHITE,
161 ShellyColorUtils.toPercent((int) s.value));
164 col.setGain((int) s.value);
165 updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GAIN,
166 ShellyColorUtils.toPercent((int) s.value, SHELLY_MIN_GAIN, SHELLY_MAX_GAIN));
169 String sensorError = s.valueStr != null ? getString(s.valueStr) : "" + s.value;
170 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(sensorError));
186 public static boolean updateChannel(Map<String, State> updates, String group, String channel, State value) {
187 updates.put(mkChannelId(group, channel), value);
191 protected void handleInput(CoIotDescrSen sen, CoIotSensor s, String rGroup, Map<String, State> updates) {
192 int idx = getSensorNumber(sen.desc, sen.id) - 1;
193 String iGroup = profile.getInputGroup(idx);
194 String iChannel = CHANNEL_INPUT + profile.getInputSuffix(idx);
195 updateChannel(updates, iGroup, iChannel, OnOffType.from(s.value != 0));
198 protected void handleInputEvent(CoIotDescrSen sen, String type, int count, int serial, Map<String, State> updates) {
199 int idx = getSensorNumber(sen.desc, sen.id) - 1;
200 String group = profile.getInputGroup(idx);
203 updateChannel(updates, group, CHANNEL_STATUS_EVENTTYPE + profile.getInputSuffix(idx), new StringType(type));
204 inputEvent[idx] = type;
207 updateChannel(updates, group, CHANNEL_STATUS_EVENTCOUNT + profile.getInputSuffix(idx), getDecimal(count));
209 "{}: Check button[{}] for event trigger (inButtonMode={}, isButton={}, hasBattery={}, serial={}, count={}, lastEventCount[{}]={}",
210 thingName, idx, profile.inButtonMode(idx), profile.isButton, profile.hasBattery, serial, count, idx,
211 lastEventCount[idx]);
212 if (profile.inButtonMode(idx) && ((profile.hasBattery && count == 1) || lastEventCount[idx] == -1
213 || count != lastEventCount[idx])) {
214 if (!profile.isButton || (profile.isButton && (serial != 0x200))) { // skip duplicate on wake-up
215 logger.debug("{}: Trigger event {}", thingName, inputEvent[idx]);
216 thingHandler.triggerButton(group, idx, inputEvent[idx]);
219 lastEventCount[idx] = count;
225 * Handles the combined updated of the brightness channel:
226 * brightness$Switch is the OnOffType (power state)
227 * brightness&Value is the brightness value
229 * @param profile Device profile, required to select the channel group and name
230 * @param updates List of updates. updatePower will add brightness$Switch and brightness&Value if changed
231 * @param id Sensor id from the update
232 * @param sen Sensor description from the update
233 * @param s New sensor value
234 * @param allUpdates List of updates. This is required, because we need to update both values at the same time
236 protected void updatePower(ShellyDeviceProfile profile, Map<String, State> updates, int id, CoIotDescrSen sen,
237 CoIotSensor s, List<CoIotSensor> allUpdates) {
239 String channel = CHANNEL_BRIGHTNESS;
240 String checkL = ""; // RGBW-white uses 4 different Power, Brightness, VSwitch values
241 if (profile.isLight || profile.isDimmer) {
242 if (profile.isBulb || profile.inColor) {
243 group = CHANNEL_GROUP_LIGHT_CONTROL;
244 channel = CHANNEL_LIGHT_POWER;
245 } else if (profile.isDuo) {
246 group = CHANNEL_GROUP_WHITE_CONTROL;
247 } else if (profile.isDimmer) {
248 group = CHANNEL_GROUP_RELAY_CONTROL;
249 } else if (profile.isRGBW2) {
250 checkL = String.valueOf(id); // String.valueOf(id - 1); // id is 1-based, L is 0-based
251 group = CHANNEL_GROUP_LIGHT_CHANNEL + id;
252 logger.trace("{}: updatePower() for L={}", thingName, checkL);
255 // We need to update brightness and on/off state at the same time to avoid "flipping brightness slider" in
257 double brightness = -1.0;
259 for (CoIotSensor update : allUpdates) {
260 CoIotDescrSen d = fixDescription(sensorMap.get(update.id), blkMap);
261 if (!checkL.isEmpty() && !d.links.equals(checkL)) {
262 // continue until we find the correct one
265 if ("brightness".equalsIgnoreCase(d.desc)) {
266 brightness = update.value;
267 } else if ("output".equalsIgnoreCase(d.desc) || "state".equalsIgnoreCase(d.desc)) {
268 power = update.value;
272 updateChannel(updates, group, channel + "$Switch", OnOffType.from(power == 1));
274 if (brightness != -1) {
275 updateChannel(updates, group, channel + "$Value",
276 toQuantityType(power == 1 ? brightness : 0, DIGITS_NONE, Units.PERCENT));
278 } else if (profile.hasRelays) {
279 group = profile.numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + id;
280 updateChannel(updates, group, CHANNEL_OUTPUT, OnOffType.from(s.value == 1));
281 } else if (profile.isSensor) {
283 if (profile.isDW) { // Door Window has item type Contact
284 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
285 s.value != 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
287 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE, OnOffType.from(s.value == 1));
293 * Find index of Input id, which is required to map to channel name
295 * @param sensorDesc D field from sensor update
296 * @param sensorId The id from the sensor update
297 * @return Index of found entry (+1 will be the suffix for the channel name) or null if sensorId is not found
299 protected int getSensorNumber(String sensorDesc, String sensorId) {
301 for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
302 CoIotDescrSen sen = se.getValue();
303 if (sen.desc.equalsIgnoreCase(sensorDesc)) {
304 idx++; // iterate from input1..2..n
306 if (sen.id.equalsIgnoreCase(sensorId) && blkMap.containsKey(sen.links)) {
307 int id = getIdFromBlk(sen);
312 if (sen.id.equalsIgnoreCase(sensorId)) {
316 logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
320 protected int getIdFromBlk(CoIotDescrSen sen) {
322 CoIotDescrBlk blk = blkMap.get(sen.links);
324 String desc = blk.desc.toLowerCase();
325 if (desc.startsWith(SHELLY_CLASS_RELAY) || desc.startsWith(SHELLY_CLASS_ROLLER)
326 || desc.startsWith(SHELLY_CLASS_LIGHT) || desc.startsWith(SHELLY_CLASS_EMETER)) {
327 if (desc.contains("_")) { // CoAP v2
328 idx = Integer.parseInt(substringAfter(desc, "_"));
330 if (desc.substring(0, 5).equalsIgnoreCase(SHELLY_CLASS_RELAY)) {
331 idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_RELAY));
333 if (desc.substring(0, 6).equalsIgnoreCase(SHELLY_CLASS_ROLLER)) {
334 idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_ROLLER));
336 if (desc.substring(0, SHELLY_CLASS_EMETER.length()).equalsIgnoreCase(SHELLY_CLASS_EMETER)) {
337 idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_EMETER));
340 idx = idx + 1; // make it 1-based (sen.L is 0-based)
348 * Get matching sensorId for updates on "External Temperature" - there might be more than 1 sensor.
350 * @param sensorId sensorId to map into a channel index
351 * @return Index of the corresponding channel (e.g. 0 build temperature1, 1->temperagture2...)
353 protected int getExtTempId(String sensorId) {
355 for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
356 CoIotDescrSen sen = se.getValue();
357 if ("external_temperature".equalsIgnoreCase(sen.desc) || "external temperature c".equalsIgnoreCase(sen.desc)
358 || ("extTemp".equalsIgnoreCase(sen.desc) && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) {
359 idx++; // iterate from temperature1..2..n
361 if (sen.id.equalsIgnoreCase(sensorId)) {
365 logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
369 protected ShellyDeviceProfile getProfile() {
373 public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
374 return sen != null ? sen : new CoIotDescrSen();
377 public void completeMissingSensorDefinition(Map<String, CoIotDescrSen> sensorMap) {
380 protected void addSensor(Map<String, CoIotDescrSen> sensorMap, String key, String json) {
382 if (!sensorMap.containsKey(key)) {
383 CoIotDescrSen sen = gson.fromJson(json, CoIotDescrSen.class);
385 sensorMap.put(key, sen);
388 } catch (JsonSyntaxException e) {
389 // should never happen
390 logger.trace("Unable to parse sensor definition: {}", json, e);
394 public String getLastWakeup() {