A power communication parallel nested state machine non-operating system control method

CN122547571APending Publication Date: 2026-08-11FUJIAN XIANDE ENERGY TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-18
Publication Date
2026-08-11

AI Technical Summary

Technical Problem

传统的做法往往通过操作系统的任务间通信(如消息队列、信号量)来同步不同任务下的状态机,这不仅增加了实现复杂度,也引入了额外的性能瓶颈和不确定的延时

Benefits of technology

1、通过将多个协议状态机的运行、超时轮询及状态机间的同步通信全部集成在一个不依赖操作系统的单主循环中,消除了任务切换、上下文保存及硬件定时器中断等传统系统开销,从而在裸机环境下显著提升了运行效率、实时性与资源利用率;同时,通过引入嵌套状态机机制使嵌套任务与当前激活状态机关联运行并直接互控行为,配合基于动态规划算法和消息优先级的特权/正常模式自适应切换策略,以及文件操作场景下的Bang-Bang控制与缓存间隙任务切换,实现了并行嵌套管理中通信策略的灵活优化与精确的资源锁定。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122547571A_ABST
    Figure CN122547571A_ABST
Patent Text Reader

Abstract

The application provides a power communication parallel nested state machine non-operating system control method in the technical field of power system automation, and comprises the following steps: integrating and running a target communication protocol state machine which is independent of an operating system in a single main loop, processing message sending and receiving, state transition and timeout processing; activating a nested state machine and associating running when executing a nested task, so as to influence the behavior of the current state machine; after obtaining a message queue with priority, using a dynamic programming algorithm to comprehensively optimize the priority, the sub-state and the response time limit, and selecting an optimal transmission strategy in a normal mode or a privileged mode; the normal mode transmits in sequence or according to the priority, and the privileged mode only allows the current message transmission and blocks other messages until completion. The application has the advantages that the running efficiency, real-time performance and resource utilization rate in the non-operating system environment are greatly improved, and the communication strategy adaptive capacity under the management of the parallel nested multiple state machines is optimized.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of power system automation technology, and in particular to a power communication parallel nested state machine control method without an operating system. Background Technology

[0002] In power automation systems, the IEC 60870 series protocols (including IEC 60870-5-101, IEC 60870-5-104, etc.) are widely used for data communication between the master station and terminal equipment (such as feeder terminals, distribution automation terminals, etc.) to realize the "four remote" functions: telemetry, remote signaling, remote control, and remote adjustment. To achieve reliable control of the communication process, state machines, as a computational model describing the behavior of discrete systems, are widely adopted. Through state machines, the communication system can execute predetermined state transitions and actions (such as sending messages, retransmitting, closing links, etc.) based on the current state and received events (such as receiving a message frame, timeout, etc.), thereby ensuring the correct execution of the communication protocol.

[0003] In existing technologies, the implementation of state machines in embedded software design of power communication terminal equipment typically relies on multi-tasking operating systems (such as embedded RTOS, Linux, etc.). These operating systems provide mechanisms such as task scheduling, semaphores, message queues, software timers, and timeout management, greatly facilitating the development of state machines. For example, an independent task can be created for each communication link or protocol stack, and the state machine's blocking and waking-up mechanisms can be implemented within the task using the operating system's delay and event waiting mechanisms. Simultaneously, timeout handling during communication often relies on the software timer service provided by the operating system.

[0004] However, existing state machine implementation schemes that rely on operating systems have the following significant technical problems and limitations: First, the reliance on an operating system prevents state machines from running on microprocessors (MCUs) with extremely limited resources or no operating system at all. In the field of power automation, many low-cost feeder terminals, sensor nodes, and other devices do not integrate or are unable to run complex operating systems in order to reduce costs and power consumption. These devices require a lightweight, self-contained state machine solution, which existing solutions cannot meet.

[0005] Secondly, even on platforms with operating systems, the system overhead of running traditional state machines is not negligible. Operating system task switching, context saving, and kernel service calls (such as obtaining system time and manipulating semaphores) all consume CPU resources and memory. For terminals that need to manage multiple communication protocols simultaneously (such as running both 101 and 104 protocols) and handle complex operations like file transfers, this overhead significantly impacts the system's real-time performance and concurrent processing capabilities. Especially when processing large amounts of data (such as file transfers), frequent task scheduling and blocking can lead to decreased communication efficiency or link timeouts.

[0006] Furthermore, existing technologies lack a unified, low-overhead parallel and nested management mechanism when dealing with multiple interconnected state machines (e.g., a client request based on the 104 protocol needs to activate a communication session based on the 101 protocol, while a burst data transmission of the 101 protocol needs to activate the 104 communication in turn). Traditional approaches often use inter-task communication of the operating system (such as message queues and semaphores) to synchronize state machines under different tasks, which not only increases implementation complexity but also introduces additional performance bottlenecks and unpredictable latency. For scenarios where other communication services need to be temporarily suspended during a single file read / write operation and precisely resumed after the file operation is completed (i.e., requirements similar to Bang-Bang control), existing solutions relying on operating system task scheduling struggle to achieve efficient and accurate resource locking and state switching.

[0007] Finally, many existing state machine designs fail to effectively integrate dynamic programming decision-making capabilities. When a communication queue contains messages with various priorities and attributes (such as telematics messages and file transfer messages), how to comprehensively analyze the current operating status of all state machines, message priorities, waiting time limits for acknowledgments, and other factors to dynamically select the optimal transmission strategy (e.g., whether to enter privileged mode to prioritize critical operations) is lacking in traditional, single-function state machine designs that rely on operating system scheduling. They typically respond passively to events rather than actively optimizing strategies.

