Embedded device rtc software drift compensation method and system

CN122963299APending Publication Date: 2026-10-23SHENZHEN ZHANYIN TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611061861.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-16
Publication Date
2026-10-23

AI Technical Summary

Technical Problem

[0004]上述现有技术存在一定局限:依赖NTP的方式要求设备保持联网,难以适配长期脱网或低功耗工况;硬件Trim电路会显著增加物料成本与电路复杂度;而仅依赖移动终端覆盖写入的方式,每次校时虽能消除当前误差,但晶振自身的漂移速率未被识别与补偿,两次校时之间累积的误差仍会反复出现,长期墙钟精度难以改善

Benefits of technology

1、通过将开机分批补偿累计量与本轮一步校正量相加构成组合量后再归一化为日历日漂移率,并在每次移动终端校时事件后清零累计量与刷新锚点,使已经被开机补偿消化掉的漂移分量重新拼回真实漂移信号中,避免了“开机补偿越多、下一轮估计越偏”的反向耦合,让校时样本与开机补偿在同一时间基准下自洽演进,在无需NTP与硬件Trim电路的条件下实现了对晶振漂移率的可持续辨识与逼近;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122963299A_ABST
    Figure CN122963299A_ABST
Patent Text Reader

Abstract

The application relates to an embedded device RTC software drift compensation method and system, and relates to the technical field of embedded device clock management. The application is based on the UTC second domain to maintain a persistent drift compensation state containing a time correction anchor point, a drift rate and a start-up compensation cumulative amount. When a mobile terminal writes an RTC each time, the UTC second values before and after writing and the anchor point are used to calculate a calendar interval and a one-step correction amount. The combination of the one-step correction amount and the start-up compensation cumulative amount is normalized according to the calendar interval to obtain an instantaneous drift measurement value and update the drift rate. Meanwhile, the start-up compensation cumulative amount is cleared and the anchor point is refreshed. When the device starts up each time, the drift rate, the start-up elapsed time and the start-up compensation cumulative amount are used to calculate a compensation amount of the current time after deducting a compensated amount and drive the RTC to write. Then, the drift rate estimation gradually approaching the real drift rate of the crystal oscillator is obtained through event iteration. The application realizes compensation of the crystal oscillator drift rate and improves the long-term wall clock accuracy of the embedded device in the off-network period.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the technical field of embedded device clock management, and in particular to an embedded device RTC software drift compensation method and system. Background Technology

[0002] With the increasing popularity of embedded screen devices such as smart speakers and smart alarm clocks, these devices still need to present users with a stable and accurate local wall clock time even in offline or weak network environments. The accuracy of the wall clock directly affects the reliability of core interactive functions such as alarm wake-up, timed broadcast, and schedule reminders. Therefore, high requirements are placed on the long-term timekeeping accuracy of the device's real-time clock (RTC) module.

[0003] In existing technologies, the RTC time maintenance of embedded devices typically relies on the following methods: First, continuously connecting to the network to call the NTP server for time synchronization; second, introducing a crystal oscillator calibration (Trim) circuit at the hardware level to physically correct the crystal oscillator frequency deviation; and third, relying on the mobile terminal to periodically send the current UTC time to the device via Bluetooth and directly overwrite it into the RTC register to complete the time synchronization.

[0004] The aforementioned existing technologies have certain limitations: relying on NTP requires the device to remain connected to the network, making it difficult to adapt to long-term offline or low-power operating conditions; hardware Trim circuits significantly increase material costs and circuit complexity; and relying solely on mobile terminal overwrite methods, although each time calibration can eliminate the current error, the crystal oscillator's own drift rate is not identified and compensated, and the accumulated error between two calibrations will still repeatedly occur, making it difficult to improve the long-term accuracy of the wall clock. Summary of the Invention

[0005] This application provides an embedded device RTC software drift compensation method and system, which aims to estimate and compensate the crystal oscillator drift rate by using the mobile terminal's low-frequency time synchronization event and the device's power-on event as the main input paths without requiring an NTP connection or a hardware crystal oscillator calibration circuit. This ensures that the batch compensation process during power-on does not contaminate the next round of drift rate estimation, thereby improving the long-term accuracy of the wall clock.

[0006] In a first aspect, this application provides a method for RTC software drift compensation in an embedded device, the method comprising: Based on the UTC second domain, the drift compensation state is maintained. The drift compensation state includes the time synchronization anchor point, drift rate and power-on compensation cumulative amount, to obtain a persistent drift compensation state. In response to a write event of the mobile terminal writing to the RTC, the calendar interval and one-step correction amount are calculated based on the UTC second value before writing, the UTC second value after writing to the RTC and the time synchronization anchor point. The one-step correction amount is equal to the UTC second value after writing minus the UTC second value before writing. Based on the combination of the one-step correction amount and the power-on compensation cumulative amount, the instantaneous drift measurement value is obtained by normalizing it to the calendar day according to the calendar interval. The drift rate is then updated according to the instantaneous drift measurement value, and the power-on compensation cumulative amount is cleared to zero and the time synchronization anchor point is updated to the post-write UTC second value. In response to a device power-on event, the power-on elapsed time is determined based on the difference between the current UTC second value and the time synchronization anchor point at the time of device power-on. Based on the drift rate, the power-on elapsed time, and the cumulative power-on compensation, the compensation amount for the current time is calculated after deducting the already compensated amount. The current compensation amount is written to the RTC, and the current compensation amount is added to the cumulative power-on compensation amount to obtain the updated cumulative power-on compensation amount. In each subsequent mobile terminal write event, the calculation of the instantaneous drift measurement value and the update of the drift rate are repeatedly performed. In each subsequent device power-on event, the calculation of the current compensation amount and the drive writing of the RTC are repeatedly performed to obtain the drift rate that iteratively approximates the true drift rate of the embedded device crystal oscillator.

