A time source switching time processing method, system and medium

CN122984306APending Publication Date: 2026-10-27CYG SUNRI CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611316196.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-27
Publication Date
2026-10-27

AI Technical Summary

Technical Problem

[0004]本申请实施例提供了一种时源切换对时处理方法、系统及介质,可以解决现有电力嵌入式装置的时源切换对时处理方法中,在硬件对时时源与网络对时时源相互切换时存在切换延迟长、切换响应速度不足的问题

Benefits of technology

本申请实施例提供一种时源切换对时处理方法,包括:响应于电力嵌入式装置开机启动,控制硬件对时模块获取硬件授时信号状态,以及,控制网络对时模块创建用户数据报套接字UDP socket,并建立与时间服务器的网络连接。若硬件授时信号状态为有效状态,则控制硬件对时模块对电力嵌入式装置的系统时钟执行硬件校时处理,并保持UDP socket处于开启状态,其中,硬件校时处理为基于硬件对时模块解析得到的硬件授时信号,修正系统时钟。若硬件授时信号状态为失效状态,则控制网络对时模块通过UDP socket对系统时钟执行网络校时处理,其中,网络校时处理为基于经由UDP socket与时间服务器交互所获取的网络授时信号,修正系统时钟。其中,硬件校时处理的时间同步精度高于网络校时处理的时间同步精度。该方法在硬件授时信号有效时优先采用精度更高的硬件校时处理对系统时钟进行修正,同时保持UDP socket处于开启就绪状态,在硬件授时信号失效时可直接复用已创建的UDP socket快速执行网络校时处理,避免硬件授时信号失效后再创建套接字、建立网络连接带来的切换时延,实现主备时源的快速无缝降级切换,提升切换响应速度。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122984306A_ABST
    Figure CN122984306A_ABST
Patent Text Reader

Abstract

The application is suitable for the technical field of power systems, and provides a time source switching time processing method, system and medium, the method comprising: in response to the power embedded device starting up, controlling a hardware time synchronization module to acquire a hardware time signal state, and controlling a network time synchronization module to create a user datagram socket (UDP socket) and establish a network connection with a time server. If the hardware time signal state is a valid state, the hardware time synchronization module is controlled to perform hardware time correction processing on the system clock of the power embedded device, and the UDP socket is kept in an open state. If the hardware time signal state is an invalid state, the network time synchronization module is controlled to perform network time correction processing on the system clock through the UDP socket. The method avoids the switching delay caused by creating a socket and establishing a network connection again after the hardware time signal fails, and improves the switching response speed.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application belongs to the field of power system technology, and in particular relates to a time source switching time synchronization processing method, system and medium. Background Technology

[0002] Currently, embedded power devices (such as relay protection and waveform recording network devices) are often equipped with two heterogeneous time sources: IRIG-B hardware time synchronization (Inter-Range Instrumentation Group-B time code) and SNTP network time synchronization (Simple Network Time Protocol). IRIG-B hardware time synchronization is the high-precision primary time source, received by the station's time synchronization device via satellite antenna from GPS or BeiDou satellite signals to provide time synchronization to all devices within the station. SNTP network time synchronization is the backup time source, obtaining signals through a local area network NTP (Network Time Protocol) server. IRIG-B hardware time synchronization may be intermittently lost due to antenna obstruction, time synchronization device failure, electromagnetic interference, etc., requiring SNTP network time synchronization to take over when IRIG-B hardware time synchronization is lost.

[0003] However, in the existing time source switching and time synchronization processing methods of power embedded devices, from the loss of IRIG-B to the completion of SNTP time synchronization, it is necessary to go through the process of creating a socket → binding a port → sending a request → receiving a response, which can be delayed to the second level. However, power embedded devices require millisecond-level time accuracy. The second-level switching means that the system clock is not corrected for the first few seconds after the loss of IRIG-B, which has the defects of long switching delay and insufficient switching response speed. Summary of the Invention

[0004] This application provides a time source switching and time synchronization processing method, system, and medium, which can solve the problems of long switching delay and insufficient switching response speed in the existing time source switching and time synchronization processing methods of power embedded devices when switching between hardware time synchronization source and network time synchronization source.

[0005] In a first aspect, embodiments of this application provide a time source switching and time synchronization processing method, applied to a power embedded device, wherein the power embedded device runs a hardware time synchronization module and a network time synchronization module, and the method includes: In response to the power-embedded device powering on, the hardware time synchronization module is controlled to acquire the hardware time synchronization signal status, and the network time synchronization module is controlled to create a user datagram socket (UDP) and establish a network connection with the time server. If the hardware time synchronization signal is in a valid state, the hardware time synchronization module is controlled to perform hardware time synchronization processing on the system clock of the power embedded device, and the UDP socket is kept in an open state. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module. If the hardware time synchronization signal is in a failed state, the network time synchronization module is controlled to perform network time synchronization processing on the system clock through the UDP socket. The network time synchronization processing is based on the network time synchronization signal obtained by interacting with the time server via the UDP socket to correct the system clock. The time synchronization accuracy of the hardware time synchronization process is higher than that of the network time synchronization process.

[0006] In one possible implementation of the first aspect, the method includes: When the hardware timing signal status changes from an effective state to an ineffective state, and the first duration of the ineffective state is greater than the first preset hysteresis duration, it is determined that the first state change of the hardware timing signal status is effective, and the network timing module is controlled to perform network time synchronization processing on the system clock. When the hardware timing signal changes from a failed state to a valid state, and the second duration of the valid state is greater than the second preset hysteresis duration, the second state change of the hardware timing signal is determined to be valid, and the hardware timing module is controlled to perform hardware time synchronization processing on the system clock.

[0007] In one possible implementation of the first aspect, if the hardware timing signal is in a failed state, controlling the network time synchronization module to perform network time synchronization processing on the system clock via the UDP socket includes: The first network time measurement is performed by the network time synchronization module to obtain the first clock deviation. If the absolute value of the first clock deviation is less than the first threshold, then network time synchronization processing is performed on the system clock based on the first clock deviation. If the absolute value of the first clock deviation is greater than or equal to the first threshold, the network time synchronization module continues to perform network time measurements more than or equal to a preset number of times. The value obtained by arithmetic processing of the multiple clock deviations obtained from the multiple network time measurements is used as the adoption deviation, and network time synchronization processing is performed on the system clock based on the adoption deviation.

[0008] In one possible implementation of the first aspect, during the process of controlling the network time synchronization module to perform network time synchronization processing on the system clock via the UDP socket, the method further includes: Calculate the network round-trip delay measured at the current network time. If the network round-trip time exceeds a preset network quality threshold, the current clock deviation value obtained from the current network time measurement will be discarded.

[0009] In one possible implementation of the first aspect, during the process of controlling the network time synchronization module to perform network time synchronization processing on the system clock via the UDP socket, the method further includes: The network time synchronization module initiates time requests to multiple time servers in sequence according to a preset priority order. The multiple time servers are divided into at least two levels: a master level and a slave level. In each round of time synchronization, communication is attempted starting from the primary time server. If the primary time server does not respond effectively, communication is downgraded to access the secondary time server. If, during the current time synchronization process, after traversing all the multiple time servers within all levels, none of the multiple time servers provide a valid response, then the next round of server traversal and retry will be automatically initiated until the preset number of retry rounds is reached.

[0010] In one possible implementation of the first aspect, the method further includes: When both the hardware timing signal status and the network timing signal status are detected to be in a failed state, a de-shake timer is started, wherein the de-shake timer is set with a preset de-shake duration; the network timing signal status is detected by the network time synchronization module. During the timing of the anti-shake timer, if it is detected that the hardware timing signal status or the network timing signal status has been restored to a valid state, the anti-shake timer is reset and no service layer alarm is executed. If the anti-shake timer expires after the preset anti-shake duration, and both the hardware timing signal and the network timing signal are still in a failed state, then a service layer alarm will be executed.

[0011] In one possible implementation of the first aspect, the method further includes: When the system clock is detected to be in the leap second critical window, the network time synchronization module is controlled to suspend the network time synchronization process. The leap second critical window is a time interval pre-configured based on the leap second effective time.

[0012] In one possible implementation of the first aspect, the method further includes: After the initial network time synchronization is completed through the network time synchronization module, the synchronized system clock is written into the hardware real-time clock chip through the hardware clock write-back thread.

[0013] Secondly, embodiments of this application provide a time source switching time synchronization processing system, applied to a power embedded device, comprising: The hardware time synchronization module is used to respond to the power-embedded device power-on startup, obtain the hardware time synchronization signal status, and perform hardware time synchronization processing on the system clock of the power-embedded device when the hardware time synchronization signal status is valid. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module. A network time synchronization module is used to respond to the power-embedded device startup by creating a User Datagram Socket (UDP) and establishing a network connection with a time server; keeping the UDP socket open when the hardware time synchronization signal is valid; and performing network time synchronization processing on the system clock via the UDP socket when the hardware time synchronization signal is invalid. The network time synchronization processing corrects the system clock based on the network time synchronization signal obtained through interaction with the time server via the UDP socket. The time synchronization accuracy of the hardware time synchronization processing is higher than that of the network time synchronization processing.

[0014] Thirdly, embodiments of this application provide a terminal device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the time source switching time synchronization processing method described in any of the above claims.

[0015] Fourthly, embodiments of this application provide a computer-readable storage medium storing a computer program that, when executed by a processor, implements the time source switching time synchronization processing method described in any of the preceding claims.

[0016] Fifthly, embodiments of this application provide a computer program product that, when run on a terminal device, causes the terminal device to execute the time source switching and time synchronization processing method described in any one of the first aspects.