[0008] Therefore, how to provide a control method for parallel nested state machines in power communication without an operating system, so as to improve the operating efficiency, real-time performance and resource utilization in an operating system-free environment, while optimizing the adaptive capability of communication strategies under the parallel nested management of multiple state machines, has become an urgent technical problem to be solved. Summary of the Invention

[0009] The technical problem to be solved by the present invention is to provide a control method for parallel nested state machines in power communication without an operating system, thereby improving the operating efficiency, real-time performance and resource utilization in an environment without an operating system, while optimizing the adaptive capability of communication strategies under the parallel nested management of multiple state machines.

[0010] This invention is implemented as follows: A method for controlling a parallel nested state machine in power communication without an operating system, applied to a microprocessor without an operating system, for managing at least a first communication protocol state machine and a second communication protocol state machine based on the IEC60870 protocol, comprising the following steps: Step S1: Initialize and run the target communication protocol state machine, which includes the first communication protocol state machine and the second communication protocol state machine. The target communication protocol state machine is used to handle message sending and receiving, state transition and timeout handling of the corresponding communication protocol. The operation of each target communication protocol state machine is integrated into a single main loop that does not depend on the operating system scheduling and timer service. Step S2: When it is necessary to execute a nested task associated with the target communication protocol state machine, activate a nested state machine and associate the nested state machine with the currently activated target communication protocol state machine, so that the state of the nested state machine affects the behavior of the currently activated target communication protocol state machine. Step S3: In the single main loop, obtain the message queue to be sent, and each message in the message queue is pre-configured to include a priority attribute; Step S4: Using a dynamic programming algorithm, based on the priority attributes of each message in the message queue, the current sub-state of each target communication protocol state machine, and the waiting time limit for acknowledgment, a comprehensive analysis is conducted to select an optimal transmission strategy from multiple predetermined transmission strategies. The optimal transmission strategy includes a normal mode strategy and a privileged mode strategy. Step S5: Execute message transmission according to the optimal transmission strategy: If the normal mode strategy is selected, the transmission of multiple message packets is processed according to the existing order or priority order of the message queue; if the privileged mode strategy is selected, only the message packet currently being processed is allowed to be transmitted, and the processing of all other message packets in the message queue is temporarily blocked until the current message packet transmission is completed.

[0011] Furthermore, the first communication protocol state machine is an IEC60870-5-101 protocol state machine, and the second communication protocol state machine is an IEC60870-5-104 protocol state machine. In step S1, the first communication protocol state machine and the second communication protocol state machine are run in parallel, and the events of both are processed through the same single main loop.

[0012] Furthermore, in step S1, the processing of received frames, message sending, timeout handling, and state transition of each target communication protocol state machine are all completed in a single main loop, and the timeout handling is implemented through software polling, without relying on the hardware timer interrupt of the operating system.

[0013] Furthermore, in step S1, when a request instruction from the client is received through the second communication protocol state machine, the message transmission of the first communication protocol state machine is activated by a semaphore or global flag within the same microprocessor. Synchronization and communication between all the target communication protocol state machines are completed within a single main loop, without relying on the inter-task communication mechanism of the operating system.

[0014] Furthermore, the nested task in step S2 is a file access task, the nested state machine is a file access state machine, the file access state machine is used to manage read and write operations on non-volatile memory, and the file access state machine is nested under the first communication protocol state machine.

[0015] Furthermore, step S2 further includes: During the file access state machine's write operation to non-volatile memory, if the first or second communication protocol state machine receives a read request for a directory or file, the read request is placed in a blocked state, and a decision is made based on the current state of the file access state machine to switch to processing other communication services.

[0016] Furthermore, in step S3, the attributes of the message message also include: sequence number, message type ID, message sending reason, whether to wait for acknowledgment flag, message initiation time, last attempt to send time, completion time, and number of retransmissions.

[0017] Furthermore, in step S4, when using the dynamic programming algorithm to select the optimal transmission strategy, a Bang-Bang control strategy is further introduced. This strategy is used to keep the target communication protocol state machine associated with the current file operation in a privileged mode during continuous read / write operations of a single file, so as to avoid frequent interruptions by other operations. After the read / write operation of a single file is completed, the strategy is switched back to the normal mode.

[0018] Furthermore, prior to step S1, the procedure also includes: Step S0: Set communication parameters and attempt to establish a communication link with the communication target to complete the handshake process. After the link is successfully established, all types of message packets enter the initial state.

[0019] Furthermore, the method also includes: Step S6: When a large amount of data needs to be transmitted, enable the caching mode to solve the problem of communication rate asynchrony, and in the gap while waiting for the cached data to be ready, the single master loop switch handles other communication tasks that do not depend on the cached data.

[0020] The advantages of this invention are: 1. By integrating the operation of multiple protocol state machines, timeout polling, and synchronous communication between state machines into a single main loop independent of the operating system, the overhead of traditional systems such as task switching, context saving, and hardware timer interrupts is eliminated, thereby significantly improving operating efficiency, real-time performance, and resource utilization in a bare-metal environment. At the same time, by introducing a nested state machine mechanism, nested tasks are associated with the currently active state machine and can directly control each other's behavior. Combined with a privilege / normal mode adaptive switching strategy based on dynamic programming algorithm and message priority, as well as Bang-Bang control and cache gap task switching in file operation scenarios, flexible optimization of communication strategies and precise resource locking in parallel nested management are achieved.

[0021] 2. Eliminate operating system dependence and significantly reduce system resource consumption and costs: The operation of multiple communication protocol state machines (such as IEC60870-5-101 and 104) and nested state machines is integrated into a single main loop that does not rely on any operating system scheduling and timer services. Compared with traditional solutions that rely on real-time operating systems (RTOS), this avoids the additional memory overhead (such as task stack, TCB, etc.), CPU time consumption, and licensing costs of commercial operating systems brought by the operating system kernel. For microprocessors with extremely limited resources (such as low-power MCUs), it can achieve complex multi-protocol parallel management with extremely low resource consumption, so that tasks that originally required high-performance processors can run stably on inexpensive, low-end hardware platforms, which has significant cost benefits and hardware universality.

