]> git.basschouten.com Git - openhab-addons.git/blob
003df0d7ab468802821911078def4d4d6746733b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.somfytahoma.internal.handler;
14
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Objects;
22
23 import javax.measure.Unit;
24
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;
56
57 /**
58  * The {@link SomfyTahomaBaseThingHandler} is base thing handler for all things.
59  *
60  * @author Ondrej Pecta - Initial contribution
61  * @author Laurent Garnier - Setting of channels at init + UoM for channels
62  */
63 @NonNullByDefault
64 public abstract class SomfyTahomaBaseThingHandler extends BaseThingHandler {
65
66     private final Logger logger = LoggerFactory.getLogger(getClass());
67     private HashMap<String, Integer> typeTable = new HashMap<>();
68     protected HashMap<String, String> stateNames = new HashMap<>();
69
70     protected String url = "";
71
72     private Map<String, Unit<?>> units = new HashMap<>();
73
74     public SomfyTahomaBaseThingHandler(Thing thing) {
75         super(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);
81     }
82
83     public HashMap<String, String> getStateNames() {
84         return stateNames;
85     }
86
87     @Override
88     public void initialize() {
89         Bridge bridge = getBridge();
90         initializeThing(bridge != null ? bridge.getStatus() : null);
91     }
92
93     @Override
94     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
95         initializeThing(bridgeStatusInfo.getStatus());
96     }
97
98     public void initializeThing(@Nullable ThingStatus bridgeStatus) {
99         SomfyTahomaBridgeHandler bridgeHandler = getBridgeHandler();
100         if (bridgeHandler != null && bridgeStatus != null) {
101             url = getURL();
102             if (getThing().getProperties().containsKey(RSSI_LEVEL_STATE)) {
103                 createRSSIChannel();
104             }
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);
112                 } else {
113                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, UNAVAILABLE);
114                 }
115             } else {
116                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
117             }
118         } else {
119             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
120         }
121     }
122
123     private void createRSSIChannel() {
124         if (thing.getChannel(RSSI) == null) {
125             logger.debug("{} Creating a rssi channel", url);
126             createChannel(RSSI, "Number", "RSSI Level");
127         }
128     }
129
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());
135     }
136
137     @Override
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());
142         }
143     }
144
145     public Logger getLogger() {
146         return logger;
147     }
148
149     protected @Nullable SomfyTahomaBridgeHandler getBridgeHandler() {
150         Bridge localBridge = this.getBridge();
151         return localBridge != null ? (SomfyTahomaBridgeHandler) localBridge.getHandler() : null;
152     }
153
154     private String getURL() {
155         return getThing().getConfiguration().get("url") != null ? getThing().getConfiguration().get("url").toString()
156                 : "";
157     }
158
159     private void setAvailable() {
160         if (ThingStatus.ONLINE != thing.getStatus()) {
161             updateStatus(ThingStatus.ONLINE);
162         }
163     }
164
165     private void setUnavailable() {
166         if (ThingStatus.OFFLINE != thing.getStatus()) {
167             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, UNAVAILABLE);
168         }
169     }
170
171     protected void sendCommand(String cmd) {
172         sendCommand(cmd, "[]");
173     }
174
175     protected void sendCommand(String cmd, String param) {
176         SomfyTahomaBridgeHandler handler = getBridgeHandler();
177         if (handler != null) {
178             handler.sendCommand(url, cmd, param, EXEC_URL + "apply");
179         }
180     }
181
182     protected void refresh(String channel) {
183         SomfyTahomaBridgeHandler handler = getBridgeHandler();
184         String stateName = stateNames.get(channel);
185         if (handler != null && stateName != null) {
186             handler.refresh(url, stateName);
187         }
188     }
189
190     protected void executeActionGroup() {
191         SomfyTahomaBridgeHandler handler = getBridgeHandler();
192         if (handler != null) {
193             handler.executeActionGroup(url);
194         }
195     }
196
197     protected @Nullable String getCurrentExecutions() {
198         SomfyTahomaBridgeHandler handler = getBridgeHandler();
199         if (handler != null) {
200             return handler.getCurrentExecutions(url);
201         }
202         return null;
203     }
204
205     protected void cancelExecution(String executionId) {
206         SomfyTahomaBridgeHandler handler = getBridgeHandler();
207         if (handler != null) {
208             handler.cancelExecution(executionId);
209         }
210     }
211
212     protected SomfyTahomaStatus getTahomaStatus(String id) {
213         SomfyTahomaBridgeHandler handler = getBridgeHandler();
214         if (handler != null) {
215             return handler.getTahomaStatus(id);
216         }
217         return new SomfyTahomaStatus();
218     }
219
220     private void cacheStateType(SomfyTahomaState state) {
221         if (state.getType() > 0 && !typeTable.containsKey(state.getName())) {
222             typeTable.put(state.getName(), state.getType());
223         }
224     }
225
226     protected void cacheStateType(String stateName, int type) {
227         if (type > 0 && !typeTable.containsKey(stateName)) {
228             typeTable.put(stateName, type);
229         }
230     }
231
232     protected Unit<?> getTemperatureUnit() {
233         return Objects.requireNonNull(units.get("Number:Temperature"));
234     }
235
236     private void updateUnits(List<SomfyTahomaState> attributes) {
237         for (SomfyTahomaState attr : attributes) {
238             if ("core:MeasuredValueType".equals(attr.getName()) && attr.getType() == TYPE_STRING) {
239                 switch ((String) attr.getValue()) {
240                     case "core:TemperatureInCelcius":
241                     case "core:TemperatureInCelsius":
242                         units.put("Number:Temperature", SIUnits.CELSIUS);
243                         break;
244                     case "core:TemperatureInKelvin":
245                         units.put("Number:Temperature", Units.KELVIN);
246                         break;
247                     case "core:TemperatureInFahrenheit":
248                         units.put("Number:Temperature", ImperialUnits.FAHRENHEIT);
249                         break;
250                     case "core:RelativeValueInPercentage":
251                         units.put("Number:Dimensionless", Units.PERCENT);
252                         break;
253                     case "core:LuminanceInLux":
254                         units.put("Number:Illuminance", Units.LUX);
255                         break;
256                     case "core:ElectricalEnergyInWh":
257                         units.put("Number:Energy", Units.WATT_HOUR);
258                         break;
259                     case "core:ElectricalEnergyInKWh":
260                         units.put("Number:Energy", Units.KILOWATT_HOUR);
261                         break;
262                     case "core:ElectricalEnergyInMWh":
263                         units.put("Number:Energy", Units.MEGAWATT_HOUR);
264                         break;
265                     default:
266                         logger.warn("Unhandled value \"{}\" for attribute \"core:MeasuredValueType\"", attr.getValue());
267                         break;
268                 }
269                 break;
270             }
271         }
272     }
273
274     protected @Nullable State parseTahomaState(@Nullable SomfyTahomaState state) {
275         return parseTahomaState(null, state);
276     }
277
278     protected @Nullable State parseTahomaState(@Nullable String acceptedItemType, @Nullable SomfyTahomaState state) {
279         if (state == null) {
280             return UnDefType.NULL;
281         }
282
283         int type = state.getType();
284
285         try {
286             if (typeTable.containsKey(state.getName())) {
287                 type = typeTable.get(state.getName());
288             } else {
289                 cacheStateType(state);
290             }
291
292             if (type == 0) {
293                 logger.debug("{} Cannot recognize the state type for: {}!", url, state.getValue());
294                 return null;
295             }
296
297             logger.trace("Value to parse: {}, type: {}", state.getValue(), type);
298             switch (type) {
299                 case TYPE_PERCENT:
300                     Double valPct = Double.parseDouble(state.getValue().toString());
301                     if (acceptedItemType != null && acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
302                         Unit<?> unit = units.get(acceptedItemType);
303                         if (unit != null) {
304                             return new QuantityType<>(normalizePercent(valPct), unit);
305                         } else {
306                             logger.warn("Do not return a quantity for {} because the unit is unknown",
307                                     acceptedItemType);
308                         }
309                     }
310                     return new PercentType(normalizePercent(valPct));
311                 case TYPE_DECIMAL:
312                     Double valDec = Double.parseDouble(state.getValue().toString());
313                     if (acceptedItemType != null && acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
314                         Unit<?> unit = units.get(acceptedItemType);
315                         if (unit != null) {
316                             return new QuantityType<>(valDec, unit);
317                         } else {
318                             logger.warn("Do not return a quantity for {} because the unit is unknown",
319                                     acceptedItemType);
320                         }
321                     }
322                     return new DecimalType(valDec);
323                 case TYPE_STRING:
324                 case TYPE_BOOLEAN:
325                     String value = state.getValue().toString();
326                     if ("String".equals(acceptedItemType)) {
327                         return new StringType(value);
328                     } else {
329                         return parseStringState(value);
330                     }
331                 default:
332                     return null;
333             }
334         } catch (IllegalArgumentException ex) {
335             logger.debug("{} Error while parsing Tahoma state! Value: {} type: {}", url, state.getValue(), type, ex);
336         }
337         return null;
338     }
339
340     private int normalizePercent(Double valPct) {
341         int value = valPct.intValue();
342         if (value < 0) {
343             value = 0;
344         } else if (value > 100) {
345             value = 100;
346         }
347         return value;
348     }
349
350     private State parseStringState(String value) {
351         if (value.endsWith("%")) {
352             // convert "100%" to 100 decimal
353             String val = value.replace("%", "");
354             logger.trace("converting: {} to value: {}", value, val);
355             Double valDec = Double.parseDouble(val);
356             return new DecimalType(valDec);
357         }
358         switch (value.toLowerCase()) {
359             case "on":
360             case "true":
361             case "active":
362                 return OnOffType.ON;
363             case "off":
364             case "false":
365             case "inactive":
366                 return OnOffType.OFF;
367             case "notdetected":
368             case "nopersoninside":
369             case "closed":
370             case "locked":
371                 return OpenClosedType.CLOSED;
372             case "detected":
373             case "personinside":
374             case "open":
375             case "opened":
376             case "unlocked":
377                 return OpenClosedType.OPEN;
378             case "unknown":
379                 return UnDefType.UNDEF;
380             default:
381                 logger.debug("{} Unknown thing state returned: {}", url, value);
382                 return UnDefType.UNDEF;
383         }
384     }
385
386     public void updateThingStatus(List<SomfyTahomaState> states) {
387         SomfyTahomaState state = getStatusState(states);
388         updateThingStatus(state);
389     }
390
391     private @Nullable SomfyTahomaState getStatusState(List<SomfyTahomaState> states) {
392         return getState(states, STATUS_STATE, TYPE_STRING);
393     }
394
395     private void updateThingStatus(@Nullable SomfyTahomaState state) {
396         if (state == null) {
397             // Most probably we are dealing with RTS device which does not return states
398             // so we have to setup ONLINE status manually
399             setAvailable();
400             return;
401         }
402         if (STATUS_STATE.equals(state.getName()) && state.getType() == TYPE_STRING) {
403             if (UNAVAILABLE.equals(state.getValue())) {
404                 setUnavailable();
405             } else {
406                 setAvailable();
407             }
408         }
409     }
410
411     public void updateThingChannels(List<SomfyTahomaState> states) {
412         Map<String, String> properties = new HashMap<>();
413         for (SomfyTahomaState state : states) {
414             logger.trace("{} processing state: {} with value: {}", url, state.getName(), state.getValue());
415             properties.put(state.getName(), state.getValue().toString());
416             if (RSSI_LEVEL_STATE.equals(state.getName())) {
417                 // RSSI channel is a dynamic one
418                 updateRSSIChannel(state);
419             } else {
420                 updateThingChannels(state);
421             }
422         }
423         updateProperties(properties);
424     }
425
426     private void updateRSSIChannel(SomfyTahomaState state) {
427         createRSSIChannel();
428         Channel ch = thing.getChannel(RSSI);
429         if (ch != null) {
430             logger.debug("{} updating RSSI channel with value: {}", url, state.getValue());
431             State newState = parseTahomaState(ch.getAcceptedItemType(), state);
432             if (newState != null) {
433                 updateState(ch.getUID(), newState);
434             }
435         }
436     }
437
438     public void updateThingChannels(SomfyTahomaState state) {
439         stateNames.forEach((k, v) -> {
440             if (v.equals(state.getName())) {
441                 Channel ch = thing.getChannel(k);
442                 if (ch != null) {
443                     logger.debug("{} updating channel: {} with value: {}", url, k, state.getValue());
444                     State newState = parseTahomaState(ch.getAcceptedItemType(), state);
445                     if (newState != null) {
446                         updateState(ch.getUID(), newState);
447                     }
448                 }
449             }
450         });
451     }
452
453     public int toInteger(Command command) {
454         return (command instanceof DecimalType) ? ((DecimalType) command).intValue() : 0;
455     }
456
457     public @Nullable BigDecimal toTemperature(Command command) {
458         BigDecimal temperature = null;
459         if (command instanceof QuantityType<?>) {
460             QuantityType<?> quantity = (QuantityType<?>) command;
461             QuantityType<?> convertedQuantity = quantity.toUnit(getTemperatureUnit());
462             if (convertedQuantity != null) {
463                 quantity = convertedQuantity;
464             }
465             temperature = quantity.toBigDecimal();
466         } else if (command instanceof DecimalType) {
467             temperature = ((DecimalType) command).toBigDecimal();
468         }
469         return temperature;
470     }
471
472     public static @Nullable SomfyTahomaState getState(List<SomfyTahomaState> states, String stateName,
473             @Nullable Integer stateType) {
474         for (SomfyTahomaState state : states) {
475             if (stateName.equals(state.getName()) && (stateType == null || stateType == state.getType())) {
476                 return state;
477             }
478         }
479         return null;
480     }
481 }