Hierarchical sleep and wake-up control method, device and medium for battery-powered devices

CN122993119APending Publication Date: 2026-10-27SHENZHEN DAMO DAZHI CONTROL TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611491615.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-23
Publication Date
2026-10-27

AI Technical Summary

Technical Problem

当按键中断、无线指令、定时器事件与电池状态事件同时或接近同时产生时,各控制逻辑之间容易出现竞争和冲突,导致状态迁移不可预期

Benefits of technology

[0008]本发明提供一种电池供电设备的分级休眠与唤醒控制方法、设备及介质,将不同来源的外部事件触发信号封装为统一的事件信号并写入单一事件队列,使原始触发信号在进入调度框架前完成数据结构归一化,同时利用该队列的先进先出结构串行化存储事件信号,使多源并发事件在调度入口不产生资源竞争,确保事件源有序可靠。本发明的控制方法在调度时按队列顺序提取事件信号并投递至分层状态机,保证事件处理顺序与到达顺序一致,且每次仅处理一个事件,从根本上避免并发冲突导致的状态错乱。在确定状态迁移时,根据当前状态和事件信号控制分层状态机进行决策,使状态切换严格依据当前工作阶段和事件类型,每一类事件在当前状态下均具有确定的迁移结果。最后依据目标状态执行相应控制操作,将状态迁移结果准确转化为设备实际行为。本发明能够使电池供电设备面对多种工作状态和多类外部事件时能够保持确定、有序、可追溯的行为响应,从而为分级休眠与唤醒提供统一可靠的调度方案。进一步地,关断检测态中深度休眠子态与唤醒窗口子态的周期性切换,使设备在维持微安级平均功耗的同时保留对多源唤醒信号的周期性扫描;唤醒窗口时长根据按键唤醒一次性标志的状态和无线链路活动状态自适应延长,兼顾了按键长按确认操作与无线链路数据接收对窗口时长的需求。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122993119A_ABST
    Figure CN122993119A_ABST
Patent Text Reader

Abstract

The application discloses a hierarchical hibernation and wake-up control method and device of a battery-powered device and a medium, and relates to the technical field of battery management. The method comprises the following steps: in response to receiving an external event trigger signal, encapsulating the external event trigger signal as an event signal and writing the event signal into a single event queue; extracting the event signal in the order of the single event queue, and delivering the event signal to a hierarchical state machine; determining a target state after migration based on the current state of the hierarchical state machine and the event signal; and performing a control operation corresponding to the target state after migration according to the target state after migration. The control method can realize unified and reliable scheduling of multiple working states and multiple types of external events of the battery-powered device, and can balance low power consumption and responsiveness.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of battery management technology, and in particular to a hierarchical sleep and wake-up control method, device and medium for battery-powered devices. Background Technology

[0002] In long-term outdoor storage scenarios, battery-powered devices need to maintain extremely low power consumption to prevent over-discharge of the battery, while also retaining the ability to be woken up by buttons or wireless links. At the same time, there is also the issue of the lifespan degradation of lithium batteries when stored at full charge. These mutually restrictive requirements make power management a complex and challenging problem.

[0003] Currently, existing technologies generally only offer two states: running and deep sleep. There's a lack of effective differentiation between intermediate states such as battery pre-processing before long-term storage, periodic wake-ups, and shallow sleep. Multiple functions, such as discharge management, charging detection, and wake-up source determination, are controlled by independent logic, lacking unified coordination. When button interruptions, wireless commands, timer events, and battery status events occur simultaneously or nearly simultaneously, competition and conflicts easily arise between the control logics, leading to unpredictable state transitions. For example, the device might respond to a button wake-up while performing discharge management, or remain in deep sleep when charging is connected. These abnormal behaviors cause the device to either experience uncontrolled power consumption or fail to reliably respond to external operations during long-term storage. Furthermore, after an external interruption wake-up, the device lacks differentiation between different wake-up sources, treating all wake-ups the same, further exacerbating the confusion in state decisions. These deficiencies result in unpredictable device behavior during long-term storage, making it impossible to balance power consumption and responsiveness. Summary of the Invention

[0004] This invention provides a hierarchical hibernation and wake-up control method, device, and medium for battery-powered devices. The technical problem it aims to solve is: how to achieve unified and reliable scheduling of various working states and external events of battery-powered devices.

[0005] In a first aspect, the present invention provides a hierarchical sleep and wake-up control method for a battery-powered device, comprising: In response to receiving an external event trigger signal, the external event trigger signal is encapsulated into an event signal and written into a single event queue; The event signals are extracted in the order of the single event queue and delivered to the hierarchical state machine. The hierarchical state machine includes a running state, a shallow sleep state, a shutdown detection state, and a discharge storage state. The shutdown detection state includes a wake-up window sub-state and a deep sleep sub-state. The event signals include a sleep command, a power-on command, a long-press button signal, a timeout signal, a power-off command, a discharge trigger signal, a discharge completion signal, a discharge abnormality signal, or a charging access signal. Based on the current state of the hierarchical state machine and the event signal, determine the target state after the transition; Execute control operations corresponding to the migrated target state according to the migrated target state, including: when the migrated target state is the deep sleep sub-state, obtain a first preset wake-up period and a first preset wake-up window duration; configure the timing period of the RTC wake-up timer to the first preset wake-up period; configure the microcontroller to a low-power mode with the kernel clock stopped, and keep the RTC wake-up timer and wake-up pin working; when the RTC wake-up timer expires, wake up the microcontroller, update the current state of the hierarchical state machine to the wake-up window sub-state, and initialize the wake-up window duration to the first preset wake-up window duration; when the migrated target state is the wake-up window sub-state, obtain the state of the button wake-up one-time flag and the wireless link activity state; determine whether the button wake-up one-time flag is set; if If the one-time wake-up flag is set, the duration of the current wake-up window is extended from the first preset wake-up window duration to the second preset wake-up window duration, and the one-time wake-up flag is cleared. The second preset wake-up window duration is longer than the first preset wake-up window duration. If the one-time wake-up flag is not set, the duration of the current wake-up window remains the first preset wake-up window duration. Within the current wake-up window, it is determined whether wireless link activity is detected based on the wireless link activity status. If wireless link activity is detected, the wake-up window sub-state is maintained until the wireless link activity ends and the current wake-up window ends, and then the current state of the hierarchical state machine is updated to the deep sleep sub-state. If no wireless link activity is detected and the current wake-up window ends, the current state of the hierarchical state machine is updated to the deep sleep sub-state.

[0006] Secondly, the present invention also provides a computer device including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the above-described method.

[0007] Thirdly, the present invention also provides a computer-readable storage medium storing a computer program that, when executed by a processor, can implement the above-described method.

[0008] This invention provides a hierarchical sleep and wake-up control method, device, and medium for battery-powered devices. External event trigger signals from different sources are encapsulated into a unified event signal and written into a single event queue. This ensures that the original trigger signals undergo data structure normalization before entering the scheduling framework. Simultaneously, the queue's first-in-first-out (FIFO) structure serializes the event signals, preventing resource contention at the scheduling entry point for concurrent events from multiple sources and ensuring the orderly and reliable operation of event sources. During scheduling, the control method extracts event signals according to the queue order and delivers them to the hierarchical state machine, ensuring that the event processing order matches the arrival order, and processing only one event at a time, fundamentally avoiding state confusion caused by concurrent conflicts. When determining state transitions, the hierarchical state machine makes decisions based on the current state and event signals, ensuring that state switching strictly follows the current working stage and event type, with each type of event having a definite transition result in the current state. Finally, corresponding control operations are executed based on the target state, accurately translating the state transition result into the actual behavior of the device. This invention enables battery-powered devices to maintain a definite, orderly, and traceable behavioral response when facing multiple working states and various types of external events, thus providing a unified and reliable scheduling scheme for hierarchical sleep and wake-up. Furthermore, the periodic switching between the deep sleep sub-state and the wake-up window sub-state in the shutdown detection state allows the device to maintain microampere-level average power consumption while retaining periodic scanning of multi-source wake-up signals; the wake-up window duration is adaptively extended according to the status of the one-time button wake-up flag and the wireless link activity status, taking into account the window duration requirements of both long-press confirmation operation and wireless link data reception. Attached Figure Description

[0009] To more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings used in the following description of the embodiments will be briefly introduced. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0010] Figure 1 A flowchart illustrating a graded sleep and wake-up control method for a battery-powered device provided in an embodiment of the present invention; Figure 2 This is a schematic block diagram of a computer device provided in an embodiment of the present invention. Detailed Implementation

[0011] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0012] It should be understood that, when used in this specification and the appended claims, the terms "comprising" and "including" indicate the presence of the described features, integrals, steps, operations, elements and / or components, but do not exclude the presence or addition of one or more other features, integrals, steps, operations, elements, components and / or collections thereof.

[0013] It should also be understood that the terminology used in this specification is for the purpose of describing particular embodiments only and is not intended to limit the invention. As used in this specification and the appended claims, the singular forms “a,” “an,” and “the” are intended to include the plural forms unless the context clearly indicates otherwise.

[0014] It should also be further understood that the term "and / or" as used in this specification and the appended claims refers to any combination of one or more of the associated listed items and all possible combinations, and includes such combinations.

[0015] As used in this 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 [described condition or event] is detected" may be interpreted, depending on the context, as "once determined," "in response to determination," "once [described condition or event] is detected," or "in response to detection of [described condition or event]."

[0016] Please see Figure 1 This invention provides a hierarchical sleep and wake-up control method for battery-powered devices. By introducing a single event queue and a hierarchical state machine, external events are unified as event signals and serially delivered to the state machine. The state machine determines the target state after the transition based on the current state and the event signals, and executes the corresponding control operations. This solves the competition and conflict problem when multiple event sources are concurrent, making the device behavior deterministic and traceable in different scenarios. Specifically, the method includes the following steps: S1, in response to receiving an external event trigger signal, encapsulate the external event trigger signal into an event signal and write it into a single event queue.

[0017] In practical implementation, a hierarchical state machine is deployed in the battery-powered equipment. This hierarchical state machine is used to uniformly schedule the behavior of the equipment at different working stages. The hierarchical state machine is an extension of a finite state machine, with its states organized in a tree-like hierarchical structure. The top-level state can contain several sub-states, and the sub-states inherit some behavioral characteristics from the parent state, enabling clear logical division of state management at different levels of abstraction. Furthermore, the battery-powered equipment also maintains a single event queue. This queue receives various external trigger signals and converts them into event signals of a unified format, storing the events to be processed serially. This allows events from different interrupt sources or detection modules to be queued according to their arrival order, avoiding resource contention and data loss caused by concurrent writes.

[0018] For example, in one specific implementation, the hierarchical state machine runs as a software module on a microcontroller, which can be an STM32U073 chip with a Cortex-M0+ core. A single event queue is implemented in the microcontroller's memory as a circular buffer. Each cell in the queue stores a data structure for an event signal, which includes at least an event type field, an event source identifier field, and a timestamp field indicating the event's occurrence. The event type field uses an enumerated type definition to distinguish different event types such as sleep commands, power-on commands, long-press button signals, timeout signals, power-off commands, discharge trigger signals, discharge completion signals, discharge abnormal signals, and charging access signals. The event source identifier field records whether the event was generated by a button interrupt, wireless link, software timer, or battery data determination. The timestamp field records the specific time the event occurred, provided by the real-time clock module. The write and read pointers of the circular buffer point to the tail and head of the queue, respectively. A write operation stores data at the write pointer position and then moves the write pointer; a fetch operation reads data from the read pointer position and then moves the read pointer. When the write pointer catches up with the read pointer, it means that the queue is full. At this time, newly arrived event signals can be discarded or blocked and waited for. In one specific implementation, a blocking and waiting strategy is adopted, that is, the write operation waits in a loop until there is a free unit in the queue.

