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.http.internal.converter;
15 import java.util.function.Consumer;
17 import javax.measure.format.MeasurementParseException;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.http.internal.config.HttpChannelConfig;
22 import org.openhab.binding.http.internal.transform.ValueTransformation;
23 import org.openhab.core.library.types.DecimalType;
24 import org.openhab.core.library.types.QuantityType;
25 import org.openhab.core.types.Command;
26 import org.openhab.core.types.State;
27 import org.openhab.core.types.UnDefType;
30 * The {@link NumberItemConverter} implements {@link org.openhab.core.library.items.NumberItem} conversions
32 * @author Jan N. Klug - Initial contribution
35 public class NumberItemConverter extends AbstractTransformingItemConverter {
37 public NumberItemConverter(Consumer<State> updateState, Consumer<Command> postCommand,
38 @Nullable Consumer<String> sendHttpValue, ValueTransformation stateTransformations,
39 ValueTransformation commandTransformations, HttpChannelConfig channelConfig) {
40 super(updateState, postCommand, sendHttpValue, stateTransformations, commandTransformations, channelConfig);
44 protected @Nullable Command toCommand(String value) {
49 protected State toState(String value) {
50 String trimmedValue = value.trim();
51 if (!trimmedValue.isEmpty()) {
53 if (channelConfig.unit != null) {
54 // we have a given unit - use that
55 return new QuantityType<>(trimmedValue + " " + channelConfig.unit);
58 // try if we have a simple number
59 return new DecimalType(trimmedValue);
60 } catch (IllegalArgumentException e1) {
61 // not a plain number, maybe with unit?
62 return new QuantityType<>(trimmedValue);
65 } catch (IllegalArgumentException | MeasurementParseException e) {
69 return UnDefType.UNDEF;
73 protected String toString(Command command) {
74 return command.toString();