1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
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
16 #ifdef FEATURE_GNSS_SUPPORT
17 #ifdef TIME_SERVICE_ENABLE
18 #include "elapsed_real_time_check.h"
19
20 #include <cmath>
21 #include <string>
22
23 #include "common_utils.h"
24 #include "location_log.h"
25 #include "time_service_client.h"
26
27 namespace OHOS {
28 namespace Location {
29 const int64_t MAX_MISS_MS = 24 * 1000; // we only allow 24s misstake
30
GetInstance()31 ElapsedRealTimeCheck *ElapsedRealTimeCheck::GetInstance()
32 {
33 static ElapsedRealTimeCheck data;
34 return &data;
35 }
36
ElapsedRealTimeCheck()37 ElapsedRealTimeCheck::ElapsedRealTimeCheck() {}
38
~ElapsedRealTimeCheck()39 ElapsedRealTimeCheck::~ElapsedRealTimeCheck() {}
40
CheckRealTime(int64_t time)41 void ElapsedRealTimeCheck::CheckRealTime(int64_t time)
42 {
43 if (timeBegin_ == 0) {
44 timeBegin_ = time;
45 timeBeginElapsed_ = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
46 } else if (timeCheck_ == 0) {
47 timeCheck_ = time;
48 timeCheckElapsed_ = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
49 } else {
50 LBSLOGD(GNSS, "checkRealTime");
51 }
52
53 if ((timeBegin_ != 0) && (timeCheck_ != 0)) {
54 int64_t missTime = (timeCheck_ - timeBegin_) - (timeCheckElapsed_ - timeBeginElapsed_);
55 LBSLOGD(GNSS,
56 "checkRealTime timeBegin_:%{public}s, timeCheck_:%{public}s, timeBeginElapsed_:%{public}s, "
57 "timeCheckElapsed_:%{public}s",
58 std::to_string(timeBegin_).c_str(), std::to_string(timeCheck_).c_str(),
59 std::to_string(timeBeginElapsed_).c_str(), std::to_string(timeCheckElapsed_).c_str());
60 LBSLOGI(GNSS, "checkRealTime missTime:%{public}s", std::to_string(missTime).c_str());
61 // we found missTime usually should not grow, results should be simillar on any moment.
62 // so if very high missTime should be problem.
63 if (std::abs(missTime) >= MAX_MISS_MS) {
64 LBSLOGI(GNSS, "checkRealTime false");
65 canTrustElapsedRealTime_ = false;
66 } else {
67 // sometimes just once system communication block, this could recover automaticly,
68 // elapsedRealtime still be ok.
69 canTrustElapsedRealTime_ = true;
70 }
71 timeCheck_ = 0;
72 timeCheckElapsed_ = 0;
73 }
74 }
75
CanTrustElapsedRealTime()76 bool ElapsedRealTimeCheck::CanTrustElapsedRealTime()
77 {
78 return canTrustElapsedRealTime_;
79 }
80
81 } // namespace Location
82 } // namespace OHOS
83 #endif // TIME_SERVICE_ENABLE
84 #endif
85