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 "time_manager.h"
19 
20 #include <string>
21 #include "common_utils.h"
22 #include "elapsed_real_time_check.h"
23 #include "location_log.h"
24 #include "time_service_client.h"
25 
26 namespace OHOS {
27 namespace Location {
28 const int64_t INVALID_TIME = 0;
29 const int64_t GPS_UTC_REFERENCE_TIME = 946656000;  // 946656000:UTC time of 2000-01-01 00:00:00
30 
GetCurrentTime()31 int64_t TimeManager::GetCurrentTime()
32 {
33     LBSLOGI(GNSS, "beginning timestamp_ is %{public}s", std::to_string(timestamp_).c_str());
34     if (timestamp_ < GPS_UTC_REFERENCE_TIME) {
35         return INVALID_TIME;
36     }
37     if (!ElapsedRealTimeCheck::GetInstance()->CanTrustElapsedRealTime()) {
38         LBSLOGI(GNSS, "getCurrentTime ElapsedRealTime INVALID_TIME");
39         return INVALID_TIME;
40     }
41 
42     int64_t timeTillNow = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs() - timeSinceBoot_;
43     if (timeTillNow >= expireTime_) {
44         LBSLOGI(GNSS, "getCurrentTime INVALID_TIME");
45         return INVALID_TIME;
46     } else {
47         LBSLOGI(GNSS, "getCurrentTime:%{public}s", std::to_string(timestamp_ + timeTillNow).c_str());
48         return timestamp_ + timeTillNow;
49     }
50 }
51 
SetCurrentTime(int64_t msTime,int64_t msTimeSynsBoot)52 void TimeManager::SetCurrentTime(int64_t msTime, int64_t msTimeSynsBoot)
53 {
54     timestamp_ = msTime;
55     timeSinceBoot_ = msTimeSynsBoot;
56     LBSLOGI(GNSS, "setCurrentTime timestamp_:%{public}s,  mTimeReference:%{public}s",
57         std::to_string(timestamp_).c_str(), std::to_string(timeSinceBoot_).c_str());
58 }
59 
GetTimestamp()60 int64_t TimeManager::GetTimestamp()
61 {
62     return timestamp_;
63 }
64 
65 }  // namespace Location
66 }  // namespace OHOS
67 #endif  // TIME_SERVICE_ENABLE
68 #endif
69