IEC104 communication protocol implementation method based on workflow

Through the IEC104 communication protocol based on workflow, dynamic analysis and service decoupling of various types of IEC104 ASDUs is realized, and a modular hierarchical architecture and intelligent reconnection strategy are adopted to solve the problem of weak coupling and observability of the protocol layer and the service layer in the existing technology, improving the system's maintainability and resource utilization efficiency.

CN120281831AActive Publication Date: 2025-07-08NANJING DAHUO TECHNOLOGY CO LTD

Patent Information

Application Number
CN202510750131.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-06
Publication Date
2025-07-08
Estimated Expiration
2045-06-06

AI Technical Summary

Technical Problem

In the industrial automation and power monitoring systems, the existing IEC104 communication protocol has problems such as network jitter and resource waste in the protocol layer and service layer, lack of structured push and weak observability of logs, and fixed reconnection strategies.

Method used

The IEC104 communication protocol implementation method based on workflow is adopted, and the configurable workflow engine is used to dynamic analysis and service decouple of ASDU, combined with a modular hierarchical architecture, integrate intelligent reconnection and structured log push, and optimize reconnection control through link quality prediction and exponential backoff strategy.

Benefits of technology

It realizes dynamic analysis and service decoupling of ASDU type, improves the observability and maintainability of the system, reduces network jitter and resource waste, and supports front-end visualization and alarm system linkage.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120281831A_ABST
    Figure CN120281831A_ABST
Patent Text Reader

Abstract

The invention discloses an IEC104 communication protocol implementation method based on workflow, which belongs to the technical field of electric power communication, comprises the steps of initialization, link management, service analysis, timing scheduling, message receiving, message sending, service response and state recovery, and solves the problem of dynamic analysis and service decoupling of various ASDUs of IEC104 by utilizing a configurable workflow engine. In order to solve the technical problem of integrating intelligent reconnection and structured log pushing in a modular layered architecture, the invention adopts modular division, link management, timing scheduling, message receiving and sending, service analysis, state recovery and other module duty single decoupling, and unified log queue pushing, so that the observability of the system is greatly improved, and the reliability of the system is improved. An exponential backoff strategy is combined with link monitoring, intelligent reconnection is achieved, and timeliness and resource saving are both considered.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention belongs to the technical field of power communication, and particularly relates to a method for implementing the IEC104 communication protocol based on a workflow. Background Art

[0002] In existing industrial automation and power monitoring systems, the IEC104 communication protocol is generally implemented by a process-oriented state machine or a hard-coded callback method, which has the following deficiencies: The protocol layer and the service layer are highly coupled. When modifying or extending a certain ASDU type, a large amount of code often needs to be changed, resulting in poor maintainability.

[0003] Most logs are scattered printf / debug statements, lacking unified structured push and front-end linkage, making debugging difficult and observability weak.

[0004] The reconnection strategy is mostly "fixed interval retry", which cannot be dynamically adjusted according to the network status, easily causing network jitter or resource waste, and having insufficient fault tolerance. Summary of the Invention

[0005] The purpose of the present invention is to provide a method for implementing the IEC104 communication protocol based on a workflow, which solves the technical problems of dynamically parsing various ASDUs of IEC104 and decoupling services by using a configurable workflow engine, and integrating intelligent reconnection and structured log push in a modular hierarchical architecture.

[0006] To achieve the above purpose, the present invention adopts the following technical solutions: A method for implementing the IEC104 communication protocol based on a workflow includes the following steps: Step 1: Initialization phase, the initialization module loads communication configuration parameters, creates a communication channel, registers a timing task, initializes the link state and counter, and establishes a log system; Step 2: Link management phase, the link management module establishes a TCP communication link, activates the timing task, parses the slave confirmation message, maintains link heartbeat detection, and dynamically updates the communication sequence number; Step 3: Service parsing phase, the service parsing module parses the ASDU type identifier of the received frame, executes the workflow, generates structured data according to the type matching parsing template, executes data push and instruction legality verification, and generates and outputs log entries; Step 4: Timing scheduling phase, the timer scheduling module activates periodic tasks based on the link state, routes the event processing function according to the counter ID, adaptively calculates the backoff delay in combination with the link quality prediction and anomaly detection mechanism, realizes self-optimized reconnection control, generates a control command message and records the log; Step 5: In the message reception phase, the message reception processing module receives the byte stream, splits the valid frames through the synchronization state machine, classifies and processes I-frames, S-frames, and U-frames, and generates parsing logs to be pushed to the log queue; Step 6: In the message sending phase, the message sending and caching module assembles and sends messages according to the IEC104 protocol, and manages the sending cache and the timeout retransmission mechanism; Step 7: In the service response phase, the service processing and response module concurrently processes the ASDU task objects, generates feedback frames, and generates full-process logs; Step 8: In the status recovery phase, the sending status recovery module implements a backoff retransmission strategy for the messages with sending failures, triggers disconnection reconnection and then restores communication, and generates retry logs.

[0007] Preferably, when executing Step 1, the specific steps executed by the initialization module are as follows: Step 1-1: Load the configuration file containing the target address, ASDU address, data start address, and time parameters; Step 1-2: Create a TCP communication channel object with a connection status identifier; Step 1-3: Register timed tasks including heartbeat detection, confirmation timeout, and automatic reconnection; Step 1-4: Initialize the link status as disconnected and clear the communication sequence number; Step 1-5: Build a log queue system linked with the visualization module.

[0008] Preferably, when executing Step 2, the link management module executes the following steps: Step 2-1: Initiate a TCP connection based on the configuration parameters and update the connection status flag; Step 2-2: Activate the timed tasks related to link maintenance after the link is established; Step 2-3: Send the link start frame and parse the slave station confirmation message; Step 2-4: Periodically maintain heartbeat detection and update the communication sequence number.

[0009] Preferably, when executing Step 3, the execution steps of the service parsing module are as follows: Step 3-1: Extract the ASDU type identifier of the received I-frame, and match the parsing process template according to the ASDU type identifier; Step 3-2: Trigger the parsing workflow according to the ASDU type identifier, and sequentially execute the processing processes of field extraction, numerical conversion, quality verification, and time tagging according to the logical nodes; Step 3-3: Package the telemetry data and telecontrol data to obtain a standardized object, and asynchronously push the standardized object to the monitoring system; Step 3-4: Verify the legality of the remote control command according to the control records cached in the send buffer. After the verification passes, generate an execution signal according to the content of the remote control command, record the operation trajectory, and generate an operation log; Step 3-5: Process the sequential event class data to construct a timing queue, and process the remote adjustment instruction class data to trace the operation link; Step 3-6: Generate a structured log entry containing the information body address, processing status, and time stamp, and synchronize the log entry to the log library, visualization platform, and alarm system.

