3-phase PV router
Loading...
Searching...
No Matches
utils.h
Go to the documentation of this file.
1
12
13#ifndef UTILS_H
14#define UTILS_H
15
16#include <Arduino.h>
17
18#include "FastDivision.h"
19
20#include "config_derived.h"
21#include "constants.h"
22#include "dualtariff.h"
23#include "energy_bucket.h"
24#include "processing.h"
25#include "serial_output.h"
26#include "shared_var.h"
27#include "teleinfo.h"
28
29#include "utils_rf.h"
30#include "utils_temp.h"
31
32#include "version.h"
33
41{
42 info(F("\tgroups"));
43 for (uint8_t g = 0; g != rotationTable.size(); ++g)
44 {
45 info(F(" {"));
46 for (uint8_t i = 0; i != NO_OF_DUMPLOADS; ++i)
47 {
48 if (rotationTable.loads(g) & (1UL << i))
49 {
50 info(F(" "));
51 info(i);
52 }
53 }
54 info(F(" }"));
55 }
56 infoln(F(""));
57}
58
67inline void infolnPresence(const bool present)
68{
69 infoln(present ? F("is present") : F("is NOT present"));
70}
71
80inline void printCalibrationLine(const __FlashStringHelper* name, const uint8_t phase, const int32_t* value,
81 const uint8_t decimals)
82{
83 info(name);
84 info(F(" for L"));
85 info(phase + 1);
86 info(F(" = "));
87 infolnDecimals_P(value, decimals);
88}
89
101template< bool newBoard >
102inline void printCalibration(const uint8_t phase)
103{
104 if constexpr (newBoard)
105 {
106 static constexpr auto ctRating_x100 PROGMEM{ SerialOutput::toDecimals(f_ctRating, 2) };
107 static constexpr auto powerCalPerAmp_x1e8 PROGMEM{ SerialOutput::toDecimals(f_powerCalPerAmp, 8) };
108 static constexpr auto voltageCalNewBoard_x1e6 PROGMEM{ SerialOutput::toDecimals(f_voltageCalNewBoard, 6) };
109
110 printCalibrationLine(F("\tf_ctRating"), phase, &ctRating_x100.value[phase], 2);
111
112 printCalibrationLine(F("\tf_powerCalPerAmp"), phase, &powerCalPerAmp_x1e8.value[phase], 8);
113
114 printCalibrationLine(F("\tf_voltageCalNewBoard"), phase, &voltageCalNewBoard_x1e6.value[phase], 6);
115 }
116 else
117 {
118 static constexpr auto powerCalOldBoard_x1e6 PROGMEM{ SerialOutput::toDecimals(f_powerCalOldBoard, 6) };
119 static constexpr auto voltageCalOldBoard_x1e6 PROGMEM{ SerialOutput::toDecimals(f_voltageCalOldBoard, 6) };
120
121 printCalibrationLine(F("\tf_powerCalOldBoard"), phase, &powerCalOldBoard_x1e6.value[phase], 6);
122
123 printCalibrationLine(F("\tf_voltageCalOldBoard"), phase, &voltageCalOldBoard_x1e6.value[phase], 6);
124 }
125}
126
143{
144#ifndef PROJECT_PATH
145#define PROJECT_PATH (__FILE__)
146#endif
147
148#ifndef BRANCH_NAME
149#define BRANCH_NAME ("N/A")
150#endif
151#ifndef COMMIT_HASH
152#define COMMIT_HASH ("N/A")
153#endif
154#ifndef BUILD_ENV
155#define BUILD_ENV ("N/A")
156#endif
157
158 infoln();
159 infoln();
160 infoln(F("----------------------------------"));
161 info(F("Sketch ID: "));
163
164 info(F("From branch '"));
165 info(F(BRANCH_NAME));
166 info(F("', commit "));
168
169 info(F("Build environment: "));
170 infoln(F(BUILD_ENV));
171
172 info(F("Build on "));
173#ifdef CURRENT_TIME
175#else
176 info(F(__DATE__));
177 info(F(" "));
178 infoln(F(__TIME__));
179#endif
180 infoln(F("ADC mode: free-running"));
181 infoln(PCB_VERSION == PcbVersion::NEW ? F("Motherboard: new (internal 1.1 V reference)") : F("Motherboard: old (AVCC reference)"));
182
183 if constexpr (CALIBRATION_MODE)
184 {
185 infoln(F("*** CALIBRATION MODE: no load will ever be switched ***"));
186 }
187
188 // the calibration constants, converted at compile time: no float printing code in the firmware
189 constexpr int32_t phaseCal_x100{ SerialOutput::toDecimals(f_phaseCal, 2) };
190
191 infoln(F("Electrical settings"));
192 for (uint8_t phase = 0; phase < NO_OF_PHASES; ++phase)
193 {
195 }
196
197 info(F("\tf_phaseCal for all phases = "));
198 infolnDecimals(phaseCal_x100, 2);
199
200 info(F("\tExport rate (Watts) = "));
202
203 info(F("\tzero-crossing persistence (sample sets) = "));
205
207
208 info(F("Temperature capability "));
210
211 info(F("Dual-tariff capability "));
213 if constexpr (DUAL_TARIFF)
214 {
216 }
217
218 info(F("Load rotation feature "));
219 infolnPresence(PRIORITY_ROTATION != RotationModes::OFF);
220 if constexpr (PRIORITY_ROTATION != RotationModes::OFF)
221 {
223 }
224
225 info(F("Relay diversion feature "));
227 if constexpr (RELAY_DIVERSION)
228 {
229 relayDiverter.printRelayEngineConfiguration();
230 }
231
232 info(F("Override feature "));
234 if constexpr (OVERRIDE_PIN_PRESENT)
235 {
236 overrideTable.printOverrideConfig();
237 }
238
239 info(F("RF capability "));
240 if constexpr (RF_CHIP_PRESENT)
241 {
242 info(F("IS present, Freq = "));
243 if constexpr (SharedRF::FREQUENCY == RF69_433MHZ)
244 infoln(F("433 MHz"));
245 else if constexpr (SharedRF::FREQUENCY == RF69_868MHZ)
246 infoln(F("868 MHz"));
247 else if constexpr (SharedRF::FREQUENCY == RF69_915MHZ)
248 infoln(F("915 MHz"));
249
250 info(F(" Network ID: "));
252 info(F(" Node ID: "));
254
255 if constexpr (RF_LOGGING_PRESENT)
256 {
257 info(F(" Data logging to Gateway ID: "));
259 }
260
261 if constexpr (REMOTE_LOADS_PRESENT)
262 {
263 info(F(" Remote loads to Node ID: "));
264 for (uint8_t idx = 0; idx != NO_OF_REMOTE_UNITS; ++idx)
265 {
267 info(' ');
268 }
269 infoln();
270 }
271 }
272 else
273 {
274 infolnPresence(false);
275 }
276
277 info(F("Datalogging capability "));
279 {
280 infoln(F("in Human-readable format"));
281 }
282 else if constexpr (SERIAL_OUTPUT_TYPE == SerialOutputType::IoT)
283 {
284 infoln(F("in IoT format"));
285 }
286 else if constexpr (SERIAL_OUTPUT_TYPE == SerialOutputType::JSON)
287 {
288 infoln(F("in JSON format"));
289 }
290 else
291 {
292 infolnPresence(false);
293 }
294}
295
296inline bool datalogOffPeak{ false };
297
314inline bool printJsonStep(Print& out, uint8_t step)
315{
316 if (step == 0)
317 {
318 out.print(F("{\"P\":"));
319 out.print(tx_data.power);
320
321 if constexpr (RELAY_DIVERSION)
322 {
323 out.print(F(",\"R\":"));
324 out.print(relayDiverter.get_average());
325 }
326 return true;
327 }
328 --step;
329
330 if (step < NO_OF_PHASES)
331 {
332 out.print(F(",\"P"));
333 out.print(step + 1);
334 out.print(F("\":"));
335 out.print(tx_data.power_L[step]);
336 return true;
337 }
338 step -= NO_OF_PHASES;
339
340 if constexpr (TEMP_SENSOR_PRESENT)
341 {
342 if (step < tempSensors.size())
343 {
344 if (isValidTemperature(tx_data.temperature_x100[step]))
345 {
346 out.print(F(",\"T"));
347 out.print(step + 1);
348 out.print(F("\":"));
349 SerialOutput::printHundredths(out, tx_data.temperature_x100[step]);
350 }
351 return true;
352 }
353 step -= tempSensors.size();
354 }
355
356 if constexpr (DUAL_TARIFF)
357 {
358 if (step == 0)
359 {
360 out.print(datalogOffPeak ? F(",\"TA\":\"low\"") : F(",\"TA\":\"high\""));
361 return true;
362 }
363 }
364
365 out.println('}');
366 return false;
367}
368
384inline bool printTextStep(Print& out, uint8_t step)
385{
386 if (step == 0)
387 {
389 return true;
390 }
391 if (step == 1)
392 {
393 out.print(F(", P:"));
394 out.print(tx_data.power);
395
396 if constexpr (RELAY_DIVERSION)
397 {
398 out.print(F("/"));
399 out.print(relayDiverter.get_average());
400 }
401 return true;
402 }
403 step -= 2;
404
405 if (step < NO_OF_PHASES)
406 {
407 out.print(F(", P"));
408 out.print(step + 1);
409 out.print(F(":"));
410 out.print(tx_data.power_L[step]);
411 return true;
412 }
413 step -= NO_OF_PHASES;
414
415 if (step < NO_OF_PHASES)
416 {
417 out.print(F(", V"));
418 out.print(step + 1);
419 out.print(F(":"));
420 SerialOutput::printDecimals(out, tx_data.Vrms_L_x100[step], 2);
421 return true;
422 }
423 step -= NO_OF_PHASES;
424
425 if constexpr (TEMP_SENSOR_PRESENT)
426 {
427 if (step < tempSensors.size())
428 {
429 if (isValidTemperature(tx_data.temperature_x100[step]))
430 {
431 out.print(F(", T"));
432 out.print(step + 1);
433 out.print(F(":"));
434 SerialOutput::printDecimals(out, tx_data.temperature_x100[step], 2);
435 }
436 return true;
437 }
438 step -= tempSensors.size();
439 }
440
441 switch (step)
442 {
443 case 0:
444 out.print(F(", (minSampleSets/MC "));
446 return true;
447 case 1:
448 out.print(F(", #ofSampleSets "));
450 return true;
451 case 2:
452 if constexpr (!DUAL_TARIFF && PRIORITY_ROTATION != RotationModes::OFF)
453 {
454 out.print(F(", NoED "));
456 }
457 return true;
458 default:
459 out.println(F(")"));
460 return false;
461 }
462}
463
479{
480 static constexpr uint8_t PHASE_COUNT{ NO_OF_PHASES };
481 static constexpr bool RELAY_DIVERSION{ ::RELAY_DIVERSION };
482 static constexpr uint8_t RELAY_COUNT{ static_cast< uint8_t >(relayDiverter.size()) };
483 static constexpr uint8_t LOAD_COUNT{ NO_OF_DUMPLOADS };
484 static constexpr uint8_t TEMP_COUNT{ TEMP_SENSOR_PRESENT ? static_cast< uint8_t >(tempSensors.size()) : uint8_t{ 0 } };
485 static constexpr bool DUAL_TARIFF{ ::DUAL_TARIFF };
486
487 static_assert(RELAY_COUNT <= 16, "the relay states are kept in 16 bits");
488
489 inline static uint16_t relayStatesAtDatalog{ 0 };
490 inline static uint16_t absenceCountAtDatalog{ 0 };
491
495 static void snapshot()
496 {
497 if constexpr (RELAY_DIVERSION)
498 {
499 uint16_t states{ 0 };
500 for (uint8_t idx = 0; idx != RELAY_COUNT; ++idx)
501 {
502 if (relayDiverter.get_relay(idx).isRelayON())
503 {
504 states |= 1U << idx;
505 }
506 }
507 relayStatesAtDatalog = states;
508 }
510 }
511
512 static int16_t power()
513 {
514 return tx_data.power;
515 }
516 static int16_t phasePower(uint8_t idx)
517 {
518 return tx_data.power_L[idx];
519 }
520 static uint16_t phaseVoltage(uint8_t idx)
521 {
522 return tx_data.Vrms_L_x100[idx];
523 }
524 static int16_t relayAverage()
525 {
526 return static_cast< int16_t >(relayDiverter.get_average());
527 }
528 static bool relayOn(uint8_t idx)
529 {
530 return relayStatesAtDatalog & (1U << idx);
531 }
532 static int16_t loadOnPercent(uint8_t idx)
533 {
534 return static_cast< int16_t >(Shared::copyOf_countLoadON[idx] * 100UL / DATALOG_PERIOD_IN_MAINS_CYCLES);
535 }
536 static bool temperatureValid(uint8_t idx)
537 {
538 return isValidTemperature(tx_data.temperature_x100[idx]);
539 }
540 static int16_t temperature(uint8_t idx)
541 {
542 return tx_data.temperature_x100[idx];
543 }
544 static uint16_t absenceCount()
545 {
547 }
548 static bool offPeak()
549 {
550 return datalogOffPeak;
551 }
552 static uint16_t sampleSets()
553 {
555 }
560};
561
562static_assert(TeleInfo::MAX_STEP_LENGTH <= SerialOutput::MAX_STEP_LENGTH, "a line of the IoT frame must fit a step of the serial output");
563
573inline bool writeTeleInfoStep(Print& out, uint8_t step)
574{
575 char text[TeleInfo::MAX_STEP_LENGTH];
576 uint8_t length;
577 const bool more{ TeleInfo::writeFrameStep< TeleInfoData >(step, text, length) };
578 out.write(text, length);
579 return more;
580}
581
602inline void sendResults(bool bOffPeak)
603{
604 static bool startup{ true };
605
606 if constexpr (RF_CHIP_PRESENT)
607 {
608 initialize_rf(); // returns at once if the module is up, else retries (about 50 ms when it fails)
609 }
610
611 if (startup)
612 {
613 startup = false;
614 return; // reject the first datalogging which is incomplete !
615 }
616
617 if constexpr (RF_LOGGING_PRESENT)
618 {
619 send_rf_data(tx_data); // *SEND RF DATA*
620 }
621
622 // The output is only started here, and written by SerialOutput::poll() from the
623 // main loop. If the previous one is still in progress (it normally takes a small
624 // part of a datalog period), this one is skipped.
625 if (SerialOutput::busy())
626 {
627 return;
628 }
629
631 {
633 }
634 else if constexpr (SERIAL_OUTPUT_TYPE == SerialOutputType::IoT)
635 {
636 datalogOffPeak = bOffPeak;
639 }
640 else if constexpr (SERIAL_OUTPUT_TYPE == SerialOutputType::JSON)
641 {
642 datalogOffPeak = bOffPeak;
644 }
645}
646
660inline void logLoadPriorities()
661{
662 statusln(F("Load Priorities: "));
663 for (const auto& loadPrioAndState : loadPrioritiesAndState)
664 {
665 status(F("\tload "));
666 statusln(loadPrioAndState);
667 }
668}
669
681inline int freeRam()
682{
683 extern int __heap_start, *__brkval;
684 int v;
685 return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
686}
687
688#endif // UTILS_H
constexpr float f_ctRating[NO_OF_PHASES]
Definition calibration.h:52
constexpr float f_phaseCal
Definition calibration.h:68
constexpr float f_powerCalPerAmp[NO_OF_PHASES]
Definition calibration.h:53
constexpr float f_powerCalOldBoard[NO_OF_PHASES]
Definition calibration.h:38
constexpr float f_voltageCalOldBoard[NO_OF_PHASES]
Definition calibration.h:43
constexpr float f_voltageCalNewBoard[NO_OF_PHASES]
Definition calibration.h:54
constexpr bool RELAY_DIVERSION
Definition config.h:63
constexpr bool OVERRIDE_PIN_PRESENT
Definition config.h:60
constexpr PcbVersion PCB_VERSION
Definition config.h:21
constexpr bool RF_LOGGING_PRESENT
Definition config.h:66
constexpr bool DUAL_TARIFF
Definition config.h:64
constexpr bool CALIBRATION_MODE
Definition config.h:35
constexpr SerialOutputType SERIAL_OUTPUT_TYPE
Definition config.h:24
constexpr uint8_t NO_OF_DUMPLOADS
Definition config.h:40
constexpr bool TEMP_SENSOR_PRESENT
Definition config.h:65
The configuration as the firmware uses it: the settings, and what is built from them.
constexpr Rotation::Table rotationTable
The priority places each rotation group rotates in.
constexpr bool REMOTE_LOADS_PRESENT
constexpr uint8_t NO_OF_REMOTE_UNITS
constexpr RelayDiverter relayDiverter
constexpr TempSensors tempSensors
constexpr OverrideTable overrideTable
constexpr int16_t REQUIRED_EXPORT_IN_WATTS
constexpr conditional< DATALOG_PERIOD_IN_SECONDS *SUPPLY_FREQUENCY >=UINT8_MAX, uint16_t, uint8_t >::type DATALOG_PERIOD_IN_MAINS_CYCLES
constexpr uint8_t NO_OF_PHASES
Some constants.
void infoln(const Args &... args)
Print an informational message and a line end, as Serial.println() does.
Definition debug.h:67
void infolnDecimals_P(const int32_t *value, const uint8_t decimals)
Same as infolnDecimals(), with the value read from PROGMEM.
Definition debug.h:110
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 info(const Args &... args)
Print an informational message, as Serial.print() does.
Definition debug.h:57
void status(const Args &... args)
Print a status message, as Serial.print() does (human-readable output only).
Definition debug.h:119
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.
Definition debug.h:100
constexpr bool isValidTemperature(int16_t temperature_x100)
Whether a temperature reading is valid, and so worth sending.
Definition ds18b20.h:146
The scheduled boosts of the dual tariff, resolved at compile time.
constexpr BoostTable boostTable PROGMEM
Definition dualtariff.h:52
uint8_t i
Integer arithmetic of the energy bucket.
void printDualTariffConfiguration()
Print the settings for off-peak period.
Definition dualtariff.h:93
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 printParamsForSelectedOutputMode()
Print the settings used for the selected output mode.
void printConfiguration()
Print the configuration during startup.
Definition utils.h:142
int freeRam()
Get the available RAM during setup.
Definition utils.h:681
void printRotationGroups()
Prints the rotation groups, as load numbers counted from 0 as in LOAD(n): "\tgroups { 0 1 2 }...
Definition utils.h:40
bool printJsonStep(Print &out, uint8_t step)
One step of the datalog in JSON format.
Definition utils.h:314
bool printTextStep(Print &out, uint8_t step)
One step of the datalog in text format.
Definition utils.h:384
bool writeTeleInfoStep(Print &out, uint8_t step)
One step of the telemetry frame, in IoT format: one line (see TeleInfo::writeFrameStep()).
Definition utils.h:573
constexpr int32_t toHundredthsOfJoule(const int32_t units)
An energy in bucket units, in hundredths of a joule (for the datalog).
constexpr uint8_t FREQUENCY
Definition config_rf.h:43
constexpr uint8_t ROUTER_NODE_ID
Definition config_rf.h:47
constexpr uint8_t REMOTE_NODE_ID[]
Node ID of each remote load unit, unit 1 first (only if REMOTE_LOADS_PRESENT=true)
Definition config_rf.h:53
constexpr uint8_t NETWORK_ID
Definition config_rf.h:46
constexpr uint8_t GATEWAY_ID
Definition config_rf.h:50
void printHundredths(Print &out, int16_t value_x100)
Print a value given in hundredths, in its shortest decimal form.
constexpr int32_t toDecimals(float value, uint8_t decimals)
A float constant as an integer with the given number of decimals, rounded.
constexpr uint8_t MAX_STEP_LENGTH
bool start(Step step)
Start an output, written by later calls to poll()
bool busy()
Whether an output is still in progress.
void printDecimals(Print &out, int32_t value, uint8_t decimals)
Print a value given as an integer with a fixed number of decimals (see toDecimals())
volatile uint16_t copyOf_sampleSetsDuringThisDatalogPeriod
Definition shared_var.h:27
volatile int32_t copyOf_energyInBucket_main
Definition shared_var.h:25
volatile uint8_t copyOf_lowestNoOfSampleSetsPerMainsCycle
Definition shared_var.h:26
volatile uint16_t copyOf_countLoadON[NO_OF_DUMPLOADS]
Definition shared_var.h:28
volatile uint16_t absenceOfDivertedEnergyCountInSeconds
Definition shared_var.h:18
bool writeFrameStep(const uint8_t step, char *const text, uint8_t &length)
Writes a step of the frame: one line, STX before the first one, ETX after the last.
Definition teleinfo.h:304
constexpr uint8_t MAX_STEP_LENGTH
The most a step writes: STX or ETX, and the longest line, a 4-character tag ("S_MC") with a signed 16...
Definition teleinfo.h:60
Public functions/variables of processing engine.
constexpr uint8_t PERSISTENCE_FOR_POLARITY_CHANGE
Definition processing.h:20
uint8_t loadPrioritiesAndState[NO_OF_DUMPLOADS]
Definition processing.h:18
PayloadTx_struct< NO_OF_PHASES, TEMP_SENSOR_PRESENT ? tempSensors.size() :0 > tx_data
Definition processing.h:26
Non-blocking serial output of the datalog.
The data of the IoT frame, for TeleInfo::writeFrameStep().
Definition utils.h:479
static constexpr uint8_t RELAY_COUNT
Definition utils.h:482
static constexpr bool RELAY_DIVERSION
Definition utils.h:481
static int16_t relayAverage()
Definition utils.h:524
static constexpr uint8_t TEMP_COUNT
Definition utils.h:484
static bool relayOn(uint8_t idx)
Definition utils.h:528
static int16_t power()
Definition utils.h:512
static uint16_t phaseVoltage(uint8_t idx)
Definition utils.h:520
static bool temperatureValid(uint8_t idx)
Definition utils.h:536
static int16_t temperature(uint8_t idx)
Definition utils.h:540
static int16_t loadOnPercent(uint8_t idx)
Definition utils.h:532
static uint16_t absenceCount()
Definition utils.h:544
static int16_t phasePower(uint8_t idx)
Definition utils.h:516
static bool offPeak()
Definition utils.h:548
static uint8_t lowestSampleSetsPerCycle()
Definition utils.h:556
static constexpr uint8_t PHASE_COUNT
Definition utils.h:480
static uint16_t sampleSets()
Definition utils.h:552
static constexpr bool DUAL_TARIFF
Definition utils.h:485
static uint16_t absenceCountAtDatalog
Definition utils.h:490
static uint16_t relayStatesAtDatalog
Definition utils.h:489
static void snapshot()
Takes the values that change during the frame (the tariff is in datalogOffPeak).
Definition utils.h:495
static constexpr uint8_t LOAD_COUNT
Definition utils.h:483
The telemetry frame of the IoT output, written a line at a time.
void printCalibration(const uint8_t phase)
Print the calibration of a phase as calibration.h has it.
Definition utils.h:102
void printCalibrationLine(const __FlashStringHelper *name, const uint8_t phase, const int32_t *value, const uint8_t decimals)
Print one calibration line: "<name> for L<phase> = <value>".
Definition utils.h:80
void infolnPresence(const bool present)
Print "is present" or "is NOT present", and a line end.
Definition utils.h:67
bool datalogOffPeak
Definition utils.h:296
RF module support for RFM69.
constexpr bool RF_CHIP_PRESENT
Definition utils_rf.h:25
bool initialize_rf()
Initialize the shared RF module.
Definition utils_rf.h:57
void send_rf_data(const PayloadType &data)
Send RF data to gateway.
Definition utils_rf.h:96
Provides utilities for managing temperature sensors.
#define BRANCH_NAME
Definition version.h:6
#define COMMIT_HASH
Definition version.h:7
#define CURRENT_TIME
Definition version.h:5
#define PROJECT_PATH
Definition version.h:4
#define BUILD_ENV
Definition version.h:8