osal-rs 1.2.0

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
483
484
485
486
487
488
489
490
/***************************************************************************
 *
 * 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/>.
 *
 ***************************************************************************/

//! Ported 1:1 from osal-rs-tests' FreeRTOS suite (`timer_tests.rs`) to run
//! against the POSIX backend, plus the ownership tests at the end of this
//! file, which cover behaviour the two backends are expected to share:
//! clones referring to one underlying timer, the callback's return value
//! feeding the next firing, and the timer being torn down when the last
//! handle goes away.

#![cfg(feature = "posix")]

use std::sync::Arc;
use core::any::Any;
use core::sync::atomic::{AtomicU32, Ordering};
use osal_rs::os::*;
use osal_rs::utils::{OsalRsBool, Result};
use core::time::Duration;
use osal_rs::{log_debug, log_info};

const TAG: &str = "TimerTests";

#[test]
fn test_timer_creation() -> Result<()> {
    log_info!(TAG, "Starting test_timer_creation");
    let timer = Timer::new(
        "test_timer",
        Duration::from_millis(100).to_ticks(),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    );

    assert!(timer.is_ok());
    log_info!(TAG, "test_timer_creation PASSED");
    Ok(())
}

#[test]
fn test_timer_one_shot() -> Result<()> {
    log_info!(TAG, "Starting test_timer_one_shot");
    static COUNTER: AtomicU32 = AtomicU32::new(0);

    let timer = Timer::new(
        "oneshot_timer",
        Duration::from_millis(50).to_ticks(),
        false,
        None,
        |_timer, param| {
            COUNTER.fetch_add(1, Ordering::SeqCst);
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let result = timer.start(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Timer started, waiting for fire...");
    assert_eq!(result, OsalRsBool::True);

    // Wait for timer to fire
    let _ = Thread::get_current().wait_notification(0, 0xFFFFFFFF, Duration::from_millis(200).to_ticks());

    let count = COUNTER.load(Ordering::SeqCst);
    log_debug!(TAG, "Timer fired {} times", count);
    assert!(count >= 1);
    log_info!(TAG, "test_timer_one_shot PASSED");
    Ok(())
}

#[test]
fn test_timer_auto_reload() -> Result<()> {
    log_info!(TAG, "Starting test_timer_auto_reload");
    static COUNTER: AtomicU32 = AtomicU32::new(0);

    let timer = Timer::new(
        "autoreload_timer",
        Duration::from_millis(50).to_ticks(),
        true,
        None,
        |_timer, param| {
            COUNTER.fetch_add(1, Ordering::SeqCst);
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let result = timer.start(Duration::from_millis(10).to_ticks());
    assert_eq!(result, OsalRsBool::True);

    let _ = Thread::get_current().wait_notification(0, 0xFFFFFFFF, Duration::from_millis(300).to_ticks());

    let count = COUNTER.load(Ordering::SeqCst);
    log_debug!(TAG, "Auto-reload timer fired {} times", count);
    assert!(count >= 2);

    timer.stop(Duration::from_millis(10).to_ticks());
    log_info!(TAG, "test_timer_auto_reload PASSED");
    Ok(())
}

#[test]
fn test_timer_start_stop() -> Result<()> {
    log_info!(TAG, "Starting test_timer_start_stop");
    let timer = Timer::new(
        "startstop_timer",
        Duration::from_millis(100).to_ticks(),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let start_result = timer.start(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Timer started");
    assert_eq!(start_result, OsalRsBool::True);

    let stop_result = timer.stop(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Timer stopped");
    assert_eq!(stop_result, OsalRsBool::True);
    log_info!(TAG, "test_timer_start_stop PASSED");
    Ok(())
}

#[test]
fn test_timer_reset() -> Result<()> {
    log_info!(TAG, "Starting test_timer_reset");
    let timer = Timer::new(
        "reset_timer",
        Duration::from_millis(100).to_ticks(),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    timer.start(Duration::from_millis(10).to_ticks());

    let reset_result = timer.reset(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Timer reset");
    assert_eq!(reset_result, OsalRsBool::True);

    timer.stop(Duration::from_millis(10).to_ticks());
    log_info!(TAG, "test_timer_reset PASSED");
    Ok(())
}

#[test]
fn test_timer_change_period() -> Result<()> {
    log_info!(TAG, "Starting test_timer_change_period");
    let timer = Timer::new(
        "period_timer",
        Duration::from_millis(100).to_ticks(),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    timer.start(Duration::from_millis(10).to_ticks());

    log_debug!(TAG, "Changing period from 100ms to 200ms");
    let change_result = timer.change_period(
        Duration::from_millis(200).to_ticks(),
        Duration::from_millis(10).to_ticks()
    );
    assert_eq!(change_result, OsalRsBool::True);

    timer.stop(Duration::from_millis(10).to_ticks());
    log_info!(TAG, "test_timer_change_period PASSED");
    Ok(())
}

#[test]
fn test_timer_with_param() -> Result<()> {
    log_info!(TAG, "Starting test_timer_with_param");
    let test_value: u32 = 42;
    let param: Arc<dyn Any + Send + Sync> = Arc::new(test_value);

    static RECEIVED_VALUE: AtomicU32 = AtomicU32::new(0);

    let timer = Timer::new(
        "param_timer",
        Duration::from_millis(50).to_ticks(),
        false,
        Some(param),
        |_timer, param| {
            if let Some(ref p) = param {
                if let Some(val) = p.downcast_ref::<u32>() {
                    RECEIVED_VALUE.store(*val, Ordering::SeqCst);
                }
            }
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    timer.start(Duration::from_millis(10).to_ticks());

    let _ = Thread::get_current().wait_notification(0, 0xFFFFFFFF, Duration::from_millis(200).to_ticks());

    let received = RECEIVED_VALUE.load(Ordering::SeqCst);
    log_debug!(TAG, "Received parameter value: {}", received);
    assert_eq!(received, 42);
    log_info!(TAG, "test_timer_with_param PASSED");
    Ok(())
}

#[test]
fn test_timer_delete() -> Result<()> {
    log_info!(TAG, "Starting test_timer_delete");
    let mut timer = Timer::new(
        "delete_timer",
        Duration::from_millis(100).to_ticks(),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let delete_result = timer.delete(Duration::from_millis(10).to_ticks());
    assert_eq!(delete_result, OsalRsBool::True);
    log_info!(TAG, "test_timer_delete PASSED");
    Ok(())
}

#[test]
fn test_timer_with_to_tick_variants() -> Result<()> {
    log_info!(TAG, "Starting test_timer_with_to_tick_variants");
    let mut timer = Timer::new_with_to_tick(
        "with_to_tick_timer",
        Duration::from_millis(100),
        false,
        None,
        |_timer, param| {
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let start_result = timer.start_with_to_tick(Duration::from_millis(10));
    log_debug!(TAG, "start_with_to_tick: {:?}", start_result);
    assert_eq!(start_result, OsalRsBool::True);

    let reset_result = timer.reset_with_to_tick(Duration::from_millis(10));
    log_debug!(TAG, "reset_with_to_tick: {:?}", reset_result);
    assert_eq!(reset_result, OsalRsBool::True);

    let change_result = timer.change_period_with_to_tick(Duration::from_millis(200), Duration::from_millis(10));
    log_debug!(TAG, "change_period_with_to_tick: {:?}", change_result);
    assert_eq!(change_result, OsalRsBool::True);

    let stop_result = timer.stop_with_to_tick(Duration::from_millis(10));
    log_debug!(TAG, "stop_with_to_tick: {:?}", stop_result);
    assert_eq!(stop_result, OsalRsBool::True);

    let delete_result = timer.delete_with_to_tick(Duration::from_millis(10));
    log_debug!(TAG, "delete_with_to_tick: {:?}", delete_result);
    assert_eq!(delete_result, OsalRsBool::True);

    log_info!(TAG, "test_timer_with_to_tick_variants PASSED");
    Ok(())
}

// ---------------------------------------------------------------------------
// Ownership
//
// The tests below are about who owns the underlying timer rather than about
// what it does, and are mirrored in the FreeRTOS suite: both backends share
// one timer between every clone of a `Timer`, hand the callback a borrowed
// handle rather than an owning one, thread the callback's return value into
// the next firing, and destroy the timer when the last handle is dropped.
// ---------------------------------------------------------------------------

#[test]
fn test_timer_callback_handle_is_not_owning() -> Result<()> {
    log_info!(TAG, "Starting test_timer_callback_handle_is_not_owning");

    static FIRES: AtomicU32 = AtomicU32::new(0);
    static NULL_SEEN: AtomicU32 = AtomicU32::new(0);

    // `TimerFnPtr` takes its `Box<dyn TimerFn>` by value and drops it on
    // return, so the handle the callback is given must not own the timer -
    // otherwise an auto-reload timer would delete itself at its own first
    // firing.
    let timer = Timer::new(
        "cb_handle_timer",
        Duration::from_millis(20).to_ticks(),
        true,
        None,
        |handle, param| {
            if handle.is_null() {
                NULL_SEEN.fetch_add(1, Ordering::SeqCst);
            }
            FIRES.fetch_add(1, Ordering::SeqCst);
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    timer.start(0);
    System::delay(Duration::from_millis(150).to_ticks());

    let fires = FIRES.load(Ordering::SeqCst);
    log_debug!(TAG, "auto-reload timer fired {} time(s)", fires);
    assert_eq!(NULL_SEEN.load(Ordering::SeqCst), 0, "the callback's handle must be live");
    assert!(fires >= 3, "an auto-reload timer must keep firing (saw {fires})");

    log_info!(TAG, "test_timer_callback_handle_is_not_owning PASSED");
    Ok(())
}

#[test]
fn test_timer_param_carries_forward() -> Result<()> {
    log_info!(TAG, "Starting test_timer_param_carries_forward");

    static LAST: AtomicU32 = AtomicU32::new(0);

    // Each firing is handed whatever the previous one returned, which is what
    // makes `TimerFnPtr`'s `Result<TimerParam>` return type useful: an
    // auto-reload timer can carry state forward without a static of its own.
    let seed: TimerParam = Arc::new(1u32);

    let timer = Timer::new(
        "carry_forward_timer",
        Duration::from_millis(20).to_ticks(),
        true,
        Some(seed),
        |_handle, param| {
            let previous = param.and_then(|p| p.downcast_ref::<u32>().copied()).unwrap_or(0);
            LAST.store(previous, Ordering::SeqCst);
            let next: TimerParam = Arc::new(previous + 1);
            Ok(next)
        }
    )?;

    timer.start(0);
    System::delay(Duration::from_millis(150).to_ticks());
    timer.stop(0);

    let last = LAST.load(Ordering::SeqCst);
    log_debug!(TAG, "last parameter handed to the callback: {}", last);
    assert!(last >= 3, "each firing must receive the previous one's result (saw {last})");

    log_info!(TAG, "test_timer_param_carries_forward PASSED");
    Ok(())
}

#[test]
fn test_timer_clone_shares_one_timer() -> Result<()> {
    log_info!(TAG, "Starting test_timer_clone_shares_one_timer");

    static FIRES: AtomicU32 = AtomicU32::new(0);

    let timer = Timer::new(
        "shared_timer",
        Duration::from_millis(20).to_ticks(),
        true,
        None,
        |_handle, param| {
            FIRES.fetch_add(1, Ordering::SeqCst);
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    let mut clone = timer.clone();

    // Starting through one handle and stopping through the other has to act
    // on the same timer.
    assert_eq!(timer.start(0), OsalRsBool::True);
    System::delay(Duration::from_millis(80).to_ticks());
    assert_eq!(clone.stop(0), OsalRsBool::True);

    let fired = FIRES.load(Ordering::SeqCst);
    assert!(fired >= 2, "the clone must drive the same timer (saw {fired})");

    // And a deletion through one handle has to be visible from the other.
    assert_eq!(clone.delete(0), OsalRsBool::True);
    assert!(clone.is_null());
    assert!(timer.is_null(), "a deletion must be visible through every clone");
    assert_eq!(timer.start(0), OsalRsBool::False);

    log_info!(TAG, "test_timer_clone_shares_one_timer PASSED");
    Ok(())
}

#[test]
fn test_timer_dropping_last_handle_stops_it() -> Result<()> {
    log_info!(TAG, "Starting test_timer_dropping_last_handle_stops_it");

    static FIRES: AtomicU32 = AtomicU32::new(0);

    {
        let timer = Timer::new(
            "dropped_timer",
            Duration::from_millis(20).to_ticks(),
            true,
            None,
            |_handle, param| {
                FIRES.fetch_add(1, Ordering::SeqCst);
                Ok(param.unwrap_or_else(|| Arc::new(())))
            }
        )?;

        // A clone keeps the timer alive; only the *last* handle going away
        // may tear it down.
        let clone = timer.clone();
        assert_eq!(timer.start(0), OsalRsBool::True);
        System::delay(Duration::from_millis(80).to_ticks());
        drop(timer);

        System::delay(Duration::from_millis(50).to_ticks());
        assert!(!clone.is_null(), "a surviving clone must keep the timer alive");
    }

    let fired_while_alive = FIRES.load(Ordering::SeqCst);
    log_debug!(TAG, "fired {} time(s) before the last handle was dropped", fired_while_alive);
    assert!(fired_while_alive >= 2, "the timer must have been running (saw {fired_while_alive})");

    System::delay(Duration::from_millis(120).to_ticks());

    assert_eq!(
        FIRES.load(Ordering::SeqCst),
        fired_while_alive,
        "dropping the last handle must destroy the timer"
    );

    log_info!(TAG, "test_timer_dropping_last_handle_stops_it PASSED");
    Ok(())
}

#[test]
fn test_timer_callback_dropping_last_handle() -> Result<()> {
    log_info!(TAG, "Starting test_timer_callback_dropping_last_handle");

    // Holds the only surviving handle, so that the callback itself can drop
    // it. Teardown then runs *on* the timer's own background thread, which
    // cannot join itself - see `posix::Thread::detach`.
    static SLOT: std::sync::Mutex<Option<Timer>> = std::sync::Mutex::new(None);
    static FIRES: AtomicU32 = AtomicU32::new(0);

    let timer = Timer::new(
        "self_drop_timer",
        Duration::from_millis(20).to_ticks(),
        true,
        None,
        |_handle, param| {
            FIRES.fetch_add(1, Ordering::SeqCst);
            if let Ok(mut slot) = SLOT.lock() {
                drop(slot.take());
            }
            Ok(param.unwrap_or_else(|| Arc::new(())))
        }
    )?;

    *SLOT.lock().unwrap() = Some(timer.clone());
    assert_eq!(timer.start(0), OsalRsBool::True);
    drop(timer);

    System::delay(Duration::from_millis(150).to_ticks());

    let fires = FIRES.load(Ordering::SeqCst);
    log_debug!(TAG, "fired {} time(s) before tearing itself down", fires);
    assert!(fires >= 1, "the timer must have fired at least once (saw {fires})");

    // Having torn itself down from inside its own callback, it must neither
    // deadlock nor keep firing.
    System::delay(Duration::from_millis(100).to_ticks());
    assert_eq!(FIRES.load(Ordering::SeqCst), fires, "the timer must be gone");

    log_info!(TAG, "test_timer_callback_dropping_last_handle PASSED");
    Ok(())
}