os/device/rtc/
mod.rs

1//! RTC 设备驱动模块
2
3use super::Driver;
4use chrono::{DateTime as ChronoDateTime, Datelike, FixedOffset, TimeZone, Timelike, Utc};
5
6/// 简化的日期时间结构(用于 sysfs 显示)
7#[derive(Debug, Clone, Copy)]
8pub struct DateTime {
9    pub year: i32,
10    pub month: u32,
11    pub day: u32,
12    pub hour: u32,
13    pub minute: u32,
14    pub second: u32,
15}
16
17impl DateTime {
18    /// 从 Unix 时间戳(秒)转换为北京时间 (UTC+8)
19    pub fn from_epoch(epoch: u64) -> Self {
20        // 创建 UTC 时间
21        let utc_time = match Utc.timestamp_opt(epoch as i64, 0) {
22            chrono::LocalResult::Single(t) => t,
23            _ => {
24                // 如果时间戳无效,返回一个默认值
25                return Self {
26                    year: 1970,
27                    month: 1,
28                    day: 1,
29                    hour: 0,
30                    minute: 0,
31                    second: 0,
32                };
33            }
34        };
35
36        // 转换为北京时间 (UTC+8)
37        let beijing_offset = FixedOffset::east_opt(8 * 3600).unwrap();
38        let beijing_time: ChronoDateTime<FixedOffset> = utc_time.with_timezone(&beijing_offset);
39
40        Self {
41            year: beijing_time.year(),
42            month: beijing_time.month(),
43            day: beijing_time.day(),
44            hour: beijing_time.hour(),
45            minute: beijing_time.minute(),
46            second: beijing_time.second(),
47        }
48    }
49}
50
51pub mod rtc_goldfish;
52
53/// RTC 设备驱动接口
54pub trait RtcDriver: Driver {
55    /// 读取自纪元以来的秒数
56    fn read_epoch(&self) -> u64;
57
58    /// 读取日期时间(北京时间,默认实现)
59    fn read_datetime(&self) -> DateTime {
60        DateTime::from_epoch(self.read_epoch())
61    }
62}