[0022] 3. Improve system determinism and predictability through software polling timeout and single main loop synchronization: All timeout handling is implemented through software polling, without relying on the operating system's hardware timer interrupts; at the same time, synchronization and communication between state machines (through activating another protocol via semaphores or global flags) are all completed within a single main loop. This design avoids interrupt response delays, task priority inversion, and uncertain task context switching time common in RTOSs; in scenarios with strong real-time requirements such as power communication, the behavior of this solution is completely deterministic in time, and the execution path and timing of each loop can be accurately analyzed and tested, thereby ensuring that the upper limit of the processing delay of critical messages (such as protection action signals) is controllable, and significantly improving the real-time reliability and behavioral predictability of the system.

[0023] 4. Introducing a nested state machine mechanism to elegantly implement limited preemption of the main communication flow by complex tasks (such as file access): When executing time-consuming nested tasks such as file access, an independent nested state machine is activated and runs in association with the current protocol state machine. This nested state machine can affect the behavior of the main state machine. For example, during a file write operation, the read request is placed in a blocked state. This design cleverly achieves a similar "priority" management effect in a cooperative kernel without an operating system: long tasks do not completely monopolize the CPU, but execute a portion in each state slice of their state machine, and check and process other communication services through a single main loop in the intervals. This avoids the drawback of traditional operating system-free solutions where interrupts must be disabled or busy waiting must be performed when executing long tasks, which would cause other communications to be completely blocked. This ensures both the integrity of file transfer and the responsiveness of the basic communication link.

[0024] 5. An intelligent message scheduling strategy based on dynamic programming and Bang-Bang control balances efficiency and exclusivity of critical transactions: Not only does it select the optimal transmission strategy (normal mode or privileged mode) based on factors such as priority, current sub-state, and waiting time limit through dynamic programming, but it also introduces a Bang-Bang control strategy. During large-block data transmissions requiring atomic operations, such as continuous file reading and writing, Bang-Bang control keeps the associated state machine in privileged mode, temporarily blocking other messages in the queue. The advantages of this dual-mode switching mechanism are: during regular communication, priority queues ensure low latency for important messages; when processing long messages requiring integrity (such as file directories or configuration file downloads), it automatically switches to strict exclusive transmission, preventing interruption by high-priority but fragmented telemetry messages that could lead to file transmission failures or verification errors. Compared to simple pure priority queues or pure FIFO, this invention achieves the best balance between throughput and critical transaction success rate.

[0025] The Bang-Bang strategy is triggered to ensure that important and short-duration tasks are run immediately. The state corresponding to a task that meets the triggering conditions will immediately switch to privileged mode (other tasks are running) or exclusive mode (idle state), run the task and block other tasks (such as high-priority tasks and long-duration tasks) until the task is completed. Other tasks will not run until the task triggered by the Bang-Bang strategy is completed. The task triggered by the Bang-Bang strategy cannot be suspended by any other task before the strategy expires.

[0026] 6. Unified handling of synchronous and asynchronous protocols (101 and 104) simplifies interconnection and data interaction of heterogeneous networks: It can run state machines based on two protocols, IEC60870-5-101 (typically used for serial ports, asynchronous communication) and IEC60870-5-104 (typically used for Ethernet, synchronous communication), in parallel, and process events of both through the same single master loop; In power automation systems, it is often necessary to communicate with serial port RTUs and network backends simultaneously; This invention achieves seamless integration of these two heterogeneous protocol stacks in a bare-metal environment without an operating system, so that, for example, remote control commands received through 104 can be immediately forwarded to serial port devices by activating the 101 state machine through internal semaphores. The entire process does not require operating system message queue forwarding, has extremely low latency, and is simple to implement, making it very suitable as the core software architecture of a protocol conversion gateway or data concentrator.

[0027] 7. The combination of caching mode and nested state machines effectively decouples communication tasks with different speeds from large data transmissions: Caching mode is enabled during large data transmissions to solve the problem of speed asynchrony. During the intervals while waiting for cached data to be ready, a single main loop switches to handle other communication tasks that do not depend on the cached data. The advantages of this feature are: when a slow device (such as a serial port 101 slave) uploads historical files to a fast network (104 master), caching mode avoids the fast side waiting for the slow side for a long time; more importantly, during idle time while waiting for external storage (such as SPI Flash) or slow peripherals to prepare data, the single main loop will not be idle and blocked, but will actively switch to serve other protocol state machines (such as processing new telemetry messages). This mechanism makes full use of CPU time, avoiding the real-time performance degradation caused by "busy waiting" or "idling" common in traditional bare-metal programs, and achieving pseudo-parallel execution of "time-consuming transmission tasks" and "low-latency periodic communication tasks." Attached Figure Description

[0028] The present invention will be further described below with reference to the accompanying drawings and embodiments.

[0029] Figure 1 This is a flowchart of a parallel nested state machine control method for power communication without an operating system, according to the present invention. Detailed Implementation

[0030] The overall approach of the technical solution in this application is as follows: A single main loop, independent of operating system scheduling and timer services, serves as the sole execution engine. This loop integrates the operation, timeout polling, state transitions, and inter-state machine collaborative communication of multiple communication protocol state machines (such as IEC60870-5-101 and 104), thereby constructing a deterministic, high real-time multi-protocol parallel processing framework in the bare-metal system. Based on this, two key adaptive and collaborative mechanisms are further introduced: First, a nested state machine mechanism. When complex tasks such as file access need to be performed, an independent nested state machine is activated and associated with the current communication protocol state machine. This allows nested tasks to influence the behavior of the main state machine in a "limited preemption" manner, maintaining basic communication responsiveness while ensuring the integrity of long tasks. Second, an intelligent message scheduling strategy based on dynamic programming and Bang-Bang control. By comprehensively analyzing message priority, current protocol sub-state, and response time limits, "normal mode" or "privileged mode" is dynamically selected for message transmission. During large-block data transmission, Bang-Bang control is used to achieve atomic exclusive access to critical transactions. Through the aforementioned interconnected technical means, efficient parallel and nested management of multi-protocol state machines is achieved on microprocessors without an operating system, significantly improving operating efficiency, real-time performance, resource utilization, and adaptability to complex communication scenarios.

