ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
mqtt_event.cpp
Go to the documentation of this file.
1#include "mqtt_event.h"
2#include "esphome/core/log.h"
3
4#include "mqtt_const.h"
5
6#ifdef USE_MQTT
7#ifdef USE_EVENT
8
9namespace esphome::mqtt {
10
11ESPHOME_LOG_TAG(TAG, "mqtt.event");
12
13using namespace esphome::event;
14
16
18 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
19 JsonArray event_types = root[MQTT_EVENT_TYPES].to<JsonArray>();
20 for (const auto &event_type : this->event_->get_event_types())
21 event_types.add(event_type);
22
23 config.command_topic = false;
24}
25
27 this->event_->add_on_event_callback([this](const std::string &event_type) { this->publish_event_(event_type); });
28}
29
31 LOG_MQTT_COMPONENT(true, true);
32 ESP_LOGCONFIG(TAG, " Event Types:");
33 for (const char *event_type : this->event_->get_event_types()) {
34 ESP_LOGCONFIG(TAG, " - %s", event_type);
35 }
36}
37
38bool MQTTEventComponent::publish_event_(const std::string &event_type) {
39 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
40 return this->publish_json(this->get_state_topic_to_(topic_buf), [event_type](JsonObject root) {
41 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
42 root[MQTT_EVENT_TYPE] = event_type;
43 });
44}
45
47const EntityBase *MQTTEventComponent::get_entity() const { return this->event_; }
48
49} // namespace esphome::mqtt
50
51#endif
52#endif // USE_MQTT
const EventTypes & get_event_types() const
Return the event types supported by this event.
Definition event.h:51
void add_on_event_callback(F &&callback)
Definition event.h:77
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
StringRef get_state_topic_to_(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Get the MQTT state topic into a buffer (no heap allocation for non-lambda custom topics).
bool publish_event_(const std::string &event_type)
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
MQTTEventComponent(event::Event *event)
ESPHOME_LOG_TAG(TAG, "alarm_control_panel")
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.