[0019] Furthermore, when the battery-powered device receives an external event trigger signal, it encapsulates the external event trigger signal into an event signal and writes it into a single event queue in response to the signal. The external event trigger signal refers to the original trigger signal from an external or internal detection module of the device, and its form can be a hardware interrupt signal, a timer expiration signal, or a software determination result signal. For example, the external event trigger signal can come from a rising edge interrupt of a button pin, a control command received from a wireless link, an expiration interrupt of an RTC wake-up timer, or a voltage and current determination result obtained periodically by the battery management unit; this invention does not specifically limit this. The encapsulation operation refers to converting the original trigger signal into an event signal with a unified data structure, which includes an event type identifier, event source information, and a timestamp of the event occurrence time. The encapsulated data is appended to the tail of the single event queue. The single event queue adopts a first-in, first-out data structure to ensure that event signals are processed sequentially according to their arrival order. The unified format of the event signal facilitates consistent processing of all types of events by the hierarchical state machine, without distinguishing the original source of the event.

[0020] S2, extract the event signals according to the order of the single event queue, and deliver the event signals to the hierarchical state machine.

[0021] In practice, event signals are extracted sequentially from a single event queue and then delivered to the hierarchical state machine. The extraction operation retrieves an event signal from the head of the single event queue; this event signal is the current event to be processed. The delivery operation uses this event signal as an input parameter to the hierarchical state machine, triggering the hierarchical state machine to perform state transition determination. Upon receiving an event signal, the hierarchical state machine determines whether a state transition should occur based on the event signal type and the current state, according to a predefined state transition table. The state transition table records the target state corresponding to each event signal in each current state. This table is stored in the microcontroller's non-volatile memory as an array or lookup table during system initialization. Furthermore, if the event signal in the current state has a corresponding transition target, the state machine performs the transition; if the event signal in the current state does not have a corresponding transition target, the state machine ignores the event signal and maintains the current state. The current state of the state machine is stored in the state machine context structure, which updates the current state field after each transition. The state machine context structure also contains other auxiliary information, such as the cumulative value of state dwell time, the remaining duration of the current wake-up window, and a one-time wake-up flag for button presses.

[0022] S3. Based on the current state of the hierarchical state machine and the event signal, determine the target state after the transition.

[0023] In practice, the current state of the hierarchical state machine is stored in the state machine context, which is updated after each transition. The current state value is read, combined with the event type of the event signal, and the state transition table is consulted to obtain the corresponding target state, which is the target state after the transition. The state transition table is pre-configured during system initialization, and its contents are determined according to the behavioral requirements of the device at different operating stages. The target state corresponds to the operating mode the device is about to enter, and each operating mode has a specific power consumption level and functional enable state.

[0024] In one specific implementation, the hierarchical state machine includes four top-level states: running state, shallow sleep state, shutdown detection state, and storage / discharge state. Each top-level state can contain several sub-states, and these sub-states can be switched without changing the top-level state. Specifically, the running state is the working state where the device normally executes its business functions. In this state, the microcontroller runs at full speed, the clocks of all functional peripherals are enabled, and the device consumes a relatively high amount of power. The shallow sleep state is an intermediate power consumption state where the clocks of some peripherals are turned off, but the microcontroller core continues to run, enabling a rapid response to wake-up signals. The shutdown detection state is a lower power consumption state where the device maintains a minimum level of wakeability through periodic wake-ups. The storage / discharge state is the working state where the device performs controlled discharge before storing the battery.

[0025] The event signals include sleep command, power-on command, long press signal, timeout signal, power-off command, discharge trigger signal, discharge completion signal, discharge abnormality signal, and charging access signal, each originating from a different trigger source.

[0026] During the determination process, an event signal is extracted from a single event queue and its type identifier is read. Simultaneously, the current state value in the state machine context is read. The combination conditions of the current state of the hierarchical state machine and the event signal are checked in a preset order. If the conditions are met, the corresponding transition target is determined. Unlisted state and event combinations do not trigger transitions by default, and the device remains in its current state.

[0027] The specific determination process includes: determining whether the current state of the hierarchical state machine is the running state and whether the event signal is the sleep command; if the current state of the hierarchical state machine is the running state and the event signal is the sleep command, then the transitioned target state is determined as the shallow sleep state; determining whether the current state of the hierarchical state machine is the shallow sleep state and whether the event signal is the power-on command or the long-press button signal; if the current state of the hierarchical state machine is the shallow sleep state and the event signal is the power-on command or the long-press button signal, then the transitioned target state is determined as the running state; determining the hierarchical state... The system checks whether the current state of the hierarchical state machine is the shallow sleep state and whether the event signal is the timeout signal or the shutdown command; if the current state of the hierarchical state machine is the shallow sleep state and the event signal is the timeout signal or the shutdown command, then the migrated target state is determined as the shutdown detection state; the system checks whether the current state of the hierarchical state machine is the running state and whether the event signal is the shutdown command or the long press signal; if the current state of the hierarchical state machine is the running state and the event signal is the shutdown command or the long press signal, then the migrated target state is determined as the shutdown detection state; the system checks whether the hierarchical state... The current state of the machine is determined to be the shutdown detection state and the event signal is the power-on command or the long-press button signal. If the current state of the hierarchical state machine is the shutdown detection state and the event signal is the power-on command or the long-press button signal, then the migrated target state is determined to be the running state. The current state of the hierarchical state machine is determined to be the shutdown detection state and the event signal is the discharge trigger signal. If the current state of the hierarchical state machine is the shutdown detection state and the event signal is the discharge trigger signal, then the migrated target state is determined to be the storage discharge state. The current state of the hierarchical state machine is determined to be... The system determines whether the current state of the hierarchical state machine is the storage discharge state and whether the event signal is the discharge completion signal or the discharge abnormal signal; if the current state of the hierarchical state machine is the storage discharge state and the event signal is the discharge completion signal or the discharge abnormal signal, then the migrated target state is determined as the shutdown detection state; the system determines whether the current state of the hierarchical state machine is the shutdown detection state or the storage discharge state and whether the event signal is the charging access signal; if the current state of the hierarchical state machine is the shutdown detection state or the storage discharge state and the event signal is the charging access signal, then the migrated target state is determined as the shallow sleep state.

[0028] In other words: In running mode, upon receiving a hibernation command, it enters a shallow hibernation state; upon receiving a power-off command or a long-press button signal, it enters a shutdown detection state. In shallow hibernation state, upon receiving a power-on command or a long-press button signal, it returns to running mode; upon receiving a timeout signal or a power-off command, it enters a shutdown detection state. In shutdown detection state, upon receiving a power-on command or a long-press button signal, it returns to running mode; upon receiving a discharge trigger signal, it enters a discharge storage state; upon receiving a charging access signal, it enters a shallow hibernation state. In discharge storage state, upon receiving a discharge completion signal or a discharge abnormality signal, it returns to the shutdown detection state; upon receiving a charging access signal, it enters a shallow hibernation state.

[0029] In other words, the shutdown detection state is an intermediate decision point. It may return to the running state due to power-on or a long press, enter the storage discharge state due to discharge, or directly return to the shallow sleep state due to charging access. The storage discharge state mainly returns to the shutdown detection state after completing discharge, or enters the shallow sleep state when charging access is detected during discharge. Unlisted state and event combinations do not trigger migration by default, and the device maintains its current state.

[0030] This embodiment determines the target state after migration by judging the combination of the current state and event signals one by one, forming a complete state transition determination link. The specific implementation method is as follows: The current state of the hierarchical state machine is stored in the state machine context variable. After retrieving an event signal from a single event queue, the type identifier of the event signal is read, and the current state value in the state machine context is read. Following a preset decision order, various combinations of the current state and event signals are checked sequentially, and the corresponding transition target is determined when the conditions are met.

[0031] Furthermore, it is determined whether the current state of the hierarchical state machine is in the running state and whether the event signal is a sleep command. A sleep command is a control command issued by the flight control link or the host computer, used to instruct the device to transition from normal operation to a low-power state. The flight control link refers to the communication link between the UAV flight controller and the parachute controller; this link can use wired serial communication or wireless communication. If the current state of the hierarchical state machine is in the running state and the event signal is a sleep command, then the transitioned target state is determined to be a shallow sleep state.

[0032] Further, it is determined whether the current state of the hierarchical state machine is in a shallow sleep state and whether the event signal is a power-on command or a long-press button signal. The power-on command is a control command issued by the flight control link or the host computer, used to instruct the device to return from a low-power state to a normal operating state. The long-press button signal is a signal triggered by an external button on the device, generated when the button is continuously pressed for more than a preset duration threshold. The long-press button signal is generated as follows: the button is connected to the external interrupt pin of the microcontroller. When a rising edge is detected on this pin, a debouncing timer is started. The debouncing timer is used to filter out multiple level transitions caused by button mechanical jitter. The duration of the debouncing timer is typically set to 10ms to 50ms. If the button is still pressed after the debouncing timer expires, a valid button event is confirmed; if the duration of the pressed state exceeds the preset long-press threshold, for example, 2 seconds, a long-press button signal is generated. If the current state of the hierarchical state machine is in a shallow sleep state and the event signal is a power-on command or a long-press button signal, the target state after the transition is determined to be the running state.

[0033] Further, it is determined whether the current state of the hierarchical state machine is a shallow sleep state and whether the event signal is a timeout signal or a shutdown command. The timeout signal is generated when a software timer expires, indicating that the device has remained in the shallow sleep state for a preset duration threshold. A timeout timer is started at the shallow sleep state entry point, with its timeout set to a preset threshold, such as 5 minutes. A timeout signal is generated when this timer expires. The shutdown command is a control command issued by the flight control link or a host computer, indicating that the device enters a deeper shutdown state. If the current state of the hierarchical state machine is a shallow sleep state and the event signal is a timeout signal or a shutdown command, then the target state after the transition is determined as the shutdown detection state.

[0034] Furthermore, it is determined whether the current state of the hierarchical state machine is in the running state and whether the event signal is a power-off command or a long-press button signal. If the current state of the hierarchical state machine is in the running state and the event signal is a power-off command or a long-press button signal, then the target state after the transition is determined to be the shutdown detection state. This transition path allows the operator to directly switch the device to a deep shutdown state during normal operation by pressing and holding a button or by using flight control commands, without needing to go through the intermediate transition of a shallow sleep state.

[0035] Furthermore, it is determined whether the current state of the hierarchical state machine is in a shutdown detection state and whether the event signal is a power-on command or a long-press button signal. If the current state of the hierarchical state machine is in a shutdown detection state and the event signal is a power-on command or a long-press button signal, then the target state after the transition is determined to be the running state. This transition path allows the device to be woken up to normal operation by pressing an external button or a flight control command even in a deep shutdown state. In the shutdown detection state, a button interrupt can wake up the microcontroller from the low-power mode. After waking up, the state machine reads the long-press button signal and executes the transition to the running state.

[0036] Further, it is determined whether the current state of the hierarchical state machine is a shutdown detection state and whether the event signal is a discharge trigger signal. The discharge trigger signal is a signal generated by the internal logic of the device, used to indicate that the device needs to start performing a pre-storage discharge operation. The generation conditions for the discharge trigger signal are that the accumulated storage time in the shutdown detection state reaches a preset storage time threshold, and the battery voltage meets the preset trigger conditions. If the current state of the hierarchical state machine is a shutdown detection state and the event signal is a discharge trigger signal, then the target state after the transition is determined to be the storage discharge state.

