2 * Copyright (c) 2010-2023 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.mqtt.generic.values;
15 import static java.util.function.Predicate.not;
17 import java.util.List;
19 import java.util.stream.Collectors;
20 import java.util.stream.Stream;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.core.library.CoreItemFactory;
25 import org.openhab.core.library.types.StringType;
26 import org.openhab.core.types.Command;
27 import org.openhab.core.types.CommandDescriptionBuilder;
28 import org.openhab.core.types.CommandOption;
29 import org.openhab.core.types.StateDescriptionFragmentBuilder;
30 import org.openhab.core.types.StateOption;
33 * Implements a text/string value. Allows to restrict the incoming value to a set of states.
35 * @author David Graeff - Initial contribution
38 public class TextValue extends Value {
39 private final @Nullable Set<String> states;
42 * Create a string value with a limited number of allowed states.
44 * @param states Allowed states. Empty states are filtered out. If the resulting set is empty, all string values
47 public TextValue(String[] states) {
48 super(CoreItemFactory.STRING, List.of(StringType.class));
49 Set<String> s = Stream.of(states).filter(not(String::isBlank)).collect(Collectors.toSet());
58 super(CoreItemFactory.STRING, List.of(StringType.class));
63 public void update(Command command) throws IllegalArgumentException {
64 final Set<String> states = this.states;
65 String valueStr = command.toString();
66 if (states != null && !states.contains(valueStr)) {
67 throw new IllegalArgumentException("Value " + valueStr + " not within range");
69 state = new StringType(valueStr);
73 * @return valid states. Can be null.
75 public @Nullable Set<String> getStates() {
80 public StateDescriptionFragmentBuilder createStateDescription(boolean readOnly) {
81 StateDescriptionFragmentBuilder builder = super.createStateDescription(readOnly);
82 final Set<String> states = this.states;
84 for (String state : states) {
85 builder = builder.withOption(new StateOption(state, state));
92 public CommandDescriptionBuilder createCommandDescription() {
93 CommandDescriptionBuilder builder = super.createCommandDescription();
94 final Set<String> commands = this.states;
96 for (String command : commands) {
97 builder = builder.withCommandOption(new CommandOption(command, command));