[0010] Preferably, when executing Step 4, the execution steps of the timer scheduling module are as follows: Step 4-1: Real-time obtain the connection status flag sent by the link management module. When the link connection is successful, activate the three pre-registered timing tasks and start the periodic timer; Step 4-2: Route to the corresponding processing according to the counter ID, including: Processing for the connection check task to trigger reconnection; Processing for the time synchronization task to trigger the generation of a calibration command; Processing for the total call task to trigger the generation of a call command; Processing for the electric energy call task to trigger according to the configured interval; Step 4-3: For any timing event or external "connection disconnected" signal, obtain the current connection status flag and the time of the most recent heartbeat confirmation; if the connection status flag is "disconnected" or the heartbeat confirmation times out, use the exponential backoff algorithm to generate a reconnection delay, and output a reconnection request signal after the delay; the reconnection request signal includes the delay time and the number of reconnection attempts; Step 4-4: Each time a timing event is triggered, decrement the time synchronization counter and the total call counter respectively. When the time synchronization counter or the total call counter reaches zero, reset the initial value and trigger the corresponding command; Step 4-5: Obtain the trigger instruction signals of each task, fill the ASDU address, function code, and time stamp for the trigger instruction, generate a control message and output it; Step 4-6: Record the metadata and execution results of the control message, and generate a formatted log to push to the log queue.

[0011] Preferably, when executing Step 4-3, it specifically includes the following steps: Step 4-3-1: During each heartbeat sending and confirmation process, maintain a sliding window, calculate the heartbeat success rate using the data in the sliding window, and then statistically analyze the heartbeat quality, taking the heartbeat quality as an indicator of the link quality; The formula for calculating the heartbeat success rate is as follows: ; Among them, represents that the response to the i-th heartbeat is received, represents that the i-th heartbeat times out without receiving a response; represents the heartbeat success rate at the current moment, ; N is the size of the sliding window, and t represents the moment; Step 4-3-2: Predict the link quality according to the following formula: ; Among them, is the predicted link quality index, is the smoothing factor, the value ranges from 0.2 to 0.5, represents the link quality index predicted at the previous moment, initialized to 1; Step 4-3-3: Dynamically adjust the reconnection delay according to the predicted link quality , and the specific formula is as follows: ; Among them, is the preset basic reconnection delay, is the adjustment factor, controlling the backoff increase; Step 4-3-4: If continues to be lower than the preset threshold of 0.3 for more than 5 heartbeat cycles, it is determined that the link is abnormal, and a reconnection signal is immediately triggered without waiting for normal backoff; otherwise, after the delay according to the reconnection delay , a reconnection request signal is output after the delay is completed.

[0012] Preferably, when executing Step 5, the message receiving and processing module executes the following steps: Step 5-1: Read the newly arrived byte stream from the TCP communication channel, append it to the receive buffer, update the available byte length of the receive buffer, and prepare for the synchronization and segmentation links; Step 5-2: Establish a half-packet synchronization state machine to segment the byte stream, specifically: State WAIT_HEAD, that is, waiting for the frame header: Search for the first 0x68 byte in the buffer. If found, switch the state to WAIT_LENGTH. Otherwise, discard one byte and continue; State WAIT_LENGTH, that is, waiting for the length field: Ensure that the buffer length ≥ 2, read the second byte L as the APDU length; Calculate the complete frame length N = L + 2, and switch to WAIT_FULL_PACKET; If the buffer has less than two bytes, pause segmentation and wait for more data; State WAIT_FULL_PACKET, i.e., waiting for a complete message: If the available bytes in the buffer ≥ N, extract the first N bytes as a complete frame and return to WAIT_HEAD; Otherwise, pause segmentation, retain the existing buffer, and wait for new data to arrive; State machine output: Whenever the state machine extracts a complete frame, it is handed over to the subsequent steps for format verification and classification processing; Step 5-3: Verify each extracted complete frame, including whether the start character is still 0x68, whether the length field L is consistent with the actual number of bytes N-2, and whether the total number of bytes meets the minimum message length requirement; If the verification fails, discard the frame and record a "discard log"; if the verification passes, it is regarded as a "qualified frame" and enters Step 5-4: Step 5-4: Extract the control bits from the control field bytes of the qualified frame to determine the frame type: For I-frames, output the ASDU and hand it over to the service parsing module; for S-frames or U-frames, output the link control information, which includes the acknowledgment sequence number or control command flag, and hand it over to the link management module; Step 5-5: For I-frames, put the byte block of the ASDU into the input queue of the service parsing module for the service parsing module to perform in-depth parsing and service distribution based on the type identifier; Step 5-6: For S-frames, extract the latest acknowledgment sequence number and notify the message sending and caching module to release the confirmed sending records; Step 5-7: For U-frames, parse the start command, stop command, or test command, and update the connection status or heartbeat timing of the link management module; Step 5-8: For each processed frame, format it into a structured log entry according to the "frame type", "sequence number", and "parsing result" fields, and push the log to the log queue; Step 5-9: When the state machine fails to extract a complete message in any state, retain the unparsed half-packet bytes in the buffer; If a complete frame still cannot be assembled after continuous timeouts (within the configured threshold), perform the following steps: Step 5-9-1: Search for the next legal start character 0x68 and discard the leading garbage data; Step 5-9-2: Retain the half-packet tail bytes to ensure continuous splicing in the future; Step 5-9-3: If the buffer backlog is too large or exceeds the longest timeout, clear the cache and generate a "receive timeout" alarm.

[0013] Preferably, when performing step 6, the message sending and caching module specifically performs the following steps: Step 6-1: Receive the sending instruction and parse the message type, where the types include time synchronization request, total call request, electric energy call request, and link start request; Step 6-2: Assemble the link layer header, length field, control field, and ASDU data area according to the IEC104 protocol, insert the current timestamp or function code, and generate a formatted message byte stream; Step 6-3: Write the message byte stream into the TCP sending buffer, perform the sending operation, and return the write result; Step 6-4: Integrate the message content and the sending result into a log record item, and push the log message to the log queue; Step 6-5: Package the sending record object and store it in the sending history queue, where the sending record object includes frame content, sending time, retransmission times, and sequence number; Step 6-6: Set the confirmation timeout threshold and start the monitoring process to track the confirmation status of the record to be confirmed; Step 6-7: When the retransmission times do not exceed the limit, perform retransmission. When the threshold is reached, trigger disconnection and reconnection, and clear the record to be confirmed.

[0014] Preferably, when performing step 7, the service processing and response module performs the following steps: Step 7-1: Receive the ASDU task object and store it in the concurrent task queue, where the ASDU task object includes type identifier, information body address, data value, and time tag; Step 7-2: Parse the task content through concurrent processing and perform the following multi-type processing: For the remote control task, perform the two-stage status verification process; For the remote adjustment task, perform the process of calculating the target setting value; For the remote measurement task or remote signaling task, perform the process of updating the device status or historical record; For the sequence event, perform the process of generating a chronological record; Step 7-3: Obtain the processing result of step 7-2, generate a control feedback frame. The control feedback frame selects the format of U frame or I frame according to the execution phase flag, and fills the corresponding control field and ASDU fields; Step 7-4: Push the control feedback frame into the sending queue of the link management module for sending, and update the link sequence number and confirmation status; Step 7-5: Extract the final status, value, or event record from the service processing result object, and asynchronously push it to the monitoring system or database through the message queue for display or storage; Step 7-6: Retrieve the original task input, processing stage, feedback frame content, and execution result status, aggregate them into a log entry, distinguish among the three types of information: received task, execution result, and feedback frame, and push them to the log queue.

