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.binding.mqtt.homeassistant.internal;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.binding.mqtt.generic.values.OnOffValue;
20 * A MQTT switch, following the https://www.home-assistant.io/components/switch.mqtt/ specification.
22 * @author David Graeff - Initial contribution
25 public class ComponentSwitch extends AbstractComponent<ComponentSwitch.ChannelConfiguration> {
26 public static final String switchChannelID = "switch"; // Randomly chosen channel "ID"
29 * Configuration class for MQTT component
31 static class ChannelConfiguration extends BaseChannelConfiguration {
32 ChannelConfiguration() {
36 protected @Nullable Boolean optimistic;
38 protected @Nullable String command_topic;
39 protected String state_topic = "";
41 protected @Nullable String state_on;
42 protected @Nullable String state_off;
43 protected String payload_on = "ON";
44 protected String payload_off = "OFF";
46 protected @Nullable String json_attributes_topic;
47 protected @Nullable String json_attributes_template;
50 public ComponentSwitch(CFactory.ComponentConfiguration componentConfiguration) {
51 super(componentConfiguration, ChannelConfiguration.class);
53 boolean optimistic = channelConfiguration.optimistic != null ? channelConfiguration.optimistic
54 : channelConfiguration.state_topic.isBlank();
56 if (optimistic && !channelConfiguration.state_topic.isBlank()) {
57 throw new UnsupportedOperationException("Component:Switch does not support forced optimistic mode");
60 String state_on = channelConfiguration.state_on != null ? channelConfiguration.state_on
61 : channelConfiguration.payload_on;
62 String state_off = channelConfiguration.state_off != null ? channelConfiguration.state_off
63 : channelConfiguration.payload_off;
65 OnOffValue value = new OnOffValue(state_on, state_off, channelConfiguration.payload_on,
66 channelConfiguration.payload_off);
68 buildChannel(switchChannelID, value, "state", componentConfiguration.getUpdateListener())
69 .stateTopic(channelConfiguration.state_topic, channelConfiguration.value_template)
70 .commandTopic(channelConfiguration.command_topic, channelConfiguration.retain, channelConfiguration.qos)