From 020108a9bc6cb903468a05b63aff832d69962fc2 Mon Sep 17 00:00:00 2001 From: guduhanyan Date: Sun, 20 Feb 2022 23:12:30 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E6=97=B6=E9=97=B4=E6=88=B3=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guduhanyan --- .../time_manager/include/ntp_trusted_time.h | 1 + services/time_manager/include/sntp_client.h | 6 +- .../time_manager/src/ntp_trusted_time.cpp | 17 +++- services/time_manager/src/ntp_update_time.cpp | 4 + services/time_manager/src/sntp_client.cpp | 87 +++++++------------ .../test/unittest/src/time_service_test.cpp | 6 +- 6 files changed, 57 insertions(+), 64 deletions(-) diff --git a/services/time_manager/include/ntp_trusted_time.h b/services/time_manager/include/ntp_trusted_time.h index 331cb8e3..489dad16 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 d9c3517f..d4bc6a16 100644 --- a/services/time_manager/include/sntp_client.h +++ b/services/time_manager/include/sntp_client.h @@ -144,7 +144,7 @@ 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 @@ -154,8 +154,8 @@ private: */ 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 6dd59895..c927bd80 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 28d5e3e1..89bb1299 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 cf2b2362..157cac71 100644 --- a/services/time_manager/src/sntp_client.cpp +++ b/services/time_manager/src/sntp_client.cpp @@ -33,12 +33,12 @@ 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; const int VERSION_MASK = 0x38; const int MODE_MASK = 0x7; + constexpr int TIME_OUT = 5; constexpr int INVALID_RETURN = -1; constexpr int INDEX_ZERO = 0; constexpr int INDEX_ONE = 1; @@ -82,24 +82,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 +140,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 +149,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; } @@ -228,7 +216,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 +249,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 +276,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 +325,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 +343,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 +352,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 +369,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 d5495045..991d1fde 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(); } -- Gitee From 73bda27a1caf546376e75b219037f45069508ca0 Mon Sep 17 00:00:00 2001 From: guduhanyan Date: Mon, 21 Feb 2022 00:11:16 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E6=97=B6=E9=97=B4=E6=88=B3=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=9C=BA=E5=88=B6=E4=B9=8B=E6=A0=BC=E5=BC=8F=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guduhanyan --- services/time_manager/src/ntp_update_time.cpp | 4 ++-- services/time_manager/src/sntp_client.cpp | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/time_manager/src/ntp_update_time.cpp b/services/time_manager/src/ntp_update_time.cpp index 89bb1299..03ba6ac6 100644 --- a/services/time_manager/src/ntp_update_time.cpp +++ b/services/time_manager/src/ntp_update_time.cpp @@ -132,9 +132,9 @@ void NtpUpdateTime::SetSystemTime() TIME_HILOGD(TIME_MODULE_SERVICE, "Ntp update time failed"); return; } - if (currentTime <= 0 ) { + if (currentTime <= 0) { TIME_HILOGD(TIME_MODULE_SERVICE, "current time invalid."); - return; + return; } TimeService::GetInstance()->SetTime(currentTime); autoTimeInfo_.lastUpdateTime = currentTime; diff --git a/services/time_manager/src/sntp_client.cpp b/services/time_manager/src/sntp_client.cpp index 157cac71..cdd56a2c 100644 --- a/services/time_manager/src/sntp_client.cpp +++ b/services/time_manager/src/sntp_client.cpp @@ -83,9 +83,9 @@ bool SNTPClient::RequestTime(std::string host) } // 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 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) { -- Gitee From 4d5606736185ee582832f8e59da31bcc0f017c6a Mon Sep 17 00:00:00 2001 From: guduhanyan Date: Mon, 21 Feb 2022 00:48:39 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E6=97=B6=E9=97=B4=E6=88=B3=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=9C=BA=E5=88=B6=E4=B9=8B=E5=A4=B4=E6=96=87=E4=BB=B6=E5=BC=95?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guduhanyan --- services/time_manager/src/sntp_client.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/time_manager/src/sntp_client.cpp b/services/time_manager/src/sntp_client.cpp index cdd56a2c..c778e6f0 100644 --- a/services/time_manager/src/sntp_client.cpp +++ b/services/time_manager/src/sntp_client.cpp @@ -84,8 +84,8 @@ bool SNTPClient::RequestTime(std::string host) // 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)); + 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) { -- Gitee From 4055d9657a1c101eb4fb8f8b0f60313f058477e6 Mon Sep 17 00:00:00 2001 From: guduhanyan Date: Tue, 1 Mar 2022 23:49:44 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E5=90=88=E5=B9=B6=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E8=8E=B7=E5=8F=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guduhanyan --- .../js/declaration/api/@ohos.systemTime.d.ts | 33 +-- .../napi/system_time/include/js_systemtime.h | 1 + .../js/napi/system_time/src/js_systemtime.cpp | 206 ++++-------------- services/time_manager/include/sntp_client.h | 7 - services/time_manager/src/sntp_client.cpp | 46 +--- 5 files changed, 48 insertions(+), 245 deletions(-) diff --git a/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts b/interfaces/kits/js/declaration/api/@ohos.systemTime.d.ts index 9071438b..43eb6e9d 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 b9dbb4f7..7aac34c4 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 1438a9cd..95cfc976 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/sntp_client.h b/services/time_manager/include/sntp_client.h index d4bc6a16..2ecbddb9 100644 --- a/services/time_manager/include/sntp_client.h +++ b/services/time_manager/include/sntp_client.h @@ -146,13 +146,6 @@ private: */ 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); int64_t m_clockOffset; uint64_t m_originateTimestamp; diff --git a/services/time_manager/src/sntp_client.cpp b/services/time_manager/src/sntp_client.cpp index c778e6f0..0025609e 100644 --- a/services/time_manager/src/sntp_client.cpp +++ b/services/time_manager/src/sntp_client.cpp @@ -38,14 +38,13 @@ namespace { constexpr uint64_t UINT32_MASK = 0xFFFFFFFF; const int VERSION_MASK = 0x38; const int MODE_MASK = 0x7; - constexpr int TIME_OUT = 5; constexpr int INVALID_RETURN = -1; constexpr int INDEX_ZERO = 0; constexpr int INDEX_ONE = 1; 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() {} @@ -169,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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -- Gitee