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_helper.h"
19
20 #include <string>
21 #include "gnss_ability.h"
22 #include "location_log.h"
23 #include "ntp_time_check.h"
24 #include "time_service_client.h"
25
26 namespace OHOS {
27 namespace Location {
28 static const int64_t NTP_INTERVAL = 24 * 60 * 60 * 1000;
29
GetInstance()30 NtpTimeHelper *NtpTimeHelper::GetInstance()
31 {
32 static NtpTimeHelper data;
33 return &data;
34 }
35
RetrieveAndInjectNtpTime()36 void NtpTimeHelper::RetrieveAndInjectNtpTime()
37 {
38 if (ntpResult_.elapsedRealTime > 0) {
39 ntpResult_.ageMillis =
40 MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - ntpResult_.elapsedRealTime;
41 LBSLOGD(GNSS, "ntp age millis %{public}s", std::to_string(ntpResult_.ageMillis).c_str());
42 }
43
44 auto gnssAbility = GnssAbility::GetInstance();
45 if (ntpResult_.ntpTime == 0 || ntpResult_.ageMillis > NTP_INTERVAL) {
46 auto ret = MiscServices::TimeServiceClient::GetInstance()->GetNtpTimeMs(ntpResult_.ntpTime);
47 if (ret != ERR_OK) {
48 ntpResult_.ntpTime = 0;
49 LBSLOGE(GNSS, "failed to get ntp time %{public}d", ret);
50 return;
51 }
52 LBSLOGI(GNSS, "get ntp time %{public}s", std::to_string(ntpResult_.ntpTime).c_str());
53 ntpResult_.elapsedRealTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
54 ntpResult_.ageMillis = 0;
55 if (gnssAbility != nullptr) {
56 gnssAbility->UpdateNtpTime(ntpResult_.ntpTime, ntpResult_.elapsedRealTime);
57 }
58 }
59 if (gnssAbility != nullptr) {
60 gnssAbility->InjectTime();
61 }
62 }
63
64 } // namespace Location
65 } // namespace OHOS
66 #endif // TIME_SERVICE_ENABLE
67 #endif
68