3-phase PV router
Loading...
Searching...
No Matches
test_main.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-3.0-or-later
17
18#include <unity.h>
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cmath>
23
24// ============================================================================
25// Constants
26// ============================================================================
27
28constexpr float PI = 3.14159265358979f;
29constexpr uint16_t SAMPLES_PER_CYCLE = 160; // ~160 samples at 50Hz with current ISR timing
30constexpr uint16_t SAMPLES_PER_HALF_CYCLE = 80;
31constexpr uint16_t ADC_MID_POINT = 512;
32constexpr uint16_t VOLTAGE_AMPLITUDE = 400; // Peak ADC counts for ~230V
33constexpr uint16_t CURRENT_AMPLITUDE = 200; // Peak ADC counts for typical load
34
35// ============================================================================
36// Old Implementation (right-aligned ADC, x256 scaling)
37// ============================================================================
38
40{
41 // DC offset filter state
42 int32_t l_DCoffset_V{ 512L * 256L }; // nominal @ x256 scale
43 int32_t l_sampleVminusDC{ 0 };
45
46 // Power accumulation
47 int32_t l_sumP{ 0 };
49
50 // RMS accumulation
51 uint32_t l_sum_Vsquared{ 0 };
52
53 // Sample counter
54 uint16_t n_samples{ 0 };
55
59 void processPolarity(int16_t rawSample)
60 {
61 l_sampleVminusDC = (static_cast< int32_t >(rawSample) << 8) - l_DCoffset_V;
62 }
63
67 void processCurrentRawSample(int16_t rawSample)
68 {
69 // Remove DC offset (using nominal mid-point)
70 int32_t sampleIminusDC = (static_cast< int32_t >(rawSample - 512)) << 8;
71
72 // Calculate power: reduce to 16-bits, multiply, scale back
73 const int32_t filtV_div4 = l_sampleVminusDC >> 2; // x64
74 const int32_t filtI_div4 = sampleIminusDC >> 2; // x64
75 int32_t instP = filtV_div4 * filtI_div4; // x4096
76 instP >>= 12; // x1
77
78 l_sumP += instP;
79 l_sumP_atSupplyPoint += instP;
80 }
81
86 {
87 const int32_t filtV_div4 = l_sampleVminusDC >> 2; // x64
88 int32_t inst_Vsquared = filtV_div4 * filtV_div4; // x4096
89 inst_Vsquared >>= 12; // x1
90
91 l_sum_Vsquared += inst_Vsquared;
93 ++n_samples;
94 }
95
100 {
103
104 // Apply limits
105 constexpr int32_t l_DCoffset_V_min = (512L - 100L) * 256L;
106 constexpr int32_t l_DCoffset_V_max = (512L + 100L) * 256L;
107 if (l_DCoffset_V < l_DCoffset_V_min) l_DCoffset_V = l_DCoffset_V_min;
108 if (l_DCoffset_V > l_DCoffset_V_max) l_DCoffset_V = l_DCoffset_V_max;
109 }
110
115 {
116 l_sumP = 0;
117 n_samples = 0;
118 }
119
123 int16_t getOffsetAsADC() const
124 {
125 return l_DCoffset_V >> 8;
126 }
127
131 float getAveragePower() const
132 {
133 return n_samples > 0 ? static_cast< float >(l_sumP) / n_samples : 0.0f;
134 }
135
139 float getRmsVoltage() const
140 {
141 return n_samples > 0 ? sqrtf(static_cast< float >(l_sum_Vsquared) / n_samples) : 0.0f;
142 }
143};
144
145// ============================================================================
146// New Implementation (left-aligned ADC, x64 scaling)
147// ============================================================================
148
150{
151 // DC offset filter state
152 static constexpr uint16_t i_DCoffset_V_nom{ 511U << 6 }; // 32704
154 uint32_t l_filterDC_V{ static_cast< uint32_t >(i_DCoffset_V_nom) << 15 };
155 int16_t i_sampleVminusDC{ 0 };
156
157 // Power accumulation
158 int32_t l_sumP{ 0 };
160
161 // RMS accumulation
162 uint32_t l_sum_Vsquared{ 0 };
163
164 // Sample counter
165 uint16_t n_samples{ 0 };
166
170 void processPolarity(uint16_t rawSample)
171 {
172 // Add 0.5 for rounding: +32 when 10-bits left aligned
173 i_sampleVminusDC = (rawSample | 32U) - i_DCoffset_V;
174 }
175
179 void processCurrentRawSample(uint16_t rawSample)
180 {
181 // Remove DC offset using voltage bias (more accurate than mid-range)
182 // Add 0.5 for rounding
183 int16_t sampleIminusDC = (rawSample | 32U) - i_DCoffset_V;
184
185 // Calculate power: reduce to 14-bits, multiply, scale back
186 const int16_t filtV_div4 = i_sampleVminusDC >> 2; // x16
187 const int16_t filtI_div4 = sampleIminusDC >> 2; // x16
188 int32_t instP = static_cast< int32_t >(filtV_div4) * filtI_div4; // x256
189 instP >>= 8; // x1
190
191 l_sumP += instP;
192 l_sumP_atSupplyPoint += instP;
193 }
194
199 {
200 const int16_t filtV_div4 = i_sampleVminusDC >> 2; // x16
201 int32_t inst_Vsquared = static_cast< int32_t >(filtV_div4) * filtV_div4; // x256
202 inst_Vsquared >>= 8; // x1
203
204 l_sum_Vsquared += inst_Vsquared;
206 ++n_samples;
207 }
208
213 {
215 }
216
221 {
222 l_sumP = 0;
223 n_samples = 0;
224 }
225
229 int16_t getOffsetAsADC() const
230 {
231 return i_DCoffset_V >> 6;
232 }
233
237 float getAveragePower() const
238 {
239 return n_samples > 0 ? static_cast< float >(l_sumP) / n_samples : 0.0f;
240 }
241
245 float getRmsVoltage() const
246 {
247 return n_samples > 0 ? sqrtf(static_cast< float >(l_sum_Vsquared) / n_samples) : 0.0f;
248 }
249};
250
251// ============================================================================
252// Helper Functions
253// ============================================================================
254
259{
260 uint32_t state;
261
262public:
263 explicit SimpleRNG(uint32_t seed = 12345)
264 : state(seed) {}
265
266 void seed(uint32_t s)
267 {
268 state = s ? s : 1;
269 }
270
271 uint32_t next()
272 {
273 state ^= state << 13;
274 state ^= state >> 17;
275 state ^= state << 5;
276 return state;
277 }
278
282 int16_t noise(int16_t amplitude)
283 {
284 if (amplitude == 0) return 0;
285 return static_cast< int16_t >((next() % (2 * amplitude + 1)) - amplitude);
286 }
287};
288
289// Global RNG for tests
291
292// ============================================================================
293// Test Statistics Output
294// ============================================================================
295
300{
301 const char* testName;
303 int16_t minCurrent;
304 int16_t maxCurrent;
305 int32_t oldSumP;
306 int32_t newSumP;
307 uint32_t oldSumVsq;
308 uint32_t newSumVsq;
309
310 void print() const
311 {
312 int32_t diffP = newSumP - oldSumP;
313 float pctP = (oldSumP != 0) ? 100.0f * fabsf(static_cast< float >(diffP)) / fabsf(static_cast< float >(oldSumP)) : 0.0f;
314
315 printf("\n [%s]\n", testName);
316 printf(" Cycles: %d, Current range: %d-%d ADC\n", cycles, minCurrent, maxCurrent);
317 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
318 static_cast< long >(oldSumP),
319 static_cast< long >(newSumP),
320 static_cast< long >(diffP),
321 static_cast< double >(pctP));
322
323 if (oldSumVsq > 0 || newSumVsq > 0)
324 {
325 int32_t diffVsq = static_cast< int32_t >(newSumVsq) - static_cast< int32_t >(oldSumVsq);
326 float pctVsq = (oldSumVsq != 0) ? 100.0f * fabsf(static_cast< float >(diffVsq)) / static_cast< float >(oldSumVsq) : 0.0f;
327 printf(" V^2 - Old: %lu, New: %lu, Diff: %ld (%.4f%%)\n",
328 static_cast< unsigned long >(oldSumVsq),
329 static_cast< unsigned long >(newSumVsq),
330 static_cast< long >(diffVsq),
331 static_cast< double >(pctVsq));
332 }
333 }
334};
335
339uint16_t generateSineADC(uint16_t sampleIndex, uint16_t dcLevel, int16_t amplitude, float phaseShift = 0.0f)
340{
341 float angle = 2.0f * PI * sampleIndex / SAMPLES_PER_CYCLE + phaseShift;
342 int16_t ac = static_cast< int16_t >(amplitude * sinf(angle));
343 int16_t adc = dcLevel + ac;
344 if (adc < 0) adc = 0;
345 if (adc > 1023) adc = 1023;
346 return static_cast< uint16_t >(adc);
347}
348
352uint16_t generateSineADCWithNoise(uint16_t sampleIndex, uint16_t dcLevel, int16_t amplitude,
353 int16_t noiseAmplitude, float phaseShift = 0.0f)
354{
355 float angle = 2.0f * PI * sampleIndex / SAMPLES_PER_CYCLE + phaseShift;
356 int16_t ac = static_cast< int16_t >(amplitude * sinf(angle));
357 int16_t noise = rng.noise(noiseAmplitude);
358 int16_t adc = dcLevel + ac + noise;
359 if (adc < 0) adc = 0;
360 if (adc > 1023) adc = 1023;
361 return static_cast< uint16_t >(adc);
362}
363
367constexpr uint16_t toLeftAligned(uint16_t rightAligned)
368{
369 return rightAligned << 6;
370}
371
372// ============================================================================
373// Test Fixtures
374// ============================================================================
375
378
379void setUp(void)
380{
383}
384
385void tearDown(void)
386{
387}
388
389// ============================================================================
390// Basic Power Calculation Tests
391// ============================================================================
392
400{
401 // Test with matching DC offset to prove mathematical equivalence
402 struct TestCase
403 {
404 uint16_t voltage_adc;
405 uint16_t current_adc;
406 };
407
408 TestCase cases[] = {
409 { 512, 512 }, // Both at mid-point (zero power)
410 { 612, 562 }, // Positive V, positive I
411 { 412, 462 }, // Negative V, negative I
412 { 612, 462 }, // Positive V, negative I
413 { 412, 562 }, // Negative V, positive I
414 { 912, 712 }, // High values
415 { 112, 312 }, // Low values
416 };
417
418 for (const auto& tc : cases)
419 {
420 // Create fresh implementations with MATCHING DC offset (512)
421 OldImplementation oldTest;
422 NewImplementation newTest;
423 oldTest.l_DCoffset_V = 512L * 256L;
424 newTest.i_DCoffset_V = 512U << 6;
425
426 // Process voltage
427 oldTest.processPolarity(tc.voltage_adc);
428 newTest.processPolarity(toLeftAligned(tc.voltage_adc));
429
430 // Process current and calculate power
431 oldTest.processCurrentRawSample(tc.current_adc);
432 newTest.processCurrentRawSample(toLeftAligned(tc.current_adc));
433
434 // With matching DC, difference is only from rounding (~1.5% per sample)
435 // This averages out to near-zero over a full cycle
436 int32_t tolerance = abs(oldTest.l_sumP) / 50 + 5; // 2% + 5 LSB
437 TEST_ASSERT_INT32_WITHIN(tolerance, oldTest.l_sumP, newTest.l_sumP);
438 }
439}
440
445{
446 // Run a full cycle with V and I in phase
447 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
448 {
449 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
450 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE);
451
452 oldImpl.processPolarity(v_adc);
453 oldImpl.processCurrentRawSample(i_adc);
454 oldImpl.processVoltage();
455
456 newImpl.processPolarity(toLeftAligned(v_adc));
457 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
458 newImpl.processVoltage();
459 }
460
461 // Both should show positive power (importing/exporting)
462 TEST_ASSERT_GREATER_THAN(0, oldImpl.l_sumP);
463 TEST_ASSERT_GREATER_THAN(0, newImpl.l_sumP);
464
465 // Power values differ by ~2% due to DC offset mismatch (511 vs 512).
466 // This is NOT an algorithm difference - with matching DC, results are identical.
467 // The 2% comes from: (512-511)/512 ≈ 0.2% DC error, amplified in V*I calculation.
468 float old_power = static_cast< float >(oldImpl.l_sumP);
469 float new_power = static_cast< float >(newImpl.l_sumP);
470 float tolerance = fabsf(old_power) * 0.03f; // 3% for DC offset difference
471 TEST_ASSERT_FLOAT_WITHIN(tolerance, old_power, new_power);
472}
473
478{
479 // Run a full cycle with V and I 90° out of phase
480 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
481 {
482 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, 0.0f);
483 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE, PI / 2.0f);
484
485 oldImpl.processPolarity(v_adc);
486 oldImpl.processCurrentRawSample(i_adc);
487 oldImpl.processVoltage();
488
489 newImpl.processPolarity(toLeftAligned(v_adc));
490 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
491 newImpl.processVoltage();
492 }
493
494 // With 90° phase shift, real power should be near zero
495 // Allow some tolerance due to discrete sampling
496 float max_power = VOLTAGE_AMPLITUDE * CURRENT_AMPLITUDE / 2.0f; // Theoretical max
497 float tolerance = max_power * 0.05f; // 5% of max
498
499 TEST_ASSERT_FLOAT_WITHIN(tolerance, 0.0f, static_cast< float >(oldImpl.l_sumP));
500 TEST_ASSERT_FLOAT_WITHIN(tolerance, 0.0f, static_cast< float >(newImpl.l_sumP));
501}
502
507{
508 // Run a full cycle with V and I 180° out of phase
509 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
510 {
511 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, 0.0f);
512 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE, PI);
513
514 oldImpl.processPolarity(v_adc);
515 oldImpl.processCurrentRawSample(i_adc);
516 oldImpl.processVoltage();
517
518 newImpl.processPolarity(toLeftAligned(v_adc));
519 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
520 newImpl.processVoltage();
521 }
522
523 // Both should show negative power (exporting)
524 TEST_ASSERT_LESS_THAN(0, oldImpl.l_sumP);
525 TEST_ASSERT_LESS_THAN(0, newImpl.l_sumP);
526
527 // Power values should be similar (within 5%)
528 float old_power = static_cast< float >(oldImpl.l_sumP);
529 float new_power = static_cast< float >(newImpl.l_sumP);
530 float tolerance = fabsf(old_power) * 0.05f;
531 TEST_ASSERT_FLOAT_WITHIN(tolerance, old_power, new_power);
532}
533
534// ============================================================================
535// RMS Voltage Calculation Tests
536// ============================================================================
537
542{
543 // Run a full cycle
544 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
545 {
546 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
547
548 oldImpl.processPolarity(v_adc);
549 oldImpl.processVoltage();
550
551 newImpl.processPolarity(toLeftAligned(v_adc));
552 newImpl.processVoltage();
553 }
554
555 // Compare RMS values (should be similar within 5%)
556 float old_rms = oldImpl.getRmsVoltage();
557 float new_rms = newImpl.getRmsVoltage();
558 float tolerance = old_rms * 0.05f;
559
560 TEST_ASSERT_FLOAT_WITHIN(tolerance, old_rms, new_rms);
561}
562
569{
570 // Run multiple cycles for stable measurement
571 for (int cycle = 0; cycle < 10; ++cycle)
572 {
573 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
574 {
575 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
576
577 oldImpl.processPolarity(v_adc);
578 oldImpl.processVoltage();
579
580 newImpl.processPolarity(toLeftAligned(v_adc));
581 newImpl.processVoltage();
582 }
583 }
584
585 // Theoretical RMS for amplitude 400: 400 / sqrt(2) ≈ 283
586 float theoretical_rms = VOLTAGE_AMPLITUDE / sqrtf(2.0f);
587
588 float old_rms = oldImpl.getRmsVoltage();
589 float new_rms = newImpl.getRmsVoltage();
590
591 // Both should be close to theoretical (within 10% due to DC offset subtraction)
592 TEST_ASSERT_FLOAT_WITHIN(theoretical_rms * 0.1f, theoretical_rms, old_rms);
593 TEST_ASSERT_FLOAT_WITHIN(theoretical_rms * 0.1f, theoretical_rms, new_rms);
594}
595
596// ============================================================================
597// Full Cycle Comparison Tests
598// ============================================================================
599
604{
605 // Run 100 cycles to allow DC filters to stabilize
606 for (int cycle = 0; cycle < 100; ++cycle)
607 {
608 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
609 {
610 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
611 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE);
612
613 // Old implementation
614 oldImpl.processPolarity(v_adc);
615 oldImpl.processCurrentRawSample(i_adc);
616 oldImpl.processVoltage();
617
618 // New implementation
619 newImpl.processPolarity(toLeftAligned(v_adc));
620 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
621 newImpl.processVoltage();
622
623 // Update DC filter at half cycle
624 if (s == SAMPLES_PER_HALF_CYCLE - 1)
625 {
626 oldImpl.processMinusHalfCycle();
627 newImpl.processMinusHalfCycle();
628 }
629 }
630 }
631
632 // Compare DC offsets
633 int16_t old_offset = oldImpl.getOffsetAsADC();
634 int16_t new_offset = newImpl.getOffsetAsADC();
635 TEST_ASSERT_INT16_WITHIN(10, old_offset, new_offset);
636
637 // Compare average power
638 float old_avg_power = oldImpl.getAveragePower();
639 float new_avg_power = newImpl.getAveragePower();
640 float power_tolerance = fabsf(old_avg_power) * 0.05f + 1.0f; // 5% + 1 LSB
641 TEST_ASSERT_FLOAT_WITHIN(power_tolerance, old_avg_power, new_avg_power);
642
643 // Compare RMS voltage
644 float old_rms = oldImpl.getRmsVoltage();
645 float new_rms = newImpl.getRmsVoltage();
646 float rms_tolerance = old_rms * 0.05f;
647 TEST_ASSERT_FLOAT_WITHIN(rms_tolerance, old_rms, new_rms);
648}
649
656{
657 // Use DC level of 530 instead of 512
658 const uint16_t dc_offset = 530;
659
660 // Run 200 cycles
661 for (int cycle = 0; cycle < 200; ++cycle)
662 {
663 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
664 {
665 uint16_t v_adc = generateSineADC(s, dc_offset, VOLTAGE_AMPLITUDE);
666 uint16_t i_adc = generateSineADC(s, dc_offset, CURRENT_AMPLITUDE);
667
668 oldImpl.processPolarity(v_adc);
669 oldImpl.processCurrentRawSample(i_adc);
670 oldImpl.processVoltage();
671
672 newImpl.processPolarity(toLeftAligned(v_adc));
673 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
674 newImpl.processVoltage();
675
676 if (s == SAMPLES_PER_HALF_CYCLE - 1)
677 {
678 oldImpl.processMinusHalfCycle();
679 newImpl.processMinusHalfCycle();
680 }
681 }
682 }
683
684 // Both should track to the new DC level
685 int16_t old_offset = oldImpl.getOffsetAsADC();
686 int16_t new_offset = newImpl.getOffsetAsADC();
687
688 // Old filter is clamped to 512±100, so may hit limit
689 // New filter tracks without limits
690 TEST_ASSERT_INT16_WITHIN(20, dc_offset, new_offset);
691
692 // Power and RMS should still be accurate after compensation
693 float old_avg_power = oldImpl.getAveragePower();
694 float new_avg_power = newImpl.getAveragePower();
695 float tolerance = fabsf(old_avg_power) * 0.10f + 5.0f; // 10% tolerance for offset case
696 TEST_ASSERT_FLOAT_WITHIN(tolerance, old_avg_power, new_avg_power);
697}
698
703{
704 OldImplementation oldPhases[3];
705 NewImplementation newPhases[3];
706
707 // Phase offsets: 0°, 120°, 240°
708 float phase_offsets[3] = { 0.0f, 2.0f * PI / 3.0f, 4.0f * PI / 3.0f };
709
710 // Run 50 cycles for all 3 phases
711 for (int cycle = 0; cycle < 50; ++cycle)
712 {
713 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
714 {
715 for (int phase = 0; phase < 3; ++phase)
716 {
717 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, phase_offsets[phase]);
718 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE, phase_offsets[phase]);
719
720 oldPhases[phase].processPolarity(v_adc);
721 oldPhases[phase].processCurrentRawSample(i_adc);
722 oldPhases[phase].processVoltage();
723
724 newPhases[phase].processPolarity(toLeftAligned(v_adc));
725 newPhases[phase].processCurrentRawSample(toLeftAligned(i_adc));
726 newPhases[phase].processVoltage();
727 }
728
729 if (s == SAMPLES_PER_HALF_CYCLE - 1)
730 {
731 for (int phase = 0; phase < 3; ++phase)
732 {
733 oldPhases[phase].processMinusHalfCycle();
734 newPhases[phase].processMinusHalfCycle();
735 }
736 }
737 }
738 }
739
740 // Compare total power across all phases
741 int32_t old_total_power = 0;
742 int32_t new_total_power = 0;
743 for (int phase = 0; phase < 3; ++phase)
744 {
745 old_total_power += oldPhases[phase].l_sumP;
746 new_total_power += newPhases[phase].l_sumP;
747 }
748
749 // Total power should be similar (within 5%)
750 float tolerance = fabsf(static_cast< float >(old_total_power)) * 0.05f;
751 TEST_ASSERT_INT32_WITHIN(static_cast< int32_t >(tolerance), old_total_power, new_total_power);
752}
753
754// ============================================================================
755// Edge Cases and Precision Tests
756// ============================================================================
757
762{
763 // Run with voltage but no current
764 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
765 {
766 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
767 uint16_t i_adc = ADC_MID_POINT; // No current (DC only)
768
769 oldImpl.processPolarity(v_adc);
770 oldImpl.processCurrentRawSample(i_adc);
771 oldImpl.processVoltage();
772
773 newImpl.processPolarity(toLeftAligned(v_adc));
774 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
775 newImpl.processVoltage();
776 }
777
778 // Power should be near zero for both
779 // Note: Small residual expected due to DC offset mismatch (512 vs 511)
780 // and rounding differences. ~300 over 160 samples is acceptable.
781 TEST_ASSERT_INT32_WITHIN(500, 0, oldImpl.l_sumP);
782 TEST_ASSERT_INT32_WITHIN(500, 0, newImpl.l_sumP);
783}
784
789{
790 // Use high amplitude that approaches ADC limits
791 const uint16_t high_amplitude = 450;
792
793 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
794 {
795 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, high_amplitude);
796 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, high_amplitude / 2);
797
798 oldImpl.processPolarity(v_adc);
799 oldImpl.processCurrentRawSample(i_adc);
800 oldImpl.processVoltage();
801
802 newImpl.processPolarity(toLeftAligned(v_adc));
803 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
804 newImpl.processVoltage();
805 }
806
807 // Both should still produce valid, similar results
808 float old_power = static_cast< float >(oldImpl.l_sumP);
809 float new_power = static_cast< float >(newImpl.l_sumP);
810 float tolerance = fabsf(old_power) * 0.10f; // 10% tolerance for extreme values
811 TEST_ASSERT_FLOAT_WITHIN(tolerance, old_power, new_power);
812}
813
821{
822 // Track power per cycle to ensure consistency
823 int32_t old_power_per_cycle[10];
824 int32_t new_power_per_cycle[10];
825
826 for (int cycle = 0; cycle < 10; ++cycle)
827 {
828 // Reset accumulators for this cycle (as in real operation)
829 oldImpl.l_sumP = 0;
830 newImpl.l_sumP = 0;
831
832 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
833 {
834 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
835 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE);
836
837 oldImpl.processPolarity(v_adc);
838 oldImpl.processCurrentRawSample(i_adc);
839 oldImpl.processVoltage();
840
841 newImpl.processPolarity(toLeftAligned(v_adc));
842 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
843 newImpl.processVoltage();
844
845 if (s == SAMPLES_PER_HALF_CYCLE - 1)
846 {
847 oldImpl.processMinusHalfCycle();
848 newImpl.processMinusHalfCycle();
849 }
850 }
851
852 old_power_per_cycle[cycle] = oldImpl.l_sumP;
853 new_power_per_cycle[cycle] = newImpl.l_sumP;
854 }
855
856 // All cycles should show positive power (PF=1, importing)
857 for (int i = 0; i < 10; ++i)
858 {
859 TEST_ASSERT_GREATER_THAN(0, old_power_per_cycle[i]);
860 TEST_ASSERT_GREATER_THAN(0, new_power_per_cycle[i]);
861 }
862
863 // Power per cycle should be consistent (within 5%)
864 int32_t old_avg = old_power_per_cycle[0];
865 int32_t new_avg = new_power_per_cycle[0];
866 for (int i = 1; i < 10; ++i)
867 {
868 TEST_ASSERT_INT32_WITHIN(old_avg / 20, old_avg, old_power_per_cycle[i]);
869 TEST_ASSERT_INT32_WITHIN(new_avg / 20, new_avg, new_power_per_cycle[i]);
870 }
871
872 // Old and new should produce similar results
873 float tolerance = fabsf(static_cast< float >(old_avg)) * 0.05f;
874 TEST_ASSERT_FLOAT_WITHIN(tolerance, static_cast< float >(old_avg), static_cast< float >(new_avg));
875}
876
884{
885 // Use matching DC offset for both
886 OldImplementation oldTest;
887 NewImplementation newTest;
888 oldTest.l_DCoffset_V = 512L * 256L;
889 newTest.i_DCoffset_V = 512U << 6;
890
891 // Run a full cycle
892 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
893 {
894 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
895 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE);
896
897 oldTest.processPolarity(v_adc);
898 oldTest.processCurrentRawSample(i_adc);
899 oldTest.processVoltage();
900
901 newTest.processPolarity(toLeftAligned(v_adc));
903 newTest.processVoltage();
904 }
905
906 // With matching DC and over a full cycle, results should be IDENTICAL
907 // (rounding averages out to zero over sine wave)
908 float diff_percent = 100.0f * fabsf(static_cast< float >(newTest.l_sumP - oldTest.l_sumP))
909 / fabsf(static_cast< float >(oldTest.l_sumP));
910
911 // Difference should be < 0.1% (essentially zero, just floating-point noise)
912 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, diff_percent);
913
914 // Also verify V² accumulation is identical
915 float vsq_diff_percent = 100.0f * fabsf(static_cast< float >(newTest.l_sum_Vsquared) - static_cast< float >(oldTest.l_sum_Vsquared))
916 / static_cast< float >(oldTest.l_sum_Vsquared);
917 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, vsq_diff_percent);
918}
919
926{
927 // Single sample test at known values
928 const uint16_t v_adc = 712; // +200 from mid-point
929 const uint16_t i_adc = 612; // +100 from mid-point
930
931 oldImpl.processPolarity(v_adc);
932 oldImpl.processCurrentRawSample(i_adc);
933
934 newImpl.processPolarity(toLeftAligned(v_adc));
935 newImpl.processCurrentRawSample(toLeftAligned(i_adc));
936
937 // Calculate expected power manually
938 // Old: V = (712 - 512) * 256 = 51200, I = (612 - 512) * 256 = 25600
939 // instP = (51200/4) * (25600/4) / 4096 = 12800 * 6400 / 4096 = 20000
940 // New: V = (712*64 - 511*64) = 12864, I = (612*64 - 511*64) = 6464
941 // instP = (12864/4) * (6464/4) / 256 = 3216 * 1616 / 256 ≈ 20295
942
943 // Both should be close (within 5%)
944 float tolerance = fabsf(static_cast< float >(oldImpl.l_sumP)) * 0.05f + 100.0f;
945 TEST_ASSERT_INT32_WITHIN(static_cast< int32_t >(tolerance), oldImpl.l_sumP, newImpl.l_sumP);
946}
947
948// ============================================================================
949// Extended Tests (Many Cycles, Noise)
950// ============================================================================
951
958{
959 OldImplementation oldTest;
960 NewImplementation newTest;
961
962 // Use matching DC for fair comparison
963 oldTest.l_DCoffset_V = 512L * 256L;
964 newTest.i_DCoffset_V = 512U << 6;
965
966 const int NUM_CYCLES = 10000;
967
968 // Track power per datalog period (every 500 cycles = 10 seconds)
969 const int DATALOG_CYCLES = 500;
970 float max_diff_percent = 0.0f;
971
972 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
973 {
974 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
975 {
976 uint16_t v_adc = generateSineADC(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE);
977 uint16_t i_adc = generateSineADC(s, ADC_MID_POINT, CURRENT_AMPLITUDE);
978
979 oldTest.processPolarity(v_adc);
980 oldTest.processCurrentRawSample(i_adc);
981 oldTest.processVoltage();
982
983 newTest.processPolarity(toLeftAligned(v_adc));
985 newTest.processVoltage();
986
987 if (s == SAMPLES_PER_HALF_CYCLE - 1)
988 {
989 oldTest.processMinusHalfCycle();
990 newTest.processMinusHalfCycle();
991 }
992 }
993
994 // Check difference at each datalog boundary
995 if ((cycle + 1) % DATALOG_CYCLES == 0)
996 {
997 float diff = 100.0f * fabsf(static_cast< float >(newTest.l_sumP - oldTest.l_sumP))
998 / fabsf(static_cast< float >(oldTest.l_sumP));
999 if (diff > max_diff_percent) max_diff_percent = diff;
1000
1001 // Reset accumulators for next datalog period
1002 oldTest.l_sumP = 0;
1003 oldTest.l_sum_Vsquared = 0;
1004 newTest.l_sumP = 0;
1005 newTest.l_sum_Vsquared = 0;
1006 }
1007 }
1008
1009 // Max difference over all datalog periods should be < 0.1%
1010 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, max_diff_percent);
1011}
1012
1020{
1021 OldImplementation oldTest;
1022 NewImplementation newTest;
1023
1024 oldTest.l_DCoffset_V = 512L * 256L;
1025 newTest.i_DCoffset_V = 512U << 6;
1026
1027 rng.seed(42); // Deterministic seed for reproducibility
1028
1029 const int NUM_CYCLES = 1000;
1030 const int16_t NOISE_AMPLITUDE = 2; // ±2 LSB typical ADC noise
1031
1032 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1033 {
1034 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1035 {
1036 // Generate same noisy sample for both implementations
1037 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1038 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, CURRENT_AMPLITUDE, NOISE_AMPLITUDE);
1039
1040 oldTest.processPolarity(v_adc);
1041 oldTest.processCurrentRawSample(i_adc);
1042 oldTest.processVoltage();
1043
1044 newTest.processPolarity(toLeftAligned(v_adc));
1045 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1046 newTest.processVoltage();
1047
1048 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1049 {
1050 oldTest.processMinusHalfCycle();
1051 newTest.processMinusHalfCycle();
1052 }
1053 }
1054 }
1055
1056 // With identical noisy input, difference should still be < 0.1%
1057 float diff_percent = 100.0f * fabsf(static_cast< float >(newTest.l_sumP - oldTest.l_sumP))
1058 / fabsf(static_cast< float >(oldTest.l_sumP));
1059 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, diff_percent);
1060
1061 // RMS should also match
1062 float vsq_diff = 100.0f * fabsf(static_cast< float >(newTest.l_sum_Vsquared) - static_cast< float >(oldTest.l_sum_Vsquared))
1063 / static_cast< float >(oldTest.l_sum_Vsquared);
1064 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, vsq_diff);
1065}
1066
1073{
1074 OldImplementation oldTest;
1075 NewImplementation newTest;
1076
1077 oldTest.l_DCoffset_V = 512L * 256L;
1078 newTest.i_DCoffset_V = 512U << 6;
1079
1080 rng.seed(12345);
1081
1082 const int NUM_CYCLES = 1000;
1083 const int16_t NOISE_AMPLITUDE = 5; // ±5 LSB higher noise
1084
1085 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1086 {
1087 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1088 {
1089 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1090 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, CURRENT_AMPLITUDE, NOISE_AMPLITUDE);
1091
1092 oldTest.processPolarity(v_adc);
1093 oldTest.processCurrentRawSample(i_adc);
1094 oldTest.processVoltage();
1095
1096 newTest.processPolarity(toLeftAligned(v_adc));
1097 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1098 newTest.processVoltage();
1099
1100 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1101 {
1102 oldTest.processMinusHalfCycle();
1103 newTest.processMinusHalfCycle();
1104 }
1105 }
1106 }
1107
1108 float diff_percent = 100.0f * fabsf(static_cast< float >(newTest.l_sumP - oldTest.l_sumP))
1109 / fabsf(static_cast< float >(oldTest.l_sumP));
1110 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, diff_percent);
1111}
1112
1120{
1121 // Test various power factors: 0°, 30°, 45°, 60°, 90°
1122 float phase_shifts[] = { 0.0f, PI / 6, PI / 4, PI / 3, PI / 2 };
1123 const int16_t NOISE_AMPLITUDE = 3;
1124
1125 for (float phase_shift : phase_shifts)
1126 {
1127 // Fresh implementations with matching DC for each power factor
1128 OldImplementation oldTest;
1129 NewImplementation newTest;
1130 oldTest.l_DCoffset_V = 512L * 256L;
1131 newTest.i_DCoffset_V = 512U << 6;
1132
1133 // Reset RNG to same seed for each power factor test
1134 rng.seed(98765);
1135
1136 for (int cycle = 0; cycle < 500; ++cycle)
1137 {
1138 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1139 {
1140 // Generate identical noisy samples for both implementations
1141 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE, 0.0f);
1142 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, CURRENT_AMPLITUDE, NOISE_AMPLITUDE, phase_shift);
1143
1144 oldTest.processPolarity(v_adc);
1145 oldTest.processCurrentRawSample(i_adc);
1146 oldTest.processVoltage();
1147
1148 newTest.processPolarity(toLeftAligned(v_adc));
1149 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1150 newTest.processVoltage();
1151
1152 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1153 {
1154 oldTest.processMinusHalfCycle();
1155 newTest.processMinusHalfCycle();
1156 }
1157 }
1158 }
1159
1160 // For meaningful power (resistive/low phase shift), check percentage
1161 // For reactive loads, DC filters track differently with noise, so use wider tolerance
1162 int32_t abs_diff = abs(newTest.l_sumP - oldTest.l_sumP);
1163
1164 if (phase_shift < PI / 4) // Less than 45° - strong power
1165 {
1166 float diff = 100.0f * static_cast< float >(abs_diff)
1167 / fabsf(static_cast< float >(oldTest.l_sumP));
1168 TEST_ASSERT_FLOAT_WITHIN(0.2f, 0.0f, diff); // <0.2% difference
1169 }
1170 else
1171 {
1172 // For higher phase shifts (weaker power), DC filter differences become significant
1173 // with noise. Just verify both produce same sign and similar magnitude.
1174 // The actual magnitude is noise-dominated at high phase shifts.
1175 TEST_ASSERT_TRUE((oldTest.l_sumP > 0) == (newTest.l_sumP > 0) || abs(oldTest.l_sumP) < 50000); // Same sign or small magnitude
1176 }
1177 }
1178}
1179
1186{
1187 OldImplementation oldTest;
1188 NewImplementation newTest;
1189
1190 oldTest.l_DCoffset_V = 512L * 256L;
1191 newTest.i_DCoffset_V = 512U << 6;
1192
1193 rng.seed(11111);
1194
1195 const int NUM_CYCLES = 50000;
1196 const int16_t NOISE_AMPLITUDE = 2;
1197 float max_diff = 0.0f;
1198
1199 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1200 {
1201 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1202 {
1203 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1204 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, CURRENT_AMPLITUDE, NOISE_AMPLITUDE);
1205
1206 oldTest.processPolarity(v_adc);
1207 oldTest.processCurrentRawSample(i_adc);
1208 oldTest.processVoltage();
1209
1210 newTest.processPolarity(toLeftAligned(v_adc));
1211 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1212 newTest.processVoltage();
1213
1214 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1215 {
1216 oldTest.processMinusHalfCycle();
1217 newTest.processMinusHalfCycle();
1218 }
1219 }
1220
1221 // Check every 1000 cycles and reset accumulators
1222 if ((cycle + 1) % 1000 == 0)
1223 {
1224 float diff = 100.0f * fabsf(static_cast< float >(newTest.l_sumP - oldTest.l_sumP))
1225 / fabsf(static_cast< float >(oldTest.l_sumP));
1226 if (diff > max_diff) max_diff = diff;
1227
1228 oldTest.l_sumP = 0;
1229 newTest.l_sumP = 0;
1230 }
1231 }
1232
1233 // Over 50,000 cycles, max difference should still be < 0.1%
1234 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, max_diff);
1235}
1236
1237// ============================================================================
1238// Realistic Load Variation Tests
1239// ============================================================================
1240
1247{
1248 // Current amplitudes in ADC counts (peak)
1249 // 50 = ~1A, 100 = ~2A, 200 = ~4A, 300 = ~6A, 500 = ~10A (approximate)
1250 // Max amplitude ~505 with ADC mid-point at 512 (stays within 7-1017)
1251 int16_t current_amplitudes[] = { 20, 50, 100, 150, 200, 300, 400, 450, 500, 505 };
1252 const int16_t NOISE_AMPLITUDE = 2;
1253 const int NUM_CYCLES = 1000;
1254
1255 printf("\n [test_multiple_current_amplitudes]\n");
1256 printf(" Testing %zu amplitude levels, %d cycles each:\n", sizeof(current_amplitudes) / sizeof(current_amplitudes[0]), NUM_CYCLES);
1257 printf(" %6s %12s %12s %12s %10s\n", "Amp", "Old_sumP", "New_sumP", "Diff", "Diff%");
1258
1259 for (int16_t i_amp : current_amplitudes)
1260 {
1261 OldImplementation oldTest;
1262 NewImplementation newTest;
1263 oldTest.l_DCoffset_V = 512L * 256L;
1264 newTest.i_DCoffset_V = 512U << 6;
1265
1266 rng.seed(77777);
1267
1268 // Run cycles for each amplitude
1269 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1270 {
1271 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1272 {
1273 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1274 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, i_amp, NOISE_AMPLITUDE);
1275
1276 oldTest.processPolarity(v_adc);
1277 oldTest.processCurrentRawSample(i_adc);
1278 oldTest.processVoltage();
1279
1280 newTest.processPolarity(toLeftAligned(v_adc));
1281 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1282 newTest.processVoltage();
1283
1284 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1285 {
1286 oldTest.processMinusHalfCycle();
1287 newTest.processMinusHalfCycle();
1288 }
1289 }
1290 }
1291
1292 int32_t diff = newTest.l_sumP - oldTest.l_sumP;
1293 float pct = (oldTest.l_sumP != 0) ? 100.0f * fabsf(static_cast< float >(diff)) / fabsf(static_cast< float >(oldTest.l_sumP)) : 0.0f;
1294 printf(" %6d %12ld %12ld %12ld %9.4f%%\n",
1295 i_amp,
1296 static_cast< long >(oldTest.l_sumP),
1297 static_cast< long >(newTest.l_sumP),
1298 static_cast< long >(diff),
1299 static_cast< double >(pct));
1300
1301 // For meaningful current, check percentage difference
1302 if (i_amp >= 50)
1303 {
1304 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, pct);
1305 }
1306 }
1307}
1308
1316{
1317 OldImplementation oldTest;
1318 NewImplementation newTest;
1319 oldTest.l_DCoffset_V = 512L * 256L;
1320 newTest.i_DCoffset_V = 512U << 6;
1321
1322 rng.seed(88888);
1323
1324 const int NUM_CYCLES = 5000;
1325 const int16_t NOISE_AMPLITUDE = 2;
1326 const int16_t MIN_CURRENT = 50; // Minimum current amplitude
1327 const int16_t MAX_CURRENT = 500; // Maximum current amplitude (near ADC limit)
1328 const int VARIATION_PERIOD = 200; // Cycles for one full load variation
1329
1330 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1331 {
1332 // Calculate current amplitude for this cycle (varies sinusoidally)
1333 float load_angle = 2.0f * PI * cycle / VARIATION_PERIOD;
1334 int16_t current_amp = MIN_CURRENT + static_cast< int16_t >((MAX_CURRENT - MIN_CURRENT) * (0.5f + 0.5f * sinf(load_angle)));
1335
1336 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1337 {
1338 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1339 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, current_amp, NOISE_AMPLITUDE);
1340
1341 oldTest.processPolarity(v_adc);
1342 oldTest.processCurrentRawSample(i_adc);
1343 oldTest.processVoltage();
1344
1345 newTest.processPolarity(toLeftAligned(v_adc));
1346 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1347 newTest.processVoltage();
1348
1349 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1350 {
1351 oldTest.processMinusHalfCycle();
1352 newTest.processMinusHalfCycle();
1353 }
1354 }
1355 }
1356
1357 int32_t diffP = newTest.l_sumP - oldTest.l_sumP;
1358 float pctP = 100.0f * fabsf(static_cast< float >(diffP)) / fabsf(static_cast< float >(oldTest.l_sumP));
1359
1360 printf("\n [test_sinusoidal_load_variation]\n");
1361 printf(" Cycles: %d, Current range: %d-%d ADC (sinusoidal variation)\n", NUM_CYCLES, MIN_CURRENT, MAX_CURRENT);
1362 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
1363 static_cast< long >(oldTest.l_sumP),
1364 static_cast< long >(newTest.l_sumP),
1365 static_cast< long >(diffP),
1366 static_cast< double >(pctP));
1367
1368 TEST_ASSERT_FLOAT_WITHIN(0.1f, 0.0f, pctP);
1369}
1370
1378{
1379 OldImplementation oldTest;
1380 NewImplementation newTest;
1381 oldTest.l_DCoffset_V = 512L * 256L;
1382 newTest.i_DCoffset_V = 512U << 6;
1383
1384 rng.seed(99999);
1385
1386 const int NUM_CYCLES = 10000;
1387 const int16_t NOISE_AMPLITUDE = 2;
1388 const int16_t MIN_CURRENT = 20;
1389 const int16_t MAX_CURRENT = 505;
1390 int16_t current_amp = 200; // Start with medium load
1391 int cycles_until_change = 30;
1392
1393 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1394 {
1395 // Random load step changes
1396 if (--cycles_until_change <= 0)
1397 {
1398 // Random new current amplitude (20-505)
1399 current_amp = MIN_CURRENT + static_cast< int16_t >(rng.next() % (MAX_CURRENT - MIN_CURRENT + 1));
1400 // Random duration until next change (10-50 cycles)
1401 cycles_until_change = 10 + static_cast< int >(rng.next() % 40);
1402 }
1403
1404 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1405 {
1406 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1407 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, current_amp, NOISE_AMPLITUDE);
1408
1409 oldTest.processPolarity(v_adc);
1410 oldTest.processCurrentRawSample(i_adc);
1411 oldTest.processVoltage();
1412
1413 newTest.processPolarity(toLeftAligned(v_adc));
1414 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1415 newTest.processVoltage();
1416
1417 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1418 {
1419 oldTest.processMinusHalfCycle();
1420 newTest.processMinusHalfCycle();
1421 }
1422 }
1423 }
1424
1425 int32_t diffP = newTest.l_sumP - oldTest.l_sumP;
1426 float pctP = 100.0f * fabsf(static_cast< float >(diffP)) / fabsf(static_cast< float >(oldTest.l_sumP));
1427
1428 printf("\n [test_random_load_steps]\n");
1429 printf(" Cycles: %d, Current range: %d-%d ADC (random steps)\n", NUM_CYCLES, MIN_CURRENT, MAX_CURRENT);
1430 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
1431 static_cast< long >(oldTest.l_sumP),
1432 static_cast< long >(newTest.l_sumP),
1433 static_cast< long >(diffP),
1434 static_cast< double >(pctP));
1435
1436 // With ADC-limit amplitudes and random loads, allow 0.2% difference
1437 TEST_ASSERT_FLOAT_WITHIN(0.2f, 0.0f, pctP);
1438}
1439
1446{
1447 OldImplementation oldTest;
1448 NewImplementation newTest;
1449 oldTest.l_DCoffset_V = 512L * 256L;
1450 newTest.i_DCoffset_V = 512U << 6;
1451
1452 rng.seed(11111);
1453
1454 const int NUM_CYCLES = 10000;
1455 const int16_t NOISE_AMPLITUDE = 3;
1456 const int16_t CLEAR_SKY_CURRENT = 500; // Full solar generation (near ADC limit)
1457 const int16_t CLOUDY_CURRENT = 80; // Reduced during cloud shadow
1458
1459 float cloud_factor = 1.0f; // 1.0 = clear, 0.0 = fully clouded
1460 float cloud_velocity = 0.0f;
1461
1462 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1463 {
1464 // Simulate cloud dynamics
1465 // Random chance of cloud starting/ending
1466 if (rng.next() % 500 == 0)
1467 {
1468 cloud_velocity = (rng.next() % 2 == 0) ? -0.05f : 0.05f;
1469 }
1470
1471 cloud_factor += cloud_velocity;
1472 if (cloud_factor > 1.0f)
1473 {
1474 cloud_factor = 1.0f;
1475 cloud_velocity = 0;
1476 }
1477 if (cloud_factor < 0.2f)
1478 {
1479 cloud_factor = 0.2f;
1480 cloud_velocity = 0;
1481 }
1482
1483 int16_t current_amp = CLOUDY_CURRENT + static_cast< int16_t >((CLEAR_SKY_CURRENT - CLOUDY_CURRENT) * cloud_factor);
1484
1485 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1486 {
1487 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1488 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, current_amp, NOISE_AMPLITUDE);
1489
1490 oldTest.processPolarity(v_adc);
1491 oldTest.processCurrentRawSample(i_adc);
1492 oldTest.processVoltage();
1493
1494 newTest.processPolarity(toLeftAligned(v_adc));
1495 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1496 newTest.processVoltage();
1497
1498 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1499 {
1500 oldTest.processMinusHalfCycle();
1501 newTest.processMinusHalfCycle();
1502 }
1503 }
1504 }
1505
1506 int32_t diffP = newTest.l_sumP - oldTest.l_sumP;
1507 float pctP = 100.0f * fabsf(static_cast< float >(diffP)) / fabsf(static_cast< float >(oldTest.l_sumP));
1508
1509 printf("\n [test_cloud_shadow_simulation]\n");
1510 printf(" Cycles: %d, Current range: %d-%d ADC (cloud dynamics)\n", NUM_CYCLES, CLOUDY_CURRENT, CLEAR_SKY_CURRENT);
1511 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
1512 static_cast< long >(oldTest.l_sumP),
1513 static_cast< long >(newTest.l_sumP),
1514 static_cast< long >(diffP),
1515 static_cast< double >(pctP));
1516
1517 // With ADC-limit amplitudes and cloud dynamics, allow 0.2% difference
1518 TEST_ASSERT_FLOAT_WITHIN(0.2f, 0.0f, pctP);
1519}
1520
1528{
1529 OldImplementation oldTest;
1530 NewImplementation newTest;
1531 oldTest.l_DCoffset_V = 512L * 256L;
1532 newTest.i_DCoffset_V = 512U << 6;
1533
1534 rng.seed(22222);
1535
1536 // Simulate 1 day scaled: 8640 cycles = 172.8 seconds at 50Hz
1537 // Represents: 0=midnight, 2160=6am, 4320=noon, 6480=6pm, 8640=midnight
1538 const int NUM_CYCLES = 8640;
1539 const int16_t NOISE_AMPLITUDE = 2;
1540 const int16_t NIGHT_CURRENT = 5; // Minimum current during night
1541 const int16_t PEAK_CURRENT = 500; // Peak solar at noon (near ADC limit)
1542
1543 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1544 {
1545 // Solar profile: sine wave with peak at noon (cycle 4320)
1546 // Night from 0-1440 (midnight-4am scaled) and 7200-8640 (8pm-midnight scaled)
1547 float hour = 24.0f * cycle / NUM_CYCLES;
1548 float solar_factor;
1549
1550 if (hour < 6.0f || hour > 20.0f)
1551 {
1552 solar_factor = 0.0f; // Night
1553 }
1554 else
1555 {
1556 // Day: sine curve peaking at noon (hour 12)
1557 float day_progress = (hour - 6.0f) / 14.0f; // 0 at 6am, 1 at 8pm
1558 solar_factor = sinf(day_progress * PI);
1559 }
1560
1561 int16_t current_amp = static_cast< int16_t >(PEAK_CURRENT * solar_factor);
1562 if (current_amp < NIGHT_CURRENT) current_amp = NIGHT_CURRENT; // Minimum for calculation stability
1563
1564 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1565 {
1566 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE);
1567 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, current_amp, NOISE_AMPLITUDE);
1568
1569 oldTest.processPolarity(v_adc);
1570 oldTest.processCurrentRawSample(i_adc);
1571 oldTest.processVoltage();
1572
1573 newTest.processPolarity(toLeftAligned(v_adc));
1574 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1575 newTest.processVoltage();
1576
1577 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1578 {
1579 oldTest.processMinusHalfCycle();
1580 newTest.processMinusHalfCycle();
1581 }
1582 }
1583 }
1584
1585 int32_t diffP = newTest.l_sumP - oldTest.l_sumP;
1586 int32_t abs_diff = abs(diffP);
1587 int32_t max_power = abs(oldTest.l_sumP) > abs(newTest.l_sumP) ? abs(oldTest.l_sumP) : abs(newTest.l_sumP);
1588 float pctP = (max_power > 0) ? 100.0f * static_cast< float >(abs_diff) / static_cast< float >(max_power) : 0.0f;
1589
1590 printf("\n [test_daily_solar_profile]\n");
1591 printf(" Cycles: %d, Current range: %d-%d ADC (24h solar profile)\n", NUM_CYCLES, NIGHT_CURRENT, PEAK_CURRENT);
1592 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
1593 static_cast< long >(oldTest.l_sumP),
1594 static_cast< long >(newTest.l_sumP),
1595 static_cast< long >(diffP),
1596 static_cast< double >(pctP));
1597
1598 // Daily profile has many night cycles with low current where noise accumulates.
1599 // With peak current at ADC limit and noise, allow up to 3% difference.
1600 if (max_power > 100000)
1601 {
1602 TEST_ASSERT_FLOAT_WITHIN(3.0f, 0.0f, pctP);
1603 }
1604 else
1605 {
1606 TEST_ASSERT_INT32_WITHIN(5000, oldTest.l_sumP, newTest.l_sumP);
1607 }
1608}
1609
1617{
1618 OldImplementation oldTest;
1619 NewImplementation newTest;
1620 oldTest.l_DCoffset_V = 512L * 256L;
1621 newTest.i_DCoffset_V = 512U << 6;
1622
1623 rng.seed(33333);
1624
1625 const int NUM_CYCLES = 10000;
1626 const int16_t NOISE_AMPLITUDE = 2;
1627
1628 // Varying phase shift to simulate import (0°) to export (180°) transitions
1629 float phase = 0.0f;
1630 float phase_velocity = 0.0f;
1631
1632 for (int cycle = 0; cycle < NUM_CYCLES; ++cycle)
1633 {
1634 // Random phase transitions (simulating load/generation balance changes)
1635 if (rng.next() % 200 == 0)
1636 {
1637 phase_velocity = (static_cast< float >(rng.next() % 100) - 50) / 1000.0f;
1638 }
1639
1640 phase += phase_velocity;
1641 if (phase > PI) phase = PI;
1642 if (phase < 0) phase = 0;
1643
1644 int16_t current_amp = 150 + rng.noise(50); // Variable current too
1645
1646 for (uint16_t s = 0; s < SAMPLES_PER_CYCLE; ++s)
1647 {
1648 uint16_t v_adc = generateSineADCWithNoise(s, ADC_MID_POINT, VOLTAGE_AMPLITUDE, NOISE_AMPLITUDE, 0.0f);
1649 uint16_t i_adc = generateSineADCWithNoise(s, ADC_MID_POINT, current_amp, NOISE_AMPLITUDE, phase);
1650
1651 oldTest.processPolarity(v_adc);
1652 oldTest.processCurrentRawSample(i_adc);
1653 oldTest.processVoltage();
1654
1655 newTest.processPolarity(toLeftAligned(v_adc));
1656 newTest.processCurrentRawSample(toLeftAligned(i_adc));
1657 newTest.processVoltage();
1658
1659 if (s == SAMPLES_PER_HALF_CYCLE - 1)
1660 {
1661 oldTest.processMinusHalfCycle();
1662 newTest.processMinusHalfCycle();
1663 }
1664 }
1665 }
1666
1667 // For bidirectional flow, accumulated power might be small, use absolute check
1668 int32_t abs_diff = abs(newTest.l_sumP - oldTest.l_sumP);
1669 int32_t max_power = abs(oldTest.l_sumP) > abs(newTest.l_sumP) ? abs(oldTest.l_sumP) : abs(newTest.l_sumP);
1670 float pctP = (max_power > 0) ? 100.0f * static_cast< float >(abs_diff) / static_cast< float >(max_power) : 0.0f;
1671
1672 printf("\n [test_import_export_transitions]\n");
1673 printf(" Cycles: %d, Current range: ~100-200 ADC (phase 0-PI transitions)\n", NUM_CYCLES);
1674 printf(" Power - Old: %ld, New: %ld, Diff: %ld (%.4f%%)\n",
1675 static_cast< long >(oldTest.l_sumP),
1676 static_cast< long >(newTest.l_sumP),
1677 static_cast< long >(newTest.l_sumP - oldTest.l_sumP),
1678 static_cast< double >(pctP));
1679
1680 if (max_power > 100000)
1681 {
1682 // Import/export transitions involve power crossing through zero,
1683 // which can cause larger relative differences. 1% is acceptable.
1684 float diff = 100.0f * static_cast< float >(abs_diff) / static_cast< float >(max_power);
1685 TEST_ASSERT_FLOAT_WITHIN(1.0f, 0.0f, diff);
1686 }
1687 else
1688 {
1689 // Small net power, just check absolute difference
1690 TEST_ASSERT_INT32_WITHIN(10000, oldTest.l_sumP, newTest.l_sumP);
1691 }
1692}
1693
1694// ============================================================================
1695// Main
1696// ============================================================================
1697
1698int main(int argc, char** argv)
1699{
1700 UNITY_BEGIN();
1701
1702 // Basic power calculation
1705 RUN_TEST(test_power_reactive_load);
1706 RUN_TEST(test_power_export);
1707
1708 // RMS voltage calculation
1711
1712 // Full cycle comparison
1716
1717 // Edge cases and precision
1718 RUN_TEST(test_zero_load);
1719 RUN_TEST(test_near_adc_limits);
1721 RUN_TEST(test_mathematical_identity); // CRITICAL: proves 0% difference
1722 RUN_TEST(test_scaling_equivalence);
1723
1724 // Extended tests (many cycles, noise)
1725 RUN_TEST(test_extended_10000_cycles); // 10,000 cycles
1726 RUN_TEST(test_with_realistic_noise_2lsb); // ±2 LSB noise
1727 RUN_TEST(test_with_higher_noise_5lsb); // ±5 LSB noise
1728 RUN_TEST(test_varying_power_factor_with_noise); // Various PF + noise
1729 RUN_TEST(test_stress_50000_cycles); // 50,000 cycles stress test
1730
1731 // Realistic load variation tests
1732 RUN_TEST(test_multiple_current_amplitudes); // Light to heavy load
1733 RUN_TEST(test_sinusoidal_load_variation); // Gradual load changes
1734 RUN_TEST(test_random_load_steps); // Appliance switching
1735 RUN_TEST(test_cloud_shadow_simulation); // Solar cloud shadows
1736 RUN_TEST(test_daily_solar_profile); // Full day simulation
1737 RUN_TEST(test_import_export_transitions); // Bidirectional power flow
1738
1739 return UNITY_END();
1740}
Simple deterministic PRNG (xorshift32) for reproducible noise.
SimpleRNG(uint32_t seed=12345)
int16_t noise(int16_t amplitude)
Generate noise in range [-amplitude, +amplitude].
uint32_t state
uint32_t next()
void seed(uint32_t s)
void setUp(void)
Definition test_main.cpp:27
void tearDown(void)
Definition test_main.cpp:28
uint8_t i
int main(void)
void test_multiple_current_amplitudes(void)
Test with multiple current amplitudes (light to heavy load)
uint16_t generateSineADC(uint16_t sampleIndex, uint16_t dcLevel, int16_t amplitude, float phaseShift=0.0f)
Generate sinusoidal ADC value.
void test_vsquared_accumulation_equivalence(void)
Test V² accumulation equivalence.
void test_dc_offset_compensation(void)
Test with DC offset drift.
NewImplementation newImpl
constexpr uint16_t ADC_MID_POINT
Definition test_main.cpp:31
void test_mathematical_identity(void)
CRITICAL TEST: Prove implementations are IDENTICAL over a full cycle.
void test_random_load_steps(void)
Test with random step changes in current (simulating appliance switching)
uint16_t generateSineADCWithNoise(uint16_t sampleIndex, uint16_t dcLevel, int16_t amplitude, int16_t noiseAmplitude, float phaseShift=0.0f)
Generate sinusoidal ADC value with noise.
void test_daily_solar_profile(void)
Test simulating a full day solar profile.
void test_full_cycle_equivalence(void)
Test complete mains cycle processing equivalence.
SimpleRNG rng
void test_import_export_transitions(void)
Test with import/export transitions (bidirectional power flow)
void test_cloud_shadow_simulation(void)
Test simulating cloud passing over solar panels.
void test_no_accumulator_overflow(void)
Test accumulator behavior over datalog period.
void test_near_adc_limits(void)
Test with maximum values (near ADC limits)
constexpr uint16_t SAMPLES_PER_CYCLE
Definition test_main.cpp:29
void test_stress_50000_cycles(void)
Stress test: 50,000 cycles (~17 minutes at 50Hz)
void test_rms_theoretical_value(void)
Test RMS calculation for known amplitude.
void test_power_export(void)
Test power calculation with 180° phase shift (export)
void test_with_realistic_noise_2lsb(void)
Extended test with realistic ADC noise (±2 LSB)
void test_varying_power_factor_with_noise(void)
Test with varying power factor and noise.
void test_power_unity_power_factor(void)
Test power calculation with unity power factor (V and I in phase)
constexpr float PI
Definition test_main.cpp:28
void test_extended_10000_cycles(void)
Extended test: 10,000 cycles (~200 seconds at 50Hz)
OldImplementation oldImpl
void test_sinusoidal_load_variation(void)
Test with sinusoidally varying current (simulating slow load changes)
void test_power_reactive_load(void)
Test power calculation with 90° phase shift (reactive load)
constexpr uint16_t SAMPLES_PER_HALF_CYCLE
Definition test_main.cpp:30
void test_instant_power_equivalence(void)
Test instantaneous power calculation equivalence.
void test_with_higher_noise_5lsb(void)
Extended test with higher noise (±5 LSB)
void test_scaling_equivalence(void)
Test scaling factor equivalence.
constexpr uint16_t VOLTAGE_AMPLITUDE
Definition test_main.cpp:32
void test_three_phase_simulation(void)
Test multiple phases (3-phase simulation)
constexpr uint16_t CURRENT_AMPLITUDE
Definition test_main.cpp:33
void test_zero_load(void)
Test with zero load (no current)
constexpr uint16_t toLeftAligned(uint16_t rightAligned)
Convert right-aligned ADC to left-aligned.
static void cycle(RemoteLoadCore< NumUnits > &core, const LoadStates(&states)[NumLoads])
Run one mains cycle: feed the states to the core, for the given map.
Definition test_main.cpp:26
void processPolarity(uint16_t rawSample)
Process voltage sample (new method - left aligned)
uint32_t l_filterDC_V
uint16_t i_DCoffset_V
void resetCycle()
Reset accumulators for new cycle.
int32_t l_sumP_atSupplyPoint
uint32_t l_sum_Vsquared
float getAveragePower() const
Get average power per sample.
void processMinusHalfCycle()
Update DC filter at end of half cycle (new method)
static constexpr uint16_t i_DCoffset_V_nom
int16_t i_sampleVminusDC
int16_t getOffsetAsADC() const
Get DC offset as ADC value.
void processVoltage()
Process voltage for RMS calculation (new method)
float getRmsVoltage() const
Get RMS voltage (relative, not calibrated)
void processCurrentRawSample(uint16_t rawSample)
Process current sample and calculate power (new method)
int32_t l_sampleVminusDC
Definition test_main.cpp:43
int16_t getOffsetAsADC() const
Get DC offset as ADC value.
void resetCycle()
Reset accumulators for new cycle.
float getRmsVoltage() const
Get RMS voltage (relative, not calibrated)
void processVoltage()
Process voltage for RMS calculation (old method)
Definition test_main.cpp:85
void processMinusHalfCycle()
Update DC filter at end of half cycle (old method)
Definition test_main.cpp:99
void processPolarity(int16_t rawSample)
Process voltage sample (old method)
Definition test_main.cpp:59
int32_t l_cumVdeltasThisCycle
Definition test_main.cpp:44
int32_t l_sumP_atSupplyPoint
Definition test_main.cpp:48
uint32_t l_sum_Vsquared
Definition test_main.cpp:51
float getAveragePower() const
Get average power per sample.
void processCurrentRawSample(int16_t rawSample)
Process current sample and calculate power (old method)
Definition test_main.cpp:67
Structure to hold test statistics for comparison.
int32_t oldSumP
int32_t newSumP
const char * testName
int16_t minCurrent
int16_t maxCurrent
void print() const
uint32_t oldSumVsq
uint32_t newSumVsq