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.component;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.binding.mqtt.generic.values.OnOffValue;
18 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
19 import org.openhab.binding.mqtt.homeassistant.internal.exception.ConfigurationException;
21 import com.google.gson.annotations.SerializedName;
24 * A MQTT switch, following the https://www.home-assistant.io/components/switch.mqtt/ specification.
26 * @author David Graeff - Initial contribution
29 public class Switch extends AbstractComponent<Switch.ChannelConfiguration> {
30 public static final String SWITCH_CHANNEL_ID = "switch"; // Randomly chosen channel "ID"
33 * Configuration class for MQTT component
35 static class ChannelConfiguration extends AbstractChannelConfiguration {
36 ChannelConfiguration() {
40 protected @Nullable Boolean optimistic;
42 @SerializedName("command_topic")
43 protected @Nullable String commandTopic;
44 @SerializedName("state_topic")
45 protected String stateTopic = "";
47 @SerializedName("state_on")
48 protected @Nullable String stateOn;
49 @SerializedName("state_off")
50 protected @Nullable String stateOff;
51 @SerializedName("payload_on")
52 protected String payloadOn = "ON";
53 @SerializedName("payload_off")
54 protected String payloadOff = "OFF";
56 @SerializedName("json_attributes_topic")
57 protected @Nullable String jsonAttributesTopic;
58 @SerializedName("json_attributes_template")
59 protected @Nullable String jsonAttributesTemplate;
62 public Switch(ComponentFactory.ComponentConfiguration componentConfiguration) {
63 super(componentConfiguration, ChannelConfiguration.class);
65 boolean optimistic = channelConfiguration.optimistic != null ? channelConfiguration.optimistic
66 : channelConfiguration.stateTopic.isBlank();
68 if (optimistic && !channelConfiguration.stateTopic.isBlank()) {
69 throw new ConfigurationException("Component:Switch does not support forced optimistic mode");
72 OnOffValue value = new OnOffValue(channelConfiguration.stateOn, channelConfiguration.stateOff,
73 channelConfiguration.payloadOn, channelConfiguration.payloadOff);
75 buildChannel(SWITCH_CHANNEL_ID, value, "state", componentConfiguration.getUpdateListener())
76 .stateTopic(channelConfiguration.stateTopic, channelConfiguration.getValueTemplate())
77 .commandTopic(channelConfiguration.commandTopic, channelConfiguration.isRetain(),
78 channelConfiguration.getQos())