[0015] Preferably, when executing Step 8, the execution steps of the sending status recovery module are as follows: Step 8-1: Receive the sending failure message, extract the sequence number of the sending failure message, construct a retry record object containing the message byte stream, sequence number, timestamp, and initial retry count, and store it in the retry queue; Step 8-2: Retrieve the first record in the retry queue. When the elapsed time exceeds the backoff interval, use the exponential backoff strategy to perform the backoff retransmission operation, which specifically includes: Write the message byte stream into the communication sending buffer; Update the retry count and the sending timestamp; Step 8-3: When the retry count does not reach the threshold, retain the record and wait for the next retry; when it exceeds the threshold, clear the associated retry record and trigger a disconnection reconnection request, generate a disconnection warning log, and push it to the log queue; Step 8-4: After receiving the reconnection success signal, resume the message sending function and inject the new message into the communication link; Step 8-5: Record the results of each retry attempt, the disconnection reconnection request triggered by the retry count exceeding the limit, and the reconnection success or queue clearing event, format them into log entries or warning messages, and push them to the log queue.

[0016] A method for implementing the IEC104 communication protocol based on a workflow according to the present invention solves the technical problems of dynamically parsing various IEC104 ASDUs and decoupling services using a configurable workflow engine, and integrating intelligent reconnection and structured log pushing in a modular hierarchical architecture. The parsing process of the present invention is driven by template configuration. Adding or modifying the ASDU type does not require code modification, but only requires updating the process template. Using modular division, the responsibilities of modules such as link management, timing scheduling, message sending and receiving, service parsing, and status recovery are single and decoupled. Unified log queue pushing supports the linkage between the front-end visualization and the alarm system, greatly improving the system observability. Using the exponential backoff strategy combined with link monitoring to achieve intelligent reconnection, taking into account timeliness and resource conservation. Description of the Drawings

[0017] Figure 1 is the main flowchart of the present invention; Figure 2 is the flowchart of the initialization stage of the present invention; Figure 3 is the flowchart of the link management stage of the present invention; Figure 4It is the flowchart of the service analysis phase of the present invention; Figure 5 It is the flowchart of the timing scheduling phase of the present invention; Figure 6 It is the flowchart of the message receiving phase of the present invention; Figure 7 It is the flowchart of the message sending phase of the present invention; Figure 8 It is the flowchart of the service response phase of the present invention; Figure 9 It is the flowchart of the status recovery phase of the present invention. Detailed implementation manners

[0018] By Figures 1-9 A method for implementing the IEC104 communication protocol based on workflow shown as follows includes the following steps: Step 1: Initialization phase. The initialization module loads communication configuration parameters, creates a communication channel, registers a timing task, initializes the link state and counter, and establishes a logging system; After the initialization module loads the configuration parameters, it stores them in a structure and establishes a logging queue; When executing Step 1, the specific steps executed by the initialization module are as follows: Step 1-1: Load a configuration file containing the target address, ASDU address, data start address, and time parameters; First, the initialization module retrieves and loads the configuration parameter file, reads the parameters from the configuration parameter file, including the destination address, common ASDU address, start addresses of telecontrol, telemetry, and telepulse, and time parameters. The time parameters include the heartbeat interval, confirmation timeout, and reconnection interval; the destination address includes the target host IP address and port number; Store the parameters in the internal configuration structure.

[0019] Step 1-2: Create a TCP communication channel object with a connection status flag; The initialization module creates a TCP communication channel object in memory and retains the target IP and port, connection status flag bit, receive buffer, and send buffer in the TCP communication channel object; The TCP communication channel object will initiate a connection using the loaded IP / port information when the link is established.

[0020] Step 1-3: Register timing tasks including heartbeat detection, confirmation timeout, and automatic reconnection; Specifically: The initialization module notifies the timer scheduling module to generate timing tasks according to various time parameters in the configuration file. The timing tasks include a confirmation timeout sending task, a heartbeat sending task, and an automatic reconnection task.

[0021] In this step, the scheduled task only performs the "registration" operation and does not start. It will be activated uniformly after the link is successfully established.

[0022] Step 1-4: Initialize the link status to disconnected and clear the communication sequence number; The initialization module sets all link status flags to the "disconnected" state, sets the link layer sequence number counter to zero, and clears or resets the send buffer and the receive buffer.

[0023] In this embodiment, the link layer sequence number counter refers to the transmission sequence number (TxSN) and the reception sequence number (RxSN) maintained according to the IEC104 protocol, and is used for orderly confirmation of link layer frames.

[0024] Step 1-5: Build a log queue system that is linked to the visualization module.

[0025] The initialization module creates a log queue and configures a formatting template, and associates the log queue with the front-end display module, so that when subsequent modules generate messages or status changes, the formatted text is pushed into the log queue, and the front-end pulls and displays it in real time.

[0026] Step 2: In the link management phase, the link management module establishes a TCP communication link, activates the scheduled task, parses the slave confirmation message, maintains the link heartbeat detection, and dynamically updates the communication sequence number; The link management module initiates a connection through the TCP channel, activates the timing task after the link is successfully established, parses the slave confirmation message, maintains periodic heartbeat frame detection during the link, and dynamically maintains the sending sequence number and receiving sequence number; When executing step 2, the link management module executes the following steps: Step 2-1: Initiate a TCP connection based on the configuration parameters and update the connection status flag; The link management module retrieves the target host IP address and port number from the output of the initialization module, extracts the connection parameters, and initiates a connection request to the slave station through the TCP communication channel object; the target host IP address and port number; Set a connection status flag variable m_bConnect. When the connection is successful, m_bConnect is set to true; when the connection fails, m_bConnect is set to false.

[0027] Step 2-2: After the link is established, activate the scheduled tasks related to link maintenance; When the link is successfully connected, the link management module controls the timer scheduling module to start multiple timed tasks related to link maintenance, including: Start the heartbeat detection task; Start sending confirmation timeout detection task; Start the reconnection monitoring task; Each timing task performs periodic checks or reconnection operations according to the time intervals registered in the initialization module.

[0028] Step 2-3: Send a link startup frame and parse the slave confirmation message; After the link is established, the link management module organizes and sends a link startup message, and then starts the data transmission frame, that is, the link startup frame; The link startup message takes starting data interaction as the task and is sent to the slave device through the existing TCP channel.

[0029] Step 2-4: Periodically maintain heartbeat detection and update the communication sequence number.

[0030] When performing Step 2-4, it specifically includes the following steps: Step 2-4-1: After the slave device receives the startup frame, it sends a confirmation message, and the confirmation message is a U-frame or an S-frame; After the link management module receives the confirmation message, it parses the control bit, sequence number, and function flag fields therein, determines whether the link is successfully established, and updates the relevant status variables. The relevant status variables include the received sequence number m_unRxSN and the transmitted sequence number m_unTxSN; Step 2-4-2: During the link maintenance process, the link management module periodically sends a heartbeat message to the slave according to the timer event. If no response from the slave is received within a certain time, a reconnection is performed; Step 2-4-3: During the communication process, the link management module continuously maintains the transmitted sequence number and the received sequence number, specifically including: incrementing the transmitted sequence number m_unTxSN every time an I-frame is sent; updating the received sequence number m_unRxSN and clearing the confirmed messages in the transmit buffer every time a confirmation frame is received; the confirmation frame is an S-frame.

