]> git.basschouten.com Git - openhab-addons.git/blob
5f63d1d950841159c6f5d0733db41c7406520540
[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.mikrotik.internal.util;
14
15 import java.math.BigInteger;
16 import java.time.LocalDateTime;
17 import java.time.ZoneId;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.library.types.DateTimeType;
22 import org.openhab.core.library.types.DecimalType;
23 import org.openhab.core.library.types.OnOffType;
24 import org.openhab.core.library.types.QuantityType;
25 import org.openhab.core.library.types.StringType;
26 import org.openhab.core.library.unit.Units;
27 import org.openhab.core.types.State;
28 import org.openhab.core.types.UnDefType;
29
30 /**
31  * The {@link StateUtil} class holds static methods to cast Java native/class types to OpenHAB values
32  *
33  * @author Oleg Vivtash - Initial contribution
34  */
35 @NonNullByDefault
36 public class StateUtil {
37
38     public static State stringOrNull(@Nullable String value) {
39         return value == null ? UnDefType.NULL : new StringType(value);
40     }
41
42     public static State qtyMegabitPerSecOrNull(@Nullable Float value) {
43         return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.MEGABIT_PER_SECOND);
44     }
45
46     public static State qtyPercentOrNull(@Nullable Integer value) {
47         return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.PERCENT);
48     }
49
50     public static State qtyBytesOrNull(@Nullable Integer value) {
51         return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.BYTE);
52     }
53
54     public static State intOrNull(@Nullable Integer value) {
55         return value == null ? UnDefType.NULL : new DecimalType(value.floatValue());
56     }
57
58     public static State bigIntOrNull(@Nullable BigInteger value) {
59         return value == null ? UnDefType.NULL : DecimalType.valueOf(value.toString());
60     }
61
62     public static State floatOrNull(@Nullable Float value) {
63         return value == null ? UnDefType.NULL : new DecimalType(value);
64     }
65
66     public static State boolOrNull(@Nullable Boolean value) {
67         if (value == null) {
68             return UnDefType.NULL;
69         }
70         return value ? OnOffType.ON : OnOffType.OFF;
71     }
72
73     public static State timeOrNull(@Nullable LocalDateTime value) {
74         return value == null ? UnDefType.NULL : new DateTimeType(value.atZone(ZoneId.systemDefault()));
75     }
76 }