[0007] In the above embodiments, existing embedded devices, relying solely on mobile terminal Bluetooth time synchronization, only overwrite the current RTC each time, without identifying and modeling the crystal oscillator drift rate itself. For example, after a certain model of smart alarm clock has been running continuously for dozens of days, the wall clock may accumulate a deviation on the order of minutes relative to the actual UTC, and the drift error cannot be compensated between two time synchronizations, causing users to perceive inaccurate time during offline periods. This application maintains a persistent drift compensation state based on the UTC second domain, including the time synchronization anchor point, drift rate, and cumulative power-on compensation. Each time the mobile terminal writes to the RTC, it calculates the calendar interval and one-step correction amount based on the UTC second values ​​before and after writing and the anchor point, and then uses the combination of the one-step correction amount and the cumulative power-on compensation amount to calculate the daily... The instantaneous drift measurement value is obtained by normalizing the interval and the drift rate is updated. At the same time, the cumulative power-on compensation is cleared and the anchor point is refreshed. Each time the device is powered on, the compensation amount for the current time is calculated based on the drift rate, the power-on duration, and the cumulative power-on compensation, after deducting the already compensated amount, and is driven to be written to the RTC. Then, through event iteration, a drift rate estimate that gradually approximates the true drift rate of the crystal oscillator is obtained. This application not only realizes software identification and batch compensation of crystal oscillator drift rate without the need for NTP and hardware Trim circuit, so that the applied power-on compensation will not be incorrectly absorbed into the next round of drift rate estimation, but also makes the time calibration sample and power-on compensation evolve in the same time, improves the long-term wall clock accuracy of embedded devices during offline periods, and reduces the proportion of time deviation perceived by users between two time calibrations.

[0008] In some embodiments, the combination of the one-step correction amount and the power-on compensation cumulative amount, normalized to calendar days according to the calendar interval, to obtain the instantaneous drift measurement value specifically includes: The sum of the cumulative power-on compensation and the one-step correction is used as the combined quantity; Multiply the combined quantity by the number of seconds per day, divide by the calendar interval, and truncate to zero to obtain the instantaneous drift measurement value; The absolute value of the instantaneous drift measurement is clamped according to a preset sample threshold.

[0009] In the above embodiments, directly using the one-step correction amount as the drift signal ignores the cumulative effect of the preceding power-on compensation on the RTC. For example, if a positive small-step compensation has been applied to the RTC during a power-on, and the drift rate is estimated using only the correction amount in the next time synchronization, the compensated part will be misjudged as a reduction in drift, resulting in an underestimation of the drift rate. This application uses the sum of the cumulative power-on compensation amount and the one-step correction amount to form a combined amount. The combined amount is multiplied by the number of seconds per day, divided by the calendar interval, and truncated to zero to obtain the instantaneous drift measurement value. Then, its absolute value is clamped according to a preset sample threshold. Not only is the compensated drift component backfilled into the real drift signal using deconvolution, but the integer truncation to zero and sample threshold clamping also prevent single abnormal samples from exceeding a reasonable level, thus improving the robustness of the estimation process.

[0010] In some embodiments, after clamping the absolute value of the instantaneous drift measurement according to a preset sample threshold, the method further includes: When the drift rate has a valid historical value, the predicted combination amount is calculated by reverse calculation based on the drift rate and the calendar interval; The difference between the combined quantity and the predicted combined quantity is calculated as the prediction residual; The confidence decay factor is determined based on the ratio of the absolute value of the predicted residual to the calendar interval. The confidence decay factor decreases monotonically as the ratio increases and is not lower than a preset lower limit. The instantaneous drift measurement is updated by multiplying the instantaneous drift measurement by the confidence decay factor.

[0011] In the above embodiments, since the fixed-weighted exponentially weighted moving average treats all samples equally, when the time interval of a certain calibration is short and the residual is large, noisy samples will be absorbed into the drift rate with the same weight. For example, the samples collected when the device is briefly connected and then recalibrated immediately have low quality, and entering the smoother with equal weight will introduce jitter. After the samples are clamped, this application reverses the calculation of the predicted combination quantity based on the current drift rate and the calendar interval, uses the difference between the measured combination quantity and the predicted combination quantity as the prediction residual, and then determines a monotonically decreasing confidence decay factor that is not lower than a preset lower limit by the ratio of the absolute value of the residual to the calendar interval. The instantaneous drift measurement value is updated by multiplying the factor with the instantaneous drift measurement value. This allows samples that deviate from the current prior to participate in the smoothing with continuous confidence. At the same time, by setting the lower limit, it avoids correct samples being completely rejected by incorrect priors after cold start, thus improving the anti-disturbance capability of drift rate estimation.

[0012] In some embodiments, updating the drift rate based on the instantaneous drift measurement includes: When there is no valid historical value for the drift rate, the drift rate is directly assigned to the instantaneous drift measurement value; When a valid historical value exists for the drift rate, an exponentially weighted moving average is calculated by weighting the drift rate and the instantaneous drift measurement value at a ratio of 3:1 to obtain the updated drift rate, and the absolute value of the drift rate is clamped according to a preset drift rate threshold.

[0013] In the above embodiments, when there is no valid historical value for the drift rate, the instantaneous drift measurement value is directly assigned as the drift rate. When there is a valid historical value, the drift rate and the instantaneous drift measurement value are weighted by an exponential weighted moving average with a weight ratio of 3:1, and the result is clamped according to a preset drift rate threshold. This eliminates the cold start dilution problem, making the first sample effective. It also balances sample noise suppression and tracking lag with a weight ratio of 3:1, improving the convergence behavior of drift rate estimation throughout its entire lifecycle.

