ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
binary_sensor.cpp
Go to the documentation of this file.
1#include "binary_sensor.h"
4#include "esphome/core/log.h"
5
7
8static const char *const TAG = "binary_sensor";
9
10// Function implementation of LOG_BINARY_SENSOR macro to reduce code size
11void log_binary_sensor(const char *tag, const char *prefix, const char *type, BinarySensor *obj) {
12 if (obj == nullptr) {
13 return;
14 }
15
16 ESP_LOGCONFIG(tag, "%s%s '%s'", prefix, type, obj->get_name().c_str());
17 LOG_ENTITY_DEVICE_CLASS(tag, prefix, *obj);
18}
19
20void BinarySensor::publish_state(bool new_state) {
21#ifdef USE_BINARY_SENSOR_FILTER
22 if (this->filter_list_ == nullptr) {
23#endif
24 this->send_state_internal(new_state);
25#ifdef USE_BINARY_SENSOR_FILTER
26 } else {
27 this->filter_list_->input(new_state);
28 }
29#endif
30}
32 this->invalidate_state();
33 this->publish_state(new_state);
34}
35bool BinarySensor::set_new_state(const optional<bool> &new_state) {
36 if (StatefulEntityBase::set_new_state(new_state)) {
37 // weirdly, this file could be compiled even without USE_BINARY_SENSOR defined
38#if defined(USE_BINARY_SENSOR) && defined(USE_CONTROLLER_REGISTRY)
39 ControllerRegistry::notify_binary_sensor_update(this);
40#endif
41 ESP_LOGV(TAG, "'%s' >> %s", this->get_name().c_str(), ONOFFMAYBE(new_state));
42 return true;
43 }
44 return false;
45}
46
47#ifdef USE_BINARY_SENSOR_FILTER
49 filter->parent_ = this;
50 if (this->filter_list_ == nullptr) {
51 this->filter_list_ = filter;
52 } else {
53 Filter *last_filter = this->filter_list_;
54 while (last_filter->next_ != nullptr)
55 last_filter = last_filter->next_;
56 last_filter->next_ = filter;
57 }
58}
59void BinarySensor::add_filters(std::initializer_list<Filter *> filters) {
60 for (Filter *filter : filters) {
61 this->add_filter(filter);
62 }
63}
64#endif // USE_BINARY_SENSOR_FILTER
65bool BinarySensor::is_status_binary_sensor() const { return false; }
66
67} // namespace esphome::binary_sensor
const StringRef & get_name() const
Definition entity_base.h:71
virtual bool set_new_state(const optional< T > &new_state)
Apply a new state, de-duplicating and firing callbacks as needed.
constexpr const char * c_str() const
Definition string_ref.h:73
Base class for all binary_sensor-type classes.
void add_filters(std::initializer_list< Filter * > filters)
void publish_state(bool new_state)
Publish a new state to the front-end.
void send_state_internal(bool new_state)
void publish_initial_state(bool new_state)
Publish the initial state, this will not make the callback manager send callbacks and is meant only f...
bool set_new_state(const optional< bool > &new_state) override
virtual bool is_status_binary_sensor() const
Return whether this binary sensor has outputted a state.
virtual void input(bool value)
Definition filter.cpp:27
uint16_t type
void log_binary_sensor(const char *tag, const char *prefix, const char *type, BinarySensor *obj)
const char * tag
Definition log.h:74