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.api1.Shelly1CoapJSonDTO.CoIotDescrBlk;
25 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrSen;
26 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensor;
27 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
28 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
29 import org.openhab.core.library.types.OnOffType;
30 import org.openhab.core.library.unit.ImperialUnits;
31 import org.openhab.core.library.unit.SIUnits;
32 import org.openhab.core.library.unit.Units;
33 import org.openhab.core.types.State;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * The {@link Shelly1CoIoTVersion1} implements the parsing for CoIoT version 1
40 * @author Markus Michels - Initial contribution
43 public class Shelly1CoIoTVersion1 extends Shelly1CoIoTProtocol implements Shelly1CoIoTInterface {
44 private final Logger logger = LoggerFactory.getLogger(Shelly1CoIoTVersion1.class);
46 public Shelly1CoIoTVersion1(String thingName, ShellyThingInterface thingHandler, Map<String, CoIotDescrBlk> blkMap,
47 Map<String, CoIotDescrSen> sensorMap) {
48 super(thingName, thingHandler, blkMap, sensorMap);
52 public int getVersion() {
53 return Shelly1CoapJSonDTO.COIOT_VERSION_1;
57 * Process CoIoT status update message. If a status update is received, but the device description has not been
58 * received yet a GET is send to query device description.
60 * @param sensorUpdates
62 * @param serial Serial for this request. If this the the same as last serial
63 * the update was already sent and processed so this one gets
71 public boolean handleStatusUpdate(List<CoIotSensor> sensorUpdates, CoIotDescrSen sen, int serial, CoIotSensor s,
72 Map<String, State> updates, ShellyColorUtils col) {
73 // first check the base implementation
74 if (super.handleStatusUpdate(sensorUpdates, sen, s, updates, col)) {
75 // process by the base class
79 // Process status information and convert into channel updates
80 Integer rIndex = Integer.parseInt(sen.links) + 1;
81 String rGroup = getProfile().numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL
82 : CHANNEL_GROUP_RELAY_CONTROL + rIndex;
83 switch (sen.type.toLowerCase()) {
84 case "t": // Temperature +
85 Double value = getDouble(s.value);
86 switch (sen.desc.toLowerCase()) {
87 case "temperature": // Sensor Temp
88 if (getString(getProfile().settings.temperatureUnits)
89 .equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT)) {
90 value = ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(getDouble(s.value))
93 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP,
94 toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
96 case "temperature f": // Device Temp -> ignore (we use C only)
98 case "temperature c": // Device Temp in C
100 updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
101 toQuantityType(value, DIGITS_NONE, SIUnits.CELSIUS));
103 case "external temperature f": // Shelly 1/1PM external temp sensors
104 // ignore F, we use C only
106 case "external temperature c": // Shelly 1/1PM external temp sensors
107 case "external_temperature":
108 int idx = getExtTempId(sen.id);
110 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TEMP + idx,
111 toQuantityType(value, DIGITS_TEMP, SIUnits.CELSIUS));
113 logger.debug("{}: Unable to get extSensorId {} from {}/{}", thingName, sen.id, sen.type,
118 logger.debug("{}: Unknown temperatur type: {}", thingName, sen.desc);
121 case "p": // Power/Watt
122 // 3EM uses 1-based meter IDs, other 0-based
123 String mGroup = profile.numMeters == 1 ? CHANNEL_GROUP_METER
124 : CHANNEL_GROUP_METER + (profile.isEMeter ? sen.links : rIndex);
125 updateChannel(updates, mGroup, CHANNEL_METER_CURRENTWATTS,
126 toQuantityType(s.value, DIGITS_WATT, Units.WATT));
127 updateChannel(updates, mGroup, CHANNEL_LAST_UPDATE, getTimestamp());
129 case "s" /* CatchAll */:
130 switch (sen.desc.toLowerCase()) {
133 thingHandler.postEvent(ALARM_TYPE_OVERTEMP, true);
136 case "energy counter 0 [w-min]":
137 updateChannel(updates, rGroup, CHANNEL_METER_LASTMIN1,
138 toQuantityType(s.value, DIGITS_WATT, Units.WATT));
140 case "energy counter 1 [w-min]":
141 case "energy counter 2 [w-min]":
144 case "energy counter total [w-h]": // 3EM reports W/h
145 case "energy counter total [w-min]":
146 Double total = profile.isEMeter ? s.value / 1000 : s.value / 60 / 1000;
147 updateChannel(updates, rGroup, CHANNEL_METER_TOTALKWH,
148 toQuantityType(total, DIGITS_KWH, Units.KILOWATT_HOUR));
151 updateChannel(updates, rGroup, CHANNEL_EMETER_VOLTAGE,
152 toQuantityType(getDouble(s.value), DIGITS_VOLT, Units.VOLT));
155 updateChannel(updates, rGroup, CHANNEL_EMETER_CURRENT,
156 toQuantityType(getDouble(s.value), DIGITS_AMPERE, Units.AMPERE));
159 updateChannel(updates, rGroup, CHANNEL_EMETER_PFACTOR, getDecimal(s.value));
162 // work around: Roller reports 101% instead max 100
163 double pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(s.value, SHELLY_MAX_ROLLER_POS));
164 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
165 toQuantityType(SHELLY_MAX_ROLLER_POS - pos, Units.PERCENT));
166 updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
167 toQuantityType(pos, Units.PERCENT));
169 case "input event": // Shelly Button 1
170 handleInputEvent(sen, getString(s.valueStr), -1, serial, updates);
172 case "input event counter": // Shelly Button 1/ix3
173 handleInputEvent(sen, "", getInteger((int) s.value), serial, updates);
176 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
177 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
179 case "tilt": // DW with FW1.6.5+ //+
180 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_TILT,
181 toQuantityType(s.value, DIGITS_NONE, Units.DEGREE_ANGLE));
183 case "vibration": // DW with FW1.6.5+
184 if (profile.isMotion) {
186 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION,
187 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
188 } else if (s.value == 1) {
190 thingHandler.triggerChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
191 EVENT_TYPE_VIBRATION);
194 case "temp": // Shelly Bulb
195 case "colortemperature": // Shelly Duo
196 updateChannel(updates,
197 profile.inColor ? CHANNEL_GROUP_COLOR_CONTROL : CHANNEL_GROUP_WHITE_CONTROL,
199 ShellyColorUtils.toPercent((int) s.value, profile.minTemp, profile.maxTemp));
201 case "sensor state": // Shelly Gas
202 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_SSTATE, getStringType(s.valueStr));
204 case "alarm state": // Shelly Gas
205 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
206 getStringType(s.valueStr));
208 case "self-test state":// Shelly Gas
209 updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_SELFTTEST,
210 getStringType(s.valueStr));
212 case "concentration":// Shelly Gas
213 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM,
214 toQuantityType(getDouble(s.value), DIGITS_NONE, Units.PARTS_PER_MILLION));
217 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(s.valueStr));
234 * Depending on the device type and firmware release there are significant bugs or incosistencies in the CoIoT
235 * Device Description returned by the discovery request. Shelly is even not following it's own speicifcation. All of
236 * that has been reported to Shelly and acknowledged. Firmware 1.6 brought significant improvements. However, the
237 * old mapping stays in to support older firmware releases.
239 * @param sen Sensor description received from device
240 * @return fixed Sensor description (sen)
243 public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
244 // Shelly1: reports null descr+type "Switch" -> map to S
245 // Shelly1PM: reports null descr+type "Overtemp" -> map to O
246 // Shelly1PM: reports null descr+type "W" -> add description
247 // Shelly1PM: reports temp senmsors without desc -> add description
248 // Shelly Dimmer: sensors are reported without descriptions -> map to S
249 // SHelly Sense: multiple issues: Description should not be lower case, invalid type for Motion and Battery
250 // Shelly Sense: Battery is reported with Desc "battery", but type "H" instead of "B"
251 // Shelly Sense: Motion is reported with Desc "battery", but type "H" instead of "B"
252 // Shelly Bulb: Colors are coded with Type="Red" etc. rather than Type="S" and color as Descr
253 // Shelly RGBW2 is reporting Brightness, Power, VSwitch for each channel, but all with L=0
255 throw new IllegalArgumentException("sen should not be null!");
257 if (sen.desc == null) {
260 String desc = sen.desc.toLowerCase();
262 // RGBW2 reports Power_0, Power_1, Power_2, Power_3; same for VSwitch and Brightness, all of them linkted to L:0
263 // we break it up to Power with L:0, Power with L:1...
264 if (desc.contains("_") && (desc.contains("power") || desc.contains("vswitch") || desc.contains("brightness"))) {
265 String newDesc = substringBefore(sen.desc, "_");
266 String newLink = substringAfter(sen.desc, "_");
269 if (!blkMap.containsKey(sen.links)) {
270 // auto-insert a matching blk entry
271 CoIotDescrBlk blk = new CoIotDescrBlk();
272 CoIotDescrBlk blk0 = blkMap.get("0"); // blk 0 is always there
275 blk.desc = blk0.desc + "_" + blk.id;
276 blkMap.put(blk.id, blk);
281 switch (sen.type.toLowerCase()) {
282 case "w": // old devices/firmware releases use "W", new ones "P"
288 sen.desc = "Temperature C";
292 sen.desc = "Temperature F";
296 sen.desc = "Overtemp";
306 switch (sen.desc.toLowerCase()) {
307 case "motion": // fix acc to spec it's T=M
311 case "battery": // fix: type is B not H
313 sen.desc = "Battery";
317 sen.desc = "Overtemp";
325 case "e cnt 0 [w-min]": // 4 Pro
326 case "e cnt 1 [w-min]":
327 case "e cnt 2 [w-min]":
328 case "e cnt total [w-min]": // 4 Pro
329 sen.desc = sen.desc.toLowerCase().replace("e cnt", "energy counter");
334 if (sen.desc.isEmpty()) {
335 switch (sen.type.toLowerCase()) {
340 sen.desc = "Temperature";
352 sen.desc = "Brightness";
359 case "temp": // Bulb: Color temperature
364 // it seems that Shelly tends to break their own spec: T is the description and D is no longer
365 // included -> map D to sen.T and set CatchAll for T
369 // Default: set no description
370 // (there are no T values defined in the CoIoT spec)