[0014] In some embodiments, the method further includes: When the calendar interval is less than a preset threshold, the calculation of the instantaneous drift measurement value and the update of the drift rate are skipped. Only the time synchronization anchor point is updated to the written UTC second value, and the cumulative power-on compensation amount is cleared to zero, so as to obtain the drift compensation state after the anchor point is refreshed.

[0015] In the above embodiments, this application skips the calculation of instantaneous drift measurement values ​​and the update of drift rate when the calendar interval is less than a preset threshold, and only updates the time synchronization anchor point to the written UTC second value and clears the power-on compensation cumulative amount; it filters out low-quality samples with short intervals and improves the stability of drift rate estimation.

[0016] In some embodiments, the method further includes: In response to an RTC time-change event other than the write event from the mobile terminal, the time synchronization anchor, the drift rate, and the cumulative power-on compensation are cleared, and the drift rate is prohibited from using the historical estimate prior to this time-change event.

[0017] In the above embodiments, in response to an RTC time-changing event other than a write event from the mobile terminal, this application clears the time-calibration anchor point, drift rate and cumulative power-on compensation, and prohibits the drift rate from using the historical estimate before the current time-changing event; thus improving the estimation purity in multi-path time-changing scenarios.

[0018] In some embodiments, RTC time-changing events other than mobile terminal write events are divided into correctable time-changing events carrying offset metadata and uncorrectable time-changing events not carrying offset metadata. When the absolute value of the number of seconds identified by the offset metadata exceeds a preset threshold, the correctable time change event is downgraded to the uncorrectable time change event. In response to the correctable time change event, the time synchronization anchor point is synchronously shifted by the number of seconds identified by the offset metadata according to the offset metadata, while retaining the drift rate and the cumulative power-on compensation amount; In response to the uncorrectable time change event, the time synchronization anchor point, the drift rate, and the power-on compensation cumulative amount are cleared.

[0019] In the above embodiments, the indiscriminate liquidation strategy discards historical drift rate estimates that could be retained when facing time-changing scenarios with known offsets, such as daylight saving time switching, time zone changes, and system-level fine-tuning. For example, each daylight saving time switch triggers a liquidation, resulting in the loss of several complete drift rate samples each year, which affects the long-term convergence speed. This application divides non-mobile terminal time-changing events into correctable time-changing events that carry offset metadata and uncorrectable time-changing events that do not carry metadata. For the former, the time synchronization anchor point is synchronously shifted according to the metadata, and the drift rate and the cumulative amount of power-on compensation are retained. For the latter, a clearing operation is performed, and when the absolute value of the offset exceeds a preset threshold, the correctable event is downgraded to an uncorrectable event. This not only avoids the unnecessary loss of drift rate history in scenarios with known offsets, but also blocks attacks on the integrity of the anchor point by abnormal metadata values ​​through the downgrade threshold, improving the continuity and security of the drift compensation state in multiple time-changing scenarios.

[0020] In some embodiments, all time values ​​of the drift compensation state are taken from the UTC second value output by the RTC, and the calculation of the calendar interval, the instantaneous drift measurement value, the power-on elapsed time, and the current compensation amount does not incorporate the monotonic running count of the embedded device processor as a time reference.

[0021] In the above embodiments, all time quantities of the constraint drift compensation state in this application are taken from the UTC second value output by the RTC. The calculation of calendar interval, instantaneous drift measurement value, power-on elapsed time and current compensation amount does not introduce the processor monotonic running count as a time reference. It eliminates the pseudo drift component introduced by the mixed calculation of dual crystal sources, and also makes the drift rate estimation physically correspond to the real deviation of the RTC crystal, thus improving the correspondence between the estimation model and the physical object.

[0022] In a second aspect, embodiments of this application provide an embedded device RTC software drift compensation system, comprising: one or more processors and a memory; the memory is coupled to the one or more processors, the memory is used to store computer program code, the computer program code including computer instructions, and the one or more processors call the computer instructions to cause the system to perform the method described in the first aspect and any possible implementation thereof.

[0023] One or more technical solutions provided in the embodiments of this application have at least the following technical effects or advantages: 1. By adding the cumulative amount of power-on batch compensation to the one-step correction amount in this round to form a combined amount and then normalizing it to the calendar day drift rate, and clearing the cumulative amount and refreshing the anchor point after each mobile terminal time synchronization event, the drift components that have been digested by power-on compensation are reassembled into the real drift signal, avoiding the reverse coupling of "the more power-on compensation, the more biased the next round of estimation", allowing the time synchronization sample and power-on compensation to evolve self-consistently under the same time base, and realizing the continuous identification and approximation of the crystal oscillator drift rate without the need for NTP and hardware Trim circuit; 2. By back-calculating the predicted combination quantity using the current drift rate and using the difference between the measured combination quantity and the predicted combination quantity as the prediction residual, and then determining the confidence decay factor that is monotonically decreasing and not lower than the preset lower limit by the ratio of the residual to the calendar interval, samples that fall within the outlier threshold but deviate from the prior are smoothed by continuous decay, which improves the anti-disturbance performance of drift rate estimation in the scenario of sample quality fluctuation. 3. By classifying non-mobile terminal time-changing events into correctable time-changing events carrying offset metadata and uncorrectable time-changing events without metadata, the former performs anchor point synchronization shift and retains the drift rate and cumulative power-on compensation, while the latter performs overall cleanup and uses a threshold downgrade mechanism to block attacks on anchor points by abnormal metadata. Compared with the indiscriminate cleanup strategy, this avoids the unnecessary loss of drift rate history in scenarios with known offsets such as daylight saving time switching and time zone changes, and improves the continuity and anti-interference capability of drift compensation status in multiple time-changing scenarios. Attached Figure Description

