ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
mqtt_binary_sensor.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3
4#include "mqtt_const.h"
5
6#ifdef USE_MQTT
7#ifdef USE_BINARY_SENSOR
8
9namespace esphome::mqtt {
10
11static const char *const TAG = "mqtt.binary_sensor";
12
14const EntityBase *MQTTBinarySensorComponent::get_entity() const { return this->binary_sensor_; }
15
17 this->binary_sensor_->add_on_state_callback([this](bool state) { this->publish_state(state); });
18}
19
21 ESP_LOGCONFIG(TAG, "MQTT Binary Sensor '%s':", this->binary_sensor_->get_name().c_str());
22 LOG_MQTT_COMPONENT(true, false);
23}
25 : binary_sensor_(binary_sensor) {
27 this->set_custom_state_topic(mqtt::global_mqtt_client->get_availability().topic.c_str());
28 }
29}
30
32 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
33 const auto device_class = this->binary_sensor_->get_device_class_ref();
34 if (!device_class.empty()) {
35 root[MQTT_DEVICE_CLASS] = device_class;
36 }
37 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
42 config.command_topic = false;
43}
45 if (this->binary_sensor_->has_state()) {
46 return this->publish_state(this->binary_sensor_->state);
47 } else {
48 return true;
49 }
50}
53 return true;
54
55 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
56 const char *state_s = state ? "ON" : "OFF";
57 return this->publish(this->get_state_topic_to_(topic_buf), state_s);
58}
59
60} // namespace esphome::mqtt
61
62#endif
63#endif // USE_MQTT
StringRef get_device_class_ref() const
Get the device class as StringRef.
const StringRef & get_name() const
void add_on_state_callback(std::function< void(T)> &&callback)
virtual bool has_state() const
constexpr const char * c_str() const
Definition string_ref.h:73
Base class for all binary_sensor-type classes.
virtual bool is_status_binary_sensor() const
Return whether this binary sensor has outputted a state.
MQTTBinarySensorComponent(binary_sensor::BinarySensor *binary_sensor)
Construct a MQTTBinarySensorComponent.
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
binary_sensor::BinarySensor * binary_sensor_
const Availability & get_availability()
bool publish(const std::string &topic, const std::string &payload)
Send a 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 state
Definition fan.h:2
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
MQTTClientComponent * global_mqtt_client
std::string payload_not_available
Definition mqtt_client.h:64
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.