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 "ntp_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 INVALID_TIME = 0;
30 const int64_t MISSTAKE_TIME = 50 * 1000; // 50s
31
NtpTimeCheck()32 NtpTimeCheck::NtpTimeCheck() {}
33
~NtpTimeCheck()34 NtpTimeCheck::~NtpTimeCheck() {}
35
GetInstance()36 NtpTimeCheck *NtpTimeCheck::GetInstance()
37 {
38 static NtpTimeCheck data;
39 return &data;
40 }
41
CheckNtpTime(int64_t ntpMsTime,int64_t msTimeSynsBoot)42 bool NtpTimeCheck::CheckNtpTime(int64_t ntpMsTime, int64_t msTimeSynsBoot)
43 {
44 int64_t currentNtpTime =
45 ntpMsTime + MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - msTimeSynsBoot;
46 if (gpsTimeManager_.GetGpsTime() != INVALID_TIME) {
47 return CompareTime(currentNtpTime, gpsTimeManager_.GetGpsTime());
48 }
49
50 LBSLOGI(GNSS, "checkNtpTime return false");
51 return false;
52 }
53
CompareTime(int64_t currentNtpTime,int64_t compareTime)54 bool NtpTimeCheck::CompareTime(int64_t currentNtpTime, int64_t compareTime)
55 {
56 LBSLOGI(GNSS, "compareTime currentNtpTime:%{public}s, compareTime:%{public}s",
57 std::to_string(currentNtpTime).c_str(), std::to_string(compareTime).c_str());
58 int64_t misstake = std::abs(currentNtpTime - compareTime);
59 if (misstake > MISSTAKE_TIME) {
60 LBSLOGI(GNSS, "find error ntp time:%{public}s", std::to_string(misstake).c_str());
61 return false;
62 } else {
63 difference_ = misstake;
64 return true;
65 }
66 }
67
SetGpsTime(int64_t gpsMsTime,int64_t bootTimeMs)68 void NtpTimeCheck::SetGpsTime(int64_t gpsMsTime, int64_t bootTimeMs)
69 {
70 if (gpsMsTime <= 0 || bootTimeMs <= 0) {
71 LBSLOGE(GNSS, "set gps time failed :%{public}s, %{public}s", std::to_string(gpsMsTime).c_str(),
72 std::to_string(bootTimeMs).c_str());
73 return;
74 }
75 gpsTimeManager_.SetGpsTime(gpsMsTime, bootTimeMs);
76 }
77
GetUncertainty()78 int NtpTimeCheck::GetUncertainty()
79 {
80 return (difference_ > DEFAULT_UNCERTAINTY) ? difference_ : DEFAULT_UNCERTAINTY;
81 }
82
83 } // namespace Location
84 } // namespace OHOS
85 #endif // TIME_SERVICE_ENABLE
86 #endif
87