2 * Copyright (c) 2010-2024 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.homeassistant.internal;
15 import java.util.concurrent.CompletableFuture;
16 import java.util.function.Predicate;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.mqtt.generic.ChannelConfig;
21 import org.openhab.binding.mqtt.generic.ChannelState;
22 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
23 import org.openhab.binding.mqtt.generic.values.Value;
24 import org.openhab.core.thing.ChannelUID;
25 import org.openhab.core.types.Command;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
30 * Extended {@link ChannelState} with added filter for {@link #publishValue(Command)}
32 * @author Anton Kharuzhy - Initial contribution
35 public class HomeAssistantChannelState extends ChannelState {
36 private final Logger logger = LoggerFactory.getLogger(HomeAssistantChannelState.class);
37 private final @Nullable Predicate<Command> commandFilter;
40 * Creates a new channel state.
42 * @param config The channel configuration
43 * @param channelUID The channelUID is used for the {@link ChannelStateUpdateListener} to notify about value changes
44 * @param cachedValue MQTT only notifies us once about a value, during the subscribe. The channel state therefore
45 * needs a cache for the current value.
46 * @param channelStateUpdateListener A channel state update listener
47 * @param commandFilter A filter for commands, on <code>true</code> command will be published, on
48 * <code>false</code> ignored. Can be <code>null</code> to publish all commands.
50 public HomeAssistantChannelState(ChannelConfig config, ChannelUID channelUID, Value cachedValue,
51 @Nullable ChannelStateUpdateListener channelStateUpdateListener,
52 @Nullable Predicate<Command> commandFilter) {
53 super(config, channelUID, cachedValue, channelStateUpdateListener);
54 this.commandFilter = commandFilter;
58 public CompletableFuture<Boolean> publishValue(Command command) {
59 if (commandFilter != null) {
61 if (!commandFilter.test(command)) {
62 logger.trace("Channel {} updates are disabled by command filter, ignoring command {}", channelUID,
64 return CompletableFuture.completedFuture(false);
66 } catch (IllegalArgumentException e) {
67 CompletableFuture<Boolean> f = new CompletableFuture<>();
68 f.completeExceptionally(e);
72 return super.publishValue(command);