1use crate::{Status, is_in_coroutine};
2use synchronization::once_lock::OnceLock;
3
4static TIME: OnceLock<&'static time::Manager<'static>> = OnceLock::new();
5pub fn initialize(time_manager: &'static time::Manager<'static>) {
8 TIME.get_or_init(|| time_manager);
9}
10
11pub unsafe extern "C" fn xila_time_monotonic(nanoseconds: *mut u64) -> Status {
15 if nanoseconds.is_null() {
16 return Status::InvalidArgument;
17 }
18 let Some(time) = TIME.try_get() else {
19 return Status::Unavailable;
20 };
21 match u64::try_from(time.monotonic_now().as_nanos()) {
22 Ok(value) => {
23 unsafe { nanoseconds.write(value) };
24 Status::Ok
25 }
26 Err(_) => Status::Overflow,
27 }
28}
29pub unsafe extern "C" fn xila_time_realtime(nanoseconds: *mut i64) -> Status {
33 if nanoseconds.is_null() {
34 return Status::InvalidArgument;
35 }
36 let Some(time) = TIME.try_get() else {
37 return Status::Unavailable;
38 };
39 match time.realtime_now() {
40 Ok(value) => match i64::try_from(value.as_nanos()) {
41 Ok(value) => {
42 unsafe { nanoseconds.write(value) };
43 Status::Ok
44 }
45 Err(_) => Status::Overflow,
46 },
47 Err(time::Error::Overflow) => Status::Overflow,
48 Err(_) => Status::Unavailable,
49 }
50}
51
52pub const XILA_CLOCK_MONOTONIC: u32 = 0;
54pub const XILA_CLOCK_REALTIME: u32 = 1;
56
57pub unsafe extern "C" fn xila_time_resolution(clock: u32, nanoseconds: *mut u64) -> Status {
64 if nanoseconds.is_null() || clock > XILA_CLOCK_REALTIME {
65 return Status::InvalidArgument;
66 }
67 let Some(time) = TIME.try_get() else {
68 return Status::Unavailable;
69 };
70 let resolution = if clock == XILA_CLOCK_MONOTONIC {
71 time.monotonic_resolution()
72 } else {
73 time.realtime_resolution()
74 };
75 match u64::try_from(resolution.as_nanos()) {
76 Ok(value) => {
77 unsafe { nanoseconds.write(value) };
78 Status::Ok
79 }
80 Err(_) => Status::Overflow,
81 }
82}
83
84pub extern "C" fn xila_time_sleep(nanoseconds: u64) -> Status {
91 use embassy_time::{Instant, Timer};
92 let deadline = task::deadline_after_nanoseconds(nanoseconds);
93 if is_in_coroutine() {
94 crate::suspend_dynamic(core::pin::pin!(Timer::at(deadline)));
95 } else {
96 while Instant::now() < deadline {
97 core::hint::spin_loop();
98 }
99 }
100 Status::Ok
101}