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.io.homekit.internal.accessories;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.openhab.core.items.GroupItem;
17 import org.openhab.core.items.Item;
18 import org.openhab.core.library.items.ContactItem;
19 import org.openhab.core.library.items.StringItem;
20 import org.openhab.core.library.items.SwitchItem;
21 import org.openhab.core.library.types.OnOffType;
22 import org.openhab.core.library.types.OpenClosedType;
23 import org.openhab.core.library.types.StringType;
24 import org.openhab.core.types.State;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Wraps either a SwitchItem or a ContactItem, interpreting the open / closed states accordingly.
31 * @author Tim Harper - Initial contribution
35 public class BooleanItemReader {
36 private final Item item;
37 private final OnOffType trueOnOffValue;
38 private final OpenClosedType trueOpenClosedValue;
39 private final Logger logger = LoggerFactory.getLogger(BooleanItemReader.class);
43 * @param item The item to read
44 * @param trueOnOffValue If OnOffType, then consider true if this value
45 * @param trueOpenClosedValue if OpenClosedType, then consider true if this value
47 BooleanItemReader(Item item, OnOffType trueOnOffValue, OpenClosedType trueOpenClosedValue) {
49 this.trueOnOffValue = trueOnOffValue;
50 this.trueOpenClosedValue = trueOpenClosedValue;
51 if (!(item instanceof SwitchItem) && !(item instanceof ContactItem) && !(item instanceof StringItem)) {
52 logger.warn("Item {} is a {} instead of the expected SwitchItem, ContactItem or StringItem", item.getName(),
53 item.getClass().getName());
58 final State state = item.getState();
59 if (state instanceof OnOffType) {
60 return state.equals(trueOnOffValue);
61 } else if (state instanceof OpenClosedType) {
62 return state.equals(trueOpenClosedValue);
63 } else if (state instanceof StringType) {
64 return state.toString().equalsIgnoreCase("Open") || state.toString().equalsIgnoreCase("Opened");
66 logger.debug("Unexpected item state, returning false. Item {}, State {}", item.getName(), state);
71 private OnOffType getOffValue(OnOffType onValue) {
72 return onValue == OnOffType.ON ? OnOffType.OFF : OnOffType.ON;
75 void setValue(Boolean value) {
76 if (item instanceof SwitchItem) {
77 ((SwitchItem) item).send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
78 } else if (item instanceof GroupItem) {
79 ((GroupItem) item).send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
81 logger.debug("Cannot set value {} for item {}. Only Switch and Group items are supported.", value, item);