[0024] Figure 1This is a flowchart illustrating an embedded device RTC software drift compensation method according to an embodiment of this application; Figure 2 This is a general architecture diagram of an embedded device RTC software drift compensation method according to an embodiment of this application; Figure 3 This is a flowchart of the APP time synchronization drift sample collection and rate update process in the embodiments of this application; Figure 4 This is a flowchart of the embedded device RTC compensation process during power-on, as described in this application embodiment. Figure 5 This is a schematic diagram of the physical device structure of an embedded device RTC software drift compensation system according to an embodiment of this application. Detailed Implementation

[0025] The terminology used in the following embodiments of this application is for the purpose of describing particular embodiments only and is not intended to be limiting of this application. As used in the specification of this application, the singular expressions “a,” “an,” “the,” “the,” and “this” are intended to include the plural expressions as well, unless the context clearly indicates otherwise. It should also be understood that the term “and / or” as used in this application refers to any or all possible combinations including one or more of the listed items.

[0026] Hereinafter, the terms "first" and "second" are used for descriptive purposes only and should not be construed as implying or suggesting relative importance or implicitly indicating the number of indicated technical features. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature, and in the description of the embodiments of this application, unless otherwise stated, "multiple" means two or more.

[0027] To facilitate understanding, the application scenarios of the embodiments of this application are described below.

[0028] In the field of embedded device clock management, embedded devices with screens, such as smart speakers and smart alarm clocks, need to continuously present users with a stable and accurate local wall clock time in offline or weak network environments. The accuracy of the wall clock directly affects the reliability of core interactions such as alarm wake-up and timed broadcast.

[0029] In related technologies, the maintenance of the real-time clock (RTC) of embedded devices usually relies on continuous network connection to call the Network Time Protocol (NTP), the introduction of hardware crystal oscillator calibration circuit, or the periodic time synchronization via mobile terminal Bluetooth to directly overwrite the RTC register. However, the method of relying on NTP is difficult to adapt to long-term offline conditions, hardware crystal oscillator calibration will significantly increase material costs, and relying solely on mobile terminal overwriting does not identify and model the crystal oscillator drift rate itself. The accumulated error between two time synchronizations will still occur repeatedly, and the long-term wall clock accuracy is difficult to improve.

[0030] This application is primarily applied to the maintenance of local wall clocks in embedded devices with screens, such as smart speakers and smart alarm clocks. These devices typically use low-frequency Bluetooth time synchronization as their main timing channel and operate under frequent power-on and power-off conditions. In these application scenarios, there is a reverse coupling relationship between the power-on batch compensation action and the next round of time synchronization samples. Improper handling will cause the drift rate estimate to consistently deviate from the true crystal oscillator value. To solve the above technical problems, this application provides a software drift compensation method for embedded device RTC. An embodiment is described below, combined with... Figure 1 The present application describes a method for RTC software drift compensation in an embedded device. Please see Figure 1 The embedded device RTC software drift compensation method provided in this application includes the following steps: S101. Based on the UTC second domain, maintain the drift compensation state. The drift compensation state includes the time synchronization anchor point, drift rate and power-on compensation accumulation, to obtain a persistent drift compensation state.

[0031] Among them, the Coordinated Universal Time (UTC) second domain refers to using the UTC second value as the sole time measurement benchmark; the time synchronization anchor point refers to the UTC second value recorded after the last successful writing of the mobile terminal to the RTC; the drift rate refers to the smoothed estimate of the crystal oscillator drift rate with the dimension of "second correction amount / natural day"; the cumulative power-on compensation amount refers to the total number of seconds that have been accumulated on the RTC through the power-on compensation action since the last time the mobile terminal synchronized its time, which can be positive or negative.

[0032] like Figure 2As shown, the embedded device maintains a drift compensation closed loop with UTC seconds as the sole time reference throughout its entire lifecycle. This closed loop consists of two trigger paths: "APP time synchronization" on the left and "power-on compensation" on the right. The two paths communicate via a persistent drift compensation status in JSON format. The drift compensation status is stored in non-volatile memory and contains four core fields: time synchronization anchor utc_last, drift rate rate_sec, cumulative power-on compensation comp_sum_sec, and drift rate validity flag rate_valid. When the device leaves the factory or undergoes a cleanup operation, the initial values ​​are set to: utc_last=0, rate_sec=0, comp_sum_sec=0, rate_valid=0.

[0033] Specifically, all time values ​​for the drift compensation state are taken from the UTC second values ​​output by the RTC hardware. The calculation of the calendar interval, the instantaneous drift measurement, the power-on elapsed time, and the current compensation amount does not incorporate the monotonic running count of the embedded device processor as a time reference throughout the entire method. This constraint ensures that the drift estimation process uses only the single RTC crystal oscillator as a reference, avoiding drift estimation distortion caused by the mixed calculation of dual clock sources (RTC crystal and processor main crystal).

[0034] S102. In response to the write event of the mobile terminal writing to the RTC, calculate the calendar interval and one-step correction amount based on the UTC second value before writing, the UTC second value after writing, and the time synchronization anchor point of the mobile terminal writing to the RTC.

[0035] Among them, after the mobile terminal APP and device complete time synchronization and successfully write the target UTC time into the RTC hardware, it triggers the following... Figure 3 The diagram illustrates the process for collecting APP time synchronization drift samples and updating the drift rate. The process entry point receives two parameters: the UTC second value `utc_before` (device local time) before writing and the UTC second value `utc_after` (standard UTC time) after writing. The system distinguishes between "APP time synchronization" and "user menu time change / production test time change" based on the function entry point of the write event: only the APP time synchronization link enters this step and the subsequent drift rate update process; when the user directly modifies the time through the device screen menu or production test commands, a separate `clear()` interface is called to reset all related states to zero.

