Power data security storage method based on power failure detection and cache compression
Patent Information
- Application Number
- CN202511858142.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-10
- Publication Date
- 2026-10-27
- Estimated Expiration
- 2045-12-10
AI Technical Summary
[0004]本发明的目的在于提供基于掉电检测与缓存压缩的电能数据安全存储方法,以智能掉电检测为基础结合数据完整性保护技术、快速数据保存技术、智能预测与诊断技术及状态监控技术形成一套完整的掉电检测数据安全存储与丢失恢复的方法,以解决上述面对复杂环境时,电能数据易丢失的问题
[0014]与现有技术相比,本发明具有以下技术效果的至少之一:
Smart Images

Figure CN121681241B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of intelligent single-chip microcomputer system technology, and in particular to a method for secure storage of electrical energy data based on power failure detection and cache compression. Background Technology
[0002] The rise of smart grids is an inevitable product of the global energy revolution and the integration of digital technologies. Its development is rooted in the need to overcome the bottlenecks of traditional power systems and the urgent demand for low-carbon transformation. With global economic growth and continuously rising energy demand, the International Energy Agency (IEA) predicts that global electricity demand will increase by nearly 50% by 2040, with 80% of that growth coming from developing countries. Traditional power systems can no longer bear this growth pressure. As smart grid construction progresses, electricity data, as the core basis for billing, grid dispatching, and energy efficiency analysis, has its storage integrity, security, and reliability directly affecting the operational efficiency of the power system and user rights. In particular, data loss prevention technology in the event of sudden power outages has become a focus of industry research.
[0003] In existing power data storage solutions, hardware redundancy designs such as supercapacitors and backup batteries are often used to cope with the risk of power outages. Although this design can temporarily solve the power supply problem and buy time for maintenance, traditional backup batteries and internally integrated capacitors are difficult to cope with complex environments, which will lead to the loss of power data. Summary of the Invention
[0004] The purpose of this invention is to provide a secure storage method for electrical energy data based on power failure detection and cache compression. This method combines intelligent power failure detection with data integrity protection technology, fast data saving technology, intelligent prediction and diagnosis technology, and status monitoring technology to form a complete method for secure storage and recovery of power failure detection data, thereby solving the problem of easy loss of electrical energy data in complex environments.
[0005] To achieve the above objectives, the present invention provides the following technical solution: This invention discloses a method for securely storing electrical energy data based on power failure detection and cache compression, the method specifically including: During the power-on initialization detection and processing phase, the small bucket data is read for non-zero detection and CRC verification. Then, all the power data in the EEPROM is read. The large bucket data is superimposed with the small bucket data, and the small bucket data is cleared to 0. All the data is then written into the EEPROM. During the timed data detection phase, based on the real-time accumulated power data, timed detection is performed and trigger conditions are set. When the conditions are triggered, the data in the small bucket is cleared to 0, and the data in the large bucket and the small bucket are written to the EEPROM. During the power failure handling phase at any time, after detecting a power failure event, the small bucket data is stored in EEPROM and the small bucket data in RAM is cleared, and the system enters sleep mode. During the abnormal recovery phase, the data in the small bucket is set to the NO-init area of RAM to ensure that the memory data at the corresponding address is not cleared to 0 when a reset occurs. Data recovery is then performed by executing the power-on initialization detection and processing program.
[0006] Furthermore, the electrical energy data, totaling 424 bytes, is backed up, including small bucket data and large bucket data; Each data item in the bucket is stored using the INT16U data type; Each data item in the large data bucket is stored using the INT32U data type.
[0007] Furthermore, in the power-on initialization detection and processing stage, an error correction code verification is added on top of the CRC verification, and a transaction log is constructed, which includes a status log and an operation log.
[0008] Furthermore, in the power-on initialization detection and processing stage, the construction of the transaction log includes extracting the status log from the EEPROM, further embedding the offline-trained lightweight decision tree model into the firmware in the form of parameters, and initializing the parameters.
[0009] Furthermore, the offline training and embedding of the lightweight decision tree model includes the following steps: Step 1) Collect data from the transaction log, including features and tags; Step 2) Select the features related to the cause of the power outage; Step 3) Select the lightweight decision tree model CART and train it; Step 4) Evaluate the model's performance and perform pruning optimization to lighten the model; Step 5) Convert the trained model into code that can run on the MCU.
[0010] Furthermore, in the timed data detection stage, the triggering conditions include threshold conditions and recording time, and the triggering conditions are dynamically adjusted using an adaptive algorithm.
[0011] Furthermore, in the timed data detection phase, a log-first WAL mechanism is used to write the operation log into the circular buffer of the EEPROM before the small bucket data is stored in the EEPROM. In the event of a sudden power failure, the data is recovered from the operation log. In addition, status parameters are recorded and saved to the status log to update the transaction log.
[0012] Furthermore, during the power outage handling phase at any time, a heartbeat monitoring mechanism is used to periodically check the health status through timer interrupts. When a heartbeat is lost multiple times in a row, a pre-power outage mechanism is triggered to perform data saving operations in advance. Furthermore, operation logs and status logs are recorded based on the context to update the transaction log.
[0013] Furthermore, in the abnormal recovery phase, after the reset operation is executed, the lightweight decision tree model is loaded; features are further extracted from the transaction log, including voltage drop slope, task execution interval and log integrity before writing, and the features are input into the decision tree model for inference, and the result outputs a power outage probability distribution vector. The cause of the power outage is further analyzed based on the probability distribution vector, and the data recovery strategy is adjusted.
[0014] Compared with the prior art, the present invention has at least one of the following technical effects: 1. In the power-on initialization detection and processing stage of this invention, the dual verification technology is used to improve the data recovery success rate. Compared with the traditional method, it has the technical advantage of data recovery and solves the problem that the traditional method only relies on a single verification, and once the verification fails, the data will be lost and cannot be recovered.
[0015] 2. In the timed data detection stage of this invention, the trigger conditions are dynamically set using an adaptive algorithm, which can automatically adjust the protection level and use the WAL mechanism to ensure that data can be recovered from the log in the event of a sudden power failure. This has technical advantages over traditional methods and solves the problem that traditional methods are difficult to cope with complex environments, resulting in the loss of power data.
[0016] 3. During the power failure processing phase at any time, this invention utilizes a heartbeat mechanism to implement early warning storage of data and record operation logs and status logs based on context. Compared with traditional methods, it has the technical advantages of pre-storing data and combining context information, solving the problems of detection response delay, limited time window for data storage, and lack of context information in traditional methods.
[0017] 4. In the abnormal recovery phase of this invention, the cause of power failure is predicted in real time based on a lightweight decision tree model after reset. Compared with traditional methods, it has the technical advantage of tracing the cause of power failure and solves the problem that traditional methods lack a prediction mechanism, which makes it impossible to trace the cause of power failure. Attached Figure Description
[0018] To more clearly illustrate the technical solutions in the embodiments or examples of the present invention, the drawings used in the embodiments or examples will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained according to these drawings without creative effort.
[0019] Figure 1 This is a schematic diagram of the process of the power data secure storage method based on power failure detection and cache compression of the present invention; Figure 2 This is a schematic diagram of the EEPROM circuit of the present invention; Figure 3 This is a schematic diagram of the MCU power-down detection circuit of the present invention. 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] The specific implementation method is as follows: See appendix Figure 1 - Appendix Figure 3 A method for securely storing electrical energy data based on power failure detection and cache compression is disclosed, the method specifically including: During the power-on initialization detection and processing phase, the small bucket data is read for non-zero detection and CRC verification. Then, all the power data in the EEPROM is read. The large bucket data is superimposed with the small bucket data, and the small bucket data is cleared to 0. All the data is then written into the EEPROM. During the timed data detection phase, based on the real-time accumulated power data, timed detection is performed and trigger conditions are set. When the conditions are triggered, the data in the small bucket is cleared to 0, and the data in the large bucket and the small bucket are written to the EEPROM. During the power failure handling phase at any time, after detecting a power failure event, the small bucket data is stored in EEPROM and the small bucket data in RAM is cleared, and the system enters sleep mode. During the abnormal recovery phase, the data in the small bucket is set to the NO-init area of RAM to ensure that the memory data at the corresponding address is not cleared to 0 when a reset occurs. Data recovery is then performed by executing the power-on initialization detection and processing program.
[0027] The aforementioned method for secure storage of electrical energy data based on power failure detection and cache compression employs a process-structured design, breaking down each function into functional points from start to implementation. Each step has a specific function, and these steps are interconnected, forming a complete implementation chain. This chain can be used for secure storage of electrical energy data and recovery from data loss during power failures. The system's hardware circuit utilizes an MCU-controlled power failure detection circuit (see appendix). Figure 3 As a power-down detection system, it incorporates the BL24C512A chip and its peripheral circuitry (see Appendix). Figure 2Using it as an external electrically erasable memory (EEPROM), the system implementation method incorporates deep learning algorithms and combines various data processing technologies to meet the design requirements of securely storing electrical energy data and preventing data loss during power failure.
[0028] In practice, the electrical energy data, totaling 424 bytes, is backed up, including small bucket data and large bucket data. Each data item in the bucket is stored using the INT16U data type; Each data item in the large data bucket is stored using the INT32U data type.
[0029] Table 1 shows the electrical energy data that needs to be saved in this invention. The electrical energy data that needs to be backed up and saved is shown in Table 1:
[0030] In specific implementation, during the power-on initialization detection and processing stage, an error correction code verification is added on top of the CRC verification, and a transaction log is constructed, which includes a status log and an operation log.
[0031] The above-mentioned dual verification using CRC check and error check is implemented through the following steps: Step 1) Let the starting address of the small bucket data in RAM be p. Check the data pointed to by p. If the result is all 0, directly read the EEPROM data (large bucket and small bucket data); if there is non-zero data, start from step 2. Step 2) Perform CRC check. Extract the energy data portion from the small bucket data area, let the length be d, and calculate the CRC value. The formula is: CRC a =CRC32(p, d), where CRC a The variable represents the verification result; CRC32(...) represents the verification function (using the polynomial 0xEDB88320, with an initial value of 0xFFFFFFFF); p represents the starting address of the bucket data; d represents the length (4 bytes); further, the stored CRC value is read using the formula: CRC b =*(uint32*)(p+4), where CRC b This represents the CRC value; p represents the starting address of the bucket data; *(uint32*) indicates that the CRC value is forcibly converted to a 32-bit unsigned integer and dereferenced using a pointer; it is stored at location p+d (4 bytes in length); further, the CRC... a With CRC bThe values are compared. If the result is equal, the verification passes (EEPROM data is read directly). If the result is not equal, the verification fails (proceed to step 3, RS verification). Finally, the verification boolean value (false / true) and the energy value are output. Step 3) Perform RS verification. Take the 8 bytes of energy data Ec (4 bytes) and CRC checksum (4 bytes) from the small bucket data as a data block. Use RS(12,8) encoding to generate a 4-byte checksum for storage, resulting in a total of 12 bytes of small bucket data. Use the RS decoding algorithm to decode the 12 bytes of small bucket data. The decoding process includes syndrome calculation, error location, and error correction. If decoding is successful, extract the corrected energy value and the corrected CRC value; if decoding fails, set it to false. Finally, output the checksum Boolean value and the energy value. Step 4) Based on the above verification results, recover the final energy value. The recovery strategy is as follows: when the CRC verification result is true, the final energy data is the energy value output by the CRC verification; when the CRC verification result is false and the RS verification result is true, the final energy data is the energy value output by the RS verification and the soft error count + 1; when both verification results are false, the current soft error count = the previous soft error count + 1, and the small bucket data is set to 0 (since the small bucket data cannot be recovered, it can only be regarded as 0 to avoid accumulating erroneous data into the total energy); finally, output the final small bucket energy value and update the soft error count and transaction log.
[0032] Step 3 above, the decoding process includes syndrome calculation, error location, and error correction, and its specific implementation steps are as follows: Step 1) Let Λ(x) = 1 (current error location polynomial), B(x) = 1 (previous error location polynomial), L = 0 (order of the current error location polynomial), n = 0 (number of iterations), and δ = 1 (correction term); Step 2) For the received data, represent it as a polynomial R(x) = r0 + r1x + r2x² + ... + rn-1xn-1, where R(x) represents the received codeword polynomial (the 12-byte bucket data mentioned above); ri represents the i-th byte of the received codeword (each byte of the bucket data); n represents the codeword length (the length of the encoded data); and x represents the formal variable (i.e., the formal power series variable). Step 3) Calculate the adjoint equation based on Step 2. The formula is: S j Represents the j-th adjoint (j ranges from 1 to 2t, where t is the error correction capability); R(α) j ) denotes polynomial evaluation; ∑ denotes summation; ri This represents the i-th byte of the received data codeword; (α) j ) is the j-th power of the fundamental element α in the Galois field; (α) j ) i The i-th power represents the check point; r i ·(α j ) i This represents the weighted contribution (the contribution of the i-th data byte to the j-th syntactic word); the formula calculates whether an error exists in the received codeword and quantifies the degree of the error. Step 4) Using the Berlekamp-Massey algorithm, construct the error localization polynomial based on the adjoint equation obtained in Step 3. The algorithm iterative process is as follows: for r from 1 to 2t (i.e., 4 steps), the difference formula is calculated as follows: , where ∆ r S represents the difference in the r-th iteration; r Denotes the r-th syndrome; Λ i S represents the coefficient of the i-th polynomial in the current Λ(x); r-i Let Δ represent the (ri)th adjoint sequence; this formula measures how well the current Λ(x) fits the adjoint sequence; when Δ=0, it means that the current Λ(x) can correctly predict S. r, When Δ≠0, then Λ(x) needs to be corrected; Step 5) Update the polynomial based on step 4). The update rules are divided into two cases, as detailed below: 1. When Δ=0, then B(x)=x*B(x); otherwise, let T(x)=Λ(x)-Δ*x*B(x); 2. When 2L≤r-1, then B(x)=Λ(x) / Δ (in the Galois field, division is multiplication by the inverse), L=rL, δ=Δ; otherwise (i.e., when 2L≤r-1 is not satisfied), let B(x)=x*B(x), and then set Λ(x)=T(x); where Δ represents the difference; L represents the current error estimate; Λ(x) represents the error location polynomial; B(x) represents the auxiliary polynomial (used to update the coefficients of the error location polynomial); r represents the iteration number; T(x) represents the temporary polynomial (used to temporarily store the updated polynomial); δ represents the difference from the previous iteration. Step 6) Based on steps 4)-5), use Chien search to locate the roots of the error-locating polynomial, thereby determining the specific error point. The search process is as follows: for each position i (from 0 to n-1), calculate: Λ(α -i )=1+Λ1α -i +Λ2α -2i +...+Λ t α -ti Where Λ represents the mislocation polynomial, when Λ(α)-i When ) = 0, it indicates an error at position i (e.g., Λ(α)). -3 =0 indicates an error at position 3); Step 7) Based on Step 6, use the Forney algorithm to calculate the error value corresponding to each error location. The process includes calculating the error value polynomial → calculating the formal derivative of the error location polynomial → calculating the error value. The formula for calculating the error value polynomial is: Ω(x) = [S(x)Λ(x)] mod x 2t Where Ω(x) represents the error value polynomial (containing error value information, used to calculate the specific error value); S(x) represents the adjoint polynomial; Λ(x) represents the error location polynomial; x 2t The expression represents a modular polynomial (limiting the degree of the polynomial to ensure that the degree of Ω(x) is less than 2t); mod represents the modular operation; the formal derivative formula of the polynomial used for calculating error location is: Where Λ′(x) represents the formal derivative polynomial; i represents the polynomial term index; Λi represents the coefficient of the i-th term of the error-locating polynomial (i.e., the coefficient of Λ(x)); i·Λi represents the coefficient multiplied by the index; v represents the actual error estimate; the formula for calculating the error value is: , where e k X represents the k-th error value; k Indicates the k-th error location; (X k -1 ) represents the inverse position of the error location; Ω(X) k -1 ) represents the error-valued polynomial in (X k -1 The value at ); Λ′(X k -1 ) represents the derivative polynomial in (X) k -1 The value at () is determined by the formula, which is based on Galois domain division. The specific error value is determined by the formula. Step 8) Based on step 7), correct each error value. The method is to traverse each error position and add the error value to the corresponding position of the received data to correct the error.
[0033] The above process of writing all data into the EEPROM involves reading the final small bucket energy value, the large bucket data in the EEPROM, and the original small bucket data, recalculating the large bucket data (new large bucket data = original large bucket data + final small bucket energy value), further clearing the small bucket data (all 12 bytes cleared to 0), and rewriting the new data into the EEPROM.
[0034] In specific implementation, during the power-on initialization detection and processing stage, the construction of the transaction log includes extracting the status log from the EEPROM, further embedding the offline-trained lightweight decision tree model into the firmware in the form of parameters, and initializing the parameters.
[0035] In specific implementation, the offline training and embedding of the lightweight decision tree model includes the following steps: Step 1) Collect data from the transaction log, including features and tags; Step 2) Select the features related to the cause of the power outage; Step 3) Select the lightweight decision tree model CART and train it; Step 4) Evaluate the model's performance and perform pruning optimization to lighten the model; Step 5) Convert the trained model into code that can run on the MCU.
[0036] The features to be collected in step 1) above include voltage trends (mean and variance of the most recent ADC readings), task execution timestamps (mean and variance of the time intervals between the most recent task executions), watchdog reset counts (number of watchdog resets in the recent period), pre-write transaction log integrity (number of entries in the most recent pre-write log, and whether they are complete), soft error counts (number of soft errors in the most recent power-on initialization), hard error counts (number of hard errors in the most recent power-on initialization), power data change rate (growth rate of power data in the recent period), and timestamps (time from the last time it was saved to the present). The tags include power failure (normal power loss), software error (watchdog reset and program crash), hardware failure (voltage anomaly and memory error), and unknown cause.
[0037] Step 2) above discretizes the features from step 1), and further uses mutual information to calculate the correlation between each feature and the label. The calculation process involves calculating the marginal distribution probability, calculating the joint distribution probability, and calculating the mutual information. The marginal formula for calculating the marginal distribution probability x is: Where p(x) represents the marginal probability of the random variable x; the marginal formula for further calculating y is: Where p(y) represents the marginal probability of the random variable y; the joint probability distribution is further calculated using the formula: Where p(x, y) represents the joint probability distribution; further, the mutual information is calculated using the following formula:
[0038] Where I(X;Y) is the mutual information value between feature X and label Y; X represents the input feature variable; Y represents the target label (reason for power failure); p(x,y) represents the joint probability distribution (calculated above); log represents the logarithmic function; p(x) represents the marginal probability of random variable x (calculated above); p(y) represents the marginal probability of random variable y (calculated above). The ratio of the joint probability p(x,y) to the independent probabilities p(x)p(y) (the purpose of taking the logarithm is to convert the probability ratio into information content); the mutual information value calculated by the formula is used to select features related to the cause of the power outage.
[0039] Step 3) above, based on step 2), training starts from the root node. For each node, iterates through all features and all possible split points, calculates the Gini impurity after splitting, selects the optimal splitting feature and threshold, and the splitting rule is: for each feature A and its possible values s, split the dataset D into two subsets D1 and D2; where D1 = {(x, y) ∈ D | xA ≤ s}; D2 = {(x, y) ∈ D | xA > s}; the formula for calculating the Gini impurity after splitting is: Where Gini basis (D, A, s) represents the Gini impurity after splitting; D represents the integrated training subset; A represents the currently considered feature; s represents the split point of the feature; |D1| and |D2| represent the number of samples in subsets D1 and D2; Gini(D1) and Gini(D2) represent the Gini impurities of subsets D1 and D2; and represent the proportions of subsets D1 and D2 in the original dataset D, respectively; further, the node is split into two child nodes according to the optimal split, and the above steps are recursively performed on the child nodes until a stopping condition is met, the stopping condition including: (1) The number of samples in a node is less than the preset minimum value (set to 15); (2) All features cannot be further split (all samples in the node belong to the same class); (3) The decision tree reaches its maximum depth (set to 4).
[0040] Step 4) Based on the decision tree model trained in step 3), starting from the trained tree, generate a series of pruned trees from the current tree to the root node; for each pruned tree, calculate the accuracy on the validation set, and the accuracy calculation formula is: Where Aaccuracy represents the accuracy calculation result; TP represents true positives (i.e., the number of samples that are actually positive and correctly predicted as positive); TN represents true negatives (i.e., the number of samples that are actually negative and correctly predicted as negative); FP represents false positives (i.e., the number of samples that are actually negative but incorrectly predicted as positive); FN represents false negatives (i.e., the number of samples that are actually positive but incorrectly predicted as negative). The complexity of the model is further evaluated using the node complexity formula: CScomplexity = α × Nnodes + β × Ddepth + γ × AFaverage, where CScomplexity represents node complexity; Nnodes represents the total number of nodes in the decision tree; Ddepth represents the maximum depth of the decision tree; AFaverage represents the average number of features used; α represents the total node weight coefficient; β represents the maximum depth weight coefficient; and AFaverage represents the weight coefficient of the average number of features used. The weight allocation is 0.6 → 0.3 → 0.1. The tree with the highest accuracy and the fewest nodes on the validation set is selected. The pruning is performed by progressively pruning the nodes with the smallest α value.
[0041] Step 5 above extracts the tree structure (including the splitting features and thresholds of each non-leaf node, and the predicted category of the leaf node) from the trained decision tree model; further converts the tree structure into if-else statements in C code; considering the limitations of embedded systems, optimizes the code (using fixed-point numbers instead of floating-point numbers and reducing memory usage); completes the offline training of the lightweight decision tree model.
[0042] In specific implementation, during the timed data detection phase, the triggering conditions include threshold conditions and recording time, and the triggering conditions are dynamically adjusted using an adaptive algorithm.
[0043] In specific implementation, during the timed data detection phase, the log-first WAL mechanism is used to write the operation log into the circular buffer of the EEPROM before the small bucket data is stored in the EEPROM. In the event of a sudden power failure, the data is recovered from the operation log, and the status parameters are further recorded and saved to the status log to update the transaction log.
[0044] The initial values for the above threshold conditions and recording time are as follows: If any electrical energy data exceeds the threshold (initial threshold 50 kWh, adjusted according to the adaptive threshold algorithm); The time difference between the current time and the last recorded time is 30 minutes; The logical steps of the adaptive threshold algorithm are as follows: Step 1) Current threshold = base threshold × (1 - α × recent power outage count), where α is the attenuation factor (set to 0.1), the base threshold is 50 degrees, and the recent power outage count is obtained from the system status log; Step 2) Perform condition judgment: if any electrical energy data in the bucket exceeds the current threshold, or if the time interval reaches 30 minutes, then perform the Write-Ahead Log (WAL) operation; otherwise, exit. Step 3) Before writing to the EEPROM, write the pre-write log to the circular buffer of the EEPROM. The pre-write log includes: periodically saving the current operation, the current timestamp, the current small bucket data (before accumulation), the current large bucket data (before accumulation), and the checksum (CRC32). Step 4) Accumulate the data from the small bucket into the large bucket, where the new large bucket data = the original large bucket data + the small bucket data, and clear the small bucket data (i.e. set it to 0). Write the new large bucket data and the cleared small bucket data into the main data area of the EEPROM; further record the operation log for this operation and update the system transaction log; after the operation is completed, mark the corresponding entry in the pre-write log as completed.
[0045] In specific implementation, during the power outage processing phase at any time, a heartbeat monitoring mechanism is used to periodically check the health status through timer interrupts. When heartbeats are lost multiple times in a row, a pre-power outage mechanism is triggered to perform data saving operations in advance. Furthermore, operation logs and status logs are recorded based on the context to update the transaction log.
[0046] The above utilizes a heartbeat monitoring mechanism to periodically check the health status via a timer interrupt. Its power-down detection includes hardware power-down detection and software heartbeat monitoring. The hardware power-down detection method generates an interrupt through a power monitoring circuit, triggered when the voltage falls below a threshold (when the 3V3 power supply voltage drops to 3.079V, the voltage at the LVD pin after voltage division is below the detection threshold of 1.04V). The software heartbeat monitoring implementation includes the following steps: Step 1) Set the initial parameters of the heartbeat mechanism as follows: heartbeat counter H (initially 0), heartbeat timeout threshold TIMEOUT (5 times), and heartbeat interval INTERVAL (100ms). Step 2) Periodically reset the heartbeat counter in the main loop; Step 3) The high-priority timer interrupt service routine (ISR) decrements the heartbeat counter by 1 every 100ms; Step 4) When the heartbeat counter drops to 0, it indicates that the system has lost response, triggering the pre-power-down process.
[0047] In specific implementation, during the abnormal recovery phase, after the reset operation is executed, the lightweight decision tree model is loaded; features are further extracted from the transaction log, including voltage drop slope, task execution interval and log integrity before writing, and the features are input into the decision tree model for reasoning, and the result outputs a power outage probability distribution vector. The cause of the power outage is further analyzed based on the probability distribution vector, and the data recovery strategy is adjusted.
[0048] The specific implementation steps for extracting features from transaction logs and using a lightweight decision tree model to predict the cause of power outages are as follows: Step 1) Input the features into the lightweight decision tree model. At this time, the output of the model is a 4-dimensional probability distribution vector, which corresponds to the probabilities of the four power failure reasons as [P1 power failure, P2 software error, P3 hardware failure, P4 unknown error]; Step 2) Dynamically adjust the response strategy. The strategy is as follows: P1 lowers the power threshold for timed saving and increases the saving frequency to cope with unstable power supply; P2 increases the watchdog timeout time and adjusts the task scheduling strategy to avoid software dead loop; P3 increases the hardware self-test frequency and records detailed logs for diagnosis; and P4 maintains the original strategy to record anomalies to the transaction log. Step 3) Record the probability distribution of the cause of this power outage and the strategy adopted into the EEPROM for subsequent model optimization and fault analysis to complete the closed loop.
[0049] Working principle: After the system powers on, it performs non-zero detection and double verification on the small bucket data, then reads all power data and stores it in EEPROM. A pre-trained lightweight decision tree model is then embedded into the system firmware, and a transaction log is constructed. Based on the real-time accumulated power data, a scheduled task is created and trigger conditions are set. When the conditions are triggered, the small bucket data is cleared to zero, and the large and small bucket data are written to EEPROM, updating the transaction log. Based on a heartbeat monitoring mechanism, the health status is periodically checked via timer interrupts. When multiple consecutive heartbeats are lost, data is pre-stored to ensure timely data preservation and transaction log updates during power outages. When power is restored, the initialization phase recovers data. The pre-trained lightweight decision tree model is then used to predict the cause of the power outage. The model outputs four possible causes of power outages, and the strategy is adaptively adjusted based on each cause to avoid power outage events. Finally, the probability distribution of the causes of power outages and the adopted strategies are recorded in EEPROM for subsequent model optimization and fault analysis to complete the closed-loop process.
[0050] Those skilled in the art will recognize that the modules, units, and algorithm implementation steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of electronic hardware and software. 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.
Claims
1. A method for secure storage of electrical energy data based on power failure detection and cache compression, characterized in that, The method specifically includes: During the power-on initialization detection and processing phase, the small bucket data is read for non-zero detection and CRC verification. An error correction code is added to the CRC verification, and a transaction log is constructed, including a status log and an operation log. Based on the verification results, the final energy value is restored. The restoration strategy is as follows: if the CRC verification result is true, the final energy data is the energy value output by the CRC verification; if the CRC verification result is false and the RS verification result is true, the final energy data is the energy value output by the RS verification, plus the soft error count; if both verification results are false, the current soft error count equals the previous soft error count plus 1, and the small bucket data is set to 0. Finally, the final small bucket energy value is output, and the soft error count and transaction log are updated. All data is written to the EEPROM. The implementation process is as follows: the final small bucket energy value, the large bucket data in the EEPROM, and the original small bucket data are read; the large bucket data is recalculated, and the new large bucket data equals the original large bucket data plus the final small bucket energy value; the small bucket data is further cleared, and the new data is rewritten to the EEPROM. During the timed data detection phase, based on the real-time accumulated power data, timed detection is performed and trigger conditions are set. When the conditions are triggered, the data in the small bucket is cleared to 0, and the data in the large bucket and the small bucket are written to the EEPROM. During the power failure handling phase at any time, after detecting a power failure event, the small bucket data is stored in EEPROM and the small bucket data in RAM is cleared, and the system enters sleep mode. During the abnormal recovery phase, the data in the small bucket is set to the NO-init area of RAM to ensure that the memory data at the corresponding address is not cleared to 0 when a reset occurs. Data recovery is performed by executing the power-on initialization detection and processing program. The electrical energy data, totaling 424 bytes, is backed up, including small bucket data and large bucket data; Each data item in the bucket is stored using the INT16U data type; Each data item in the large data bucket is stored using the INT32U data type; During the power-on initialization detection and processing phase, the construction of the transaction log includes extracting the status log from the EEPROM, embedding the offline-trained lightweight decision tree model into the firmware in the form of parameters, and initializing the parameters. During the timed data detection phase, the log-first WAL mechanism is used to write the operation log into the circular buffer of the EEPROM before the small bucket data is stored in the EEPROM. In the event of a sudden power failure, the data is recovered from the operation log, and the status parameters are further recorded and saved to the status log to update the transaction log. The offline training and embedding of the lightweight decision tree model includes the following steps: Step 1) Collect data from the transaction log, including features and tags; Step 2) Select the features related to the cause of the power outage; Step 3) Select the lightweight decision tree model CART and train it; Step 4) Evaluate the model's performance and perform pruning optimization to lighten the model; Step 5) Convert the trained model into code that can run on the MCU; During the anomaly recovery phase, after the reset operation is executed, the lightweight decision tree model is loaded; features are further extracted from the transaction log, including voltage drop slope, task execution interval, and log integrity before writing. The features are input into the decision tree model for inference, and the result outputs a power outage probability distribution vector. The cause of the power outage is further analyzed based on the probability distribution vector, and the data recovery strategy is adjusted.
2. The method for secure storage of electrical energy data based on power failure detection and cache compression according to claim 1, characterized in that, In the timed data detection phase, the triggering conditions include threshold conditions and recording time, and the triggering conditions are dynamically adjusted using an adaptive algorithm.
3. The method for secure storage of electrical energy data based on power failure detection and cache compression according to claim 1, characterized in that, During the power failure handling phase at any time, a heartbeat monitoring mechanism is used to periodically check the health status through timer interrupts. When a heartbeat is lost multiple times in a row, a pre-power failure mechanism is triggered to perform data saving operations in advance. Furthermore, operation logs and status logs are recorded based on the context to update the transaction log.
Citation Information
Patent Citations
Method for managing high reliability of electric energy measurement data
CN101923112A
Method and system for prolonging service life of FLASH simulation EEPROM in single-chip microcomputer
CN121011238A