3 * Copyright (c) 2020 Project CHIP Authors
4 * Copyright (c) 2018 Nest Labs, Inc.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
22 * Provides implementations of the CHIP System Layer platform
23 * time/clock functions that are suitable for use on the ESP32 platform.
25 /* this file behaves like a config.h, comes first */
26 #include <platform/internal/CHIPDeviceLayerInternal.h>
28 #include <support/TimeUtils.h>
29 #include <support/logging/CHIPLogging.h>
31 #include <esp_timer.h>
38 uint64_t GetClock_Monotonic(void)
40 return (uint64_t)::esp_timer_get_time();
43 uint64_t GetClock_MonotonicMS(void)
45 return (uint64_t)::esp_timer_get_time() / 1000;
48 uint64_t GetClock_MonotonicHiRes(void)
50 return (uint64_t)::esp_timer_get_time();
53 Error GetClock_RealTime(uint64_t & curTime)
56 int res = gettimeofday(&tv, NULL);
59 return MapErrorPOSIX(errno);
61 if (tv.tv_sec < CHIP_SYSTEM_CONFIG_VALID_REAL_TIME_THRESHOLD)
63 return CHIP_SYSTEM_ERROR_REAL_TIME_NOT_SYNCED;
65 curTime = (tv.tv_sec * UINT64_C(1000000)) + tv.tv_usec;
66 return CHIP_SYSTEM_NO_ERROR;
69 Error GetClock_RealTimeMS(uint64_t & curTime)
72 int res = gettimeofday(&tv, NULL);
75 return MapErrorPOSIX(errno);
77 if (tv.tv_sec < CHIP_SYSTEM_CONFIG_VALID_REAL_TIME_THRESHOLD)
79 return CHIP_SYSTEM_ERROR_REAL_TIME_NOT_SYNCED;
81 curTime = (tv.tv_sec * UINT64_C(1000)) + (tv.tv_usec / 1000);
82 return CHIP_SYSTEM_NO_ERROR;
85 Error SetClock_RealTime(uint64_t newCurTime)
88 tv.tv_sec = static_cast<time_t>(newCurTime / UINT64_C(1000000));
89 tv.tv_usec = static_cast<long>(newCurTime % UINT64_C(1000000));
90 int res = settimeofday(&tv, NULL);
93 return (errno == EPERM) ? CHIP_SYSTEM_ERROR_ACCESS_DENIED : MapErrorPOSIX(errno);
95 #if CHIP_PROGRESS_LOGGING
98 uint8_t month, dayOfMonth, hour, minute, second;
99 SecondsSinceEpochToCalendarTime(tv.tv_sec, year, month, dayOfMonth, hour, minute, second);
100 ChipLogProgress(DeviceLayer,
101 "Real time clock set to %ld (%04" PRId16 "/%02" PRId8 "/%02" PRId8 " %02" PRId8 ":%02" PRId8 ":%02" PRId8
103 tv.tv_sec, year, month, dayOfMonth, hour, minute, second);
105 #endif // CHIP_PROGRESS_LOGGING
106 return CHIP_SYSTEM_NO_ERROR;
110 } // namespace Platform
111 } // namespace System