1 #![allow(dead_code)]
2 use crate::include::bindings::bindings::{rtc_get_cmos_time, rtc_time_t};
3
4 #[allow(non_camel_case_types)]
5 pub type ktime_t = i64;
6
7 // @brief 将ktime_t类型转换为纳秒类型
8 #[inline]
ktime_to_ns(kt: ktime_t) -> i649 fn ktime_to_ns(kt: ktime_t) -> i64 {
10 return kt as i64;
11 }
12
13 /// @brief 从RTC获取当前时间,然后计算时间戳。
14 /// 时间戳为从UTC+0 1970-01-01 00:00到当前UTC+0时间,所经过的纳秒数。
15 /// 注意,由于当前未引入时区,因此本函数默认时区为UTC+8来计算
ktime_get_real() -> ktime_t16 fn ktime_get_real() -> ktime_t {
17 let mut rtc_time: rtc_time_t = rtc_time_t {
18 second: (0),
19 minute: (0),
20 hour: (0),
21 day: (0),
22 month: (0),
23 year: (0),
24 };
25
26 unsafe {
27 //调用rtc.h里面的函数
28 rtc_get_cmos_time(&mut rtc_time);
29 }
30
31 let mut day_count: i32 = 0;
32 for year in 1970..rtc_time.year {
33 let leap: bool = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
34 if leap {
35 day_count += 366;
36 } else {
37 day_count += 365;
38 }
39 //println!("{},{}",year,day_count);
40 }
41 //println!("day count1: {}",day_count);
42 for month in 1..rtc_time.month {
43 match month {
44 1 | 3 | 5 | 7 | 8 | 10 | 12 => day_count += 31,
45 2 => day_count += 28,
46 4 | 6 | 9 | 11 => day_count += 30,
47 _ => day_count += 0,
48 }
49 //println!("{}:{}",month,day_count);
50 }
51
52 day_count += rtc_time.day - 1;
53 //println!("day count2: {}",day_count);
54 //转换成纳秒
55 let timestamp: ktime_t = day_count as i64 * 86_400_000_000_000i64
56 + (rtc_time.hour - 8) as i64 * 3_600_000_000_000i64
57 + rtc_time.minute as i64 * 60_000_000_000i64
58 + rtc_time.second as i64 * 1_000_000_000i64 as ktime_t;
59
60 return timestamp;
61 }
62
63 /// @brief 暴露给外部使用的接口,返回一个时间戳
64 #[inline]
ktime_get_real_ns() -> i6465 pub fn ktime_get_real_ns() -> i64 {
66 let kt: ktime_t = ktime_get_real();
67 return ktime_to_ns(kt);
68 }
69