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