[0037] Furthermore, it is determined whether the current state of the hierarchical state machine is in the discharge storage state and whether the event signal is a discharge completion signal or a discharge abnormality signal. The discharge completion signal is generated when the battery voltage drops below the preset normal termination voltage, indicating that the discharge process has ended normally. The discharge abnormality signal is generated when abnormal conditions such as overcurrent, open circuit, backflow, or excessive differential voltage between individual cells are detected during the discharge process, indicating that the discharge process has terminated due to an abnormality. If the current state of the hierarchical state machine is in the discharge storage state and the event signal is a discharge completion signal or a discharge abnormality signal, the target state after migration is determined to be the shutdown detection state. This migration path ensures that regardless of whether the discharge process completes normally or terminates abnormally, the device returns to the shutdown detection state to continue low-power standby.

[0038] Further, it is determined whether the current state of the hierarchical state machine is a shutdown detection state or a discharge storage state, and whether the event signal is a charging access signal. The charging access signal is a signal generated by the battery current detection logic, used to indicate that the device has detected an external charger connection. When an external charger is connected, the battery current direction changes from the discharge direction to the charging direction, and the current value changes from negative to positive. If the current state of the hierarchical state machine is a shutdown detection state or a discharge storage state, and the event signal is a charging access signal, then the target state after the transition is determined to be a shallow sleep state. This transition path allows the device to automatically exit the deep shutdown or discharge state and enter the shallow sleep state when charging is accessed, preparing to execute further runtime wake-up operations.

[0039] After completing the above state transition determination, the target state after the transition is obtained. This target state is used to trigger the execution of subsequent control operations.

[0040] In one specific implementation, the operating state of the hierarchical state machine further includes two sub-states: a ready-to-launch state and a locked state. The ready-to-launch state further includes a parachute compartment closure sub-state and a parachute compartment opening sub-state, and the locked state further includes a protection electronics-on state and a protection electronics-off state. These sub-states are used to subdivide the business stages within the operating state. The switching between sub-states is controlled by the logic within the operating state and does not involve the migration between top-level states. Within the operating state, the device switches between the ready-to-launch state and the locked state according to the business logic. In the ready-to-launch state, the device is in a standby launch state, and in the locked state, the device is in a safety locked state. The parachute compartment closure and parachute compartment opening sub-states within the ready-to-launch state correspond to the two physical states of the UAV parachute controller: parachute compartment closure and parachute compartment opening, respectively. The protection electronics-on state and protection electronics-off state within the locked state correspond to the two states of the protection circuit: power-on and power-off, respectively. The switching of these sub-states does not affect the top-level state migration determination logic described in this embodiment. The top-level state migration determination only focuses on the switching between the four top-level states: operating state, shallow hibernation state, shutdown detection state, and storage discharge state.

[0041] This embodiment sets four state levels: running state, shallow sleep state, shutdown detection state, and storage discharge state, enabling battery-powered devices to operate at appropriate power consumption levels in different scenarios. The transition paths between states cover multiple stages, including normal operation, low-power standby, deep sleep, and pre-storage discharge, avoiding the contradiction between power consumption and functionality that exists in existing solutions with only two or three states. By judging various combinations of the current state and event signals, the system can accurately respond to multiple events, providing complete logical coverage for state transition decisions. Furthermore, a bidirectional transition mechanism is introduced between the shutdown detection state and the storage discharge state, allowing the storage discharge process to be executed independently of the shutdown detection, while automatically returning to the shutdown detection state after discharge completion or an anomaly, achieving seamless integration between pre-storage preprocessing and long-term low-power standby. The path for the charging access signal to transition from the shutdown detection state or storage discharge state to the shallow sleep state ensures that the device can automatically wake up and prepare to enter the running state when external charging is connected, without manual intervention. The complete description of all transition branches ensures the determinism and verifiability of the state machine behavior. The decision order of the state transition table has been optimized, placing the most frequently occurring transition conditions at the beginning of the decision sequence, reducing the average decision time and improving the throughput of the state machine. The sub-state division within the running state decouples the business logic within the running state from the top-level sleep / wake-up logic, facilitating independent development and testing.

[0042] S4, execute the control operation corresponding to the migrated target state according to the migrated target state.

[0043] In specific implementation, control operations refer to the sequence of actions executed after the device transitions to a target state. Examples include configuring the microcontroller's low-power mode, enabling or disabling the clock of a specific peripheral, adjusting the period of the RTC wake-up timer, and controlling the output level of general-purpose input / output pins to drive external switches. This invention does not specifically limit these actions. Each target state corresponds to a set of predefined control operations, which are triggered and executed by the state machine after the state transition is complete. The specific content of the control operations depends on the operating mode represented by the target state; different target states correspond to different power management strategies and peripheral management strategies. After executing the control operations, the hierarchical state machine completes one event processing cycle and waits for the next event signal to be extracted from and delivered from the single event queue.

[0044] In one specific implementation, the state machine operates using a polling scheduling method. The main loop continuously checks whether a single event queue is empty. If it is not empty, an event signal is extracted and processed. If it is empty, it enters a low-power waiting state.

[0045] This embodiment encapsulates external event trigger signals into event signals and writes them into a single event queue, enabling the standardized processing of multi-source heterogeneous events before they enter the state machine. This eliminates priority conflicts and concurrency competition between different interrupt sources. The single event queue guarantees the sequentiality and atomicity of event processing, ensuring that the state machine is not interrupted by newly arriving events while processing the current event, thus guaranteeing the determinism of the state transition process. The hierarchical state machine determines the transition target based on the current state and event signals, abstracting device behavior into a state- and event-driven transition model, making the behavioral logic clear and verifiable. Based on the target state after the transition, corresponding control operations are executed, achieving differentiated power consumption management and function configuration for the device in different operating modes. This method enables battery-powered devices to maintain necessary external wake-up capabilities with minimal power consumption in long-term storage scenarios, while responding quickly upon receiving valid operation signals. Furthermore, the unified data structure of the event signals includes three fields: event type, source identifier, and timestamp. This allows the state machine to not only identify the event type but also trace the event source and occurrence time, facilitating subsequent logging and troubleshooting. The pre-configuration of the state transition table makes the time complexity of state transition decisions constant, and the processing time of the state machine for each event is a definite finite value, ensuring the real-time performance of the system.

[0046] In some preferred embodiments, the shutdown detection state includes a wake-up window sub-state and a deep sleep sub-state; the step of performing control operations corresponding to the migrated target state according to the migrated target state includes: when the migrated target state is the deep sleep sub-state, obtaining a first preset wake-up period and a first preset wake-up window duration; configuring the timing period of the RTC wake-up timer to the first preset wake-up period; configuring the microcontroller to a low-power mode that stops the kernel clock, while keeping the RTC wake-up timer and wake-up pin working; when the RTC wake-up timer expires, waking up the microcontroller, updating the current state of the hierarchical state machine to the wake-up window sub-state, and initializing the wake-up window duration to the first preset wake-up window duration.

[0047] In this embodiment, the shutdown detection state is divided into two sub-states: the wake-up window sub-state and the deep sleep sub-state. The wake-up window sub-state is the state in which the device briefly wakes up during a deep sleep cycle to scan for wake-up sources, while the deep sleep sub-state is the state in which the device maintains minimum power consumption operation between two wake-up windows. In the shutdown detection state, the device uses the deep sleep sub-state as its primary resident state, only briefly switching to the wake-up window sub-state to perform detection when the RTC (Real-Time Clock) wake-up timer expires. When the hierarchical state machine determines that the target state after the transition is the deep sleep sub-state based on the current state and event signals, it executes the control operation sequence corresponding to entering the deep sleep sub-state.

[0048] Further, the first preset wake-up period and the first preset wake-up window duration are obtained. The first preset wake-up period refers to the time interval between two consecutive expirations of the RTC wake-up timer, used to control the frequency at which the device is periodically woken up from the deep sleep sub-state. The first preset wake-up window duration refers to the length of time the device remains in the wake-up window sub-state after each wake-up, used to limit the duration for detecting wake-up sources and service events after each wake-up. The first preset wake-up period and the first preset wake-up window duration are pre-configured parameters, read from non-volatile memory during system initialization or loaded from a configuration file. These parameters can be adjusted according to the actual application scenario to balance power consumption and responsiveness requirements. In one specific implementation, the first preset wake-up period is set to 2000ms, and the first preset wake-up window duration is set to 500ms. The value range of the first preset wake-up period is from 1ms to 31995ms, which can be adjusted according to the actual power consumption budget. The shorter the period, the higher the average power consumption and the lower the response latency; the longer the period, the lower the average power consumption and the higher the response latency. The value range of the first preset wake-up window duration can also be flexibly configured according to the actual application scenario. The shorter the window, the lower the average power consumption, but it may not be able to complete some business operations that require a longer time.

[0049] Furthermore, the timing period of the RTC wake-up timer is configured to a first preset wake-up period. The RTC wake-up timer is a timer included in the microcontroller's internal real-time clock module. This timer can run independently after the microcontroller enters low-power mode, and its clock source is independent of the system main clock, unaffected by the kernel clock stopping. The RTC wake-up timer generates a wake-up interrupt signal when its timing period arrives, which wakes the microcontroller from low-power mode. The configuration operation is achieved by writing to the relevant registers of the RTC wake-up timer, loading the timing period value into the RTC wake-up timer's period register. After configuration, the RTC wake-up timer begins counting down at the first preset wake-up period. For example, in one specific implementation, the clock source of the RTC wake-up timer is a low-speed clock inside the real-time clock module, which runs at a frequency of 32.768kHz in all low-power modes of the microcontroller and can generate millisecond-level precision timing interrupts through a frequency divider. The division factor of the frequency divider is calculated based on the target timing period. For example, for a timing period of 2000ms, the clock frequency of 32.768kHz needs to be divided to 0.5Hz, and the division factor is 65536.

[0050] Furthermore, the microcontroller is configured to a low-power mode with the core clock stopped, while keeping the RTC wake-up timer and wake-up pin active. Low-power mode refers to a microcontroller operating state in which the core clock is stopped and most peripheral clocks are turned off to reduce power consumption. In low-power mode with the core clock stopped, the microcontroller's quiescent current consumption is reduced to the microamp level. The RTC wake-up timer and wake-up pin are configured to remain active in low-power mode. The RTC wake-up timer remains active to ensure the periodic wake-up function executes correctly. The wake-up pin remains active so that external button trigger signals can generate an interrupt during microcontroller sleep, waking the device from low-power mode. For example, in one specific implementation, the low-power mode uses the STOP2 mode supported by the Cortex-M0+ microcontroller. STOP2 mode is a deep low-power mode in which the core clock and most system clocks are turned off, leaving only the real-time clock module and a few low-power peripheral clocks active. Before entering STOP2 mode, all unused peripheral clocks must be turned off, general-purpose input / output pins must be configured to appropriate levels to avoid leakage current, and the wake-up pin must be configured for external interrupt mode and its interrupt enabled. After the instruction execution enters STOP2 mode, the microcontroller kernel pauses instruction fetching, the system clock stops, and the chip power consumption is reduced to a minimum.