[0031] Step 3: Service parsing stage. The service parsing module parses the ASDU type identifier of the received frame, executes the workflow, generates structured data according to the type-matched parsing template, performs data push and instruction legality verification, and generates and outputs log entries; The service parsing module parses the ASDU type identifier of the I-frame, matches the parsing template according to the type and executes the workflow. After completing the data encapsulation, it asynchronously pushes the data to the SCADA or the database; verifies the legality of the remote control instruction and generates an execution signal, constructs an event queue and a remote adjustment execution link, and finally outputs a structured service data stream and generates log entries; When performing Step 3, the execution steps of the service parsing module are as follows: Step 3-1: Extract the ASDU type identifier of the received I-frame and match the parsing process template according to the ASDU type identifier; After the service parsing module receives the I-frame message incoming from the link, it first extracts the content of the ASDU data area, locates the type identification byte in the first field, identifies the data type to which the current message belongs according to this field, and extracts the type identification value; The type identification value may include telemetry, telemetry signal, sequence event, remote control command (single-point / double-point), remote adjustment command, and unknown type; After the identification is completed, according to the identification result, match and load the parsing process template corresponding to the type identification in the memory as the execution path for this data parsing.

[0032] Step 3-2: Trigger the parsing workflow according to the ASDU type identifier, and sequentially execute the processing processes of field extraction, numerical conversion, quality verification, and time tagging according to the logical nodes; The service parsing module automatically enters the preset parsing workflow according to the current type identification value. There are multiple logical nodes configured in the workflow, including field extraction node, numerical conversion node, quality verification node, and time tagging processing node; each node is executed in sequence according to the configuration to complete the field disassembly and data conversion tasks of the ASDU; Telemetry: Extract the measurement value field and parse the value and its time tag: Telemetry signal: Extract the status value field and parse the switch status and change flag; Sequence event: Extract the event items and mark them in the order of event time; Remote control command: Identify single-point or double-point instructions, and verify the command stage, execution flag, and command legality; Remote adjustment command: Identify the "selection" or "execution" stage, and extract the target value, adjustment parameter, and path information; Unknown type: Record the type exception, generate an alarm log, and discard the invalid data.

[0033] Step 3-3: Package the telemetry data and telemetry signal data to obtain a standardized object, and asynchronously push the standardized object to the monitoring system; the monitoring system is the upper computer SCADA platform or the historical database, which is used to display and store the collected telemetry and telemetry signal data in real time.

[0034] When the identification result is telemetry or telemetry signal data, the service parsing module obtains key information such as the original measurement value, information body address, and time tag from the parsing node, and packages them into a standardized data item object according to the unified structure; After the data item is packaged, it is sent to the monitoring system by using an asynchronous push mechanism. In this embodiment, it can also be pushed to the historical database or the front-end display module, and then the real-time reporting and archiving of the monitoring data are carried out.

[0035] Step 3-4: Verify the legality of the remote control command according to the control records cached in the sending buffer. After passing the verification, generate an execution signal according to the content of the remote control command, record the operation track, and generate an operation log. When the recognition result is remote control command type data, the service parsing module compares the currently received remote control command with the control records cached in the sending buffer to determine whether it is a legal response frame: If the verification passes, clear the corresponding record in the sending buffer, and generate and issue an execution instruction according to the command content; At the same time, record the execution track of the remote control action, including information such as instruction issuance time, control type, response status, etc., and write it into the operation log.

[0036] Step 3-5: Process the sequential event type data to construct a timing queue, and process the remote adjustment instruction type data to trace the operation link. When the recognition result is a sequential event or a remote adjustment command, the service parsing module processes it according to the following steps: For sequential events: Parse out each event record and its time tag, construct an event queue in chronological order, and uniformly incorporate it into the event stream management. For remote adjustment commands: According to whether it is in the "selection" or "execution" stage, trigger different service processing branches, and generate a remote adjustment control signal; Automatically record the remote adjustment path, operation stage, execution parameters, and form a complete remote adjustment execution link.

[0037] Step 3-6: Generate a structured log entry containing the information body address, processing status, and time tag, and synchronize the log entry to the log library, visualization platform, and alarm system. All parsed business data is finally uniformly formatted, structurally encapsulated, and packaged to generate a structured log entry; The content of the log entry includes core fields such as the information body address, data type, parsing time, and processing result status; Log data supports being written into the system log library, visualization platform, and operation and maintenance alarm system simultaneously.

[0038] Step 4: Timing scheduling stage, the timer scheduling module activates periodic tasks based on the link status, routes the event processing function according to the counter ID, adaptively calculates the backoff delay in combination with the link quality prediction and anomaly detection mechanism, realizes self-optimizing reconnection control, generates a control command message, and records the log. The counter ID is the timer number assigned to different timing tasks in the timer scheduling module, such as T1, T2, T3.

[0039] The timer scheduling module activates periodic tasks after the link is connected, routes the event processing function according to the counter ID, uses the exponential backoff method for connection reconnection, generates a control command message, and formats the task trigger record into a log entry and pushes it into the message queue. When performing Step 4, the execution steps of the timer scheduling module are as follows: Step 4-1: Obtain the connection status flag sent by the link management module in real time. When the link connection is successful, activate the three pre-registered timing tasks and start the periodic timer; After obtaining the connection status flag sent by the link management module, if the "connected" signal is received, activate the three registered timing tasks simultaneously and start the corresponding periodic timer.

[0040] Step 4-2: Route to the corresponding processing according to the counter ID, including: Processing for the connection check task to trigger reconnection; Processing for the time synchronization task to trigger the generation of calibration commands; Processing for the total call task to trigger the generation of call commands; Processing for the power call task to trigger according to the configured interval; Monitor and obtain the identification ID carried when each timer is triggered, and obtain the current system time and the remaining count value; the current system time and the remaining count value are obtained from the timer m_ucAdjustTime and the counter m_ucGenCall respectively; Route the event to the corresponding data processing function for processing according to the counter ID of the trigger event, and output the trigger command signals for each task; The specific data processing function is: Connection check processing: Check the connection status flag, and if it is found to be disconnected, enter the reconnection process; Time synchronization task processing: Read the current system time m_ucAdjustTime count, and if it has reached zero, prepare the time calibration command; Total call task processing: Read the remaining count value m_ucGenCall count, and if it has reached zero, prepare the total call command; Power call task processing: Trigger according to the power call configuration interval.

[0041] Output the trigger command signals for each task, such as "Execute time synchronization", "Execute total call", "Execute power call", and "Execute connection detection".

[0042] Step 4-3: For any timing event or external "connection disconnected" signal, obtain the current connection status flag and the time of the most recent heartbeat confirmation; if the connection status flag is "disconnected" or the heartbeat confirmation times out, generate a reconnection delay using the exponential backoff algorithm, and output a reconnection request signal after the delay; the reconnection request signal includes the delay time and the number of reconnection attempts.

