ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
hbridge_switch.cpp
Go to the documentation of this file.
1#include "hbridge_switch.h"
2#include "esphome/core/log.h"
3
4#include <cinttypes>
5
6namespace esphome::hbridge {
7
8ESPHOME_LOG_TAG(TAG, "switch.hbridge");
9
12 // Like GPIOSwitch does, set the pin state both before and after pin setup()
13 this->on_pin_->digital_write(false);
14 this->on_pin_->setup();
15 this->on_pin_->digital_write(false);
16
17 this->off_pin_->digital_write(false);
18 this->off_pin_->setup();
19 this->off_pin_->digital_write(false);
20
21 this->restore();
22}
23
25 LOG_SWITCH("", "H-Bridge Switch", this);
26 LOG_PIN(" On Pin: ", this->on_pin_);
27 LOG_PIN(" Off Pin: ", this->off_pin_);
28 ESP_LOGCONFIG(TAG, " Pulse length: %" PRId32 " ms", this->pulse_length_);
29 if (this->wait_time_) {
30 ESP_LOGCONFIG(TAG, " Wait time %" PRId32 " ms", this->wait_time_);
31 }
32}
33
35 this->desired_state_ = state;
36 if (!this->timer_running_)
37 this->timer_fn_();
38}
39
41 uint32_t next_timeout = 0;
42
43 while ((uint8_t) this->desired_state_ != this->relay_state_) {
44 switch (this->relay_state_) {
45 case RELAY_STATE_ON:
46 case RELAY_STATE_OFF:
48 if (this->desired_state_) {
49 this->on_pin_->digital_write(true);
51 } else {
52 this->off_pin_->digital_write(true);
54 }
55 next_timeout = this->pulse_length_;
56 if (!this->optimistic_)
57 this->publish_state(this->desired_state_);
58 break;
59
61 this->on_pin_->digital_write(false);
63 if (this->optimistic_)
64 this->publish_state(true);
65 next_timeout = this->wait_time_;
66 break;
67
69 this->off_pin_->digital_write(false);
71 if (this->optimistic_)
72 this->publish_state(false);
73 next_timeout = this->wait_time_;
74 break;
75 }
76
77 if (next_timeout) {
78 this->timer_running_ = true;
79 this->set_timeout(next_timeout, [this]() { this->timer_fn_(); });
80 return;
81 }
82
83 // In the case where ON/OFF state has been reached but we need to
84 // immediately change back again to reach desired_state_, we loop.
85 }
86 this->timer_running_ = false;
87}
88
89} // namespace esphome::hbridge
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
virtual void setup()=0
virtual void digital_write(bool value)=0
void write_state(bool state) override
float get_setup_priority() const override
bool state
The current reported state of the binary sensor.
Definition switch.h:60
void restore()
Drive the switch to the state its restore mode yields, through control(), so inversion and write_stat...
Definition switch.cpp:68
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:75
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "fan.hbridge")
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:43
static void uint32_t