Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2021 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : #include <lib/support/UnitTestUtils.h>
19 :
20 : // Platform specific includes for test_utils
21 : #include <platform/CHIPDeviceConfig.h>
22 : #if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA
23 : #include <FreeRTOS.h>
24 : #include <task.h>
25 : #else
26 : #include <time.h>
27 : #include <unistd.h>
28 : #endif
29 :
30 : namespace chip {
31 : namespace test_utils {
32 :
33 : #if CHIP_DEVICE_LAYER_TARGET_EFR32 || CHIP_DEVICE_LAYER_TARGET_AMEBA
34 :
35 : namespace {
36 :
37 : constexpr uint64_t TicksToMillis(uint32_t ticks)
38 : {
39 : const uint64_t seconds = ticks / configTICK_RATE_HZ;
40 : const uint64_t millis_ticks = ticks - (seconds * configTICK_RATE_HZ);
41 : const uint64_t millis = (((millis_ticks * 1000) + (configTICK_RATE_HZ / 2)) / configTICK_RATE_HZ);
42 : return (seconds * 1000) + millis;
43 : }
44 :
45 : } // namespace
46 :
47 : uint64_t TimeMonotonicMillis()
48 : {
49 : return TicksToMillis(xTaskGetTickCount());
50 : }
51 :
52 : void SleepMillis(uint64_t millisecs)
53 : {
54 : uint32_t ticks = pdMS_TO_TICKS(millisecs);
55 : vTaskDelay(ticks == 0 ? 1 : ticks); // delay at least 1 tick
56 : }
57 :
58 : void SleepMicros(uint64_t microsecs)
59 : {
60 : // FreeRTOS currently only sleep for intervals of 1ms
61 : SleepMillis((microsecs + 500) / 1000);
62 : }
63 :
64 : #else
65 :
66 21 : void SleepMicros(uint64_t microsecs)
67 : {
68 21 : usleep(static_cast<useconds_t>(microsecs));
69 21 : }
70 :
71 18 : void SleepMillis(uint64_t millisecs)
72 : {
73 18 : SleepMicros(millisecs * 1000);
74 18 : }
75 :
76 979321 : uint64_t TimeMonotonicMillis()
77 : {
78 979321 : return static_cast<uint64_t>(time(nullptr) * 1000);
79 : }
80 :
81 : #endif
82 :
83 : } // namespace test_utils
84 : } // namespace chip
|