ESPHome 2025.9.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 {
10namespace mqtt {
11
12static const char *const TAG = "mqtt.event";
13
14using namespace esphome::event;
15
17
19 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
20 JsonArray event_types = root[MQTT_EVENT_TYPES].to<JsonArray>();
21 for (const auto &event_type : this->event_->get_event_types())
22 event_types.add(event_type);
23
24 if (!this->event_->get_device_class().empty())
26
27 config.command_topic = false;
28}
29
31 this->event_->add_on_event_callback([this](const std::string &event_type) { this->publish_event_(event_type); });
32}
33
35 ESP_LOGCONFIG(TAG, "MQTT Event '%s': ", this->event_->get_name().c_str());
36 ESP_LOGCONFIG(TAG, "Event Types: ");
37 for (const auto &event_type : this->event_->get_event_types()) {
38 ESP_LOGCONFIG(TAG, "- %s", event_type.c_str());
39 }
40 LOG_MQTT_COMPONENT(true, true);
41}
42
43bool MQTTEventComponent::publish_event_(const std::string &event_type) {
44 return this->publish_json(this->get_state_topic_(), [event_type](JsonObject root) {
45 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
46 root[MQTT_EVENT_TYPE] = event_type;
47 });
48}
49
50std::string MQTTEventComponent::component_type() const { return "event"; }
51const EntityBase *MQTTEventComponent::get_entity() const { return this->event_; }
52
53} // namespace mqtt
54} // namespace esphome
55
56#endif
57#endif // USE_MQTT
std::string get_device_class()
Get the device class, using the manual override if set.
const StringRef & get_name() const
constexpr const char * c_str() const
Definition string_ref.h:69
std::set< std::string > get_event_types() const
Definition event.h:30
void add_on_event_callback(std::function< void(const std::string &event_type)> &&callback)
Definition event.cpp:21
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
std::string component_type() const override
bool publish_event_(const std::string &event_type)
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
const EntityBase * get_entity() const override
MQTTEventComponent(event::Event *event)
constexpr const char *const MQTT_EVENT_TYPES
Definition mqtt_const.h:81
constexpr const char *const MQTT_DEVICE_CLASS
Definition mqtt_const.h:58
constexpr const char *const MQTT_EVENT_TYPE
Definition mqtt_const.h:80
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.