[0043] When performing Step 4-3, it specifically includes the following steps: Step 4-3-1: During each heartbeat sending and confirmation process, maintain a sliding window, calculate the heartbeat success rate using the data in the sliding window, and then statistically analyze the heartbeat quality. Use the heartbeat quality as an indicator of the link quality; The formula for calculating the heartbeat success rate is as follows: ; where, represents that the response to the i-th heartbeat confirmation is received, represents that the i-th heartbeat times out without receiving a response; represents the heartbeat success rate at the current moment, ; N is the size of the sliding window, and t represents the moment; Step 4-3-2: Predict the link quality according to the following formula: ; where, is the predicted link quality indicator, is the smoothing factor, takes values between 0.2 and 0.5, represents the link quality indicator predicted at the previous moment, is initialized to 1; Step 4-3-3: Dynamically adjust the reconnection delay according to the predicted link quality , and the specific formula is as follows: ; where, is the preset basic reconnection delay, is the adjustment factor, which controls the backoff increase; When the link quality is good, that is, , at this time , the delay approaches the basic value; When the link quality is poor, that is, , the backoff interval increases to reduce frequent reconnections; Step 4-3-4: If continues to be lower than the preset threshold of 0.3 for more than 5 heartbeat cycles, it is determined that the link is abnormal, and a reconnection signal is immediately triggered without waiting for normal backoff; otherwise, after the delay according to the reconnection delay is completed, a reconnection request signal is output.

[0044] Step 4-4: Each time a timing event is triggered, decrement the time synchronization counter and the total call counter respectively. When the time synchronization counter or the total call counter reaches zero, reset the initial value and trigger the corresponding command; Upon each timing event trigger, read counter m_ucAdjustTime and counter m_ucGenCall; Decrement counter m_ucAdjustTime and counter m_ucGenCall by one respectively; When counter m_ucAdjustTime or counter m_ucGenCall reaches zero, in addition to outputting the corresponding task trigger instruction, reset the corresponding counter to its initial configuration value.

[0045] Step 4-5: Obtain the trigger instruction signals for each task (timing-triggered functional tasks such as heartbeat detection, time synchronization, general call, power call, etc.), fill the ASDU address, function code, and timestamp for the trigger instruction, generate a control message and output it; in this embodiment, the instruction signal is the internal event identifier generated after the task expires.

[0046] The timer scheduling module will obtain the trigger instruction signals for each task, fill the corresponding ASDU address, function code, and current timestamp for each control command, form a complete message, and output the three types of control command message byte streams.

[0047] Step 4-6: Record the metadata and execution results of the control message, generate a formatted log and push it to the log queue.

[0048] Obtain the message content and execution results during the scheduling of various control commands, format the binary content, task type, and trigger time of the message into log entries, and push them into the log queue.

[0049] Step 5: In the message receiving phase, the message receiving and processing module receives the byte stream, splits the valid frames through the synchronization state machine, classifies and processes I-frames, S-frames, and U-frames, and generates a parsing log and pushes it to the log queue; The message receiving and processing module receives the byte stream from the TCP channel and caches it, splits the valid frames through the start delimiter 0x68 and the frame length, performs classification processing after format verification, and generates a parsing log and pushes it to the log queue; the byte stream is the original network data read from the underlying TCP socket interface.

[0050] When performing Step 5, the message receiving and processing module executes the following steps: Step 5-1: Read the newly arrived byte stream from the TCP communication channel, append it to the receive buffer, update the available byte length of the receive buffer, and prepare for the synchronization and splitting process; Step 5-2: Establish a half-packet synchronization state machine to split the byte stream, specifically: State WAIT_HEAD, that is, waiting for the frame header: Search for the first byte of 0x68 in the buffer. If found, switch the state to WAIT_LENGTH; otherwise, discard one byte and continue. State WAIT_LENGTH, i.e., waiting for the length field: Ensure that the buffer length ≥ 2, and read the second byte L as the APDU length. Calculate the full frame length N = L + 2, and switch to WAIT_FULL_PACKET. If the buffer has less than two bytes, pause segmentation and wait for more data. State WAIT_FULL_PACKET, i.e., waiting for the complete message: If the available bytes in the buffer ≥ N, extract the first N bytes as the complete frame and return to WAIT_HEAD. Otherwise, pause segmentation, retain the existing buffer, and wait for new data to arrive. Output of the state machine: Whenever the state machine extracts a complete frame, it is handed over to the subsequent steps for format verification and classification processing. Step 5-3: Verify each extracted complete frame, including verifying whether the start character is still 0x68, whether the length field L is consistent with the actual number of bytes N - 2, and whether the total number of bytes meets the minimum message length requirement. If the verification fails, discard the frame and record the "discard log"; if the verification passes, consider it a "qualified frame" and enter Step 5-4: Step 5-4: Extract the control bits from the control field bytes of the qualified frame to determine the frame type: I-frame (application data frame): Contains user data, and the subsequent ASDU part should be extracted. S-frame (acknowledgment frame): Only contains the receive sequence number, used to update the status of the frames already acknowledged by the sender. U-frame (management frame): Contains control commands such as link startup, stop, and test, used to adjust the link status. For I-frames, output the ASDU and hand it over to the service parsing module; for S-frames or U-frames, output the link control information, which includes the acknowledgment sequence number or control command flag, and hand it over to the link management module. Step 5-5: For I-frames, put the byte block of the ASDU into the input queue of the service parsing module for in-depth parsing and service distribution by the service parsing module according to the type identifier. Step 5-6: For S-frames, extract the latest acknowledgment sequence number and notify the message sending and caching module to release the sent records that have been acknowledged. Step 5-7: For U-frames, parse the startup command, stop command, or test command, and update the connection status or heartbeat timing of the link management module. Step 5-8: For each processed frame, format it into a structured log entry according to the fields of "frame type", "sequence number", and "parsing result", and push the log to the log queue; Step 5-9: When the full message cannot be extracted during the stay of any state machine, retain the unparsed half-packet bytes in the buffer; If the complete frame still cannot be assembled after consecutive timeouts (within the configured threshold), perform the following steps: Step 5-9-1: Search for the next legal start character 0x68 and discard the leading garbage data; Step 5-9-2: Retain the tail bytes of the half-packet to ensure subsequent continuous splicing; Step 5-9-3: If the buffer backlog is too large or exceeds the longest timeout, clear the cache and generate a "receive timeout" alarm.

[0051] Step 6: In the message sending stage, the message sending and caching module assembles the message according to the IEC104 protocol and sends it, managing the sending cache and the timeout retransmission mechanism; The message sending and caching module assembles the message according to the IEC104 protocol, sends it through TCP, records the log and puts it into the sending history queue. If it times out, retransmit according to the retransmission times threshold or trigger disconnection and reconnection; When performing Step 6, the message sending and caching module specifically performs the following steps: Step 6-1: Receive the sending instruction and parse the message type, where the types include time synchronization request, total call request, electric energy call request, and link startup request; In this embodiment, the message sending and caching module receives the sending instruction from the timer scheduling module or the link management module to obtain the type and key fields of the message to be sent; Specifically include: Time synchronization request: includes the current timestamp and the ASDU address; Total call request: includes the ASDU address and the function code; Electric energy call request: includes the electric energy function code and the ASDU address; Link startup request: includes the link startup control field; Step 6-2: Assemble the link layer frame header, length field, control field, and ASDU data area according to the IEC104 protocol, insert the current timestamp or function code, and generate a formatted message byte stream; In this embodiment, specifically according to the IEC104 protocol format, assemble the link layer frame header, length field, control field, ASDU data area, and insert the current timestamp or function code to obtain a formatted message byte stream.

