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.apache.commons.lang.StringUtils;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.openhab.binding.mqtt.generic.values.OnOffValue;
21 * A MQTT switch, following the https://www.home-assistant.io/components/switch.mqtt/ specification.
23 * @author David Graeff - Initial contribution
26 public class ComponentSwitch extends AbstractComponent<ComponentSwitch.ChannelConfiguration> {
27 public static final String switchChannelID = "switch"; // Randomly chosen channel "ID"
30 * Configuration class for MQTT component
32 static class ChannelConfiguration extends BaseChannelConfiguration {
33 ChannelConfiguration() {
37 protected @Nullable Boolean optimistic;
39 protected @Nullable String command_topic;
40 protected String state_topic = "";
42 protected @Nullable String state_on;
43 protected @Nullable String state_off;
44 protected String payload_on = "ON";
45 protected String payload_off = "OFF";
47 protected @Nullable String json_attributes_topic;
48 protected @Nullable String json_attributes_template;
51 public ComponentSwitch(CFactory.ComponentConfiguration componentConfiguration) {
52 super(componentConfiguration, ChannelConfiguration.class);
54 boolean optimistic = channelConfiguration.optimistic != null ? channelConfiguration.optimistic
55 : StringUtils.isBlank(channelConfiguration.state_topic);
57 if (optimistic && StringUtils.isNotBlank(channelConfiguration.state_topic)) {
58 throw new UnsupportedOperationException("Component:Switch does not support forced optimistic mode");
61 String state_on = channelConfiguration.state_on != null ? channelConfiguration.state_on
62 : channelConfiguration.payload_on;
63 String state_off = channelConfiguration.state_off != null ? channelConfiguration.state_off
64 : channelConfiguration.payload_off;
66 OnOffValue value = new OnOffValue(state_on, state_off, channelConfiguration.payload_on,
67 channelConfiguration.payload_off);
69 buildChannel(switchChannelID, value, "state", componentConfiguration.getUpdateListener())
70 .stateTopic(channelConfiguration.state_topic, channelConfiguration.value_template)
71 .commandTopic(channelConfiguration.command_topic, channelConfiguration.retain, channelConfiguration.qos)