]> git.basschouten.com Git - openhab-addons.git/blob
c3c06418afacc39943b9e3447270c5b302f4bb32
[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.miio.internal;
14
15 import java.util.Arrays;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.stream.Collectors;
19
20 import javax.measure.Unit;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.core.library.unit.ImperialUnits;
25 import org.openhab.core.library.unit.SIUnits;
26 import org.openhab.core.library.unit.SmartHomeUnits;
27
28 import tec.uom.se.unit.Units;
29
30 /**
31  * Enum of the units used in the miio protocol
32  * Used to find the right {@link javax.measure.Unit} given the string of the unit
33  *
34  * @author Marcel Verpaalen - Initial contribution
35  */
36 @NonNullByDefault
37 public enum MiIoQuantiyTypes {
38
39     CELCIUS(SIUnits.CELSIUS, "C"),
40     FAHRENHEIT(ImperialUnits.FAHRENHEIT),
41     SECOND(SmartHomeUnits.SECOND, "seconds"),
42     MINUTE(SmartHomeUnits.MINUTE, "minutes"),
43     HOUR(SmartHomeUnits.HOUR, "hours"),
44     AMPERE(SmartHomeUnits.AMPERE),
45     WATT(SmartHomeUnits.WATT),
46     SQUARE_METRE(Units.SQUARE_METRE, "square_meter", "squaremeter"),
47     PERCENT(SmartHomeUnits.PERCENT);
48
49     private final Unit<?> unit;
50     private final String[] aliasses;
51
52     private static Map<String, Unit<?>> stringMap = Arrays.stream(values())
53             .collect(Collectors.toMap(Enum::toString, MiIoQuantiyTypes::getUnit));
54
55     private static Map<String, Unit<?>> aliasMap() {
56         Map<String, Unit<?>> aliassesMap = new HashMap<>();
57         for (MiIoQuantiyTypes miIoQuantiyType : values()) {
58             for (String alias : miIoQuantiyType.getAliasses()) {
59                 aliassesMap.put(alias.toLowerCase(), miIoQuantiyType.getUnit());
60             }
61         }
62         return aliassesMap;
63     }
64
65     private MiIoQuantiyTypes(Unit<?> unit, String... aliasses) {
66         this.unit = unit;
67         this.aliasses = aliasses;
68     }
69
70     public Unit<?> getUnit() {
71         return unit;
72     }
73
74     public String[] getAliasses() {
75         return aliasses;
76     }
77
78     public static @Nullable Unit<?> get(String unitName) {
79         Unit<?> unit = stringMap.get(unitName.toUpperCase());
80         if (unit == null) {
81             unit = aliasMap().get(unitName.toLowerCase());
82         }
83         return unit;
84     }
85 }