etl/include/etl/message_timer_interrupt.h
Roland Reichwein b0548949df
Fix circular reference in callback_timer_* (#1611)
* Add docs and tutorial for etl::intrusive_avl_tree (#1608)

* Add docs and tutorial for etl::intrusive_avl_tree

Documents the intrusive AVL tree added in PR #1425: a full API reference
page under Containers/Trees, and a tutorial demonstrating ordered access
to intrusively-linked objects with unpredictable lifetimes, including
move support and destructor-driven automatic removal from the tree.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Add complexity shortcode and document its usage

Introduces a {{< complexity >}} Hugo shortcode (with light/dark styling
for constant/logarithmic/linear/linearithmic/polynomial/exponential
classes) for rendering Big-O complexity inline, applies it throughout
the intrusive_avl_tree API reference in place of raw "O(...)" text, and
documents the Description/Complexity structure and supported classes in
DOCUMENTATION.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Fix issues found by @CodeRabbit

* Put complexity notes on their own lines in intrusive_avl_tree docs

Move the complexity shortcode from the inline "**Complexity:**" label
to its own line under a "**Complexity**" label. Notes that give several
alternatives (e.g. amortized vs. worst-case) now show each one on a
separate line. Update the guideline in DOCUMENTATION.md to match.

* Update complexity examples in DOCUMENTATION.md

Add the hard line break after the "**Complexity**" label in the
example, and rewrite the list of supported complexity classes in the
new two-line format, including an example with several alternatives.

* Add logarithmic complexity example to DOCUMENTATION.md

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: John Wellbelove <jwellbelove@users.noreply.github.com>

* Updated sponsors pages

* Refactor the documentation css to group styles for light and dark themes

* Fix circular reference in callback_timer_*

Fixes #967

* Unify timer tick() ordering and detect duplicate inserts

Address review feedback on #1611.

Replace the is_active() guard with a consistent tick() ordering across
all timer controllers: a repeating timer is now reinserted before its
callback is invoked or its message is sent, matching etl::callback_timer.
A callback that restarts the timer then replaces the existing entry
instead of causing a second insert. Applied to message_timer_atomic,
message_timer_interrupt and message_timer_locked as well, which are
affected in the same way.

Reject an insert of a timer that is already in the active list, rather
than linking it to itself, and record that it happened. The regression
tests now assert duplicate_insert_detected() instead of relying on the
resulting circular reference hanging the test.

---------

Co-authored-by: Sergei <sergej.shirokov@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: John Wellbelove <jwellbelove@users.noreply.github.com>
Co-authored-by: John Wellbelove <john.wellbelove@etlcpp.com>
2026-09-30 08:27:23 +01:00

717 lines
20 KiB
C++

/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2022 John Wellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#ifndef ETL_MESSAGE_TIMER_INTERRUPT_INCLUDED
#define ETL_MESSAGE_TIMER_INTERRUPT_INCLUDED
#include "platform.h"
#include "algorithm.h"
#include "delegate.h"
#include "message.h"
#include "message_bus.h"
#include "message_router.h"
#include "message_types.h"
#include "nullptr.h"
#include "static_assert.h"
#include "timer.h"
#include <stdint.h>
namespace etl
{
//***************************************************************************
/// Interface for message timer
//***************************************************************************
template <typename TInterruptGuard>
class imessage_timer_interrupt
{
public:
typedef etl::delegate<void(void)> callback_type;
typedef etl::delegate<void(etl::timer::id::type)> event_callback_type;
public:
//*******************************************
/// Register a timer.
//*******************************************
etl::timer::id::type register_timer(const etl::imessage& message_, etl::imessage_router& router_, uint32_t period_, bool repeating_,
etl::message_router_id_t destination_router_id_ = etl::imessage_router::ALL_MESSAGE_ROUTERS)
{
etl::timer::id::type id = etl::timer::id::NO_TIMER;
bool is_space = (number_of_registered_timers < Max_Timers);
if (is_space)
{
// There's no point adding null message routers.
if (!router_.is_null_router())
{
// Search for the free space.
for (uint_least8_t i = 0U; i < Max_Timers; ++i)
{
timer_data& timer = timer_array[i];
if (timer.id == etl::timer::id::NO_TIMER)
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
// Create in-place.
new (&timer) timer_data(i, message_, router_, period_, repeating_, destination_router_id_);
++number_of_registered_timers;
id = i;
break;
}
}
}
}
return id;
}
//*******************************************
/// Unregister a timer.
//*******************************************
bool unregister_timer(etl::timer::id::type id_)
{
bool result = false;
if (id_ != etl::timer::id::NO_TIMER)
{
timer_data& timer = timer_array[id_];
if (timer.id != etl::timer::id::NO_TIMER)
{
if (timer.is_active())
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
active_list.remove(timer.id, false);
remove_callback.call_if(timer.id);
}
// Reset in-place.
new (&timer) timer_data();
--number_of_registered_timers;
result = true;
}
}
return result;
}
//*******************************************
/// Enable/disable the timer.
//*******************************************
void enable(bool state_)
{
enabled = state_;
}
//*******************************************
/// Get the enable/disable state.
//*******************************************
bool is_running() const
{
return enabled;
}
//*******************************************
/// Clears the timer of data.
//*******************************************
void clear()
{
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
active_list.clear();
}
for (int i = 0; i < Max_Timers; ++i)
{
new (&timer_array[i]) timer_data();
}
number_of_registered_timers = 0U;
}
//*******************************************
// Called by the timer service to indicate the
// amount of time that has elapsed since the last successful call to 'tick'.
// Returns true if the tick was processed,
// false if not.
//*******************************************
bool tick(uint32_t count)
{
if (enabled)
{
// We have something to do?
bool has_active = !active_list.empty();
if (has_active)
{
while (has_active && (count >= active_list.front().delta))
{
timer_data& timer = active_list.front();
count -= timer.delta;
active_list.remove(timer.id, true);
remove_callback.call_if(timer.id);
// The timer is reinserted before the message is sent, so that
// a receiver that restarts the timer replaces this entry instead
// of the timer being inserted into the active list twice.
if (timer.repeating)
{
// Reinsert the timer.
timer.delta = timer.period;
active_list.insert(timer.id);
insert_callback.call_if(timer.id);
}
if (timer.p_router != ETL_NULLPTR)
{
timer.p_router->receive(timer.destination_router_id, *(timer.p_message));
}
has_active = !active_list.empty();
}
if (has_active)
{
// Subtract any remainder from the next due timeout.
active_list.front().delta -= count;
}
}
return true;
}
return false;
}
//*******************************************
/// Starts a timer.
//*******************************************
bool start(etl::timer::id::type id_, bool immediate_ = false)
{
bool result = false;
// Valid timer id?
if (id_ != etl::timer::id::NO_TIMER)
{
timer_data& timer = timer_array[id_];
// Registered timer?
if (timer.id != etl::timer::id::NO_TIMER)
{
// Has a valid period.
if (timer.period != etl::timer::state::Inactive)
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
if (timer.is_active())
{
active_list.remove(timer.id, false);
remove_callback.call_if(timer.id);
}
timer.delta = immediate_ ? 0 : timer.period;
active_list.insert(timer.id);
insert_callback.call_if(timer.id);
result = true;
}
}
}
return result;
}
//*******************************************
/// Stops a timer.
//*******************************************
bool stop(etl::timer::id::type id_)
{
bool result = false;
// Valid timer id?
if (id_ != etl::timer::id::NO_TIMER)
{
timer_data& timer = timer_array[id_];
// Registered timer?
if (timer.id != etl::timer::id::NO_TIMER)
{
if (timer.is_active())
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
active_list.remove(timer.id, false);
remove_callback.call_if(timer.id);
}
result = true;
}
}
return result;
}
//*******************************************
/// Sets a timer's period.
//*******************************************
bool set_period(etl::timer::id::type id_, uint32_t period_)
{
if (stop(id_))
{
timer_array[id_].period = period_;
return true;
}
return false;
}
//*******************************************
/// Sets a timer's mode.
//*******************************************
bool set_mode(etl::timer::id::type id_, bool repeating_)
{
if (stop(id_))
{
timer_array[id_].repeating = repeating_;
return true;
}
return false;
}
//*******************************************
/// Returns true if an attempt was ever made to insert a timer into the
/// active list when it was already there. Such an insert is rejected, as
/// it would create a circular reference in the list.
//*******************************************
bool duplicate_insert_detected() const
{
return active_list.duplicate_insert_detected();
}
//*******************************************
/// Check if there is an active timer.
//*******************************************
bool has_active_timer() const
{
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
return !active_list.empty();
}
//*******************************************
/// Get the time to the next timer event.
/// Returns etl::timer::interval::No_Active_Interval if there is no active
/// timer.
//*******************************************
uint32_t time_to_next() const
{
uint32_t delta = static_cast<uint32_t>(etl::timer::interval::No_Active_Interval);
TInterruptGuard guard;
(void)guard; // Silence 'unused variable warnings.
if (!active_list.empty())
{
delta = active_list.front().delta;
}
return delta;
}
//*******************************************
/// Set a callback when a timer is inserted on list
//*******************************************
void set_insert_callback(event_callback_type insert_)
{
insert_callback = insert_;
}
//*******************************************
/// Set a callback when a timer is removed from list
//*******************************************
void set_remove_callback(event_callback_type remove_)
{
remove_callback = remove_;
}
//*******************************************
void clear_insert_callback()
{
insert_callback.clear();
}
//*******************************************
void clear_remove_callback()
{
remove_callback.clear();
}
protected:
//*************************************************************************
/// The configuration of a timer.
struct timer_data
{
//*******************************************
timer_data()
: p_message(ETL_NULLPTR)
, p_router(ETL_NULLPTR)
, period(0)
, delta(etl::timer::state::Inactive)
, destination_router_id(etl::imessage_bus::ALL_MESSAGE_ROUTERS)
, id(etl::timer::id::NO_TIMER)
, previous(etl::timer::id::NO_TIMER)
, next(etl::timer::id::NO_TIMER)
, repeating(true)
{
}
//*******************************************
timer_data(etl::timer::id::type id_, const etl::imessage& message_, etl::imessage_router& irouter_, uint32_t period_, bool repeating_,
etl::message_router_id_t destination_router_id_ = etl::imessage_bus::ALL_MESSAGE_ROUTERS)
: p_message(&message_)
, p_router(&irouter_)
, period(period_)
, delta(etl::timer::state::Inactive)
, destination_router_id(destination_router_id_)
, id(id_)
, previous(etl::timer::id::NO_TIMER)
, next(etl::timer::id::NO_TIMER)
, repeating(repeating_)
{
}
//*******************************************
/// Returns true if the timer is active.
//*******************************************
bool is_active() const
{
return delta != etl::timer::state::Inactive;
}
//*******************************************
/// Sets the timer to the inactive state.
//*******************************************
void set_inactive()
{
delta = etl::timer::state::Inactive;
}
const etl::imessage* p_message;
etl::imessage_router* p_router;
uint32_t period;
uint32_t delta;
etl::message_router_id_t destination_router_id;
etl::timer::id::type id;
uint_least8_t previous;
uint_least8_t next;
bool repeating;
private:
// Disabled.
timer_data(const timer_data& other);
timer_data& operator=(const timer_data& other);
};
//*******************************************
/// Constructor.
//*******************************************
imessage_timer_interrupt(timer_data* const timer_array_, const uint_least8_t Max_Timers_)
: timer_array(timer_array_)
, active_list(timer_array_)
, enabled(false)
, number_of_registered_timers(0U)
, Max_Timers(Max_Timers_)
{
}
//*******************************************
/// Destructor.
//*******************************************
~imessage_timer_interrupt() {}
private:
//*************************************************************************
/// A specialised intrusive linked list for timer data.
//*************************************************************************
class timer_list
{
public:
//*******************************
timer_list(timer_data* ptimers_)
: head(etl::timer::id::NO_TIMER)
, tail(etl::timer::id::NO_TIMER)
, ptimers(ptimers_)
, duplicate_insert(false)
{
}
//*******************************
bool empty() const
{
return head == etl::timer::id::NO_TIMER;
}
//*******************************
/// Returns true if an attempt was ever made to insert a timer that was
/// already in the list.
//*******************************
bool duplicate_insert_detected() const
{
return duplicate_insert;
}
//*******************************
// Inserts the timer at the correct delta position
//*******************************
void insert(etl::timer::id::type id_)
{
timer_data& timer = ptimers[id_];
// A timer is in this list exactly when it is the head or has a previous
// link, as remove() clears both links. Inserting one that is already
// here would link it to itself and create a circular reference, so
// record the attempt and abandon the insert to keep the list intact.
if ((head == id_) || (timer.previous != etl::timer::id::NO_TIMER))
{
duplicate_insert = true;
return;
}
if (head == etl::timer::id::NO_TIMER)
{
// No entries yet.
head = id_;
tail = id_;
timer.previous = etl::timer::id::NO_TIMER;
timer.next = etl::timer::id::NO_TIMER;
}
else
{
// We already have entries.
etl::timer::id::type test_id = begin();
while (test_id != etl::timer::id::NO_TIMER)
{
timer_data& test = ptimers[test_id];
// Find the correct place to insert.
if (timer.delta <= test.delta)
{
if (test.id == head)
{
head = timer.id;
}
// Insert before test.
timer.previous = test.previous;
test.previous = timer.id;
timer.next = test.id;
// Adjust the next delta to compensate.
test.delta -= timer.delta;
if (timer.previous != etl::timer::id::NO_TIMER)
{
ptimers[timer.previous].next = timer.id;
}
break;
}
else
{
timer.delta -= test.delta;
}
test_id = next(test_id);
}
// Reached the end?
if (test_id == etl::timer::id::NO_TIMER)
{
// Tag on to the tail.
ptimers[tail].next = timer.id;
timer.previous = tail;
timer.next = etl::timer::id::NO_TIMER;
tail = timer.id;
}
}
}
//*******************************
void remove(etl::timer::id::type id_, bool has_expired)
{
timer_data& timer = ptimers[id_];
if (head == id_)
{
head = timer.next;
}
else
{
ptimers[timer.previous].next = timer.next;
}
if (tail == id_)
{
tail = timer.previous;
}
else
{
ptimers[timer.next].previous = timer.previous;
}
if (!has_expired)
{
// Adjust the next delta.
if (timer.next != etl::timer::id::NO_TIMER)
{
ptimers[timer.next].delta += timer.delta;
}
}
timer.previous = etl::timer::id::NO_TIMER;
timer.next = etl::timer::id::NO_TIMER;
timer.delta = etl::timer::state::Inactive;
}
//*******************************
timer_data& front()
{
return ptimers[head];
}
//*******************************
const timer_data& front() const
{
return ptimers[head];
}
//*******************************
etl::timer::id::type begin()
{
return head;
}
//*******************************
etl::timer::id::type next(etl::timer::id::type last)
{
return ptimers[last].next;
}
//*******************************
void clear()
{
etl::timer::id::type id = begin();
while (id != etl::timer::id::NO_TIMER)
{
timer_data& timer = ptimers[id];
id = next(id);
timer.next = etl::timer::id::NO_TIMER;
}
head = etl::timer::id::NO_TIMER;
tail = etl::timer::id::NO_TIMER;
}
private:
etl::timer::id::type head;
etl::timer::id::type tail;
timer_data* const ptimers;
// Set if an attempt was ever made to insert a timer that was already
// in the list.
bool duplicate_insert;
};
// The array of timer data structures.
timer_data* const timer_array;
// The list of active timers.
timer_list active_list;
bool enabled;
uint_least8_t number_of_registered_timers;
event_callback_type insert_callback;
event_callback_type remove_callback;
public:
const uint_least8_t Max_Timers;
};
//***************************************************************************
/// The message timer
//***************************************************************************
template <uint_least8_t Max_Timers_, typename TInterruptGuard>
class message_timer_interrupt : public etl::imessage_timer_interrupt<TInterruptGuard>
{
public:
ETL_STATIC_ASSERT(Max_Timers_ <= 254, "No more than 254 timers are allowed");
typedef typename imessage_timer_interrupt<TInterruptGuard>::callback_type callback_type;
//*******************************************
/// Constructor.
//*******************************************
message_timer_interrupt()
: imessage_timer_interrupt<TInterruptGuard>(timer_array, Max_Timers_)
{
}
private:
typename etl::imessage_timer_interrupt<TInterruptGuard>::timer_data timer_array[Max_Timers_];
};
} // namespace etl
#endif