[0017] The beneficial effects of the embodiments in this application compared with the prior art are: This application provides a time source switching and time synchronization processing method, including: in response to the power-on startup of a power embedded device, controlling a hardware time synchronization module to acquire the hardware time synchronization signal status, and controlling a network time synchronization module to create a User Datagram Socket (UDP) and establish a network connection with a time server. If the hardware time synchronization signal status is valid, the hardware time synchronization module performs hardware time synchronization processing on the system clock of the power embedded device, and keeps the UDP socket open. The hardware time synchronization processing corrects the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module. If the hardware time synchronization signal status is invalid, the network time synchronization module performs network time synchronization processing on the system clock via the UDP socket. The network time synchronization processing corrects the system clock based on the network time synchronization signal obtained through interaction with the time server via the UDP socket. The time synchronization accuracy of the hardware time synchronization processing is higher than that of the network time synchronization processing. This method prioritizes using higher-precision hardware time synchronization processing to correct the system clock when the hardware time synchronization signal is valid, while keeping the UDP socket in an open and ready state. When the hardware time synchronization signal fails, the already created UDP socket can be directly reused to quickly perform network time synchronization processing, avoiding the switching latency caused by creating sockets and establishing network connections after the hardware time synchronization signal fails. This achieves fast and seamless degradation switching of primary and backup time sources and improves switching response speed. Attached Figure Description

[0018] To more clearly illustrate the technical solutions in the embodiments of this application, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0019] Figure 1 This is a flowchart illustrating a time source switching time synchronization processing method provided in an embodiment of this application; Figure 2 This is a schematic diagram of the structure of a time source switching time synchronization processing system provided in an embodiment of this application; Figure 3 This is a schematic diagram of the structure of a time source switching time synchronization processing system provided in an embodiment of this application; Figure 4 This is a schematic diagram of the structure of a terminal device provided in an embodiment of this application. Detailed Implementation

[0020] In the following description, specific details such as particular system architectures and techniques are set forth for illustrative purposes and not for limitation, in order to provide a thorough understanding of the embodiments of this application. However, those skilled in the art will understand that this application may also be implemented in other embodiments without these specific details. In other instances, detailed descriptions of well-known systems, apparatuses, circuits, and methods have been omitted so as not to obscure the description of this application with unnecessary detail.

[0021] It should be understood that, when used in this application specification and the appended claims, the term "comprising" indicates the presence of the described features, integrals, steps, operations, elements and / or components, but does not exclude the presence or addition of one or more other features, integrals, steps, operations, elements, components and / or a collection thereof.

[0022] It should also be understood that the term “and / or” as used in this application specification and the appended claims means any combination of one or more of the associated listed items and all possible combinations, and includes such combinations.

[0023] As used in this application specification and the appended claims, the term "if" may be interpreted, depending on the context, as "when," "once," "in response to determination," or "in response to detection." Similarly, the phrase "if determined" or "if detected [the described condition or event]" may be interpreted, depending on the context, as meaning "once determined," "in response to determination," "once detected [the described condition or event]," or "in response to detection [the described condition or event]."

[0024] Furthermore, in the description of this application and the appended claims, the terms "first," "second," "third," etc., are used only to distinguish descriptions and should not be construed as indicating or implying relative importance.

[0025] References to "one embodiment" or "some embodiments" as described in this specification mean that one or more embodiments of this application include a specific feature, structure, or characteristic described in connection with that embodiment. Therefore, the phrases "in one embodiment," "in some embodiments," "in other embodiments," "in still other embodiments," etc., appearing in different parts of this specification do not necessarily refer to the same embodiment, but rather mean "one or more, but not all, embodiments," unless otherwise specifically emphasized. The terms "comprising," "including," "having," and variations thereof mean "including but not limited to," unless otherwise specifically emphasized.

[0026] Power embedded devices (such as relay protection and waveform recording network substations) are often equipped with two heterogeneous time sources: IRIG-B hardware time synchronization (Inter-Range Instrumentation Group-B time code) and SNTP network time synchronization (Simple Network Time Protocol). IRIG-B hardware time synchronization is the high-precision primary time source, received by the station's time synchronization device via a satellite antenna from GPS or BeiDou satellites to provide time synchronization to all devices within the station. SNTP network time synchronization is the backup time source, obtaining signals through a local area network NTP (Network Time Protocol) server. IRIG-B hardware time synchronization may be intermittently lost due to antenna obstruction, time synchronization device failure, electromagnetic interference, etc., requiring SNTP network time synchronization to take over when IRIG-B hardware time synchronization is lost.

[0027] Currently, there are two main solutions in existing technologies: Option A (Dual Time Source Simultaneous Operation): Two time source channels synchronize independently at the same time. The disadvantage is that they may compete for the system clock write, and when IRIG-B hardware time synchronization is effective, SNTP network time synchronization is still consuming CPU and network bandwidth to make unnecessary requests.

[0028] Option B (on-demand start / stop): When IRIG-B hardware time synchronization is lost, SNTP network time synchronization is started, and when IRIG-B hardware time synchronization is restored, SNTP network time synchronization is shut down. This is the most intuitive approach, but it has the following drawbacks: (1) The socket() reconstruction is expensive and unreliable. socket() involves kernel protocol stack memory allocation and file descriptor allocation, and bind() involves global port number registration. In the actual code, ClientReset() presets 30 retries (50ms each time, totaling up to 1.5s), and socket() reconstruction itself is unreliable. When IRIG-B hardware time synchronization jitters frequently due to poor antenna contact, reconstruction is repeatedly triggered. (2) The switching delay is uncontrollable. From the loss of IRIG-B hardware time synchronization to the completion of SNTP network time synchronization, it is necessary to go through creating a socket → binding a port → sending a request → receiving a response, and the delay can reach the second level. Power embedded devices require millisecond-level time accuracy, and second-level switching means that the system clock is not corrected for the first few seconds after the loss of IRIG-B hardware time synchronization. (3) There is no anti-jitter for dual time source loss alarm. When both time sources are lost simultaneously, an alarm is immediately reported. However, the power field antenna is frequently blocked momentarily and the network is briefly congested, resulting in a large number of false alarms. (4) The measurement overhead is constant. Each time synchronization is either a single measurement (unreliable) or fixed multiple samplings (wasteful). During normal operation, the deviation of more than 99% is only a few milliseconds, and fixed multiple samplings are overly conservative.

[0029] Therefore, in view of the shortcomings of the prior art, this application aims to solve the following problems: (1) Time source switching delay problem: How to ensure that the SNTP thread does not consume network resources when IRIG-B is valid, and that when IRIG-B is lost, the switching delay is determined by the thread scheduling cycle (millisecond level) rather than by the process or thread restart level (second level), so that the switching delay is determined by the thread scheduling cycle and not by the resource reconstruction cycle.

[0030] (2) Measurement efficiency problem: How to adaptively adjust the subsequent measurement depth according to the deviation amplitude of the first measurement, that is, if the normal deviation is small, the single measurement is straight through, and if the abnormal deviation is large, multiple samplings are automatically added so that the measurement cost is proportional to the deviation risk.

[0031] (3) Alarm accuracy issue: How to make dual-source loss alarms based on duration rather than instantaneous state triggering, that is, no alarm when instantaneous simultaneous loss occurs, and only alarm when continuous loss exceeds a preset duration, so as to adapt to frequent instantaneous disturbances in the power field.

[0032] Please see Figure 1 , Figure 1 This is a flowchart illustrating a time source switching and time synchronization processing method according to an embodiment of this application. As an example and not a limitation, this method can be applied to or run in a power embedded device that includes a hardware time synchronization module and a network time synchronization module. The method includes: S11. In response to the power-embedded device powering on, control the hardware time synchronization module to obtain the hardware time synchronization signal status, and control the network time synchronization module to create a user datagram socket (UDP socket) and establish a network connection with the time server.

[0033] S12. If the hardware time synchronization signal is in a valid state, control the hardware time synchronization module to perform hardware time synchronization processing on the system clock of the power embedded device, and keep the UDP socket in an open state. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module.

[0034] S13. If the hardware time synchronization signal is in a failed state, the control network time synchronization module performs network time synchronization processing on the system clock through UDP socket. The network time synchronization processing corrects the system clock based on the network time synchronization signal obtained by interacting with the time server via UDP socket.

[0035] Among them, the time synchronization accuracy of hardware time synchronization is higher than that of network time synchronization.

[0036] It should be noted that power embedded devices refer to embedded hardware devices deployed in the field of power systems, such as protection devices, measurement and control devices, and intelligent terminals. These power embedded devices have embedded operating systems and are responsible for power data acquisition, fault diagnosis, and message transmission. They have extremely high requirements for system clock synchronization accuracy; clock errors can lead to power safety problems such as malfunctioning protection systems, disordered event timing, and invalid waveform timestamps.

[0037] A hardware time synchronization module refers to a hardware-level time synchronization receiver unit. It typically receives hardware time synchronization signals such as B-code, IRIG-B, and PPS pulses. This physical layer hardware reception provides high time synchronization accuracy, down to the microsecond level. This hardware time synchronization module can directly analyze external hardware time reference signals to complete device clock calibration.

[0038] A network time synchronization module refers to a software protocol time synchronization unit, typically implementing the NTP / SNTP network time protocol and relying on Ethernet packet exchange to obtain time. The time synchronization of this module is affected by network jitter and packet delay, and its accuracy is usually in the millisecond range.

[0039] Hardware timing signals refer to time reference signals input through an external physical interface, typically IRIG-B (B code) or 1PPS second pulses. These signals are output by BeiDou or GPS timing devices and connected to the power embedded device via a hardware cable. A valid hardware timing signal status means the hardware timing module can stably identify and resolve a legitimate and complete hardware timing signal. A failed hardware timing signal status refers to situations where the cable is disconnected, the timing source malfunctions, or the signal is distorted, preventing the hardware module from resolving a reliable time reference, such as no signal detected, signal loss, or abnormal signal distortion.

[0040] UDP sockets are user datagram sockets. The NTP / SNTP protocol standard uses UDP for transmission. It is connectionless, has high message sending and receiving efficiency, and is suitable for short message exchanges in time servers. It does not require establishing a long connection handshake, but it does not guarantee reliable message arrival.

