osal-rs 0.4.6

Operating System Abstraction Layer for Rust with support for FreeRTOS and POSIX
Documentation
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/***************************************************************************
 *
 * osal-rs
 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 *
 ***************************************************************************/

//! Software timer trait for delayed and periodic callbacks.
//!
//! Timers execute callback functions in the context of a timer service task,
//! enabling delayed operations and periodic tasks without dedicated threads.
//!
//! # Overview
//!
//! Software timers provide a way to execute callback functions at specified
//! intervals without creating dedicated tasks. All timer callbacks run in
//! the context of a single timer service daemon task.
//!
//! # Timer Types
//!
//! - **One-shot**: Expires once after the period elapses
//! - **Auto-reload (Periodic)**: Automatically restarts after expiring
//!
//! # Timer Service Task
//!
//! All timer callbacks execute in a dedicated timer service task that:
//! - Has a configurable priority
//! - Processes timer commands from a queue
//! - Executes callbacks sequentially (not in parallel)
//!
//! # Important Constraints
//!
//! - Timer callbacks should be short and non-blocking
//! - Callbacks should not call blocking RTOS APIs (may cause deadlock)
//! - Long callbacks delay other timer expirations
//! - Use task notifications or queues to defer work to other tasks
//!
//! # Accuracy
//!
//! Timer accuracy depends on:
//! - System tick rate (e.g., 1ms for 1000 Hz)
//! - Timer service task priority
//! - Duration of other timer callbacks
//! - System load
//!
//! # Examples
//!
//! ```ignore
//! use osal_rs::os::Timer;
//! use core::time::Duration;
//!
//! // One-shot timer
//! let once = Timer::new(
//!     "timeout",
//!     Duration::from_secs(5),
//!     false,  // Not auto-reload
//!     None,
//!     |_timer, _param| {
//!         println!("Timeout!");
//!         Ok(None)
//!     }
//! ).unwrap();
//! once.start(0);
//!
//! // Periodic timer
//! let periodic = Timer::new(
//!     "heartbeat",
//!     Duration::from_millis(500),
//!     true,  // Auto-reload
//!     None,
//!     |_timer, _param| {
//!         toggle_led();
//!         Ok(None)
//!     }
//! ).unwrap();
//! periodic.start(0);
//! ```

use core::any::Any;

use alloc::{boxed::Box, sync::Arc};

use crate::os::types::TickType;
use crate::utils::{OsalRsBool, Result};

/// Type-erased parameter for timer callbacks.
///
/// Allows passing arbitrary data to timer callback functions in a type-safe
/// manner. The parameter is wrapped in an `Arc` for safe sharing and can be
/// downcast to its original type.
///
/// # Thread Safety
///
/// The inner type must implement `Any + Send + Sync` since timer callbacks
/// execute in the timer service task context.
///
/// # Examples
///
/// ```ignore
/// use std::sync::Arc;
/// use osal_rs::traits::TimerParam;
///
/// // Create a parameter
/// let count: TimerParam = Arc::new(0u32);
///
/// // In timer callback, downcast to access
/// if let Some(value) = param.downcast_ref::<u32>() {
///     println!("Count: {}", value);
/// }
/// ```
pub type TimerParam = Arc<dyn Any + Send + Sync>;

/// Timer callback function pointer type.
///
/// Callbacks receive the timer handle and optional parameter,
/// and can return an updated parameter value.
///
/// # Parameters
///
/// - `Box<dyn Timer>` - Handle to the timer that expired
/// - `Option<TimerParam>` - Optional parameter passed at creation
///
/// # Returns
///
/// `Result<TimerParam>` - Updated parameter or error
///
/// # Execution Context
///
/// Callbacks execute in the timer service task, not ISR context.
/// They should be short and avoid blocking operations.
///
/// # Trait Bounds
///
/// The function must be `Send + Sync + 'static` to safely execute
/// in the timer service task.
///
/// # Examples
///
/// ```ignore
/// use osal_rs::traits::{Timer, TimerParam};
/// use std::sync::Arc;
///
/// let callback: Box<TimerFnPtr> = Box::new(|timer, param| {
///     if let Some(p) = param {
///         if let Some(count) = p.downcast_ref::<u32>() {
///             println!("Timer expired, count: {}", count);
///             return Ok(Arc::new(*count + 1));
///         }
///     }
///     Ok(Arc::new(0u32))
/// });
/// ```
pub type TimerFnPtr = dyn Fn(Box<dyn Timer>, Option<TimerParam>) -> Result<TimerParam> + Send + Sync + 'static;

