49static_assert(
MAX_SAMPLE_SETS_PER_DATALOG <= UINT16_MAX,
"******** The counter of the sample sets of a datalog period would overflow ! ********");
53 "******** The datalog power sum would overflow ! ********");
74 return static_cast< int32_t
>(lower
151template<
typename T,
size_t N >
154 for (
size_t i = 0;
i < N; ++
i)
176 uint16_t output_pins{ 0 };
204 const auto relayPin =
relayDiverter.get_relay(idx).get_pin();
206 if (
bit_read(output_pins, relayPin))
209 bit_set(output_pins, relayPin);
233 uint16_t input_pins{ 0 };
302 constexpr uint32_t filterDC_V_nom =
static_cast< uint32_t
>(
i_DCoffset_V_nom) << 15;
321 infoln(F(
"RF module initialized"));
325 infoln(F(
"RF module initialization FAILED"));
332 infoln(F(
"Remote loads initialized"));
347 | bit(ADPS2) | bit(ADPS1) | bit(ADPS0);
361 uint16_t load_pins{ 0 };
394 uint16_t pinsON{ 0 };
395 uint16_t pinsOFF{ 0 };
481 [overrideBitmask, remoteOverrideBitmask](
const uint8_t iLoad) __attribute__((always_inline)) {
485 bool bOverrideActive{ (overrideBitmask & pgm_read_word(&overrideMasks.local[iLoad])) != 0 };
488 bOverrideActive = bOverrideActive || ((remoteOverrideBitmask & pgm_read_byte(&overrideMasks.remote[iLoad])) != 0);
490 return bOverrideActive;
543 int16_t sampleIminusDC = (rawSample | 32U) -
i_DCoffset_V[phase];
553 sampleIminusDC = ctFilter[phase].
apply(sampleIminusDC, ctFilterCoefficients);
559 const int16_t filtI_div4{ sampleIminusDC >> 2 };
637 int32_t inst_Vsquared_signed;
639 uint32_t inst_Vsquared =
static_cast< uint32_t
>(inst_Vsquared_signed);
645 inst_Vsquared >>= 12;
812 int32_t sumP{
l_sumP[phase] };
813 uint8_t index{
static_cast< uint8_t
>(n -
N_MIN) };
818 sumP = (sumP / n) *
N_MIN;
1063 info(F(
"Output mode: "));
1070 infoln(F(
"anti-flicker"));
1072 info(F(
"\toffsetOfEnergyThresholds = "));
1075 info(F(
"\tl_capacityOfEnergyBucket_main = "));
1077 info(F(
"\tl_lowerEnergyThreshold = "));
1079 info(F(
"\tl_upperEnergyThreshold = "));
1148 uint16_t adc_raw = ADC;
1150 if ((
_ctx->index & 1) == 0)
1163 ADMUX =
_ctx->admux;
The six ADC conversions of the 3-phase board, and the ADMUX pipeline of the free-running ADC.
constexpr uint8_t loadPrioritiesAtStartup[NO_OF_DUMPLOADS]
constexpr bool ROUTER_OFF_PIN_PRESENT
constexpr bool RELAY_DIVERSION
constexpr bool OVERRIDE_PIN_PRESENT
constexpr uint8_t dualTariffPin
constexpr PcbVersion PCB_VERSION
constexpr uint8_t physicalLoadPin[NO_OF_DUMPLOADS]
constexpr bool DUAL_TARIFF
constexpr uint8_t diversionPin
constexpr uint8_t NO_OF_DUMPLOADS
constexpr uint8_t routerOffPin
constexpr bool WATCHDOG_PIN_PRESENT
constexpr bool DIVERSION_PIN_PRESENT
constexpr uint8_t rotationPin
constexpr uint8_t watchDogPin
The configuration as the firmware uses it: the settings, and what is built from them.
RemoteLoadCore< NO_OF_REMOTE_UNITS > remoteLoads
The one and only remote-load controller.
constexpr Rotation::Table rotationTable
The priority places each rotation group rotates in.
constexpr uint32_t MAX_SAMPLE_SETS_PER_DATALOG
constexpr bool REMOTE_LOADS_PRESENT
constexpr RelayDiverter relayDiverter
constexpr float f_powerCal[NO_OF_PHASES]
constexpr uint8_t DATALOG_POWER_SHIFT
constexpr OverrideTable overrideTable
constexpr int16_t REQUIRED_EXPORT_IN_WATTS
constexpr uint32_t WORKING_ZONE_IN_JOULES
constexpr conditional< DATALOG_PERIOD_IN_SECONDS *SUPPLY_FREQUENCY >=UINT8_MAX, uint16_t, uint8_t >::type DATALOG_PERIOD_IN_MAINS_CYCLES
constexpr uint8_t DATALOG_PERIOD_IN_SECONDS
constexpr uint8_t NO_OF_PHASES
constexpr uint8_t SUPPLY_FREQUENCY
constexpr int16_t DIVERSION_START_THRESHOLD_WATTS
The CT filter: a low-pass of the current added back with a gain, one per phase.
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.
void info(const Args &... args)
Print an informational message, as Serial.print() does.
void infolnDecimals(const int32_t value, const uint8_t decimals)
Print a value given as an integer with a fixed number of decimals, and a line end.
The scheduled boosts of the dual tariff, resolved at compile time.
constexpr BoostTable boostTable PROGMEM
Integer arithmetic of the energy bucket.
constexpr uint16_t getLoadPins()
The pins the loads drive: the local TRIACs, plus the status LED of each remote load.
constexpr void initializeArray(T(&array)[N], T value)
Initializes all elements of a given array to a specified value.
constexpr uint16_t getInputPins()
Retrieves the input pins configuration.
void printParamsForSelectedOutputMode()
Print the settings used for the selected output mode.
constexpr uint16_t getOutputPins()
Retrieves the output pins configuration.
void initializeProcessing()
Initializes the processing engine, including ports, load states, and ADC setup.
void updatePhysicalLoadStates()
Updates the physical load states based on logical load priorities and states.
void processLatestContribution(const uint8_t phase)
Process the latest contribution after each phase-specific new cycle.
void updatePortsStates()
Updates the control ports for each of the physical loads.
void processStartUp(const uint8_t phase)
Processes the startup period for the router.
static void multS16x16_to32(int32_t &result, A a, B b)
Optimized 16×16→32 signed multiplication with assembly.
void processStartNewCycle()
Processes the start of a new mains cycle on phase 0.
void processMinusHalfCycle(const uint8_t phase)
Processes the start of a new negative half cycle for the specified phase.
void processRawSamples(const uint8_t phase)
Processes raw voltage and current samples for the specified phase.
void processPolarity(const uint8_t phase, const uint16_t rawSample)
Processes the polarity of the current voltage sample for a specific phase.
void processPlusHalfCycle(const uint8_t phase)
Process the start of a new positive half cycle for the specified phase.
void processDataLogging()
Process data logging at the end of each logging period.
void processCurrentRawSample(const uint8_t phase, const uint16_t rawSample)
Processes the current raw sample for the specified phase.
void processVoltageRawSample(const uint8_t phase, const uint16_t rawSample)
Processes the current voltage raw sample for the specified phase.
void confirmPolarity(const uint8_t phase)
Confirms the polarity of the current voltage sample for a specific phase.
void processVoltage(const uint8_t phase)
Processes the current voltage sample for the specified phase.
The load priority state machine: which load to switch at each mains cycle.
constexpr uint8_t loadStateMask
constexpr uint8_t loadStateOnBit
Assembly-optimized multiplication functions for AVR microcontrollers.
constexpr uint8_t admuxOf(const PcbVersion board, const Channel ch)
The ADMUX value that converts a channel: reference, left-adjusted result, analog input.
constexpr uint8_t BIT_REFS0
constexpr uint8_t BIT_REFS1
constexpr uint8_t BIT_ADLAR
constexpr uint8_t admuxWrittenAfter(const PcbVersion board, const Channel converted)
The ADMUX value the interrupt writes after the conversion of a channel.
constexpr uint8_t NO_OF_CONVERSIONS
constexpr Coefficients coefficientsOf(const float gain, const float alpha)
Converts the float settings to fixed point, at compile time.
int32_t contribution(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
Contribution of one mains cycle of one phase to the bucket.
constexpr PerSampleCalibration< NMin, NMax, N > toFixedPerSample(const float(&cal)[N])
Build the per-sample calibration table at compile time.
constexpr int32_t fromWatts(const int32_t watts)
A power in watts, in bucket units per mains cycle.
void toPhysical(const uint8_t(&priorities)[N], LoadStates(&physical)[N], const bool diversionEnabled, IsOverridden isOverridden)
Maps the logical load states to the physical ones.
constexpr bool isLocal(uint8_t entry)
True if the entry describes a locally driven load.
constexpr uint8_t pinOf(uint8_t entry)
The pin of the entry: TRIAC pin if local, status LED (0 = none) if remote.
constexpr OverrideMasks< N > overrideMasks(const uint8_t(&map)[N])
Build the override bits of a load map.
constexpr int32_t toDecimals(float value, uint8_t decimals)
A float constant as an integer with the given number of decimals, rounded.
volatile uint16_t overrideBitmask
volatile bool b_datalogEventPending
volatile bool b_reOrderLoads
volatile uint16_t copyOf_sampleSetsDuringThisDatalogPeriod
volatile int32_t copyOf_sumP_atSupplyPoint[NO_OF_PHASES]
volatile int32_t copyOf_energyInBucket_main
volatile uint8_t copyOf_lowestNoOfSampleSetsPerMainsCycle
volatile uint16_t copyOf_countLoadON[NO_OF_DUMPLOADS]
volatile uint8_t remoteOverrideBitmask
volatile uint16_t absenceOfDivertedEnergyCountInSeconds
volatile uint32_t copyOf_sum_Vsquared[NO_OF_PHASES]
volatile bool b_newMainsCycle
volatile bool b_diversionEnabled
Polarities polarityConfirmedOfLastSampleV[NO_OF_PHASES]
uint8_t n_lowestNoOfSampleSetsPerMainsCycle
static adc_ctx_t _channels[AdcChain::NO_OF_CONVERSIONS]
constexpr OutputModes outputMode
uint32_t absenceOfDivertedEnergyCountInMC
constexpr int32_t l_capacityOfEnergyBucket_main
uint16_t countLoadON[NO_OF_DUMPLOADS]
constexpr float f_offsetOfEnergyThresholdsInAFmode
LoadPriorities::Switching< NO_OF_DUMPLOADS > loadSwitching
remove_cv< remove_reference< decltype(DATALOG_PERIOD_IN_MAINS_CYCLES)>::type >::type n_cycleCountForDatalogging
LoadStates physicalLoadState[NO_OF_DUMPLOADS]
constexpr uint8_t powerCalPerSampleShift
constexpr LoadPriorities::Bucket bucketLevels
constexpr int32_t l_upperThreshold_default
uint32_t l_filterDC_V[NO_OF_PHASES]
int32_t l_sumP[NO_OF_PHASES]
constexpr int32_t l_midPointOfEnergyBucket_main
Polarities polarityConfirmed[NO_OF_PHASES]
uint8_t n_samplesDuringThisMainsCycle[NO_OF_PHASES]
constexpr int32_t initThreshold(const bool lower)
set default threshold at compile time so the variable can be read-only
int16_t i_sampleVminusDC[NO_OF_PHASES]
constexpr uint16_t i_DCoffset_V_nom
Polarities polarityOfMostRecentSampleV[NO_OF_PHASES]
uint16_t i_sampleSetsDuringThisDatalogPeriod
constexpr int32_t l_lowerThreshold_default
uint32_t l_sum_Vsquared[NO_OF_PHASES]
constexpr uint32_t FULL_SCALE_PER_SAMPLE
uint16_t i_DCoffset_V[NO_OF_PHASES]
int32_t l_sumP_atSupplyPoint[NO_OF_PHASES]
int32_t l_energyInBucket_main
Public functions/variables of processing engine.
constexpr uint16_t startUpPeriod
constexpr uint8_t PERSISTENCE_FOR_POLARITY_CHANGE
uint8_t loadPrioritiesAndState[NO_OF_DUMPLOADS]
constexpr uint16_t initialDelay
The coefficients of the filter, in fixed point: the multiples the filter needs, ready.
The state of the filter of one CT (one per phase), and the filter itself.
int16_t apply(const int16_t sampleMinusDC, const Coefficients &coefficients)
Filters one sample.
cal / n for every phase and every expected sample count n, in fixed point.
The fixed levels of the energy bucket, in bucket units.
The switching decision, once per mains cycle, and its state.
Override bit of each load, in the local or in the remote override bitmask.
Interrupt Service Routine - Interrupt-Driven Analog Conversion.
constexpr void bit_set(T &_dest, const uint8_t bit)
Set the specified bit to 1.
constexpr uint8_t bit_read(const T &_src, const uint8_t bit)
Read the specified bit.
Some utility functions for pins manipulation.
void setPinsState(uint16_t pinsON, uint16_t pinsOFF)
Switch pins ON and OFF, with one write per port.
void setPinsAsInputPullup()
Set the pins as INPUT_PULLUP.
void setPinsAsOutput()
Set the pins as OUTPUT.
constexpr bool RF_CHIP_PRESENT
bool initialize_rf()
Initialize the shared RF module.