[0041] A time server refers to a network time reference server that runs NTP / SNTP services. This time server is a local time server deployed within the power grid. The network time synchronization module requests time messages from this time server via Ethernet to obtain network time synchronization signals.

[0042] The network time synchronization signal is a timestamp message returned by the time server via UDP packets, which contains standard time information. The network time synchronization module obtains the network time reference after parsing the message.

[0043] The system clock is the system time maintained by the local operating system of the power embedded device. All event recordings, waveform recordings, alarms, and message timestamps in the power embedded device depend on this clock.

[0044] Hardware time synchronization can be understood as using the hardware time synchronization module to resolve the hardware time signal and directly correct the system clock of the embedded power device. In this hardware time synchronization process, the physical link transmission of the hardware signal has a fixed delay and high synchronization accuracy (microsecond level). Network time synchronization can be understood as obtaining the network timestamp through interaction with a time server via a UDP socket and correcting the system clock of the embedded power device at the software level. This network time synchronization process is affected by switch congestion and packet round-trip delay, resulting in uncertain delays and lower synchronization accuracy than hardware time synchronization (millisecond level).

[0045] Specifically, during the power-embedded device's power-on initialization phase, two parallel initialization actions are performed: First, the hardware time synchronization module acquires and detects external hardware time synchronization signals, and outputs the hardware time synchronization signal status (valid or invalid). Upon power-up, the hardware time synchronization module detects cables and signal waveforms to determine the availability of the external hardware time source. Simultaneously, the network time synchronization module creates a UDP socket, completing the network connection initialization with the time server and preparing for subsequent NTP time message transmission and reception. It should be understood that both time synchronization links are initialized simultaneously during the power-on phase, rather than waiting for hardware time synchronization to fail before creating the network socket. Pre-emptive network communication resources avoid the time-consuming process of creating a socket and establishing a network connection in the event of hardware time synchronization failure, thus reducing handover latency.

[0046] Then, upon determining that the hardware time synchronization signal is valid, the high-precision hardware time synchronization module is prioritized for hardware time synchronization processing. That is, the hardware time synchronization module parses the hardware time synchronization signal and uses the high-precision hardware time base correction device to correct the system clock, leveraging the microsecond-level high precision advantage of hardware time synchronization. During this time, the network UDP socket remains open and is not closed or destroyed. It should be understood that while the hardware time source is working normally, hardware time synchronization is the primary method of processing, but network time synchronization communication resources are not released, and the UDP socket remains continuously ready. If the hardware time synchronization signal suddenly fails, there is no need to recreate the UDP socket and re-establish the connection; the system can immediately switch to network time synchronization, reducing the latency of time source switching.

[0047] When the hardware timing signal fails, such as a broken hardware cable, a faulty external B code or BeiDou timing source, the hardware cannot obtain a reliable time reference. In this case, the control network timing module reuses the pre-created UDP socket, interacts with the time server to obtain the network timing signal, performs network time synchronization processing, and uses the time reference obtained from network parsing to correct the system clock.

[0048] In other words, the SNTP time synchronization thread runs continuously after the power-embedded device is powered on, and is neither destroyed nor rebuilt when the IRIG-B signal changes. When the IRIG-B signal is valid, the SNTP time synchronization thread skips the time synchronization processing of the current cycle (suppression), but the thread itself, UDP socket, and network configuration remain unchanged. When the IRIG-B signal is lost, the SNTP time synchronization thread immediately resumes time synchronization processing in the next scheduling cycle (approximately 3ms) without any initialization.

[0049] In this embodiment, the time source switching is an internal control flow branch switching (if-else) within the thread, rather than a thread lifecycle management operation (create / destroy).

[0050] In some examples, the corresponding implementation code for time source switching is as follows: / / Sntp_TaskMain() — The main thread for SNTP time synchronization (persistent, never exits) static int Sntp_TaskMain() { while(1) / / Infinite loop, thread is persistent, lifecycle = device runtime { if(FALSE == LibHard_GetIrigSynStatus()) { ClientMainProcess(); / / IRIG-B lost → Execute SNTP time synchronization } else { LibHard_SetNtpStatus(FALSE); / / IRIG-B enabled → only mark status, skip time synchronization / / Key point: close(socket) is not called here, the thread is not terminated, and no network resources are released. } taskDelay(3); / / Scheduling period is approximately 3ms, which determines the delay of IRIG-B status detection. } return 0; } Correspondingly, the existing on-demand start / stop scheme requires executing ClientReset() every time IRIG-B is lost (this operation is deliberately avoided in the time source switching time synchronization processing method provided in this application embodiment). The execution code of ClientReset() is as follows: / / ClientReset() static BOOLEAN ClientReset() { int tryLoop, tryCount = 30; pthread_mutex_lock(&g_mutexNTPClient); if (TimeForNTPClient.m_Socket>0) { close(TimeForNTPClient.m_Socket); / / Close the old socket TimeForNTPClient.m_Socket = -1; } / / Recreate the UDP socket, retrying up to 30 times. for(tryLoop = 0; tryLoop <tryCount; tryLoop++) { if ((TimeForNTPClient.m_Socket = socket(AF_INET, SOCK_DGRAM, 0))>0) break taskDelay(50); / / Wait 50ms for each failure. } if (TimeForNTPClient.m_Socket<0) return FALSE; / / If it still fails after 30 retries (maximum 1.5 seconds) / / Rebind address and port TimeForNTPClient.m_addr.sin_family = AF_INET; TimeForNTPClient.m_addr.sin_port = htons(g_tNTPClient.dwNetPort); bzero(&(TimeForNTPClient.m_addr.sin_zero), 8); pthread_mutex_unlock(&g_mutexNTPClient); return TRUE; }

[0051] The ClientReset() function described above includes close() → looping socket() (maximum 30 × 50ms = 1500ms) → address rebinding. In scenarios with frequent IRG-B signal jitter, the persistent suppression strategy in this application ensures that ClientReset() is executed zero times, and all switching is completed only between if-else branches.

[0052] As shown in Table 1, Table 1 is a quantitative comparison of the switching delay of the resident suppression strategy of this application and the on-demand start-stop strategy of the prior art.

[0053] Table 1. Quantitative comparison of the switching delay of the resident suppression strategy of this application and the on-demand start-stop strategy of the prior art.

[0054] As shown in Table 1, the core difference between the resident suppression strategy of this application and the on-demand start / stop strategy of existing technologies is not just how much faster it is, but the change in the nature of latency. The switching latency of the on-demand start / stop strategy is probabilistic (depending on the kernel state, file descriptor availability, and port remnants; in extreme cases, if all 30 retries of ClientReset() fail, switching will never occur), while the switching latency of the resident suppression strategy of this application is deterministic (constantly equal to the scheduling period + RTT). For industrial real-time systems requiring deterministic latency, the shift from probabilistic to deterministic latency is more critical than a reduction in absolute value.

[0055] It should be noted that the time synchronization accuracy of hardware time synchronization is greater than that of network time synchronization. When the hardware time source is available, hardware time synchronization is used first; when the hardware time source is unavailable, network time synchronization is used as a backup time source to ensure that the power embedded device does not lose time synchronization.

[0056] It is understood that this application provides a time source switching time synchronization processing method, which performs time signal status detection of the hardware time synchronization module and UDP socket creation and network connection initialization of the network time synchronization module in parallel during the power-embedded device startup phase. When the hardware time synchronization signal is valid, the system clock is corrected by using the more accurate hardware time synchronization processing first, while keeping the UDP socket in the open and ready state. When the hardware time synchronization signal fails, the already created UDP socket can be directly reused to quickly perform network time synchronization processing.

[0057] This approach fully leverages the high synchronization accuracy of hardware time synchronization to meet the stringent clock synchronization requirements of power equipment. Furthermore, it avoids the switching latency caused by recreating sockets and establishing network connections after hardware time synchronization signal failure, enabling rapid and seamless degradation switching between primary and backup time sources. Parallel initialization of dual time synchronization links shortens the total time required for device startup to complete time synchronization. In the event of a hardware time synchronization link failure, it automatically switches to network time synchronization, ensuring continuous and effective clock synchronization of the device system. This prevents issues such as clock synchronization failure, event timing errors, and abnormal waveform timestamps, improving the fault tolerance and reliability of power embedded devices under complex field conditions. Moreover, under normal hardware time synchronization conditions, it only maintains socket readiness without frequently initiating network time synchronization requests, effectively controlling network resource consumption and adapting to unattended substation application scenarios.

[0058] In one possible implementation, the method includes: When the hardware timing signal changes from an effective state to an ineffective state, and the first duration of the ineffective state is greater than the first preset hysteresis duration, the first state change of the hardware timing signal is determined to be effective, and the network timing module is controlled to perform network time synchronization processing on the system clock.

[0059] When the hardware timing signal changes from a failed state to a valid state, and the second duration of the valid state is greater than the second preset hysteresis duration, the second state change of the hardware timing signal is determined to be valid, and the hardware timing module is controlled to perform hardware time synchronization processing on the system clock.

[0060] The first duration can be understood as the time during which the hardware time synchronization signal continuously maintains the failed state after transitioning from an active state to a failed state. The first preset hysteresis duration is a pre-configured time threshold used to verify whether the signal failure is a genuine fault and to filter out brief, transient interference. The specific value of this first preset hysteresis duration can be configured according to the on-site operating conditions. The first state change being valid can be understood as, after hysteresis verification, confirming that the change from "active" to "failed" is a genuine steady-state fault, not a transient fluctuation caused by interference, allowing the switch to network time synchronization to proceed.