[0031] Please refer to Figure 1 As shown, a preferred embodiment of the power communication parallel nested state machine control method without an operating system is provided by the present invention. Applied to a microprocessor without an operating system, it manages at least a first communication protocol state machine and a second communication protocol state machine based on the IEC60870 protocol, and includes the following steps: Step S1: Initialize and run the target communication protocol state machine, which includes the first communication protocol state machine and the second communication protocol state machine. The target communication protocol state machine is used to handle message sending and receiving, state transition and timeout handling of the corresponding communication protocol. The operation of each target communication protocol state machine is integrated into a single main loop that does not depend on the operating system scheduling and timer service. Step S2: When it is necessary to execute a nested task associated with the target communication protocol state machine, activate a nested state machine and associate the nested state machine with the currently activated target communication protocol state machine, so that the state of the nested state machine affects the behavior of the currently activated target communication protocol state machine. The specific implementation method by which the nested state machine influences the behavior of the main state machine (target communication protocol state machine) is as follows: Each communication protocol state machine instance contains a pointer to a nested state machine, nested_fsm_ptr. If the pointer is NULL, it indicates that there are no nested tasks.

[0032] When a nested state machine is activated, the main state machine calls nested_fsm_ptr->evaluate() before each state transition. This function returns a nested_action enumeration value, which may include: NACT_NONE (no effect), NACT_BLOCK_READ (block read request), NACT_SUSPEND_SEND (pause sending), and NACT_YIELD_CPU (voluntarily yield execution).

[0033] For example, during a file write operation, the file access state machine returns NACT_BLOCK_READ. When the main state machine receives a request to read a directory or file, it directly jumps to the "wait" sub-state without entering the actual read operation. At the same time, the main state machine checks nested_fsm_ptr->can_switch_task(). If it returns true, the current loop will no longer process its own state transition, and instead, the single main loop will process other state machines, thus realizing "determining whether to switch to other communication services based on the current state of the nested state machine".

[0034] Specifically, the influence of the nested state machine on the behavior of the main state machine can be achieved through a "state query and action callback" mechanism. Each communication protocol state machine (main state machine) contains a pointer to the currently active nested state machine instance in its data structure. Before the main state machine performs a state transition or processes a specific event (e.g., receiving a read request message), it calls a predefined interface function (such as nested_fsm_evaluate()) of the nested state machine. This interface function returns an action suggestion code based on the current internal state of the nested state machine (e.g., "performing a file write operation"). For example, when the file access state machine is in the sub-state of "writing data to non-volatile memory," it returns an "ACTION_BLOCK" suggestion code for "read directory" or "read file" events. Upon receiving this suggestion code, the main state machine places the currently received read request into a temporary blocking queue instead of processing it immediately, thus achieving "limited preemption" of the main process by the nested task. Once the nested state machine completes its write operation, it returns "ACTION_NONE" or "ACTION_ALLOW", allowing the main state machine to then remove the previously pending read requests from the blocking queue and process them.

[0035] Step S3: In the single main loop, obtain the message queue to be sent, and each message in the message queue is pre-configured to include a priority attribute; Step S4: Using a dynamic programming algorithm, based on the priority attributes of each message in the message queue, the current sub-state of each target communication protocol state machine, and the waiting time limit for acknowledgment, a comprehensive analysis is conducted to select an optimal transmission strategy from multiple predetermined transmission strategies. The optimal transmission strategy includes a normal mode strategy and a privileged mode strategy. Step S5: Execute message transmission according to the optimal transmission strategy: If the normal mode strategy is selected, the transmission of multiple message packets is processed according to the existing order or priority order of the message queue; if the privileged mode strategy is selected, only the message packet currently being processed is allowed to be transmitted, and the processing of all other message packets in the message queue is temporarily blocked until the current message packet transmission is completed.

[0036] The first communication protocol state machine is the IEC60870-5-101 protocol state machine, and the second communication protocol state machine is the IEC60870-5-104 protocol state machine; In step S1, the first communication protocol state machine and the second communication protocol state machine are run in parallel, and the events of both are processed through the same single main loop.

[0037] In a preferred embodiment of the present invention, the single main loop is an infinite loop structure (while(1)), in which the following operations are performed sequentially in each loop: 1. Poll the state machines of each communication protocol: Call the "frame reception processing function", "state transition function" and "message sending function" of each state machine in a fixed order (e.g., first 101 then 104); 2. Polling nested state machines: If an active nested state machine (such as a file access state machine) exists, its state handling function is called; 3. Unified timeout check: Based on the global time counter, traverse the timer structure of all state machines to determine whether a timeout event has been triggered; 4. Message queue scheduling: Call the dynamic programming selection module to determine whether to send a message in the current loop and which mode to use; 5. Short-term sleep or direct loop: In scenarios with extremely low latency requirements, it directly enters the next loop; in power-sensitive scenarios, a limited number of NOPs can be inserted or it can enter a low-power idle mode.

[0038] By using the fixed sequence and deterministic scheduling described above, each state machine is guaranteed an execution opportunity in each loop, thereby achieving "pseudo-parallel" operation in an environment without an operating system.

