ESPHome  2024.11.3
mqtt_button.cpp
Go to the documentation of this file.
1 #include "mqtt_button.h"
2 #include "esphome/core/log.h"
3 
4 #include "mqtt_const.h"
5 
6 #ifdef USE_MQTT
7 #ifdef USE_BUTTON
8 
9 namespace esphome {
10 namespace mqtt {
11 
12 static const char *const TAG = "mqtt.button";
13 
14 using namespace esphome::button;
15 
17 
19  this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) {
20  if (payload == "PRESS") {
21  this->button_->press();
22  } else {
23  ESP_LOGW(TAG, "'%s': Received unknown status payload: %s", this->friendly_name().c_str(), payload.c_str());
24  this->status_momentary_warning("state", 5000);
25  }
26  });
27 }
29  ESP_LOGCONFIG(TAG, "MQTT Button '%s': ", this->button_->get_name().c_str());
30  LOG_MQTT_COMPONENT(true, true);
31 }
32 
34  config.state_topic = false;
35  if (!this->button_->get_device_class().empty())
37 }
38 
39 std::string MQTTButtonComponent::component_type() const { return "button"; }
40 const EntityBase *MQTTButtonComponent::get_entity() const { return this->button_; }
41 
42 } // namespace mqtt
43 } // namespace esphome
44 
45 #endif
46 #endif // USE_MQTT
MQTTButtonComponent(button::Button *button)
Definition: mqtt_button.cpp:16
std::string get_device_class()
Get the device class, using the manual override if set.
Definition: entity_base.cpp:78
Base class for all buttons.
Definition: button.h:29
void status_momentary_warning(const std::string &name, uint32_t length=5000)
Definition: component.cpp:178
bool state_topic
If the state topic should be included. Defaults to true.
std::string component_type() const override
"button" component type.
Definition: mqtt_button.cpp:39
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos=0)
Subscribe to a MQTT topic.
void press()
Press this button.
Definition: button.cpp:9
Simple Helper struct used for Home Assistant MQTT send_discovery().
constexpr const char * c_str() const
Definition: string_ref.h:68
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
Definition: mqtt_button.cpp:33
virtual std::string friendly_name() const
Get the friendly name of this MQTT component.
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
constexpr const char *const MQTT_DEVICE_CLASS
Definition: mqtt_const.h:58
std::string get_command_topic_() const
Get the MQTT topic for listening to commands.
const EntityBase * get_entity() const override
Definition: mqtt_button.cpp:40
const StringRef & get_name() const
Definition: entity_base.cpp:10