[0061] The second duration can be understood as the time during which the hardware time synchronization signal maintains its valid state after transitioning from a failed state back to a valid state. The second preset hysteresis duration is another pre-configured time threshold used to verify the stability of signal recovery and prevent a brief signal rebound before switching back to hardware time synchronization. The specific value of the second preset hysteresis duration can be configured according to the on-site operating conditions and can be the same as or different from the first preset hysteresis duration. In some examples, the first hysteresis duration ranges from 0.5 seconds to 30 seconds, and the second hysteresis duration ranges from 3 seconds to 120 seconds. The second state change being valid can be understood as, after hysteresis time verification, confirming that the change from "failure → validity" is a stable recovery and not an instantaneous signal rebound, allowing a switch back to hardware time synchronization.

[0062] In some examples, following the basic scheme described above, Snp_TaskMain() polls the hardware timing signal status (IRIG-B status) approximately every 3ms. If the signal becomes lost, Network Time Synchronization Processing (SNTP) is immediately activated; if it is restored, SNTP is immediately suppressed. When the IRIG-B signal is in a critical state (e.g., poor antenna contact causing the signal to repeatedly jump within milliseconds), SNTP will oscillate at high frequency between activation and suppression, frequently executing unnecessary ClientMainProcess() or even settimeofday(). As a preferred implementation, a handover hysteresis can be added to the IRIG-B signal validity determination, i.e.: (1) Delayed Confirmation of Loss: When the hardware time synchronization signal changes from an active state to an inactive state, it does not immediately switch to network time synchronization processing, but starts timing for the first duration. Only when the continuous time of the inactive state is greater than the first preset delay duration is the change of state determined to be real and valid, confirming a continuous failure of hardware time synchronization, and then controlling the network time synchronization module to perform network time synchronization processing. This is to filter out instantaneous signal loss caused by electromagnetic interference and contact jitter, and to prevent unnecessary time source switching from being triggered by short-term disturbances. For example, after the IRIG-B signal changes from active to inactive, the inactive state must continue for more than the first preset delay duration, such as 1 to 5 seconds, before it is considered to be truly lost and SNTP is activated.

[0063] (2) Recovery Confirmation Delay: When the hardware timing signal recovers from a failed state to a valid state, the hardware time synchronization process is not immediately switched back; instead, the second duration of timing begins. Only when the continuous duration of the valid state is greater than the second preset delay duration is the state change deemed genuine and valid, confirming that the hardware timing source has been stably recovered, and then the hardware time synchronization module is controlled to perform hardware time synchronization processing. This is to avoid repeated switching of the time source caused by repeated signal interruptions and brief rebounds. For example, after the IRIG-B signal recovers from a failed state to a valid state, this valid state must last for more than the second preset delay duration, such as 5 to 30 seconds, before it is considered to have been truly recovered and SNTP suppressed.

[0064] It should be understood that in this embodiment, a bidirectional hysteresis verification mechanism is introduced for the state transition of the hardware time synchronization signal. When the hardware time synchronization signal changes from valid to lost, the first duration of the lost state must be greater than the first preset hysteresis duration before the state change is deemed valid and the system switches to network time synchronization. When the hardware time synchronization signal recovers from lost to valid, the second duration of the valid state must be greater than the second preset hysteresis duration before the state change is deemed valid and the system switches back to hardware time synchronization. This can filter out non-fault disturbances such as electromagnetic interference in the power field, momentary signal interruptions caused by line contact jitter, and brief signal rebounds. It avoids frequent back-and-forth transitions between hardware and network time synchronization, reduces clock jumps and timestamp jitter caused by frequent system clock switching, improves the stability of time source switching, reduces the risk of erroneous switching caused by momentary interference, ensures the stable and continuous clock of the power embedded device system, and further improves the time synchronization reliability of the power embedded device under complex electromagnetic field conditions.

[0065] It should be understood that even if IRIG-B briefly recovers during the lost acknowledgment hysteresis period and is lost again, since the SNTP thread is resident and the socket remains bound, no additional resource operation overhead will be incurred. This further highlights the advantages of the resident architecture proposed in this application compared with the on-demand start-stop scheme in critical signal scenarios.

[0066] In one possible implementation, if the hardware time synchronization signal is in a failed state, the control network time synchronization module performs network time synchronization processing on the system clock via a UDP socket, including: The first network time measurement is performed through the network time synchronization module to obtain the first clock deviation.

[0067] If the absolute value of the first clock deviation is less than the first threshold, then network time synchronization processing is performed on the system clock based on the first clock deviation.

[0068] If the absolute value of the first clock deviation is greater than or equal to the first threshold, the network time synchronization module continues to perform network time measurements more than or equal to a preset number of times. The value obtained by arithmetic processing of the multiple clock deviations obtained from the multiple network time measurements is used as the adoption deviation, and network time synchronization processing is performed on the system clock based on the adoption deviation.

[0069] The first network time measurement can be understood as a single measurement process in which the network time synchronization module performs a complete time interaction with the time server via a UDP socket, calculating the deviation between the local system clock and the standard time of the time server. The first clock deviation can be understood as the difference between the local system clock and the standard time of the time server obtained in the first network time measurement. The first clock deviation can be positive or negative; a positive value indicates that the local clock is ahead of the standard time, and a negative value indicates that the local clock is behind the standard time.

[0070] The first threshold refers to the pre-configured absolute value threshold of the deviation, which is used to determine whether the clock deviation obtained from a single measurement is within a reasonable range, and to distinguish between normal small deviations and abnormally large deviations.

[0071] The preset number of measurements refers to the minimum number of times the network time measurement will be repeated beforehand. When a single clock deviation is too large, multiple measurements at least this preset number are required to eliminate random errors caused by a single network packet anomaly. Multiple clock deviations can be understood as the deviation values ​​between each set of local clock values ​​and the standard time, calculated separately from multiple network time measurements. In some examples, the first threshold can range from 10 milliseconds to 1000 milliseconds, and the preset number of measurements can be any number from 3 to 12.

[0072] The adoption deviation refers to the final effective deviation value output after arithmetic processing of multiple clock deviations. The network time synchronization actually uses this adoption deviation value to correct the system clock. Arithmetic processing can include operations such as filtering to calculate the mean, removing extreme values ​​and then averaging, to suppress random outliers.

[0073] Specifically, when performing network time synchronization after hardware time synchronization fails, instead of performing multiple samplings each time, a two-level progressive architecture is adopted: Level 1 (Probe Level): Performs a single network time measurement (SNTP measurement), where the network time synchronization module completes a time interaction with the time server via UDP socket, calculating the first clock deviation between the local system clock and the server's standard time. If the absolute value of the first clock deviation is less than a first threshold (e.g., ±100ms), it indicates that the network measurement result is reliable and the clock is in a good synchronized state. The first clock deviation is directly used to correct the system clock, completing network time synchronization. In this case, only one NTP request is consumed, eliminating the need for multiple repeated measurements and improving processing efficiency.

[0074] Level 2 (Confirmation Level): If the absolute value of the first clock deviation measured in the first measurement is greater than or equal to the first threshold, it indicates that this single measurement is likely affected by factors such as network jitter, sudden changes in packet delay, or packet anomalies, and the result is unreliable. In this case, instead of directly modifying the clock using the first clock deviation, the network time synchronization module is controlled to continue performing network time measurements at least a preset number of times (e.g., continuously collecting at least four deviations, with each sampling interval of 1 second), resulting in multiple sets of clock deviations. Then, arithmetic processing is performed on the multiple sets of deviations to obtain the adoption deviation (e.g., after removing the maximum and minimum values, the arithmetic mean is taken as the adoption deviation). Finally, network time synchronization processing is performed on the system clock based on this adoption deviation, which consumes five NTP requests.

[0075] It should be understood that in this embodiment, for small deviations, a single result is used directly to ensure response speed; for large deviations, a single result is considered unreliable, and multiple sampling is triggered for arithmetic processing to suppress time synchronization errors caused by occasional network anomalies. The goal is to cover the vast majority of time synchronization periods (>99%) with the low cost of a single measurement, while incurring the high cost of multiple measurements only for a few abnormal periods. This minimizes the expected value of measurement overhead, rather than simply focusing on accuracy or speed.

[0076] In this embodiment, the corresponding implementation code is as follows: Adaptive measurement logic in ClientMainProcess() if (ClientGetTimeDiffValue(&lTimeDiffUS, FALSE)) / / ① Perform a single "probe" measurement first. { if (lTimeDiffUS<(1000) 100))&&(lTimeDiffUS>(1000 -100))) { / / ② Deviation < ±100ms → Direct acceptance, no additional sampling required LibHard_SetNtpStatus(TRUE); Time_TimerBStart(..., g_tNTPClient.dwTimeforNTP, ...); / / Normal cycle } else { / / ③ Deviation ≥ ±100ms → Trigger N≥4 resampling and extreme value removal confirmation if (ClientConfirmTimeDiffValue(&lTimeDiffUS, 4)) { / / ④ Deviation after resampling and averaging → Enter tolerance judgment → Time calibration if (tolerance check passes) { settimeofday(&tTimeVal, NULL); ... } } else { / / ⑤ A network error occurred during resampling → Failed, will retry in 30 seconds. Time_TimerBStart(..., 30, ...); } } } / / ClientConfirmTimeDiffValue() — N resampling cycles, removing extreme values ​​and taking the average static BOOLEAN ClientConfirmTimeDiffValue(long long plTimeDiffUS, intnTimes) { long long lSum = 0, lMaxValue = 0, lMinValue = 0, lTempValue = 0; if (nTimes < 4) nTimes = 4; / / Minimum 4 times for (int i = 0; i <nTimes; i++) { if(!ClientGetTimeDiffValue(&lTempValue, FALSE)) return FALSE; / / Fail if any network error occurs. if (i == 0) { lMaxValue = lMinValue = lTempValue;} if (lTempValue>lMaxValue) lMaxValue = lTempValue; else if (lTempValue <lMinValue) lMinValue = lTempValue; lSum += lTempValue; usleep(1000000); / / 1-second sampling interval } lSum = lSum - lMaxValue - lMinValue; / / Remove the maximum and minimum values plTimeDiffUS = lSum / (nTimes - 2); / / Average the remainder return TRUE; }

