2 * Copyright (c) 2010-2022 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 java.util.stream.Collectors;
16 import java.util.stream.Stream;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.core.library.CoreItemFactory;
21 import org.openhab.core.library.types.OpenClosedType;
22 import org.openhab.core.library.types.StringType;
23 import org.openhab.core.types.Command;
26 * Implements an open/close boolean value.
28 * @author David Graeff - Initial contribution
31 public class OpenCloseValue extends Value {
32 private final String openString;
33 private final String closeString;
36 * Creates a contact Open/Close type.
38 public OpenCloseValue() {
39 super(CoreItemFactory.CONTACT, Stream.of(OpenClosedType.class, StringType.class).collect(Collectors.toList()));
40 this.openString = OpenClosedType.OPEN.name();
41 this.closeString = OpenClosedType.CLOSED.name();
45 * Creates a new contact Open/Close value.
47 * @param openValue The ON value string. This will be compared to MQTT messages.
48 * @param closeValue The OFF value string. This will be compared to MQTT messages.
50 public OpenCloseValue(@Nullable String openValue, @Nullable String closeValue) {
51 super(CoreItemFactory.CONTACT, Stream.of(OpenClosedType.class, StringType.class).collect(Collectors.toList()));
52 this.openString = openValue == null ? OpenClosedType.OPEN.name() : openValue;
53 this.closeString = closeValue == null ? OpenClosedType.CLOSED.name() : closeValue;
57 public void update(Command command) throws IllegalArgumentException {
58 if (command instanceof OpenClosedType) {
59 state = (OpenClosedType) command;
61 final String updatedValue = command.toString();
62 if (openString.equals(updatedValue)) {
63 state = OpenClosedType.OPEN;
64 } else if (closeString.equals(updatedValue)) {
65 state = OpenClosedType.CLOSED;
67 state = OpenClosedType.valueOf(updatedValue);
73 public String getMQTTpublishValue(@Nullable String pattern) {
74 String formatPattern = pattern;
75 if (formatPattern == null) {
79 return String.format(formatPattern, state == OpenClosedType.OPEN ? openString : closeString);