Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / system / TimeSource.h
1 /*
2  *
3  *    Copyright (c) 2020 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 /**
19  * @brief defines a generic time source interface that uses a real clock
20  *        at runtime but can be substituted by a test one for unit tests.
21  */
22
23 #pragma once
24
25 #include <stdlib.h>
26 #include <system/SystemClock.h>
27
28 namespace chip {
29 namespace Time {
30
31 enum class Source
32 {
33     kSystem, // System time source
34     kTest,   // Test time source
35 };
36
37 /**
38  * Defines a generic time source within a system. System time and test times
39  * are available.
40  */
41 template <Source kSource>
42 class TimeSource
43 {
44 public:
45     /**
46      * Returns a monotonically increasing time in milliseconds since an arbitrary, platform-defined
47      * epoch.
48      *
49      * Maintains requirements for the System::Platform::Layer clock implementation:
50      *
51      *  - Return a value that is ever-increasing (i.e. never * wraps) between reboots of the system.
52      *  - The underlying time source is required to tick continuously during any system sleep modes
53      *    such that the values do not entail a restart upon wake.
54      *  - This function is expected to be thread-safe on any platform that employs threading.
55      */
56     uint64_t GetCurrentMonotonicTimeMs();
57 };
58
59 /**
60  * A system time source, based on the system platform layer.
61  */
62 template <>
63 class TimeSource<Source::kSystem>
64 {
65 public:
66     uint64_t GetCurrentMonotonicTimeMs() { return System::Platform::Layer::GetClock_MonotonicMS(); }
67 };
68
69 /**
70  * A test time source. Allows setting the current time.
71  */
72 template <>
73 class TimeSource<Source::kTest>
74 {
75 public:
76     uint64_t GetCurrentMonotonicTimeMs() { return mCurrentTimeMs; }
77
78     void SetCurrentMonotonicTimeMs(uint64_t value)
79     {
80         if (value < mCurrentTimeMs)
81         {
82             abort();
83         }
84         mCurrentTimeMs = value;
85     }
86
87 private:
88     uint64_t mCurrentTimeMs = 0;
89 };
90
91 } // namespace Time
92 } // namespace chip