[0077] It is understood that in this embodiment, when network time synchronization is performed due to the loss of hardware time synchronization signal, the first network time measurement is performed to obtain the first clock deviation. When the absolute value of the first clock deviation is less than the first threshold, network time synchronization is performed directly based on the first clock deviation. When the first clock deviation is greater than or equal to the first threshold, multiple network time measurements are performed at least a preset number of times. The multiple clock deviations are then arithmetically processed to obtain the adopted deviation before time synchronization is performed.

[0078] Thus, when the network is in good working condition and the clock deviation is small, time synchronization can be completed using a single measurement result, reducing the number of network interactions and improving the network time synchronization response speed. When network jitter, sudden changes in message delay, or other factors cause abnormally large deviations in a single measurement, multiple network time measurements are taken and arithmetic processing is performed to suppress the adverse effects of a single abnormal measurement sample. This avoids large clock corrections caused by a single network anomaly, which could lead to significant jumps in the system clock. This balances the real-time response of network time synchronization with the reliability of the synchronization results, reduces the risk of time jumps caused by network disturbances to the system clock of power embedded devices, and ensures the accuracy and reliability of timestamps for event recordings and fault waveforms.

[0079] In one possible implementation, during the process of the control network time synchronization module performing network time synchronization processing on the system clock via UDP socket, the method further includes: Calculate the network round-trip delay measured at the current network time.

[0080] If the network round-trip latency exceeds the preset network quality threshold, the current clock deviation value obtained from the current network time measurement will be discarded.

[0081] Network round-trip time (RTT) can be understood as the complete round-trip time from when the network time synchronization module sends a time request message to the time server and receives a response message from the time server. This RTT can include switch forwarding delay, message queuing delay, and transmission link delay, and is a core indicator characterizing the quality of the time synchronization link in an NTP / SNTP network.

[0082] The preset network quality threshold refers to a pre-configured latency threshold in the power embedded device, used to evaluate whether the link quality of the current network measurement is acceptable. When the network round-trip latency exceeds this threshold, it indicates that the jitter in the current packet transmission is too large, and the reliability of the measurement results is low. In this embodiment, the preset network quality threshold can be configured according to the on-site network conditions.

[0083] Because the NTP protocol assumes symmetry in the network round-trip path, this symmetry assumption no longer holds when the RTT (Round-Trip Time) is too large, leading to a sharp increase in the resulting clock offset error. RTT gating eliminates unreliable measurements in high-latency network environments, ensuring that any accepted deviation is supported by reliable network transmission quality. Therefore, in the two-stage measurement described above, each NTP request-response interaction implicitly includes an independent quality control step: RTT quality gating.

[0084] Specifically, before calculating the clock skew, the network round-trip delay measured at the current network time is first calculated based on the timestamp. ,in, The local timestamp for sending time synchronization request messages to the network time synchronization module. The timestamp of the time synchronization request message received by the time server. The timestamp for sending the response message to the time server. This is the local timestamp for the response message received by the network time synchronization module. The calculated network round-trip time (RTT) is compared with a preset network quality threshold. If the RTT exceeds the preset network quality threshold (e.g., 100ms), it indicates that there is severe queuing, network congestion, or transient disturbances in the message transmission. The clock deviation measured in this instance is not of reference value, so the measurement result is discarded. The current clock deviation value obtained in this instance is not included in subsequent deviation statistics, arithmetic averages, and system clock correction calculations, and the process waits for the next valid network time measurement sample.

[0085] It should be understood that the deviation calculation in network time synchronization is highly dependent on the stability of round-trip time. When the network round-trip time is too large, the parsed clock deviation will be distorted. Bad samples should be discarded directly to avoid contaminating the time synchronization calculation results with inferior samples.

[0086] In some examples, the implementation code for RTT quality gating is as follows: RTT gating in ClientGetTimeDiffValueByIP() lDlyUS = (lRecUS - lOriUS) + (lDesUS - lTraUS); / / Calculate RTT if ((lDlyUS>100000) || (lDlyUS<0)) / / RTT>100ms → Discard { return FALSE; }

[0087] It should be noted that this gating mechanism is independent of the probe-acknowledgment two-level architecture and applies to every original NTP measurement. That is, whether it is a single measurement at the probe level or multiple samplings at the acknowledgment level, it is subject to RTT gating constraints.

[0088] Understandably, in this embodiment, during the network time synchronization process, the corresponding network round-trip time is calculated for each network time measurement. When the network round-trip time exceeds a preset network quality threshold, the current clock deviation value obtained from that measurement is discarded. This achieves link quality screening of network measurement samples, filtering out invalid measurement samples with excessive round-trip time caused by network congestion, packet queuing, or link transient disturbances. This prevents distorted clock deviations from participating in clock correction calculations, and prevents inaccurate system clock correction and clock jumps caused by erroneous time synchronization inputs introduced by instantaneous network link deterioration. This improves the effectiveness of network time measurement samples, further enhances the reliability of network time synchronization results, and ensures the time accuracy of event recording, fault recording, and message timestamps in power embedded devices.

[0089] In one possible implementation, during the process of the control network time synchronization module performing network time synchronization processing on the system clock via UDP socket, the method further includes: The network time synchronization module sends time requests to multiple time servers in sequence according to a preset priority order. The multiple time servers are divided into at least two levels: a master level and a slave level.

[0090] In each round of time synchronization, communication is attempted starting from the primary time server. If the primary time server does not provide a valid response, communication is downgraded to accessing the secondary time server.

[0091] If, during the current time synchronization process, after traversing multiple time servers across all levels, none of the time servers provide a valid response, the next round of server traversal and retry will be automatically initiated until the preset number of retry rounds is reached.

[0092] Multiple time servers refer to multiple NTP / SNTP time servers deployed in the power intranet to provide network time sources for embedded power devices, including primary and backup server nodes. The preset priority order can be understood as a pre-configured time server access sorting rule, specifying the priority access order, with higher-level servers initiating time requests first.

[0093] The primary time server is the highest priority time synchronization server and the first choice for network time synchronization processing. It is generally the core time synchronization server within the site, and its time synchronization reliability is given top priority. The secondary time server is a backup time synchronization server with a lower priority than the primary time server. It is used as an alternative time synchronization source when the primary time server cannot respond normally.

[0094] Each round of time synchronization can be understood as a complete network time synchronization execution cycle, which is a process of trying to interact with each time server in order of priority and obtain valid time synchronization data.

[0095] No valid response can be understood as follows: after sending a UDP time request message to the time server, no response is received within a timeout period, the received message verification is incorrect, or the message time information is invalid. In such cases, the server cannot be used to complete time synchronization.

[0096] The preset retry rounds are the maximum number of time synchronization retries configured in advance. If none of the servers respond, the retry will not loop indefinitely; the current time synchronization attempt will terminate after reaching this number of rounds. The next round of server traversal retries involves resuming communication by sending time requests to each time server sequentially from the beginning, according to the preset priority order, if none of the previous rounds have responded.

[0097] Specifically, this logic is embedded in the network time synchronization process to implement a multi-level, multi-time server primary / backup round-robin access mechanism: First, the network time synchronization module initiates UDP time requests to multiple time servers, which are divided into master and slave levels, in a preset priority order. The master level time server has a higher priority than the slave level time server.

[0098] Then, within a single-round time synchronization process, the primary-level time server is accessed first to attempt to obtain the time synchronization message. If the primary-level time server times out or the message is abnormal, indicating no valid response, a fallback access is performed, and the secondary-level time server is accessed instead to attempt to obtain network time synchronization data. If, in the current round of time synchronization, all primary and secondary-level time servers have been traversed in sequence, and none of the servers have returned a valid response, and the current time synchronization process cannot obtain usable time synchronization data, then the next round of server traversal retry is automatically initiated, requesting each time server in order of priority. The above retry process cannot be executed indefinitely; it continues until the preset number of retry rounds is reached, at which point the retry stops, and the current network time synchronization attempt ends, to avoid an infinite loop.

[0099] It should be understood that in this embodiment, during the network time synchronization process, multiple time servers are divided into primary and secondary levels, and time requests are initiated sequentially according to a preset priority order. In each round of time synchronization, the primary level time server is tried first, and if the primary level does not respond effectively, the secondary level time server is accessed instead. When there is no effective response from all time servers in a single round of traversal, the next round of server traversal and retry is automatically started until the preset number of retry rounds is reached.

[0100] This enables hierarchical management of multiple time servers, prioritizing the use of the more reliable primary time server and automatically switching to the secondary server in case of primary server failure or network outage, preventing a single point of failure from causing complete network time synchronization failure. A multi-round traversal retry mechanism addresses transient anomalies such as momentary network disconnections and temporary packet loss, increasing the probability of obtaining valid time synchronization messages. Simultaneously, a preset retry round number constrains the number of retries, preventing infinite retries from continuously consuming CPU and network resources. This improves network time synchronization fault tolerance while controlling device resource consumption, further ensuring the availability of network time synchronization for power embedded devices in scenarios where hardware time synchronization is lost.

[0101] In one possible implementation, the method further includes: When both the hardware time synchronization signal and the network time synchronization signal are detected to be in a failed state, a de-shake timer is activated. This timer has a preset de-shake duration. The network time synchronization signal status is detected by the network time synchronization module.

[0102] If, during the timing of the debounce timer, the hardware timing signal or the network timing signal is detected to have returned to a valid state, the debounce timer is reset and no service layer alarm is executed.

[0103] If the anti-shake timer expires after the preset anti-shake duration, and both the hardware timing signal and the network timing signal are still in an invalid state, then a service layer alarm will be executed.