[0051] When the RTC wake-up timer expires, the microcontroller is woken up, the current state of the hierarchical state machine is updated to the wake-up window substate, and the wake-up window duration is initialized to the first preset wake-up window duration. The RTC wake-up timer expires when its countdown reaches zero, at which point the real-time clock module generates a wake-up interrupt signal. This interrupt signal causes the microcontroller to exit low-power mode, restore the kernel clock and system clock, and re-execute instructions. In response to this wake-up interrupt, the current state of the hierarchical state machine is updated from the deep sleep substate to the wake-up window substate. Simultaneously, a window duration timer is started, with its initial value set to the first preset wake-up window duration, and its count begins to decrease. This window duration timer controls the time the device remains in the wake-up window substate. When the window duration timer decreases to zero and no condition requiring an extension of the window is detected, the state is rolled back to the deep sleep substate. The window duration timer can reuse a general-purpose timer of the microcontroller, which starts immediately after wake-up and generates an interrupt upon expiration, performing a state rollback operation in the interrupt service routine.

[0052] In the deep sleep sub-state, the timing period of the RTC wake-up timer and the wake-up window duration jointly determine the device's average power consumption. Average power consumption is calculated as follows: within each wake-up cycle, the current consumed in the deep sleep sub-state multiplied by the deep sleep duration, plus the current consumed in the wake-up window sub-state multiplied by the wake-up window duration, and the sum divided by the wake-up cycle length, yields the average current. Furthermore, the actual power consumption level also depends on the complexity of the operations performed within the wake-up window; more complex operations result in higher current consumption. By optimizing the detection code executed within the wake-up window and reducing unnecessary peripheral accesses, average power consumption can be further reduced.

[0053] This embodiment further divides the shutdown detection state into two sub-states: the wake-up window sub-state and the deep sleep sub-state, thus clearly separating the sleep period and the wake-up window period in the periodic wake-up mechanism. When entering the deep sleep sub-state, the microcontroller is configured to a low-power mode with the kernel clock stopped, while maintaining the operation of the RTC wake-up timer and wake-up pin. This reduces the device's power consumption to the microampere level during sleep, while retaining two recovery methods: periodic self-wake-up and external button wake-up. The timing period of the RTC wake-up timer is configured to a first preset wake-up period, allowing the device to wake up from deep sleep at fixed intervals, ensuring that the device can periodically detect external events without long-term disconnection. After waking up, the state automatically switches to the wake-up window sub-state, and the wake-up window duration is initialized to the first preset wake-up window duration, providing a basis for subsequent event detection and adaptive window extension within the wake-up window. The cross-sleep cycle timing implemented through the RTC wake-up timer allows accumulated time information such as storage duration to continuously accumulate during deep sleep. Even if the system clock stops, the real-time clock module continues to maintain time counting, ensuring the accuracy of time-related determinations. This control sequence enables the device to establish a stable periodic switching between deep sleep sub-state and wake-up window sub-state. The configurable period of the RTC wake-up timer allows this method to adapt to different power budgets and response latency requirements, exhibiting good portability.

[0054] In some preferred embodiments, performing control operations corresponding to the migrated target state based on the migrated target state further includes: when the migrated target state is the wake-up window sub-state, acquiring the state of the one-time button wake-up flag and the wireless link activity state; determining whether the one-time button wake-up flag is set; if the one-time button wake-up flag is set, extending the duration of the current wake-up window from the first preset wake-up window duration to the second preset wake-up window duration, and clearing the one-time button wake-up flag, wherein the second preset wake-up window duration is longer than the first preset wake-up window duration; if the one-time button wake-up flag is not set, maintaining the duration of the current wake-up window at the first preset wake-up window duration; within the current wake-up window, determining whether wireless link activity is detected based on the wireless link activity state; if wireless link activity is detected, continuing to maintain the wake-up window sub-state until the wireless link activity ends and the current wake-up window ends, and then updating the current state of the hierarchical state machine to the deep sleep sub-state; if no wireless link activity is detected and the current wake-up window ends, updating the current state of the hierarchical state machine to the deep sleep sub-state.

[0055] In specific implementation, this embodiment detects a one-time wake-up flag at the entrance of the wake-up window. When the flag is set, the duration of the current wake-up window is extended from the first preset wake-up window duration to the second preset wake-up window duration. Within this window, the timing of returning to sleep is dynamically controlled according to the wireless link activity status. This solves the timing conflict problem between the short window and the long press confirmation operation, while maintaining low average power consumption under normal conditions. The specific implementation method is as follows: When the target state after the transition of the hierarchical state machine is the wake-up window sub-state, the control operation sequence corresponding to the wake-up window sub-state is executed.

[0056] First, the status of the one-time button wake-up flag and the wireless link activity status are obtained. The one-time button wake-up flag is a Boolean variable stored in system memory, indicating whether the current wake-up cycle was triggered by an external button interrupt. This flag is set in the button interrupt service routine and cleared after being read, processed, and executed at the wake-up window entry point. The button interrupt service routine executes upon detecting a rising edge on the button pin. Besides setting the one-time button wake-up flag, it also performs necessary button debouncing to prevent multiple interrupt triggers due to button bounce. Debouncing is typically implemented using software delay or timer counting. After detecting a pin level change, a certain period is waited before reading the pin status to confirm a valid button event. The wireless link activity status is a status variable indicating whether data transmission activity exists on the current wireless link, maintained by the wireless link receiving module. The wireless link activity status can be obtained within each wake-up window by detecting level changes in the wireless receiving pin or by querying the data arrival status of the wireless receiving buffer. For example, in one specific implementation, the wireless link is an infrared link. The wireless link activity status is determined by detecting level changes in the signal output pin of the infrared receiver head. When this pin remains low, it indicates the presence of a carrier signal, and the wireless link is active. An infrared link is a short-range wireless communication method that uses infrared light as the transmission medium. When the receiver head receives a modulated infrared signal, the output level will change.

[0057] Further, it is determined whether the one-time button wake-up flag is set. Setting the flag means that the value of the flag is logically true, indicating that this wake-up was triggered by a button press. If the one-time button wake-up flag is set, the duration of this wake-up window is extended from the first preset wake-up window duration to the second preset wake-up window duration, and the one-time button wake-up flag is cleared. The second preset wake-up window duration is longer than the first preset wake-up window duration. The purpose of the extension is to provide sufficient time for the user to perform a long-press confirmation operation. In one specific implementation, the first preset wake-up window duration is 500ms, and the second preset wake-up window duration is 10000ms. The short window of 500ms is sufficient to complete the normal wake-up source scanning and status determination, maintaining the average power consumption at the microamp level; the long window of 10000ms is sufficient to cover the 2-second long-press confirmation operation and subsequent business processing. Clearing the one-time button wake-up flag is to prevent the extended effect from being incorrectly carried over to subsequent wake-up cycles, ensuring that the extension only takes effect within a single window after the button wake-up. If there is no button trigger in the next cycle, it will revert to a short window. Before clearing the flag, the value of the flag can be temporarily stored in another variable so that it can be referenced in subsequent processing to determine whether the wake-up was triggered by a key press, such as for logging or business logic branch judgment.

[0058] Furthermore, if the one-time wake-up flag is not set, the wake-up window duration remains the first preset wake-up window duration. The unset flag indicates that the wake-up is generated by periodic wake-ups from the real-time clock timer, rather than being triggered by a button. In this case, the device maintains a short window operation without extending it, in order to maintain low average power consumption.

[0059] Furthermore, within the current wake-up window, the system determines whether wireless link activity has been detected based on the wireless link activity status. Wireless link activity refers to the wireless receiving module detecting a valid carrier signal or receiving a complete data packet. If wireless link activity is detected, it indicates that data is being transmitted via the wireless link, and the wake-up window sub-state is maintained until the wireless link activity ends. Furthermore, during the duration of wireless link activity, the state is not rolled back to the deep sleep sub-state to ensure the integrity and reliability of data reception. When the wireless link activity ends and the current wake-up window also ends, the current state of the hierarchical state machine is updated to the deep sleep sub-state. If no wireless link activity is detected and the current wake-up window ends, the current state of the hierarchical state machine is directly updated to the deep sleep sub-state. This mechanism implicitly extends the wake-up window until data transmission is complete when wireless link data transmission is present, avoiding the interruption of ongoing wireless data reception due to a fixed window termination. For example, in one specific implementation, wireless link activity detection is performed in each tick interrupt of the window duration timer. If wireless link activity is detected, the count value of the window duration timer is reset, causing it to restart counting from the current moment, thereby effectively extending the wake-up window. The window duration timer reset operation delays the end time of the window. As long as wireless link activity continues, the window duration timer will be continuously reset, and the window will remain open.

[0060] Furthermore, during the wake-up window sub-state, in addition to detecting wireless link activity, other wake-up source scanning operations are performed, such as secondary confirmation of button status and data reception on the communication bus. These scanning operations are executed cyclically under the control of the window duration timer. At the beginning of each cycle, it is checked whether the window duration timer has expired. If it has expired and there is no wireless link activity, the wake-up window sub-state is exited. All operations performed within the window are designed with low power consumption in mind, minimizing unnecessary peripheral operations and bus accesses to reduce power consumption during the window. For necessary peripheral operations, an on-demand startup method is adopted, and the peripheral clock is immediately turned off after the operation is completed to avoid the peripheral clock being continuously turned on during the window.

[0061] This embodiment achieves adaptive extension of the single-window duration after a button-triggered wake-up by determining the one-time wake-up flag at the wake-up window entry point. The wake-up window triggered by a button is extended from a first preset wake-up window duration to a second preset wake-up window duration, providing ample time for the user to complete the long-press confirmation operation; while the periodic wake-up window not triggered by a button maintains the first preset wake-up window duration, keeping the device's average power consumption at a low level under normal conditions. Furthermore, the extension only takes effect within the single wake-up window after button triggering; the flag is cleared after the window ends, and the short window automatically resumes in the next cycle, achieving an adaptive balance between maximum power saving during normal operation and maximum usability when the button is pressed. Furthermore, by superimposing wireless link activity status determination, the wake-up state continues until the activity ends when wireless link activity is detected within the wake-up window, avoiding the problem of forced interruption during wireless data reception due to window closure and ensuring the integrity of wireless communication. Furthermore, this adaptive extension mechanism requires no external intervention; it is entirely determined automatically by the state machine at the window entry point based on the flag status, making it simple and reliable. The mechanism for setting and clearing the one-time wake-up flag via button press ensures the atomicity of the extended operation. The flag transfer between the interrupt service routine and the main loop uses atomic operations to avoid data races. Furthermore, the linkage design between the wireless link activity status and the wake-up window duration ensures that the window extension not only responds to button triggers but also to the dynamic needs of wireless link data transmission, further enhancing the device's adaptability in different scenarios.

[0062] In some preferred embodiments, the step of performing control operations corresponding to the migrated target state further includes: when the migrated target state is the storage discharge state, acquiring the storage duration accumulated across sleep cycles via RTC and the voltage of all individual cells in the battery; determining whether the storage duration reaches a preset storage duration threshold and whether the voltage of all individual cells in the battery is higher than a preset discharge trigger voltage; if the storage duration does not reach the preset storage duration threshold or the voltage of all individual cells in the battery is not higher than the preset discharge trigger voltage, then updating the current state of the hierarchical state machine to the shutdown detection state; if the storage duration reaches the preset storage duration threshold and the voltage of all individual cells in the battery is higher than the preset discharge trigger voltage, then closing the discharge enable switch and sending a discharge enable command to the battery management unit to control the battery to start discharging.

