zephyrproject-rtos / zephyr

Primary Git Repository for the Zephyr Project. Zephyr is a new generation, scalable, optimized, secure RTOS for multiple hardware architectures.
https://docs.zephyrproject.org
Apache License 2.0
9.74k stars 6k forks source link

lib: sys: time: Add native real-time time library #72173

Open bjarki-trackunit opened 2 weeks ago

bjarki-trackunit commented 2 weeks ago

Introduction

This PR adds native APIs for getting and setting real-time, either formatted as a timestamp or a struct rtc_time formatted datetime, abstracting both conversions between the two time formats, and the interactions with the underlying hardware which will be used to keep time.

The API

/** Get universal coordinated time timestamp */
int sys_time_get_timestamp(int64_t *timestamp);
/** Set universal coordinated time timestamp */
int sys_time_set_timestamp(const int64_t *timestamp);

/** Get universal coordinated time datetime */
int sys_time_get_datetime(struct rtc_time *datetime);
/** Set universal coordinated time datetime */
int sys_time_set_datetime(const struct rtc_time *datetime);

/** Convert universal coordinated time datetime to timestamp */
int sys_time_datetime_to_timestamp(int64_t *timestamp, const struct rtc_time *datetime);
/** Convert universal coordinated time timestamp to datetime */
int sys_time_timestamp_to_datetime(struct rtc_time *datetime, const int64_t *timestamp);

The timestamp is a UTC timestamp, stored in an int64_t. Datetime (clock+calendar) formatted time is stored in a struct rtc_time, which is 1-1 mapped to the struct tm.

Hardware support

RTC

This PR currently supports using an RTC as time provider. The RTC to use is designated using a DTS chosen node

/ {
    chosen {
        zephyr,rtc = &rtc;
    };
};

Counter (In progress)

This PR will be expanded to support using a low power counter as a time provider, using the counter.h API to configure it, and the retained_mem.h to store the offset between the counter value and the timestamp. Chosen nodes will be used to designate both the retained mem area, and the counter to use:

/ {
    chosen {
        zephyr,real-time-counter = &counter0;
        zephyr,real-time-retmem = &retmem0;
    };
};

fixes: #35333