[0052] Step 6-3: Write the message byte stream into the TCP sending buffer, perform the sending operation, and return the write result; Step 6-4: Integrate the message content and the sending result into a log record item, and push the log message to the log queue; Step 6-5: Package the sending record object and store it in the sending history queue. The sending record object includes the frame content, the sending time, the number of retransmissions, and the sequence number; In this embodiment, the message sending and caching module packages the message byte stream into a sending record object, including the frame content, the sending time, the number of retransmissions, the sequence number information, inserts it into the sending history queue, and adds a record to be confirmed in the sending history queue.

[0053] Step 6-6: Set the confirmation timeout threshold and start the monitoring process to track the confirmation status of the record to be confirmed; After setting the sending time of the record to be confirmed and the configured confirmation timeout time, the message sending and caching module notifies the timer scheduling module to start a counter (this counter is a dedicated timeout timer used to track the confirmation timeout time of each I-frame), and monitors the confirmation status of the record to be confirmed; Step 6-7: When the number of retransmissions does not exceed the limit, perform retransmission. When the threshold is reached, trigger disconnection and reconnection, and clear the records to be confirmed.

[0054] Specifically: If the number of retransmissions does not exceed the maximum threshold, rewrite the sending record object corresponding to the record to be confirmed into the sending buffer again, and update the sending time and the number of retransmissions; If the number of retransmissions has reached the threshold, notify the link management module to execute the disconnection and reconnection process, and clear all records to be confirmed.

[0055] Step 7: In the service response phase, the service processing and response module concurrently processes the ASDU task object, generates a feedback frame, and generates a full-process log; The service processing and response module receives the ASDU task object and processes it concurrently, verifies the permissions and executes the service logic in the thread pool, generates a feedback frame and pushes it to the link sending queue, and records the full-process log of the task to the message queue; When executing Step 7, the service processing and response module performs the following steps: Step 7-1: Receive the ASDU task object and store it in the concurrent task queue. The ASDU task object includes the type identifier, the information body address, the data value, and the time stamp; The service processing and response module receives the ASDU task object output by the service parsing module, places the task object in the concurrent task queue, and updates the task queue length; the ASDU task object includes the ASDU type identifier, the information body address, the original data value or status, and the time stamp.

[0056] Step 7-2: Parse the task content through concurrent processing and perform the following multi-type processing: For remote control tasks, perform two-stage status verification processing; For remote adjustment tasks, perform the processing of calculating the target setting value; For telemetry tasks or tele-signaling tasks, perform the processing of updating device status or historical records; For sequential events, perform the processing of generating chronological records; In this embodiment, the service processing and response module takes out a single ASDU task object from the task queue, parses the task content in the working thread of the thread pool, performs permission verification, status verification and service calculation, and outputs the service processing result object; Specifically: Remote control task: Verify the command legality and generate the status of two stages of "accept" and "execute"; Remote adjustment task: Calculate the target setting value according to the selection or execution process; Telemetry / tele-signaling task: Process status update or historical record writing; Sequential event: Sort and generate event records.

[0057] The service processing result object includes an execution stage flag (such as selection confirmation, execution confirmation), a processing result status (success, failure reason), and possible new values or status updates.

[0058] Step 7-3: Obtain the processing result of Step 7-2, generate a control feedback frame. The control feedback frame selects the format of U-frame or I-frame according to the execution stage flag, and fills the corresponding control field and ASDU field; In this embodiment, the service processing and response module extracts the stage flag, the original information body address and the ASDU address from the service processing result object, fills the control field and the ASDU field of the U-frame or I-frame with feedback data, generates an acknowledgment response frame or an execution result frame, and encapsulates it into a byte stream of the control feedback frame.

[0059] Step 7-4: Push the control feedback frame into the sending queue of the link management module for sending, and update the link sequence number and acknowledgment status; Step 7-5: Extract the final status, value or event record from the service processing result object, and asynchronously push it to the monitoring system or database through the message queue for display or storage; Step 7-6: Retrieve the original task input, processing stage, feedback frame content and execution result status, summarize them into log entries, distinguish the three types of information of received tasks, execution results and feedback frames, and push them to the log queue.

[0060] Step 8: State recovery phase. The sending status recovery module implements a back-off and retransmission strategy for the failed transmission messages, triggers disconnection reconnection to restore communication, and generates a retry log.

[0061] The sending status recovery module constructs a retry record for the failed transmission messages, triggers retransmission based on the back-off strategy, clears the queue and notifies disconnection reconnection when the maximum retry count is reached, restores the sending function after successful reconnection, records the retry log throughout the process, and pushes it to the message queue.

[0062] When executing Step 8, the execution steps of the sending status recovery module are as follows: Step 8-1: Receive the failed transmission messages, extract the sequence number of the failed transmission messages, construct a retry record object containing the message text stream, sequence number, timestamp, and initial retry count, and store it in the retry queue; In this embodiment, after retrieving the complete message text stream of a failed transmission submitted by the message sending and caching module and its associated sending sequence number, the sending status recovery module constructs a retry record object containing the message text stream, sending sequence number, current timestamp, and an initial retry count of 0, and inserts the retry record object into the retry queue.

[0063] Step 8-2: Retrieve the first record in the retry queue. When the elapsed time exceeds the back-off interval, perform a back-off and retransmission operation using the exponential back-off strategy, specifically including: Write the message text stream into the communication sending buffer; Update the retry count and sending timestamp; In this embodiment, the sending status recovery module retrieves the first record in the retry queue, calculates the elapsed time since the last retry; if it exceeds the current back-off interval to be used, perform a retransmission operation; The retransmission operation specifically includes: writing the message text stream back to the TCP sending buffer, incrementing the retry count of the record by one, and recording the new sending timestamp.

[0064] Step 8-3: When the retry count does not reach the threshold, retain the record and wait for the next retry; when it exceeds the threshold, clear the associated retry record and trigger a disconnection reconnection request, generate a disconnection warning log, and push it to the log queue; In this embodiment, if the retry count of a certain retry record is less than the maximum retry threshold, retain it in the queue and wait for the next retry; If the retry count has reached or exceeded the threshold, it is considered that the retry record object cannot be successfully sent, clear the corresponding retry record, and output a disconnection reconnection request; the disconnection reconnection request includes notifying the link management module (M2) to execute the reconnection process, clearing all remaining retry records, and recording and pushing the warning log.

[0065] Step 8-4: After receiving the reconnection success signal, resume the message sending function and inject the new message into the communication link; In this embodiment, the transmission status recovery module obtains the reconnection success status fed back by the path management module. After triggering the reconnection success, it sets the sendable flag to true, allowing message sending and the cache to continue pushing new messages to be sent.

