ESPHome 2025.7.1
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
33 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
34 if (!this->binary_sensor_->get_device_class().empty())
40 config.command_topic = false;
41}
43 if (this->binary_sensor_->has_state()) {
44 return this->publish_state(this->binary_sensor_->state);
45 } else {
46 return true;
47 }
48}
51 return true;
52
53 const char *state_s = state ? "ON" : "OFF";
54 return this->publish(this->get_state_topic_(), state_s);
55}
56
57} // namespace mqtt
58} // namespace esphome
59
60#endif
61#endif // USE_MQTT
std::string get_device_class()
Get the device class, using the manual override if set.
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:69
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.
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:62
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.