ESPHome 2025.8.0
Loading...
Searching...
No Matches
atm90e32.cpp
Go to the documentation of this file.
1#include "atm90e32.h"
2#include <cinttypes>
3#include <cmath>
4#include <numbers>
5#include "esphome/core/log.h"
6
7namespace esphome {
8namespace atm90e32 {
9
10static const char *const TAG = "atm90e32";
12 if (this->get_publish_interval_flag_()) {
13 this->set_publish_interval_flag_(false);
14 for (uint8_t phase = 0; phase < 3; phase++) {
15 if (this->phase_[phase].voltage_sensor_ != nullptr)
16 this->phase_[phase].voltage_ = this->get_phase_voltage_(phase);
17
18 if (this->phase_[phase].current_sensor_ != nullptr)
19 this->phase_[phase].current_ = this->get_phase_current_(phase);
20
21 if (this->phase_[phase].power_sensor_ != nullptr)
22 this->phase_[phase].active_power_ = this->get_phase_active_power_(phase);
23
24 if (this->phase_[phase].power_factor_sensor_ != nullptr)
25 this->phase_[phase].power_factor_ = this->get_phase_power_factor_(phase);
26
27 if (this->phase_[phase].reactive_power_sensor_ != nullptr)
28 this->phase_[phase].reactive_power_ = this->get_phase_reactive_power_(phase);
29
30 if (this->phase_[phase].apparent_power_sensor_ != nullptr)
31 this->phase_[phase].apparent_power_ = this->get_phase_apparent_power_(phase);
32
33 if (this->phase_[phase].forward_active_energy_sensor_ != nullptr)
35
36 if (this->phase_[phase].reverse_active_energy_sensor_ != nullptr)
38
39 if (this->phase_[phase].phase_angle_sensor_ != nullptr)
40 this->phase_[phase].phase_angle_ = this->get_phase_angle_(phase);
41
42 if (this->phase_[phase].harmonic_active_power_sensor_ != nullptr)
44
45 if (this->phase_[phase].peak_current_sensor_ != nullptr)
46 this->phase_[phase].peak_current_ = this->get_phase_peak_current_(phase);
47
48 // After the local store is collected we can publish them trusting they are within +-1 hardware sampling
49 if (this->phase_[phase].voltage_sensor_ != nullptr)
51
52 if (this->phase_[phase].current_sensor_ != nullptr)
54
55 if (this->phase_[phase].power_sensor_ != nullptr)
57
58 if (this->phase_[phase].power_factor_sensor_ != nullptr)
60
61 if (this->phase_[phase].reactive_power_sensor_ != nullptr)
63
64 if (this->phase_[phase].apparent_power_sensor_ != nullptr)
66
67 if (this->phase_[phase].forward_active_energy_sensor_ != nullptr) {
70 }
71
72 if (this->phase_[phase].reverse_active_energy_sensor_ != nullptr) {
75 }
76
77 if (this->phase_[phase].phase_angle_sensor_ != nullptr)
79
80 if (this->phase_[phase].harmonic_active_power_sensor_ != nullptr) {
83 }
84
85 if (this->phase_[phase].peak_current_sensor_ != nullptr)
87 }
88 if (this->freq_sensor_ != nullptr)
90
91 if (this->chip_temperature_sensor_ != nullptr)
93 }
94}
95
97 if (this->read16_(ATM90E32_REGISTER_METEREN) != 1) {
98 this->status_set_warning();
99 return;
100 }
101 this->set_publish_interval_flag_(true);
102 this->status_clear_warning();
103
104#ifdef USE_TEXT_SENSOR
105 this->check_phase_status();
106 this->check_over_current();
107 this->check_freq_status();
108#endif
109}
110
112 this->spi_setup();
113 this->cs_summary_ = this->cs_->dump_summary();
114 const char *cs = this->cs_summary_.c_str();
115
116 uint16_t mmode0 = 0x87; // 3P4W 50Hz
117 uint16_t high_thresh = 0;
118 uint16_t low_thresh = 0;
119
120 if (line_freq_ == 60) {
121 mmode0 |= 1 << 12; // sets 12th bit to 1, 60Hz
122 // for freq threshold registers
123 high_thresh = 6300; // 63.00 Hz
124 low_thresh = 5700; // 57.00 Hz
125 } else {
126 high_thresh = 5300; // 53.00 Hz
127 low_thresh = 4700; // 47.00 Hz
128 }
129
130 if (current_phases_ == 2) {
131 mmode0 |= 1 << 8; // sets 8th bit to 1, 3P3W
132 mmode0 |= 0 << 1; // sets 1st bit to 0, phase b is not counted into the all-phase sum energy/power (P/Q/S)
133 }
134
135 this->write16_(ATM90E32_REGISTER_SOFTRESET, 0x789A, false); // Perform soft reset
136 delay(6); // Wait for the minimum 5ms + 1ms
137 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA); // enable register config access
138 if (!this->validate_spi_read_(0x55AA, "setup()")) {
139 ESP_LOGW(TAG, "Could not initialize ATM90E32 IC, check SPI settings");
140 this->mark_failed();
141 return;
142 }
143
144 this->write16_(ATM90E32_REGISTER_METEREN, 0x0001); // Enable Metering
145 this->write16_(ATM90E32_REGISTER_SAGPEAKDETCFG, 0xFF3F); // Peak Detector time (15:8) 255ms, Sag Period (7:0) 63ms
146 this->write16_(ATM90E32_REGISTER_PLCONSTH, 0x0861); // PL Constant MSB (default) = 140625000
147 this->write16_(ATM90E32_REGISTER_PLCONSTL, 0xC468); // PL Constant LSB (default)
148 this->write16_(ATM90E32_REGISTER_ZXCONFIG, 0xD654); // Zero crossing (ZX2, ZX1, ZX0) pin config
149 this->write16_(ATM90E32_REGISTER_MMODE0, mmode0); // Mode Config (frequency set in main program)
150 this->write16_(ATM90E32_REGISTER_MMODE1, pga_gain_); // PGA Gain Configuration for Current Channels
151 this->write16_(ATM90E32_REGISTER_FREQHITH, high_thresh); // Frequency high threshold
152 this->write16_(ATM90E32_REGISTER_FREQLOTH, low_thresh); // Frequency low threshold
153 this->write16_(ATM90E32_REGISTER_PSTARTTH, 0x1D4C); // All Active Startup Power Threshold - 0.02A/0.00032 = 7500
154 this->write16_(ATM90E32_REGISTER_QSTARTTH, 0x1D4C); // All Reactive Startup Power Threshold - 50%
155 this->write16_(ATM90E32_REGISTER_SSTARTTH, 0x1D4C); // All Reactive Startup Power Threshold - 50%
156 this->write16_(ATM90E32_REGISTER_PPHASETH, 0x02EE); // Each Phase Active Phase Threshold - 0.002A/0.00032 = 750
157 this->write16_(ATM90E32_REGISTER_QPHASETH, 0x02EE); // Each phase Reactive Phase Threshold - 10%
158
159 if (this->enable_offset_calibration_) {
160 // Initialize flash storage for offset calibrations
161 uint32_t o_hash = fnv1_hash(std::string("_offset_calibration_") + this->cs_summary_);
164
165 // Initialize flash storage for power offset calibrations
166 uint32_t po_hash = fnv1_hash(std::string("_power_offset_calibration_") + this->cs_summary_);
169 } else {
170 ESP_LOGI(TAG, "[CALIBRATION][%s] Power & Voltage/Current offset calibration is disabled. Using config file values.",
171 cs);
172 for (uint8_t phase = 0; phase < 3; ++phase) {
173 this->write16_(this->voltage_offset_registers[phase],
174 static_cast<uint16_t>(this->offset_phase_[phase].voltage_offset_));
175 this->write16_(this->current_offset_registers[phase],
176 static_cast<uint16_t>(this->offset_phase_[phase].current_offset_));
177 this->write16_(this->power_offset_registers[phase],
178 static_cast<uint16_t>(this->power_offset_phase_[phase].active_power_offset));
179 this->write16_(this->reactive_power_offset_registers[phase],
180 static_cast<uint16_t>(this->power_offset_phase_[phase].reactive_power_offset));
181 }
182 }
183
184 if (this->enable_gain_calibration_) {
185 // Initialize flash storage for gain calibration
186 uint32_t g_hash = fnv1_hash(std::string("_gain_calibration_") + this->cs_summary_);
189
190 if (!this->using_saved_calibrations_) {
191 for (uint8_t phase = 0; phase < 3; ++phase) {
192 this->write16_(voltage_gain_registers[phase], this->phase_[phase].voltage_gain_);
193 this->write16_(current_gain_registers[phase], this->phase_[phase].ct_gain_);
194 }
195 }
196 } else {
197 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration is disabled. Using config file values.", cs);
198 for (uint8_t phase = 0; phase < 3; ++phase) {
199 this->write16_(voltage_gain_registers[phase], this->phase_[phase].voltage_gain_);
200 this->write16_(current_gain_registers[phase], this->phase_[phase].ct_gain_);
201 }
202 }
203
204 // Sag threshold (78%)
205 uint16_t sagth = calculate_voltage_threshold(line_freq_, this->phase_[0].voltage_gain_, 0.78f);
206 // Overvoltage threshold (122%)
207 uint16_t ovth = calculate_voltage_threshold(line_freq_, this->phase_[0].voltage_gain_, 1.22f);
208
209 // Write to registers
210 this->write16_(ATM90E32_REGISTER_SAGTH, sagth);
211 this->write16_(ATM90E32_REGISTER_OVTH, ovth);
212
213 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000); // end configuration
214}
215
217 const char *cs = this->cs_summary_.c_str();
218
219 bool offset_mismatch = false;
220 bool power_mismatch = false;
221 bool gain_mismatch = false;
222
223 for (uint8_t phase = 0; phase < 3; ++phase) {
224 offset_mismatch |= this->offset_calibration_mismatch_[phase];
225 power_mismatch |= this->power_offset_calibration_mismatch_[phase];
226 gain_mismatch |= this->gain_calibration_mismatch_[phase];
227 }
228
229 if (offset_mismatch) {
230 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
231 ESP_LOGW(TAG,
232 "[CALIBRATION][%s] ===================== Offset mismatch: using flash values =====================", cs);
233 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
234 cs);
235 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
236 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
237 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
238 cs);
239 for (uint8_t phase = 0; phase < 3; ++phase) {
240 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
241 this->config_offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].voltage_offset_,
242 this->config_offset_phase_[phase].current_offset_, this->offset_phase_[phase].current_offset_);
243 }
244 ESP_LOGW(TAG,
245 "[CALIBRATION][%s] ===============================================================================", cs);
246 }
247 if (power_mismatch) {
248 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
249 ESP_LOGW(TAG,
250 "[CALIBRATION][%s] ================= Power offset mismatch: using flash values =================", cs);
251 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
252 cs);
253 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | offset_active_power|offset_reactive_power|", cs);
254 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
255 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
256 cs);
257 for (uint8_t phase = 0; phase < 3; ++phase) {
258 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
259 this->config_power_offset_phase_[phase].active_power_offset,
260 this->power_offset_phase_[phase].active_power_offset,
261 this->config_power_offset_phase_[phase].reactive_power_offset,
262 this->power_offset_phase_[phase].reactive_power_offset);
263 }
264 ESP_LOGW(TAG,
265 "[CALIBRATION][%s] ===============================================================================", cs);
266 }
267 if (gain_mismatch) {
268 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
269 ESP_LOGW(TAG,
270 "[CALIBRATION][%s] ====================== Gain mismatch: using flash values =====================", cs);
271 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
272 cs);
273 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
274 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
275 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
276 cs);
277 for (uint8_t phase = 0; phase < 3; ++phase) {
278 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6u | %6u | %6u | %6u |", cs, 'A' + phase,
279 this->config_gain_phase_[phase].voltage_gain, this->gain_phase_[phase].voltage_gain,
280 this->config_gain_phase_[phase].current_gain, this->gain_phase_[phase].current_gain);
281 }
282 ESP_LOGW(TAG,
283 "[CALIBRATION][%s] ===============================================================================", cs);
284 }
285 if (!this->enable_offset_calibration_) {
286 ESP_LOGI(TAG, "[CALIBRATION][%s] Power & Voltage/Current offset calibration is disabled. Using config file values.",
287 cs);
288 } else if (this->restored_offset_calibration_ && !offset_mismatch) {
289 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
290 ESP_LOGI(TAG, "[CALIBRATION][%s] ============== Restored offset calibration from memory ==============", cs);
291 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
292 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
293 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
294 for (uint8_t phase = 0; phase < 3; phase++) {
295 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
296 this->offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].current_offset_);
297 }
298 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\\n", cs);
299 }
300
301 if (this->restored_power_offset_calibration_ && !power_mismatch) {
302 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
303 ESP_LOGI(TAG, "[CALIBRATION][%s] ============ Restored power offset calibration from memory ============", cs);
304 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
305 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
306 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
307 for (uint8_t phase = 0; phase < 3; phase++) {
308 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
309 this->power_offset_phase_[phase].active_power_offset,
310 this->power_offset_phase_[phase].reactive_power_offset);
311 }
312 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
313 }
314 if (!this->enable_gain_calibration_) {
315 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration is disabled. Using config file values.", cs);
316 } else if (this->restored_gain_calibration_ && !gain_mismatch) {
317 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
318 ESP_LOGI(TAG, "[CALIBRATION][%s] ============ Restoring saved gain calibrations to registers ============", cs);
319 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
320 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
321 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
322 for (uint8_t phase = 0; phase < 3; phase++) {
323 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase,
324 this->gain_phase_[phase].voltage_gain, this->gain_phase_[phase].current_gain);
325 }
326 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\\n", cs);
327 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration loaded and verified successfully.\n", cs);
328 }
329 this->calibration_message_printed_ = true;
330}
331
333 ESP_LOGCONFIG("", "ATM90E32:");
334 LOG_PIN(" CS Pin: ", this->cs_);
335 if (this->is_failed()) {
336 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
337 }
338 LOG_UPDATE_INTERVAL(this);
339 LOG_SENSOR(" ", "Voltage A", this->phase_[PHASEA].voltage_sensor_);
340 LOG_SENSOR(" ", "Current A", this->phase_[PHASEA].current_sensor_);
341 LOG_SENSOR(" ", "Power A", this->phase_[PHASEA].power_sensor_);
342 LOG_SENSOR(" ", "Reactive Power A", this->phase_[PHASEA].reactive_power_sensor_);
343 LOG_SENSOR(" ", "Apparent Power A", this->phase_[PHASEA].apparent_power_sensor_);
344 LOG_SENSOR(" ", "PF A", this->phase_[PHASEA].power_factor_sensor_);
345 LOG_SENSOR(" ", "Active Forward Energy A", this->phase_[PHASEA].forward_active_energy_sensor_);
346 LOG_SENSOR(" ", "Active Reverse Energy A", this->phase_[PHASEA].reverse_active_energy_sensor_);
347 LOG_SENSOR(" ", "Harmonic Power A", this->phase_[PHASEA].harmonic_active_power_sensor_);
348 LOG_SENSOR(" ", "Phase Angle A", this->phase_[PHASEA].phase_angle_sensor_);
349 LOG_SENSOR(" ", "Peak Current A", this->phase_[PHASEA].peak_current_sensor_);
350 LOG_SENSOR(" ", "Voltage B", this->phase_[PHASEB].voltage_sensor_);
351 LOG_SENSOR(" ", "Current B", this->phase_[PHASEB].current_sensor_);
352 LOG_SENSOR(" ", "Power B", this->phase_[PHASEB].power_sensor_);
353 LOG_SENSOR(" ", "Reactive Power B", this->phase_[PHASEB].reactive_power_sensor_);
354 LOG_SENSOR(" ", "Apparent Power B", this->phase_[PHASEB].apparent_power_sensor_);
355 LOG_SENSOR(" ", "PF B", this->phase_[PHASEB].power_factor_sensor_);
356 LOG_SENSOR(" ", "Active Forward Energy B", this->phase_[PHASEB].forward_active_energy_sensor_);
357 LOG_SENSOR(" ", "Active Reverse Energy B", this->phase_[PHASEB].reverse_active_energy_sensor_);
358 LOG_SENSOR(" ", "Harmonic Power B", this->phase_[PHASEB].harmonic_active_power_sensor_);
359 LOG_SENSOR(" ", "Phase Angle B", this->phase_[PHASEB].phase_angle_sensor_);
360 LOG_SENSOR(" ", "Peak Current B", this->phase_[PHASEB].peak_current_sensor_);
361 LOG_SENSOR(" ", "Voltage C", this->phase_[PHASEC].voltage_sensor_);
362 LOG_SENSOR(" ", "Current C", this->phase_[PHASEC].current_sensor_);
363 LOG_SENSOR(" ", "Power C", this->phase_[PHASEC].power_sensor_);
364 LOG_SENSOR(" ", "Reactive Power C", this->phase_[PHASEC].reactive_power_sensor_);
365 LOG_SENSOR(" ", "Apparent Power C", this->phase_[PHASEC].apparent_power_sensor_);
366 LOG_SENSOR(" ", "PF C", this->phase_[PHASEC].power_factor_sensor_);
367 LOG_SENSOR(" ", "Active Forward Energy C", this->phase_[PHASEC].forward_active_energy_sensor_);
368 LOG_SENSOR(" ", "Active Reverse Energy C", this->phase_[PHASEC].reverse_active_energy_sensor_);
369 LOG_SENSOR(" ", "Harmonic Power C", this->phase_[PHASEC].harmonic_active_power_sensor_);
370 LOG_SENSOR(" ", "Phase Angle C", this->phase_[PHASEC].phase_angle_sensor_);
371 LOG_SENSOR(" ", "Peak Current C", this->phase_[PHASEC].peak_current_sensor_);
372 LOG_SENSOR(" ", "Frequency", this->freq_sensor_);
373 LOG_SENSOR(" ", "Chip Temp", this->chip_temperature_sensor_);
377 }
378}
379
381
382// R/C registers can conly be cleared after the LastSPIData register is updated (register 78H)
383// Peakdetect period: 05H. Bit 15:8 are PeakDet_period in ms. 7:0 are Sag_period
384// Default is 143FH (20ms, 63ms)
385uint16_t ATM90E32Component::read16_(uint16_t a_register) {
386 this->enable();
387 delay_microseconds_safe(1); // min delay between CS low and first SCK is 200ns - 1us is plenty
388 uint8_t addrh = (1 << 7) | ((a_register >> 8) & 0x03);
389 uint8_t addrl = (a_register & 0xFF);
390 uint8_t data[4] = {addrh, addrl, 0x00, 0x00};
391 this->transfer_array(data, 4);
392 uint16_t output = encode_uint16(data[2], data[3]);
393 ESP_LOGVV(TAG, "read16_ 0x%04" PRIX16 " output 0x%04" PRIX16, a_register, output);
394 delay_microseconds_safe(1); // allow the last clock to propagate before releasing CS
395 this->disable();
396 delay_microseconds_safe(1); // meet minimum CS high time before next transaction
397 return output;
398}
399
400int ATM90E32Component::read32_(uint16_t addr_h, uint16_t addr_l) {
401 const uint16_t val_h = this->read16_(addr_h);
402 const uint16_t val_l = this->read16_(addr_l);
403 const int32_t val = (val_h << 16) | val_l;
404
405 ESP_LOGVV(TAG,
406 "read32_ addr_h 0x%04" PRIX16 " val_h 0x%04" PRIX16 " addr_l 0x%04" PRIX16 " val_l 0x%04" PRIX16
407 " = %" PRId32,
408 addr_h, val_h, addr_l, val_l, val);
409
410 return val;
411}
412
413void ATM90E32Component::write16_(uint16_t a_register, uint16_t val, bool validate) {
414 ESP_LOGVV(TAG, "write16_ 0x%04" PRIX16 " val 0x%04" PRIX16, a_register, val);
415 uint8_t addrh = ((a_register >> 8) & 0x03);
416 uint8_t addrl = (a_register & 0xFF);
417 uint8_t data[4] = {addrh, addrl, uint8_t((val >> 8) & 0xFF), uint8_t(val & 0xFF)};
418 this->enable();
419 delay_microseconds_safe(1); // ensure CS setup time
420 this->write_array(data, 4);
421 delay_microseconds_safe(1); // allow clock to settle before raising CS
422 this->disable();
423 delay_microseconds_safe(1); // ensure minimum CS high time
424 if (validate)
425 this->validate_spi_read_(val, "write16()");
426}
427
428float ATM90E32Component::get_local_phase_voltage_(uint8_t phase) { return this->phase_[phase].voltage_; }
429
430float ATM90E32Component::get_local_phase_current_(uint8_t phase) { return this->phase_[phase].current_; }
431
432float ATM90E32Component::get_local_phase_active_power_(uint8_t phase) { return this->phase_[phase].active_power_; }
433
435
437
438float ATM90E32Component::get_local_phase_power_factor_(uint8_t phase) { return this->phase_[phase].power_factor_; }
439
443
447
448float ATM90E32Component::get_local_phase_angle_(uint8_t phase) { return this->phase_[phase].phase_angle_; }
449
453
454float ATM90E32Component::get_local_phase_peak_current_(uint8_t phase) { return this->phase_[phase].peak_current_; }
455
457 const uint16_t voltage = this->read16_(ATM90E32_REGISTER_URMS + phase);
458 this->validate_spi_read_(voltage, "get_phase_voltage()");
459 return (float) voltage / 100;
460}
461
463 const uint8_t reads = 10;
464 uint32_t accumulation = 0;
465 uint16_t voltage = 0;
466 for (uint8_t i = 0; i < reads; i++) {
467 voltage = this->read16_(ATM90E32_REGISTER_URMS + phase);
468 this->validate_spi_read_(voltage, "get_phase_voltage_avg_()");
469 accumulation += voltage;
470 }
471 voltage = accumulation / reads;
472 this->phase_[phase].voltage_ = (float) voltage / 100;
473 return this->phase_[phase].voltage_;
474}
475
477 const uint8_t reads = 10;
478 uint32_t accumulation = 0;
479 uint16_t current = 0;
480 for (uint8_t i = 0; i < reads; i++) {
481 current = this->read16_(ATM90E32_REGISTER_IRMS + phase);
482 this->validate_spi_read_(current, "get_phase_current_avg_()");
483 accumulation += current;
484 }
485 current = accumulation / reads;
486 this->phase_[phase].current_ = (float) current / 1000;
487 return this->phase_[phase].current_;
488}
489
491 const uint16_t current = this->read16_(ATM90E32_REGISTER_IRMS + phase);
492 this->validate_spi_read_(current, "get_phase_current_()");
493 return (float) current / 1000;
494}
495
497 const int val = this->read32_(ATM90E32_REGISTER_PMEAN + phase, ATM90E32_REGISTER_PMEANLSB + phase);
498 return val * 0.00032f;
499}
500
502 const int val = this->read32_(ATM90E32_REGISTER_QMEAN + phase, ATM90E32_REGISTER_QMEANLSB + phase);
503 return val * 0.00032f;
504}
505
507 const int val = this->read32_(ATM90E32_REGISTER_SMEAN + phase, ATM90E32_REGISTER_SMEANLSB + phase);
508 return val * 0.00032f;
509}
510
512 uint16_t powerfactor = this->read16_(ATM90E32_REGISTER_PFMEAN + phase); // unsigned to compare to lastspidata
513 this->validate_spi_read_(powerfactor, "get_phase_power_factor_()");
514 return (float) ((int16_t) powerfactor) / 1000; // make it signed again
515}
516
518 const uint16_t val = this->read16_(ATM90E32_REGISTER_APENERGY + phase);
519 if ((UINT32_MAX - this->phase_[phase].cumulative_forward_active_energy_) > val) {
521 } else {
523 }
524 // 0.01CF resolution = 0.003125 Wh per count
525 return ((float) this->phase_[phase].cumulative_forward_active_energy_ * (10.0f / 3200.0f));
526}
527
529 const uint16_t val = this->read16_(ATM90E32_REGISTER_ANENERGY + phase);
530 if (UINT32_MAX - this->phase_[phase].cumulative_reverse_active_energy_ > val) {
532 } else {
534 }
535 // 0.01CF resolution = 0.003125 Wh per count
536 return ((float) this->phase_[phase].cumulative_reverse_active_energy_ * (10.0f / 3200.0f));
537}
538
540 int val = this->read32_(ATM90E32_REGISTER_PMEANH + phase, ATM90E32_REGISTER_PMEANHLSB + phase);
541 return val * 0.00032f;
542}
543
545 uint16_t val = this->read16_(ATM90E32_REGISTER_PANGLE + phase) / 10.0;
546 return (val > 180) ? (float) (val - 360.0f) : (float) val;
547}
548
550 int16_t val = (float) this->read16_(ATM90E32_REGISTER_IPEAK + phase);
551 if (!this->peak_current_signed_)
552 val = std::abs(val);
553 // phase register * phase current gain value / 1000 * 2^13
554 return (val * this->phase_[phase].ct_gain_ / 8192000.0);
555}
556
558 const uint16_t freq = this->read16_(ATM90E32_REGISTER_FREQ);
559 return (float) freq / 100;
560}
561
563 const uint16_t ctemp = this->read16_(ATM90E32_REGISTER_TEMP);
564 return (float) ctemp;
565}
566
568 const char *cs = this->cs_summary_.c_str();
569 if (!this->enable_gain_calibration_) {
570 ESP_LOGW(TAG, "[CALIBRATION][%s] Gain calibration is disabled! Enable it first with enable_gain_calibration: true",
571 cs);
572 return;
573 }
574
575 float ref_voltages[3] = {
576 this->get_reference_voltage(0),
577 this->get_reference_voltage(1),
578 this->get_reference_voltage(2),
579 };
580 float ref_currents[3] = {this->get_reference_current(0), this->get_reference_current(1),
581 this->get_reference_current(2)};
582
583 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
584 ESP_LOGI(TAG, "[CALIBRATION][%s] ========================= Gain Calibration =========================", cs);
585 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
586 ESP_LOGI(
587 TAG,
588 "[CALIBRATION][%s] | Phase | V_meas (V) | I_meas (A) | V_ref | I_ref | V_gain (old→new) | I_gain (old→new) |",
589 cs);
590 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
591
592 for (uint8_t phase = 0; phase < 3; phase++) {
593 float measured_voltage = this->get_phase_voltage_avg_(phase);
594 float measured_current = this->get_phase_current_avg_(phase);
595
596 float ref_voltage = ref_voltages[phase];
597 float ref_current = ref_currents[phase];
598
599 uint16_t current_voltage_gain = this->read16_(voltage_gain_registers[phase]);
600 uint16_t current_current_gain = this->read16_(current_gain_registers[phase]);
601
602 bool did_voltage = false;
603 bool did_current = false;
604
605 // Voltage calibration
606 if (ref_voltage <= 0.0f) {
607 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping voltage calibration: reference voltage is 0.", cs,
608 phase_labels[phase]);
609 } else if (measured_voltage == 0.0f) {
610 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping voltage calibration: measured voltage is 0.", cs,
611 phase_labels[phase]);
612 } else {
613 uint32_t new_voltage_gain = static_cast<uint16_t>((ref_voltage / measured_voltage) * current_voltage_gain);
614 if (new_voltage_gain == 0) {
615 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Voltage gain would be 0. Check reference and measured voltage.", cs,
616 phase_labels[phase]);
617 } else {
618 if (new_voltage_gain >= 65535) {
619 ESP_LOGW(TAG,
620 "[CALIBRATION][%s] Phase %s - Voltage gain exceeds 65535. You may need a higher output voltage "
621 "transformer.",
622 cs, phase_labels[phase]);
623 new_voltage_gain = 65535;
624 }
625 this->gain_phase_[phase].voltage_gain = static_cast<uint16_t>(new_voltage_gain);
626 did_voltage = true;
627 }
628 }
629
630 // Current calibration
631 if (ref_current == 0.0f) {
632 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping current calibration: reference current is 0.", cs,
633 phase_labels[phase]);
634 } else if (measured_current == 0.0f) {
635 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping current calibration: measured current is 0.", cs,
636 phase_labels[phase]);
637 } else {
638 uint32_t new_current_gain = static_cast<uint16_t>((ref_current / measured_current) * current_current_gain);
639 if (new_current_gain == 0) {
640 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Current gain would be 0. Check reference and measured current.", cs,
641 phase_labels[phase]);
642 } else {
643 if (new_current_gain >= 65535) {
644 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Current gain exceeds 65535. You may need to turn up pga gain.",
645 cs, phase_labels[phase]);
646 new_current_gain = 65535;
647 }
648 this->gain_phase_[phase].current_gain = static_cast<uint16_t>(new_current_gain);
649 did_current = true;
650 }
651 }
652
653 // Final row output
654 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %9.2f | %9.4f | %5.2f | %6.4f | %5u → %-5u | %5u → %-5u |", cs,
655 'A' + phase, measured_voltage, measured_current, ref_voltage, ref_current, current_voltage_gain,
656 did_voltage ? this->gain_phase_[phase].voltage_gain : current_voltage_gain, current_current_gain,
657 did_current ? this->gain_phase_[phase].current_gain : current_current_gain);
658 }
659
660 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
661
664 this->verify_gain_writes_();
665}
666
668 const char *cs = this->cs_summary_.c_str();
669 bool success = this->gain_calibration_pref_.save(&this->gain_phase_);
671 if (success) {
672 this->using_saved_calibrations_ = true;
673 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration saved to memory.", cs);
674 } else {
675 this->using_saved_calibrations_ = false;
676 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save gain calibration to memory!", cs);
677 }
678}
679
681 const char *cs = this->cs_summary_.c_str();
682 bool success = this->offset_pref_.save(&this->offset_phase_);
684 if (success) {
685 this->using_saved_calibrations_ = true;
686 this->restored_offset_calibration_ = true;
687 for (bool &phase : this->offset_calibration_mismatch_)
688 phase = false;
689 ESP_LOGI(TAG, "[CALIBRATION][%s] Offset calibration saved to memory.", cs);
690 } else {
691 this->using_saved_calibrations_ = false;
692 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save offset calibration to memory!", cs);
693 }
694}
695
697 const char *cs = this->cs_summary_.c_str();
698 bool success = this->power_offset_pref_.save(&this->power_offset_phase_);
700 if (success) {
701 this->using_saved_calibrations_ = true;
703 for (bool &phase : this->power_offset_calibration_mismatch_)
704 phase = false;
705 ESP_LOGI(TAG, "[CALIBRATION][%s] Power offset calibration saved to memory.", cs);
706 } else {
707 this->using_saved_calibrations_ = false;
708 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save power offset calibration to memory!", cs);
709 }
710}
711
713 const char *cs = this->cs_summary_.c_str();
714 if (!this->enable_offset_calibration_) {
715 ESP_LOGW(TAG,
716 "[CALIBRATION][%s] Offset calibration is disabled! Enable it first with enable_offset_calibration: true",
717 cs);
718 return;
719 }
720
721 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
722 ESP_LOGI(TAG, "[CALIBRATION][%s] ======================== Offset Calibration ========================", cs);
723 ESP_LOGI(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------", cs);
724 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
725 ESP_LOGI(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------", cs);
726
727 for (uint8_t phase = 0; phase < 3; phase++) {
728 int16_t voltage_offset = calibrate_offset(phase, true);
729 int16_t current_offset = calibrate_offset(phase, false);
730
731 this->write_offsets_to_registers_(phase, voltage_offset, current_offset);
732
733 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
734 current_offset);
735 }
736
737 ESP_LOGI(TAG, "[CALIBRATION][%s] ==================================================================\n", cs);
738
740}
741
743 const char *cs = this->cs_summary_.c_str();
744 if (!this->enable_offset_calibration_) {
745 ESP_LOGW(
746 TAG,
747 "[CALIBRATION][%s] Offset power calibration is disabled! Enable it first with enable_offset_calibration: true",
748 cs);
749 return;
750 }
751
752 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
753 ESP_LOGI(TAG, "[CALIBRATION][%s] ===================== Power Offset Calibration =====================", cs);
754 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
755 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
756 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
757
758 for (uint8_t phase = 0; phase < 3; ++phase) {
759 int16_t active_offset = calibrate_power_offset(phase, false);
760 int16_t reactive_offset = calibrate_power_offset(phase, true);
761
762 this->write_power_offsets_to_registers_(phase, active_offset, reactive_offset);
763
764 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
765 reactive_offset);
766 }
767 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
768
770}
771
773 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
774
775 for (int phase = 0; phase < 3; phase++) {
776 this->write16_(voltage_gain_registers[phase], this->gain_phase_[phase].voltage_gain);
777 this->write16_(current_gain_registers[phase], this->gain_phase_[phase].current_gain);
778 }
779
780 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
781}
782
783void ATM90E32Component::write_offsets_to_registers_(uint8_t phase, int16_t voltage_offset, int16_t current_offset) {
784 // Save to runtime
785 this->offset_phase_[phase].voltage_offset_ = voltage_offset;
786 this->phase_[phase].voltage_offset_ = voltage_offset;
787
788 // Save to flash-storable struct
789 this->offset_phase_[phase].current_offset_ = current_offset;
790 this->phase_[phase].current_offset_ = current_offset;
791
792 // Write to registers
793 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
794 this->write16_(voltage_offset_registers[phase], static_cast<uint16_t>(voltage_offset));
795 this->write16_(current_offset_registers[phase], static_cast<uint16_t>(current_offset));
796 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
797}
798
799void ATM90E32Component::write_power_offsets_to_registers_(uint8_t phase, int16_t p_offset, int16_t q_offset) {
800 // Save to runtime
801 this->phase_[phase].active_power_offset_ = p_offset;
802 this->phase_[phase].reactive_power_offset_ = q_offset;
803
804 // Save to flash-storable struct
805 this->power_offset_phase_[phase].active_power_offset = p_offset;
806 this->power_offset_phase_[phase].reactive_power_offset = q_offset;
807
808 // Write to registers
809 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
810 this->write16_(this->power_offset_registers[phase], static_cast<uint16_t>(p_offset));
811 this->write16_(this->reactive_power_offset_registers[phase], static_cast<uint16_t>(q_offset));
812 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
813}
814
816 const char *cs = this->cs_summary_.c_str();
817 for (uint8_t i = 0; i < 3; ++i) {
820 this->gain_phase_[i] = this->config_gain_phase_[i];
821 }
822
823 if (this->gain_calibration_pref_.load(&this->gain_phase_)) {
824 bool all_zero = true;
825 bool same_as_config = true;
826 for (uint8_t phase = 0; phase < 3; ++phase) {
827 const auto &cfg = this->config_gain_phase_[phase];
828 const auto &saved = this->gain_phase_[phase];
829 if (saved.voltage_gain != 0 || saved.current_gain != 0)
830 all_zero = false;
831 if (saved.voltage_gain != cfg.voltage_gain || saved.current_gain != cfg.current_gain)
832 same_as_config = false;
833 }
834
835 if (!all_zero && !same_as_config) {
836 for (uint8_t phase = 0; phase < 3; ++phase) {
837 bool mismatch = false;
838 if (this->has_config_voltage_gain_[phase] &&
839 this->gain_phase_[phase].voltage_gain != this->config_gain_phase_[phase].voltage_gain)
840 mismatch = true;
841 if (this->has_config_current_gain_[phase] &&
842 this->gain_phase_[phase].current_gain != this->config_gain_phase_[phase].current_gain)
843 mismatch = true;
844 if (mismatch)
845 this->gain_calibration_mismatch_[phase] = true;
846 }
847
849
850 if (this->verify_gain_writes_()) {
851 this->using_saved_calibrations_ = true;
852 this->restored_gain_calibration_ = true;
853 return;
854 }
855
856 this->using_saved_calibrations_ = false;
857 ESP_LOGE(TAG, "[CALIBRATION][%s] Gain verification failed! Calibration may not be applied correctly.", cs);
858 }
859 }
860
861 this->using_saved_calibrations_ = false;
862 for (uint8_t i = 0; i < 3; ++i)
863 this->gain_phase_[i] = this->config_gain_phase_[i];
865
866 ESP_LOGW(TAG, "[CALIBRATION][%s] No stored gain calibrations found. Using config file values.", cs);
867}
868
870 const char *cs = this->cs_summary_.c_str();
871 for (uint8_t i = 0; i < 3; ++i)
872 this->config_offset_phase_[i] = this->offset_phase_[i];
873
874 bool have_data = this->offset_pref_.load(&this->offset_phase_);
875 bool all_zero = true;
876 if (have_data) {
877 for (auto &phase : this->offset_phase_) {
878 if (phase.voltage_offset_ != 0 || phase.current_offset_ != 0) {
879 all_zero = false;
880 break;
881 }
882 }
883 }
884
885 if (have_data && !all_zero) {
886 this->restored_offset_calibration_ = true;
887 for (uint8_t phase = 0; phase < 3; phase++) {
888 auto &offset = this->offset_phase_[phase];
889 bool mismatch = false;
890 if (this->has_config_voltage_offset_[phase] &&
891 offset.voltage_offset_ != this->config_offset_phase_[phase].voltage_offset_)
892 mismatch = true;
893 if (this->has_config_current_offset_[phase] &&
894 offset.current_offset_ != this->config_offset_phase_[phase].current_offset_)
895 mismatch = true;
896 if (mismatch)
897 this->offset_calibration_mismatch_[phase] = true;
898 }
899 } else {
900 for (uint8_t phase = 0; phase < 3; phase++)
901 this->offset_phase_[phase] = this->config_offset_phase_[phase];
902 ESP_LOGW(TAG, "[CALIBRATION][%s] No stored offset calibrations found. Using default values.", cs);
903 }
904
905 for (uint8_t phase = 0; phase < 3; phase++) {
906 write_offsets_to_registers_(phase, this->offset_phase_[phase].voltage_offset_,
907 this->offset_phase_[phase].current_offset_);
908 }
909}
910
912 const char *cs = this->cs_summary_.c_str();
913 for (uint8_t i = 0; i < 3; ++i)
915
916 bool have_data = this->power_offset_pref_.load(&this->power_offset_phase_);
917 bool all_zero = true;
918 if (have_data) {
919 for (auto &phase : this->power_offset_phase_) {
920 if (phase.active_power_offset != 0 || phase.reactive_power_offset != 0) {
921 all_zero = false;
922 break;
923 }
924 }
925 }
926
927 if (have_data && !all_zero) {
929 for (uint8_t phase = 0; phase < 3; ++phase) {
930 auto &offset = this->power_offset_phase_[phase];
931 bool mismatch = false;
932 if (this->has_config_active_power_offset_[phase] &&
933 offset.active_power_offset != this->config_power_offset_phase_[phase].active_power_offset)
934 mismatch = true;
935 if (this->has_config_reactive_power_offset_[phase] &&
936 offset.reactive_power_offset != this->config_power_offset_phase_[phase].reactive_power_offset)
937 mismatch = true;
938 if (mismatch)
939 this->power_offset_calibration_mismatch_[phase] = true;
940 }
941 } else {
942 for (uint8_t phase = 0; phase < 3; ++phase)
943 this->power_offset_phase_[phase] = this->config_power_offset_phase_[phase];
944 ESP_LOGW(TAG, "[CALIBRATION][%s] No stored power offsets found. Using default values.", cs);
945 }
946
947 for (uint8_t phase = 0; phase < 3; ++phase) {
948 write_power_offsets_to_registers_(phase, this->power_offset_phase_[phase].active_power_offset,
949 this->power_offset_phase_[phase].reactive_power_offset);
950 }
951}
952
954 const char *cs = this->cs_summary_.c_str();
955 if (!this->using_saved_calibrations_) {
956 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored gain calibrations to clear. Current values:", cs);
957 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
958 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
959 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
960 for (int phase = 0; phase < 3; phase++) {
961 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase,
962 this->gain_phase_[phase].voltage_gain, this->gain_phase_[phase].current_gain);
963 }
964 ESP_LOGI(TAG, "[CALIBRATION][%s] ==========================================================\n", cs);
965 return;
966 }
967
968 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored gain calibrations and restoring config-defined values", cs);
969 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
970 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
971 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
972
973 for (int phase = 0; phase < 3; phase++) {
974 uint16_t voltage_gain = this->phase_[phase].voltage_gain_;
975 uint16_t current_gain = this->phase_[phase].ct_gain_;
976
977 this->config_gain_phase_[phase].voltage_gain = voltage_gain;
978 this->config_gain_phase_[phase].current_gain = current_gain;
979 this->gain_phase_[phase].voltage_gain = voltage_gain;
980 this->gain_phase_[phase].current_gain = current_gain;
981
982 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase, voltage_gain, current_gain);
983 }
984 ESP_LOGI(TAG, "[CALIBRATION][%s] ==========================================================\n", cs);
985
986 GainCalibration zero_gains[3]{{0, 0}, {0, 0}, {0, 0}};
987 bool success = this->gain_calibration_pref_.save(&zero_gains);
989
990 this->using_saved_calibrations_ = false;
991 this->restored_gain_calibration_ = false;
992 for (bool &phase : this->gain_calibration_mismatch_)
993 phase = false;
994
995 if (!success) {
996 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to clear gain calibrations!", cs);
997 }
998
999 this->write_gains_to_registers_(); // Apply them to the chip immediately
1000}
1001
1003 const char *cs = this->cs_summary_.c_str();
1004 if (!this->restored_offset_calibration_) {
1005 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored offset calibrations to clear. Current values:", cs);
1006 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1007 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
1008 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1009 for (uint8_t phase = 0; phase < 3; phase++) {
1010 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
1011 this->offset_phase_[phase].voltage_offset_, this->offset_phase_[phase].current_offset_);
1012 }
1013 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\n", cs);
1014 return;
1015 }
1016
1017 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored offset calibrations and restoring config-defined values", cs);
1018 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1019 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
1020 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1021
1022 for (uint8_t phase = 0; phase < 3; phase++) {
1023 int16_t voltage_offset =
1024 this->has_config_voltage_offset_[phase] ? this->config_offset_phase_[phase].voltage_offset_ : 0;
1025 int16_t current_offset =
1026 this->has_config_current_offset_[phase] ? this->config_offset_phase_[phase].current_offset_ : 0;
1027 this->write_offsets_to_registers_(phase, voltage_offset, current_offset);
1028 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
1029 current_offset);
1030 }
1031 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\n", cs);
1032
1033 OffsetCalibration zero_offsets[3]{{0, 0}, {0, 0}, {0, 0}};
1034 this->offset_pref_.save(&zero_offsets); // Clear stored values in flash
1036
1037 this->restored_offset_calibration_ = false;
1038 for (bool &phase : this->offset_calibration_mismatch_)
1039 phase = false;
1040
1041 ESP_LOGI(TAG, "[CALIBRATION][%s] Offsets cleared.", cs);
1042}
1043
1045 const char *cs = this->cs_summary_.c_str();
1047 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored power offsets to clear. Current values:", cs);
1048 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1049 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
1050 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1051 for (uint8_t phase = 0; phase < 3; phase++) {
1052 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
1053 this->power_offset_phase_[phase].active_power_offset,
1054 this->power_offset_phase_[phase].reactive_power_offset);
1055 }
1056 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
1057 return;
1058 }
1059
1060 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored power offsets and restoring config-defined values", cs);
1061 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1062 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
1063 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1064
1065 for (uint8_t phase = 0; phase < 3; phase++) {
1066 int16_t active_offset =
1068 int16_t reactive_offset = this->has_config_reactive_power_offset_[phase]
1070 : 0;
1071 this->write_power_offsets_to_registers_(phase, active_offset, reactive_offset);
1072 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
1073 reactive_offset);
1074 }
1075 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
1076
1077 PowerOffsetCalibration zero_power_offsets[3]{{0, 0}, {0, 0}, {0, 0}};
1078 this->power_offset_pref_.save(&zero_power_offsets);
1080
1082 for (bool &phase : this->power_offset_calibration_mismatch_)
1083 phase = false;
1084
1085 ESP_LOGI(TAG, "[CALIBRATION][%s] Power offsets cleared.", cs);
1086}
1087
1088int16_t ATM90E32Component::calibrate_offset(uint8_t phase, bool voltage) {
1089 const uint8_t num_reads = 5;
1090 uint64_t total_value = 0;
1091
1092 for (uint8_t i = 0; i < num_reads; ++i) {
1093 uint32_t reading = voltage ? this->read32_(ATM90E32_REGISTER_URMS + phase, ATM90E32_REGISTER_URMSLSB + phase)
1094 : this->read32_(ATM90E32_REGISTER_IRMS + phase, ATM90E32_REGISTER_IRMSLSB + phase);
1095 total_value += reading;
1096 }
1097
1098 const uint32_t average_value = total_value / num_reads;
1099 const uint32_t shifted = average_value >> 7;
1100 const uint32_t offset = ~shifted + 1;
1101 return static_cast<int16_t>(offset); // Takes lower 16 bits
1102}
1103
1104int16_t ATM90E32Component::calibrate_power_offset(uint8_t phase, bool reactive) {
1105 const uint8_t num_reads = 5;
1106 int64_t total_value = 0;
1107
1108 for (uint8_t i = 0; i < num_reads; ++i) {
1109 int32_t reading = reactive ? this->read32_(ATM90E32_REGISTER_QMEAN + phase, ATM90E32_REGISTER_QMEANLSB + phase)
1110 : this->read32_(ATM90E32_REGISTER_PMEAN + phase, ATM90E32_REGISTER_PMEANLSB + phase);
1111 total_value += reading;
1112 }
1113
1114 int32_t average_value = total_value / num_reads;
1115 int32_t power_offset = -average_value;
1116 return static_cast<int16_t>(power_offset); // Takes the lower 16 bits
1117}
1118
1120 const char *cs = this->cs_summary_.c_str();
1121 bool success = true;
1122 for (uint8_t phase = 0; phase < 3; phase++) {
1123 uint16_t read_voltage = this->read16_(voltage_gain_registers[phase]);
1124 uint16_t read_current = this->read16_(current_gain_registers[phase]);
1125
1126 if (read_voltage != this->gain_phase_[phase].voltage_gain ||
1127 read_current != this->gain_phase_[phase].current_gain) {
1128 ESP_LOGE(TAG, "[CALIBRATION][%s] Mismatch detected for Phase %s!", cs, phase_labels[phase]);
1129 success = false;
1130 }
1131 }
1132 return success; // Return true if all writes were successful, false otherwise
1133}
1134
1135#ifdef USE_TEXT_SENSOR
1137 uint16_t state0 = this->read16_(ATM90E32_REGISTER_EMMSTATE0);
1138 uint16_t state1 = this->read16_(ATM90E32_REGISTER_EMMSTATE1);
1139
1140 for (int phase = 0; phase < 3; phase++) {
1141 std::string status;
1142
1143 if (state0 & over_voltage_flags[phase])
1144 status += "Over Voltage; ";
1145 if (state1 & voltage_sag_flags[phase])
1146 status += "Voltage Sag; ";
1147 if (state1 & phase_loss_flags[phase])
1148 status += "Phase Loss; ";
1149
1150 auto *sensor = this->phase_status_text_sensor_[phase];
1151 if (sensor == nullptr)
1152 continue;
1153
1154 if (!status.empty()) {
1155 status.pop_back(); // remove space
1156 status.pop_back(); // remove semicolon
1157 ESP_LOGW(TAG, "%s: %s", sensor->get_name().c_str(), status.c_str());
1158 sensor->publish_state(status);
1159 } else {
1160 sensor->publish_state("Okay");
1161 }
1162 }
1163}
1164
1166 uint16_t state1 = this->read16_(ATM90E32_REGISTER_EMMSTATE1);
1167
1168 std::string freq_status;
1169
1170 if (state1 & ATM90E32_STATUS_S1_FREQHIST) {
1171 freq_status = "HIGH";
1172 } else if (state1 & ATM90E32_STATUS_S1_FREQLOST) {
1173 freq_status = "LOW";
1174 } else {
1175 freq_status = "Normal";
1176 }
1177 if (this->freq_status_text_sensor_ != nullptr) {
1178 if (freq_status == "Normal") {
1179 ESP_LOGD(TAG, "Frequency status: %s", freq_status.c_str());
1180 } else {
1181 ESP_LOGW(TAG, "Frequency status: %s", freq_status.c_str());
1182 }
1183 this->freq_status_text_sensor_->publish_state(freq_status);
1184 }
1185}
1186
1188 constexpr float max_current_threshold = 65.53f;
1189
1190 for (uint8_t phase = 0; phase < 3; phase++) {
1191 float current_val =
1192 this->phase_[phase].current_sensor_ != nullptr ? this->phase_[phase].current_sensor_->state : 0.0f;
1193
1194 if (current_val > max_current_threshold) {
1195 ESP_LOGW(TAG, "Over current detected on Phase %c: %.2f A", 'A' + phase, current_val);
1196 ESP_LOGW(TAG, "You may need to half your gain_ct: value & multiply the current and power values by 2");
1197 if (this->phase_status_text_sensor_[phase] != nullptr) {
1198 this->phase_status_text_sensor_[phase]->publish_state("Over Current; ");
1199 }
1200 }
1201 }
1202}
1203#endif
1204
1205uint16_t ATM90E32Component::calculate_voltage_threshold(int line_freq, uint16_t ugain, float multiplier) {
1206 // this assumes that 60Hz electrical systems use 120V mains,
1207 // which is usually, but not always the case
1208 float nominal_voltage = (line_freq == 60) ? 120.0f : 220.0f;
1209 float target_voltage = nominal_voltage * multiplier;
1210
1211 float peak_01v = target_voltage * 100.0f * std::numbers::sqrt2_v<float>; // convert RMS → peak, scale to 0.01V
1212 float divider = (2.0f * ugain) / 32768.0f;
1213
1214 float threshold = peak_01v / divider;
1215
1216 return static_cast<uint16_t>(threshold);
1217}
1218
1219bool ATM90E32Component::validate_spi_read_(uint16_t expected, const char *context) {
1220 uint16_t last = this->read16_(ATM90E32_REGISTER_LASTSPIDATA);
1221 if (last != expected) {
1222 if (context != nullptr) {
1223 ESP_LOGW(TAG, "[%s] SPI read mismatch: expected 0x%04X, got 0x%04X", context, expected, last);
1224 } else {
1225 ESP_LOGW(TAG, "SPI read mismatch: expected 0x%04X, got 0x%04X", expected, last);
1226 }
1227 return false;
1228 }
1229 return true;
1230}
1231
1232} // namespace atm90e32
1233} // namespace esphome
uint8_t status
Definition bl0942.h:8
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
virtual std::string dump_summary() const =0
float get_local_phase_reactive_power_(uint8_t phase)
Definition atm90e32.cpp:434
float get_phase_forward_active_energy_(uint8_t phase)
Definition atm90e32.cpp:517
float get_phase_current_avg_(uint8_t phase)
Definition atm90e32.cpp:476
float get_local_phase_apparent_power_(uint8_t phase)
Definition atm90e32.cpp:436
void write16_(uint16_t a_register, uint16_t val, bool validate=true)
Definition atm90e32.cpp:413
text_sensor::TextSensor * freq_status_text_sensor_
Definition atm90e32.h:255
ESPPreferenceObject power_offset_pref_
Definition atm90e32.h:248
const uint16_t voltage_gain_registers[3]
Definition atm90e32.h:24
float get_phase_voltage_avg_(uint8_t phase)
Definition atm90e32.cpp:462
void write_power_offsets_to_registers_(uint8_t phase, int16_t p_offset, int16_t q_offset)
Definition atm90e32.cpp:799
const uint16_t current_gain_registers[3]
Definition atm90e32.h:26
float get_reference_voltage(uint8_t phase)
Definition atm90e32.h:110
struct esphome::atm90e32::ATM90E32Component::GainCalibration gain_phase_[3]
const uint16_t current_offset_registers[3]
Definition atm90e32.h:30
static const uint8_t PHASEB
Definition atm90e32.h:20
float get_phase_reverse_active_energy_(uint8_t phase)
Definition atm90e32.cpp:528
float get_local_phase_harmonic_active_power_(uint8_t phase)
Definition atm90e32.cpp:450
float get_phase_angle_(uint8_t phase)
Definition atm90e32.cpp:544
float get_local_phase_current_(uint8_t phase)
Definition atm90e32.cpp:430
bool validate_spi_read_(uint16_t expected, const char *context=nullptr)
const uint16_t reactive_power_offset_registers[3]
Definition atm90e32.h:34
const uint16_t over_voltage_flags[3]
Definition atm90e32.h:36
float get_phase_voltage_(uint8_t phase)
Definition atm90e32.cpp:456
GainCalibration config_gain_phase_[3]
Definition atm90e32.h:238
int16_t calibrate_offset(uint8_t phase, bool voltage)
float get_local_phase_reverse_active_energy_(uint8_t phase)
Definition atm90e32.cpp:444
float get_local_phase_forward_active_energy_(uint8_t phase)
Definition atm90e32.cpp:440
OffsetCalibration config_offset_phase_[3]
Definition atm90e32.h:224
struct esphome::atm90e32::ATM90E32Component::OffsetCalibration offset_phase_[3]
uint16_t calculate_voltage_threshold(int line_freq, uint16_t ugain, float multiplier)
float get_local_phase_power_factor_(uint8_t phase)
Definition atm90e32.cpp:438
float get_phase_reactive_power_(uint8_t phase)
Definition atm90e32.cpp:501
const uint16_t phase_loss_flags[3]
Definition atm90e32.h:40
float get_phase_apparent_power_(uint8_t phase)
Definition atm90e32.cpp:506
float get_local_phase_voltage_(uint8_t phase)
Definition atm90e32.cpp:428
ESPPreferenceObject gain_calibration_pref_
Definition atm90e32.h:249
void write_offsets_to_registers_(uint8_t phase, int16_t voltage_offset, int16_t current_offset)
Definition atm90e32.cpp:783
static const uint8_t PHASEA
Definition atm90e32.h:19
struct esphome::atm90e32::ATM90E32Component::PowerOffsetCalibration power_offset_phase_[3]
float get_reference_current(uint8_t phase)
Definition atm90e32.h:117
float get_phase_peak_current_(uint8_t phase)
Definition atm90e32.cpp:549
float get_phase_harmonic_active_power_(uint8_t phase)
Definition atm90e32.cpp:539
const uint16_t voltage_sag_flags[3]
Definition atm90e32.h:38
float get_phase_active_power_(uint8_t phase)
Definition atm90e32.cpp:496
PowerOffsetCalibration config_power_offset_phase_[3]
Definition atm90e32.h:231
static const uint8_t PHASEC
Definition atm90e32.h:21
const uint16_t power_offset_registers[3]
Definition atm90e32.h:32
float get_setup_priority() const override
Definition atm90e32.cpp:380
uint16_t read16_(uint16_t a_register)
Definition atm90e32.cpp:385
int read32_(uint16_t addr_h, uint16_t addr_l)
Definition atm90e32.cpp:400
sensor::Sensor * chip_temperature_sensor_
Definition atm90e32.h:257
float get_phase_power_factor_(uint8_t phase)
Definition atm90e32.cpp:511
float get_local_phase_angle_(uint8_t phase)
Definition atm90e32.cpp:448
const uint16_t voltage_offset_registers[3]
Definition atm90e32.h:28
text_sensor::TextSensor * phase_status_text_sensor_[3]
Definition atm90e32.h:254
float get_phase_current_(uint8_t phase)
Definition atm90e32.cpp:490
float get_local_phase_peak_current_(uint8_t phase)
Definition atm90e32.cpp:454
void set_publish_interval_flag_(bool flag)
Definition atm90e32.h:172
int16_t calibrate_power_offset(uint8_t phase, bool reactive)
struct esphome::atm90e32::ATM90E32Component::ATM90E32Phase phase_[3]
ESPPreferenceObject offset_pref_
Definition atm90e32.h:247
float get_local_phase_active_power_(uint8_t phase)
Definition atm90e32.cpp:432
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:133
void publish_state(const std::string &state)
mopeka_std_values val[4]
const float IO
For components that represent GPIO pins like PCF8573.
Definition component.cpp:48
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:134
ESPPreferences * global_preferences
void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:611
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:173
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29