/// Software timer for delayed and periodic callbacks.
///
/// Timers run callbacks in the timer service task context, not ISR context.
/// They can be one-shot or auto-reloading (periodic).
///
/// # Timer Lifecycle
///
/// 1. **Creation**: `Timer::new()` with name, period, auto-reload flag, and callback
/// 2. **Start**: `start()` begins the timer countdown
/// 3. **Expiration**: Callback executes when period elapses
/// 4. **Auto-reload**: If enabled, timer automatically restarts
/// 5. **Management**: Use `stop()`, `reset()`, `change_period()` to control
/// 6. **Cleanup**: `delete()` frees resources
///
/// # Command Queue
///
/// Timer operations (start, stop, etc.) send commands to a queue processed
/// by the timer service task. The `ticks_to_wait` parameter controls how
/// long to wait if the queue is full.
///
/// # Callback Constraints
///
/// - Keep callbacks short (< 1ms ideally)
/// - Avoid blocking operations (delays, mutex waits, etc.)
/// - Don't call APIs that might block indefinitely
/// - Use task notifications or queues to defer work to tasks
///
/// # Examples
///
/// ## One-shot Timer
///
/// ```ignore
/// use osal_rs::os::Timer;
/// use core::time::Duration;
/// 
/// let timer = Timer::new(
///     "alarm",
///     Duration::from_secs(5),
///     false,  // One-shot
///     None,
///     |_timer, _param| {
///         println!("Alarm!");
///         trigger_alarm();
///         Ok(None)
///     }
/// ).unwrap();
/// 
/// timer.start(0);
/// // Expires once after 5 seconds
/// ```
///
/// ## Periodic Timer
///
/// ```ignore
/// use std::sync::Arc;
///
/// let counter = Arc::new(0u32);
/// let periodic = Timer::new(
///     "counter",
///     Duration::from_millis(100),
///     true,  // Auto-reload
///     Some(counter.clone()),
///     |_timer, param| {
///         if let Some(p) = param {
///             if let Some(count) = p.downcast_ref::<u32>() {
///                 println!("Count: {}", count);
///                 return Ok(Arc::new(*count + 1));
///             }
///         }
///         Ok(Arc::new(0u32))
///     }
/// ).unwrap();
/// 
/// periodic.start(0);
/// // Runs every 100ms until stopped
/// ```
pub trait Timer {
    /// Starts or restarts the timer.
    ///
    /// If the timer is already running, this command resets it to its full
    /// period (equivalent to calling `reset()`). If stopped, the timer begins
    /// counting down from its period.
    ///
    /// # Parameters
    ///
    /// * `ticks_to_wait` - Maximum ticks to wait if command queue is full:
    ///   - `0`: Return immediately if queue full
    ///   - `n`: Wait up to n ticks
    ///   - `TickType::MAX`: Wait forever
    ///
    /// # Returns
    ///
    /// * `True` - Command sent successfully to timer service
    /// * `False` - Failed to send command (queue full, timeout)
    ///
    /// # Timing
    ///
    /// The timer begins counting after the command is processed by the
    /// timer service task, not immediately when this function returns.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::Timer;
    ///
    /// // Start immediately, don't wait
    /// if timer.start(0).into() {
    ///     println!("Timer started");
    /// }
    ///
    /// // Wait up to 100 ticks for command queue
    /// timer.start(100);
    /// ```
    fn start(&self, ticks_to_wait: TickType) -> OsalRsBool;
    
    /// Stops the timer.
    ///
    /// The timer will not expire until started again with `start()` or `reset()`.
    /// For periodic timers, this stops the automatic reloading.
    ///
    /// # Parameters
    ///
    /// * `ticks_to_wait` - Maximum ticks to wait if command queue is full:
    ///   - `0`: Return immediately if queue full
    ///   - `n`: Wait up to n ticks
    ///   - `TickType::MAX`: Wait forever
    ///
    /// # Returns
    ///
    /// * `True` - Command sent successfully to timer service
    /// * `False` - Failed to send command (queue full, timeout)
    ///
    /// # State
    ///
    /// If the timer is already stopped, this command has no effect but
    /// still returns `True`.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::Timer;
    ///
    /// // Stop the timer, wait up to 100 ticks
    /// if timer.stop(100).into() {
    ///     println!("Timer stopped");
    /// }
    ///
    /// // Later, restart it
    /// timer.start(100);
    /// ```
    fn stop(&self, ticks_to_wait: TickType)  -> OsalRsBool;
    
