ESPHome  2024.3.1
slow_pwm_output.cpp
Go to the documentation of this file.
1 #include "slow_pwm_output.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace slow_pwm {
6 
7 static const char *const TAG = "output.slow_pwm";
8 
10  if (this->pin_)
11  this->pin_->setup();
12  this->turn_off();
13 }
14 
16 void SlowPWMOutput::set_output_state_(bool new_state) {
17  if (this->pin_) {
18  this->pin_->digital_write(new_state);
19  }
20  if (new_state != current_state_) {
21  if (this->pin_) {
22  ESP_LOGV(TAG, "Switching output pin %s to %s", this->pin_->dump_summary().c_str(), ONOFF(new_state));
23  } else {
24  ESP_LOGV(TAG, "Switching to %s", ONOFF(new_state));
25  }
26 
27  if (this->state_change_trigger_) {
28  this->state_change_trigger_->trigger(new_state);
29  }
30  if (new_state) {
31  if (this->turn_on_trigger_)
32  this->turn_on_trigger_->trigger();
33  } else {
34  if (this->turn_off_trigger_)
35  this->turn_off_trigger_->trigger();
36  }
37  current_state_ = new_state;
38  }
39 }
40 
42  uint32_t now = millis();
43  float scaled_state = this->state_ * this->period_;
44 
45  if (now - this->period_start_time_ >= this->period_) {
46  ESP_LOGVV(TAG, "End of period. State: %f, Scaled state: %f", this->state_, scaled_state);
47  this->period_start_time_ += this->period_;
48  }
49 
50  this->set_output_state_(scaled_state > now - this->period_start_time_);
51 }
52 
54  ESP_LOGCONFIG(TAG, "Slow PWM Output:");
55  LOG_PIN(" Pin: ", this->pin_);
56  if (this->state_change_trigger_) {
57  ESP_LOGCONFIG(TAG, " State change automation configured");
58  }
59  if (this->turn_on_trigger_) {
60  ESP_LOGCONFIG(TAG, " Turn on automation configured");
61  }
62  if (this->turn_off_trigger_) {
63  ESP_LOGCONFIG(TAG, " Turn off automation configured");
64  }
65  ESP_LOGCONFIG(TAG, " Period: %d ms", this->period_);
66  ESP_LOGCONFIG(TAG, " Restart cycle on state change: %s", YESNO(this->restart_cycle_on_state_change_));
67  LOG_FLOAT_OUTPUT(this);
68 }
69 
71  this->state_ = state;
73  this->restart_cycle();
74 }
75 
76 } // namespace slow_pwm
77 } // namespace esphome
virtual void digital_write(bool value)=0
void write_state(float state) override
std::unique_ptr< Trigger<> > turn_off_trigger_
std::unique_ptr< Trigger<> > turn_on_trigger_
virtual void turn_off()
Disable this binary output.
Definition: binary_output.h:51
void set_output_state_(bool state)
turn on/off the configured output
virtual void setup()=0
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
virtual std::string dump_summary() const =0
void setup() override
Initialize pin.
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
std::unique_ptr< Trigger< bool > > state_change_trigger_
bool state
Definition: fan.h:34