ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
atm90e32.cpp
Go to the documentation of this file.
1#include "atm90e32.h"
2#include <algorithm>
3#include <cinttypes>
4#include <cmath>
5#include <cstring>
6#include <numbers>
8#include "esphome/core/log.h"
9
11
12ESPHOME_LOG_TAG(TAG, "atm90e32");
13
14static const LogString *offset_calibration_name(bool power_offsets) {
15 return power_offsets ? LOG_STR("Power offset") : LOG_STR("Offset");
16}
17
18static uint32_t pref_hash(const char *prefix, const char *name_space) {
19 auto hash = fnv1_hash(prefix);
20 return fnv1_hash_extend(hash, name_space);
21}
22
23template<typename T>
24static int migrate_legacy_pref_if_needed(ESPPreferenceObject &current_pref, ESPPreferenceObject &legacy_pref,
25 T *scratch) {
26 T current{};
27 if (current_pref.load(&current)) {
28 return 0;
29 }
30 if (!legacy_pref.load(scratch)) {
31 return 0;
32 }
33 return current_pref.save(scratch) ? 1 : -1;
34}
35
37 if (this->get_publish_interval_flag_()) {
38 this->set_publish_interval_flag_(false);
39 for (uint8_t phase = 0; phase < 3; phase++) {
40 if (this->phase_[phase].voltage_sensor_ != nullptr)
41 this->phase_[phase].voltage_ = this->get_phase_voltage_(phase);
42
43 if (this->phase_[phase].current_sensor_ != nullptr)
44 this->phase_[phase].current_ = this->get_phase_current_(phase);
45
46 if (this->phase_[phase].power_sensor_ != nullptr)
47 this->phase_[phase].active_power_ = this->get_phase_active_power_(phase);
48
49 if (this->phase_[phase].power_factor_sensor_ != nullptr)
50 this->phase_[phase].power_factor_ = this->get_phase_power_factor_(phase);
51
52 if (this->phase_[phase].reactive_power_sensor_ != nullptr)
53 this->phase_[phase].reactive_power_ = this->get_phase_reactive_power_(phase);
54
55 if (this->phase_[phase].apparent_power_sensor_ != nullptr)
56 this->phase_[phase].apparent_power_ = this->get_phase_apparent_power_(phase);
57
58 if (this->phase_[phase].forward_active_energy_sensor_ != nullptr)
60
61 if (this->phase_[phase].reverse_active_energy_sensor_ != nullptr)
63
64 if (this->phase_[phase].phase_angle_sensor_ != nullptr)
65 this->phase_[phase].phase_angle_ = this->get_phase_angle_(phase);
66
67 if (this->phase_[phase].harmonic_active_power_sensor_ != nullptr)
69
70 if (this->phase_[phase].peak_current_sensor_ != nullptr)
71 this->phase_[phase].peak_current_ = this->get_phase_peak_current_(phase);
72
73 // After the local store is collected we can publish them trusting they are within +-1 hardware sampling
74 PUBLISH_STATE(this->phase_[phase].voltage_sensor_, this->get_local_phase_voltage_(phase));
75
76 PUBLISH_STATE(this->phase_[phase].current_sensor_, this->get_local_phase_current_(phase));
77
78 PUBLISH_STATE(this->phase_[phase].power_sensor_, this->get_local_phase_active_power_(phase));
79
80 PUBLISH_STATE(this->phase_[phase].power_factor_sensor_, this->get_local_phase_power_factor_(phase));
81
82 PUBLISH_STATE(this->phase_[phase].reactive_power_sensor_, this->get_local_phase_reactive_power_(phase));
83
84 PUBLISH_STATE(this->phase_[phase].apparent_power_sensor_, this->get_local_phase_apparent_power_(phase));
85
86 PUBLISH_STATE(this->phase_[phase].forward_active_energy_sensor_,
88
89 PUBLISH_STATE(this->phase_[phase].reverse_active_energy_sensor_,
91
92 PUBLISH_STATE(this->phase_[phase].phase_angle_sensor_, this->get_local_phase_angle_(phase));
93
94 PUBLISH_STATE(this->phase_[phase].harmonic_active_power_sensor_,
96
97 PUBLISH_STATE(this->phase_[phase].peak_current_sensor_, this->get_local_phase_peak_current_(phase));
98 }
99 PUBLISH_STATE(this->freq_sensor_, this->get_frequency_());
100
101 PUBLISH_STATE(this->chip_temperature_sensor_, this->get_chip_temperature_());
102 }
103}
104
106 if (!this->status_comm_result(this->read16_(ATM90E32_REGISTER_METEREN) == 1, nullptr))
107 return;
108 this->set_publish_interval_flag_(true);
109
110#ifdef USE_TEXT_SENSOR
111 this->check_phase_status();
112 this->check_freq_status();
113#endif
114}
115
116void ATM90E32Component::get_cs_summary_(std::span<char, GPIO_SUMMARY_MAX_LEN> buffer) {
117 this->cs_->dump_summary(buffer.data(), buffer.size());
118}
119
121
123 this->spi_setup();
124 this->configure_chip_();
125}
126
128 const char *cs = this->get_calibration_id_();
129 char legacy_cs[GPIO_SUMMARY_MAX_LEN];
130 this->get_cs_summary_(legacy_cs);
131 const bool has_distinct_legacy_namespace = strcmp(cs, legacy_cs) != 0;
132
133 uint16_t mmode0 = 0x87; // 3P4W 50Hz
134
135 if (line_freq_ == 60) {
136 mmode0 |= 1 << 12; // sets 12th bit to 1, 60Hz
137 }
138
139 if (current_phases_ == 2) {
140 mmode0 |= 1 << 8; // sets 8th bit to 1, 3P3W
141 mmode0 |= 0 << 1; // sets 1st bit to 0, phase b is not counted into the all-phase sum energy/power (P/Q/S)
142 }
143
144 this->write16_(ATM90E32_REGISTER_SOFTRESET, 0x789A, false); // Perform soft reset
145 delay(6); // Wait for the minimum 5ms + 1ms
146 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA); // enable register config access
147 if (!this->validate_spi_read_(0x55AA, "setup()")) {
148 ESP_LOGW(TAG, "Could not initialize ATM90E32 IC, check SPI settings");
149 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
150 return;
151 }
152
153 this->write16_(ATM90E32_REGISTER_METEREN, 0x0001); // Enable Metering
154 this->write16_(ATM90E32_REGISTER_SAGPEAKDETCFG, 0xFF3F); // Peak Detector time (15:8) 255ms, Sag Period (7:0) 63ms
155 this->write16_(ATM90E32_REGISTER_PLCONSTH, 0x0861); // PL Constant MSB (default) = 140625000
156 this->write16_(ATM90E32_REGISTER_PLCONSTL, 0xC468); // PL Constant LSB (default)
157 this->write16_(ATM90E32_REGISTER_ZXCONFIG, 0xD654); // Zero crossing (ZX2, ZX1, ZX0) pin config
158 this->write16_(ATM90E32_REGISTER_MMODE0, mmode0); // Mode Config (frequency set in main program)
159 this->write16_(ATM90E32_REGISTER_MMODE1, pga_gain_); // PGA Gain Configuration for Current Channels
160 this->write16_(ATM90E32_REGISTER_PSTARTTH, 0x1D4C); // All Active Startup Power Threshold - 0.02A/0.00032 = 7500
161 this->write16_(ATM90E32_REGISTER_QSTARTTH, 0x1D4C); // All Reactive Startup Power Threshold - 50%
162 this->write16_(ATM90E32_REGISTER_SSTARTTH, 0x1D4C); // All Reactive Startup Power Threshold - 50%
163 this->write16_(ATM90E32_REGISTER_PPHASETH, 0x02EE); // Each Phase Active Phase Threshold - 0.002A/0.00032 = 750
164 this->write16_(ATM90E32_REGISTER_QPHASETH, 0x02EE); // Each phase Reactive Phase Threshold - 10%
165
166 if (this->enable_offset_calibration_) {
167 // Initialize flash storage for offset calibrations
168 uint32_t o_hash = pref_hash("_offset_calibration_", cs);
170 bool migrated_offset = false;
171 if (has_distinct_legacy_namespace) {
172 uint32_t legacy_o_hash = pref_hash("_offset_calibration_", legacy_cs);
173 auto legacy_offset_pref = global_preferences->make_preference<OffsetCalibration[3]>(legacy_o_hash, true);
174 OffsetCalibration offset_data[3]{};
175 int migration_status = migrate_legacy_pref_if_needed(this->offset_pref_, legacy_offset_pref, &offset_data);
176 migrated_offset = migration_status > 0;
177 if (migration_status > 0) {
178 ESP_LOGI(TAG, "[CALIBRATION][%s] Migrated offset calibrations from legacy storage.", cs);
179 } else if (migration_status < 0) {
180 ESP_LOGW(TAG, "[CALIBRATION][%s] Failed to migrate offset calibrations from legacy storage.", cs);
181 }
182 }
183
184 // Initialize flash storage for power offset calibrations
185 uint32_t po_hash = pref_hash("_power_offset_calibration_", cs);
187 bool migrated_power_offset = false;
188 if (has_distinct_legacy_namespace) {
189 uint32_t legacy_po_hash = pref_hash("_power_offset_calibration_", legacy_cs);
190 auto legacy_power_offset_pref = global_preferences->make_preference<OffsetCalibration[3]>(legacy_po_hash, true);
191 OffsetCalibration power_offset_data[3]{};
192 int migration_status =
193 migrate_legacy_pref_if_needed(this->power_offset_pref_, legacy_power_offset_pref, &power_offset_data);
194 migrated_power_offset = migration_status > 0;
195 if (migration_status > 0) {
196 ESP_LOGI(TAG, "[CALIBRATION][%s] Migrated power offset calibrations from legacy storage.", cs);
197 } else if (migration_status < 0) {
198 ESP_LOGW(TAG, "[CALIBRATION][%s] Failed to migrate power offset calibrations from legacy storage.", cs);
199 }
200 }
201
202 if (migrated_offset || migrated_power_offset) {
204 }
205
208 } else {
209 ESP_LOGI(TAG, "[CALIBRATION][%s] Power & Voltage/Current offset calibration is disabled. Using config file values.",
210 cs);
211 for (uint8_t phase = 0; phase < 3; ++phase) {
212 this->write16_(this->voltage_offset_registers[phase],
213 static_cast<uint16_t>(this->offset_phase_[phase].first_offset));
214 this->write16_(this->current_offset_registers[phase],
215 static_cast<uint16_t>(this->offset_phase_[phase].second_offset));
216 this->write16_(this->power_offset_registers[phase],
217 static_cast<uint16_t>(this->power_offset_phase_[phase].first_offset));
218 this->write16_(this->reactive_power_offset_registers[phase],
219 static_cast<uint16_t>(this->power_offset_phase_[phase].second_offset));
220 }
221 }
222
223 if (this->enable_gain_calibration_) {
224 // Initialize flash storage for gain calibration
225 uint32_t g_hash = pref_hash("_gain_calibration_", cs);
227 bool migrated_gain = false;
228 if (has_distinct_legacy_namespace) {
229 uint32_t legacy_g_hash = pref_hash("_gain_calibration_", legacy_cs);
230 auto legacy_gain_calibration_pref = global_preferences->make_preference<GainCalibration[3]>(legacy_g_hash, true);
231 GainCalibration gain_data[3]{};
232 int migration_status =
233 migrate_legacy_pref_if_needed(this->gain_calibration_pref_, legacy_gain_calibration_pref, &gain_data);
234 migrated_gain = migration_status > 0;
235 if (migration_status > 0) {
236 ESP_LOGI(TAG, "[CALIBRATION][%s] Migrated gain calibrations from legacy storage.", cs);
237 } else if (migration_status < 0) {
238 ESP_LOGW(TAG, "[CALIBRATION][%s] Failed to migrate gain calibrations from legacy storage.", cs);
239 }
240 }
241
242 if (migrated_gain) {
244 }
245
247 } else {
248 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration is disabled. Using config file values.", cs);
249 for (uint8_t phase = 0; phase < 3; ++phase) {
250 this->gain_phase_[phase].voltage_gain = this->phase_[phase].voltage_gain_;
251 this->gain_phase_[phase].current_gain = this->phase_[phase].ct_gain_;
252 }
254 }
255
256 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
257 this->write16_(ATM90E32_REGISTER_FREQHITH, this->frequency_high_threshold_);
258 this->write16_(ATM90E32_REGISTER_FREQLOTH, this->frequency_low_threshold_);
259 // SAGTH, OVTH and OITH were written with the gains, by write_gains_to_registers_().
260 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000); // end configuration
261}
262
264 const char *cs = this->get_calibration_id_();
265
266 bool offset_mismatch = false;
267 bool power_mismatch = false;
268 bool gain_mismatch = false;
269
270 for (uint8_t phase = 0; phase < 3; ++phase) {
271 offset_mismatch |= this->offset_calibration_mismatch_[phase];
272 power_mismatch |= this->power_offset_calibration_mismatch_[phase];
273 gain_mismatch |= this->gain_calibration_mismatch_[phase];
274 }
275
276 if (offset_mismatch) {
277 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
278 ESP_LOGW(TAG,
279 "[CALIBRATION][%s] ===================== Offset mismatch: using flash values =====================", cs);
280 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
281 cs);
282 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
283 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
284 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
285 cs);
286 for (uint8_t phase = 0; phase < 3; ++phase) {
287 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
288 this->config_offset_phase_[phase].first_offset, this->offset_phase_[phase].first_offset,
289 this->config_offset_phase_[phase].second_offset, this->offset_phase_[phase].second_offset);
290 }
291 ESP_LOGW(TAG,
292 "[CALIBRATION][%s] ===============================================================================", cs);
293 }
294 if (power_mismatch) {
295 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
296 ESP_LOGW(TAG,
297 "[CALIBRATION][%s] ================= Power offset mismatch: using flash values =================", cs);
298 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
299 cs);
300 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | offset_active_power|offset_reactive_power|", cs);
301 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
302 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
303 cs);
304 for (uint8_t phase = 0; phase < 3; ++phase) {
305 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6d | %6d | %6d | %6d |", cs, 'A' + phase,
306 this->config_power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].first_offset,
307 this->config_power_offset_phase_[phase].second_offset, this->power_offset_phase_[phase].second_offset);
308 }
309 ESP_LOGW(TAG,
310 "[CALIBRATION][%s] ===============================================================================", cs);
311 }
312 if (gain_mismatch) {
313 ESP_LOGW(TAG, "[CALIBRATION][%s] ", cs);
314 ESP_LOGW(TAG,
315 "[CALIBRATION][%s] ====================== Gain mismatch: using flash values =====================", cs);
316 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
317 cs);
318 ESP_LOGW(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
319 ESP_LOGW(TAG, "[CALIBRATION][%s] | | config | flash | config | flash |", cs);
320 ESP_LOGW(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------------------",
321 cs);
322 for (uint8_t phase = 0; phase < 3; ++phase) {
323 ESP_LOGW(TAG, "[CALIBRATION][%s] | %c | %6u | %6u | %6u | %6u |", cs, 'A' + phase,
324 this->config_gain_phase_[phase].voltage_gain, this->gain_phase_[phase].voltage_gain,
325 this->config_gain_phase_[phase].current_gain, this->gain_phase_[phase].current_gain);
326 }
327 ESP_LOGW(TAG,
328 "[CALIBRATION][%s] ===============================================================================", cs);
329 }
330 if (!this->enable_offset_calibration_) {
331 ESP_LOGI(TAG, "[CALIBRATION][%s] Power & Voltage/Current offset calibration is disabled. Using config file values.",
332 cs);
333 } else if (this->restored_offset_calibration_ && !offset_mismatch) {
334 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
335 ESP_LOGI(TAG, "[CALIBRATION][%s] ============== Restored offset calibration from memory ==============", cs);
336 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
337 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
338 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
339 for (uint8_t phase = 0; phase < 3; phase++) {
340 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
341 this->offset_phase_[phase].first_offset, this->offset_phase_[phase].second_offset);
342 }
343 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\\n", cs);
344 }
345
346 if (this->restored_power_offset_calibration_ && !power_mismatch) {
347 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
348 ESP_LOGI(TAG, "[CALIBRATION][%s] ============ Restored power offset calibration from memory ============", cs);
349 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
350 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
351 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
352 for (uint8_t phase = 0; phase < 3; phase++) {
353 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
354 this->power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].second_offset);
355 }
356 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
357 }
358 if (!this->enable_gain_calibration_) {
359 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration is disabled. Using config file values.", cs);
360 } else if (this->restored_gain_calibration_ && !gain_mismatch) {
361 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
362 ESP_LOGI(TAG, "[CALIBRATION][%s] ============ Restoring saved gain calibrations to registers ============", cs);
363 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
364 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
365 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
366 for (uint8_t phase = 0; phase < 3; phase++) {
367 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase,
368 this->gain_phase_[phase].voltage_gain, this->gain_phase_[phase].current_gain);
369 }
370 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\\n", cs);
371 ESP_LOGI(TAG, "[CALIBRATION][%s] Gain calibration loaded and verified successfully.\n", cs);
372 }
373 this->calibration_message_printed_ = true;
374}
375
377 ESP_LOGCONFIG("", "ATM90E32:");
378 LOG_PIN(" CS Pin: ", this->cs_);
379 LOG_UPDATE_INTERVAL(this);
380 LOG_SENSOR(" ", "Voltage A", this->phase_[PHASEA].voltage_sensor_);
381 LOG_SENSOR(" ", "Current A", this->phase_[PHASEA].current_sensor_);
382 LOG_SENSOR(" ", "Power A", this->phase_[PHASEA].power_sensor_);
383 LOG_SENSOR(" ", "Reactive Power A", this->phase_[PHASEA].reactive_power_sensor_);
384 LOG_SENSOR(" ", "Apparent Power A", this->phase_[PHASEA].apparent_power_sensor_);
385 LOG_SENSOR(" ", "PF A", this->phase_[PHASEA].power_factor_sensor_);
386 LOG_SENSOR(" ", "Active Forward Energy A", this->phase_[PHASEA].forward_active_energy_sensor_);
387 LOG_SENSOR(" ", "Active Reverse Energy A", this->phase_[PHASEA].reverse_active_energy_sensor_);
388 LOG_SENSOR(" ", "Harmonic Power A", this->phase_[PHASEA].harmonic_active_power_sensor_);
389 LOG_SENSOR(" ", "Phase Angle A", this->phase_[PHASEA].phase_angle_sensor_);
390 LOG_SENSOR(" ", "Peak Current A", this->phase_[PHASEA].peak_current_sensor_);
391 LOG_SENSOR(" ", "Voltage B", this->phase_[PHASEB].voltage_sensor_);
392 LOG_SENSOR(" ", "Current B", this->phase_[PHASEB].current_sensor_);
393 LOG_SENSOR(" ", "Power B", this->phase_[PHASEB].power_sensor_);
394 LOG_SENSOR(" ", "Reactive Power B", this->phase_[PHASEB].reactive_power_sensor_);
395 LOG_SENSOR(" ", "Apparent Power B", this->phase_[PHASEB].apparent_power_sensor_);
396 LOG_SENSOR(" ", "PF B", this->phase_[PHASEB].power_factor_sensor_);
397 LOG_SENSOR(" ", "Active Forward Energy B", this->phase_[PHASEB].forward_active_energy_sensor_);
398 LOG_SENSOR(" ", "Active Reverse Energy B", this->phase_[PHASEB].reverse_active_energy_sensor_);
399 LOG_SENSOR(" ", "Harmonic Power B", this->phase_[PHASEB].harmonic_active_power_sensor_);
400 LOG_SENSOR(" ", "Phase Angle B", this->phase_[PHASEB].phase_angle_sensor_);
401 LOG_SENSOR(" ", "Peak Current B", this->phase_[PHASEB].peak_current_sensor_);
402 LOG_SENSOR(" ", "Voltage C", this->phase_[PHASEC].voltage_sensor_);
403 LOG_SENSOR(" ", "Current C", this->phase_[PHASEC].current_sensor_);
404 LOG_SENSOR(" ", "Power C", this->phase_[PHASEC].power_sensor_);
405 LOG_SENSOR(" ", "Reactive Power C", this->phase_[PHASEC].reactive_power_sensor_);
406 LOG_SENSOR(" ", "Apparent Power C", this->phase_[PHASEC].apparent_power_sensor_);
407 LOG_SENSOR(" ", "PF C", this->phase_[PHASEC].power_factor_sensor_);
408 LOG_SENSOR(" ", "Active Forward Energy C", this->phase_[PHASEC].forward_active_energy_sensor_);
409 LOG_SENSOR(" ", "Active Reverse Energy C", this->phase_[PHASEC].reverse_active_energy_sensor_);
410 LOG_SENSOR(" ", "Harmonic Power C", this->phase_[PHASEC].harmonic_active_power_sensor_);
411 LOG_SENSOR(" ", "Phase Angle C", this->phase_[PHASEC].phase_angle_sensor_);
412 LOG_SENSOR(" ", "Peak Current C", this->phase_[PHASEC].peak_current_sensor_);
413 LOG_SENSOR(" ", "Frequency", this->freq_sensor_);
414 LOG_SENSOR(" ", "Chip Temp", this->chip_temperature_sensor_);
418 }
419}
420
422
423// R/C registers can conly be cleared after the LastSPIData register is updated (register 78H)
424// Peakdetect period: 05H. Bit 15:8 are PeakDet_period in ms. 7:0 are Sag_period
425// Default is 143FH (20ms, 63ms)
426uint16_t ATM90E32Component::read16_(uint16_t a_register) {
427 this->enable();
428 delay_microseconds_safe(1); // min delay between CS low and first SCK is 200ns - 1us is plenty
429 uint8_t addrh = (1 << 7) | ((a_register >> 8) & 0x03);
430 uint8_t addrl = (a_register & 0xFF);
431 uint8_t data[4] = {addrh, addrl, 0x00, 0x00};
432 this->transfer_array(data, 4);
433 uint16_t output = encode_uint16(data[2], data[3]);
434 ESP_LOGVV(TAG, "read16_ 0x%04" PRIX16 " output 0x%04" PRIX16, a_register, output);
435 delay_microseconds_safe(1); // allow the last clock to propagate before releasing CS
436 this->disable();
437 delay_microseconds_safe(1); // meet minimum CS high time before next transaction
438 return output;
439}
440
441int ATM90E32Component::read32_(uint16_t addr_h, uint16_t addr_l) {
442 const uint16_t val_h = this->read16_(addr_h);
443 const uint16_t val_l = this->read16_(addr_l);
444 const int32_t val = (val_h << 16) | val_l;
445
446 ESP_LOGVV(TAG,
447 "read32_ addr_h 0x%04" PRIX16 " val_h 0x%04" PRIX16 " addr_l 0x%04" PRIX16 " val_l 0x%04" PRIX16
448 " = %" PRId32,
449 addr_h, val_h, addr_l, val_l, val);
450
451 return val;
452}
453
454void ATM90E32Component::write16_(uint16_t a_register, uint16_t val, bool validate) {
455 ESP_LOGVV(TAG, "write16_ 0x%04" PRIX16 " val 0x%04" PRIX16, a_register, val);
456 uint8_t addrh = ((a_register >> 8) & 0x03);
457 uint8_t addrl = (a_register & 0xFF);
458 uint8_t data[4] = {addrh, addrl, uint8_t((val >> 8) & 0xFF), uint8_t(val & 0xFF)};
459 this->enable();
460 delay_microseconds_safe(1); // ensure CS setup time
461 this->write_array(data, 4);
462 delay_microseconds_safe(1); // allow clock to settle before raising CS
463 this->disable();
464 delay_microseconds_safe(1); // ensure minimum CS high time
465 if (validate)
466 this->validate_spi_read_(val, "write16()");
467}
468
469float ATM90E32Component::get_local_phase_voltage_(uint8_t phase) { return this->phase_[phase].voltage_; }
470
471float ATM90E32Component::get_local_phase_current_(uint8_t phase) { return this->phase_[phase].current_; }
472
473float ATM90E32Component::get_local_phase_active_power_(uint8_t phase) { return this->phase_[phase].active_power_; }
474
476
478
479float ATM90E32Component::get_local_phase_power_factor_(uint8_t phase) { return this->phase_[phase].power_factor_; }
480
484
488
489float ATM90E32Component::get_local_phase_angle_(uint8_t phase) { return this->phase_[phase].phase_angle_; }
490
494
495float ATM90E32Component::get_local_phase_peak_current_(uint8_t phase) { return this->phase_[phase].peak_current_; }
496
498 const uint16_t voltage = this->read16_(ATM90E32_REGISTER_URMS + phase);
499 this->validate_spi_read_(voltage, "get_phase_voltage()");
500 return (float) voltage / 100;
501}
502
504 const uint8_t reads = 10;
505 uint32_t accumulation = 0;
506 uint16_t voltage = 0;
507 for (uint8_t i = 0; i < reads; i++) {
508 voltage = this->read16_(ATM90E32_REGISTER_URMS + phase);
509 this->validate_spi_read_(voltage, "get_phase_voltage_avg_()");
510 accumulation += voltage;
511 }
512 voltage = accumulation / reads;
513 this->phase_[phase].voltage_ = (float) voltage / 100;
514 return this->phase_[phase].voltage_;
515}
516
518 const uint8_t reads = 10;
519 uint32_t accumulation = 0;
520 uint16_t current = 0;
521 for (uint8_t i = 0; i < reads; i++) {
522 current = this->read16_(ATM90E32_REGISTER_IRMS + phase);
523 this->validate_spi_read_(current, "get_phase_current_avg_()");
524 accumulation += current;
525 }
526 current = accumulation / reads;
527 this->phase_[phase].current_ = (float) current / 1000;
528 return this->phase_[phase].current_;
529}
530
532 const uint16_t current = this->read16_(ATM90E32_REGISTER_IRMS + phase);
533 this->validate_spi_read_(current, "get_phase_current_()");
534 return (float) current / 1000;
535}
536
538 const int val = this->read32_(ATM90E32_REGISTER_PMEAN + phase, ATM90E32_REGISTER_PMEANLSB + phase);
539 return val * 0.00032f;
540}
541
543 const int val = this->read32_(ATM90E32_REGISTER_QMEAN + phase, ATM90E32_REGISTER_QMEANLSB + phase);
544 return val * 0.00032f;
545}
546
548 const int val = this->read32_(ATM90E32_REGISTER_SMEAN + phase, ATM90E32_REGISTER_SMEANLSB + phase);
549 return val * 0.00032f;
550}
551
553 uint16_t powerfactor = this->read16_(ATM90E32_REGISTER_PFMEAN + phase); // unsigned to compare to lastspidata
554 this->validate_spi_read_(powerfactor, "get_phase_power_factor_()");
555 return (float) ((int16_t) powerfactor) / 1000; // make it signed again
556}
557
559 const uint16_t val = this->read16_(ATM90E32_REGISTER_APENERGY + phase);
560 if ((UINT32_MAX - this->phase_[phase].cumulative_forward_active_energy_) > val) {
562 } else {
564 }
565 // 0.01CF resolution = 0.003125 Wh per count
566 return ((float) this->phase_[phase].cumulative_forward_active_energy_ * (10.0f / 3200.0f));
567}
568
570 const uint16_t val = this->read16_(ATM90E32_REGISTER_ANENERGY + phase);
571 if (UINT32_MAX - this->phase_[phase].cumulative_reverse_active_energy_ > val) {
573 } else {
575 }
576 // 0.01CF resolution = 0.003125 Wh per count
577 return ((float) this->phase_[phase].cumulative_reverse_active_energy_ * (10.0f / 3200.0f));
578}
579
581 int val = this->read32_(ATM90E32_REGISTER_PMEANH + phase, ATM90E32_REGISTER_PMEANHLSB + phase);
582 return val * 0.00032f;
583}
584
586 float val = this->read16_(ATM90E32_REGISTER_PANGLE + phase) / 10.0f;
587 return (val > 180.0f) ? val - 360.0f : val;
588}
589
591 int16_t val = (float) this->read16_(ATM90E32_REGISTER_IPEAK + phase);
592 if (!this->peak_current_signed_)
593 val = std::abs(val);
594 // phase register * phase current gain value / 1000 * 2^13
595 return (val * this->phase_[phase].ct_gain_ / 8192000.0);
596}
597
599 const uint16_t freq = this->read16_(ATM90E32_REGISTER_FREQ);
600 return (float) freq / 100;
601}
602
604 const uint16_t ctemp = this->read16_(ATM90E32_REGISTER_TEMP);
605 return (float) ctemp;
606}
607
609 const LogString *hint, const LogString *hint2) {
610 ESP_LOGI(TAG, "%s", LOG_STR_ARG(entity->get_log_name()));
611 if (hint != nullptr) {
612 ESP_LOGI(TAG, "%s", LOG_STR_ARG(hint));
613 }
614 if (hint2 != nullptr) {
615 ESP_LOGI(TAG, "%s", LOG_STR_ARG(hint2));
616 }
617 (this->*action)();
618}
619
621 const char *cs = this->get_calibration_id_();
622 if (!this->enable_gain_calibration_) {
623 ESP_LOGW(TAG, "[CALIBRATION][%s] Gain calibration is disabled! Enable it first with enable_gain_calibration: true",
624 cs);
625 return;
626 }
627
628 float ref_voltages[3] = {
629 this->get_reference_voltage(0),
630 this->get_reference_voltage(1),
631 this->get_reference_voltage(2),
632 };
633 float ref_currents[3] = {this->get_reference_current(0), this->get_reference_current(1),
634 this->get_reference_current(2)};
635
636 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
637 ESP_LOGI(TAG, "[CALIBRATION][%s] ========================= Gain Calibration =========================", cs);
638 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
639 ESP_LOGI(
640 TAG,
641 "[CALIBRATION][%s] | Phase | V_meas (V) | I_meas (A) | V_ref | I_ref | V_gain (old→new) | I_gain (old→new) |",
642 cs);
643 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
644
645 GainCalibration previous_gains[3] = {this->gain_phase_[0], this->gain_phase_[1], this->gain_phase_[2]};
646
647 for (uint8_t phase = 0; phase < 3; phase++) {
648 float measured_voltage = this->get_phase_voltage_avg_(phase);
649 float measured_current = this->get_phase_current_avg_(phase);
650
651 float ref_voltage = ref_voltages[phase];
652 float ref_current = ref_currents[phase];
653
654 uint16_t current_voltage_gain = this->read16_(voltage_gain_registers[phase]);
655 uint16_t current_current_gain = this->read16_(current_gain_registers[phase]);
656
657 bool did_voltage = false;
658 bool did_current = false;
659
660 // Voltage calibration
661 if (ref_voltage <= 0.0f) {
662 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping voltage calibration: reference voltage is 0.", cs,
663 phase_labels[phase]);
664 } else if (measured_voltage == 0.0f) {
665 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping voltage calibration: measured voltage is 0.", cs,
666 phase_labels[phase]);
667 } else {
668 uint32_t new_voltage_gain = static_cast<uint32_t>((ref_voltage / measured_voltage) * current_voltage_gain);
669 if (new_voltage_gain == 0) {
670 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Voltage gain would be 0. Check reference and measured voltage.", cs,
671 phase_labels[phase]);
672 } else {
673 if (new_voltage_gain >= 65535) {
674 ESP_LOGW(TAG,
675 "[CALIBRATION][%s] Phase %s - Voltage gain exceeds 65535. You may need a higher output voltage "
676 "transformer.",
677 cs, phase_labels[phase]);
678 new_voltage_gain = 65535;
679 }
680 this->gain_phase_[phase].voltage_gain = static_cast<uint16_t>(new_voltage_gain);
681 did_voltage = true;
682 }
683 }
684
685 // Current calibration
686 if (ref_current == 0.0f) {
687 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping current calibration: reference current is 0.", cs,
688 phase_labels[phase]);
689 } else if (measured_current == 0.0f) {
690 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Skipping current calibration: measured current is 0.", cs,
691 phase_labels[phase]);
692 } else {
693 uint32_t new_current_gain = static_cast<uint32_t>((ref_current / measured_current) * current_current_gain);
694 if (new_current_gain == 0) {
695 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Current gain would be 0. Check reference and measured current.", cs,
696 phase_labels[phase]);
697 } else {
698 if (new_current_gain >= 65535) {
699 ESP_LOGW(TAG, "[CALIBRATION][%s] Phase %s - Current gain exceeds 65535. You may need to turn up pga gain.",
700 cs, phase_labels[phase]);
701 new_current_gain = 65535;
702 }
703 this->gain_phase_[phase].current_gain = static_cast<uint16_t>(new_current_gain);
704 did_current = true;
705 }
706 }
707
708 // Final row output
709 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %9.2f | %9.4f | %5.2f | %6.4f | %5u → %-5u | %5u → %-5u |", cs,
710 'A' + phase, measured_voltage, measured_current, ref_voltage, ref_current, current_voltage_gain,
711 did_voltage ? this->gain_phase_[phase].voltage_gain : current_voltage_gain, current_current_gain,
712 did_current ? this->gain_phase_[phase].current_gain : current_current_gain);
713 }
714
715 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
716
718 this->finish_gain_calibration_(previous_gains);
719}
720
721template<typename T, typename F>
722void ATM90E32Component::finish_calibration_(const LogString *name, const LogString *noun,
723 ESPPreferenceObject &preference, const T (&values)[3], bool writes_verified,
724 bool &has_stored, bool &restored, bool (&mismatches)[3], F &&rollback) {
725 static_assert(sizeof(values) == CALIBRATION_PAYLOAD_SIZE, "Calibration payload size mismatch");
726 const char *cs = this->get_calibration_id_();
727 const bool previous_has_stored = has_stored;
728 const bool previous_restored = restored;
729 // Raw stored bytes, re-saved on rollback; all zero (the cleared sentinel) when nothing was stored.
730 uint8_t previous_stored[CALIBRATION_PAYLOAD_SIZE]{};
731 bool attempt = writes_verified;
732 if (writes_verified && previous_has_stored && !preference.load(&previous_stored)) {
733 attempt = false;
734 ESP_LOGE(TAG,
735 "[CALIBRATION][%s] Failed to load stored %s calibration "
736 "values; refusing to overwrite them. "
737 "Clear stored %s calibrations and retry.",
738 cs, LOG_STR_ARG(noun), LOG_STR_ARG(noun));
739 }
740
741 bool persisted = false;
742 if (attempt) {
743 const bool saved = preference.save(&values);
744 const bool synced = global_preferences->sync();
745 persisted = saved && synced;
746 }
747
748 if (persisted) {
749 has_stored = true;
750 restored = true;
751 for (bool &mismatch : mismatches)
752 mismatch = false;
753 ESP_LOGI(TAG, "[CALIBRATION][%s] %s calibration saved to memory. %s calibration completed and verified.", cs,
754 LOG_STR_ARG(name), LOG_STR_ARG(name));
755 return;
756 }
757
758 if (attempt) {
759 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to save %s calibration to memory!", cs, LOG_STR_ARG(noun));
760 }
761
762 const bool rollback_verified = rollback();
763
764 if (attempt) {
765 const bool rollback_saved = preference.save(&previous_stored);
766 const bool rollback_synced = global_preferences->sync();
767 if (!rollback_saved || !rollback_synced) {
768 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to persist restored %s calibration values!", cs, LOG_STR_ARG(noun));
769 }
770 }
771
772 restored = previous_restored && rollback_verified;
773 has_stored = previous_has_stored;
774 if (!rollback_verified) {
775 for (bool &mismatch : mismatches)
776 mismatch = false;
777 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration failed; rollback readback verification failed.", cs,
778 LOG_STR_ARG(name));
779 return;
780 }
781 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration failed; previous values restored.", cs, LOG_STR_ARG(name));
782}
783
785 this->finish_calibration_(LOG_STR("Gain"), LOG_STR("gain"), this->gain_calibration_pref_, this->gain_phase_,
787 this->restored_gain_calibration_, this->gain_calibration_mismatch_, [this, &previous]() {
788 for (uint8_t phase = 0; phase < 3; phase++)
789 this->gain_phase_[phase] = previous[phase];
791 return this->verify_gain_writes_();
792 });
793}
794
798 offset_calibration_name(power_offsets), offset_calibration_name(power_offsets),
799 power_offsets ? this->power_offset_pref_ : this->offset_pref_,
800 power_offsets ? this->power_offset_phase_ : this->offset_phase_, this->verify_offset_writes_(type),
804 [this, &previous, type]() {
805 for (uint8_t phase = 0; phase < 3; phase++)
806 this->write_offsets_to_registers_(phase, previous[phase].first_offset, previous[phase].second_offset, type);
807 return this->verify_offset_writes_(type);
808 });
809}
810
812 const char *cs = this->get_calibration_id_();
813 if (!this->enable_offset_calibration_) {
814 ESP_LOGW(TAG,
815 "[CALIBRATION][%s] Offset calibration is disabled! Enable it first with enable_offset_calibration: true",
816 cs);
817 return;
818 }
819
820 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
821 ESP_LOGI(TAG, "[CALIBRATION][%s] ======================== Offset Calibration ========================", cs);
822 ESP_LOGI(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------", cs);
823 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
824 ESP_LOGI(TAG, "[CALIBRATION][%s] ------------------------------------------------------------------", cs);
825
826 OffsetCalibration previous_offsets[3] = {this->offset_phase_[0], this->offset_phase_[1], this->offset_phase_[2]};
827
828 for (uint8_t phase = 0; phase < 3; phase++) {
829 int16_t voltage_offset = calibrate_offset(phase, true);
830 int16_t current_offset = calibrate_offset(phase, false);
831
832 this->write_offsets_to_registers_(phase, voltage_offset, current_offset,
834
835 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
836 current_offset);
837 }
838
839 ESP_LOGI(TAG, "[CALIBRATION][%s] ==================================================================\n", cs);
840
842}
843
845 const char *cs = this->get_calibration_id_();
846 if (!this->enable_offset_calibration_) {
847 ESP_LOGW(
848 TAG,
849 "[CALIBRATION][%s] Offset power calibration is disabled! Enable it first with enable_offset_calibration: true",
850 cs);
851 return;
852 }
853
854 ESP_LOGI(TAG, "[CALIBRATION][%s] ", cs);
855 ESP_LOGI(TAG, "[CALIBRATION][%s] ===================== Power Offset Calibration =====================", cs);
856 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
857 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
858 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
859
860 OffsetCalibration previous_offsets[3] = {this->power_offset_phase_[0], this->power_offset_phase_[1],
861 this->power_offset_phase_[2]};
862
863 for (uint8_t phase = 0; phase < 3; ++phase) {
864 int16_t active_offset = calibrate_power_offset(phase, false);
865 int16_t reactive_offset = calibrate_power_offset(phase, true);
866
867 this->write_offsets_to_registers_(phase, active_offset, reactive_offset,
869
870 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
871 reactive_offset);
872 }
873 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
874
876}
877
879 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
880
881 for (int phase = 0; phase < 3; phase++) {
882 this->write16_(voltage_gain_registers[phase], this->gain_phase_[phase].voltage_gain);
883 this->write16_(current_gain_registers[phase], this->gain_phase_[phase].current_gain);
884 }
885
886 this->write_thresholds_();
887 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
888}
889
891 static constexpr uint16_t LEGACY_OITH = 0xC000;
892 struct GainRange {
893 uint16_t min{UINT16_MAX};
894 uint16_t max{0};
895 };
896 // Reads back the gain registers of the configured phases; {0, 0} when none are configured.
897 auto read_gain_range = [this](const bool (&configured)[3], const uint16_t (&registers)[3]) {
898 GainRange range;
899 for (uint8_t phase = 0; phase < 3; phase++) {
900 if (configured[phase]) {
901 const uint16_t gain = this->read16_(registers[phase]);
902 range.min = std::min(range.min, gain);
903 range.max = std::max(range.max, gain);
904 }
905 }
906 if (range.max == 0)
907 range.min = 0;
908 return range;
909 };
910 const GainRange voltage = read_gain_range(this->has_config_voltage_gain_, this->voltage_gain_registers);
911 const GainRange current = read_gain_range(this->has_config_current_gain_, this->current_gain_registers);
912 const bool current_configured = !std::isnan(this->threshold_current_peak_a_);
913#ifdef USE_TEXT_SENSOR
914 this->use_voltage_threshold_flags_ = voltage.min == voltage.max;
915 if (!this->use_voltage_threshold_flags_) {
916 ESP_LOGW(TAG, "Phase voltage gains differ; using per-phase RMS voltage alarms");
917 }
918 // The shared OITH is encoded at the highest gain, so a lower-gain phase would flag below current_peak.
919 this->use_current_threshold_flags_ = current.min == current.max;
920 if (!this->use_current_threshold_flags_ && current_configured) {
921 ESP_LOGW(TAG, "Phase current gains differ; using per-phase RMS over-current alarms");
922 }
923#endif
924
925 const uint16_t sagth = calculate_voltage_threshold_from_volts(this->threshold_voltage_sag_v_, voltage.min);
926 const uint16_t ovth = calculate_voltage_threshold_from_volts(this->threshold_voltage_peak_v_, voltage.max);
927 const uint16_t oith = current_configured
929 : LEGACY_OITH;
930 ESP_LOGD(TAG, "Thresholds: SAGTH=0x%04" PRIX16 ", OVTH=0x%04" PRIX16 ", OITH=0x%04" PRIX16, sagth, ovth, oith);
931 this->write16_(ATM90E32_REGISTER_SAGTH, sagth);
932 this->write16_(ATM90E32_REGISTER_OVTH, ovth);
933 this->write16_(ATM90E32_REGISTER_OITH, oith);
934}
935
936void ATM90E32Component::write_offsets_to_registers_(uint8_t phase, int16_t first_offset, int16_t second_offset,
939 OffsetCalibration &offsets = power_offsets ? this->power_offset_phase_[phase] : this->offset_phase_[phase];
940 offsets.first_offset = first_offset;
941 offsets.second_offset = second_offset;
942 if (power_offsets) {
943 this->phase_[phase].active_power_offset_ = first_offset;
944 this->phase_[phase].reactive_power_offset_ = second_offset;
945 } else {
946 this->phase_[phase].voltage_offset_ = first_offset;
947 this->phase_[phase].current_offset_ = second_offset;
948 }
949
950 const uint16_t *first_registers = power_offsets ? this->power_offset_registers : this->voltage_offset_registers;
951 const uint16_t *second_registers =
952 power_offsets ? this->reactive_power_offset_registers : this->current_offset_registers;
953 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x55AA);
954 this->write16_(first_registers[phase], static_cast<uint16_t>(first_offset));
955 this->write16_(second_registers[phase], static_cast<uint16_t>(second_offset));
956 this->write16_(ATM90E32_REGISTER_CFGREGACCEN, 0x0000);
957}
958
960 const char *cs = this->get_calibration_id_();
961 for (uint8_t i = 0; i < 3; ++i) {
964 this->gain_phase_[i] = this->config_gain_phase_[i];
965 }
966
967 const bool have_data = this->gain_calibration_pref_.load(&this->gain_phase_);
968 bool all_zero = true;
969 bool same_as_config = true;
970 if (have_data) {
971 for (uint8_t phase = 0; phase < 3; ++phase) {
972 const auto &config = this->config_gain_phase_[phase];
973 const auto &saved = this->gain_phase_[phase];
974 if (saved.voltage_gain != 0 || saved.current_gain != 0)
975 all_zero = false;
976 if (saved.voltage_gain != config.voltage_gain || saved.current_gain != config.current_gain)
977 same_as_config = false;
978 }
979 }
980
981 // A stored table equal to the config still counts as stored, so it is backed up and can be cleared;
982 // it is only not reported as restored from flash.
983 this->has_stored_gain_calibration_ = have_data && !all_zero;
984 if (!this->has_stored_gain_calibration_) {
985 for (uint8_t phase = 0; phase < 3; ++phase)
986 this->gain_phase_[phase] = this->config_gain_phase_[phase];
987 ESP_LOGW(TAG, "[CALIBRATION][%s] No stored gain calibrations found. Using config file values.", cs);
988 }
989
991 const bool initial_values_verified = this->verify_gain_writes_();
992 if (initial_values_verified) {
993 for (uint8_t phase = 0; phase < 3; ++phase) {
994 this->gain_calibration_mismatch_[phase] =
996 ((this->has_config_voltage_gain_[phase] &&
997 this->gain_phase_[phase].voltage_gain != this->config_gain_phase_[phase].voltage_gain) ||
998 (this->has_config_current_gain_[phase] &&
999 this->gain_phase_[phase].current_gain != this->config_gain_phase_[phase].current_gain));
1000 }
1001 this->restored_gain_calibration_ = this->has_stored_gain_calibration_ && !same_as_config;
1002 return;
1003 }
1004
1005 for (uint8_t phase = 0; phase < 3; ++phase) {
1006 this->gain_calibration_mismatch_[phase] = false;
1007 this->gain_phase_[phase] = this->config_gain_phase_[phase];
1008 }
1010 const bool fallback_verified = this->verify_gain_writes_();
1011 this->restored_gain_calibration_ = false;
1012 if (fallback_verified) {
1013 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore failed verification; config values verified.", cs,
1014 LOG_STR_LITERAL("gain"));
1015 } else {
1016 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore and config fallback both failed verification.", cs,
1017 LOG_STR_LITERAL("gain"));
1018 }
1019}
1020
1022 const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
1023 const char *cs = this->get_calibration_id_();
1024 const LogString *name = power_offsets ? LOG_STR("power offset") : LOG_STR("offset");
1025 OffsetCalibration(*offsets)[3] = power_offsets ? &this->power_offset_phase_ : &this->offset_phase_;
1026 OffsetCalibration(*config_offsets)[3] =
1027 power_offsets ? &this->config_power_offset_phase_ : &this->config_offset_phase_;
1028 ESPPreferenceObject *preference = power_offsets ? &this->power_offset_pref_ : &this->offset_pref_;
1029 bool *has_stored =
1031 bool *restored = power_offsets ? &this->restored_power_offset_calibration_ : &this->restored_offset_calibration_;
1032 bool *mismatches = power_offsets ? this->power_offset_calibration_mismatch_ : this->offset_calibration_mismatch_;
1033 const bool *has_first = power_offsets ? this->has_config_active_power_offset_ : this->has_config_voltage_offset_;
1034 const bool *has_second = power_offsets ? this->has_config_reactive_power_offset_ : this->has_config_current_offset_;
1035
1036 for (uint8_t i = 0; i < 3; ++i)
1037 (*config_offsets)[i] = (*offsets)[i];
1038
1039 const bool have_data = preference->load(offsets);
1040 bool all_zero = true;
1041 if (have_data) {
1042 for (const auto &phase : *offsets) {
1043 if (phase.first_offset != 0 || phase.second_offset != 0) {
1044 all_zero = false;
1045 break;
1046 }
1047 }
1048 }
1049
1050 *has_stored = have_data && !all_zero;
1051
1052 if (!*has_stored) {
1053 for (uint8_t phase = 0; phase < 3; phase++)
1054 (*offsets)[phase] = (*config_offsets)[phase];
1055 ESP_LOGW(TAG, "[CALIBRATION][%s] No stored %s calibrations found. Using default values.", cs, LOG_STR_ARG(name));
1056 }
1057
1058 for (uint8_t phase = 0; phase < 3; phase++) {
1059 this->write_offsets_to_registers_(phase, (*offsets)[phase].first_offset, (*offsets)[phase].second_offset, type);
1060 }
1061 const bool initial_values_verified = this->verify_offset_writes_(type);
1062 if (initial_values_verified) {
1063 for (uint8_t phase = 0; phase < 3; phase++) {
1064 mismatches[phase] =
1065 *has_stored &&
1066 ((has_first[phase] && (*offsets)[phase].first_offset != (*config_offsets)[phase].first_offset) ||
1067 (has_second[phase] && (*offsets)[phase].second_offset != (*config_offsets)[phase].second_offset));
1068 }
1069 *restored = *has_stored;
1070 ESP_LOGI(TAG, "[CALIBRATION][%s] %s calibration values verified.", cs, LOG_STR_ARG(name));
1071 return;
1072 }
1073
1074 for (uint8_t phase = 0; phase < 3; phase++)
1075 mismatches[phase] = false;
1076 for (uint8_t phase = 0; phase < 3; phase++) {
1077 (*offsets)[phase] = (*config_offsets)[phase];
1078 this->write_offsets_to_registers_(phase, (*offsets)[phase].first_offset, (*offsets)[phase].second_offset, type);
1079 }
1080 const bool fallback_verified = this->verify_offset_writes_(type);
1081 *restored = false;
1082 if (fallback_verified) {
1083 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore failed verification; config values verified.", cs,
1084 LOG_STR_ARG(name));
1085 } else {
1086 ESP_LOGE(TAG, "[CALIBRATION][%s] %s calibration restore and config fallback both failed verification.", cs,
1087 LOG_STR_ARG(name));
1088 }
1089}
1090
1091bool ATM90E32Component::clear_calibration_pref_(ESPPreferenceObject &preference, bool &has_stored, bool &restored,
1092 bool (&mismatches)[3]) {
1093 const uint8_t cleared[CALIBRATION_PAYLOAD_SIZE]{};
1094 const bool saved = preference.save(&cleared);
1095 const bool synced = global_preferences->sync();
1096 if (saved && synced)
1097 has_stored = false;
1098 restored = false;
1099 for (bool &mismatch : mismatches)
1100 mismatch = false;
1101 return saved && synced;
1102}
1103
1105 const char *cs = this->get_calibration_id_();
1106 if (!this->has_stored_gain_calibration_) {
1107 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored gain calibrations to clear. Current values:", cs);
1108 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
1109 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
1110 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
1111 for (int phase = 0; phase < 3; phase++) {
1112 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase,
1113 this->gain_phase_[phase].voltage_gain, this->gain_phase_[phase].current_gain);
1114 }
1115 ESP_LOGI(TAG, "[CALIBRATION][%s] ==========================================================\n", cs);
1116 return;
1117 }
1118
1119 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored gain calibrations and restoring config-defined values", cs);
1120 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
1121 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | voltage_gain | current_gain |", cs);
1122 ESP_LOGI(TAG, "[CALIBRATION][%s] ----------------------------------------------------------", cs);
1123
1124 for (int phase = 0; phase < 3; phase++) {
1125 uint16_t voltage_gain = this->phase_[phase].voltage_gain_;
1126 uint16_t current_gain = this->phase_[phase].ct_gain_;
1127
1128 this->config_gain_phase_[phase].voltage_gain = voltage_gain;
1129 this->config_gain_phase_[phase].current_gain = current_gain;
1130 this->gain_phase_[phase].voltage_gain = voltage_gain;
1131 this->gain_phase_[phase].current_gain = current_gain;
1132
1133 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6u | %6u |", cs, 'A' + phase, voltage_gain, current_gain);
1134 }
1135 ESP_LOGI(TAG, "[CALIBRATION][%s] ==========================================================\n", cs);
1136
1139 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to clear gain calibrations!", cs);
1140 }
1141
1142 this->write_gains_to_registers_(); // Apply them to the chip immediately
1143}
1144
1146 const char *cs = this->get_calibration_id_();
1147 if (!this->has_stored_offset_calibration_) {
1148 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored offset calibrations to clear. Current values:", cs);
1149 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1150 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
1151 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1152 for (uint8_t phase = 0; phase < 3; phase++) {
1153 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
1154 this->offset_phase_[phase].first_offset, this->offset_phase_[phase].second_offset);
1155 }
1156 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\n", cs);
1157 return;
1158 }
1159
1160 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored offset calibrations and restoring config-defined values", cs);
1161 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1162 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_voltage | offset_current |", cs);
1163 ESP_LOGI(TAG, "[CALIBRATION][%s] --------------------------------------------------------------", cs);
1164
1165 for (uint8_t phase = 0; phase < 3; phase++) {
1166 int16_t voltage_offset =
1167 this->has_config_voltage_offset_[phase] ? this->config_offset_phase_[phase].first_offset : 0;
1168 int16_t current_offset =
1169 this->has_config_current_offset_[phase] ? this->config_offset_phase_[phase].second_offset : 0;
1170 this->write_offsets_to_registers_(phase, voltage_offset, current_offset,
1172 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, voltage_offset,
1173 current_offset);
1174 }
1175 ESP_LOGI(TAG, "[CALIBRATION][%s] ==============================================================\n", cs);
1176
1179 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to clear offset calibrations!", cs);
1180 } else {
1181 ESP_LOGI(TAG, "[CALIBRATION][%s] Offsets cleared.", cs);
1182 }
1183}
1184
1186 const char *cs = this->get_calibration_id_();
1188 ESP_LOGI(TAG, "[CALIBRATION][%s] No stored power offsets to clear. Current values:", cs);
1189 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1190 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
1191 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1192 for (uint8_t phase = 0; phase < 3; phase++) {
1193 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase,
1194 this->power_offset_phase_[phase].first_offset, this->power_offset_phase_[phase].second_offset);
1195 }
1196 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
1197 return;
1198 }
1199
1200 ESP_LOGI(TAG, "[CALIBRATION][%s] Clearing stored power offsets and restoring config-defined values", cs);
1201 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1202 ESP_LOGI(TAG, "[CALIBRATION][%s] | Phase | offset_active_power | offset_reactive_power |", cs);
1203 ESP_LOGI(TAG, "[CALIBRATION][%s] ---------------------------------------------------------------------", cs);
1204
1205 for (uint8_t phase = 0; phase < 3; phase++) {
1206 int16_t active_offset =
1208 int16_t reactive_offset =
1210 this->write_offsets_to_registers_(phase, active_offset, reactive_offset,
1212 ESP_LOGI(TAG, "[CALIBRATION][%s] | %c | %6d | %6d |", cs, 'A' + phase, active_offset,
1213 reactive_offset);
1214 }
1215 ESP_LOGI(TAG, "[CALIBRATION][%s] =====================================================================\n", cs);
1216
1220 ESP_LOGE(TAG, "[CALIBRATION][%s] Failed to clear power offsets!", cs);
1221 } else {
1222 ESP_LOGI(TAG, "[CALIBRATION][%s] Power offsets cleared.", cs);
1223 }
1224}
1225
1226int16_t ATM90E32Component::calibrate_offset(uint8_t phase, bool voltage) {
1227 const uint8_t num_reads = 5;
1228 uint64_t total_value = 0;
1229
1230 for (uint8_t i = 0; i < num_reads; ++i) {
1231 uint32_t reading = voltage ? this->read32_(ATM90E32_REGISTER_URMS + phase, ATM90E32_REGISTER_URMSLSB + phase)
1232 : this->read32_(ATM90E32_REGISTER_IRMS + phase, ATM90E32_REGISTER_IRMSLSB + phase);
1233 total_value += reading;
1234 }
1235
1236 const uint32_t average_value = total_value / num_reads;
1237 const uint32_t shifted = average_value >> 7;
1238 const uint32_t offset = ~shifted + 1;
1239 return static_cast<int16_t>(offset); // Takes lower 16 bits
1240}
1241
1242int16_t ATM90E32Component::calibrate_power_offset(uint8_t phase, bool reactive) {
1243 const uint8_t num_reads = 5;
1244 int64_t total_value = 0;
1245
1246 for (uint8_t i = 0; i < num_reads; ++i) {
1247 int32_t reading = reactive ? this->read32_(ATM90E32_REGISTER_QMEAN + phase, ATM90E32_REGISTER_QMEANLSB + phase)
1248 : this->read32_(ATM90E32_REGISTER_PMEAN + phase, ATM90E32_REGISTER_PMEANLSB + phase);
1249 total_value += reading;
1250 }
1251
1252 int32_t average_value = total_value / num_reads;
1253 int32_t power_offset = -average_value;
1254 return static_cast<int16_t>(power_offset); // Takes the lower 16 bits
1255}
1256
1258 const char *cs = this->get_calibration_id_();
1259 bool success = true;
1260 for (uint8_t phase = 0; phase < 3; phase++) {
1261 uint16_t read_voltage = this->read16_(voltage_gain_registers[phase]);
1262 uint16_t read_current = this->read16_(current_gain_registers[phase]);
1263
1264 if (read_voltage != this->gain_phase_[phase].voltage_gain ||
1265 read_current != this->gain_phase_[phase].current_gain) {
1266 ESP_LOGE(TAG, "[CALIBRATION][%s] Mismatch detected for Phase %s!", cs, phase_labels[phase]);
1267 success = false;
1268 }
1269 }
1270 return success; // Return true if all writes were successful, false otherwise
1271}
1272
1274 const bool power_offsets = type == OffsetCalibrationType::OFFSET_CALIBRATION_TYPE_POWER;
1275 const char *cs = this->get_calibration_id_();
1276 const LogString *name = offset_calibration_name(power_offsets);
1277 const LogString *first_name = power_offsets ? LOG_STR("active") : LOG_STR("voltage");
1278 const LogString *second_name = power_offsets ? LOG_STR("reactive") : LOG_STR("current");
1279 const OffsetCalibration *offsets = power_offsets ? this->power_offset_phase_ : this->offset_phase_;
1280 const uint16_t *first_registers = power_offsets ? this->power_offset_registers : this->voltage_offset_registers;
1281 const uint16_t *second_registers =
1282 power_offsets ? this->reactive_power_offset_registers : this->current_offset_registers;
1283 bool success = true;
1284 for (uint8_t phase = 0; phase < 3; phase++) {
1285 const uint16_t first = this->read16_(first_registers[phase]);
1286 const uint16_t second = this->read16_(second_registers[phase]);
1287 if (!offset_register_value_matches(first, offsets[phase].first_offset) ||
1288 !offset_register_value_matches(second, offsets[phase].second_offset)) {
1289 ESP_LOGE(TAG, "[CALIBRATION][%s] %s readback failed for Phase %s: %s %d/%d, %s %d/%d.", cs, LOG_STR_ARG(name),
1290 phase_labels[phase], LOG_STR_ARG(first_name), static_cast<int16_t>(first), offsets[phase].first_offset,
1291 LOG_STR_ARG(second_name), static_cast<int16_t>(second), offsets[phase].second_offset);
1292 success = false;
1293 }
1294 }
1295 return success;
1296}
1297
1298#ifdef USE_TEXT_SENSOR
1300 static constexpr uint16_t OVER_CURRENT_FLAGS[3] = {ATM90E32_STATUS_S0_OIPHASEAST, ATM90E32_STATUS_S0_OIPHASEBST,
1301 ATM90E32_STATUS_S0_OIPHASECST};
1302 static constexpr float LEGACY_OVER_CURRENT_A = 65.53f;
1303 uint16_t state0 = this->read16_(ATM90E32_REGISTER_EMMSTATE0);
1304 uint16_t state1 = this->read16_(ATM90E32_REGISTER_EMMSTATE1);
1305 const bool current_configured = !std::isnan(this->threshold_current_peak_a_);
1306 const float current_limit = current_configured ? this->threshold_current_peak_a_ : LEGACY_OVER_CURRENT_A;
1307
1308 for (int phase = 0; phase < 3; phase++) {
1309 auto *sensor = this->phase_status_text_sensor_[phase];
1310 if (sensor == nullptr)
1311 continue;
1312
1313 char status[sizeof("Over Current; Over Voltage; Voltage Sag; Phase Loss; ")];
1314 size_t length = 0;
1315 bool over_voltage = state0 & this->over_voltage_flags[phase];
1316 bool voltage_sag = state1 & this->voltage_sag_flags[phase];
1317 if (!this->use_voltage_threshold_flags_) {
1318 const float voltage = this->get_phase_voltage_(phase);
1319 over_voltage = voltage > this->threshold_voltage_peak_v_;
1320 voltage_sag = voltage < this->threshold_voltage_sag_v_;
1321 }
1322
1323 const float current = this->has_config_current_gain_[phase] ? this->get_phase_current_(phase) : 0.0f;
1324 if ((current_configured && this->use_current_threshold_flags_ && (state0 & OVER_CURRENT_FLAGS[phase])) ||
1325 current > current_limit)
1326 length = buf_append_str(status, sizeof(status), length, "Over Current; ");
1327 if (over_voltage)
1328 length = buf_append_str(status, sizeof(status), length, "Over Voltage; ");
1329 if (voltage_sag)
1330 length = buf_append_str(status, sizeof(status), length, "Voltage Sag; ");
1331 if (state1 & this->phase_loss_flags[phase])
1332 length = buf_append_str(status, sizeof(status), length, "Phase Loss; ");
1333
1334 if (length != 0) {
1335 length -= 2; // Remove the trailing separator.
1336 status[length] = '\0';
1337 ESP_LOGW(TAG, "%s: %s", LOG_STR_ARG(sensor->get_log_name()), status);
1338 sensor->publish_state(status, length);
1339 } else {
1340 sensor->publish_state("Okay");
1341 }
1342 }
1343}
1344
1346 uint16_t state1 = this->read16_(ATM90E32_REGISTER_EMMSTATE1);
1347
1348 std::string freq_status;
1349
1350 if (state1 & ATM90E32_STATUS_S1_FREQHIST) {
1351 freq_status = "HIGH";
1352 } else if (state1 & ATM90E32_STATUS_S1_FREQLOST) {
1353 freq_status = "LOW";
1354 } else {
1355 freq_status = "Normal";
1356 }
1357 if (this->freq_status_text_sensor_ != nullptr) {
1358 if (freq_status == "Normal") {
1359 ESP_LOGD(TAG, "Frequency status: %s", freq_status.c_str());
1360 } else {
1361 ESP_LOGW(TAG, "Frequency status: %s", freq_status.c_str());
1362 }
1363 this->freq_status_text_sensor_->publish_state(freq_status);
1364 }
1365}
1366
1367#endif
1368
1369static uint16_t encode_threshold(float value) {
1370 if (!std::isfinite(value) || value > UINT16_MAX) {
1371 ESP_LOGW(TAG, "Threshold exceeds the 16-bit register range; clamping to 65535");
1372 return UINT16_MAX;
1373 }
1374 return static_cast<uint16_t>(std::round(std::max(value, 0.0f)));
1375}
1376
1377// Datasheet equation (section "Power Quality Monitoring"): xxThRegValue =
1378// RmsRegValue * sqrt(2) / (VIgain / 2^14). RmsRegValue is in 0.01V for voltage and 0.001A for current.
1379static uint16_t calculate_threshold(float rms, float scale, uint16_t gain) {
1380 if (gain == 0)
1381 return 0;
1382 return encode_threshold(rms * scale * std::numbers::sqrt2_v<float> / (gain / 16384.0f));
1383}
1384
1385uint16_t ATM90E32Component::calculate_voltage_threshold_from_volts(float voltage_rms, uint16_t ugain) {
1386 return calculate_threshold(voltage_rms, 100.0f, ugain);
1387}
1388
1389uint16_t ATM90E32Component::calculate_current_threshold_from_amps(float current_rms, uint16_t igain) {
1390 return calculate_threshold(current_rms, 1000.0f, igain);
1391}
1392
1393bool ATM90E32Component::validate_spi_read_(uint16_t expected, const char *context) {
1394 uint16_t last = this->read16_(ATM90E32_REGISTER_LASTSPIDATA);
1395 if (last != expected) {
1396 if (context != nullptr) {
1397 ESP_LOGW(TAG, "[%s] SPI read mismatch: expected 0x%04X, got 0x%04X", context, expected, last);
1398 } else {
1399 ESP_LOGW(TAG, "SPI read mismatch: expected 0x%04X, got 0x%04X", expected, last);
1400 }
1401 return false;
1402 }
1403 return true;
1404}
1405
1406} // namespace esphome::atm90e32
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
virtual size_t dump_summary(char *buffer, size_t len) const
Write a summary of this pin to the provided buffer.
Definition gpio_pin.h:126
float get_local_phase_reactive_power_(uint8_t phase)
Definition atm90e32.cpp:475
float get_phase_forward_active_energy_(uint8_t phase)
Definition atm90e32.cpp:558
OffsetCalibration config_power_offset_phase_[3]
Definition atm90e32.h:270
float get_phase_current_avg_(uint8_t phase)
Definition atm90e32.cpp:517
float get_local_phase_apparent_power_(uint8_t phase)
Definition atm90e32.cpp:477
void write16_(uint16_t a_register, uint16_t val, bool validate=true)
Definition atm90e32.cpp:454
void finish_gain_calibration_(const GainCalibration(&previous)[3])
Definition atm90e32.cpp:784
ESPPreferenceObject power_offset_pref_
Definition atm90e32.h:283
const uint16_t voltage_gain_registers[3]
Definition atm90e32.h:56
void restore_offset_calibrations_(OffsetCalibrationType type)
float get_phase_voltage_avg_(uint8_t phase)
Definition atm90e32.cpp:503
const uint16_t current_gain_registers[3]
Definition atm90e32.h:58
float get_reference_voltage(uint8_t phase)
Definition atm90e32.h:149
void press_calibration_button(EntityBase *entity, void(ATM90E32Component::*action)(), const LogString *hint=nullptr, const LogString *hint2=nullptr)
Definition atm90e32.cpp:608
const uint16_t current_offset_registers[3]
Definition atm90e32.h:62
static const uint8_t PHASEB
Definition atm90e32.h:52
float get_phase_reverse_active_energy_(uint8_t phase)
Definition atm90e32.cpp:569
float get_local_phase_harmonic_active_power_(uint8_t phase)
Definition atm90e32.cpp:491
float get_phase_angle_(uint8_t phase)
Definition atm90e32.cpp:585
float get_local_phase_current_(uint8_t phase)
Definition atm90e32.cpp:471
bool validate_spi_read_(uint16_t expected, const char *context=nullptr)
const uint16_t reactive_power_offset_registers[3]
Definition atm90e32.h:66
const uint16_t over_voltage_flags[3]
Definition atm90e32.h:68
float get_phase_voltage_(uint8_t phase)
Definition atm90e32.cpp:497
GainCalibration config_gain_phase_[3]
Definition atm90e32.h:273
int16_t calibrate_offset(uint8_t phase, bool voltage)
float get_local_phase_reverse_active_energy_(uint8_t phase)
Definition atm90e32.cpp:485
float get_local_phase_forward_active_energy_(uint8_t phase)
Definition atm90e32.cpp:481
OffsetCalibration config_offset_phase_[3]
Definition atm90e32.h:268
static uint16_t calculate_voltage_threshold_from_volts(float voltage_rms, uint16_t ugain)
float get_local_phase_power_factor_(uint8_t phase)
Definition atm90e32.cpp:479
float get_phase_reactive_power_(uint8_t phase)
Definition atm90e32.cpp:542
const uint16_t phase_loss_flags[3]
Definition atm90e32.h:72
float get_phase_apparent_power_(uint8_t phase)
Definition atm90e32.cpp:547
float get_local_phase_voltage_(uint8_t phase)
Definition atm90e32.cpp:469
ESPPreferenceObject gain_calibration_pref_
Definition atm90e32.h:284
static const uint8_t PHASEA
Definition atm90e32.h:51
float get_reference_current(uint8_t phase)
Definition atm90e32.h:156
float get_phase_peak_current_(uint8_t phase)
Definition atm90e32.cpp:590
void finish_offset_calibration_(const OffsetCalibration(&previous)[3], OffsetCalibrationType type)
Definition atm90e32.cpp:795
float get_phase_harmonic_active_power_(uint8_t phase)
Definition atm90e32.cpp:580
const uint16_t voltage_sag_flags[3]
Definition atm90e32.h:70
float get_phase_active_power_(uint8_t phase)
Definition atm90e32.cpp:537
void get_cs_summary_(std::span< char, GPIO_SUMMARY_MAX_LEN > buffer)
Definition atm90e32.cpp:116
static const uint8_t PHASEC
Definition atm90e32.h:53
const uint16_t power_offset_registers[3]
Definition atm90e32.h:64
float get_setup_priority() const override
Definition atm90e32.cpp:421
uint16_t read16_(uint16_t a_register)
Definition atm90e32.cpp:426
int read32_(uint16_t addr_h, uint16_t addr_l)
Definition atm90e32.cpp:441
void write_offsets_to_registers_(uint8_t phase, int16_t first_offset, int16_t second_offset, OffsetCalibrationType type)
Definition atm90e32.cpp:936
float get_phase_power_factor_(uint8_t phase)
Definition atm90e32.cpp:552
OffsetCalibration power_offset_phase_[3]
Definition atm90e32.h:269
float get_local_phase_angle_(uint8_t phase)
Definition atm90e32.cpp:489
const uint16_t voltage_offset_registers[3]
Definition atm90e32.h:60
OffsetCalibration offset_phase_[3]
Definition atm90e32.h:267
bool clear_calibration_pref_(ESPPreferenceObject &preference, bool &has_stored, bool &restored, bool(&mismatches)[3])
static uint16_t calculate_current_threshold_from_amps(float current_rms, uint16_t igain)
text_sensor::TextSensor * phase_status_text_sensor_[3]
Definition atm90e32.h:289
float get_phase_current_(uint8_t phase)
Definition atm90e32.cpp:531
float get_local_phase_peak_current_(uint8_t phase)
Definition atm90e32.cpp:495
void set_publish_interval_flag_(bool flag)
Definition atm90e32.h:209
int16_t calibrate_power_offset(uint8_t phase, bool reactive)
struct esphome::atm90e32::ATM90E32Component::ATM90E32Phase phase_[3]
bool verify_offset_writes_(OffsetCalibrationType type)
ESPPreferenceObject offset_pref_
Definition atm90e32.h:282
void finish_calibration_(const LogString *name, const LogString *noun, ESPPreferenceObject &preference, const T(&values)[3], bool writes_verified, bool &has_stored, bool &restored, bool(&mismatches)[3], F &&rollback)
Definition atm90e32.cpp:722
float get_local_phase_active_power_(uint8_t phase)
Definition atm90e32.cpp:473
uint8_t second
uint8_t type
uint32_t buffer
Definition gif.cpp:50
AlsGain501 gain
mopeka_std_values val[3]
Range range
Definition msa3xx.h:0
bool offset_register_value_matches(uint16_t actual, int16_t expected)
Definition atm90e32.h:20
ESPHOME_LOG_TAG(TAG, "atm90e32")
constexpr float IO
For components that represent GPIO pins like PCF8573.
Definition component.h:41
size_t buf_append_str(char *buf, size_t size, size_t pos, const char *str)
Safely append a string to buffer, returning new position (capped at size).
Definition helpers.h:1382
uint32_t value
Definition hal.cpp:41
constexpr uint32_t fnv1_hash_extend(uint32_t hash, T value)
Extend a FNV-1 hash with an integer (hashes each byte).
Definition helpers.h:973
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:169
void delay_microseconds_safe(uint32_t us)
Delay for the given amount of microseconds, possibly yielding to other processes during the wait.
Definition helpers.cpp:889
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:1043
constexpr size_t GPIO_SUMMARY_MAX_LEN
Maximum buffer size for dump_summary output.
Definition gpio_pin.h:14
void HOT delay(uint32_t ms)
Definition hal.cpp:85
static void uint32_t
watchdog_hw scratch[0]
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33