[0104] A de-jitter timer refers to a software timer internally configured in a power embedded device. It's used to de-jitter in scenarios where both time sources are simultaneously lost, filtering out brief disturbances caused by the instantaneous loss of both sources and preventing false alarms. The preset de-jitter duration is a pre-configured time threshold used to distinguish between instantaneous disturbances and genuine dual time source failures. In some examples, the preset de-jitter duration can range from 10 seconds to 600 seconds.

[0105] Resetting the debounce timer refers to clearing the timer's countdown value to zero, stopping the timer, and clearing the current fault countdown state. Business layer alarms can be understood as time synchronization anomaly alarms output to the upper-layer business logic. They can be used by power embedded devices to send alerts to the backend, local alarm lights, and event logs, notifying maintenance personnel that the device has lost its time synchronization source.

[0106] Because power systems experience numerous transient disturbances, such as antennas being briefly deflected by strong winds for a few seconds or network switches experiencing momentary congestion leading to timeouts of a few seconds, if an alarm is reported every time both time sources are briefly and simultaneously lost, the power embedded device will generate a large number of noisy alarms, making it impossible for maintenance personnel to distinguish between "true long-term time synchronization failures" and "transient disturbances." By setting a debounce window, most transient disturbances are filtered out, and alarms are only generated for persistent time synchronization failures.

[0107] Specifically, this embodiment addresses the extreme scenario where both hardware and network time synchronization sources are lost simultaneously by adding a de-jitter timer for alarm de-jittering, preventing false alarms due to momentary disturbances.

[0108] The system simultaneously monitors the status of both the hardware timing signal and the network timing signal output by the network timing module in real time. When both the hardware timing signal and the network timing signal are in a failed state, the anti-shake timer is activated, and the anti-shake timer begins timing according to the preset anti-shake duration (e.g., 60 seconds).

[0109] If, before the anti-shake timer expires, either the hardware timing signal or the network timing signal is detected to be back to valid, indicating that at least one timing source has returned to normal, the anti-shake timer is reset without triggering a service layer alarm. Even if there was a brief simultaneous loss of both sources, as long as they are restored within the anti-shake duration, no alarm will be reported.

[0110] If the anti-shake timer continues to count until the preset anti-shake duration expires, and the hardware timing signal remains in a failed state, and the network timing signal also remains in a failed state, it means that both timing sources have indeed been continuously failed; at this time, a service layer alarm is executed, and the fault of the complete loss of time synchronization sources is reported to the upper layer service.

[0111] In some examples, the corresponding implementation code for dual-source loss alarm debouncing is as follows: / / LibHard_Main() — Comprehensive monitoring of time source status (approximately 1 second cycle) tagTimerB tTimeBForTimeWarn; Time_TimerBStart(&tTimeBForTimeWarn, 60, ...); / / 60-second anti-shake timer while(TRUE) { IRIG_AdjustTime(); / / Update IRIG-B state bSntpState = pSynState->bSntpState; / / Read SNTP state bIrigState = pSynState->bIrigState; / / Read IRIIG-B state if (FALSE == bSntpState && FALSE == bIrigState) / / Both sources are lost simultaneously { if (TRUE == Time_TimerBCheck(&tTimeBForTimeWarn) / / 60 seconds of continuous data loss?) &&NULL != pSynState->asynTrigger) { pSynState->asynTrigger(NULL); / / Trigger an alarm in the business layer. Time_TimerBReset(&tTimeBForTimeWarn); / / Reset the timer } pSynState->bSynState = FALSE; Led_SetStatus(ENUM_LED_TIME, LED_ON); / / Panel indicator light: Alarm } else if(FALSE == bSntpState&&TRUE == bIrigState) { pSynState->bSynState = TRUE; / / IRIG-B is valid alone → Normal } else if(TRUE == bSntpState&&FALSE == bIrigState) { pSynState->bSynState = TRUE; / / SNTP is valid alone → Normal } else / / Both sources are effective { pSynState->bSynState = TRUE; } taskDelay(1000); / / 1-second monitoring cycle }

[0112] It is understood that in this embodiment, when both the hardware timing signal status and the network timing signal status are detected to be in a failed state, a stabilization timer with a preset stabilization duration is started. During the stabilization timer's countdown, if either the hardware timing signal status or the network timing signal status recovers to a valid state, the stabilization timer is reset and no service layer alarm is executed; a service layer alarm is only executed when the stabilization timer counts to the preset stabilization duration and both the hardware timing signal status and the network timing signal status are still in a failed state.

[0113] This enables alarm debouncing in scenarios where both time synchronization sources are simultaneously lost. It can filter out transient disturbances caused by the simultaneous loss of both sources due to electromagnetic interference, network jitter, and other factors, avoiding the generation of a large number of false alarms and reducing alarm interference in the operation and maintenance system. Service layer alarms are only output when it is confirmed that both time synchronization sources have suffered a continuous failure. This not only reflects the serious fault of the device completely losing its time synchronization source, but also reduces false alarms, improves the accuracy of alarm output of power embedded devices, and makes it easier for operation and maintenance personnel to identify real time synchronization faults.

[0114] In one possible implementation, the method further includes: When the system clock is detected to be in the leap second critical window, the control network time synchronization module suspends network time synchronization processing. The leap second critical window is a pre-configured time interval based on the leap second effective time.

[0115] It should be noted that the leap second critical window can be understood as a pre-configured time interval based on the leap second's effective time, generally a period before and after the leap second's effective time. A time jump occurs before and after the leap second occurs, and this leap second critical window is used to avoid clock instability caused by network time synchronization during the leap second transition period. The leap second's effective time refers to the moment when the International Standard Time (UTC) performs the leap second addition or subtraction, which involves a 1-second insertion or subtraction, causing timestamp jumps and potentially leading to anomalies in power device timing, waveform recording, and message timing. For example, the leap second critical window could be 7:59:50 to 8:00:10.

[0116] In this embodiment, the current system clock is continuously monitored to determine whether it has entered a pre-configured leap second critical window (the time interval before and after the leap second takes effect). Once the system clock is detected to be within the leap second critical window, the network time synchronization module is controlled to suspend network time synchronization processing.

[0117] Because the NTP server time jumps by one second before and after the leap second takes effect, performing network time synchronization during this time would cause abnormal jumps in the local system clock, leading to recording errors and disrupted event timing. Therefore, during the leap second critical window, network time requests, clock offset calculations, and system clock corrections are suspended. UDP socket resources are preserved, and only the time synchronization business logic is suspended. Network time synchronization is resumed after the leap second critical window ends. It should be noted that hardware time synchronization is not subject to this pause logic and can continue to function normally.

[0118] It should be understood that in this embodiment, when the system clock is detected to be in the leap second critical window pre-configured based on the leap second effective time, the network time synchronization module is controlled to suspend network time synchronization processing to avoid network time synchronization anomalies caused by the time jump of the network time synchronization server during the leap second transition period, prevent the network time synchronization at the leap second time from introducing unexpected jumps in the system clock, and avoid generating incorrect timestamps in event records, fault recordings, and communication messages.

[0119] In one possible implementation, the method further includes: After the initial network time synchronization is completed through the network time synchronization module, the synchronized system clock is written into the hardware real-time clock chip through the hardware clock write-back thread.

[0120] The hardware real-time clock chip (RTC chip) is an onboard hardware clock chip for power embedded devices. It is independent of the operating system's system clock. After power failure, it continues to keep time using a backup battery. After the operating system restarts, it reads the initial time from the chip.

[0121] The hardware clock write-back thread refers to an independently running software thread within the device, specifically responsible for synchronously writing the system clock, which has been calibrated at the operating system level, into the hardware real-time clock chip to achieve persistent storage even after power failure.

[0122] Because the operating system's system clock is a memory-level clock, it is lost when the device is powered off. The hardware RTC chip relies on a battery to maintain time. The calibrated time is written back to the RTC, so that when the device powers on and restarts, it can read a more accurate initial time from the RTC, avoiding significant time inconsistencies upon power-up. Therefore, after the network time synchronization module completes its first effective network time synchronization, the operating system's system clock has been corrected to a reliable time. This triggers the hardware clock write-back thread, writing the currently calibrated system clock to the onboard hardware real-time clock chip and updating the time stored internally in the RTC chip.

[0123] It should be understood that in this embodiment, after the network time synchronization module completes the first network time synchronization process, the system clock after time synchronization is written to the hardware real-time clock chip through the hardware clock write-back thread. The system clock that has been calibrated in memory is persisted to the hardware real-time clock chip that can be maintained even when power is lost. This enables the power embedded device to obtain a relatively accurate initial time when it is powered on and restarted next time, reduces the initial time deviation after power-on, improves the time reference quality after the power embedded device restarts, and further enhances the overall reliability of the device's time synchronization.

[0124] In some examples, an application scenario of seamless switching between heterogeneous time sources is provided in a substation network packet recording and analysis device. The deployment environment is as follows: the hardware is a substation network packet recording and analysis device; the operating system is Linux (kernel 4.x series); the network has dual network cards, connected to network A and network B respectively; Scenario 1: IRIG-B remains active (operating normally, accounting for the vast majority of the time).

[0125] (1) Power on the device → Start the `Sntp_TaskMain()` thread → Create a UDP socket and bind the port using `ClientInit()` (completed in one go).

[0126] (2) Check every 3ms, and `LibHard_GetIrigSynStatus()` returns TRUE.

[0127] (3) The thread executes the `else` branch: only `LibHard_SetNtpStatus(FALSE)` (one boolean assignment).

[0128] (4) CPU overhead: IRIG-B status check and assignment every 3ms. No socket operations, no network I / O.

[0129] (5) This state can continue to run for several months, and the socket will always remain bound.

[0130] Scenario 2: IRIG-B momentary loss followed by recovery (antenna briefly blocked, for a few seconds).

[0131] (1) Nth cycle: `LibHard_GetIrigSynStatus()` returns FALSE.

[0132] (2) The thread enters the `if` branch: `ClientMainProcess()` is called.