[0036] Specifically, such as Figure 3As shown, firstly, the time synchronization anchor point utc_last in the persistent state is read, and the time synchronization interval d_interval = utc_before - utc_last is calculated. At this point, there are two special cases where the drift rate update needs to be skipped: First, if utc_last is 0, it indicates that the device has never undergone valid time synchronization; second, if d_interval is less than the preset minimum interval threshold, it indicates that the time since the last synchronization is too close, and the sample lacks statistical significance. In either case, the calculation of subsequent instantaneous drift measurements and the update of the drift rate are skipped. Only the time synchronization anchor point utc_last is updated to utc_after, and the cumulative power-on compensation amount comp_sum_sec is cleared to zero. After obtaining the drift compensation state after the anchor point refresh, the data is persisted and returned. If the interval threshold condition is met, the one-step correction amount bias_raw = utc_after - utc_before is calculated. Here, bias_raw > 0 indicates that the device's local time is slower than the standard UTC time, and it was in a slow state before RTC; bias_raw < 0 indicates that it was in a fast state before RTC. The notation for the drift rate `rate_sec` follows the same convention: a positive value indicates that the RTC is slow by a certain number of seconds per day and requires compensation, while a negative value indicates that the RTC is fast by a certain number of seconds per day and requires deduction of compensation. If `|bias_raw|` exceeds the preset wild threshold, the sample is considered abnormal, all persistent fields are cleared, and the system is reset.

[0037] S103. Based on the combination of the one-step correction amount and the power-on compensation cumulative amount, normalize it to the calendar day according to the calendar interval to obtain the instantaneous drift measurement value, update the drift rate according to the instantaneous drift measurement value, clear the power-on compensation cumulative amount to zero, and update the time calibration anchor point to the written UTC second value.

[0038] Reference Figure 3 After the one-step correction amount passes the outlier check, the sum of the power-on compensation cumulative amount and the one-step correction amount is first used as the combined amount: comb = comp_sum_sec + bias_raw. The physical meaning of this combined amount is the true total drift seconds of the RTC crystal oscillator within this cumulative period, which is restored by adding the portion already digested by power-on compensation (comp_sum_sec) and the residual uncompensated bias revealed by this time calibration (bias_raw). Then, the combined amount is multiplied by the number of seconds per day, 86400, divided by the calendar interval, and truncated to zero to obtain the instantaneous drift measurement value meas. Then, the absolute value of meas is clamped according to a preset sample threshold to prevent a single abnormal sample from excessively affecting the drift rate estimation.

[0039] Specifically, let's illustrate this with a set of actual operating values: Assume a device's RTC crystal oscillator is actually 10 seconds slow per day, and 30 seconds have been accumulated through power-on compensation in the previous operating cycle. After a 4-day interval, the app time synchronization shows that the local time is still 40 seconds behind the standard UTC time. Given the conditions: comp_sum_sec=30, bias_raw=40, d_interval=4 days. Substituting into the formula: comb=30+40=70, meas=70×86400 / (4×86400)=17.5, truncating to zero, we get meas=17 seconds / day, and clamp the absolute value of meas. This absolute value of 17 accurately reflects the residual component of the remaining 40-second deviation spread across each day after the 30-second accumulated error has been absorbed through power-on compensation, providing a clean sample for EWMA smoothing that is unaffected by the already compensated amount.

[0040] Combination Figure 3 The drift rate update employs the following weighted strategy: When the drift rate lacks a valid historical value (i.e., a cold start state with rate_valid = 0), the drift rate is directly assigned the instantaneous drift measurement value, i.e., rate_sec = meas; when the drift rate has a valid historical value (i.e., a state with rate_valid = 1), an exponentially weighted moving average is calculated using the drift rate and the instantaneous drift measurement value at a weight ratio of 3:1, resulting in the updated rate_sec = (3 × rate_sec + meas) / 4, with the result truncated to zero. After the update, the absolute value of the drift rate is clamped according to a preset drift rate threshold. If it exceeds the rationality upper limit, the estimate is deemed divergent, triggering a full-state liquidation. At the end of this step, terminal operations are performed: utc_last is assigned the value utc_after, comp_sum_sec is cleared to zero, and all state fields are persisted, completing the anchor point reset for this cycle.

[0041] S104. In response to the device power-on event, determine the power-on elapsed time based on the difference between the current UTC second value and the time synchronization anchor point when the device is powered on, and calculate the current compensation amount after deducting the already compensated amount based on the drift rate, the power-on elapsed time and the cumulative power-on compensation amount.

[0042] Among them, the device triggers the following every time it is powered on and started: Figure 4 The boot-up RTC compensation process is shown below. First, the drift compensation status is loaded from the JSON file. If `rate_valid` is 0 or `utc_last` is 0, it means the device has never undergone at least two valid app time synchronizations, and the drift rate cannot be reliably estimated. In this case, the compensation amount of 0 is returned directly, and no RTC write operation is performed. If the status is valid, the UTC second value `cur_utc_sec` read by the current RTC is passed from the upper layer, and the process proceeds to the next step.

[0043] Specifically, the elapsed shutdown duration is calculated as elapsed=cur_utc_sec-utc_last. If it is detected that cur_utc_sec<utc_last, a time rollback anomaly is determined to have occurred, all persistent states are cleared immediately and 0 is returned. Under normal circumstances, the total compensation amount to be made up during the shutdown period is calculated according to the drift rate: total=rate_sec×elapsed / 86400, and the result is truncated towards zero. Then the accumulated amount that has been written through previous power-on compensations in the current cycle is deducted to obtain the current adjustment amount: this=total-comp_sum_sec.

[0044] S105. Drive and write to the RTC according to the current compensation amount, and accumulate the current compensation amount to the power-on compensation accumulated amount to obtain the updated power-on compensation accumulated amount.

