3-phase PV router
Loading...
Searching...
No Matches
relay_engine.h
Go to the documentation of this file.
1
20
21#ifndef RELAY_ENGINE_H
22#define RELAY_ENGINE_H
23
24#include <stdint.h>
25
26#include "config_system.h" // DATALOG_PERIOD_IN_SECONDS
27#include "type_traits.hpp" // make_index_sequence
28#include "ewma_avg.hpp"
29#include "utils_bits.h"
30
35namespace RelayLogic
36{
41{
48 static void switched(uint8_t /* pin */, bool /* on */)
49 {
50 }
51};
52
69template< typename Output = NoOutput >
70class Relay
71{
72public:
73 constexpr Relay() = delete;
74
80 explicit constexpr Relay(const uint8_t _relay_pin)
81 : relay_pin{ _relay_pin }
82 {
83 }
84
95 constexpr Relay(uint8_t _relay_pin, int16_t _surplusThreshold, int16_t _importThreshold)
96 : relay_pin{ _relay_pin }, surplusThreshold{ negativeOf(_surplusThreshold) }, importThreshold{ _importThreshold }
97 {
98 }
99
112 constexpr Relay(uint8_t _relay_pin, int16_t _surplusThreshold, int16_t _importThreshold, uint16_t _minON, uint16_t _minOFF)
113 : relay_pin{ _relay_pin }, surplusThreshold{ negativeOf(_surplusThreshold) }, importThreshold{ _importThreshold }, minON{ toSeconds(_minON) }, minOFF{ toSeconds(_minOFF) }
114 {
115 }
116
122 constexpr auto get_pin() const
123 {
124 return relay_pin;
125 }
126
132 constexpr auto get_surplusThreshold() const
133 {
134 return -surplusThreshold;
135 }
136
142 constexpr auto get_importThreshold() const
143 {
144 return importThreshold;
145 }
146
152 constexpr auto get_minON() const
153 {
154 return minON;
155 }
156
162 constexpr auto get_minOFF() const
163 {
164 return minOFF;
165 }
166
172 constexpr bool hasValidMinimumTimes() const
173 {
174 return (minON != UINT16_MAX) && (minOFF != UINT16_MAX);
175 }
176
182 auto isRelayON() const
183 {
184 return relayIsON;
185 }
186
192 void inc_duration() const
193 {
194 if (duration < UINT16_MAX)
195 {
196 ++duration;
197 }
198 }
199
208 bool proceed_relay(const int32_t currentAvgPower, const uint16_t overrideBitmask, const bool onAllowed = true) const
209 {
210 const bool forced{ isForced(overrideBitmask) };
211
212 // To avoid changing sign, surplus is a negative value
213 // Turn ON if surplus threshold is met OR if override is active
214 if (onAllowed && (currentAvgPower < surplusThreshold || forced))
215 {
216 return try_switch(true);
217 }
218
219 // Positive threshold: turn OFF when importing > threshold (normal mode).
220 // Negative threshold: turn OFF when surplus < abs(threshold) (battery mode).
221 if (!forced && currentAvgPower > importThreshold)
222 {
223 return try_switch(false);
224 }
225
226 return false;
227 }
228
236 bool proceed_forced_only(const uint16_t overrideBitmask) const
237 {
238 return try_switch(isForced(overrideBitmask));
239 }
240
241private:
249 static constexpr uint16_t toSeconds(const uint16_t minutes)
250 {
251 return minutes * 60UL > UINT16_MAX ? UINT16_MAX : static_cast< uint16_t >(minutes * 60UL);
252 }
253
255 static constexpr int16_t negativeOf(const int16_t value)
256 {
257 return value > 0 ? -value : value;
258 }
259
260 bool isForced(const uint16_t overrideBitmask) const
261 {
262 return bit_read(overrideBitmask, relay_pin);
263 }
264
271 bool try_switch(const bool on) const
272 {
273 if ((relayIsON == on) || (duration < (on ? minOFF : minON)))
274 {
275 return false;
276 }
277
278 Output::switched(relay_pin, on);
279
280 relayIsON = on;
281 duration = 0;
282
283 return true;
284 }
285
286private:
287 const uint8_t relay_pin{ 0xff };
288 const int16_t surplusThreshold{ -1000 };
289 const int16_t importThreshold{ 200 };
290 const uint16_t minON{ 5 * 60 };
291 const uint16_t minOFF{ 5 * 60 };
292
293 mutable uint16_t duration{ 0 };
294 mutable bool relayIsON{ false };
295};
296
313template< typename R, uint8_t N, uint8_t D >
315{
316public:
322 explicit constexpr Engine(const R (&ref)[N])
323 : Engine(ref, make_index_sequence< N >{})
324 {
325 }
326
332 constexpr auto size() const
333 {
334 return N;
335 }
336
343 constexpr const auto& get_relay(uint8_t idx) const
344 {
345 return relay[idx];
346 }
347
353 inline static auto get_average()
354 {
355 return ewma_average.getAverageT(); // Use TEMA for better cloud immunity
356 }
357
363 inline static void update_average(int16_t currentPower)
364 {
365 ewma_average.addValue(currentPower);
366 }
367
374#if defined(__DOXYGEN__)
375 void inc_duration() const;
376#else
377 void inc_duration() const __attribute__((optimize("-O3")));
378#endif
379
394 void proceed_relays(const uint16_t overrideBitmask, const bool diversionEnabled = true) const
395 {
396 if (settle_change != 0)
397 {
398 // A relay has been toggle less than a minute ago, wait until changes take effect
399 return;
400 }
401
402 if (!diversionEnabled)
403 {
404 bool anyChanges{ false };
405 uint8_t idx{ N };
406 do
407 {
408 anyChanges |= relay[--idx].proceed_forced_only(overrideBitmask);
409 } while (idx);
410
411 if (anyChanges)
412 settle_change = 60;
413
414 return;
415 }
416
417 const auto currentAvgPower{ ewma_average.getAverageT() };
418
419 const bool importing{ currentAvgPower > 0 };
420
421 // First from the last relay down: OFF on an import (where a forced relay comes in too), and
422 // on a small surplus for the relays in battery mode. Then, on a surplus only, from the first
423 // relay up: ON. One call site, so that the switching code is inlined once.
424 for (uint8_t step = 0; step != 2 * N; ++step)
425 {
426 const bool down{ step < N };
427 if (!down && importing)
428 {
429 return;
430 }
431
432 const uint8_t idx{ static_cast< uint8_t >(down ? N - 1 - step : step - N) };
433 if (relay[idx].proceed_relay(currentAvgPower, overrideBitmask, importing || !down))
434 {
435 settle_change = 60;
436 return;
437 }
438 }
439 }
440
441protected:
442 const R relay[N];
443
444private:
446 template< uint8_t... I >
447 constexpr Engine(const R (&ref)[N], index_sequence< I... > /* is */)
448 : relay{ ref[I]... }
449 {
450 }
451
452private:
453 mutable uint8_t settle_change{ 60 };
454
456};
457
458template< typename R, uint8_t N, uint8_t D > void Engine< R, N, D >::inc_duration() const
459{
460 uint8_t idx{ N };
461 do
462 {
463 relay[--idx].inc_duration();
464 } while (idx);
465
466 if (settle_change)
467 {
469 }
470}
471} // namespace RelayLogic
472
473#endif /* RELAY_ENGINE_H */
Implements an Exponentially Weighted Moving Average (EWMA).
Definition ewma_avg.hpp:109
static void update_average(int16_t currentPower)
Update the sliding average.
constexpr auto size() const
Get the number of relays.
void inc_duration() const
Increment the duration's state of each relay.
constexpr Engine(const R(&ref)[N], index_sequence< I... >)
Copies each relay of ref: an array cannot be initialized from another.
static auto get_average()
Get the current average.
constexpr const auto & get_relay(uint8_t idx) const
Get the relay object.
void proceed_relays(const uint16_t overrideBitmask, const bool diversionEnabled=true) const
Proceed all relays: OFF in decreasing order, ON in increasing order.
constexpr Engine(const R(&ref)[N])
Construct a list of relays.
static EWMA_average< D *60/DATALOG_PERIOD_IN_SECONDS > ewma_average
static constexpr int16_t negativeOf(const int16_t value)
-abs(value), without the abs() macro of Arduino.h.
constexpr auto get_minON() const
Get the minimum ON-time in seconds.
bool proceed_forced_only(const uint16_t overrideBitmask) const
Proceed with the relay while diversion is disabled: ON only while forced.
constexpr auto get_minOFF() const
Get the minimum OFF-time in seconds.
constexpr auto get_surplusThreshold() const
Get the surplus threshold which will turns ON the relay.
auto isRelayON() const
Return the state.
const uint16_t minOFF
const int16_t importThreshold
bool try_switch(const bool on) const
Turn the relay ON or OFF if the 'time' condition is met.
void inc_duration() const
Increment the duration of the current state.
constexpr Relay(uint8_t _relay_pin, int16_t _surplusThreshold, int16_t _importThreshold, uint16_t _minON, uint16_t _minOFF)
Construct a new relay Config object with custom parameters.
constexpr Relay()=delete
bool isForced(const uint16_t overrideBitmask) const
const int16_t surplusThreshold
constexpr auto get_importThreshold() const
Get the import threshold which will turns OFF the relay.
const uint8_t relay_pin
constexpr auto get_pin() const
Get the control pin of the relay.
bool proceed_relay(const int32_t currentAvgPower, const uint16_t overrideBitmask, const bool onAllowed=true) const
Proceed with the relay.
constexpr Relay(const uint8_t _relay_pin)
Construct a new relay Config object with default parameters.
const uint16_t minON
static constexpr uint16_t toSeconds(const uint16_t minutes)
Minutes to seconds, in 16 bits.
constexpr Relay(uint8_t _relay_pin, int16_t _surplusThreshold, int16_t _importThreshold)
Construct a new relay Config object with default/custom parameters.
constexpr bool hasValidMinimumTimes() const
Whether both minimum times fit in 16 bits of seconds (1092 minutes at most).
Basic configuration values to be set by the end-user.
constexpr uint8_t DATALOG_PERIOD_IN_SECONDS
This file implements an Exponentially Weighted Moving Average template class.
typename make_index_sequence_impl< N >::type make_index_sequence
index_sequence< 0, 1, ..., N - 1 >.
The relay engine without its I/O.
The default output of a relay: none, the state only.
static void switched(uint8_t, bool)
Called on each change, before the state changes.
The indexes I..., as a type.
Some useful but missing stl functions templates.
Bit manipulation utility functions.
constexpr uint8_t bit_read(const T &_src, const uint8_t bit)
Read the specified bit.
Definition utils_bits.h:44