101876902SGou Ngai #![allow(dead_code)] 2ba0d93d8SGou Ngai 362e46139SGou Ngai use crate::driver::timers::rtc::rtc::RtcTime; 401876902SGou Ngai 501876902SGou Ngai #[allow(non_camel_case_types)] 601876902SGou Ngai pub type ktime_t = i64; 701876902SGou Ngai 801876902SGou Ngai // @brief 将ktime_t类型转换为纳秒类型 901876902SGou Ngai #[inline] 1001876902SGou Ngai fn ktime_to_ns(kt: ktime_t) -> i64 { 11*840045afSLoGin return kt; 1201876902SGou Ngai } 1301876902SGou Ngai 1401876902SGou Ngai /// @brief 从RTC获取当前时间,然后计算时间戳。 1501876902SGou Ngai /// 时间戳为从UTC+0 1970-01-01 00:00到当前UTC+0时间,所经过的纳秒数。 1601876902SGou Ngai /// 注意,由于当前未引入时区,因此本函数默认时区为UTC+8来计算 1701876902SGou Ngai fn ktime_get_real() -> ktime_t { 1862e46139SGou Ngai let mut rtc_time: RtcTime = RtcTime::default(); 1901876902SGou Ngai 2062e46139SGou Ngai { 2162e46139SGou Ngai let r = rtc_time.get(); 2262e46139SGou Ngai // 返回错误码 23*840045afSLoGin if let Err(e) = r { 24*840045afSLoGin return e as ktime_t; 2562e46139SGou Ngai } 2662e46139SGou Ngai } 2701876902SGou Ngai 2801876902SGou Ngai let mut day_count: i32 = 0; 2901876902SGou Ngai for year in 1970..rtc_time.year { 3001876902SGou Ngai let leap: bool = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); 3101876902SGou Ngai if leap { 3201876902SGou Ngai day_count += 366; 3301876902SGou Ngai } else { 3401876902SGou Ngai day_count += 365; 3501876902SGou Ngai } 3601876902SGou Ngai } 3701876902SGou Ngai for month in 1..rtc_time.month { 3801876902SGou Ngai match month { 3901876902SGou Ngai 1 | 3 | 5 | 7 | 8 | 10 | 12 => day_count += 31, 4001876902SGou Ngai 2 => day_count += 28, 4101876902SGou Ngai 4 | 6 | 9 | 11 => day_count += 30, 4201876902SGou Ngai _ => day_count += 0, 4301876902SGou Ngai } 4401876902SGou Ngai } 4501876902SGou Ngai 4601876902SGou Ngai day_count += rtc_time.day - 1; 4701876902SGou Ngai //转换成纳秒 4801876902SGou Ngai let timestamp: ktime_t = day_count as i64 * 86_400_000_000_000i64 4901876902SGou Ngai + (rtc_time.hour - 8) as i64 * 3_600_000_000_000i64 5001876902SGou Ngai + rtc_time.minute as i64 * 60_000_000_000i64 51ba0d93d8SGou Ngai + rtc_time.second as i64 * 1_000_000_000u64 as ktime_t; 5201876902SGou Ngai 5301876902SGou Ngai return timestamp; 5401876902SGou Ngai } 5501876902SGou Ngai 5601876902SGou Ngai /// @brief 暴露给外部使用的接口,返回一个时间戳 5701876902SGou Ngai #[inline] 5801876902SGou Ngai pub fn ktime_get_real_ns() -> i64 { 5901876902SGou Ngai let kt: ktime_t = ktime_get_real(); 6001876902SGou Ngai return ktime_to_ns(kt); 6101876902SGou Ngai } 62