1 // Copyright 2017 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // Provides strong definition for system time functions relied upon
16 // by core components.
17 #include "sdkconfig.h"
18 
19 #if CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER
20 #include "esp_timer.h"
21 #include "esp_timer_impl.h"
22 #include "esp_system.h"
23 #include "esp_newlib.h"
24 #include "esp_log.h"
25 
26 #include "esp_private/startup_internal.h"
27 
28 #if CONFIG_IDF_TARGET_ESP32
29 #include "esp32/rtc.h"
30 #elif CONFIG_IDF_TARGET_ESP32S2
31 #include "esp32s2/rtc.h"
32 #elif CONFIG_IDF_TARGET_ESP32S3
33 #include "esp32s3/rtc.h"
34 #elif CONFIG_IDF_TARGET_ESP32C3
35 #include "esp32c3/rtc.h"
36 #elif CONFIG_IDF_TARGET_ESP32H2
37 #include "esp32h2/rtc.h"
38 #endif
39 
40 __attribute__((unused)) static const char* TAG = "system_time";
41 
42 // Correction for underlying timer to keep definition
43 // of system time consistent.
44 static int64_t s_correction_us = 0;
45 
esp_timer_impl_init_system_time(void)46 void esp_timer_impl_init_system_time(void)
47 {
48     s_correction_us = esp_rtc_get_time_us() - g_startup_time - esp_timer_impl_get_time();
49 #if defined(CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER) && defined(CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER)
50     esp_err_t err = esp_register_shutdown_handler(esp_sync_counters_rtc_and_frc);
51     if (err != ESP_OK) {
52         ESP_LOGW(TAG, "Register shutdown handler failed, err = 0x%x", err);
53     }
54 #endif
55 }
56 
esp_system_get_time(void)57 int64_t IRAM_ATTR esp_system_get_time(void)
58 {
59     return esp_timer_get_time() + s_correction_us;
60 }
61 
esp_system_get_time_resolution(void)62 uint32_t IRAM_ATTR esp_system_get_time_resolution(void)
63 {
64     return 1000;
65 }
66 #endif
67