2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mikrotik.internal.util;
15 import java.math.BigInteger;
16 import java.time.LocalDateTime;
17 import java.time.ZoneId;
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;
31 * The {@link StateUtil} class holds static methods to cast Java native/class types to OpenHAB values
33 * @author Oleg Vivtash - Initial contribution
36 public class StateUtil {
38 public static State stringOrNull(@Nullable String value) {
39 return value == null ? UnDefType.NULL : new StringType(value);
42 public static State qtyMegabitPerSecOrNull(@Nullable Float value) {
43 return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.MEGABIT_PER_SECOND);
46 public static State qtyPercentOrNull(@Nullable Integer value) {
47 return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.PERCENT);
50 public static State qtyBytesOrNull(@Nullable Integer value) {
51 return value == null ? UnDefType.NULL : new QuantityType<>(value, Units.BYTE);
54 public static State intOrNull(@Nullable Integer value) {
55 return value == null ? UnDefType.NULL : new DecimalType(value.floatValue());
58 public static State bigIntOrNull(@Nullable BigInteger value) {
59 return value == null ? UnDefType.NULL : DecimalType.valueOf(value.toString());
62 public static State floatOrNull(@Nullable Float value) {
63 return value == null ? UnDefType.NULL : new DecimalType(value);
66 public static State boolOrNull(@Nullable Boolean value) {
68 return UnDefType.NULL;
70 return value ? OnOffType.ON : OnOffType.OFF;
73 public static State timeOrNull(@Nullable LocalDateTime value) {
74 return value == null ? UnDefType.NULL : new DateTimeType(value.atZone(ZoneId.systemDefault()));