[0045] Wherein, with continued reference to Figure 4 , the current adjustment amount this is clamped by the single power-on compensation upper limit to obtain the actual adjustment amount adj, so as to prevent user-perceivable time jumps caused by long-time shutdown. If adj is not equal to 0, new_utc=cur_utc_sec+adj is returned to the upper layer, and the upper layer interface writes the value to the RTC hardware to complete the physical clock correction; then the state comp_sum_sec+=adj is updated and persisted. If adj is equal to 0, the RTC writing is skipped, and comp_sum_sec remains unchanged. This mechanism ensures that the accumulated error is eliminated in small batches in steps, rather than being adjusted drastically at one time.

[0046] The single power-on compensation upper limit can be configured according to the tolerance of the device to time jumps, and a typical preset value is ±3600 seconds (i.e., 1 hour). The basis for selecting this upper limit is: in most application scenarios, the threshold of time jump that users can perceive is usually on the order of tens of minutes. Limiting the single power-on compensation to within 1 hour can not only gradually eliminate long-term accumulated errors after several power-on and power-off operations, but also avoid sudden time jumps on the user interface caused by one-time drastic adjustment. In a specific implementation, the upper limit value is stored in the firmware in the form of a macro definition or a configuration parameter. If the absolute value of this calculated at this time exceeds the upper limit, adj takes the product of its sign and the upper limit; if not, adj is directly equal to this.

[0047] S106. The calculation of the instantaneous drift measurement value and the update of the drift rate are repeatedly executed in each subsequent writing event of the mobile terminal, and the calculation of the current compensation amount and the driving writing of the RTC are repeatedly executed in each subsequent device power-on event, so as to obtain a drift rate that iteratively approximates the real drift rate of the crystal oscillator of the embedded device.

[0048] Wherein, as shown in Figure 2As shown in the overall architecture, each APP time synchronization write event triggers the execution of the complete drift sample acquisition and drift rate EWMA update process from S102 to S103, and each device power-on event triggers the execution of the power-on compensation and status accumulation process from S104 to S105. As the running cycle increases, the power-on compensation continuously digests the accumulated error during the shutdown period based on the successive approximation of rate_sec, while the APP time synchronization extracts the instantaneous drift measurement value that is not affected by the compensated amount from the residual deviation after compensation, and updates rate_sec after 3:1 weighted smoothing. The two triggering paths alternate and iterate throughout the entire life cycle, so that rate_sec gradually converges to the true physical drift rate of the embedded device's RTC crystal oscillator.

[0049] In the above embodiments, by collecting APP time synchronization samples and smoothing EWMA updates, as well as accumulating and clearing the boot compensation amount in batches, a basic closed loop of drift compensation has been achieved.

[0050] In one embodiment, this application further introduces a classification and processing mechanism for non-APP time synchronization and modification events. This embodiment establishes a two-level classification and differentiated processing strategy. This type of event broadly refers to RTC time modification events other than those written to the mobile terminal. Typical scenarios include users manually adjusting the system time through the device screen menu, or batch settings of the RTC performed by production testing tools before shipment. In response to this type of RTC time modification event, the system first determines whether the event carries offset metadata. The offset metadata identifies the number of seconds offset from the original time in this time modification operation.

[0051] The "offset metadata" refers to structured data explicitly passed by the caller during an RTC time modification operation, representing the time difference before and after the modification. For example, when batch calibrating device time, production testing tools provide an additional offset field (such as offset in seconds Δ, where a positive value indicates forward adjustment and a negative value indicates backward adjustment) in addition to writing the target UTC value. This field is the offset metadata. When a user directly modifies the time through the device menu, since the original time before the modification is not recorded, this operation does not carry offset metadata and is classified as an uncorrectable time modification event.

[0052] Specifically, when an RTC time-changing event does not carry offset metadata, the system classifies it as an uncorrectable time-changing event. For such events, since the direction and magnitude of the time modification are unknown, the time synchronization anchor `utc_last` has lost its temporal semantic consistency with the historical compensation amount `comp_sum_sec` and drift rate `rate_sec`. Therefore, in response to an uncorrectable time-changing event, the system immediately clears the time synchronization anchor, drift rate, and power-on compensation accumulation, sets the drift rate validity flag `rate_valid` to invalid, persists the reset state, and prohibits the drift rate from using historical estimates prior to this time-changing event.

[0053] When an RTC time-correction event carries offset metadata, the system first checks the absolute value of the number of seconds identified by the metadata against a preset threshold. If the absolute value exceeds a preset correctable threshold, the offset is deemed too large to maintain anchor point validity through simple translation. The correctable time-correction event is then downgraded to an uncorrectable time-correction event, and the aforementioned clear and reset operation is performed. If the offset does not exceed the threshold, in response to the correctable time-correction event, the system does not disrupt the established drift rate estimation and power-on compensation accumulation. Instead, it synchronously translates the time-correction anchor point utc_last by the number of seconds identified by the offset metadata. This anchor point translation operation ensures that the subsequent APP time-correction process can still obtain the correct calendar interval when calculating d_interval = utc_before - utc_last, thus preserving the continuous estimation capability of the drift rate.

[0054] Furthermore, in this embodiment, after the instantaneous drift measurement value is clamped by a preset sample threshold and before the drift rate is updated, a reliability assessment mechanism based on the prediction residual is introduced.

[0055] Specifically, when a valid historical value for the drift rate exists (i.e., rate_valid is 1), the system first uses the currently converged drift rate rate_sec and the current calendar interval d_interval to inversely calculate the predicted combination amount under no additional perturbation: pred_comb = rate_sec × d_interval / 86400, rounding the result. Then, the difference between the actual combination amount combb = comp_sum_sec + bias_raw and the predicted combination amount is calculated as the prediction residual. The physical meaning of this prediction residual is the unexplained component between the actual deviation revealed by the current APP time synchronization and the deviation expected based on the historical drift rate; its absolute value reflects the degree of consistency between the current sample and the historical model.

