]> git.basschouten.com Git - openhab-addons.git/blob
ec92206021de468ac0817be6bce29c5f7df8bcdb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.homematic.internal.type;
14
15 import static org.openhab.binding.homematic.internal.HomematicBindingConstants.*;
16 import static org.openhab.binding.homematic.internal.misc.HomematicConstants.*;
17
18 import java.io.BufferedReader;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.math.BigDecimal;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Locale;
28 import java.util.Map;
29 import java.util.ResourceBundle;
30 import java.util.Set;
31
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.commons.lang.WordUtils;
34 import org.openhab.binding.homematic.internal.model.HmDatapoint;
35 import org.openhab.binding.homematic.internal.model.HmDevice;
36 import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
37 import org.osgi.framework.Bundle;
38 import org.osgi.framework.FrameworkUtil;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Helper methods for generating the openHAB metadata.
44  *
45  * @author Gerhard Riegler - Initial contribution
46  * @author Michael Reitler - QuantityType support
47  */
48
49 public class MetadataUtils {
50     private static final Logger logger = LoggerFactory.getLogger(MetadataUtils.class);
51     private static ResourceBundle descriptionsBundle;
52     private static Map<String, String> descriptions = new HashMap<>();
53     private static Map<String, Set<String>> standardDatapoints = new HashMap<>();
54
55     protected static void initialize() {
56         // loads all Homematic device names
57         loadBundle("homematic/generated-descriptions");
58         loadBundle("homematic/extra-descriptions");
59         loadStandardDatapoints();
60     }
61
62     private static void loadBundle(String filename) {
63         descriptionsBundle = ResourceBundle.getBundle(filename, Locale.getDefault());
64         for (String key : descriptionsBundle.keySet()) {
65             descriptions.put(key.toUpperCase(), descriptionsBundle.getString(key));
66         }
67         ResourceBundle.clearCache();
68         descriptionsBundle = null;
69     }
70
71     /**
72      * Loads the standard datapoints for channel metadata generation.
73      */
74     private static void loadStandardDatapoints() {
75         Bundle bundle = FrameworkUtil.getBundle(MetadataUtils.class);
76         try (InputStream stream = bundle.getResource("homematic/standard-datapoints.properties").openStream();
77                 BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
78             String line;
79             while ((line = reader.readLine()) != null) {
80                 if (StringUtils.trimToNull(line) != null && !StringUtils.startsWith(line, "#")) {
81                     String channelType = StringUtils.trimToNull(StringUtils.substringBefore(line, "|"));
82                     String datapointName = StringUtils.trimToNull(StringUtils.substringAfter(line, "|"));
83
84                     Set<String> channelDatapoints = standardDatapoints.get(channelType);
85                     if (channelDatapoints == null) {
86                         channelDatapoints = new HashSet<>();
87                         standardDatapoints.put(channelType, channelDatapoints);
88                     }
89
90                     channelDatapoints.add(datapointName);
91                 }
92             }
93         } catch (IllegalStateException | IOException e) {
94             logger.warn("Can't load standard-datapoints.properties file!", e);
95         }
96     }
97
98     public interface OptionsBuilder<T> {
99         public T createOption(String value, String description);
100     }
101
102     /**
103      * Creates channel and config description metadata options for the given Datapoint.
104      */
105     public static <T> List<T> generateOptions(HmDatapoint dp, OptionsBuilder<T> optionsBuilder) {
106         List<T> options = null;
107         if (dp.getOptions() == null) {
108             logger.warn("No options for ENUM datapoint {}", dp);
109         } else {
110             options = new ArrayList<>();
111             for (int i = 0; i < dp.getOptions().length; i++) {
112                 String description = null;
113                 if (!dp.isVariable() && !dp.isScript()) {
114                     description = getDescription(dp.getChannel().getType(), dp.getName(), dp.getOptions()[i]);
115                 }
116                 if (description == null) {
117                     description = dp.getOptions()[i];
118                 }
119                 options.add(optionsBuilder.createOption(dp.getOptions()[i], description));
120             }
121         }
122         return options;
123     }
124
125     /**
126      * Returns the ConfigDescriptionParameter type for the given Datapoint.
127      */
128     public static Type getConfigDescriptionParameterType(HmDatapoint dp) {
129         if (dp.isBooleanType()) {
130             return Type.BOOLEAN;
131         } else if (dp.isIntegerType()) {
132             return Type.INTEGER;
133         } else if (dp.isFloatType()) {
134             return Type.DECIMAL;
135         } else {
136             return Type.TEXT;
137         }
138     }
139
140     /**
141      * Returns the unit metadata string for the given Datapoint.
142      */
143     public static String getUnit(HmDatapoint dp) {
144         if (dp.getUnit() != null) {
145             String unit = StringUtils.replace(dp.getUnit(), "100%", "%");
146             return StringUtils.replace(unit, "%", "%%");
147         }
148         return null;
149     }
150
151     /**
152      * Returns the pattern metadata string for the given Datapoint.
153      */
154     public static String getPattern(HmDatapoint dp) {
155         if (dp.isFloatType()) {
156             return "%.2f";
157         } else if (dp.isNumberType()) {
158             return "%d";
159         } else {
160             return null;
161         }
162     }
163
164     /**
165      * Returns the state pattern metadata string with unit for the given Datapoint.
166      */
167     public static String getStatePattern(HmDatapoint dp) {
168         String unit = getUnit(dp);
169         if (unit != null && unit != "") {
170             String pattern = getPattern(dp);
171             if (pattern != null) {
172                 return String.format("%s %s", pattern, "%unit%");
173             }
174         }
175         return null;
176     }
177
178     /**
179      * Returns the label string for the given Datapoint.
180      */
181     public static String getLabel(HmDatapoint dp) {
182         return WordUtils.capitalizeFully(StringUtils.replace(dp.getName(), "_", " "));
183     }
184
185     /**
186      * Returns the parameter name for the specified Datapoint.
187      */
188     public static String getParameterName(HmDatapoint dp) {
189         return String.format("HMP_%d_%s", dp.getChannel().getNumber(), dp.getName());
190     }
191
192     /**
193      * Returns the description for the given keys.
194      */
195     public static String getDescription(String... keys) {
196         StringBuilder sb = new StringBuilder();
197         for (int startIdx = 0; startIdx < keys.length; startIdx++) {
198             String key = StringUtils.join(keys, "|", startIdx, keys.length);
199             if (key.endsWith("|")) {
200                 key = key.substring(0, key.length() - 1);
201             }
202             String description = descriptions.get(key.toUpperCase());
203             if (description != null) {
204                 return description;
205             }
206             sb.append(key).append(", ");
207         }
208         if (logger.isTraceEnabled()) {
209             logger.trace("Description not found for: {}", StringUtils.substring(sb.toString(), 0, -2));
210         }
211         return null;
212     }
213
214     /**
215      * Returns the device name for the given device type.
216      */
217     public static String getDeviceName(HmDevice device) {
218         if (device.isGatewayExtras()) {
219             return getDescription(HmDevice.TYPE_GATEWAY_EXTRAS);
220         }
221
222         String deviceDescription = null;
223         boolean isTeam = device.getType().endsWith("-Team");
224         String type = isTeam ? StringUtils.remove(device.getType(), "-Team") : device.getType();
225         deviceDescription = getDescription(type);
226
227         if (deviceDescription != null && isTeam) {
228             deviceDescription += " Team";
229         }
230
231         return deviceDescription == null ? "No Description" : deviceDescription;
232     }
233
234     /**
235      * Returns the description for the given datapoint.
236      */
237     public static String getDatapointDescription(HmDatapoint dp) {
238         if (dp.isVariable() || dp.isScript()) {
239             return null;
240         }
241         return getDescription(dp.getChannel().getType(), dp.getName());
242     }
243
244     /**
245      * Returns true, if the given datapoint is a standard datapoint.
246      */
247     public static boolean isStandard(HmDatapoint dp) {
248         Set<String> channelDatapoints = standardDatapoints.get(dp.getChannel().getType());
249         if (channelDatapoints == null) {
250             return true;
251         }
252
253         return channelDatapoints.contains(dp.getName());
254     }
255
256     /**
257      * Helper method for creating a BigDecimal.
258      */
259     public static BigDecimal createBigDecimal(Number number) {
260         if (number == null) {
261             return null;
262         }
263         try {
264             return new BigDecimal(number.toString());
265         } catch (Exception ex) {
266             logger.warn("Can't create BigDecimal for number: {}", number.toString());
267             return null;
268         }
269     }
270
271     /**
272      * Determines the itemType for the given Datapoint.
273      */
274     public static String getItemType(HmDatapoint dp) {
275         String dpName = dp.getName();
276         String channelType = StringUtils.defaultString(dp.getChannel().getType());
277
278         if (dp.isBooleanType()) {
279             if (((dpName.equals(DATAPOINT_NAME_STATE) || dpName.equals(VIRTUAL_DATAPOINT_NAME_STATE_CONTACT))
280                     && (channelType.equals(CHANNEL_TYPE_SHUTTER_CONTACT)
281                             || channelType.contentEquals(CHANNEL_TYPE_TILT_SENSOR)))
282                     || (dpName.equals(DATAPOINT_NAME_SENSOR) && channelType.equals(CHANNEL_TYPE_SENSOR))) {
283                 return ITEM_TYPE_CONTACT;
284             } else {
285                 return ITEM_TYPE_SWITCH;
286             }
287         } else if (dp.isNumberType()) {
288             if (dpName.startsWith(DATAPOINT_NAME_LEVEL) && isRollerShutter(dp)) {
289                 return ITEM_TYPE_ROLLERSHUTTER;
290             } else if (dpName.startsWith(DATAPOINT_NAME_LEVEL) && !channelType.equals(CHANNEL_TYPE_WINMATIC)
291                     && !channelType.equals(CHANNEL_TYPE_AKKU)) {
292                 return ITEM_TYPE_DIMMER;
293             } else {
294                 // determine QuantityType
295                 String unit = dp.getUnit() != null ? dp.getUnit() : "";
296                 switch (unit) {
297                     case "°C":
298                     case "°C":
299                         return ITEM_TYPE_NUMBER + ":Temperature";
300                     case "V":
301                         return ITEM_TYPE_NUMBER + ":ElectricPotential";
302                     case "%":
303                         return ITEM_TYPE_NUMBER + ":Dimensionless";
304                     case "mHz":
305                     case "Hz":
306                         return ITEM_TYPE_NUMBER + ":Frequency";
307                     case "hPa":
308                         return ITEM_TYPE_NUMBER + ":Pressure";
309                     case "Lux":
310                         return ITEM_TYPE_NUMBER + ":Illuminance";
311                     case "degree":
312                         return ITEM_TYPE_NUMBER + ":Angle";
313                     case "km/h":
314                         return ITEM_TYPE_NUMBER + ":Speed";
315                     case "mm":
316                         return ITEM_TYPE_NUMBER + ":Length";
317                     case "W":
318                         return ITEM_TYPE_NUMBER + ":Power";
319                     case "Wh":
320                         return ITEM_TYPE_NUMBER + ":Energy";
321                     case "m3":
322                         return ITEM_TYPE_NUMBER + ":Volume";
323                     case "s":
324                     case "min":
325                     case "minutes":
326                     case "day":
327                     case "month":
328                     case "year":
329                     case "100%":
330                     case "":
331                     default:
332                         return ITEM_TYPE_NUMBER;
333                 }
334             }
335         } else if (dp.isDateTimeType()) {
336             return ITEM_TYPE_DATETIME;
337         } else {
338             return ITEM_TYPE_STRING;
339         }
340     }
341
342     /**
343      * Returns true, if the device of the datapoint is a rollershutter.
344      */
345     public static boolean isRollerShutter(HmDatapoint dp) {
346         String channelType = dp.getChannel().getType();
347         return channelType.equals(CHANNEL_TYPE_BLIND) || channelType.equals(CHANNEL_TYPE_JALOUSIE)
348                 || channelType.equals(CHANNEL_TYPE_BLIND_TRANSMITTER)
349                 || channelType.equals(CHANNEL_TYPE_SHUTTER_TRANSMITTER)
350                 || channelType.equals(CHANNEL_TYPE_SHUTTER_VIRTUAL_RECEIVER)
351                 || channelType.contentEquals(CHANNEL_TYPE_BLIND_VIRTUAL_RECEIVER);
352     }
353
354     /**
355      * Determines the category for the given Datapoint.
356      */
357     public static String getCategory(HmDatapoint dp, String itemType) {
358         String dpName = dp.getName();
359         String channelType = StringUtils.defaultString(dp.getChannel().getType());
360
361         if (dpName.equals(DATAPOINT_NAME_BATTERY_TYPE) || dpName.equals(DATAPOINT_NAME_LOWBAT)
362                 || dpName.equals(DATAPOINT_NAME_LOWBAT_IP)) {
363             return CATEGORY_BATTERY;
364         } else if (dpName.equals(DATAPOINT_NAME_STATE) && channelType.equals(CHANNEL_TYPE_ALARMACTUATOR)) {
365             return CATEGORY_ALARM;
366         } else if (dpName.equals(DATAPOINT_NAME_HUMIDITY)) {
367             return CATEGORY_HUMIDITY;
368         } else if (dpName.contains(DATAPOINT_NAME_TEMPERATURE)) {
369             return CATEGORY_TEMPERATURE;
370         } else if (dpName.equals(DATAPOINT_NAME_MOTION)) {
371             return CATEGORY_MOTION;
372         } else if (dpName.equals(DATAPOINT_NAME_AIR_PRESSURE)) {
373             return CATEGORY_PRESSURE;
374         } else if (dpName.equals(DATAPOINT_NAME_STATE) && channelType.equals(CHANNEL_TYPE_SMOKE_DETECTOR)) {
375             return CATEGORY_SMOKE;
376         } else if (dpName.equals(DATAPOINT_NAME_STATE) && channelType.equals(CHANNEL_TYPE_WATERDETECTIONSENSOR)) {
377             return CATEGORY_WATER;
378         } else if (dpName.equals(DATAPOINT_NAME_WIND_SPEED)) {
379             return CATEGORY_WIND;
380         } else if (dpName.startsWith(DATAPOINT_NAME_RAIN)
381                 || dpName.equals(DATAPOINT_NAME_STATE) && channelType.equals(CHANNEL_TYPE_RAINDETECTOR)) {
382             return CATEGORY_RAIN;
383         } else if (channelType.equals(CHANNEL_TYPE_POWERMETER) && !dpName.equals(DATAPOINT_NAME_BOOT)
384                 && !dpName.equals(DATAPOINT_NAME_FREQUENCY)) {
385             return CATEGORY_ENERGY;
386         } else if (itemType.equals(ITEM_TYPE_ROLLERSHUTTER)) {
387             return CATEGORY_BLINDS;
388         } else if (itemType.equals(ITEM_TYPE_CONTACT)) {
389             return CATEGORY_CONTACT;
390         } else if (itemType.equals(ITEM_TYPE_DIMMER)) {
391             return CATEGORY_DIMMABLE_LIGHT;
392         } else if (itemType.equals(ITEM_TYPE_SWITCH)) {
393             return CATEGORY_SWITCH;
394         } else {
395             return null;
396         }
397     }
398 }