[0066] Step 8-5: Record the results of each retry attempt, the disconnection and reconnection request triggered by the over-limit of the retry times, the reconnection success or queue emptying event, format them into log entries or alarm messages, and push them to the log queue.

[0067] A method for implementing the IEC104 communication protocol based on a workflow according to the present invention solves the technical problems of dynamically parsing various ASDUs of IEC104 and decoupling services by using a configurable workflow engine, and integrating intelligent reconnection and structured log pushing in a modular hierarchical architecture. The parsing process of the present invention is driven by template configuration. Adding or modifying the ASDU type does not require code modification, but only needs to update the process template. Using modular division, the responsibilities of modules such as link management, timing scheduling, message sending and receiving, service parsing, and status recovery are single and decoupled. Unified log queue pushing supports the linkage between front-end visualization and the alarm system, greatly improving the system observability. Using the exponential backoff strategy combined with link monitoring to achieve intelligent reconnection, taking into account timeliness and resource conservation.

Claims

1. A method for implementing the IEC104 communication protocol based on a workflow, characterized in that: It includes the following steps: Step 1: Initialization phase. The initialization module loads communication configuration parameters, creates a communication channel, registers a timing task, initializes the link status and counter, and establishes a logging system; Step 2: Link management phase. The link management module establishes a TCP communication link, activates the timing task, parses the slave confirmation message, maintains the link heartbeat detection, and dynamically updates the communication sequence number; Step 3: Service parsing phase. The service parsing module parses the ASDU type identifier of the received frame, executes the workflow, generates structured data according to the type-matching parsing template, executes data push and instruction legality verification, and generates and outputs log entries; Step 4: Timing scheduling phase. The timer scheduling module activates periodic tasks based on the link status, routes event handling functions according to the counter ID, adaptively calculates the backoff delay in combination with the link quality prediction and anomaly detection mechanism, realizes self-optimizing reconnection control, generates control command messages and records logs; Step 5: Message reception phase. The message reception processing module receives the byte stream, splits the valid frame through the synchronization state machine, classifies and processes I-frames, S-frames, and U-frames, and generates parsing logs to be pushed to the log queue; Step 6: Message sending phase. The message sending and caching module assembles and sends messages according to the IEC104 protocol, and manages the sending cache and timeout retransmission mechanism; Step 7: Service response phase. The service processing and response module concurrently processes ASDU task objects, generates feedback frames, and generates full-process logs; Step 8: Status recovery phase. The sending status recovery module implements a backoff retransmission strategy for the failed sent messages, triggers reconnection after disconnection, and resumes communication, generating retry logs.

2. The method for implementing the IEC104 communication protocol based on workflow according to claim 1, characterized in that: When executing Step 1, the specific steps executed by the initialization module are as follows: Step 1-1: Load the configuration file containing the target address, ASDU address, data start address, and time parameters; Step 1-2: Create a TCP communication channel object with a connection status flag; Step 1-3: Register timing tasks including heartbeat detection, confirmation timeout, and automatic reconnection; Step 1-4: Initialize the link status as disconnected and clear the communication sequence number; Step 1-5: Build a log queue system linked with the visualization module.

3. The method for implementing the IEC104 communication protocol based on a workflow according to claim 2, wherein: When executing Step 2, the link management module executes the following steps: Step 2-1: Initiate a TCP connection based on the configuration parameters and update the connection status flag; Step 2-2: Activate the timing tasks related to link maintenance after the link is established; Step 2-3: Send a link startup frame and parse the slave confirmation message; Step 2-4: Periodically maintain the heartbeat detection and update the communication sequence number.

4. The method for implementing the IEC104 communication protocol based on workflow according to claim 3, characterized in that: When executing Step 3, the execution steps of the service parsing module are as follows: Step 3-1: Extract the ASDU type identifier of the received I-frame and match the parsing process template according to the ASDU type identifier; Step 3-2: Trigger the parsing workflow according to the ASDU type identifier, and sequentially execute the processing processes of field extraction, numerical conversion, quality verification, and time tagging according to the logical node; Step 3-3: Package the telemetry data and telecontrol data to obtain a standardized object, and asynchronously push the standardized object to the monitoring system; Step 3-4: Verify the legality of the remote control command according to the control records cached in the send buffer. After the verification passes, generate an execution signal according to the content of the remote control command, record the operation trajectory, and generate an operation log; Step 3-5: Process the sequential event class data to construct a timing queue, and process the remote adjustment instruction class data to trace the operation link; Step 3-6: Generate a structured log entry containing the information body address, processing status, and time stamp, and synchronize the log entry to the log library, visualization platform, and alarm system.

5. The method for implementing the IEC104 communication protocol based on workflow according to claim 4, characterized in that: When executing Step 4, the execution steps of the timer scheduling module are as follows: Step 4-1: Real-time obtain the connection status flag sent by the link management module. When the link connection is successful, activate various pre-registered timing tasks and start a periodic timer; Step 4-2: Route to the corresponding processing according to the counter ID, including: Processing for the connection check task to trigger reconnection; Processing for the time synchronization task to trigger the generation of a calibration command; Processing for the total call task to trigger the generation of a call command; Processing for the power call task to trigger according to the configured interval; Step 4-3: For any timing event or external "connection disconnected" signal, obtain the current connection status flag and the time of the most recent heartbeat confirmation; if the connection status flag is "disconnected" or the heartbeat confirmation times out, generate a reconnection delay using the exponential backoff algorithm, and output a reconnection request signal after the delay; the reconnection request signal includes the delay time and the number of reconnection attempts; Step 4-4: Each time a timing event is triggered, perform a decrement operation on the time synchronization counter and the total call counter respectively. When the time synchronization counter or the total call counter reaches zero, reset the initial value and trigger the corresponding command; Step 4-5: Obtain the trigger instruction signals of each task, fill the trigger instruction with the ASDU address, function code, and time stamp, generate a control message and output it; Step 4-6: Record the metadata and execution result of the control message, and generate a formatted log to push to the log queue.

6. The method for implementing the IEC104 communication protocol based on a workflow according to claim 5, characterized in that: When executing Step 4-3, it specifically includes the following steps: Step 4-3-1: During each heartbeat sending and confirmation process, maintain a sliding window, calculate the heartbeat success rate using the data in the sliding window, and then statistically calculate the heartbeat quality, taking the heartbeat quality as an indicator of the link quality; The formula for calculating the heartbeat success rate is as follows: ; wherein, indicates that the response to the i-th heartbeat confirmation is received, indicates that the response to the i-th heartbeat is not received due to timeout; indicates the heartbeat success rate at the current moment, ; N is the size of the sliding window, and t represents the moment; Step 4-3-2: Predict the link quality according to the following formula: ; Among them, is the predicted link quality indicator, is the smoothing factor, takes values between 0.2 and 0.5, represents the predicted link quality indicator at the previous moment, is initialized to 1; Step 4-3-3: Dynamically adjust the reconnection delay according to the predicted link quality , where the specific formula is as follows: , as follows: ; Among them, is the preset basic reconnection delay, is the adjustment factor to control the backoff increase amplitude; Step 4-3-4: If it continuously remains below the preset threshold 0.3 for more than 5 heartbeat cycles, it is determined that the link is abnormal, and a reconnection signal is immediately triggered without waiting for normal backoff; otherwise, after the delay according to the reconnection delay is completed, a reconnection request signal is output.