    /// Resets the timer to its full period.
    ///
    /// If the timer is running, this restarts it from the beginning of its
    /// period. If the timer is stopped, this starts it. This is useful for
    /// implementing watchdog-style timers that must be periodically reset.
    ///
    /// # Parameters
    ///
    /// * `ticks_to_wait` - Maximum ticks to wait if command queue is full:
    ///   - `0`: Return immediately if queue full
    ///   - `n`: Wait up to n ticks
    ///   - `TickType::MAX`: Wait forever
    ///
    /// # Returns
    ///
    /// * `True` - Command sent successfully to timer service
    /// * `False` - Failed to send command (queue full, timeout)
    ///
    /// # Use Cases
    ///
    /// - Watchdog timer: Reset timer to prevent timeout
    /// - Activity timer: Reset when activity detected
    /// - Timeout extension: Give more time before expiration
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::Timer;
    /// use core::time::Duration;
    ///
    /// // Watchdog timer pattern
    /// let watchdog = Timer::new(
    ///     "watchdog",
    ///     Duration::from_secs(10),
    ///     false,
    ///     None,
    ///     |_timer, _param| {
    ///         println!("WATCHDOG TIMEOUT!");
    ///         system_reset();
    ///         Ok(None)
    ///     }
    /// ).unwrap();
    ///
    /// watchdog.start(0);
    ///
    /// // In main loop: reset watchdog to prevent timeout
    /// loop {
    ///     do_work();
    ///     watchdog.reset(0);  // "Feed" the watchdog
    /// }
    /// ```
    fn reset(&self, ticks_to_wait: TickType) -> OsalRsBool;
    
    /// Changes the timer period.
    ///
    /// Updates the timer period. The new period takes effect immediately:
    /// - If the timer is running, it continues with the new period
    /// - The remaining time is adjusted proportionally
    /// - For periodic timers, future expirations use the new period
    ///
    /// # Parameters
    ///
    /// * `new_period_in_ticks` - New timer period in ticks
    /// * `ticks_to_wait` - Maximum ticks to wait if command queue is full:
    ///   - `0`: Return immediately if queue full
    ///   - `n`: Wait up to n ticks
    ///   - `TickType::MAX`: Wait forever
    ///
    /// # Returns
    ///
    /// * `True` - Command sent successfully to timer service
    /// * `False` - Failed to send command (queue full, timeout)
    ///
    /// # Behavior
    ///
    /// - If timer has already expired and is auto-reload, the new period
    ///   applies to the next expiration
    /// - If timer is stopped, the new period will be used when started
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::Timer;
    /// use core::time::Duration;
    ///
    /// let timer = Timer::new(
    ///     "adaptive",
    ///     Duration::from_millis(100),
    ///     true,
    ///     None,
    ///     |_timer, _param| Ok(None)
    /// ).unwrap();
    ///
    /// timer.start(0);
    ///
    /// // Later, adjust the period based on system load
    /// if system_busy() {
    ///     // Slow down to 500ms
    ///     timer.change_period(500, 100);
    /// } else {
    ///     // Speed up to 100ms
    ///     timer.change_period(100, 100);
    /// }
    /// ```
    fn change_period(&self, new_period_in_ticks: TickType, ticks_to_wait: TickType) -> OsalRsBool;
    
    /// Deletes the timer and frees its resources.
    ///
    /// Terminates the timer and releases its resources. After deletion,
    /// the timer handle becomes invalid and should not be used.
    ///
    /// # Parameters
    ///
    /// * `ticks_to_wait` - Maximum ticks to wait if command queue is full:
    ///   - `0`: Return immediately if queue full
    ///   - `n`: Wait up to n ticks
    ///   - `TickType::MAX`: Wait forever
    ///
    /// # Returns
    ///
    /// * `True` - Command sent successfully to timer service
    /// * `False` - Failed to send command (queue full, timeout)
    ///
    /// # Safety
    ///
    /// - The timer should be stopped before deletion (recommended)
    /// - Do not use the timer handle after calling this
    /// - The timer is deleted asynchronously by the timer service task
    ///
    /// # Best Practice
    ///
    /// Stop the timer before deleting it to ensure clean shutdown:
    ///
    /// ```ignore
    /// timer.stop(100);
    /// timer.delete(100);
    /// ```
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use osal_rs::os::Timer;
    /// use core::time::Duration;
    ///
    /// let mut timer = Timer::new(
    ///     "temporary",
    ///     Duration::from_secs(1),
    ///     false,
    ///     None,
    ///     |_timer, _param| Ok(None)
    /// ).unwrap();
    ///
    /// timer.start(0);
    /// // ... use timer ...
    ///
    /// // Clean shutdown
    /// timer.stop(100);
    /// if timer.delete(100).into() {
    ///     println!("Timer deleted");
    /// }
    /// ```
    fn delete(&mut self, ticks_to_wait: TickType) -> OsalRsBool;
}