[0063] In specific implementation, this embodiment uses a software timer to accumulate storage time across sleep cycles during the shutdown detection state. When the storage time reaches a preset storage time threshold and the battery voltage meets a preset trigger condition, a discharge trigger signal is generated, causing the device to enter the storage discharge state. In the storage discharge state, the storage time accumulated across sleep cycles via a real-time clock and the voltage of all individual battery cells are acquired. Based on the storage time and individual cell voltage determination results, it is decided whether to perform discharge or return to the shutdown detection state. This achieves automatic triggering and conditional control of discharge before storage. The specific implementation method is as follows: When the target state after the transition of the hierarchical state machine is to store the discharge state, the control operation sequence corresponding to the storage discharge state is executed.

[0064] First, the accumulated storage time across sleep cycles via the real-time clock and the voltage of all individual battery cells are obtained. Storage time refers to the accumulated time from when the device enters the shutdown detection state, during the alternating operation between deep sleep and wake-up windows. Since the system clock stops during the deep sleep sub-state, the accumulation of storage time depends on the real-time clock module continuously timing during sleep. Specifically, the current time of the real-time clock is recorded as the starting time each time the device enters the shutdown detection state. In each subsequent wake-up window, the current time of the real-time clock is read, and the difference between the current time and the starting time is calculated to obtain the accumulated storage time up to the present. Furthermore, this calculation process is performed within each wake-up window, thereby achieving time accumulation across sleep cycles. The real-time clock module uses a 32-bit counter, counting in seconds, capable of covering a timing range of up to 136 years without concern for counter overflow. For example, in one specific implementation, the timing accuracy of the real-time clock module is ±20ppm, meaning the timing error per second does not exceed 20 microseconds under room temperature conditions, maintaining high timing accuracy even over long periods.

[0065] Furthermore, the "all cell voltages" in the battery refers to the individual cell voltage value within the battery pack, obtained via the communication bus from the battery management unit (BMU). The BMU is a dedicated integrated circuit chip for monitoring and managing battery status. Its functions include measuring individual cell voltages, battery current, temperature, and calculating parameters such as state of charge (SOC) and state of health. For example, in one specific implementation, the BMU is a BQ40Z50 fuel gauge chip, communicating with the main microcontroller via the I2C bus using the SBS protocol. The battery data includes individual cell voltages, current, temperature, and SOC. The main microcontroller obtains the individual cell voltage values ​​by reading the registers of the BMU. The BQ40Z50 chip integrates an analog-to-digital converter, capable of measuring the voltage value of each cell with millivolt accuracy. The measurement results are stored in a register in two's complement binary format, requiring format conversion after being read via the I2C bus.

[0066] The system determines whether the storage time has reached a preset storage time threshold and whether the voltage of all individual battery cells is higher than a preset discharge trigger voltage. The preset storage time threshold is the minimum cumulative time the device needs to remain in the shutdown detection state. This ensures the device has entered a long-term storage state before triggering discharge, avoiding unnecessary discharge operations after a short shutdown. The preset discharge trigger voltage is the lower limit of the individual battery cell voltage required to trigger storage discharge. This ensures the battery is fully charged or nearly fully charged before discharge, avoiding unnecessary discharge when the battery is low. For example, in one specific implementation, the preset storage time threshold is set to 60 hours, and the preset discharge trigger voltage is set to 3850mV. The 60-hour storage time threshold ensures the device remains in the shutdown detection state for at least 60 hours before triggering discharge, which is sufficient to exclude short shutdown scenarios during normal use. The 3850mV discharge trigger voltage is slightly higher than the nominal voltage of the lithium battery, ensuring the battery is fully charged before discharge, reducing the battery voltage to the storage voltage range. The storage voltage range of lithium batteries is typically 3.7V to 3.85V. Discharging above 3850mV can reduce the voltage to within the storage voltage range.

[0067] Furthermore, if the storage time does not reach the preset storage time threshold or the voltage of all individual battery cells is not higher than the preset discharge trigger voltage, it indicates that the discharge trigger condition is not met, and the current state of the hierarchical state machine is updated to the shutdown detection state. If the storage time has not reached the preset storage time threshold, the device continues to maintain periodic deep sleep in the shutdown detection state, continuing to accumulate storage time. If the voltage of any individual battery cell is not higher than the preset discharge trigger voltage, the device returns to the shutdown detection state and does not perform a discharge operation to avoid unnecessary discharge and over-discharge when the battery power is insufficient. After returning to the shutdown detection state, the device continues to perform periodic deep sleep, and the accumulated storage time is not reset to zero but continues to accumulate from the current value. Only when both the storage time threshold and voltage condition are met simultaneously within a subsequent wake-up window will the device re-enter the storage-discharge state.

[0068] Furthermore, if the storage time reaches a preset storage time threshold and the voltage of all individual battery cells is higher than the preset discharge trigger voltage, it indicates that the discharge trigger condition has been met. The discharge enable switch is then closed, and a discharge enable command is sent to the battery management unit to control the battery to begin discharging. Further, the discharge enable switch is an electronic switch located on the battery discharge path, with its control terminal connected to the microcontroller's general purpose input / output (GPIO) pin. Closing the switch means that the microcontroller sets the output level of the GPIO pin to the level that enables the switch to conduct. For example, in one specific embodiment, the discharge enable switch uses an N-channel metal-oxide-semiconductor (MOSFET), with its gate connected to the microcontroller's GPIO pin. When the GPIO pin outputs a high level, the MOSFET conducts, and the discharge path is closed. The discharge enable command is a control command sent by the microcontroller to the battery management unit via the communication bus to enable the battery management unit's discharge control function. After the discharge enable switch is closed and the battery management unit receives the discharge enable command, the battery begins to release electrical energy through the discharge path, and the device enters a storage discharge state to execute the discharge process. A discharge resistor is provided on the discharge path as a load to dissipate the battery's electrical energy as heat. The resistance value of the discharge resistor is determined based on the battery voltage and the target discharge current. In one specific implementation, the discharge current is controlled between 200mA and 500mA. The power rating of the discharge resistor needs to be selected based on the product of the discharge current and the resistance value to ensure that the resistor will not overheat and be damaged during the discharge process.

[0069] Furthermore, during the discharge state, the device keeps the wake-up timer of the real-time clock module running to ensure that time tracking functionality is maintained during the discharge process. The discharge process may last for several hours, during which the microcontroller remains in a state of switching between running and low-power modes, but does not enter a deep sleep sub-state, in order to monitor changes in battery voltage and current in real time. The closed state of the discharge enable switch and the discharge enable state of the battery management unit are maintained throughout the discharge process until the discharge is completed or abnormally terminated.

[0070] This embodiment achieves unmanned automatic triggering of pre-storage discharge by using a software timer to accumulate storage time across sleep cycles during the shutdown detection state, and automatically transitioning to the storage discharge state when both storage time thresholds and battery voltage thresholds are met. If the storage time does not reach the preset storage time threshold or a single battery cell voltage is lower than the preset discharge trigger voltage, the branch processing returns to the shutdown detection state, ensuring that the discharge triggering timing is neither too early nor too late, avoiding the risk of triggering discharge after a short shutdown or forced discharge when the battery is low on power. Furthermore, when the storage time reaches the preset storage time threshold and all single cell voltages are higher than the preset discharge trigger voltage, discharge is initiated through dual control of closing the discharge enable switch and sending a discharge enable command, allowing the battery to automatically enter the storage voltage range without manual intervention. Furthermore, this storage discharge triggering mechanism combines time and voltage conditions, ensuring that the discharge operation is only performed after the device has truly entered the long-term storage state, and only when the battery is fully charged, protecting battery life and avoiding ineffective discharge. Furthermore, the accumulated storage time of the real-time clock across sleep cycles continues to count during deep sleep, ensuring that the accumulated storage time remains accurate even when the device is in STOP2 low-power mode for most of the time. The dual control mechanism of the discharge enable switch and the battery management unit provides redundant safety; even if one control fails, the other can still ensure the safety of the discharge operation.

[0071] In some preferred embodiments, after closing the discharge enable switch and sending a discharge enable command to the battery management unit to control the battery to start discharging, the method further includes: acquiring the voltage and current of all individual cells of the battery; determining whether a discharge stop condition is met, wherein the discharge stop condition includes: all individual cell voltages of the battery dropping below a preset normal termination voltage, any individual cell voltage dropping below a preset protection termination voltage, the discharge duration reaching a preset hard timeout threshold but not meeting the conditions that all individual cell voltages of the battery dropping below the preset normal termination voltage, the battery current being less than a preset overcurrent threshold, the absolute value of the battery current being less than a preset open-circuit current threshold, the battery current being greater than a preset reverse current threshold, and the difference between the highest and lowest individual cell voltages of all individual cells exceeding a preset differential voltage threshold; if the discharge stop condition is met, then the discharge is stopped and the current state of the hierarchical state machine is updated to the shutdown detection state; if the discharge stop condition is not met, then the discharge continues and the process returns to the step of acquiring the voltage and current of all individual cells of the battery.

[0072] In specific implementation, this embodiment obtains the voltage and current of all individual cells in the battery, determines whether any of the various discharge stop conditions are met, and stops discharging and returns to the shutdown detection state when the conditions are met. If none of the conditions are met, discharging continues and monitoring is maintained, forming a complete closed-loop control of the discharge process. The specific implementation method is as follows: After closing the discharge enable switch and sending a discharge enable command to the battery management unit to control the battery to start discharging, a continuous monitoring cycle of the discharge process is entered.

[0073] First, the voltage and current of all individual battery cells are acquired. The voltage of each individual cell is obtained by reading it from the battery management unit (BMU) via the communication bus. The battery current is also obtained by reading it from the BMU via the communication bus. The positive or negative direction of the current value indicates the charging or discharging direction according to the protocol definition. For example, in one specific implementation, the current value is in milliamperes (mA), with positive values ​​representing charging current and negative values ​​representing discharging current. The BQ40Z50 BMU measures the battery current using an internal current-sensing resistor. The resistance of the current-sensing resistor is typically 1 milliohm to 10 milliohms, allowing for current sampling accuracy at the milliampere level. The current value is stored in a register as a signed 16-bit integer. The microcontroller reads this value via the I2C bus, performs sign expansion and unit conversion, and obtains the current value in milliamperes.

[0074] Further, it is determined whether the conditions for stopping the discharge are met. The conditions for stopping the discharge include multiple independent termination conditions; if any one of these conditions is met, it is determined that the discharge needs to be stopped. Specifically, the conditions for stopping the discharge include the following:

[0075] All individual cell voltages of the battery drop below the preset normal termination voltage. The preset normal termination voltage is the target voltage for normal discharge completion. When all individual cell voltages drop below this voltage, it indicates that the battery has entered the storage voltage range and the discharge is complete. In one specific embodiment, the preset normal termination voltage is set to 3800mV. This voltage value is near the middle value of the lithium battery storage voltage range, which avoids the risk of capacity decay from storing a fully charged battery and also prevents over-discharge due to excessively low voltage.

[0076] If the voltage of any single cell falls below the preset protection termination voltage, the battery is considered to be nearing over-discharge. This preset protection termination voltage is a threshold voltage to prevent over-discharge. When the voltage of any single cell falls below this threshold, it indicates that the cell is close to over-discharge and discharge must be stopped immediately to prevent battery damage. In one specific embodiment, the preset protection termination voltage is set to 3500mV. The discharge termination voltage of lithium batteries is typically 2.5V to 3.0V; the 3500mV setting provides a sufficient safety margin, ensuring that the battery remains within the safe voltage range when the protection action occurs.