7. The method for implementing the IEC104 communication protocol based on workflow according to claim 5, characterized in that: When executing Step 5, the message receiving and processing module executes the following steps: Step 5-1: Read the newly arrived byte stream from the TCP communication channel, append it to the receive buffer, update the available byte length of the receive buffer, and prepare for the synchronization and segmentation steps; Step 5-2: Establish a half-packet synchronization state machine to segment the byte stream. Specifically: State WAIT_HEAD, that is, waiting for the frame header: Search for the first 0x68 byte in the buffer. If found, switch the state to WAIT_LENGTH. Otherwise, discard one byte and continue; State WAIT_LENGTH, that is, waiting for the length field: Ensure that the buffer length ≥ 2, and read the second byte L as the APDU length; Calculate the complete frame length N = L + 2, and switch to WAIT_FULL_PACKET; If there are less than two bytes in the buffer, suspend segmentation and wait for more data; The state WAIT_FULL_PACKET, that is, waiting for the complete message: If the available bytes in the buffer ≥ N, extract the first N bytes as the complete frame and return to WAIT_HEAD; Otherwise, suspend segmentation, retain the existing buffer, and wait for new data to arrive; State machine output: Whenever the state machine extracts a complete frame, it is handed over to the subsequent steps for format verification and classification processing; Step 5-3: Verify each extracted complete frame, including whether the start symbol is still 0x68, whether the length field L is consistent with the actual number of bytes N - 2, and whether the total number of bytes meets the minimum message length requirement; If the verification fails, discard the frame and record the "discard log"; if the verification passes, it is regarded as a "qualified frame" and enters Step 5-4: Step 5-4: Extract the control bit from the control field byte of the qualified frame to determine the frame type: For I frames, output the ASDU and hand it over to the service parsing module; for S frames or U frames, output the link control information and hand it over to the link management module. The link control information includes the acknowledgment sequence number or the control command flag; Step 5-5: For I frames, put the byte block of the ASDU into the input queue of the service parsing module for the service parsing module to perform in-depth parsing and service distribution according to the type identifier; Step 5-6: For S frames, extract the latest acknowledgment sequence number and notify the message sending and caching module to release the confirmed sending records; Step 5-7: For U frames, parse the start command, stop command, or test command, and update the connection status or heartbeat timing of the link management module; Step 5-8: For each processed frame, format it into a structured log entry according to the "frame type", "sequence number", and "parsing result" fields, and push the log to the log queue; Step 5-9: When the state machine fails to extract a complete message in any state, retain the unparsed half-packet bytes in the buffer; If a complete frame still cannot be assembled after continuous timeouts (within the configured threshold), perform the following steps: Step 5-9-1: Find the next legal start symbol 0x68 and discard the leading garbage data; Step 5-9-2: Retain the tail bytes of the half-packet to ensure that subsequent splicing can continue; Step 5-9-3: If the buffer backlog is too large or exceeds the longest timeout, clear the cache and generate a "receive timeout" alarm.

8. The method for implementing the IEC104 communication protocol based on workflow according to claim 7, characterized in that: When executing Step 6, the message sending and caching module specifically performs the following steps: Step 6-1: Receive the sending instruction and parse the message type, and the types include time synchronization request, total call request, power energy call request, and link startup request; Step 6-2: Assemble the link layer frame header, length field, control field, and ASDU data area according to the IEC104 protocol, insert the current timestamp or function code, and generate a formatted message byte stream; Step 6-3: Write the message byte stream into the TCP sending buffer, perform the sending operation, and return the write result; Step 6-4: Integrate the message content and the sending result into a log record item, and push the log message to the log queue; Step 6-5: Package the transmission record object and store it in the transmission history queue. The transmission record object includes frame content, transmission time, number of retransmissions, and sequence number; Step 6-6: Set the confirmation timeout threshold and start the monitoring process to track the confirmation status of the records to be confirmed; Step 6-7: When the number of retransmissions does not exceed the limit, perform retransmission. When the threshold is reached, trigger disconnection and reconnection, and clear the records to be confirmed.

9. A method for implementing the IEC104 communication protocol based on a workflow, characterized in that: When executing Step 7, the service processing and response module performs the following steps: Step 7-1: Receive the ASDU task object and store it in the concurrent task queue. The ASDU task object includes type identifier, information body address, data value, and time tag; Step 7-2: Parse the task content through concurrent processing and perform the following multi-type processing: For remote control tasks, perform two-stage status verification processing; For remote adjustment tasks, perform the processing of calculating the target setting value; For remote measurement tasks or remote signaling tasks, perform the processing of updating device status or historical records; For sequence events, perform the processing of generating chronological records; Step 7-3: Obtain the processing result of Step 7-2, generate a control feedback frame. The control feedback frame selects the format of U-frame or I-frame according to the execution phase flag, and fills the corresponding control field and ASDU field; Step 7-4: Push the control feedback frame into the transmission queue of the link management module for transmission, and update the link sequence number and confirmation status; Step 7-5: Extract the final status, value, or event record from the service processing result object, and asynchronously push it to the monitoring system or database through the message queue for display or storage; Step 7-6: Retrieve the original task input, processing phase, feedback frame content, and execution result status, summarize them into log entries, distinguish the three types of information: received task, execution result, and feedback frame, and push them to the log queue.

10. The method for implementing the IEC104 communication protocol based on workflow according to claim 9, characterized in that: When executing Step 8, the execution steps of the transmission status recovery module are as follows: Step 8-1: Receive the transmission failure message, extract the sequence number of the transmission failure message, construct a retry record object containing the message byte stream, sequence number, timestamp, and initial retry count, and store it in the retry queue; Step 8-2: Retrieve the first record in the retry queue. When the elapsed time exceeds the backoff interval, use the exponential backoff strategy to perform backoff retransmission operations, specifically including: Write the message byte stream into the communication transmission buffer; Update the retry count and transmission timestamp; Step 8-3: When the retry count does not reach the threshold, retain the record and wait for the next retry. When it exceeds the threshold, clear the associated retry record and trigger a disconnection and reconnection request, generate a disconnection alarm log, and push it to the log queue; Step 8-4: After receiving the reconnection success signal, restore the message transmission function and inject the new message into the communication link; Step 8-5: Record the results of each retry attempt, the disconnection and reconnection requests triggered by the retry count exceeding the limit, and the reconnection success or queue emptying events, format them as log entries or alarm messages, and push them to the log queue.

Citation Information

Patent Citations

  • Detection method for communication states of IEC104 protocol of dispatching automation system

    CN103368263A

  • IEC60870-5-104 Protocol-based SCADA (supervisory control and data acquisition) network intrusion detection method and system

    CN106911514A

  • 104 protocol data receiving, processing and uploading method and system

    CN116366496A

  • IEC104 message analysis method, IEC104 message analysis device and computing equipment

    CN117834757A

  • IEC104 power distribution automation terminal debugging system and method

    CN119420039A

Cited By

  • NET-based Modbus TCP protocol equipment communication method

    CN121217798A