[0056] Based on this, a confidence decay factor is determined according to the ratio of the absolute value of the predicted residual to the calendar interval. This confidence decay factor monotonically decreases as the ratio increases, indicating that the further a sample deviates from the model's expectations, the lower its confidence. Simultaneously, this decay factor has a preset lower limit to prevent the weights of a very small number of outlier samples from being completely zeroed, causing the drift rate update to stagnate. Finally, the instantaneous drift measurement is updated by the product of the instantaneous drift measurement and the confidence decay factor. The confidence-weighted measurement is then fed into the subsequent EWMA smoothing formula for drift rate update. This design allows the iterative estimation of the drift rate to automatically reduce the contribution of outlier samples when facing occasional atypical time deviations, further improving the robustness and convergence quality of the drift rate estimation over long-term operation.

[0057] In a specific implementation of this embodiment, the confidence attenuation factor is determined in the following manner: a normalized residual upper limit threshold R_max (e.g., R_max=1.0) and a lower limit factor α_min (e.g., α_min=0.2) are preset. The normalized residual r=|prediction residual| / d_interval is calculated. When r≥R_max, the attenuation factor is taken as α_min; when r<R_max, the attenuation factor α=1-(1-α_min)×(r / R_max). This functional form ensures that the attenuation factor decreases linearly as the normalized residual increases, and is always no less than the preset lower limit α_min.

[0058] Assume that the RTC of a certain device actually loses about 17 seconds per day, the historical drift rate rate_sec has converged to 10 seconds / day, and the cumulative boot compensation amount of the previous cycle comp_sum_sec=30 seconds. The current APP time calibration interval d_interval=4 days, and the one-step correction amount bias_raw=40 seconds. Calculated according to step S103, the combined quantity comb=30+40=70, and the instantaneous drift measurement value meas=17 seconds / day. At this time, there is a valid historical value for the drift rate, and the system further performs confidence assessment: first, the predicted combined quantity pred_comb=rate_sec×d_interval / 86400=10×4=40 is calculated inversely, whose physical meaning is: under the prior historical drift rate of 10 seconds / day, the RTC is expected to accumulate a delay of 40 seconds within the 4-day period. The actual combined quantity comb is 70, so the prediction residual=comb-pred_comb=70-40=30, and its absolute value is 30, which reflects that the current sample additionally reveals an unexplained delay deviation of 30 seconds relative to the historical prior. The normalized residual r=30 / (4×86400)≈0.0000868. Assuming R_max=0.001, r is far less than R_max, and the attenuation factor α≈1-(1-0.2)×(0.0000868 / 0.001)≈0.931. The instantaneous drift measurement value is multiplied by the attenuation factor to obtain the corrected meas=17×0.931≈15.8, which is truncated towards zero to 15 seconds / day. Then proceed to EWMA update: rate_sec_new=(3×10+15) / 4=45 / 4=11.25, which is truncated towards zero to 11 seconds / day. This result reflects the conservative adoption of the current sample by the adaptive mechanism: rate_sec converges smoothly from the prior 10 towards the measured 17, avoiding one-step overestimation of the drift rate caused by accidental fluctuations in the residual deviation.

[0059] If, during another time calibration, the predicted residual abnormally increases to the point that the normalized residual exceeds a threshold, the decay factor will be reduced to the lower limit according to a preset rule, thereby significantly weakening the influence of outliers on the drift rate update. Through this mechanism, this application significantly improves robustness to occasional time perturbations while maintaining the convergence speed of the drift rate iteration.

[0060] The following describes an embedded device RTC software drift compensation system from the perspective of hardware processing in an embodiment of this application. Please refer to [link to relevant documentation]. Figure 5 This is a schematic diagram of the physical device structure of an embedded device RTC software drift compensation system according to an embodiment of this application.

[0061] It should be noted that, Figure 5 The structure of an embedded device RTC software drift compensation system shown is merely an example and should not impose any limitations on the functionality and scope of use of the embodiments of this application.

[0062] like Figure 5 As shown, the system includes a CPU, which can perform various appropriate actions and processes based on a program stored in the ROM or a program loaded into the RAM from a storage portion, such as executing the methods described in the above embodiments. The RAM also stores various programs and data required for system operation. The CPU, ROM, and RAM are interconnected via a bus. I / O interfaces are also connected to the bus.

[0063] The following components are connected to the I / O interface: input sections including cameras, infrared sensors, etc.; output sections including liquid crystal displays (LCDs) and speakers, etc.; storage sections including hard drives, etc.; and communication sections including network interface cards such as LAN (Local Area Network) cards and modems, etc. The communication section performs communication processing via a network such as the Internet. Drives are also connected to the I / O interface as needed. Removable media, such as disks, optical disks, magneto-optical disks, semiconductor memories, etc., are installed on the drive as needed so that computer programs read from them can be installed into the storage section as needed.

[0064] Specifically, according to embodiments of this application, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of this application include a computer program product comprising a computer program carried on a computer-readable medium, the computer program including a computer program for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication component, and / or installed from a removable medium. When the computer program is executed by the CPU, it performs the various functions defined in this application.

[0065] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. Each block in a flowchart or block diagram may represent a module, segment, or portion of code, which contains one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those shown in the drawings.

[0066] Specifically, the system in this embodiment includes a processor and a memory. The memory stores a computer program, and when the computer program is executed by the processor, it implements the method provided in the above embodiment.

[0067] In another aspect, this application also provides a computer-readable storage medium, which may be included in the system described in the above embodiments; or it may exist independently and not assembled into the system. The storage medium carries one or more computer programs that, when executed by a processor of the system, cause the system to implement the methods provided in the above embodiments.

