ESPHome 2026.2.1
Loading...
Searching...
No Matches
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
9namespace esphome::mqtt {
10
11static const char *const TAG = "mqtt.button";
12
13using namespace esphome::button;
14
16
18 this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) {
19 if (payload == "PRESS") {
20 this->button_->press();
21 } else {
22 ESP_LOGW(TAG, "'%s': Received unknown status payload: %s", this->friendly_name_().c_str(), payload.c_str());
23 this->status_momentary_warning("state", 5000);
24 }
25 });
26}
28 ESP_LOGCONFIG(TAG, "MQTT Button '%s': ", this->button_->get_name().c_str());
29 LOG_MQTT_COMPONENT(false, true);
30}
31
33 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
34 config.state_topic = false;
35 const auto device_class = this->button_->get_device_class_ref();
36 if (!device_class.empty()) {
37 root[MQTT_DEVICE_CLASS] = device_class;
38 }
39 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
40}
41
43const EntityBase *MQTTButtonComponent::get_entity() const { return this->button_; }
44
45} // namespace esphome::mqtt
46
47#endif
48#endif // USE_MQTT
void status_momentary_warning(const char *name, uint32_t length=5000)
Set warning status flag and automatically clear it after a timeout.
StringRef get_device_class_ref() const
Get the device class as StringRef.
const StringRef & get_name() const
constexpr const char * c_str() const
Definition string_ref.h:73
Base class for all buttons.
Definition button.h:25
void press()
Press this button.
Definition button.cpp:18
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
MQTTButtonComponent(button::Button *button)
const StringRef & friendly_name_() const
Get the friendly name of this MQTT component.
std::string get_command_topic_() const
Get the MQTT topic for listening to commands (allocates std::string).
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos=0)
Subscribe to a MQTT topic.
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool state_topic
If the state topic should be included. Defaults to true.