ESPHome  2022.6.3
ct_clamp_sensor.cpp
Go to the documentation of this file.
1 #include "ct_clamp_sensor.h"
2 
3 #include "esphome/core/log.h"
4 #include <cmath>
5 
6 namespace esphome {
7 namespace ct_clamp {
8 
9 static const char *const TAG = "ct_clamp";
10 
12  LOG_SENSOR("", "CT Clamp Sensor", this);
13  ESP_LOGCONFIG(TAG, " Sample Duration: %.2fs", this->sample_duration_ / 1e3f);
14  LOG_UPDATE_INTERVAL(this);
15 }
16 
18  // Update only starts the sampling phase, in loop() the actual sampling is happening.
19 
20  // Request a high loop() execution interval during sampling phase.
21  this->high_freq_.start();
22 
23  // Set timeout for ending sampling phase
24  this->set_timeout("read", this->sample_duration_, [this]() {
25  this->is_sampling_ = false;
26  this->high_freq_.stop();
27 
28  if (this->num_samples_ == 0) {
29  // Shouldn't happen, but let's not crash if it does.
30  this->publish_state(NAN);
31  return;
32  }
33 
34  const float rms_ac_dc_squared = this->sample_squared_sum_ / this->num_samples_;
35  const float rms_dc = this->sample_sum_ / this->num_samples_;
36  const float rms_ac = std::sqrt(rms_ac_dc_squared - rms_dc * rms_dc);
37  ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA after %d different samples (%d SPS)", this->name_.c_str(), rms_ac,
38  this->num_samples_, 1000 * this->num_samples_ / this->sample_duration_);
39  this->publish_state(rms_ac);
40  });
41 
42  // Set sampling values
43  this->last_value_ = 0.0;
44  this->num_samples_ = 0;
45  this->sample_sum_ = 0.0f;
46  this->sample_squared_sum_ = 0.0f;
47  this->is_sampling_ = true;
48 }
49 
51  if (!this->is_sampling_)
52  return;
53 
54  // Perform a single sample
55  float value = this->source_->sample();
56  if (std::isnan(value))
57  return;
58 
59  // Assuming a sine wave, avoid requesting values faster than the ADC can provide them
60  if (this->last_value_ == value)
61  return;
62  this->last_value_ = value;
63 
64  this->num_samples_++;
65  this->sample_sum_ += value;
66  this->sample_squared_sum_ += value * value;
67 }
68 
69 } // namespace ct_clamp
70 } // namespace esphome
uint32_t sample_duration_
Duration in ms of the sampling phase.
std::string name_
Definition: entity_base.h:54
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:67
HighFrequencyLoopRequester high_freq_
High Frequency loop() requester used during sampling phase.
voltage_sampler::VoltageSampler * source_
The sampling source to read values from.
void start()
Start running the loop continuously.
Definition: helpers.cpp:357
virtual float sample()=0
Get a voltage reading, in V.
float last_value_
The DC offset of the circuit.
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:70
void stop()
Stop running the loop continuously.
Definition: helpers.cpp:363
Definition: a4988.cpp:4