1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use anyhow::{anyhow, Result};
use esp_idf_hal::{delay::BLOCK, task::notification};
use std::{
    collections::HashSet, fmt::Debug, hash::Hash, num::NonZeroU32, sync::Arc,
};

/// A trait for notification trigger types used in the inter-thread messaging system.
///
/// Implementors must be thread-safe (`Send + Sync + 'static`) and support
/// equality comparison and hashing for use in `HashSet` collections.
/// Each variant maps to a unique `u32` bitmask for `FreeRTOS` task notifications.
///
/// Use the `trigger_enum!` macro to derive this trait automatically.
pub trait Trigger: Debug + Eq + Hash + Sized + Send + Sync + 'static {
    /// A slice containing all possible trigger variants.
    const ALL: &[Self];

    /// Returns the `u32` bitmask value for this trigger.
    ///
    /// # Returns
    /// A non-zero `u32` suitable for use as a `FreeRTOS` task notification bit.
    fn as_u32(&self) -> u32;
}

/// Defines a trigger enum with an automatic [`Trigger`] trait implementation.
///
/// Generates a `#[repr(u32)]` enum and implements [`Trigger::ALL`] and [`Trigger::as_u32`].
/// Each variant must be assigned a power-of-two value for use as a notification bitmask.
///
/// ```text
/// trigger_enum! {
///     #[derive(Debug, Eq, Hash, PartialEq)]
///     pub enum MyTrigger {
///         Foo = 1 << 0,
///         Bar = 1 << 1,
///     }
/// }
/// ```
#[macro_export]
macro_rules! trigger_enum {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $($variant:ident = $value:expr),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[repr(u32)]
        $vis enum $name {
            $($variant = $value),*
        }

        impl $crate::message::Trigger for $name {
            const ALL: &[Self] = &[
                $(Self::$variant),*
            ];

            fn as_u32(&self) -> u32 {
                match self {
                    $(Self::$variant => $value),*
                }
            }
        }
    };
}

fn trigger_to_nonzero<T: Trigger>(trigger: &T) -> Result<NonZeroU32> {
    NonZeroU32::new(trigger.as_u32())
        .ok_or_else(|| anyhow!("Invalid value for NonZeroU32"))
}

/// Represents a notifier for sending notifications.
///
/// # Type Parameters
/// * `T` - The trigger type implementing the `Trigger` trait.
pub struct Notifier<T: Trigger> {
    notifier: Arc<notification::Notifier>,
    _marker: std::marker::PhantomData<T>,
}

impl<T: Trigger> Notifier<T> {
    /// Creates a new `Notifier` instance.
    ///
    /// # Arguments
    /// * `notifier` - An `Arc` of a `notification::Notifier`.
    ///
    /// # Returns
    /// A new `Notifier` instance.
    ///
    /// # Errors
    /// Returns an error if the notifier cannot be initialized.
    pub fn new(notifier: Arc<notification::Notifier>) -> Result<Self> {
        Ok(Self {
            notifier,
            _marker: std::marker::PhantomData,
        })
    }

    /// Sends a notification for a given trigger.
    ///
    /// # Arguments
    /// * `trigger` - The trigger to notify.
    ///
    /// # Returns
    /// `Ok(())` on success.
    ///
    /// # Errors
    /// Returns an error if the trigger value is zero or the notification fails.
    pub fn notify(&self, trigger: &T) -> Result<()> {
        unsafe {
            self.notifier.notify_and_yield(trigger_to_nonzero(trigger)?);
        }

        Ok(())
    }
}

/// Represents a dispatcher for collecting triggers.
///
/// # Type Parameters
/// * `T` - The trigger type implementing the `Trigger` trait.
pub struct Dispatcher<T: Trigger> {
    notification: notification::Notification,
    _marker: std::marker::PhantomData<T>,
}

impl<T: Trigger> Dispatcher<T> {
    /// Creates a new `Dispatcher` instance.
    ///
    /// # Returns
    /// A new `Dispatcher` ready to create notifiers and collect triggers.
    ///
    /// # Errors
    /// Returns an error if the dispatcher cannot be initialized.
    pub fn new() -> Result<Self> {
        Ok(Self {
            notification: notification::Notification::new(),
            _marker: std::marker::PhantomData,
        })
    }

    /// Returns a `Notifier` associated with the dispatcher.
    ///
    /// # Returns
    /// A `Notifier` linked to this dispatcher's notification system.
    ///
    /// # Errors
    /// Returns an error if the notifier cannot be created.
    pub fn notifier(&self) -> Result<Notifier<T>> {
        Notifier::new(self.notification.notifier())
    }

    /// Collects triggers from the notification system.
    ///
    /// # Returns
    /// A `HashSet` of collected triggers.
    ///
    /// # Errors
    /// Returns an error if the collection fails.
    pub fn collect(&self) -> Result<HashSet<&'static T>> {
        let mut set = HashSet::new();

        let notification = self.notification.wait(BLOCK);
        if let Some(notification) = notification {
            let bits = notification.get();
            for trigger in T::ALL {
                if bits & trigger.as_u32() != 0 {
                    set.insert(trigger);
                }
            }
        }

        Ok(set)
    }
}