ESPHome 2026.5.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
37 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
38 config.command_topic = false;
39}
41 if (this->binary_sensor_->has_state()) {
42 return this->publish_state(this->binary_sensor_->state);
43 } else {
44 return true;
45 }
46}
49 return true;
50
51 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
52 const char *state_s = state ? "ON" : "OFF";
53 return this->publish(this->get_state_topic_to_(topic_buf), state_s);
54}
55
56} // namespace esphome::mqtt
57
58#endif
59#endif // USE_MQTT
const StringRef & get_name() const
Definition entity_base.h:71
bool has_state() const
void add_on_state_callback(F &&callback)
constexpr const char * c_str() const
Definition string_ref.h:73
Base class for all binary_sensor-type classes.
bool state
The current state of this binary sensor. Also used as the backing storage for StatefulEntityBase.
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.