[0077] The discharge duration reaches a preset hard timeout threshold without all individual battery cell voltages dropping below a preset normal termination voltage. The preset hard timeout threshold is the maximum allowable duration of the discharge process, used to prevent situations where the discharge time is too long due to battery aging or abnormalities, preventing normal termination. In one specific embodiment, the preset hard timeout threshold is set to 22 hours. If the discharge duration reaches 22 hours and the battery voltage still has not dropped below 3800mV, it indicates that there may be an abnormality in the discharge process, and the discharge is forcibly terminated. The discharge duration is calculated from the moment the discharge enable switch is closed, and also relies on the timing function of the real-time clock module.

[0078] The battery current is less than the preset overcurrent threshold. The preset overcurrent threshold is the maximum allowable value of the discharge current. When the discharge current is too high, it indicates that the discharge load may be short-circuited or there is other abnormality. In one specific embodiment, the preset overcurrent threshold is set to -300mA, meaning that an absolute value of the discharge current exceeding 300mA is considered an overcurrent. Overcurrent determination uses negative value comparison; the discharge current is negative, and a value less than -300mA indicates that the current is too high. An overcurrent condition may be caused by a short circuit in the discharge resistor or an abnormal load, requiring immediate termination of discharge to prevent equipment damage.

[0079] The absolute value of the battery current is less than the preset open-circuit current threshold. The preset open-circuit current threshold is the minimum current value used to determine if the discharge path is open. When the absolute value of the current is less than this threshold, it indicates that almost no current flows through the discharge path, suggesting a possible open-circuit fault. In one specific implementation, the preset open-circuit current threshold is set to 10mA, meaning that an open circuit is determined when the absolute value of the discharge current is less than 10mA. An open circuit may be caused by a faulty discharge enable switch, an open discharge resistor, or a loose connection wire, requiring immediate termination of the discharge for troubleshooting.

[0080] The battery current exceeds a preset reverse current threshold. The preset reverse current threshold is a positive current threshold used to determine if external power is flowing into the battery. When the current value is positive and exceeds this threshold, it indicates that an external power source is charging the battery. In one specific embodiment, the preset reverse current threshold is set to 10mA, meaning that a current greater than 10mA is considered reverse charging. Reverse charging may be caused by an external power source accidentally connecting to the discharge path, requiring immediate termination of the discharge to prevent the battery from being reverse-charged.

[0081] The difference between the highest and lowest voltage values ​​of all individual cells in the battery exceeds a preset voltage difference threshold. This preset voltage difference threshold is the maximum permissible voltage difference between cells within the battery pack; exceeding this threshold indicates a severe imbalance among the cells. In one specific implementation, the preset voltage difference threshold is set to 200mV. This threshold is significantly larger than the normal voltage difference between cells during use. When the voltage difference exceeds 200mV, it indicates a potential internal fault in the battery pack or damage to individual cells, requiring immediate termination of discharge to prevent further damage.

[0082] Furthermore, each of the above-mentioned discharge cessation conditions is evaluated one by one. The order in which the conditions are evaluated can be adjusted according to priority, and this invention does not specifically limit this. For example, in one specific embodiment, protective termination conditions are evaluated first, namely, the cell voltage is lower than the preset protective termination voltage and the battery current is abnormal, because these conditions are directly related to the safety of the battery and the device. Then, normal termination conditions and hard timeout conditions are evaluated, and finally, the voltage difference condition is evaluated.

[0083] Furthermore, if any of the conditions for stopping discharge are met, the discharge is stopped and the current state of the hierarchical state machine is updated to the shutdown detection state. The stop-discharge operation includes disconnecting the discharge enable switch via a general-purpose input / output pin and sending a discharge prohibition command to the battery management unit via the communication bus, causing the battery management unit to stop discharge control. Further, after stopping discharge, the device exits the stored discharge state and returns to the shutdown detection state to continue periodic deep sleep. When stopping discharge, the reason for stopping is recorded for subsequent fault analysis and log traceability. The reason for stopping is stored as an enumerated value in the log field of the state machine context, and this log can be read through the debug interface when the device wakes up next time.

[0084] Furthermore, if any of the conditions for stopping discharge are not met, the discharge continues and the process returns to the step of acquiring the voltage and current of all individual battery cells. This return operation forms a continuous monitoring loop for the discharge process, re-acquiring battery data and re-determining the stopping conditions within each monitoring cycle. The length of the monitoring cycle can be set according to actual needs; in one specific implementation, it is set to 1 second. A 1-second monitoring cycle balances response speed and communication load, ensuring that anomalies are not missed due to an excessively long monitoring cycle, nor that unnecessary bus communication power consumption is increased due to an excessively short monitoring cycle. Monitoring continues until one of the conditions for stopping discharge is met, at which point the loop terminates.

[0085] This embodiment achieves comprehensive safety protection during the storage discharge process by continuously monitoring the voltage and current of all individual cells and setting seven discharge stop scenarios. The normal termination condition automatically stops the battery discharge when it reaches the storage voltage range, preventing over-discharge. The protective termination condition immediately stops the discharge when any individual cell voltage drops below the preset protection termination voltage, effectively preventing irreversible battery damage caused by over-discharge of individual cells. Furthermore, the hard timeout condition forcibly terminates the discharge if the duration is too long, preventing indefinite discharge under abnormal conditions. Additionally, four types of process anomaly detection—overcurrent, open circuit, backflow, and excessive voltage difference—timely terminate the discharge in cases of excessive discharge current, open discharge path, external power backflow, and battery cell imbalance, ensuring the safety of the equipment and battery. All stop scenarios are determined based on real-time collected battery data, and the determination logic is repeatedly executed in the continuous monitoring loop, ensuring the safety and controllability of the discharge process. Furthermore, the device automatically returns to the shutdown detection state after discharge, allowing it to return to low-power standby mode without manual intervention and continue periodic deep sleep. The 1-second monitoring cycle ensures that the maximum response time for abnormal situations does not exceed 1 second, enabling timely termination of discharge after an anomaly occurs and minimizing potential risks.

[0086] In some preferred embodiments, the generation of the charging access signal includes: sampling the battery current at a preset sampling period to obtain a current sampling value; determining whether the current sampling value is greater than a preset charging current threshold; if the current sampling value is greater than the preset charging current threshold and no first threshold exceeding time has been recorded, then recording the current time as the first threshold exceeding time, and returning to the step of sampling the battery current at the preset sampling period; if the current sampling value is greater than the preset charging current threshold and the first threshold exceeding time has been recorded, then calculating the duration from the first threshold exceeding time to the current time; determining whether the duration reaches a preset duration; if the duration reaches the preset duration, then generating the charging access signal, clearing the first threshold exceeding time record, and writing the charging access signal as an external event trigger signal into the single event queue; if the duration does not reach the preset duration, then returning to the step of sampling the battery current at the preset sampling period; if the current sampling value is less than or equal to the preset charging current threshold and the first threshold exceeding time has been recorded, then clearing the first threshold exceeding time record, and returning to the step of sampling the battery current at the preset sampling period.

[0087] This embodiment employs a mechanism that combines the initial threshold recording time with periodic verification. It requires that the charging current continuously exceeds the preset charging current threshold for a preset duration before a charging access signal is generated. This effectively filters out instantaneous current disturbances while ensuring reliable detection of actual charging access.

[0088] The battery current is sampled at a preset sampling period to obtain the current sample value. The preset sampling period is a pre-configured current sampling time interval that determines the frequency of current detection. The sampling operation is performed by the battery management unit when the preset sampling period arrives, and the microcontroller reads the current register in the battery management unit through the communication bus to obtain the current sample value. For example, in one specific implementation, the preset sampling period is set to 1 second. A 1-second sampling period is a commonly used setting in battery current detection scenarios, as it can detect current changes in a timely manner without placing an excessive load on the communication bus. The setting of the sampling period needs to balance the detection response speed and power consumption; a shorter period results in a faster detection response, but higher bus communication power consumption.

[0089] Furthermore, it is determined whether the current sampling value is greater than a preset charging current threshold. The preset charging current threshold is a reference value used to determine whether charging current is present. Its value should be greater than the current fluctuation range of the battery in a static or discharging state, and less than the charging current value during normal charging. In one specific embodiment, the preset charging current threshold is set to 100mA. The 100mA threshold is much greater than the self-discharge current of the device in deep sleep mode, and also much greater than the self-discharge current of the battery when it is static, while being less than the charging current of a conventional charger. This ensures that actual charging access can be reliably detected, and that fluctuations in the device's own power consumption will not trigger false alarms.

[0090] If the sampled current value exceeds the preset charging current threshold and the first threshold exceedance moment is not recorded, the current moment is recorded as the first threshold exceedance moment using the real-time clock, and the process returns to the step of sampling the battery current at a preset sampling period. The first threshold exceedance moment refers to the first sampling moment in a continuous threshold exceedance sequence that exceeds the preset charging current threshold. After the real-time clock records this moment, it continues to acquire current sample values ​​in subsequent sampling periods to determine whether the threshold exceedance state continues. The first threshold exceedance moment is stored in a dedicated field in the state machine context, which is used exclusively during the charging access detection process and will not be confused with other timing functions. Simultaneously with recording the first threshold exceedance moment, the real-time clock count value at that moment can also be recorded to obtain higher accuracy when calculating the duration later.

[0091] If the sampled current value is greater than the preset charging current threshold and the first time the threshold is exceeded has been recorded, calculate the duration from the first time the threshold is exceeded to the current time. This duration represents the cumulative duration for which the current continuously exceeds the preset charging current threshold. Determine whether this duration has reached the preset duration. The preset duration is a threshold value used to determine whether the charging access is stable and effective. Its value should be sufficient to filter out instantaneous current disturbances, while not being too long to delay the response of actual charging access. In one specific embodiment, the preset duration is set to 5 seconds. A duration of 5 seconds is sufficient to filter out most current transients caused by load switching or electromagnetic interference, while keeping the detection delay of charging access within an acceptable range.

[0092] If the duration reaches the preset duration, it indicates that the current has continuously exceeded the preset charging current threshold for a sufficiently long time, and is determined to be a valid charging access. A charging access signal is generated, the record of the first threshold exceedance time is cleared, and the charging access signal is written into a single event queue as an external event trigger signal. After generating the charging access signal, the record of the first threshold exceedance time is cleared to prepare for the next charging access detection. Clearing the record allows subsequent new charging access events to re-record the first threshold exceedance time, avoiding interference from old records to subsequent detections. After the charging access signal is encapsulated as an event signal and written into a single event queue as an external event trigger signal, the hierarchical state machine performs a transition from the shutdown detection state or the storage discharge state to the shallow sleep state when processing this event signal.

[0093] If the duration does not reach the preset duration, return to the step of sampling the battery current at the preset sampling period and continue to obtain subsequent sampling values ​​to determine whether the over-threshold state continues.

[0094] If the sampled current value is less than or equal to the preset charging current threshold, and the first time the threshold is exceeded has been recorded, it indicates that the current has fallen back below the threshold after exceeding it, and the threshold-exceeding state is interrupted. The record of the first threshold-exceeding moment is cleared, and the process returns to sampling the battery current at the preset sampling period. Clearing the record allows subsequent new threshold-exceeding events to restart the timing, preventing confusion with interrupted historical threshold-exceeding states. The atomicity of the clearing operation must be guaranteed, and no data races caused by nested interruptions should occur during the clearing process.

[0095] If the current sample value is less than or equal to the preset charging current threshold and the first time the threshold is exceeded is not recorded, return directly to the step of sampling the battery current at the preset sampling period and continue normal sampling.

