3-phase PV router
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1
24
25static_assert(__cplusplus >= 201703L, "**** Please define 'gnu++17' in 'platform.txt' ! ****");
26static_assert(__cplusplus >= 201703L, "See also : https://github.com/FredM67/PVRouter-3-phase/blob/main/Mk2_3phase_RFdatalog_temp/Readme.md");
27
28#include <Arduino.h> // may not be needed, but it's probably a good idea to include this
29
30#include "config_derived.h"
31
32// In this sketch, the ADC is free-running with a cycle time of ~104uS.
33
34#include "datalog_math.h"
35#include "pin_edges.h"
36#include "processing.h"
37#include "shared_var.h"
38#include "types.h"
39#include "utils.h"
40#include "utils_relay.h"
41#include "validation.h"
42#include "main.h"
43#include "override_masks.h"
44#include "temp_schedule.h"
45
46// -------------- general global variables -----------------
47//
48// Some of these variables are used in multiple blocks so cannot be static.
49// For integer maths, some variables need to be 'int32_t'
50//
51
54
57
77OverrideMasks getDualTariffForcingBitmask(const bool bOffPeak, const int16_t currentTemperature_x100)
78{
79 if constexpr (!DUAL_TARIFF)
80 {
81 return { 0, 0 };
82 }
83
84 constexpr int16_t iTemperatureThreshold_x100{ iTemperatureThreshold * 100 };
85
86 return Forcing::boostForcing(bOffPeak, static_cast< uint32_t >(millis() - ul_TimeOffPeak), currentTemperature_x100,
87 iTemperatureThreshold_x100, NO_OF_BOOSTS, readBoost);
88}
89
113OverrideMasks getOverrideBitmask(const bool bOffPeak, const int16_t currentTemperature_x100)
114{
115 OverrideMasks masks{ 0, 0 };
116
117 // Add external override pins
118 if constexpr (OVERRIDE_PIN_PRESENT)
119 {
120 masks = Forcing::pinForcing(overrideTable, [](const uint8_t pin)
121 {
122 return !getPinState(pin); // Pin is LOW (active)
123 });
124 }
125
126 // Add dual tariff forcing - OR operation handles precedence automatically
127 return masks | getDualTariffForcingBitmask(bOffPeak, currentTemperature_x100);
128}
129
141template< uint8_t pin >
146
156{
157 if constexpr (DIVERSION_PIN_PRESENT)
158 {
160
161 if (pin.changed)
162 {
163 statusln(pin.active ? F("Trigger diversion OFF!") : F("End diversion OFF!"));
164 }
165
166 return !pin.active;
167 }
168 else
169 {
170 return true;
171 }
172}
173
183{
184 if constexpr (CALIBRATION_MODE)
185 {
186 return true;
187 }
188 else if constexpr (ROUTER_OFF_PIN_PRESENT)
189 {
191
192 if (pin.changed)
193 {
194 statusln(pin.active ? F("Router OFF!") : F("Router ON!"));
195 }
196
197 return pin.active;
198 }
199 else
200 {
201 return false;
202 }
203}
204
219{
221
222 // waits till the priorities have been rotated from inside the ISR
223 do
224 {
225 delay(10);
226 } while (Shared::b_reOrderLoads);
227
228 // prints the (new) load priorities
230}
231
250{
252
253 if (pin.pressed())
254 {
255 // we start off-peak period
256 statusln(F("Change to off-peak period!"));
257
258 ul_TimeOffPeak = millis();
259
260 if constexpr (PRIORITY_ROTATION == RotationModes::AUTO)
261 {
263 }
264 }
265
266 // end of off-peak period
267 if (pin.released())
268 {
269 statusln(F("Change to peak period!"));
270 }
271
272 return pin.active;
273}
274
294void proceedLoadPriorities(const bool bOverridden)
295{
296 if constexpr (PRIORITY_ROTATION == RotationModes::PIN)
297 {
299
300 if (isRotationRequested(pin, bOverridden))
301 {
302 statusln(F("Trigger rotation!"));
303
305 }
306 }
307 else if constexpr (PRIORITY_ROTATION == RotationModes::AUTO && !DUAL_TARIFF)
308 {
310 {
312
314 }
315 }
316}
317
335void setup()
336{
337 delay(initialDelay); // allows time to open the Serial Monitor
338
339 // 8N1 even for the IoT output, so the startup configuration shows on a serial monitor with its
340 // default settings: 7E1 comes at the end of setup().
342
343 // On start, display config info in the serial monitor (human-readable and IoT outputs)
345
346 // initializes all loads to OFF at startup
348
349 // The control inputs are then read once per second: read them now, before the first load decision
351
353
354 if constexpr (TEMP_SENSOR_PRESENT)
355 {
356 tempSensors.printSensorsOnBus(); // empty unless CALIBRATION_MODE
357 tempSensors.initTemperatureSensors();
358 for (auto &reading : temperatureReadings)
359 {
360 reading = DEVICE_DISCONNECTED_RAW; // not sent until read
361 }
362 }
363
364 debug(F(">>free RAM = "));
365 debugln(freeRam()); // a useful value to keep an eye on
366 infoln(F("----"));
367
369}
370
386{
387 // the calibration constants in fixed point, converted at compile time: no float code (#120)
388 static constexpr auto powerCal PROGMEM{ Datalog::powerCalibration(f_powerCal) };
390
391 tx_data.power = 0;
392 uint8_t phase{ NO_OF_PHASES };
393 do
394 {
395 --phase;
396 const uint16_t sampleSets{ Shared::copyOf_sampleSetsDuringThisDatalogPeriod };
397
398 // import = +ve: the sum of the ISR is negative when importing
400 pgm_read_word(&powerCal.value[phase]), powerCal.shift);
401
402 tx_data.power += tx_data.power_L[phase];
403
404 tx_data.Vrms_L_x100[phase] = Datalog::vrms(Shared::copyOf_sum_Vsquared[phase] / sampleSets,
405 pgm_read_word(&voltageCal.value[phase]), voltageCal.shift);
406 } while (phase);
407}
408
422void runTemperatureTransaction(const bool onTime)
423{
424 const TempSchedule::Action action{ tempSchedule.next(onTime) };
425 switch (action.step)
426 {
428 tempSensors.requestTemperatures();
429 break;
431 if (!tempSensors.startRead(action.sensor))
432 {
433 temperatureReadings[action.sensor] = DEVICE_DISCONNECTED_RAW; // no answer to the reset
434 tempSchedule.skipRestOf(action.sensor);
435 }
436 break;
438 tempSensors.readScratchpad(action.sensor);
439 break;
441 temperatureReadings[action.sensor] = tempSensors.endRead();
442 break;
443 default:
444 break;
445 }
446}
447
468void processTemperatureData(const bool bStartNow)
469{
470 // 85.00 °C more than 5.00 °C away from the last valid reading: the power-on value, skipped
471 static DS18B20::PowerOnFilter powerOnFilter[tempSensors.size()];
472
473 uint8_t idx{ tempSensors.size() };
474 do
475 {
476 --idx;
477 tx_data.temperature_x100[idx] = powerOnFilter[idx](temperatureReadings[idx]);
478 } while (idx);
479
480 // the next round: its conversion now, in the cycle that ends the period (which had no transaction,
481 // the round being over), or with the next cycle
482 if (tempSchedule.newPeriod() && bStartNow)
483 {
485 }
486}
487
512void handlePerSecondTasks(bool &bOffPeak, int16_t &iTemperature_x100)
513{
514 if constexpr (WATCHDOG_PIN_PRESENT)
515 {
517 }
518
519 // Tariff transitions must be tracked every second, whatever the override state:
520 // dual tariff forcing depends on the off-peak start timestamp set here.
521 if constexpr (DUAL_TARIFF)
522 {
523 bOffPeak = proceedDualTariffLogic();
524 }
525
526 // Router OFF: no forcing and no diversion, so every load and relay is OFF
527 const bool bRouterOff{ isRouterOff() };
528 const bool bDiversionEnabled{ !bRouterOff && isDiversionEnabled() };
529
530 // Get complete override bitmasks atomically (external pins + dual tariff forcing)
531 const OverrideMasks privateOverrideMasks{ bRouterOff ? OverrideMasks{ 0, 0 } : getOverrideBitmask(bOffPeak, iTemperature_x100) };
532
533 if constexpr (RELAY_DIVERSION)
534 {
535 relayDiverter.inc_duration();
536 relayDiverter.proceed_relays(privateOverrideMasks.local, bDiversionEnabled);
537 }
538
539 // Copy to the shared versions for ISR access
540 Shared::b_diversionEnabled = bDiversionEnabled;
541 Shared::overrideBitmask = privateOverrideMasks.local;
542 Shared::remoteOverrideBitmask = privateOverrideMasks.remote;
543
544 // no rotation while anything is forced (local or remote)
545 proceedLoadPriorities(privateOverrideMasks.local || privateOverrideMasks.remote);
546}
547
564void loop()
565{
566 static uint8_t perSecondTimer{ 0 };
567 static bool bOffPeak{ false };
568 static int16_t iTemperature_x100{ 0 };
569
570 const bool bNewMainsCycle{ Shared::b_newMainsCycle }; // set once per mains cycle, by the ADC interrupt
571 if (bNewMainsCycle)
572 {
573 Shared::b_newMainsCycle = false; // reset the flag
574 }
575
576 [[maybe_unused]] uint32_t cycleSeen_us{ 0 }; // temperature sensing: when this pass saw the new cycle
577 [[maybe_unused]] bool bCycleOnTime{ false }; // ... and whether on time
578
579 if constexpr (TEMP_SENSOR_PRESENT)
580 {
581 // The flag was set at most one loop pass ago: on time if the last pass was short (the loop
582 // idle when the cycle began), late after a long one (per-second work, datalog, RF frame).
583 constexpr uint32_t ON_TIME_US{ 1000 };
584 static uint32_t passStart_us{ 0 };
585 const uint32_t now_us{ micros() };
586 const bool bOnTime{ (now_us - passStart_us) < ON_TIME_US };
587 passStart_us = now_us;
588
589 if (bNewMainsCycle)
590 {
591 cycleSeen_us = now_us;
592 bCycleOnTime = bOnTime;
593 runTemperatureTransaction(bOnTime); // first: its long slots must end before the next cycle's work
594 }
595 }
596
597 // Write the datalog output in progress, as far as the serial buffer allows (never waits)
599
600 // Process any pending RF transmissions (called outside ISR to avoid blocking)
601 if constexpr (REMOTE_LOADS_PRESENT)
602 {
604 }
605
606 if (bNewMainsCycle)
607 {
608 ++perSecondTimer;
609
610 if (perSecondTimer >= SUPPLY_FREQUENCY)
611 {
612 perSecondTimer = 0;
613 handlePerSecondTasks(bOffPeak, iTemperature_x100);
614 }
615 }
616
617 // With temperature sensing, the end of the period waits for the pass that sees the new cycle, so
618 // that the next round's conversion starts after the cycle's work and before the datalog output.
619 // The timing, a sample set being 6 conversions (624 µs, whatever the mains frequency):
620 // - L1's positive crossing: the period's datalog copies (processDataLogging(), from
621 // processPlusHalfCycle()), then b_datalogEventPending;
622 // - 2 sample sets later (1248 µs): the cycle's work, processStartNewCycle(), the heaviest call
623 // (its ADMUX written ~660 to 780 cycles in with 4 loads: sim/README.md, Temperature with remote
624 // loads, RF datalog and relays), then b_newMainsCycle;
625 // - the next such call, a mains cycle later.
626 // The conversion (reset, Skip ROM, Convert T: ~2.1 ms of bus I/O) cannot fit between the event
627 // and processStartNewCycle(); started after it, its slots fall among the ordinary calls.
628 if (Shared::b_datalogEventPending && (bNewMainsCycle || !TEMP_SENSOR_PRESENT))
629 {
631
633
634 if constexpr (RELAY_DIVERSION)
635 {
636 relayDiverter.update_average(tx_data.power);
637 }
638
639 if constexpr (TEMP_SENSOR_PRESENT)
640 {
641 // On time if this pass saw the new cycle on time and is still within 3 ms of it (the per-second
642 // work may run in between): the conversion's slots then end within ~6 ms of the cycle's work
643 constexpr uint32_t PERIOD_END_ON_TIME_US{ 3000 };
644 processTemperatureData(bCycleOnTime && (micros() - cycleSeen_us) < PERIOD_END_ON_TIME_US);
645
646 // the sensor checked against the dual tariff temperature threshold
647 iTemperature_x100 = tx_data.temperature_x100[BOOST_TEMP_SENSOR];
648 }
649
650 sendResults(bOffPeak);
651 }
652} // end of loop()
The round of the sensors, one transaction per mains cycle.
constexpr bool ROUTER_OFF_PIN_PRESENT
Definition config.h:58
constexpr bool RELAY_DIVERSION
Definition config.h:63
constexpr bool OVERRIDE_PIN_PRESENT
Definition config.h:60
constexpr uint32_t ROTATION_AFTER_SECONDS
Definition config.h:181
constexpr bool DUAL_TARIFF
Definition config.h:64
constexpr bool CALIBRATION_MODE
Definition config.h:35
constexpr bool TEMP_SENSOR_PRESENT
Definition config.h:65
constexpr int16_t iTemperatureThreshold
Definition config.h:174
constexpr bool WATCHDOG_PIN_PRESENT
Definition config.h:62
constexpr uint8_t BOOST_TEMP_SENSOR
Definition config.h:175
constexpr bool DIVERSION_PIN_PRESENT
Definition config.h:57
constexpr uint8_t watchDogPin
Definition config.h:107
The configuration as the firmware uses it: the settings, and what is built from them.
constexpr float f_voltageCal[NO_OF_PHASES]
constexpr bool REMOTE_LOADS_PRESENT
constexpr RelayDiverter relayDiverter
constexpr float f_powerCal[NO_OF_PHASES]
constexpr TempSensors tempSensors
constexpr OverrideTable overrideTable
constexpr uint8_t DATALOG_PERIOD_IN_SECONDS
constexpr uint8_t NO_OF_PHASES
constexpr uint8_t SUPPLY_FREQUENCY
Integer arithmetic of the datalog: power and RMS voltage per phase.
void infoln(const Args &... args)
Print an informational message and a line end, as Serial.println() does.
Definition debug.h:67
void statusln(const Args &... args)
Print a status message and a line end, as Serial.println() does (human-readable output only).
Definition debug.h:131
void debugln(const Args &... args)
Print a debug message and a line end, as Serial.println() does (only with ENABLE_DEBUG).
Definition debug.h:155
void debug(const Args &... args)
Print a debug message, as Serial.print() does (only with ENABLE_DEBUG).
Definition debug.h:143
constexpr int16_t DEVICE_DISCONNECTED_RAW
Definition ds18b20.h:38
constexpr BoostTable boostTable PROGMEM
Definition dualtariff.h:52
uint32_t ul_TimeOffPeak
Definition dualtariff.h:20
constexpr uint8_t NO_OF_BOOSTS
Definition dualtariff.h:22
static volatile float powerCal[]
Definition test_main.cpp:31
static volatile float voltageCal[]
Definition test_main.cpp:32
DualTariff::Boost readBoost(const uint8_t i)
Reads scheduled boost i from flash.
Definition dualtariff.h:62
OverrideMasks getDualTariffForcingBitmask(const bool bOffPeak, const int16_t currentTemperature_x100)
Calculates the dual tariff forcing bitmasks based on current conditions.
Definition main.cpp:77
void updatePowerAndVoltageData()
Updates power and voltage data for all phases.
Definition main.cpp:385
bool isRouterOff()
Tells whether the router is OFF.
Definition main.cpp:182
OverrideMasks getOverrideBitmask(const bool bOffPeak, const int16_t currentTemperature_x100)
Gets the combined bitmasks of all active override pins and dual tariff forcing.
Definition main.cpp:113
void handlePerSecondTasks(bool &bOffPeak, int16_t &iTemperature_x100)
Handles tasks that need to be executed every second.
Definition main.cpp:512
bool isDiversionEnabled()
Reads the diversion pin.
Definition main.cpp:155
bool proceedDualTariffLogic()
Handles dual tariff state transitions and priority rotation during off-peak periods.
Definition main.cpp:249
void proceedLoadPriorities(const bool bOverridden)
Handles load priority rotation.
Definition main.cpp:294
void proceedRotation()
Proceeds with load priority rotation.
Definition main.cpp:218
PinEdges readPinEdges()
Reads an active-LOW input pin, and tells how it changed since the previous reading.
Definition main.cpp:142
void sendResults(bool bOffPeak)
Prints or sends telemetry data logs based on the selected output format.
Definition utils.h:602
void logLoadPriorities()
Prints the load priorities to the Serial output.
Definition utils.h:660
void loop()
Main processor loop.
Definition main.cpp:564
void setup()
Called once during startup.
Definition main.cpp:335
void printConfiguration()
Print the configuration during startup.
Definition utils.h:142
int freeRam()
Get the available RAM during setup.
Definition utils.h:681
void initializeProcessing()
Initializes the processing engine, including ports, load states, and ADC setup.
void runTemperatureTransaction(const bool onTime)
Runs the 1-Wire transaction of this mains cycle, if any.
Definition main.cpp:422
void processTemperatureData(const bool bStartNow)
Processes temperature data from DS18B20 sensors.
Definition main.cpp:468
TempSchedule::Scheduler< tempSensors.size(), TempSchedule::conversionCycles(SUPPLY_FREQUENCY) > tempSchedule
The round of the temperature sensors: one 1-Wire transaction per mains cycle (temp_schedule....
Definition main.cpp:53
int16_t temperatureReadings[tempSensors.size()]
The last reading of each sensor, in hundredths of °C, as endRead() returned it (none yet: setup()).
Definition main.cpp:56
Header file for the main application.
constexpr uint16_t vrmsFactor(const uint8_t datalogPeriodInSeconds)
Scaling of the datalog voltage, Vrms_L_x100.
constexpr FixedCalibration< N > voltageCalibration(const uint16_t factor, const float(&cal)[N])
The voltage calibration in fixed point, for vrms(), built at compile time.
int16_t watts(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
The average power of a phase, in watts.
constexpr FixedCalibration< N > powerCalibration(const float(&cal)[N])
The power calibration in fixed point, for watts(), built at compile time.
int32_t averagePower(const int32_t sum, const Count sampleSets)
The average power of a datalog period, back at the x1 scale of V_ADC x I_ADC.
uint16_t vrms(const uint32_t meanSquare, const uint16_t calFixed, const uint8_t shift)
The RMS voltage of a phase.
OverrideMasks boostForcing(const bool bOffPeak, const uint32_t elapsed, const int16_t temperature_x100, const int16_t threshold_x100, const uint8_t count, ReadBoost readBoost)
The targets of the scheduled boosts whose window is open.
OverrideMasks pinForcing(const Pins &pins, IsActive isActive)
The targets of the override pins that are active (held LOW).
void beginStartupText()
Serial settings for the startup text: 9600 baud 8N1, the default of serial monitors.
void endStartupText()
Serial settings after the startup text: 7E1 for the IoT telemetry frames, as the mk2Wifi module expec...
void poll(Print &out=Serial)
Write as many steps as the transmit buffer can take, without waiting.
volatile uint16_t overrideBitmask
Definition shared_var.h:15
volatile bool b_datalogEventPending
Definition shared_var.h:11
volatile bool b_reOrderLoads
Definition shared_var.h:13
volatile uint16_t copyOf_sampleSetsDuringThisDatalogPeriod
Definition shared_var.h:27
volatile int32_t copyOf_sumP_atSupplyPoint[NO_OF_PHASES]
Definition shared_var.h:23
volatile uint8_t remoteOverrideBitmask
Definition shared_var.h:16
volatile uint16_t absenceOfDivertedEnergyCountInSeconds
Definition shared_var.h:18
volatile uint32_t copyOf_sum_Vsquared[NO_OF_PHASES]
Definition shared_var.h:24
volatile bool b_newMainsCycle
Definition shared_var.h:12
volatile bool b_diversionEnabled
Definition shared_var.h:14
constexpr uint16_t conversionCycles(const uint8_t supplyFrequency)
The mains cycles from the conversion to the first read.
The forced outputs: the override pins, and the scheduled boosts of the dual tariff.
The edges of the active-LOW input pins: pressed, released, or no change.
constexpr bool isRotationRequested(const PinEdges &pin, const bool bOverridden)
Tells whether the rotation pin asks for a rotation now.
Definition pin_edges.h:87
PinEdges trackPinEdges(const bool active)
Gives the edges of a pin from its current level, and keeps that level for the next call.
Definition pin_edges.h:70
Public functions/variables of processing engine.
PayloadTx_struct< NO_OF_PHASES, TEMP_SENSOR_PRESENT ? tempSensors.size() :0 > tx_data
Definition processing.h:26
constexpr uint16_t initialDelay
Definition processing.h:22
void processRemoteLoadTransmissions()
Process pending RF transmissions.
The readings of one sensor, the power-on value skipped.
Definition ds18b20.h:162
Holds both local and remote override bitmasks.
State of an active-LOW input pin, and how it changed since the previous reading.
Definition pin_edges.h:30
bool active
Definition pin_edges.h:31
The transaction to run, and the sensor it reads (ADDRESS, READ, CLOSE).
Which 1-Wire transaction of the temperature sensors runs on which mains cycle.
Some basics classes/types.
Some utility functions.
constexpr bool getPinState(uint8_t pin)
Get the Pin State.
Definition utils_pins.h:179
constexpr void togglePin(uint8_t pin)
Toggle the specified pin.
Definition utils_pins.h:56
Some utility functions for the relay output feature.
Compile-time validations.