[0039] In a specific embodiment, the single main loop is implemented as an infinite loop structure (while(1)). Inside this loop, the following modules are executed sequentially according to a predetermined order: First, the receive frame queue of the first communication protocol state machine (e.g., IEC60870-5-101) is polled and processed, and its state transition function and message sending function are executed; second, the second communication protocol state machine (e.g., IEC60870-5-104) is processed in the same way; next, any active nested state machines (e.g., file access state machines) are checked and run; then, a unified timeout check function is called, which iterates through the timer structures of all active state machines based on a global clock counter (provided by the microprocessor's SysTick timer in non-interrupt mode); finally, the message queue scheduling module is executed. Through this deterministic sequential execution, each state machine gets a processing opportunity in each loop cycle, thus achieving deterministic "pseudo-parallelism" in an operating system-free environment.

[0040] In step S1, the processing of received frames, message sending, timeout handling, and state transition of each target communication protocol state machine are all completed in a single main loop, and the timeout handling is implemented by software polling, without relying on the hardware timer interrupt of the operating system.

[0041] To achieve software polling timeouts that do not rely on hardware timer interrupts, this invention provides a global time base using any of the following methods: Method A (Internal Clock Counter): This method utilizes the SysTick or DWT counter built into the microprocessor core, setting it to automatically increment a global unsigned long integer variable g_sys_tick_ms every 1ms. The main loop reads this variable each time and compares it with the timeout recorded by each state machine. Although this method uses a hardware counter, it does not rely on the operating system and does not enable any interrupts (it only requires polling to read the data).

[0042] Method B (Instruction Cycle Estimation): Before starting the main loop, a rough time base is calibrated by running a fixed number of empty loops (e.g., approximately 1ms for 1000 loops), and then this count is periodically accumulated in the main loop. This method has lower accuracy but is sufficient for second-level timeout scenarios.

[0043] This embodiment uses method A, which configures SysTick to increment every millisecond during the initialization phase, but disables interrupts. The main loop performs all timeout checks by querying g_sys_tick_ms.

[0044] In step S1, when a request instruction from the client is received through the second communication protocol state machine, the message transmission of the first communication protocol state machine is activated by a semaphore or global flag bit within the same microprocessor. Synchronization and communication between all the target communication protocol state machines are completed within a single main loop without relying on the inter-task communication mechanism of the operating system.

[0045] To avoid confusion with the concept of "semaphores" in operating systems and to clarify its implementation in a bare-metal environment, further explanation is provided here. The "semaphore or global flag within the same microprocessor" specifically refers to a global variable (e.g., an 8-bit or 32-bit integer) in the microprocessor's memory. When the second communication protocol state machine (protocol 104) receives an instruction to activate the first communication protocol state machine (protocol 101) to send a message, it does not call the operating system's semaphore `Give` function, but instead executes a simple assignment statement, such as `g_activation_flag_101=1`. Within the same single main loop, the first communication protocol state machine checks this flag at the beginning of each loop iteration (e.g., `if(g_activation_flag_101)`). If the flag is valid, after executing its original state logic, it appends the message transmission task and finally clears the flag. Since the entire checking and assignment process is completed within the same main loop thread, and there is no task preemption as in the operating system, this primitive global flag operation is atomic, safe, and does not introduce any system call overhead.

[0046] The nested task in step S2 is a file access task, and the nested state machine is a file access state machine. The file access state machine is used to manage read and write operations on non-volatile memory, and the file access state machine is nested under the first communication protocol state machine.

[0047] Step S2 further includes: During the file access state machine's write operation to non-volatile memory, if the first or second communication protocol state machine receives a read request for a directory or file, the read request is placed in a blocked state, and a decision is made based on the current state of the file access state machine to switch to processing other communication services.

[0048] In step S3, the attributes of the message message also include: sequence number, message type ID, message sending reason, whether to wait for acknowledgment flag, message initiation time, last attempt to send time, completion time, and number of retransmissions.

[0049] In step S4, when using dynamic programming to select the optimal transmission strategy, a Bang-Bang control strategy is further introduced. This strategy is used to keep the target communication protocol state machine associated with the current file operation in privileged mode during continuous read / write operations of a single file, so as to avoid frequent interruptions by other operations. After the read / write operation of a single file is completed, the strategy is switched back to the normal mode.

[0050] In practice, only sudden events or remote control during communication are considered the highest priority tasks. If other communication tasks are in progress (such as file reading and writing), the sudden event or remote control will enter the privileged mode policy, blocking other communication tasks and preventing interruption by other communication tasks until the highest priority task is completed.

[0051] The specific implementation of the dynamic programming algorithm is as follows: State variables: the highest priority in the current message queue, P_max (the larger the value, the higher the priority), the sub-state s of the currently active state machine (e.g., S_WAIT_CONFIRM (waiting for acknowledgment), S_TRANSFER_FILE (transferring files)), and the latest remaining acknowledgment timeout for the current message, T_left (in milliseconds).

[0052] Action set: A = {Normal mode, Privileged mode}.

[0053] Cost function: Cost(mode) = w1*(1-P_max / P_max_possible) + w2*(T_left / T_max) + w3*I_privilege_penalty, where I_privilege_penalty is 0.2 in privileged mode (representing the cost of blocking other packets) and 0 in normal mode. Weights w1, w2, and w3 are configured by the system (typical values ​​w1=0.5, w2=0.3, w3=0.2).

[0054] Here, Cost(mode) represents the total cost of choosing a certain transmission strategy (normal mode or privileged mode). The smaller the value, the better the mode is in the current state, and the dynamic programming algorithm will choose the mode with the smaller cost. w1, w2, and w3 are weight coefficients, corresponding to the importance of the priority item, time limit item, and privilege penalty item, respectively. The sum of the three is usually 1, used to balance the influence of different factors on the decision. P_max represents the highest priority value of all messages in the message queue to be sent (the larger the value, the higher the priority, for example, the priority of remote control messages is higher than that of telemetry messages). P_max_possible represents the maximum possible priority value defined by the system (such as 255), used to normalize P_max to the range [0,1]. 1-P_max / P_max_possible represents the priority cost item. When the highest priority in the queue is higher (P_max is close to P_max_possible), this item is smaller. The lower the cost, the more the algorithm tends to choose this mode to ensure that high-priority messages are processed as quickly as possible; T_left represents the latest acknowledgment timeout (in milliseconds) for the currently being processed or the message at the head of the queue, indicating the remaining time that can be tolerated before timeout; T_max represents the maximum acknowledgment timeout allowed by the system (e.g., 10 seconds), used to normalize T_left to the [0,1] interval; T_left / T_max represents the urgency of the timeout, the shorter the remaining time, the smaller this term, the lower the cost, and the more the algorithm will tend to choose the mode that can complete the message as quickly as possible (usually the privileged mode); I_privilege_penalty represents the privileged mode penalty, a flag valued at 0 or 0.2: when calculating the cost of privileged mode, I_privilege_penalty = 0.2 (representing the cost of blocking other messages); when calculating the cost of normal mode, I_privilege_penalty = 0.

[0055] Recursive strategy: In each round of scheduling, only the current head packet or the highest priority packet is considered, the cost of the two modes is calculated, and the mode with the lower cost is selected. If T_left < 50ms and the priority is higher than the threshold, the privileged mode is forced to be selected.

[0056] The integration of Bang-Bang control: When the file access state machine is in the FSM_FILE_WRITE (file write failed) or FSM_FILE_READ sub-state, it directly outputs "privileged mode" and ignores the cost calculation result of dynamic programming until the file access sub-state exits. This is equivalent to providing a "hard switch" overriding mechanism during file operations.

[0057] In the collaboration of dynamic programming and Bang-Bang control, the final transmission mode selection follows the priority order (from highest to lowest): 1. Bang-Bang control conditions: If an emergency occurs or remote control is needed, the system will be forced into privileged mode; 2. Dynamic programming calculation results: If condition 1 is not met, then the selection mode is based on the cost function; 3. Default fallback strategy: If dynamic programming cannot be calculated due to missing states, the normal mode will be used by default.

[0058] In privileged mode, only the currently processed single message is allowed to complete its full sending, receiving, and acknowledgment process (including possible retransmission). During this period, the entire message queue is marked as blocked, and the processing functions of other messages are skipped until the message's state machine enters the SEND_COMPLETE sub-state.

[0059] Consider a dynamic decision-making scenario: The system is currently transmitting a long historical file via the first communication protocol state machine (protocol 101) (Bang-Bang control has been triggered, forcing it into privileged mode). During this process, the second communication protocol state machine (protocol 104) receives a remote control command message from the master station with a priority marked "high" and an extremely tight response time limit (e.g., 50ms remaining).

[0060] In the control logic of this invention, because Bang-Bang control has a high priority, the entire file transfer process remains in privileged mode and will not be interrupted by remote control commands, thus ensuring the integrity and atomicity of file transfer. However, the dynamic programming algorithm still runs in the background. When a remote control command is placed in the message queue, the algorithm calculates its cost function. Although the actual strategy selected is not directly determined by the cost function due to Bang-Bang control, the system records the urgency of the remote control command. Once a single consecutive read / write block (or the entire file operation) of the current file is completed, Bang-Bang control releases its forced privileged state, and the system immediately dynamically elevates the priority of the remote control command to the highest level based on the high urgency cost calculated by the dynamic programming algorithm, and sends the command in privileged mode with priority in the next cycle. This two-level collaborative mechanism ensures both the atomicity of long transactions and that truly urgent messages do not suffer unacceptable delays.

[0061] Before step S1, the method further includes: Step S0: Set communication parameters and attempt to establish a communication link with the communication target to complete the handshake process. After the link is successfully established, all types of message packets enter the initial state.

[0062] The method further includes: Step S6: When a large amount of data needs to be transmitted, enable the caching mode to solve the problem of communication rate asynchrony, and in the gap while waiting for the cached data to be ready, the single master loop switch handles other communication tasks that do not depend on the cached data.

[0063] The caching mode is automatically enabled under any of the following conditions: the data block to be sent exceeds the system-set threshold (e.g., 512 bytes), or the baud rate difference between the two communicating parties exceeds 4 times.

[0064] Once enabled, data blocks are read in segments into a circular buffer, and the main loop retrieves one segment from the buffer and sends it in each round. While waiting for the next segment to become ready from a slow peripheral (such as an SPI Flash or serial slave), the main loop checks the `buffer_ready_flag`. If it is false, it does not continue processing the data transmission state machine, but instead jumps to execute other communication tasks that do not depend on the data in this buffer (such as processing newly arrived telemetry messages). This "gap switching" is implemented through a `WAIT_DATA_READY` sub-state of the state machine, in which the state machine returns `sched_yield_request`, and the single main loop immediately switches to the processing function of the next state machine.

[0065] The specific implementation of the buffered mode can be based on a ring buffer. When enabling buffered mode for large-scale data transfer (e.g., reading a file from a slow SPI Flash and sending it over a high-speed Ethernet), the transmit state machine does not send the entire file at once, but rather divides the file into multiple data blocks. One data block is taken from the ring buffer each time for transmission. When the data blocks in the buffer are about to run out and the next block needs to be read from the SPI Flash, the transmit state machine enters an intermediate sub-state called "WAIT_DATA_READY". In this state, the transmit state machine sets a "data not ready" flag and then actively returns CPU control to the single-main loop. Upon detecting this flag, the single-main loop stops calling the transmit function of the transmit state machine and instead polls and executes other communication tasks that do not depend on the buffered data (e.g., processing periodic heartbeat messages of the 101 protocol). When the SPI Flash completes data reading in the background (via DMA or simple polling) and fills the ring buffer with the data, it clears the "data not ready" flag. In the next single main loop cycle, when the sending state machine is called again, it detects that the flag has been cleared and transitions from the "WAIT_DATA_READY" sub-state to the "DATA_READY" sub-state to continue sending the next data block. In this way, the CPU can make full use of the gaps while waiting for slow I / O, achieving "pseudo-parallelism" between time-consuming tasks and real-time small tasks.

[0066] In summary, the advantages of this invention are: 1. By integrating the operation of multiple protocol state machines, timeout polling, and synchronous communication between state machines into a single main loop independent of the operating system, the overhead of traditional systems such as task switching, context saving, and hardware timer interrupts is eliminated, thereby significantly improving operating efficiency, real-time performance, and resource utilization in a bare-metal environment. At the same time, by introducing a nested state machine mechanism, nested tasks are associated with the currently active state machine and can directly control each other's behavior. Combined with a privilege / normal mode adaptive switching strategy based on dynamic programming algorithm and message priority, as well as Bang-Bang control and cache gap task switching in file operation scenarios, flexible optimization of communication strategies and precise resource locking in parallel nested management are achieved.

[0067] 2. Eliminate operating system dependence and significantly reduce system resource consumption and costs: The operation of multiple communication protocol state machines (such as IEC60870-5-101 and 104) and nested state machines is integrated into a single main loop that does not rely on any operating system scheduling and timer services. Compared with traditional solutions that rely on real-time operating systems (RTOS), this avoids the additional memory overhead (such as task stack, TCB, etc.), CPU time consumption, and licensing costs of commercial operating systems brought by the operating system kernel. For microprocessors with extremely limited resources (such as low-power MCUs), it can achieve complex multi-protocol parallel management with extremely low resource consumption, so that tasks that originally required high-performance processors can run stably on inexpensive, low-end hardware platforms, which has significant cost benefits and hardware universality.

[0068] 3. Improve system determinism and predictability through software polling timeout and single main loop synchronization: All timeout handling is implemented through software polling, without relying on the operating system's hardware timer interrupts; at the same time, synchronization and communication between state machines (through activating another protocol via semaphores or global flags) are all completed within a single main loop. This design avoids interrupt response delays, task priority inversion, and uncertain task context switching time common in RTOSs; in scenarios with strong real-time requirements such as power communication, the behavior of this solution is completely deterministic in time, and the execution path and timing of each loop can be accurately analyzed and tested, thereby ensuring that the upper limit of the processing delay of critical messages (such as protection action signals) is controllable, and significantly improving the real-time reliability and behavioral predictability of the system.

[0069] 4. Introducing a nested state machine mechanism to elegantly implement limited preemption of the main communication flow by complex tasks (such as file access): When executing time-consuming nested tasks such as file access, an independent nested state machine is activated and runs in association with the current protocol state machine. This nested state machine can affect the behavior of the main state machine. For example, during a file write operation, the read request is placed in a blocked state. This design cleverly achieves a similar "priority" management effect in a cooperative kernel without an operating system: long tasks do not completely monopolize the CPU, but execute a portion in each state slice of their state machine, and check and process other communication services through a single main loop in the intervals. This avoids the drawback of traditional operating system-free solutions where interrupts must be disabled or busy waiting must be performed when executing long tasks, which would cause other communications to be completely blocked. This ensures both the integrity of file transfer and the responsiveness of the basic communication link.

[0070] 5. An intelligent message scheduling strategy based on dynamic programming and Bang-Bang control balances efficiency and exclusivity of critical transactions: Not only does it select the optimal transmission strategy (normal mode or privileged mode) based on factors such as priority, current sub-state, and waiting time limit through dynamic programming, but it also introduces a Bang-Bang control strategy. During large-block data transmissions requiring atomic operations, such as continuous file reading and writing, Bang-Bang control keeps the associated state machine in privileged mode, temporarily blocking other messages in the queue. The advantages of this dual-mode switching mechanism are: during regular communication, priority queues ensure low latency for important messages; when processing long messages requiring integrity (such as file directories or configuration file downloads), it automatically switches to strict exclusive transmission, preventing interruption by high-priority but fragmented telemetry messages that could lead to file transmission failures or verification errors. Compared to simple pure priority queues or pure FIFO, this invention achieves the best balance between throughput and critical transaction success rate.

[0071] The Bang-Bang strategy is triggered to ensure that important and short-duration tasks are run immediately. The state corresponding to a task that meets the triggering conditions will immediately switch to privileged mode (other tasks are running) or exclusive mode (idle state), run the task and block other tasks (such as high-priority tasks and long-duration tasks) until the task is completed. Other tasks will not run until the task triggered by the Bang-Bang strategy is completed. The task triggered by the Bang-Bang strategy cannot be suspended by any other task before the strategy expires.

[0072] 6. Unified handling of synchronous and asynchronous protocols (101 and 104) simplifies interconnection and data interaction of heterogeneous networks: It can run state machines based on two protocols, IEC60870-5-101 (typically used for serial ports, asynchronous communication) and IEC60870-5-104 (typically used for Ethernet, synchronous communication), in parallel, and process events of both through the same single master loop; In power automation systems, it is often necessary to communicate with serial port RTUs and network backends simultaneously; This invention achieves seamless integration of these two heterogeneous protocol stacks in a bare-metal environment without an operating system, so that, for example, remote control commands received through 104 can be immediately forwarded to serial port devices by activating the 101 state machine through internal semaphores. The entire process does not require operating system message queue forwarding, has extremely low latency, and is simple to implement, making it very suitable as the core software architecture of a protocol conversion gateway or data concentrator.

[0073] 7. The combination of caching mode and nested state machines effectively decouples communication tasks with different speeds from large data transmissions: Caching mode is enabled during large data transmissions to solve the problem of speed asynchrony. During the intervals while waiting for cached data to be ready, a single main loop switches to handle other communication tasks that do not depend on the cached data. The advantages of this feature are: when a slow device (such as a serial port 101 slave) uploads historical files to a fast network (104 master), caching mode avoids the fast side waiting for the slow side for a long time; more importantly, during idle time while waiting for external storage (such as SPI Flash) or slow peripherals to prepare data, the single main loop will not be idle and blocked, but will actively switch to serve other protocol state machines (such as processing new telemetry messages). This mechanism makes full use of CPU time, avoiding the real-time performance degradation caused by "busy waiting" or "idling" common in traditional bare-metal programs, and achieving pseudo-parallel execution of "time-consuming transmission tasks" and "low-latency periodic communication tasks."

[0074] While specific embodiments of the present invention have been described above, those skilled in the art should understand that the specific embodiments described are merely illustrative and not intended to limit the scope of the present invention. Equivalent modifications and variations made by those skilled in the art in accordance with the spirit of the present invention should be covered within the scope of protection of the claims of the present invention.

Claims

1. A power communication parallel nested state machine non-OS control method, characterized in that: For use in microprocessors without an operating system, for managing at least a first communication protocol state machine and a second communication protocol state machine based on the IEC60870 protocol, the following steps are included: Step S1: Initialize and run the target communication protocol state machine, which includes the first communication protocol state machine and the second communication protocol state machine. The target communication protocol state machine is used to handle message sending and receiving, state transition and timeout handling of the corresponding communication protocol. The operation of each target communication protocol state machine is integrated into a single main loop that does not depend on the operating system scheduling and timer service. Step S2: When it is necessary to execute a nested task associated with the target communication protocol state machine, activate a nested state machine and associate the nested state machine with the currently activated target communication protocol state machine, so that the state of the nested state machine affects the behavior of the currently activated target communication protocol state machine. Step S3: In the single main loop, obtain the message queue to be sent, and each message in the message queue is pre-configured to include a priority attribute; Step S4: Using a dynamic programming algorithm, based on the priority attributes of each message in the message queue, the current sub-state of each target communication protocol state machine, and the waiting time limit for acknowledgment, a comprehensive analysis is conducted to select an optimal transmission strategy from multiple predetermined transmission strategies. The optimal transmission strategy includes a normal mode strategy and a privileged mode strategy. Step S5: Execute message transmission according to the optimal transmission strategy: If the normal mode strategy is selected, the transmission of multiple message packets is processed according to the existing order or priority order of the message queue; if the privileged mode strategy is selected, only the message packet currently being processed is allowed to be transmitted, and the processing of all other message packets in the message queue is temporarily blocked until the current message packet transmission is completed.

2. The power communication non-operating system control method of claim 1, wherein: The first communication protocol state machine is the IEC60870-5-101 protocol state machine, and the second communication protocol state machine is the IEC60870-5-104 protocol state machine; In step S1, the first communication protocol state machine and the second communication protocol state machine are run in parallel, and the events of both are processed through the same single main loop.

3. The power communication non-operating system control method of claim 1, wherein: In step S1, the processing of received frames, message sending, timeout handling, and state transition of each target communication protocol state machine are all completed in a single main loop, and the timeout handling is implemented by software polling, without relying on the hardware timer interrupt of the operating system.

4. The power communication non-operating system control method of parallel nested state machines of claim 1, wherein: In step S1, when a request instruction from the client is received through the second communication protocol state machine, the message transmission of the first communication protocol state machine is activated by a semaphore or global flag bit within the same microprocessor. Synchronization and communication between all target communication protocol state machines are completed within a single main loop without relying on the inter-task communication mechanism of the operating system.

5. The power communication parallel nested state machine control method without an operating system as described in claim 1, characterized in that: The nested task in step S2 is a file access task, and the nested state machine is a file access state machine. The file access state machine is used to manage read and write operations on non-volatile memory, and the file access state machine is nested under the first communication protocol state machine.

6. A power communication parallel nested state machine non-OS control method according to claim 5, characterized in that: Step S2 further includes: During the file access state machine's write operation to non-volatile memory, if the first or second communication protocol state machine receives a read request for a directory or file, the read request is placed in a blocked state, and a decision is made based on the current state of the file access state machine to switch to processing other communication services.

7. The power communication parallel nested state machine control method without an operating system as described in claim 1, characterized in that: In step S3, the attributes of the message message also include: sequence number, message type ID, message sending reason, whether to wait for acknowledgment flag, message initiation time, last attempt to send time, completion time, and number of retransmissions.

8. The power communication parallel nested state machine control method without an operating system as described in claim 1, characterized in that: In step S4, when using dynamic programming to select the optimal transmission strategy, a Bang-Bang control strategy is further introduced. This strategy is used to keep the target communication protocol state machine associated with the current file operation in privileged mode during continuous read / write operations of a single file, so as to avoid frequent interruptions by other operations. After the read / write operation of a single file is completed, the strategy is switched back to the normal mode.

9. The power communication parallel nested state machine control method without an operating system as described in claim 1, characterized in that: Before step S1, the method further includes: Step S0: Set communication parameters and attempt to establish a communication link with the communication target to complete the handshake process. After the link is successfully established, all types of message packets enter the initial state.

10. The power communication parallel nested state machine control method without an operating system as described in claim 1, characterized in that: The method further includes: Step S6: When a large amount of data needs to be transmitted, enable the caching mode to solve the problem of communication rate asynchrony, and in the gap while waiting for the cached data to be ready, the single master loop switch handles other communication tasks that do not depend on the cached data.