ESPHome 2025.5.0
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 {
10namespace mqtt {
11
12static const char *const TAG = "mqtt.binary_sensor";
13
14std::string MQTTBinarySensorComponent::component_type() const { return "binary_sensor"; }
16
18 this->binary_sensor_->add_on_state_callback([this](bool state) { this->publish_state(state); });
19}
20
22 ESP_LOGCONFIG(TAG, "MQTT Binary Sensor '%s':", this->binary_sensor_->get_name().c_str());
23 LOG_MQTT_COMPONENT(true, false)
24}
26 : binary_sensor_(binary_sensor) {
28 this->set_custom_state_topic(mqtt::global_mqtt_client->get_availability().topic.c_str());
29 }
30}
31
42 if (this->binary_sensor_->has_state()) {
43 return this->publish_state(this->binary_sensor_->state);
44 } else {
45 return true;
46 }
47}
50 return true;
51
52 const char *state_s = state ? "ON" : "OFF";
53 return this->publish(this->get_state_topic_(), state_s);
54}
55
56} // namespace mqtt
57} // namespace esphome
58
59#endif
60#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:68
Base class for all binary_sensor-type classes.
virtual bool has_state() const
Return whether this binary sensor has outputted a state.
bool state
The current reported state of the binary sensor.
void add_on_state_callback(std::function< void(bool)> &&callback)
Add a callback to be notified of state changes.
virtual bool is_status_binary_sensor() const
MQTTBinarySensorComponent(binary_sensor::BinarySensor *binary_sensor)
Construct a MQTTBinarySensorComponent.
const EntityBase * get_entity() const override
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
std::string component_type() const override
binary_sensor::BinarySensor * binary_sensor_
const Availability & get_availability()
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
bool state
Definition fan.h:0
constexpr const char *const MQTT_PAYLOAD_ON
Definition mqtt_const.h:153
constexpr const char *const MQTT_PAYLOAD_OFF
Definition mqtt_const.h:151
MQTTClientComponent * global_mqtt_client
constexpr const char *const MQTT_DEVICE_CLASS
Definition mqtt_const.h:58
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string payload_not_available
Definition mqtt_client.h:61
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.