[0133] (3) Single probe measurement → deviation 5ms (<100ms threshold) → direct time calibration, without triggering resampling.

[0134] (4) N+1 cycle: IRIG-B resumes → thread returns to `else` branch → only set flag.

[0135] (5) The entire process: No socket creation / destruction, no thread creation / destruction. It only switches once between if-else statements.

[0136] Scenario 3: Frequent jitter of IRIG-B (poor antenna contact, switching on and off every few seconds).

[0137] (1) During the jitter, `Sntp_TaskMain()` switches repeatedly between if-else branches.

[0138] (2) Each time you switch to SNTP: send the request directly using the already bound socket, without preprocessing.

[0139] (3) Each time you switch back to IRIG-B: only set the NTP status flag to FALSE, and do not perform any post-processing.

[0140] (4) Comparison with the on-demand start / stop solution: On-demand start / stop executes `ClientReset()` (close → up to 30 socket retries → rebind) once every time the connection is interrupted in the same scenario, and the overhead increases with the frequency of jitter. In the embodiment of this application, the number of times `ClientReset()` is executed is always zero, regardless of the number of jitters.

[0141] Scenario 4: Network jitter causes a large single deviation (triggering adaptive resampling).

[0142] (1) During normal operation, an NTP request returned an abnormal deviation of +500ms due to instantaneous network congestion.

[0143] (2) Single probe: |500ms| ≥100ms threshold → trigger resampling.

[0144] (3) Four additional measurements were performed, with a 1-second interval between each measurement: the results were +3ms, +5ms, -2ms, and +500ms (the second network failure).

[0145] (4) Remove extreme values: remove +500ms (maximum value) and -2ms (minimum value), and take (3+5) / 2 = 4ms.

[0146] (5) 4ms < ±100ms → Normal time calibration, the actual time calibration amount is 4ms, and it is not affected by abnormal values.

[0147] Scenario 5: Simultaneous brief loss of both sources (antenna blockage and network interruption occur simultaneously).

[0148] (1) `LibHard_Main()` detected `bSntpState==FALSE&&bIrigState==FALSE`.

[0149] (2) Start the 60s anti-shake timer, and the panel LED will light up as an alarm.

[0150] (3) The IRIG-B signal recovers within 60 seconds → the timer is reset and the alarm callback is “not triggered”.

[0151] (4) The maintenance personnel are unaware of it, that is, a momentary disturbance is correctly filtered out.

[0152] (5) Compared with the non-anti-shake solution: a 15-second instantaneous dual-source loss will generate an alarm record, which will be mixed with the real long-term time synchronization failure.

[0153] In some examples, a degenerate operation is provided in an IRIG-B-free device.

[0154] For devices equipped with only a single SNTP time source, the embodiments of this application perform degenerate operation, namely: the SNTP thread always performs time synchronization processing (without entering the suppressed state); the adaptive measurement depth strategy takes effect independently (small deviation pass-through, large deviation resampling); the alarm anti-shake strategy is based only on the SNTP single source state determination.

[0155] It should be noted that the embodiments of this application can be applied to the following scenarios: (1) power embedded devices that simultaneously possess IRIG-B (or other hardware time sources such as GPS second pulse) and SNTP / NTP network time synchronization capabilities. (2) industrial real-time systems that require a definite and controllable (millisecond-level) time source switching delay. (3) harsh electromagnetic environments (substations, power plants) where IRIG-B signals may experience frequent switching. (4) operation and maintenance scenarios that require high accuracy in dual-source loss alarms. (5) embedded platforms running multi-threaded operating systems, etc.

[0156] It is understood that the embodiments of this application have the following beneficial effects: (1) The switching latency changes from "probabilistic" to "deterministic". The switching latency of conventional on-demand start-stop schemes depends on the kernel state (file descriptor availability, port remnants). The 30-retry mechanism of ClientReset() itself proves that socket creation is unreliable in embedded environments and may never succeed in creation in extreme cases. In the embodiments of this application, resource reconstruction is completely excluded from the critical path of switching. The switching latency is always equal to the sum of the scheduling period (about 3ms) and the network round-trip time. The upper bound of the latency is determined and predictable.

[0157] (2) Minimize the expected measurement overhead. Replace the fixed number of measurements with a probe-acknowledgment two-level architecture. Normal operation (>99% time synchronization cycle) requires only 1 NTP request; additional sampling is only added when the probe detects an abnormally large deviation. The expected number of measurements is close to 1, rather than a fixed 4 or more.

[0158] (3) Alarm anti-shake adapts to instantaneous disturbances in industrial sites. When both time sources are lost simultaneously, no alarm is triggered immediately. The alarm is only triggered if the loss continues for more than a preset duration (e.g., 60s). This filters out short-term disturbances such as instantaneous antenna blockage and brief network congestion, reducing the false alarm rate.

[0159] (4) RTT quality gating eliminates erroneous time synchronization under high-latency networks. The round-trip time is automatically calculated before each NTP measurement, and measurement results exceeding the threshold are discarded directly. This prevents unreliable clock offsets from entering the time synchronization process when the network is congested, forming a two-level quality defense with adaptive measurement depth. That is, RTT gating filters unreliable data at a lower level, and probe-confirmation adjusts the sampling depth as needed at an upper level.

[0160] (5) The architecture is simple and the thread lifecycle is clear. The lifecycle of an SNTP thread is equal to the device's operating cycle. Changes in the IRIG-B signal only affect the execution path (if-else) within the thread and do not trigger thread management operations (create / destroy).

[0161] It should be understood that the sequence number of each step in the above embodiments does not imply the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiments of this application.

[0162] Corresponding to the time source switching time synchronization method in the above embodiment, Figure 2 The diagram shows a schematic of a time source switching time synchronization processing system according to an embodiment of this application. For ease of explanation, only the parts related to the embodiment of this application are shown.

[0163] Reference Figure 2 The time source switching time synchronization processing system 3 of this embodiment is applied to a power embedded device and includes: The hardware time synchronization module 31 is used to respond to the power-embedded device power-on startup, obtain the hardware time synchronization signal status, and perform hardware time synchronization processing on the system clock of the power-embedded device when the hardware time synchronization signal status is valid. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module.

[0164] The network time synchronization module 32 is used to create a UDP socket and establish a network connection with the time server in response to the power-embedded device's startup. It keeps the UDP socket open when the hardware time synchronization signal is valid. When the hardware time synchronization signal is invalid, it performs network time synchronization processing on the system clock via the UDP socket. This network time synchronization processing corrects the system clock based on the network time synchronization signal obtained through interaction with the time server via the UDP socket. The time synchronization accuracy of the hardware time synchronization processing is higher than that of the network time synchronization processing.

[0165] Furthermore, the time source switching time synchronization processing system 3 in this embodiment also includes an adaptive measurement module, which adopts a probe-confirmation two-level progressive architecture. That is, the first level uses a single network time measurement as a probe. If the absolute value of the clock deviation is less than the first threshold, it is directly accepted and time is synchronized. Only when the deviation is greater than or equal to the first threshold is the second level triggered to add no less than a preset number of samples, remove extreme values ​​and take the average before time synchronization.

[0166] Furthermore, the time source switching and time synchronization processing system 3 in this embodiment also includes a time source monitoring and alarm module, which reads the validity status of the hardware time synchronization signal obtained by the hardware time synchronization interface in a first cycle, and comprehensively determines the validity status of the hardware time synchronization interface and the network time synchronization module in a second cycle; when it is detected that both the hardware time synchronization signal status and the network time synchronization signal status are invalid at the same time, a stabilization timer with a preset stabilization duration is started; if either one becomes valid before the stabilization timer expires, the stabilization timer is reset; an alarm is triggered only when both are still invalid at the timer expires.

[0167] like Figure 3 As shown, Figure 3 This is a schematic diagram of the structure of a time source switching time synchronization processing system provided in an embodiment of this application. Figure 3 The overall architecture of the system includes: an in-station time synchronization device (BeiDou and GPS time sources) that simultaneously outputs two time signals: IRIG-B (DC B code hardware time synchronization, high priority) and SNTP network time synchronization (backup), which is connected to an embedded relay protection / recording network distribution device. The device internally realizes dual time source priority switching, quality gating, status determination, and alarm indication.

[0168] (1) Upstream time source: Station time synchronization device. It receives GPS / BeiDou satellite signals through a satellite antenna to generate a reference time. It simultaneously outputs two time signals to the outside world: IRIG-B (DC level signal) and SNTP (Local Area Network NTP / SNTP Network Time Protocol message).

[0169] (2) Two main time synchronization paths inside the embedded device. Path 1: IRIG-B hardware time synchronization (high priority time source). Call the function IRIG_AdjustTime() to acquire IRIG-B hardware signals, parse the time, and read the B code signal quality status at the same time, and output the status flag bIrigState (B code valid / lost status).

[0170] Pathway 2: SNTP network time synchronization (backup, resident thread tSntp). tSntp is a resident background thread that never exits, with a loop logic of while(1){taskDelay(3)}, periodically polling the execution source for judgment: Determine if IRIG-B is valid, with input from bIrigState; If IRIG-B is active, the suppression branch is executed. In this case, SNTP backup time synchronization is suppressed: time correction is skipped, the socket connection is not closed, and a 3ms deterministic handover delay is set. That is, when IRIG-B is normal, network time synchronization only maintains the link, does not modify the system clock, and retains the socket. If IRIG-B fails, it can quickly switch to SNTP. The output status is bSntpState.

[0171] If IRIG-B is lost or fails, the adaptive measurement module is activated, and SNTP backup time synchronization is enabled. The adaptive measurement module includes a two-level recursive probe confirmation mechanism and RTT quality gating. The first level is a single probe, ensuring network time probing is completed in >99% of cycles; the second level involves N confirmations, triggered only in network anomaly scenarios. RTT quality gating filters high-latency, low-quality measurement samples based on round-trip time (RTT). At this point, the SNTP time source state (bSntpState) and the clock offset after quality filtering are output; settimeofday() is called to correct the system clock using the clock offset.