[0096] Furthermore, in one specific embodiment, the aforementioned charging access detection logic is implemented as a state machine within the battery monitoring task, which is executed within each wake-up window. During the deep sleep sub-state, the battery monitoring task is paused, but the real-time clock module continues timing. When the device is periodically woken up and enters the wake-up window sub-state, the battery monitoring task is executed, reading the current battery current sampling value and executing the aforementioned determination logic. This means that charging access detection is performed during the device's wake-up window sub-state and is not performed during the deep sleep sub-state. Since current sampling is paused during the deep sleep sub-state, the real-time performance of charging access detection is limited by the wake-up cycle. If charging access occurs during the deep sleep sub-state, it will only be detected when the next wake-up window arrives. Therefore, the setting of the first preset wake-up cycle needs to consider both the response delay requirements of charging access detection; a shorter cycle results in a faster response but higher power consumption.

[0097] This embodiment achieves reliable generation of charging access signals through a mechanism of recording the first threshold exceedance time and periodic verification. When the current sample value is greater than the preset charging current threshold and the first threshold exceedance time has not yet been recorded, the current time is recorded, establishing a time reference at the starting point of continuous threshold exceedances. When the current sample value is greater than the preset charging current threshold and the first threshold exceedance time has been recorded, the duration is calculated, and a charging access signal is generated after the duration reaches a preset duration, ensuring that the charging access determination is based on a continuous and stable threshold exceedance state, rather than instantaneous disturbances. When the current sample value is less than or equal to the preset charging current threshold and the first threshold exceedance time has been recorded, the recorded branch is cleared, so that any intermediate sample value falling below the threshold will cause the timer to reset, requiring the continuous threshold exceedance accumulation to restart, thus effectively filtering out brief current fluctuations. Furthermore, this mechanism ensures that the generation of the charging access signal has sufficient anti-interference capability and can be reliably triggered after actual charging access with a preset duration time delay, avoiding power waste caused by frequent false wake-ups, while ensuring timely response to charging access events. Furthermore, after the charging access signal is generated, it is written into a single event queue. A unified event processing framework using a hierarchical state machine triggers state transitions, ensuring that the charging access event is processed consistently within the same event processing loop as other events such as button presses and timers, maintaining system behavior consistency. The parameter combination of a 1-second sampling period and a 5-second duration achieves a balance between false wake-up frequency and detection latency, and can be adjusted according to the anti-interference capability and response speed requirements of different application scenarios.

[0098] In some preferred embodiments, the method further includes: calculating the difference between the highest and lowest individual cell voltages among all individual cell voltages of the battery, as the individual cell voltage difference; determining whether the individual cell voltage difference is greater than a preset imbalance voltage difference threshold; if the individual cell voltage difference is greater than the preset imbalance voltage difference threshold, generating an imbalance prohibition signal and writing the imbalance prohibition signal as an external event trigger signal into the single event queue, the imbalance prohibition signal being used to prevent the current state of the hierarchical state machine from transitioning to the stored discharge state; and / or determining whether all individual cell voltages of the battery are all less than a preset shutdown voltage threshold and the individual cell voltages are in a balanced state; if all individual cell voltages of the battery are all less than the preset shutdown voltage threshold and the individual cell voltages are in a balanced state, generating a shutdown signal and sending the shutdown signal to the battery management unit to stop the device from consuming power.

[0099] In specific implementation, this embodiment calculates the difference between the highest and lowest voltages of all individual cells in the battery as the cell voltage difference. When the cell voltage difference exceeds a preset imbalance voltage difference threshold, an imbalance prohibition signal is generated, preventing the state machine from transitioning to the storage discharge state, thus avoiding storage discharge in an unbalanced state. When all cell voltages are below a preset shutdown voltage threshold and the cell voltages are in a balanced state, a shutdown signal is generated and sent to the battery management unit to stop the device's self-power consumption. The specific implementation method is as follows: The difference between the highest and lowest voltage values ​​of all individual cells in the battery is calculated as the cell voltage differential. The battery management unit (BMU) reads the voltage values ​​of all individual cells via the communication bus, iterates through all cell voltage values, obtains the maximum and minimum values, and calculates the difference between the maximum and minimum values; this difference is the cell voltage differential. The cell voltage differential reflects the degree of voltage imbalance among the cells within the battery pack. This iteration operation is performed once per wake-up window to obtain the latest battery status information. Furthermore, for battery packs containing multiple cells, iterating through all cell voltage values ​​requires multiple reads of the BMU registers. There may be time intervals between each read, but these intervals are typically on the order of milliseconds and have a negligible impact on the accuracy of the voltage differential calculation.

[0100] The system determines whether the individual cell voltage difference exceeds a preset imbalance voltage difference threshold. This preset imbalance voltage difference threshold is the maximum permissible voltage difference value used to determine whether the battery pack is in an acceptable equilibrium state. In one specific implementation, the preset imbalance voltage difference threshold is set to 40mV. The 40mV threshold is a commonly used standard for judging the equilibrium state of lithium-ion battery packs. When the individual cell voltage difference is within 40mV, the battery pack is considered to be in an equilibrium state, and operations such as storage and discharge can be performed. When the individual cell voltage difference exceeds 40mV, the battery pack is considered to be unbalanced, and certain operations that may exacerbate the imbalance must be prohibited.

[0101] Furthermore, if the differential pressure between individual cells exceeds a preset imbalance differential pressure threshold, an imbalance prohibition signal is generated and written into a single event queue as an external event trigger signal. The imbalance prohibition signal is a prohibitive signal whose function is to prevent the current state of the hierarchical state machine from transitioning to the storage discharge state when the state machine processes this signal. Specifically, when the state machine receives the imbalance prohibition signal and its current state is the shutdown detection state, even if the storage time has reached a preset storage time threshold and all cell voltages are higher than the preset discharge trigger voltage, the state machine will not perform a transition to the storage discharge state. This prohibited state persists until the imbalance prohibition signal is cleared, i.e., the differential pressure between individual cells falls below the preset imbalance differential pressure threshold. After the imbalance prohibition signal is written into the single event queue, it awaits processing by the state machine in a first-in, first-out order. The writing operation is consistent with the method of encapsulating other external event trigger signals into event signals and writing them into the single event queue. When the imbalance prohibition signal is processed in the state machine, the state machine sets an internal prohibition flag, which is checked each time an attempt is made to transition to the storage discharge state; if the flag is set, the transition is prohibited.

[0102] If the differential pressure between individual cells is less than or equal to a preset imbalance differential pressure threshold, no imbalance prohibition signal is generated, and the battery pack is considered to be in an balanced state, allowing normal discharge to trigger the determination. If the imbalance prohibition flag has been set previously, an imbalance release signal is generated when the differential pressure between individual cells falls back below the threshold. This signal is written to a single event queue and then the state machine clears the imbalance prohibition flag.

[0103] The system determines whether the voltage of all individual cells in the battery is below a preset shutdown voltage threshold and whether the voltages of all cells are in a balanced state. The preset shutdown voltage threshold is a reference value used to determine whether the battery has discharged to a voltage level that requires stopping the device's self-consumption. For example, in one specific embodiment, the preset shutdown voltage threshold is set to 3900mV. The balanced state of the individual cell voltages means that the voltage difference between cells is less than or equal to a preset imbalance voltage difference threshold, i.e., the battery pack is in an acceptable balanced state. The shutdown condition determination requires two conditions: all individual cell voltages are less than 3900mV, and the voltage difference between cells is not greater than 40mV. The simultaneous fulfillment of these two conditions ensures that the shutdown operation occurs when the overall battery voltage is low and balanced, avoiding a situation where shutdown is triggered due to low voltage in some cells while other cell voltages remain high in an imbalanced state.

[0104] If the voltage of all individual cells in the battery is below the preset shutdown voltage threshold and the voltages of all cells are in a balanced state, a shutdown signal is generated and sent to the battery management unit to stop the device from self-discharging. The shutdown signal is a control command used to instruct the battery management unit to perform a shutdown operation. After receiving the shutdown signal, the battery management unit shuts off the device's power supply, causing the device to stop consuming power. The shutdown signal is sent via a communication bus; the microcontroller writes a control register to the battery management unit through the communication bus, triggering the shutdown operation. After shutdown, the device enters an extremely low-power state, and the remaining battery energy is preserved, preventing over-discharge due to self-discharge. In one specific implementation, the shutdown signal is achieved by writing a specific value to the shutdown control register of the BQ40Z50 fuel gauge chip. Upon receiving this command, the chip cuts off the discharge field-effect transistor, stopping power supply to the load. After shutdown, the device consumes almost no current, and battery self-discharge becomes the only energy consumption pathway.

[0105] If the voltage of all individual cells in the battery is not lower than the preset shutdown voltage threshold, or if the voltage of each individual cell is not in a balanced state, no shutdown signal will be generated, and the device will continue to maintain its current operating state and continue to perform voltage monitoring.

[0106] In one specific implementation, the logic for determining the imbalance prohibition signal and the shutdown signal is executed within the battery monitoring task, which is executed sequentially within the same wake-up window as the charging access detection task. The battery monitoring task first reads the voltage of all individual cells in the battery, calculates the individual cell voltage difference, determines whether an imbalance prohibition signal or an imbalance release signal is generated, and then determines whether a shutdown signal is generated. The two determination logics are executed sequentially within the same task, ensuring the consistency of the determination results. After the battery monitoring task is completed, the generated signals are written to a single event queue, and the hierarchical state machine performs the corresponding state transition or state prohibition operation when processing the queue.

[0107] This embodiment calculates the individual cell voltage difference and determines whether it exceeds a preset imbalance voltage difference threshold. When the battery pack becomes unbalanced, an imbalance prohibition signal is generated and written to a single event queue, preventing the state machine from transitioning to a storage discharge state. This effectively avoids the problem of over-discharge of individual cells or exacerbation of imbalance that may occur when performing storage discharge under unbalanced conditions. The imbalance prohibition signal is included in the single event queue as an external event trigger signal for unified processing, maintaining consistency with the event processing framework. Furthermore, when the voltage of all individual cells is less than a preset shutdown voltage threshold and the voltage of each individual cell is in a balanced state, a shutdown signal is generated and sent to the battery management unit. This enables the device to automatically stop self-discharge when the battery voltage drops below a safety threshold, avoiding battery over-discharge. The generation of the shutdown signal also requires that the voltage of each individual cell is in a balanced state, preventing shutdown from being performed when the average voltage of individual cells meets the condition but the voltage of individual cells is actually too low under unbalanced conditions, further ensuring battery safety. Furthermore, the combined use of the imbalance prohibition signal and the shutdown signal allows the battery management decision to consider both individual cell voltage difference and absolute voltage level dimensions, forming a complete protection mechanism in both the balanced state and voltage level dimensions of the battery pack. The combination of the 40mV imbalance threshold and the 3900mV shutdown threshold is determined based on the typical characteristics of lithium-ion batteries. This combination ensures battery safety while avoiding excessively frequent protection actions that could disrupt normal device operation. Once a shutdown operation is performed, the device cannot automatically resume operation and requires external charging to restart. Therefore, the selection of the shutdown threshold must strike a balance between battery protection and device availability.

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

[0109] Please see Figure 2 , Figure 2 This is a schematic block diagram of a computer device provided in an embodiment of this application. The computer device 500 can be a terminal or a server, wherein the server can be a standalone server or a server cluster composed of multiple servers.

[0110] The computer device 500 includes a processor 502, a memory, and a network interface 505 connected via a system bus 501. The memory may include a non-volatile storage medium 503 and internal memory 504.

[0111] The non-volatile storage medium 503 may store an operating system 5031 and a computer program 5032. When the computer program 5032 is executed, it causes the processor 502 to execute a hierarchical sleep and wake-up control method for a battery-powered device.

