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.somfytahoma.internal.handler;
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
17 import java.math.BigDecimal;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.Objects;
23 import javax.measure.Unit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaDevice;
28 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaState;
29 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaStatus;
30 import org.openhab.core.library.CoreItemFactory;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.library.types.OpenClosedType;
34 import org.openhab.core.library.types.PercentType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.library.types.StringType;
37 import org.openhab.core.library.unit.ImperialUnits;
38 import org.openhab.core.library.unit.SIUnits;
39 import org.openhab.core.library.unit.Units;
40 import org.openhab.core.thing.Bridge;
41 import org.openhab.core.thing.Channel;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.openhab.core.thing.ThingStatusInfo;
47 import org.openhab.core.thing.binding.BaseThingHandler;
48 import org.openhab.core.thing.binding.builder.ChannelBuilder;
49 import org.openhab.core.thing.binding.builder.ThingBuilder;
50 import org.openhab.core.types.Command;
51 import org.openhab.core.types.RefreshType;
52 import org.openhab.core.types.State;
53 import org.openhab.core.types.UnDefType;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * The {@link SomfyTahomaBaseThingHandler} is base thing handler for all things.
60 * @author Ondrej Pecta - Initial contribution
61 * @author Laurent Garnier - Setting of channels at init + UoM for channels
64 public abstract class SomfyTahomaBaseThingHandler extends BaseThingHandler {
66 private final Logger logger = LoggerFactory.getLogger(getClass());
67 private HashMap<String, Integer> typeTable = new HashMap<>();
68 protected HashMap<String, String> stateNames = new HashMap<>();
70 protected String url = "";
72 private Map<String, Unit<?>> units = new HashMap<>();
74 public SomfyTahomaBaseThingHandler(Thing thing) {
76 // Define default units
77 units.put("Number:Temperature", SIUnits.CELSIUS);
78 units.put("Number:Energy", Units.WATT_HOUR);
79 units.put("Number:Illuminance", Units.LUX);
80 units.put("Number:Dimensionless", Units.PERCENT);
83 public HashMap<String, String> getStateNames() {
88 public void initialize() {
89 Bridge bridge = getBridge();
90 initializeThing(bridge != null ? bridge.getStatus() : null);
94 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
95 initializeThing(bridgeStatusInfo.getStatus());
98 public void initializeThing(@Nullable ThingStatus bridgeStatus) {
99 SomfyTahomaBridgeHandler bridgeHandler = getBridgeHandler();
100 if (bridgeHandler != null && bridgeStatus != null) {
102 if (getThing().getProperties().containsKey(RSSI_LEVEL_STATE)) {
105 if (bridgeStatus == ThingStatus.ONLINE) {
106 SomfyTahomaDevice device = bridgeHandler.getCachedDevice(url);
107 if (device != null) {
108 updateUnits(device.getAttributes());
109 List<SomfyTahomaState> states = device.getStates();
110 updateThingStatus(states);
111 updateThingChannels(states);
113 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, UNAVAILABLE);
116 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
119 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
123 private void createRSSIChannel() {
124 if (thing.getChannel(RSSI) == null) {
125 logger.debug("{} Creating a rssi channel", url);
126 createChannel(RSSI, "Number", "RSSI Level");
130 private void createChannel(String name, String type, String label) {
131 ThingBuilder thingBuilder = editThing();
132 Channel channel = ChannelBuilder.create(new ChannelUID(thing.getUID(), name), type).withLabel(label).build();
133 thingBuilder.withChannel(channel);
134 updateThing(thingBuilder.build());
138 public void handleCommand(ChannelUID channelUID, Command command) {
139 logger.debug("{} Received command {} for channel {}", url, command, channelUID);
140 if (command instanceof RefreshType) {
141 refresh(channelUID.getId());
145 public Logger getLogger() {
149 protected boolean isAlwaysOnline() {
153 protected @Nullable SomfyTahomaBridgeHandler getBridgeHandler() {
154 Bridge localBridge = this.getBridge();
155 return localBridge != null ? (SomfyTahomaBridgeHandler) localBridge.getHandler() : null;
158 private String getURL() {
159 return getThing().getConfiguration().get("url") != null ? getThing().getConfiguration().get("url").toString()
163 private void setAvailable() {
164 if (ThingStatus.ONLINE != thing.getStatus()) {
165 updateStatus(ThingStatus.ONLINE);
169 private void setUnavailable() {
170 if (ThingStatus.OFFLINE != thing.getStatus() && !isAlwaysOnline()) {
171 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, UNAVAILABLE);
175 protected void sendCommand(String cmd) {
176 sendCommand(cmd, "[]");
179 protected void sendCommand(String cmd, String param) {
180 SomfyTahomaBridgeHandler handler = getBridgeHandler();
181 if (handler != null) {
182 handler.sendCommand(url, cmd, param, EXEC_URL + "apply");
186 protected void refresh(String channel) {
187 SomfyTahomaBridgeHandler handler = getBridgeHandler();
188 String stateName = stateNames.get(channel);
189 if (handler != null && stateName != null) {
190 handler.refresh(url, stateName);
194 protected void executeActionGroup() {
195 SomfyTahomaBridgeHandler handler = getBridgeHandler();
196 if (handler != null) {
197 handler.executeActionGroup(url);
201 protected @Nullable String getCurrentExecutions() {
202 SomfyTahomaBridgeHandler handler = getBridgeHandler();
203 if (handler != null) {
204 return handler.getCurrentExecutions(url);
209 protected void cancelExecution(String executionId) {
210 SomfyTahomaBridgeHandler handler = getBridgeHandler();
211 if (handler != null) {
212 handler.cancelExecution(executionId);
216 protected SomfyTahomaStatus getTahomaStatus(String id) {
217 SomfyTahomaBridgeHandler handler = getBridgeHandler();
218 if (handler != null) {
219 return handler.getTahomaStatus(id);
221 return new SomfyTahomaStatus();
224 private void cacheStateType(SomfyTahomaState state) {
225 if (state.getType() > 0 && !typeTable.containsKey(state.getName())) {
226 typeTable.put(state.getName(), state.getType());
230 protected void cacheStateType(String stateName, int type) {
231 if (type > 0 && !typeTable.containsKey(stateName)) {
232 typeTable.put(stateName, type);
236 protected Unit<?> getTemperatureUnit() {
237 return Objects.requireNonNull(units.get("Number:Temperature"));
240 private void updateUnits(List<SomfyTahomaState> attributes) {
241 for (SomfyTahomaState attr : attributes) {
242 if ("core:MeasuredValueType".equals(attr.getName()) && attr.getType() == TYPE_STRING) {
243 switch ((String) attr.getValue()) {
244 case "core:TemperatureInCelcius":
245 case "core:TemperatureInCelsius":
246 units.put("Number:Temperature", SIUnits.CELSIUS);
248 case "core:TemperatureInKelvin":
249 units.put("Number:Temperature", Units.KELVIN);
251 case "core:TemperatureInFahrenheit":
252 units.put("Number:Temperature", ImperialUnits.FAHRENHEIT);
254 case "core:RelativeValueInPercentage":
255 units.put("Number:Dimensionless", Units.PERCENT);
257 case "core:LuminanceInLux":
258 units.put("Number:Illuminance", Units.LUX);
260 case "core:ElectricalEnergyInWh":
261 units.put("Number:Energy", Units.WATT_HOUR);
263 case "core:ElectricalEnergyInKWh":
264 units.put("Number:Energy", Units.KILOWATT_HOUR);
266 case "core:ElectricalEnergyInMWh":
267 units.put("Number:Energy", Units.MEGAWATT_HOUR);
270 logger.warn("Unhandled value \"{}\" for attribute \"core:MeasuredValueType\"", attr.getValue());
278 protected @Nullable State parseTahomaState(@Nullable SomfyTahomaState state) {
279 return parseTahomaState(null, state);
282 protected @Nullable State parseTahomaState(@Nullable String acceptedItemType, @Nullable SomfyTahomaState state) {
284 return UnDefType.NULL;
287 int type = state.getType();
290 if (typeTable.containsKey(state.getName())) {
291 type = typeTable.get(state.getName());
293 cacheStateType(state);
297 logger.debug("{} Cannot recognize the state type for: {}!", url, state.getValue());
301 logger.trace("Value to parse: {}, type: {}", state.getValue(), type);
304 Double valPct = Double.parseDouble(state.getValue().toString());
305 if (acceptedItemType != null && acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
306 Unit<?> unit = units.get(acceptedItemType);
308 return new QuantityType<>(normalizePercent(valPct), unit);
310 logger.warn("Do not return a quantity for {} because the unit is unknown",
314 return new PercentType(normalizePercent(valPct));
316 Double valDec = Double.parseDouble(state.getValue().toString());
317 if (acceptedItemType != null && acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
318 Unit<?> unit = units.get(acceptedItemType);
320 return new QuantityType<>(valDec, unit);
322 logger.warn("Do not return a quantity for {} because the unit is unknown",
326 return new DecimalType(valDec);
329 String value = state.getValue().toString();
330 if ("String".equals(acceptedItemType)) {
331 return new StringType(value);
333 return parseStringState(value);
338 } catch (IllegalArgumentException ex) {
339 logger.debug("{} Error while parsing Tahoma state! Value: {} type: {}", url, state.getValue(), type, ex);
344 private int normalizePercent(Double valPct) {
345 int value = valPct.intValue();
348 } else if (value > 100) {
354 private State parseStringState(String value) {
355 if (value.endsWith("%")) {
356 // convert "100%" to 100 decimal
357 String val = value.replace("%", "");
358 logger.trace("converting: {} to value: {}", value, val);
359 Double valDec = Double.parseDouble(val);
360 return new DecimalType(valDec);
362 switch (value.toLowerCase()) {
370 return OnOffType.OFF;
372 case "nopersoninside":
375 return OpenClosedType.CLOSED;
381 return OpenClosedType.OPEN;
383 return UnDefType.UNDEF;
385 logger.debug("{} Unknown thing state returned: {}", url, value);
386 return UnDefType.UNDEF;
390 public void updateThingStatus(List<SomfyTahomaState> states) {
391 SomfyTahomaState state = getStatusState(states);
392 updateThingStatus(state);
395 private @Nullable SomfyTahomaState getStatusState(List<SomfyTahomaState> states) {
396 return getState(states, STATUS_STATE, TYPE_STRING);
399 private void updateThingStatus(@Nullable SomfyTahomaState state) {
401 // Most probably we are dealing with RTS device which does not return states
402 // so we have to setup ONLINE status manually
406 if (STATUS_STATE.equals(state.getName()) && state.getType() == TYPE_STRING) {
407 if (UNAVAILABLE.equals(state.getValue())) {
415 public void updateThingChannels(List<SomfyTahomaState> states) {
416 Map<String, String> properties = new HashMap<>();
417 for (SomfyTahomaState state : states) {
418 logger.trace("{} processing state: {} with value: {}", url, state.getName(), state.getValue());
419 properties.put(state.getName(), state.getValue().toString());
420 if (RSSI_LEVEL_STATE.equals(state.getName())) {
421 // RSSI channel is a dynamic one
422 updateRSSIChannel(state);
424 updateThingChannels(state);
427 updateProperties(properties);
430 private void updateRSSIChannel(SomfyTahomaState state) {
432 Channel ch = thing.getChannel(RSSI);
434 logger.debug("{} updating RSSI channel with value: {}", url, state.getValue());
435 State newState = parseTahomaState(ch.getAcceptedItemType(), state);
436 if (newState != null) {
437 updateState(ch.getUID(), newState);
442 public void updateThingChannels(SomfyTahomaState state) {
443 stateNames.forEach((k, v) -> {
444 if (v.equals(state.getName())) {
445 Channel ch = thing.getChannel(k);
447 logger.debug("{} updating channel: {} with value: {}", url, k, state.getValue());
448 State newState = parseTahomaState(ch.getAcceptedItemType(), state);
449 if (newState != null) {
450 updateState(ch.getUID(), newState);
457 public int toInteger(Command command) {
458 return (command instanceof DecimalType) ? ((DecimalType) command).intValue() : 0;
461 public @Nullable BigDecimal toTemperature(Command command) {
462 BigDecimal temperature = null;
463 if (command instanceof QuantityType<?>) {
464 QuantityType<?> quantity = (QuantityType<?>) command;
465 QuantityType<?> convertedQuantity = quantity.toUnit(getTemperatureUnit());
466 if (convertedQuantity != null) {
467 quantity = convertedQuantity;
469 temperature = quantity.toBigDecimal();
470 } else if (command instanceof DecimalType) {
471 temperature = ((DecimalType) command).toBigDecimal();
476 public static @Nullable SomfyTahomaState getState(List<SomfyTahomaState> states, String stateName,
477 @Nullable Integer stateType) {
478 for (SomfyTahomaState state : states) {
479 if (stateName.equals(state.getName()) && (stateType == null || stateType == state.getType())) {