[0172] (3) Time source monitoring and alarm module LibHard_Main (runs in 1s cycle).

[0173] Input states: IRIG-B state bIrigState and SNTP network time source state bSntpState. Perform four-state determination, namely: four state combinations: IRIG-B valid / SNTP valid; IRIG-B valid / SNTP invalid; IRIG-B invalid / SNTP valid; IRIG-B invalid / SNTP invalid.

[0174] After performing a four-state determination, two actions are output: one is a debounce timer of 60 seconds, which triggers an alarm callback if the dual time sources are continuously lost for 60 seconds; once either time source is restored, the timer is automatically reset. The other is an LED panel indicator, which drives the panel LEDs based on the four-state results to visually display the current working status of the time sources.

[0175] Figure 3 In this system, the on-site time synchronization device receives the BeiDou / GPS satellite time reference and simultaneously outputs an IRIG-B DC-level hardware time signal and an SNTP network time protocol signal. The embedded relay protection / wave recording network distribution device sets the IRIG-B hardware time synchronization as the high-priority primary time source, with the SNTP network time synchronization serving as the backup time source. A resident tSntp thread continuously monitors the IRIG-B signal status. When the IRIG-B signal is valid, it suppresses the SNTP clock correction action to maintain the network socket connection. When the IRIG-B signal is lost, it activates the adaptive measurement module, performs a probe-confirmation two-level recursive measurement, and discards high-latency measurement samples through RTT quality gating to obtain the clock offset correction system clock. The time source monitoring and alarm module collects the IRIG-B status bIrigState and the SNTP status bSntpState at 1-second intervals for four-state determination. A 60-second anti-jitter timer is configured; continuous time source loss triggers an alarm callback, and automatic reset occurs upon time source recovery, simultaneously driving the LED panel to indicate the status.

[0176] It should be noted that the information interaction and execution process between the modules in the aforementioned time source switching time synchronization processing system 3 are based on the same concept as the method embodiment of this application. For details on their specific functions and technical effects, please refer to the method embodiment section, which will not be repeated here.

[0177] This application also provides a terminal device, such as... Figure 4 As shown, Figure 4 This is a schematic diagram of the structure of a terminal device provided in an embodiment of this application. (Refer to...) Figure 4 The terminal device 4 in this embodiment includes a memory 41, a processor 42, and a computer program stored in the memory 41 and executable on the processor 42. When the processor 42 executes the computer program, it implements the steps in the time source switching time matching method embodiment described above.

[0178] This application also provides a computer-readable storage medium storing a computer program, which, when executed by a processor, can implement the steps in the above-described method embodiments.

[0179] This application provides a computer program product that, when run on a mobile terminal, enables the mobile terminal to implement the steps described in the various method embodiments.

[0180] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, all or part of the processes in the methods of the above embodiments of this application can be implemented by a computer program instructing related hardware. The computer program can be stored in a computer-readable storage medium, and when executed by a processor, it can implement the steps of the various method embodiments described above. The computer program includes computer program code, which can be in the form of source code, object code, executable files, or certain intermediate forms. The computer-readable medium can include at least: any entity or device capable of carrying the computer program code to a photographic device / terminal device, a recording medium, a computer memory, a read-only memory (ROM), a random access memory (RAM), an electrical carrier signal, a telecommunication signal, and a software distribution medium. Examples include USB flash drives, portable hard drives, magnetic disks, or optical disks.

[0181] In the above embodiments, the descriptions of each embodiment have different focuses. For parts that are not described in detail or recorded in a certain embodiment, please refer to the relevant descriptions of other embodiments.

[0182] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, or a combination of computer software and electronic hardware. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.

[0183] In the embodiments provided in this application, it should be understood that the disclosed apparatus / network devices and methods can be implemented in other ways. For example, the apparatus / network device embodiments described above are merely illustrative. For instance, the division of modules or units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces; the indirect coupling or communication connection between apparatuses or units may be electrical, mechanical, or other forms.

[0184] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0185] The technical features of the various embodiments described above in this application can be combined arbitrarily without conflict. For the sake of brevity, this specification does not describe all possible combinations, but as long as these combinations do not violate the technical spirit of this application, they should all be considered within the scope of this application. Based on the content disclosed in this application, those skilled in the art can reasonably combine, delete, or replace the technical features of the above embodiments according to actual needs, and such modifications and variations all fall within the protection scope of this application.

[0186] The above embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit them. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of this application, and should all be included within the protection scope of this application.

Claims

1. A time source switching time synchronization processing method, characterized in that, Applied to a power embedded device, wherein the power embedded device runs a hardware time synchronization module and a network time synchronization module, the method includes: In response to the power embedded device being powered on, the hardware time synchronization module is controlled to acquire the hardware time synchronization signal status, and the network time synchronization module is controlled to create a user datagram socket (UDP) and establish a network connection with the time server. If the hardware time synchronization signal is in a valid state, the hardware time synchronization module is controlled to perform hardware time synchronization processing on the system clock of the power embedded device, and the UDP socket is kept in an open state. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module. If the hardware time synchronization signal is in a failed state, the network time synchronization module is controlled to perform network time synchronization processing on the system clock through the UDP socket. The network time synchronization processing is based on the network time synchronization signal obtained by interacting with the time server via the UDP socket to correct the system clock. The time synchronization accuracy of the hardware time synchronization process is higher than that of the network time synchronization process.

2. The time source switching and time synchronization processing method as described in claim 1, characterized in that, The method includes: When the hardware timing signal status changes from an effective state to an ineffective state, and the first duration of the ineffective state is greater than the first preset hysteresis duration, it is determined that the first state change of the hardware timing signal status is effective, and the network timing module is controlled to perform network time synchronization processing on the system clock. When the hardware timing signal changes from a failed state to a valid state, and the second duration of the valid state is greater than the second preset hysteresis duration, the second state change of the hardware timing signal is determined to be valid, and the hardware timing module is controlled to perform hardware time synchronization processing on the system clock.

3. The time source switching and time synchronization processing method as described in claim 2, characterized in that, If the hardware time synchronization signal is in a failed state, the network time synchronization module is controlled to perform network time synchronization processing on the system clock through the UDP socket, including: The first network time measurement is performed by the network time synchronization module to obtain the first clock deviation. If the absolute value of the first clock deviation is less than the first threshold, then network time synchronization processing is performed on the system clock based on the first clock deviation. If the absolute value of the first clock deviation is greater than or equal to the first threshold, the network time synchronization module continues to perform network time measurements more than or equal to a preset number of times. The value obtained by arithmetic processing of the multiple clock deviations obtained from the multiple network time measurements is used as the adoption deviation, and network time synchronization processing is performed on the system clock based on the adoption deviation.

4. The time source switching and time synchronization processing method as described in claim 3, characterized in that, In the process of controlling the network time synchronization module to perform network time synchronization processing on the system clock through the UDP socket, the method further includes: Calculate the network round-trip delay measured at the current network time. If the network round-trip time exceeds a preset network quality threshold, the current clock deviation value obtained from the current network time measurement will be discarded.

5. The time source switching and time synchronization processing method as described in claim 4, characterized in that, In the process of controlling the network time synchronization module to perform network time synchronization processing on the system clock through the UDP socket, the method further includes: The network time synchronization module initiates time requests to multiple time servers in sequence according to a preset priority order. The multiple time servers are divided into at least two levels: a master level and a slave level. In each round of time synchronization, communication is attempted starting from the primary time server. If the primary time server does not respond effectively, communication is downgraded to access the secondary time server. If, during the current time synchronization process, after traversing all the multiple time servers within all levels, none of the multiple time servers provide a valid response, then the next round of server traversal and retry will be automatically initiated until the preset number of retry rounds is reached.

6. The time source switching and time synchronization processing method as described in claim 1, characterized in that, The method further includes: When both the hardware timing signal status and the network timing signal status are detected to be in a failed state, a de-shake timer is started, wherein the de-shake timer is set with a preset de-shake duration; the network timing signal status is detected by the network time synchronization module. During the timing of the anti-shake timer, if it is detected that the hardware timing signal status or the network timing signal status has been restored to a valid state, the anti-shake timer is reset and no service layer alarm is executed. If the anti-shake timer expires after the preset anti-shake duration, and both the hardware timing signal and the network timing signal are still in a failed state, then a service layer alarm will be executed.

7. The time source switching and time synchronization processing method as described in claim 1, characterized in that, The method further includes: When the system clock is detected to be in the leap second critical window, the network time synchronization module is controlled to suspend the network time synchronization process. The leap second critical window is a time interval pre-configured based on the leap second effective time.

8. The time source switching and time synchronization processing method as described in claim 1, characterized in that, The method further includes: After the initial network time synchronization is completed through the network time synchronization module, the synchronized system clock is written into the hardware real-time clock chip through the hardware clock write-back thread.

9. A time source switching time synchronization processing system, characterized in that, Applications in power embedded devices, including: The hardware time synchronization module is used to respond to the power-embedded device power-on startup, obtain the hardware time synchronization signal status, and perform hardware time synchronization processing on the system clock of the power-embedded device when the hardware time synchronization signal status is valid. The hardware time synchronization processing is to correct the system clock based on the hardware time synchronization signal parsed by the hardware time synchronization module. A network time synchronization module is used to respond to the power-embedded device's power-on startup by creating a User Datagram Socket (UDP) and establishing a network connection with a time server; keeping the UDP socket open when the hardware time synchronization signal is valid; and performing network time synchronization processing on the system clock via the UDP socket when the hardware time synchronization signal is invalid. The network time synchronization processing corrects the system clock based on the network time synchronization signal obtained through interaction with the time server via the UDP socket. The time synchronization accuracy of the hardware time synchronization processing is higher than that of the network time synchronization processing.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the method as described in any one of claims 1 to 8.