[0112] The processor 502 provides computing and control capabilities to support the operation of the entire computer device 500.

[0113] The internal memory 504 provides an environment for the operation of the computer program 5032 in the non-volatile storage medium 503. When the computer program 5032 is executed by the processor 502, the processor 502 can execute a hierarchical hibernation and wake-up control method for a battery-powered device.

[0114] The network interface 505 is used for network communication with other devices. Those skilled in the art will understand that the above structure is merely a block diagram of a portion of the structure related to the present application and does not constitute a limitation on the computer device 500 to which the present application is applied. A specific computer device 500 may include more or fewer components than shown in the figures, or combine certain components, or have different component arrangements.

[0115] The processor 502 is used to run a computer program 5032 stored in a memory to implement the steps of a graded sleep and wake-up control method for a battery-powered device provided in any of the above method embodiments.

[0116] It should be understood that in the embodiments of this application, the processor 502 may be a central processing unit (CPU), or it may be other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. The general-purpose processor may be a microprocessor or any conventional processor.

[0117] It will be understood by those skilled in the art that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program may be stored in a storage medium, which is a computer-readable storage medium. The computer program is executed by at least one processor in the computer system to implement the process steps of the embodiments of the above methods.

[0118] Therefore, the present invention also provides a storage medium. This storage medium can be a computer-readable storage medium. The storage medium stores a computer program. When executed by a processor, the computer program causes the processor to perform the steps of a graded sleep and wake-up control method for a battery-powered device provided in any of the above method embodiments.

[0119] The storage medium is a physical, non-transient storage medium, such as a USB flash drive, external hard drive, read-only memory (ROM), magnetic disk, or optical disk, or any other physical storage medium capable of storing program code. The computer-readable storage medium can be non-volatile or volatile.

[0120] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of both. To clearly illustrate the interchangeability of hardware and software, the components and steps of the various examples have been generally described in terms of functionality in the foregoing description. 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 implementations should not be considered beyond the scope of this invention.

[0121] In the several embodiments provided by this invention, it should be understood that the disclosed apparatus and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative. For example, the division of each unit is merely a logical functional division, and there may be other division methods in actual implementation. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed.

[0122] The steps in the method of this invention can be adjusted, merged, or reduced in order according to actual needs. The units in the device of this invention can be merged, divided, or reduced according to actual needs. Furthermore, the functional units in the various embodiments of this invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0123] If the integrated unit is implemented as a software functional unit and sold or used as an independent product, it can be stored in a storage medium. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art, or all or part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, a terminal, or a network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention.

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

[0125] Obviously, those skilled in the art can make various modifications and variations to this invention without departing from its spirit and scope. Therefore, this invention is also intended to include these modifications and variations as long as they fall within the scope of the claims of this invention and their equivalents.

[0126] The above description is merely a specific embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any person skilled in the art can easily conceive of various equivalent modifications or substitutions within the technical scope disclosed in the present invention, and these modifications or substitutions should all be covered within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the scope of the claims.

Claims

1. A hierarchical sleep and wake-up control method for a battery-powered device, characterized in that, include: In response to receiving an external event trigger signal, the external event trigger signal is encapsulated into an event signal and written into a single event queue; The event signals are extracted in the order of the single event queue and delivered to the hierarchical state machine. The hierarchical state machine includes a running state, a shallow sleep state, a shutdown detection state, and a discharge storage state. The shutdown detection state includes a wake-up window sub-state and a deep sleep sub-state. The event signals include a sleep command, a power-on command, a long-press button signal, a timeout signal, a power-off command, a discharge trigger signal, a discharge completion signal, a discharge abnormality signal, or a charging access signal. Based on the current state of the hierarchical state machine and the event signal, determine the target state after the transition; Execute control operations corresponding to the migrated target state according to the migrated target state, including: when the migrated target state is the deep sleep sub-state, obtain a first preset wake-up period and a first preset wake-up window duration; Configure the RTC wake-up timer's timing period to the first preset wake-up period; configure the microcontroller to a low-power mode that stops the kernel clock, while keeping the RTC wake-up timer and wake-up pin operational; when the RTC wake-up timer expires, wake up the microcontroller, update the current state of the hierarchical state machine to the wake-up window sub-state, and initialize the wake-up window duration to the first preset wake-up window duration; when the target state after migration is the wake-up window sub-state, obtain the status of the one-time button wake-up flag and the wireless link activity status; determine whether the one-time button wake-up flag is set; if the one-time button wake-up flag is set, extend the current wake-up window duration from the first preset wake-up window duration to... The second preset wake-up window duration is set, and the one-time wake-up flag of the button is cleared. The second preset wake-up window duration is longer than the first preset wake-up window duration. If the one-time wake-up flag of the button is not set, the wake-up window duration is maintained at the first preset wake-up window duration. Within the wake-up window, it is determined whether wireless link activity is detected based on the wireless link activity status. If wireless link activity is detected, the wake-up window sub-state is maintained until the wireless link activity ends and the wake-up window ends, and then the current state of the hierarchical state machine is updated to the deep sleep sub-state. If no wireless link activity is detected and the wake-up window ends, the current state of the hierarchical state machine is updated to the deep sleep sub-state.

2. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, Determining the target state after the transition based on the current state of the hierarchical state machine and the event signal includes: Determine whether the current state of the hierarchical state machine is the running state and whether the event signal is the sleep instruction; if the current state of the hierarchical state machine is the running state and the event signal is the sleep instruction, then determine the transitioned target state as the shallow sleep state; Determine whether the current state of the hierarchical state machine is the shallow sleep state and whether the event signal is the power-on command or the long press signal of the key; if the current state of the hierarchical state machine is the shallow sleep state and the event signal is the power-on command or the long press signal of the key, then determine the transitioned target state as the running state; Determine whether the current state of the hierarchical state machine is the shallow sleep state and whether the event signal is the timeout signal or the shutdown command; if the current state of the hierarchical state machine is the shallow sleep state and the event signal is the timeout signal or the shutdown command, then determine the transitioned target state as the shutdown detection state; Determine whether the current state of the hierarchical state machine is the running state and whether the event signal is the power-off command or the long-press signal; if the current state of the hierarchical state machine is the running state and the event signal is the power-off command or the long-press signal, then determine the transitioned target state as the shutdown detection state; Determine whether the current state of the hierarchical state machine is the shutdown detection state and whether the event signal is the power-on command or the long press signal; if the current state of the hierarchical state machine is the shutdown detection state and the event signal is the power-on command or the long press signal, then determine the transitioned target state as the running state; Determine whether the current state of the hierarchical state machine is the shutdown detection state and whether the event signal is the discharge trigger signal; if the current state of the hierarchical state machine is the shutdown detection state and the event signal is the discharge trigger signal, then determine the migrated target state as the storage discharge state; Determine whether the current state of the hierarchical state machine is the stored discharge state and whether the event signal is the discharge completion signal or the discharge abnormality signal; if the current state of the hierarchical state machine is the stored discharge state and the event signal is the discharge completion signal or the discharge abnormality signal, then determine the migrated target state as the shutdown detection state; Determine whether the current state of the hierarchical state machine is the shutdown detection state or the storage discharge state and whether the event signal is the charging access signal; if the current state of the hierarchical state machine is the shutdown detection state or the storage discharge state and the event signal is the charging access signal, then determine the migrated target state as the shallow sleep state.

3. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, The step of performing control operations corresponding to the migrated target state based on the migrated target state further includes: When the target state after migration is the storage discharge state, obtain the storage duration accumulated across sleep cycles via RTC and the voltage of all individual cells in the battery; Determine whether the storage time has reached a preset storage time threshold and whether the voltage of all individual cells of the battery is higher than a preset discharge trigger voltage; If the storage time does not reach the preset storage time threshold or the voltage of all individual cells of the battery is not higher than the preset discharge trigger voltage, then the current state of the hierarchical state machine is updated to the shutdown detection state. If the storage time reaches the preset storage time threshold and the voltage of all individual cells of the battery is higher than the preset discharge trigger voltage, then the discharge enable switch is closed and a discharge enable command is sent to the battery management unit to control the battery to start discharging.

4. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 3, characterized in that, After closing the discharge enable switch and sending a discharge enable command to the battery management unit to control the battery to start discharging, the method further includes: Obtain the voltage and current of all individual cells in the battery. Determine whether the discharge stop conditions are met. The discharge stop conditions include: all cell voltages of the battery drop below a preset normal termination voltage; any cell voltage is below a preset protection termination voltage; the discharge duration reaches a preset hard timeout threshold but does not meet the condition that all cell voltages of the battery drop below the preset normal termination voltage; the battery current is less than a preset overcurrent threshold; the absolute value of the battery current is less than a preset open circuit current threshold; the battery current is greater than a preset reverse current threshold; and the difference between the highest and lowest cell voltages of all cells exceeds a preset voltage difference threshold. If the discharge stop condition is met, then discharge is stopped and the current state of the hierarchical state machine is updated to the shutdown detection state; If the conditions for stopping discharge are not met, then continue discharging and return to the step of obtaining the voltage of all individual cells and the battery current.

5. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, The generation of the charging access signal includes: The battery current is sampled at a preset sampling period to obtain the current sample value; Determine whether the current sample value is greater than a preset charging current threshold; If the current sample value is greater than the preset charging current threshold and the first time the threshold is exceeded is not recorded, then the current time is recorded as the first time the threshold is exceeded, and the step of sampling the battery current with a preset sampling period is returned. If the current sample value is greater than the preset charging current threshold and the first time the threshold is exceeded has been recorded, then calculate the duration from the first time the threshold is exceeded to the current time. Determine whether the duration has reached the preset duration; If the duration reaches the preset duration, the charging access signal is generated, the first time the threshold is exceeded is cleared, and the charging access signal is written into the single event queue as an external event trigger signal. If the duration does not reach the preset duration, then return to the step of sampling the battery current at a preset sampling period; If the current sample value is less than or equal to the preset charging current threshold, and the first time the threshold is exceeded has been recorded, then the record of the first time the threshold is exceeded is cleared, and the process returns to the step of sampling the battery current at a preset sampling period.

6. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, The method further includes: Calculate the difference between the highest and lowest voltages of all individual cells in the battery, and use this as the cell voltage difference. Determine whether the differential pressure of the individual cells is greater than a preset imbalance differential pressure threshold; if the differential pressure of the individual cells is greater than the preset imbalance differential pressure threshold, generate an imbalance prohibition signal and write the imbalance prohibition signal as an external event trigger signal into the single event queue. The imbalance prohibition signal is used to prohibit the current state of the hierarchical state machine from being transitioned to the stored discharge state.

7. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, The method further includes: Determine whether the voltage of all individual cells in the battery is less than a preset shutdown voltage threshold and whether the voltage of each individual cell is in a balanced state; if the voltage of all individual cells in the battery is less than the preset shutdown voltage threshold and the voltage of each individual cell is in a balanced state, then generate a shutdown signal and send the shutdown signal to the battery management unit to stop the device from consuming power.

8. The hierarchical sleep and wake-up control method for battery-powered devices according to claim 1, characterized in that, The first preset wake-up period ranges from 1ms to 31995ms.

9. A computer device, characterized in that, The computer device includes a memory and a processor. The memory stores a computer program, and when the processor executes the computer program, it implements the hierarchical sleep and wake-up control method for a battery-powered device as described in any one of claims 1-8.

10. A computer-readable storage medium, characterized in that, The storage medium stores a computer program that, when executed by a processor, can implement the hierarchical sleep and wake-up control method for a battery-powered device as described in any one of claims 1-8.