[0068] The above-described embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit it. 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 scope of the technical solutions of the embodiments of this application.

[0069] As used in the above embodiments, depending on the context, the term "when..." can be interpreted as meaning "if...", "after...", "in response to determining...", or "in response to detecting...". Similarly, depending on the context, the phrase "when determining..." or "if (the stated condition or event) is interpreted as meaning "if determining...", "in response to determining...", "when (the stated condition or event) is detected", or "in response to detecting (the stated condition or event)".

Claims

1. A method for compensating for RTC software drift in an embedded device, characterized in that, The method includes: Based on the UTC second domain, the drift compensation state is maintained. The drift compensation state includes the time synchronization anchor point, drift rate and power-on compensation cumulative amount, to obtain a persistent drift compensation state. In response to a write event of the mobile terminal writing to the RTC, the calendar interval and one-step correction amount are calculated based on the UTC second value before writing, the UTC second value after writing to the RTC and the time synchronization anchor point. The one-step correction amount is equal to the UTC second value after writing minus the UTC second value before writing. Based on the combination of the one-step correction amount and the power-on compensation cumulative amount, the instantaneous drift measurement value is obtained by normalizing it to the calendar day according to the calendar interval. The drift rate is then updated according to the instantaneous drift measurement value, and the power-on compensation cumulative amount is cleared to zero and the time synchronization anchor point is updated to the post-write UTC second value. In response to a device power-on event, the power-on elapsed time is determined based on the difference between the current UTC second value and the time synchronization anchor point at the time of device power-on. Based on the drift rate, the power-on elapsed time, and the cumulative power-on compensation, the compensation amount for the current time is calculated after deducting the already compensated amount. The current compensation amount is written to the RTC, and the current compensation amount is added to the cumulative power-on compensation amount to obtain the updated cumulative power-on compensation amount. In each subsequent mobile terminal write event, the calculation of the instantaneous drift measurement value and the update of the drift rate are repeatedly performed. In each subsequent device power-on event, the calculation of the current compensation amount and the drive writing of the RTC are repeatedly performed to obtain the drift rate that iteratively approximates the true drift rate of the embedded device crystal oscillator.

2. The method according to claim 1, characterized in that, The combined amount based on the one-step correction amount and the cumulative power-on compensation amount, normalized to the calendar day according to the calendar interval, yields the instantaneous drift measurement value, specifically including: The sum of the cumulative power-on compensation and the one-step correction is used as the combined quantity; Multiply the combined quantity by the number of seconds per day, divide by the calendar interval, and truncate to zero to obtain the instantaneous drift measurement value; The absolute value of the instantaneous drift measurement is clamped according to a preset sample threshold.

3. The method according to claim 2, characterized in that, After clamping the absolute value of the instantaneous drift measurement according to a preset sample threshold, the method further includes: When the drift rate has a valid historical value, the predicted combination amount is calculated by reverse calculation based on the drift rate and the calendar interval; The difference between the combined quantity and the predicted combined quantity is calculated as the prediction residual; The confidence decay factor is determined based on the ratio of the absolute value of the predicted residual to the calendar interval. The confidence decay factor decreases monotonically as the ratio increases and is not lower than a preset lower limit. The instantaneous drift measurement is updated by multiplying the instantaneous drift measurement by the confidence decay factor.

4. The method according to claim 1, characterized in that, The step of updating the drift rate based on the instantaneous drift measurement includes: When there is no valid historical value for the drift rate, the drift rate is directly assigned to the instantaneous drift measurement value; When a valid historical value exists for the drift rate, an exponentially weighted moving average is calculated by weighting the drift rate and the instantaneous drift measurement value at a ratio of 3:1 to obtain the updated drift rate, and the absolute value of the drift rate is clamped according to a preset drift rate threshold.

5. The method according to claim 1, characterized in that, The method further includes: When the calendar interval is less than a preset threshold, the calculation of the instantaneous drift measurement value and the update of the drift rate are skipped. Only the time synchronization anchor point is updated to the written UTC second value, and the cumulative power-on compensation amount is cleared to zero, so as to obtain the drift compensation state after the anchor point is refreshed.

6. The method according to claim 1, characterized in that, The method further includes: In response to an RTC time-change event other than the write event from the mobile terminal, the time synchronization anchor, the drift rate, and the cumulative power-on compensation are cleared, and the drift rate is prohibited from using the historical estimate prior to this time-change event.

7. The method according to claim 1, characterized in that, The RTC time-changing events other than the mobile terminal write events are divided into correctable time-changing events that carry offset metadata and uncorrectable time-changing events that do not carry offset metadata. When the absolute value of the number of seconds identified by the offset metadata exceeds a preset threshold, the correctable time change event is downgraded to the uncorrectable time change event. In response to the correctable time change event, the time synchronization anchor point is synchronously shifted by the number of seconds identified by the offset metadata according to the offset metadata, while retaining the drift rate and the cumulative power-on compensation amount; In response to the uncorrectable time change event, the time synchronization anchor point, the drift rate, and the power-on compensation cumulative amount are cleared.

8. The method according to claim 1, characterized in that, All time values ​​of the drift compensation state are taken from the UTC second value output by the RTC. The calculation of the calendar interval, the instantaneous drift measurement value, the power-on elapsed time, and the current compensation amount does not incorporate the monotonic running count of the embedded device processor as a time reference.

9. An embedded device RTC software drift compensation system, characterized in that, include: One or more processors and a memory; the memory is coupled to the one or more processors, the memory being used to store computer program code, the computer program code including computer instructions, the one or more processors invoking the computer instructions to cause the system to perform the method as described in any one of claims 1-8.