diff --git a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts index 9071438b0ea18674ecaa7efc934630dca7ccf933..43eb6e9d21878919e843a72da10e029fe8e7016a 100644 --- a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts +++ b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts @@ -36,43 +36,22 @@ declare namespace systemTime { * Obtains the number of milliseconds that have elapsed since the Unix epoch. * @since 8 */ - function getCurrentTime(callback: AsyncCallback): void; - function getCurrentTime(): Promise; - - /** - * Obtains the number of nanoseconds that have elapsed since the Unix epoch. - * @since 8 - */ - function getCurrentTimeNs(callback: AsyncCallback): void; - function getCurrentTimeNs(): Promise; + function getCurrentTime(isNano?: boolean, callback: AsyncCallback): void; + function getCurrentTime(isNano?: boolean,): Promise; /** * Obtains the number of milliseconds elapsed since the system was booted, not including deep sleep time. * @since 8 */ - function getRealActiveTime(callback: AsyncCallback): void; - function getRealActiveTime(): Promise; - - /** - * Obtains the number of nanoseconds elapsed since the system was booted, not including deep sleep time. - * @since 8 - */ - function getRealActiveTimeNs(callback: AsyncCallback): void; - function getRealActiveTimeNs(): Promise; + function getRealActiveTime(isNano?: boolean, callback: AsyncCallback): void; + function getRealActiveTime(isNano?: boolean, ): Promise; /** * Obtains the number of milliseconds elapsed since the system was booted, including deep sleep time. * @since 8 */ - function getRealTime(callback: AsyncCallback): void; - function getRealTime(): Promise; - - /** - * Obtains the number of nanoseconds elapsed since the system was booted, including deep sleep time. - * @since 8 - */ - function getRealTimeNs(callback: AsyncCallback): void; - function getRealTimeNs(): Promise; + function getRealTime(isNano?: boolean, callback: AsyncCallback): void; + function getRealTime(isNano?: boolean, ): Promise; /** * Sets the system time. diff --git a/interfaces/kits/js/napi/system_time/include/js_systemtime.h b/interfaces/kits/js/napi/system_time/include/js_systemtime.h index b9dbb4f79f5a0c548e34e99b7a9932aefc9ac6d3..7aac34c4b451a04f341356927824803e817563dd 100644 --- a/interfaces/kits/js/napi/system_time/include/js_systemtime.h +++ b/interfaces/kits/js/napi/system_time/include/js_systemtime.h @@ -47,6 +47,7 @@ typedef struct AsyncContext { napi_ref callbackRef = nullptr; bool isCallback = false; bool isOK = false; + bool isNano = false; int errorCode = NO_ERROR; } AsyncContext; diff --git a/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp b/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp index 1438a9cdfa0cd8a441aa99a4763953adcbbd7d48..95cfc976d2732c580f358c726061a08709a703b2 100644 --- a/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp +++ b/interfaces/kits/js/napi/system_time/src/js_systemtime.cpp @@ -272,7 +272,6 @@ napi_value JSSystemTimeSetTimeZone(napi_env env, napi_callback_info info) napi_value ParseParametersGet(const napi_env &env, const napi_value (&argv)[SET_TIMEZONE_MAX_PARA], const size_t &argc, napi_ref &callback) { - NAPI_ASSERT(env, argc >= SET_TIMEZONE_MAX_PARA - 1, "Wrong number of arguments"); napi_valuetype valueType = napi_undefined; if (argc == 1) { NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); @@ -282,67 +281,33 @@ napi_value ParseParametersGet(const napi_env &env, const napi_value (&argv)[SET_ return TimeNapiGetNull(env); } -napi_value JSSystemTimeGetCurrentTime(napi_env env, napi_callback_info info) +napi_value ParseParametersGetNA(const napi_env &env, const napi_value (&argv)[SET_TIMEZONE_MAX_PARA], + const size_t &argc, napi_ref &callback, bool *isNano) { - size_t argc = SET_TIMEZONE_MAX_PARA; - napi_value argv[SET_TIMEZONE_MAX_PARA] = {0}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { - return TimeJSParaError(env, callback); - } - AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; - if (!asyncContext) { - return TimeJSParaError(env, callback); - } - napi_value promise = nullptr; - TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); - napi_value resource = nullptr; - napi_create_string_utf8(env, "JSSystemTimeGetCurrentTime", NAPI_AUTO_LENGTH, &resource); - napi_create_async_work(env, - nullptr, - resource, - [](napi_env env, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeMs(); - }, - [](napi_env env, napi_status status, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - if (asyncContext->time < 0) { - } - TimeCallbackPromiseInfo info; - info.isCallback = asyncContext->isCallback; - info.callback = asyncContext->callbackRef; - info.deferred = asyncContext->deferred; - info.errorCode = asyncContext->errorCode; - napi_value result = nullptr; - napi_create_int64(env, asyncContext->time, &result); - TimeReturnCallbackPromise(env, info, result); - napi_delete_async_work(env, asyncContext->work); - if (asyncContext) { - delete asyncContext; - asyncContext = nullptr; - } - }, - (void*)asyncContext, - &asyncContext->work); - NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work)); - if (asyncContext->isCallback) { - return TimeNapiGetNull(env); - } else { - return promise; + napi_valuetype valueType = napi_undefined; + if (argc == 1) { + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + if (valueType == napi_function) { + napi_create_reference(env, argv[0], 1, &callback); + } else if (valueType == napi_boolean) { + napi_get_value_bool(env, argv[0], isNano); + } + } else if (argc == 2) { + napi_get_value_bool(env, argv[0], isNano); + napi_create_reference(env, argv[1], 1, &callback); } + return TimeNapiGetNull(env); } -napi_value JSSystemTimeGetCurrentTimeNs(napi_env env, napi_callback_info info) +napi_value JSSystemTimeGetCurrentTime(napi_env env, napi_callback_info info) { size_t argc = SET_TIMEZONE_MAX_PARA; napi_value argv[SET_TIMEZONE_MAX_PARA] = {0}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { + bool isNano = false; + if (ParseParametersGetNA(env, argv, argc, callback, &isNano) == nullptr) { return TimeJSParaError(env, callback); } AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; @@ -351,19 +316,23 @@ napi_value JSSystemTimeGetCurrentTimeNs(napi_env env, napi_callback_info info) } napi_value promise = nullptr; TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); + asyncContext->isNano = isNano; napi_value resource = nullptr; - napi_create_string_utf8(env, "JSSystemTimeGetCurrentTimeNs", NAPI_AUTO_LENGTH, &resource); + napi_create_string_utf8(env, "JSSystemTimeGetCurrentTime", NAPI_AUTO_LENGTH, &resource); napi_create_async_work(env, nullptr, resource, [](napi_env env, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeNs(); + if (asyncContext->isNano) { + asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeNs(); + } else { + asyncContext->time = TimeServiceClient::GetInstance()->GetWallTimeMs(); + } }, [](napi_env env, napi_status status, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; if (asyncContext->time < 0) { - asyncContext->errorCode = ERROR; } TimeCallbackPromiseInfo info; info.isCallback = asyncContext->isCallback; @@ -396,7 +365,8 @@ napi_value JSSystemTimeGetRealActiveTime(napi_env env, napi_callback_info info) napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { + bool isNano = false; + if (ParseParametersGetNA(env, argv, argc, callback, &isNano) == nullptr) { return TimeJSParaError(env, callback); } AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; @@ -405,6 +375,7 @@ napi_value JSSystemTimeGetRealActiveTime(napi_env env, napi_callback_info info) } napi_value promise = nullptr; TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); + asyncContext->isNano = isNano; napi_value resource = nullptr; napi_create_string_utf8(env, "JSSystemTimeGetRealActiveTime", NAPI_AUTO_LENGTH, &resource); napi_create_async_work(env, @@ -412,62 +383,12 @@ napi_value JSSystemTimeGetRealActiveTime(napi_env env, napi_callback_info info) resource, [](napi_env env, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeMs(); - }, - [](napi_env env, napi_status status, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - if (asyncContext->time < 0) { - asyncContext->errorCode = ERROR; - } - TimeCallbackPromiseInfo info; - info.isCallback = asyncContext->isCallback; - info.callback = asyncContext->callbackRef; - info.deferred = asyncContext->deferred; - info.errorCode = asyncContext->errorCode; - napi_value result = nullptr; - napi_create_int64(env, asyncContext->time, &result); - TimeReturnCallbackPromise(env, info, result); - napi_delete_async_work(env, asyncContext->work); - if (asyncContext) { - delete asyncContext; - asyncContext = nullptr; + if (asyncContext->isNano) { + asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeNs(); + } else { + asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeMs(); } }, - (void*)asyncContext, - &asyncContext->work); - NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work)); - if (asyncContext->isCallback) { - return TimeNapiGetNull(env); - } else { - return promise; - } -} - -napi_value JSSystemTimeGetRealActiveTimeNs(napi_env env, napi_callback_info info) -{ - size_t argc = SET_TIMEZONE_MAX_PARA; - napi_value argv[SET_TIMEZONE_MAX_PARA] = {0}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { - return TimeJSParaError(env, callback); - } - AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; - if (!asyncContext) { - return TimeJSParaError(env, callback); - } - napi_value promise = nullptr; - TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); - napi_value resource = nullptr; - napi_create_string_utf8(env, "JSSystemTimeGetRealActiveTimeNs", NAPI_AUTO_LENGTH, &resource); - napi_create_async_work(env, - nullptr, - resource, - [](napi_env env, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetMonotonicTimeNs(); - }, [](napi_env env, napi_status status, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; if (asyncContext->time < 0) { @@ -504,7 +425,8 @@ napi_value JSSystemTimeGetRealTime(napi_env env, napi_callback_info info) napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { + bool isNano = false; + if (ParseParametersGetNA(env, argv, argc, callback, &isNano) == nullptr) { return TimeJSParaError(env, callback); } AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; @@ -513,6 +435,7 @@ napi_value JSSystemTimeGetRealTime(napi_env env, napi_callback_info info) } napi_value promise = nullptr; TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); + asyncContext->isNano = isNano; napi_value resource = nullptr; napi_create_string_utf8(env, "JSSystemTimeGetRealTime", NAPI_AUTO_LENGTH, &resource); napi_create_async_work(env, @@ -520,62 +443,12 @@ napi_value JSSystemTimeGetRealTime(napi_env env, napi_callback_info info) resource, [](napi_env env, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeMs(); - }, - [](napi_env env, napi_status status, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - if (asyncContext->time < 0) { - asyncContext->errorCode = ERROR; - } - TimeCallbackPromiseInfo info; - info.isCallback = asyncContext->isCallback; - info.callback = asyncContext->callbackRef; - info.deferred = asyncContext->deferred; - info.errorCode = asyncContext->errorCode; - napi_value result = nullptr; - napi_create_int64(env, asyncContext->time, &result); - TimeReturnCallbackPromise(env, info, result); - napi_delete_async_work(env, asyncContext->work); - if (asyncContext) { - delete asyncContext; - asyncContext = nullptr; + if (asyncContext->isNano) { + asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeNs(); + } else { + asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeMs(); } }, - (void*)asyncContext, - &asyncContext->work); - NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work)); - if (asyncContext->isCallback) { - return TimeNapiGetNull(env); - } else { - return promise; - } -} - -napi_value JSSystemTimeGetRealTimeNs(napi_env env, napi_callback_info info) -{ - size_t argc = SET_TIMEZONE_MAX_PARA; - napi_value argv[SET_TIMEZONE_MAX_PARA] = {0}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - napi_ref callback = nullptr; - if (ParseParametersGet(env, argv, argc, callback) == nullptr) { - return TimeJSParaError(env, callback); - } - AsyncContext* asyncContext = new (std::nothrow)AsyncContext {.env = env}; - if (!asyncContext) { - return TimeJSParaError(env, callback); - } - napi_value promise = nullptr; - TimePaddingAsyncCallbackInfo(env, asyncContext, callback, promise); - napi_value resource = nullptr; - napi_create_string_utf8(env, "JSSystemTimeGetRealTimeNs", NAPI_AUTO_LENGTH, &resource); - napi_create_async_work(env, - nullptr, - resource, - [](napi_env env, void* data) { - AsyncContext* asyncContext = (AsyncContext*)data; - asyncContext->time = TimeServiceClient::GetInstance()->GetBootTimeNs(); - }, [](napi_env env, napi_status status, void* data) { AsyncContext* asyncContext = (AsyncContext*)data; if (asyncContext->time < 0) { @@ -726,11 +599,8 @@ napi_value SystemTimeExport(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("setDate", JSSystemTimeSetTime), DECLARE_NAPI_FUNCTION("setTimezone", JSSystemTimeSetTimeZone), DECLARE_NAPI_FUNCTION("getCurrentTime", JSSystemTimeGetCurrentTime), - DECLARE_NAPI_FUNCTION("getCurrentTimeNs", JSSystemTimeGetCurrentTimeNs), DECLARE_NAPI_FUNCTION("getRealActiveTime", JSSystemTimeGetRealActiveTime), - DECLARE_NAPI_FUNCTION("getRealActiveTimeNs", JSSystemTimeGetRealActiveTimeNs), DECLARE_NAPI_FUNCTION("getRealTime", JSSystemTimeGetRealTime), - DECLARE_NAPI_FUNCTION("getRealTimeNs", JSSystemTimeGetRealTimeNs), DECLARE_NAPI_FUNCTION("getDate", JSSystemTimeGetDate), DECLARE_NAPI_FUNCTION("getTimezone", JSSystemTimeGetTimeZone), }; diff --git a/services/time_manager/include/ntp_trusted_time.h b/services/time_manager/include/ntp_trusted_time.h index 331cb8e3a5a19b52d41a39bc7dce3ffebe8e93aa..489dad16db13a7788a6c2ecde9b714cf82a3527c 100644 --- a/services/time_manager/include/ntp_trusted_time.h +++ b/services/time_manager/include/ntp_trusted_time.h @@ -48,6 +48,7 @@ public: int64_t GetCertaintyMillis(); int64_t CurrentTimeMillis(); int64_t GetAgeMillis(); + void Clear(); private: int64_t mTimeMillis; int64_t mElapsedRealtimeMillis; diff --git a/services/time_manager/include/sntp_client.h b/services/time_manager/include/sntp_client.h index d9c3517fbf0119cc3c69234d1c216ec52494be62..2ecbddb9da62f4419b14395bf1799ae68b076187 100644 --- a/services/time_manager/include/sntp_client.h +++ b/services/time_manager/include/sntp_client.h @@ -144,18 +144,11 @@ private: * @param _ntpTs the NTP timestamp to be converted * Returns the milliseconds */ - uint64_t ConvertNtpToStamp(uint64_t _ntpTs); + int64_t ConvertNtpToStamp(uint64_t _ntpTs); - /** - * This function converts the NTP time to local time - * - * @param _ntpTs the NTP timestamp to be converted - * @param _outDataTs the structure Date where the [HH, MM, SS, MMMMMM] are stored - */ - uint64_t ConvertNtpToDate(uint64_t _ntpTs, struct date_structure* _outDataTs); - int m_clockOffset; - int64_t m_originateTimestamp; + int64_t m_clockOffset; + uint64_t m_originateTimestamp; int64_t mNtpTime; int64_t mNtpTimeReference; int64_t mRoundTripTime; diff --git a/services/time_manager/src/ntp_trusted_time.cpp b/services/time_manager/src/ntp_trusted_time.cpp index 6dd59895cc7eb7863a02bcc19f566ddec13d8869..c927bd8003618df46be6cb66ec6b7bb91fc71f14 100644 --- a/services/time_manager/src/ntp_trusted_time.cpp +++ b/services/time_manager/src/ntp_trusted_time.cpp @@ -14,6 +14,11 @@ */ #include +#include +#include +#include +#include +#include #include "time_common.h" #include "sntp_client.h" #include "ntp_trusted_time.h" @@ -31,6 +36,9 @@ bool NtpTrustedTime::ForceRefresh(std::string ntpServer) { SNTPClient client; if (client.RequestTime(ntpServer)) { + if (mTimeResult != nullptr) { + mTimeResult->Clear(); + } int64_t ntpCertainty = client.getRoundTripTime() / 2; mTimeResult = std::make_shared(client.getNtpTIme(), client.getNtpTimeReference(), ntpCertainty); TIME_HILOGD(TIME_MODULE_SERVICE, "Get Ntp time result"); @@ -46,7 +54,7 @@ int64_t NtpTrustedTime::CurrentTimeMillis() TIME_HILOGD(TIME_MODULE_SERVICE, "Missing authoritative time source"); return INVALID_MILLIS; } - return mTimeResult->CurrentTimeMillis(); + return mTimeResult->GetTimeMillis(); } bool NtpTrustedTime::HasCache() @@ -109,5 +117,12 @@ NtpTrustedTime::TimeResult::TimeResult(int64_t mTimeMillis, int64_t mElapsedReal this->mElapsedRealtimeMillis = mElapsedRealtimeMills; this->mCertaintyMillis = mCertaintyMillis; } + +void NtpTrustedTime::TimeResult::Clear() +{ + TIME_HILOGD(TIME_MODULE_SERVICE, "start."); + (void)memset_s(this, sizeof(*this), 0, sizeof(*this)); + TIME_HILOGD(TIME_MODULE_SERVICE, "end."); +} } // MiscServices } // OHOS \ No newline at end of file diff --git a/services/time_manager/src/ntp_update_time.cpp b/services/time_manager/src/ntp_update_time.cpp index 28d5e3e10e31634fb0df5174e40c7aeccbc32120..03ba6ac6012ac01e73d1e6a3f3470a23b5bc6817 100644 --- a/services/time_manager/src/ntp_update_time.cpp +++ b/services/time_manager/src/ntp_update_time.cpp @@ -132,6 +132,10 @@ void NtpUpdateTime::SetSystemTime() TIME_HILOGD(TIME_MODULE_SERVICE, "Ntp update time failed"); return; } + if (currentTime <= 0) { + TIME_HILOGD(TIME_MODULE_SERVICE, "current time invalid."); + return; + } TimeService::GetInstance()->SetTime(currentTime); autoTimeInfo_.lastUpdateTime = currentTime; TIME_HILOGD(TIME_MODULE_SERVICE, "Ntp update currentTime: %{public}" PRId64 "", currentTime); diff --git a/services/time_manager/src/sntp_client.cpp b/services/time_manager/src/sntp_client.cpp index cf2b23622aea4caeca5d481667a7d0d53c032ef3..0025609e1b4a5994706862ebce8240729e474715 100644 --- a/services/time_manager/src/sntp_client.cpp +++ b/services/time_manager/src/sntp_client.cpp @@ -33,7 +33,6 @@ namespace OHOS { namespace MiscServices { namespace { constexpr auto SECONDS_SINCE_FIRST_EPOCH = (2208988800UL); // Seconds from 1/1/1900 00.00 to 1/1/1970 00.00; - constexpr uint64_t MICRO_TO_MILESECOND = 1000; constexpr uint64_t MILLISECOND_TO_SECOND = 1000; constexpr uint64_t FRACTION_TO_SECOND = 0x100000000; constexpr uint64_t UINT32_MASK = 0xFFFFFFFF; @@ -45,7 +44,7 @@ namespace { constexpr int INDEX_TWO = 2; constexpr int INDEX_THREE = 3; constexpr int INDEX_FOUR = 4; - constexpr int INDEX_SIX = 6; + constexpr int TIME_OUT = 5; constexpr unsigned char MODE_THREE = 3; constexpr unsigned char VERSION_THREE = 3; constexpr double TEN_TO_MINUS_SIX_POWER = 1.0e-6; @@ -61,9 +60,6 @@ namespace { constexpr int NTP_PACKAGE_SIZE = 48; constexpr int SNTP_MSG_OFFSET_SIX = 6; constexpr int SNTP_MSG_OFFSET_THREE = 3; - constexpr int SECOND_OF_DAY = 86400; - constexpr int SECOND_OF_HOUR = 3600; - constexpr int SECOND_OF_MINUTE = 60; } SNTPClient::SNTPClient() {} SNTPClient::~SNTPClient() {} @@ -82,24 +78,20 @@ bool SNTPClient::RequestTime(std::string host) return false; } + // Set send and recv function timeout + struct timeval timeout = {TIME_OUT, 0}; + setsockopt(SendSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(struct timeval)); + setsockopt(SendSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval)); + struct hostent* hostV; if ((hostV = gethostbyname(host.c_str())) == nullptr) { // More descriptive error message TIME_HILOGE(TIME_MODULE_SERVICE, "Get host by name %{public}s but get nullptr.", host.c_str()); return false; } - - errno_t ret = memset_s((char*)& RecvAddr, sizeof(RecvAddr), 0, sizeof(RecvAddr)); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret); - return false; - } + (void)memset_s((char*)& RecvAddr, sizeof(RecvAddr), 0, sizeof(RecvAddr)); RecvAddr.sin_family = AF_INET; - errno_t ret1 = memcpy_s((char*)& RecvAddr.sin_addr.s_addr, hostV->h_length, (char*)hostV->h_addr, hostV->h_length); - if (ret1 != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret1); - return false; - } + (void)memcpy_s((char*)& RecvAddr.sin_addr.s_addr, hostV->h_length, (char*)hostV->h_addr, hostV->h_length); RecvAddr.sin_port = htons(Port); if (connect(SendSocket, (struct sockaddr*) & RecvAddr, sizeof(RecvAddr)) < 0) { TIME_HILOGE(TIME_MODULE_SERVICE, "Connect socket failed with host: %{public}s", host.c_str()); @@ -144,11 +136,8 @@ uint64_t SNTPClient::GetNtpTimestamp64(int offset, char* buffer) { const int _len = sizeof(uint64_t); char valueRx[_len]; - errno_t ret = memset_s(valueRx, sizeof(uint64_t), 0, sizeof(uint64_t)); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret); - return false; - } + (void)memset_s(valueRx, sizeof(uint64_t), 0, sizeof(uint64_t)); + int numOfBit = sizeof(uint64_t) - 1; for (int loop = offset; loop < offset + _len; loop++) { valueRx[numOfBit] = buffer[loop]; @@ -156,12 +145,7 @@ uint64_t SNTPClient::GetNtpTimestamp64(int offset, char* buffer) } uint64_t milliseconds; - errno_t ret1 = memcpy_s(&milliseconds, sizeof(uint64_t), valueRx, sizeof(uint64_t)); - if (ret1 != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret1); - return false; - } - + (void)memcpy_s(&milliseconds, sizeof(uint64_t), valueRx, sizeof(uint64_t)); return milliseconds; } @@ -181,45 +165,9 @@ void SNTPClient::ConvertNtpToUnix(struct ntp_timestamp *ntpTs, struct timeval *u (uint32_t)((double)ntpTs->fraction * TEN_TO_SIX_POWER / (double)(1LL << RECEIVE_TIMESTAMP_OFFSET)); } -uint64_t SNTPClient::ConvertNtpToDate(uint64_t _ntpTs, struct date_structure *_outDataTs) -{ - uint32_t second = (uint32_t)((_ntpTs >> RECEIVE_TIMESTAMP_OFFSET) & UINT32_MASK); - uint32_t fraction = (uint32_t)(_ntpTs & UINT32_MASK); - - struct timeval unix; - struct ntp_timestamp ntpTs; - ntpTs.second = second; - ntpTs.fraction = fraction; - - ConvertNtpToUnix(&ntpTs, &unix); - _outDataTs->hour = (unix.tv_sec % SECOND_OF_DAY) / SECOND_OF_HOUR; - _outDataTs->minute = (unix.tv_sec % SECOND_OF_HOUR) / SECOND_OF_MINUTE; - _outDataTs->second = (unix.tv_sec % SECOND_OF_MINUTE); - _outDataTs->millisecond = unix.tv_usec; - - std::ostringstream _ss; - _ss << std::internal - << std::setfill('0') - << std::setw(INDEX_TWO) - << _outDataTs->hour - << std::internal - << std::setfill('0') - << std::setw(INDEX_TWO) - << _outDataTs->minute - << std::internal - << std::setfill('0') - << std::setw(INDEX_TWO) << _outDataTs->second - << std::internal - << std::setfill('0') - << std::setw(INDEX_SIX) - << _outDataTs->millisecond; - - std::string _s = _ss.str(); - return (stoull(_s)); -} - /* - * /// SNTP Timestamp Format (as described in RFC 2030) +/* + * /// SNTP Timestamp Format (as described in RFC 2030) * 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -228,7 +176,7 @@ uint64_t SNTPClient::ConvertNtpToDate(uint64_t _ntpTs, struct date_structure *_o * | Seconds Fraction (0-padded) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ -uint64_t SNTPClient::ConvertNtpToStamp(uint64_t _ntpTs) +int64_t SNTPClient::ConvertNtpToStamp(uint64_t _ntpTs) { uint32_t second = (uint32_t)((_ntpTs >> RECEIVE_TIMESTAMP_OFFSET) & UINT32_MASK); uint32_t fraction = (uint32_t)(_ntpTs & UINT32_MASK); @@ -261,11 +209,8 @@ void SNTPClient::CreateMessage(char* buffer) // optional (?) _sntpMsg._originateTimestamp = _ntpTs; char value[sizeof(uint64_t)]; - errno_t ret = memcpy_s(value, sizeof(uint64_t), &_sntpMsg._originateTimestamp, sizeof(uint64_t)); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret); - return; - } + (void)memcpy_s(value, sizeof(uint64_t), &_sntpMsg._originateTimestamp, sizeof(uint64_t)); + int numOfBit = sizeof(uint64_t) - 1; int ofssetEnd = ORIGINATE_TIMESTAMP_OFFSET + sizeof(uint64_t); for (int loop = ORIGINATE_TIMESTAMP_OFFSET; loop < ofssetEnd; loop++) { @@ -291,11 +236,8 @@ void SNTPClient::WriteTimeStamp(char* buffer, ntp_timestamp *ntp) _sntpMsg._mode = MODE_THREE; _sntpMsg._originateTimestamp = _ntpTs; char value[sizeof(uint64_t)]; - errno_t ret = memcpy_s(value, sizeof(uint64_t), &_sntpMsg._originateTimestamp, sizeof(uint64_t)); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret); - return; - } + (void)memcpy_s(value, sizeof(uint64_t), &_sntpMsg._originateTimestamp, sizeof(uint64_t)); + int numOfBit = sizeof(uint64_t) - 1; int ofssetEnd = ORIGINATE_TIMESTAMP_OFFSET + sizeof(uint64_t); for (int loop = ORIGINATE_TIMESTAMP_OFFSET; loop < ofssetEnd; loop++) { @@ -343,16 +285,13 @@ void SNTPClient::ReceivedMessage(char* buffer) _tempOriginate = _sntpMsg._originateTimestamp; } - struct date_structure dataTs; - uint64_t _originClient = ConvertNtpToDate(_tempOriginate, &dataTs); - uint64_t _receiveServer = ConvertNtpToDate(_sntpMsg._receiveTimestamp, &dataTs); - uint64_t _transmitServer = ConvertNtpToDate(_sntpMsg._transmitTimestamp, &dataTs); - uint64_t _receiveClient = ConvertNtpToDate(_ntpTs, &dataTs); + int64_t _originClient = ConvertNtpToStamp(_tempOriginate); + int64_t _receiveServer = ConvertNtpToStamp(_sntpMsg._receiveTimestamp); + int64_t _transmitServer = ConvertNtpToStamp(_sntpMsg._transmitTimestamp); + int64_t _receiveClient = ConvertNtpToStamp(_ntpTs); - int _clockOffset = (((_receiveServer - _originClient) + (_transmitServer - _receiveClient)) / INDEX_TWO); - _clockOffset = _clockOffset / MICRO_TO_MILESECOND; - int _roundTripDelay = (_receiveClient - _originClient) - (_receiveServer - _transmitServer); - _roundTripDelay = _roundTripDelay / MICRO_TO_MILESECOND; + int64_t _clockOffset = (((_receiveServer - _originClient) + (_transmitServer - _receiveClient)) / INDEX_TWO); + int64_t _roundTripDelay = (_receiveClient - _originClient) - (_transmitServer - _receiveServer); mRoundTripTime = _roundTripDelay; mNtpTime = ConvertNtpToStamp(_ntpTs) + _clockOffset; mNtpTimeReference = std::chrono::duration_cast @@ -364,11 +303,8 @@ unsigned int SNTPClient::GetNtpField32(int offset, char* buffer) { const int _len = sizeof(int); char valueRx[_len]; - errno_t ret = memset_s(valueRx, _len, 0, _len); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", ret); - return false; - } + (void)memset_s(valueRx, _len, 0, _len); + int numOfBit = sizeof(int) - 1; for (int loop = offset; loop < offset + _len; loop++) { valueRx[numOfBit] = buffer[loop]; @@ -376,12 +312,8 @@ unsigned int SNTPClient::GetNtpField32(int offset, char* buffer) } unsigned int milliseconds; - errno_t retValue = memcpy_s(&milliseconds, sizeof(int), valueRx, sizeof(int)); - if (retValue != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %d\n", retValue); - milliseconds = 0; - return milliseconds; - } + (void)memcpy_s(&milliseconds, sizeof(int), valueRx, sizeof(int)); + TIME_HILOGD(TIME_MODULE_SERVICE, "end."); return milliseconds; } @@ -397,10 +329,9 @@ void SNTPClient::GetReferenceId(int offset, char* buffer, int* _outArray) void SNTPClient::SNTPMessage::clear() { - errno_t ret = memset_s(this, sizeof(*this), 0, sizeof(*this)); - if (ret != EOK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed."); - } + TIME_HILOGD(TIME_MODULE_SERVICE, "start."); + (void)memset_s(this, sizeof(*this), 0, sizeof(*this)); + TIME_HILOGD(TIME_MODULE_SERVICE, "end."); } int64_t SNTPClient::getNtpTIme() diff --git a/services/time_manager/test/unittest/src/time_service_test.cpp b/services/time_manager/test/unittest/src/time_service_test.cpp index d54950457a59fdba38d06f77fcb035a9fef20269..991d1fdee0771e3ffde87867674a1469ef34dc11 100644 --- a/services/time_manager/test/unittest/src/time_service_test.cpp +++ b/services/time_manager/test/unittest/src/time_service_test.cpp @@ -319,9 +319,11 @@ HWTEST_F(TimeServiceTest, NetworkTime001, TestSize.Level0) auto UTCTimeMicro1 = system_clock::now().time_since_epoch().count(); auto UTCTimeMillis = (UTCTimeMicro1 / 1000) + 86400000; TimeServiceClient::GetInstance()->SetTime(UTCTimeMillis); + auto UTCTimeMicro2 = system_clock::now().time_since_epoch().count(); + TimeServiceClient::GetInstance()->NetworkTimeStatusOff(); TimeServiceClient::GetInstance()->NetworkTimeStatusOn(); sleep(5); - auto UTCTimeMicro2 = system_clock::now().time_since_epoch().count(); - EXPECT_TRUE(UTCTimeMicro2 < UTCTimeMicro1); + auto UTCTimeMicro3 = system_clock::now().time_since_epoch().count(); + EXPECT_TRUE(UTCTimeMicro3 < UTCTimeMicro2); TimeServiceClient::GetInstance()->NetworkTimeStatusOff(); }