1 /* 2 * Copyright (c) 2023 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 #ifndef TIME_UTILS_H 17 #define TIME_UTILS_H 18 19 #include <chrono> 20 #include <cstdio> 21 #include <random> 22 #include <stdlib.h> 23 #include <string> 24 #include <time.h> 25 26 #include "update_log.h" 27 28 namespace OHOS { 29 namespace UpdateEngine { 30 class TimeUtils { 31 static constexpr int64_t BOOT_COMPLETE_SIMULATE_DURATION = 60L; // 模拟开机广播:时间判断门限 32 public: GetTimestamp()33 static int64_t GetTimestamp() 34 { 35 time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 36 return static_cast<int64_t>(currentTime); 37 } 38 GetTimestampByMilliseconds()39 static int64_t GetTimestampByMilliseconds() 40 { 41 return std::chrono::duration_cast<std::chrono::milliseconds> 42 (std::chrono::system_clock::now().time_since_epoch()).count(); 43 } 44 GetPrintTimeStr(int64_t time)45 static std::string GetPrintTimeStr(int64_t time) 46 { 47 time_t printTime = static_cast<time_t>(time); 48 tm *tmpTm = localtime(&printTime); 49 if (tmpTm == NULL) { 50 return ""; 51 } 52 return asctime(tmpTm); 53 } 54 GetRandTime(int32_t minTime,int32_t maxTime)55 static int64_t GetRandTime(int32_t minTime, int32_t maxTime) 56 { 57 // 随机 minTime ~ maxTime时间 58 if (maxTime < minTime) { 59 return minTime; 60 } 61 constexpr uint32_t randMin = 0; 62 std::random_device rd; 63 std::mt19937 gen(rd()); 64 std::uniform_int_distribution<> dis(randMin, maxTime - minTime - 1); 65 int64_t randomNumber = dis(gen); 66 return randomNumber; 67 } 68 GetSystemBootDuration()69 static int64_t GetSystemBootDuration() 70 { 71 int64_t bootSeconds = 72 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()) 73 .count(); 74 int64_t currentTime = GetTimestamp(); 75 int64_t bootTime = currentTime - bootSeconds; 76 ENGINE_LOGI("GetSystemBootDuration bootSeconeds is %{public}s, bootTime is %{public}s", 77 std::to_string(bootSeconds).c_str(), GetPrintTimeStr(bootTime).c_str()); 78 return bootSeconds; 79 } 80 IsInRebootDuration()81 static bool IsInRebootDuration() 82 { 83 return GetSystemBootDuration() <= BOOT_COMPLETE_SIMULATE_DURATION; 84 } 85 }; 86 } // namespace UpdateEngine 87 } // namespace OHOS 88 #endif // TIME_UTILS_H