A data stream monitoring method and device based on a frame-level callback function

By registering callback functions within the frame sending and receiving functions of the MSTP protocol stack, constructing tracking information and writing it into a circular queue, the problems of data latency and device misjudgment in the BACnet MS/TP protocol are solved, achieving efficient data flow monitoring and automatic context matching.

CN122160407APending Publication Date: 2026-06-05XIAMEN MILESIGHT IOT CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
XIAMEN MILESIGHT IOT CO LTD
Filing Date
2026-04-22
Publication Date
2026-06-05

AI Technical Summary

Technical Problem

In the existing BACnet MS/TP protocol, if the monitored device fails to complete data transmission within the specified time, it will cause a bus error recovery process, resulting in data delay, device misjudgment failure, or communication interruption. Furthermore, the existing monitoring solution cannot automatically match the business context and record the original frame information.

Method used

Callback functions are registered within the frame sending and receiving functions of the MSTP protocol stack. Trace information is constructed and written to a circular queue. The capture and publishing processes are decoupled through an asynchronous queue. The invoke_id is bound to the device identifier to build a complete causal chain of request-response.

Benefits of technology

It enables frame-level operations to be completed within microseconds, eliminates the risk of token timeout, automatically matches business context, records original frame information, and provides monitoring records for debugging and business value.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122160407A_ABST
    Figure CN122160407A_ABST
Patent Text Reader

Abstract

The embodiment of the application provides a data stream monitoring method and device based on a frame-level callback function, which is applied to a gateway device, communicates with a to-be-monitored device through an MSTP protocol stack, and registers a sending callback function and a receiving callback function in advance. The method comprises the following steps: the MSTP protocol stack calls the sending callback function to construct tracking information based on a sending request and write the tracking information into a tracking table, and constructs sending frame information and writes the sending frame information into a ring queue during a token holding period; the MSTP protocol stack calls the receiving callback function to analyze response frame information to obtain a second device identifier, a second call identifier and data stream information; the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, and then takes the tracking information from the tracking table, constructs receiving frame information based on the tracking information and the data stream information, and writes the receiving frame information into the ring queue; and a sending thread sends the frame information and the receiving frame information to a monitoring platform through Redis.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of industrial IoT protocol gateway technology, specifically to a data flow monitoring method and device based on frame-level callback functions. Background Technology

[0002] BACnet MS / TP is a token passing protocol based on the RS-485 physical layer. Each monitored device on the bus takes turns holding a token, and only the monitored device holding the token can send data frames. The token holding time is constrained by the protocol parameters of the maximum number of frames that can be sent at one time (MaxInfoFrames) and the time slot per frame (Tslot). Under typical configuration, the token holding time at one time is from several milliseconds to tens of milliseconds. If the monitored device fails to send and pass the token within the specified time, the bus enters an error recovery process, which may result in: a delay of several times in normal data acquisition; other monitored devices misjudging that the monitored device has failed; and in severe cases, triggering a protocol-level "token regeneration" mechanism, interrupting the entire bus communication for several seconds. Summary of the Invention

[0003] The purpose of this application is to provide a data stream monitoring method and device based on frame-level callback functions, and the specific technical solution adopted is as follows: Firstly, a data stream monitoring method based on frame-level callback functions is provided, applied to a gateway device. The gateway device communicates with the device to be monitored via a master-slave / token passing MSTP protocol stack. The MSTP protocol stack pre-registers send and receive callback functions. The method includes: In response to the acquisition thread sending a request message to the MSTP protocol stack, the MSTP protocol stack calls the sending callback function during the token holding period to construct trace information based on the sending request and write it into the trace table. At the same time, it constructs sending frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. The MSTP protocol stack will take the transmission frame information from the circular queue and send it to the monitored device that is communicating with the gateway device, so that the monitored device can send the response frame information to the gateway device based on the received transmission frame information; The MSTP protocol stack calls the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and data stream information; If the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, then writes it into the circular queue. The sending thread publishes the sending frame information and the receiving frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis.

[0004] Secondly, a data stream monitoring device based on a frame-level callback function is provided, the device comprising: The first construction module is used to respond to the acquisition thread sending a request message to the master-slave / token passing MSTP protocol stack, and use the MSTP protocol stack to call the send callback function during the token holding period to construct trace information based on the send request and write it into the trace table. At the same time, it constructs send frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. The sending module uses the MSTP protocol stack to send the sending frame information taken from the circular queue to the monitored device that communicates with the gateway device, so that the monitored terminal device can send the response frame information to the gateway device based on receiving the sending frame information; The parsing module uses the MSTP protocol stack to call the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and the data stream information; The second construction module uses the receiving callback function to determine that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier. Then, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, which is then written into the circular queue. The publishing module uses a sending thread to publish the sent frame information and the received frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis.

[0005] Thirdly, an electronic device is provided, comprising: a memory and at least one processor, wherein the memory stores instructions; the at least one processor invokes the instructions in the memory to cause the electronic device to execute the above-described data flow monitoring method based on frame-level callback functions.

[0006] Fourthly, a computer program product is provided, comprising: computer program code, which, when run on a computer, causes the computer to perform the methods described in the first aspect or any possible implementation thereof.

[0007] Fifthly, a computer-readable storage medium is provided that stores computer program code, which, when executed on a computer, causes the computer to perform the methods described in the first aspect or any possible implementation thereof.

[0008] This application offers the following advantages: It moves the monitoring capture point (callback function) down from the application layer to the protocol frame layer and completely decouples it through an asynchronous queue. The callback function only performs two steps: constructing trace information and writing it into the trace table, and constructing the sending frame information and writing it into the circular queue. A single execution time is less than 5 microseconds (μs); all time-consuming operations are completed asynchronously by an independent thread (the sending thread). "Capture" and "publish" are separated into two independent execution contexts: the former is completed within the token slot (microsecond level), and the latter is completed during the idle time after token transfer (millisecond level). These two are decoupled through a lock-free / lightweight lock circular queue. This reduces the operation time during the token holding period to the microsecond level, completely eliminating the risk of token timeout. Utilizing the uniqueness of the call identifier within the send / receive lifecycle, a complete causal chain of request-response is constructed; the trace table consumes the response message upon receipt, naturally preventing duplicate associations. The raw bytes (sending frame information) are passed to the sending thread as part of the queue entry, and are finally published together with the received message. Business layer information (response frame information) and raw bytes (sending frame information) coexist in the same monitoring record. The monitoring log contains both the "interpretation layer" (object values) and the "raw layer" (frame bytes), which can be mutually verified, and has both debugging and business value. Attached Figure Description

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

[0010] Figure 1 A schematic diagram illustrating the process of registering two callback interfaces in the MSTP protocol stack according to an embodiment of this application; Figure 2 An interactive diagram illustrating the message sending behavior of a TX callback function provided in this application embodiment. Figure 3 This application provides a schematic diagram illustrating the implementation process of an RX callback function parsing response frame information. Figure 4 This is a schematic diagram of component interaction timing provided in an embodiment of this application; Figure 5 A schematic diagram illustrating the implementation process of bidirectional frame filtering provided in an embodiment of this application; Figure 6 A schematic diagram illustrating the implementation process of a data flow monitoring method based on frame-level callback functions provided in this application embodiment; Figure 7 A schematic diagram of the structure of a data flow monitoring device based on a frame-level callback function provided in this application embodiment; Figure 8 This is a schematic diagram of the structure of a computer device provided in an embodiment of this application. Detailed Implementation

[0011] To further illustrate the technical means and effects adopted by this application to achieve the intended inventive objective, the following, in conjunction with the accompanying drawings and preferred embodiments, details the specific implementation, structure, features, and effects of a data flow monitoring method based on frame-level callback functions proposed in this application. In the following description, different "one embodiment" or "another embodiment" do not necessarily refer to the same embodiment. Furthermore, specific features, structures, or characteristics in one or more embodiments can be combined from any suitable form.

[0012] In the description of the embodiments of this application, unless otherwise stated, " / " means "or". For example, A / B can mean A or B. The "and / or" in the text is merely a description of the relationship between related objects, indicating that there can be three relationships. For example, A and / or B can mean: A exists alone, A and B exist simultaneously, and B exists alone. In addition, in the description of the embodiments of this application, "multiple" means two or more.

[0013] Hereinafter, the terms "first" and "second" are used for descriptive purposes only and should not be construed as implying or suggesting relative importance or implicitly indicating the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature.

[0014] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application pertains.

[0015] The Building Automation and Control Networks (BACnet) protocol layer uses invoke_id (an 8-bit integer from 0 to 255) as a transaction identifier to mark each issued confirmed request. The peer returns a response (ACK / Error / Abort) with the same invoke_id. The invoke_id is allocated by the protocol stack when the request is issued and released after the corresponding response is received, and can be reused.

[0016] The existing data flow monitoring solutions and their problems are as follows: An external sniffing device is connected in series on the RS-485 bus to capture all physical layer frames and parse them on the PC. This requires additional hardware, cannot be shipped with the product, and the captured raw frames need to be manually associated with the BACnet device ID (the device ID is in the application layer, not in the frame header) frame by frame, and cannot automatically match the business context.

[0017] Directly calling log writing or Redis / MQTT publish functions within the MSTP protocol stack's frame receive / send functions to synchronously report frame information. Network I / O operations such as Redis Publish typically take 5-50ms, while the next frame token slot on a 9600bps RS-485 network is approximately 8-20ms. Performing such operations within the frame processing path (token holding period) directly leads to token timeout.

[0018] After the Application Protocol Data Unit (APDU) at the BACnet application layer is processed, the parsed object value is published through Redis, without recording the original frame. The APDU is a standardized basic information unit for transmitting commands and responses between smart cards (such as SIM cards and CPU cards) and terminal devices (such as card readers, mobile phones, and POS machines). When the application layer reports, the invoke_id has already been recycled by the protocol stack (transaction completed), making it impossible to determine which request the response corresponds to; the TX frame (request) information is never reported; and the original bytes are lost, making it unusable for in-depth protocol analysis or fault reproduction.

[0019] This application proposes three mutually cooperating core mechanisms: 1. Frame-level hook registration: Register lightweight callback functions on the MSTP protocol layer's frame transmission completion (TX) and frame reception completion (RX) events to advance the frame capture point to the protocol layer, rather than the application layer. This allows for the acquisition of complete raw frame bytes, and the capture occurs before `invoke_id` is released.

[0020] 2. Zero-blocking circular queue buffer: The callback function performs only two steps (microseconds) – parsing the frame header and writing to the circular queue – and immediately returns control of the token; an independent sending thread asynchronously consumes the queue, performing time-consuming operations such as Redis publishing and JSON serialization. Problem solved: Operation time during the token holding period is reduced to the microsecond level, completely eliminating the risk of token timeout.

[0021] 3. TX Phase invoke_id Tracking Table: When the TX callback sends a frame, it binds the invoke_id with {target device ID, object type, object instance, attribute ID, and sending timestamp} and records it in the tracking table. When the RX callback receives a response frame, it extracts the invoke_id from the frame and looks up the corresponding request context in the tracking table. Problem Solved: The RX frame cannot independently provide its corresponding business information; the tracking table enables a complete request-response association.

[0022] This application provides a BACnet MSTP bus bypass data flow monitoring method based on frame-level hooks and the invoke_id tracking table, which can be implemented through the following steps one to five: Step 1: Register frame-level hooks; Triggering timing: After system initialization, after the Multi-Service Transport Platform (MSTP) protocol stack has started, and before the data flow monitoring module starts.

[0023] The execution logic is as follows: Register two callback interfaces with the MSTP protocol stack: the TX completion callback interface and the RX completion callback interface. TX completion callback: Triggered after physical frame bytes are written to the serial port Direct Memory Access (DMA) function. Parameters include {original frame byte array, frame length, and target MAC address}.

[0024] RX completion callback: Triggered after the physical frame is fully received from the serial port and the CRC check passes. Parameters include {original frame byte array, frame length, source MAC address, parsed NPDU / APDU content (optional)}.

[0025] This step places the information capture point on the MSTP protocol stack, completing information acquisition before invoke_id is released and the original frame bytes are discarded.

[0026] Figure 1 A schematic diagram illustrating the process of registering two callback interfaces in the MSTP protocol stack provided in this application embodiment is shown below. Figure 1 As shown, this can be achieved through the following steps: Step 11: System initialization.

[0027] Step 12: Start the MSTP protocol stack.

[0028] Step 13: Initialize the data flow monitoring module.

[0029] Step 14: Register TX completion callback.

[0030] The original frame + MAC target address is triggered after the token holding period ends, and the TX callback processing logic is executed.

[0031] Step 15: Register the RX completion callback.

[0032] The RX callback processing logic is triggered after the original frame + MAC source address + APDU passes the CRC check.

[0033] Steps 14 and 15 above are listed side by side below the "Data Flow Monitoring Module Initialization" box, indicating that the TX callback function and RX callback function can be pre-built after initialization.

[0034] Step 2: TX frame processing – parsing and writing to the tracking table and adding to the queue; Triggering timing: The TX completion callback is invoked by the MSTP protocol stack.

[0035] The execution logic is as follows: TX completion callback (original frame[], frame length, target MAC): 1. Parse the following from the APDU: service_choice, object_type, object_instance, property_id, invoke_id, and value (when writing). If parsing fails (not a Confirmed Request frame) → return directly.

[0036] Here, the parsed fields form the core structure of APDU (Application Protocol Data Unit), and their definitions and functions are as follows: Service selection information (service_choice) identifies the type of service requested, corresponding to service primitives defined in the BACnet standard (such as Who-Is, I-Am, ReadProperty, WriteProperty, etc.). It determines subsequent data parsing rules and device response logic.

[0037] Example: 0x10: Who-Is service (device discovery request).

[0038] 0x0C: ReadProperty service (read property).

[0039] 0x15: WriteProperty service (write properties).

[0040] The object type (object_type) indicates the category of BACnet objects, such as Analog Input, Binary Output, and Device. Each type has preset attributes and behaviors. It limits the attribute range and data format of subsequent operations.

[0041] Example: AnalogInput(0): Physical sensor value (e.g., temperature).

[0042] Device(8): Device metadata (such as manufacturer and model).

[0043] BinaryOutput(4): Switch control (such as relay status).

[0044] An object instance (object_instance) is a unique instance identifier within the same object type, ranging from 0 to 4194302, used to distinguish specific devices or logical units. It ensures precise location of the target object and avoids type confusion.

[0045] Example: A device contains three temperature sensors, with instance numbers 0, 1, and 2.

[0046] Air conditioning equipment instance number 0, lighting controller instance number 1.

[0047] The property ID (property_id) is a unique identifier for an object's property, such as the present value, description, and units. The BACnet standard defines over 166 properties. It specifies the concrete property for the operation and determines the granularity of data read / write.

[0048] Example: PresentValue(10): The current value of the object (such as the temperature reading).

[0049] ObjectName(11): Object name (e.g., "MainSensor").

[0050] Reliability(12): Data reliability level.

[0051] The invoke_id is a request-response associated identifier. The client generates a unique value (typically 1-255), which is returned verbatim in the server's response. It matches requests and responses, preventing confusion from multiple requests. It also supports session management in asynchronous communication.

[0052] Example: When the client sends a read permission (ReadProperty) request, it sets invoke_id=42, and the server response contains the same value.

[0053] The value (write value, Write operation only) in the WriteProperty service contains the specific value to be written to the target property.

[0054] Format: Determined by the attribute type (e.g., floating-point number, integer, string, structure, etc.).

[0055] Example: The PresentValue written to AnalogOutput is 23.5 (a floating-point number).

[0056] The PresentValue written to BinaryOutput is 1 (binary state).

[0057] 2. Look up the device_id (local address table) from the MAC address; 3. Construct the tracking entry: {device_id, invoke_id, object_type, object_instance, property_id, timestamp}; Write to the tracking table (linked list, protected by mutex lock).

[0058] 4. Construct queue entries: {direction=TX, device_id, raw frame bytes, frame length, pdu_parse_info, destination address}; Call queue_enqueue() (circular queue, discards items when full, does not block).

[0059] 5. Return immediately.

[0060] Step two involves saving the business context mapping corresponding to invoke_id into a tracking table during TX (transaction) for reverse lookup during RX (redirection); at the same time, the original frame of the request direction is recorded.

[0061] Figure 2 This is an interactive diagram illustrating the message sending behavior of a TX callback function provided in an embodiment of this application, as shown below. Figure 2 As shown, the following execution entities are included: MSTP protocol stack, TX callback, trace table, circular queue.

[0062] MSTP Protocol Stack: Located on the far left of the diagram. Its flow starts from the top, with a black arrow pointing to the "TX callback" on the right, labeled "Frame transmission completed (raw frame, destination MAC)". At the bottom of the diagram, an arrow points from the "TX callback" to the "MSTP Protocol Stack", labeled "Immediate return (microseconds)", next to which is a yellow rectangle containing the text "Token control returned".

[0063] TX Callback: Located to the right of the "MSTP Protocol Stack". Upon receiving an arrow from the "MSTP Protocol Stack", there is first a self-circulating arrow labeled "Parse APDU\nExtract invoke_id / object information". Next, an arrow points to the "Trace Table" on the right, labeled "Write {invoke_id→Device ID+Object+Timestamp}". Afterwards, a return arrow from the "Trace Table" is received, labeled "Write successful". Then, an arrow points to the "Circular Queue" on the right, labeled "enqueue({TX, device_id, raw frame, PDU information})". Finally, an arrow points to the "MSTP Protocol Stack" below, labeled "Immediate return (microseconds)".

[0064] Trace table: Located to the right of "TX callback". Upon receiving a write request from "TX callback", it returns an arrow indicating "Write successful".

[0065] Circular queue: Located on the far right of the diagram. When an enqueue request is received from the "TX callback", there is a yellow rectangle next to it with the text "Discard when full, no blocking", and a dashed arrow pointing to the "TX callback" with the label "Return (Immediately)".

[0066] The entire interaction diagram details the processing flow of the TX callback after the MSTP protocol stack completes frame transmission, including steps such as parsing APDU information, writing to the trace table, adding information to the circular queue, as well as the interaction and return mechanisms between each step.

[0067] Step 3: RX frame processing – invoke_id reverse lookup in the tracking table and add to the queue; Triggering timing: The RX completion callback is invoked by the MSTP protocol stack.

[0068] Execution logic: RX completion callback (original frame [], frame length, source MAC, APDU content): 1. Parse from APDU: pdu_type (ACK / Error / Abort / COV notification, etc.), invoke_id, service_choice; If it is not the target service type (such as Who-Is / I-Am) → return directly.

[0069] 2. Look up the device_id from the source MAC address; 3. Use (device_id, invoke_id) to find and remove the corresponding entry in the tracking table; If found, obtain the complete request context; If no push frame (such as a COV notification without a request) is found, only the RX frame is recorded, and the context is left blank.

[0070] 4. Resolve the current value from the APDU (if it exists); 5. Construct queue entries: {direction=RX, device_id, raw frame bytes, pdu_parse_info (including associated request information, source address)}; Call queue_enqueue() (discard if full, no blocking).

[0071] 6. Return immediately In this step, the RX frame originally only contains invoke_id. The complete business context (device ID, object type, instance) is obtained by looking up the trace table, so that the monitoring system can present, for example, "the read response value of AI:3 of device X is 22.5°C" instead of simply "the response of invoke_id=7".

[0072] Figure 3 This is a schematic diagram illustrating the implementation process of parsing response frame information using an RX callback function, as provided in an embodiment of this application. Figure 3 As shown, this can be achieved through the following steps: Step 301: RX completes callback trigger.

[0073] Step 302: Analyze whether the APDU is the target service type.

[0074] If it is determined that the APDU is not the target service type, proceed to step 303; if it is determined that the APDU is the target service type, proceed to step 304.

[0075] Step 303: Return directly.

[0076] Step 304: Reverse lookup of device_id from source MAC address.

[0077] Step 305: Determine if invoke_id + device_id exists in the tracking table.

[0078] If invoke_id+device_id exists in the tracking table, proceed to step 306; if invoke_id+device_id does not exist in the tracking table, proceed to step 307.

[0079] Step 306: Retrieve the complete request context and remove the tracking entry.

[0080] Step 307: Leave the context blank and only record RX frame information.

[0081] Subsequent processing steps: Step 308: Parse the current value.

[0082] Step 309: Construct queue entries containing original frames and service information.

[0083] Step 310: Enqueue_enqueue.

[0084] Step 311: Immediately return to the MSTP protocol stack.

[0085] Figure 3 It clearly demonstrates the logical relationships and decision branches between each step. Starting from the RX completion callback trigger, after two judgments, corresponding processing is carried out according to different situations, and finally the queue entry is constructed and enqueued, and finally returned to the MSTP protocol stack.

[0086] Step 4: Asynchronous sending thread – consumes the queue and publishes; Triggering timing: When the sending thread is blocked and waiting for the queue to be non-empty (condition variable), independent of the MSTP token cycle.

[0087] Execution logic: Sending thread loop: 1. The blocking wait queue is not empty (pthread_cond_wait). 2. Retrieve an item from the circular queue; 3. Based on the direction (TX / RX) and service type, assemble pdu_parse_info with the original frame bytes into JSON format: { "dataType": "TX" or "RX", "devId":<device_id> , "objectType": "<type name>", "instanceId":<instance number>, "action": "read" / "write" / "cov_notification", "value": "<current value>", (includes value in RX cases) "payload": "<raw frame in hexadecimal>", "time": "<RFC3339 timestamp>" } 4. Publish to the upper - layer monitoring platform through Redis Publish; 5. Return to step 1.

[0088] In this step, time - consuming operations such as Redis publishing and JSON serialization (5 - 50 ms) are fully executed in an independent thread, having no competition relationship with the MSTP token loop, and the token path is completely non - blocking.

[0089] Step Five: Trace table timeout cleanup.

[0090] Triggering timing: Executed once every 2 seconds in the main acquisition loop.

[0091] Execution logic: Traverse the trace table and remove entries with a timestamp exceeding 10 seconds (corresponding to requests that have timed out and will never receive a response, such as sudden disconnection of the device). Prevent the trace table from growing indefinitely (with an upper limit of 2048 entries), and implicitly release resources related to these requests.

[0092] Figure 4 This is the schematic diagram of component interaction timing provided by the embodiment of this application. As Figure 4 shown, it includes the following components: Acquisition thread: Located at the left - most side of the figure, responsible for sending requests to read attributes.

[0093] MSTP protocol stack: Receive requests from the acquisition thread and perform protocol processing.

[0094] TX callback: Process the callback operation after sending is completed.

[0095] RX callback: Process the callback operation after receiving is completed.

[0096] Trace table: Used to record trace information.

[0097] Circular queue: Store data entries for sending and receiving.

[0098] Sending thread: An independent thread that does not occupy the token, responsible for retrieving data from the circular queue and publishing it to Redis.

[0099] Redis: Located at the right - most side of the figure, used to store and read data.

[0100] The interaction process is as follows: 1. Acquisition thread sends a request: The acquisition thread sends a ReadProperty(device = 101, AI:3, PRESENT_VALUE) request to the MSTP protocol stack.

[0101] 2. MSTP protocol stack handles requests: The token holding period is written to the serial port DMA.

[0102] After the frame is sent, the TX callback is called, [invoke_id=7, device=101, AI:3, PV] is written to the tracking table, and the information is enqueued into the circular queue.

[0103] Return immediately (<1μs) and display the message "Token has been passed to the next node".

[0104] 3. Sending thread processing: An independent thread, without holding a token, retrieves the TX entry from the circular queue.

[0105] Publish the request data stream JSON to Redis.

[0106] 4. MSTP protocol stack waiting for response: waiting for response frame.

[0107] 5. Frame reception complete: After the frame is received, the RX callback is called to find invoke_id=7, device=101, return [AI:3, PV] and remove the entry.

[0108] Enqueue [RX frame + full context + value = 22.5] into a circular queue.

[0109] Return immediately (<1μs).

[0110] 6. The sending thread processes again: Remove RX entries from the circular queue.

[0111] Publish [devid:101, AI:3, action:read, value:22.5, payload: raw frame HEX] to Redis.

[0112] 7. Exception Handling: Device suddenly disconnected: After a 2-second timeout, the cleanup thread scans and clears the entry with invoke_id=7.

[0113] Figure 4 It describes the entire process from the collection thread sending a request to the final data being stored in Redis, as well as the handling mechanism in case of exceptions.

[0114] In this embodiment, the monitoring capture point (callback function) is moved from the application layer to the protocol frame layer and completely decoupled through an asynchronous queue. The callback function only performs two steps: "parsing key fields + writing to the circular queue," with a single execution time of less than 5 microseconds (μs); all time-consuming operations are completed asynchronously by an independent thread (sending thread). "Capture" and "publish" are separated into two independent execution contexts: the former is completed within the token slot (microsecond level), and the latter is completed during the idle time after token transmission (millisecond level), with the two decoupled through a lock-free / lightweight lock circular queue.

[0115] During the TX phase, an invoke_id tracking table is proactively built to achieve automatic request-response association. When the TX callback is sent (invoke_id has been allocated but not yet fully used), the invoke_id is bound to the complete request context and written to the tracking table. When the RX callback receives the response, it looks up the table using (device_id, invoke_id), retrieves the request context, and then removes the entry. Leveraging the uniqueness of invoke_id throughout the TX→RX lifecycle, a complete causal chain of request-response is built, rather than attempting association afterward. The tracking table is consumed during RX (remove-on-read), naturally preventing duplicate associations.

[0116] The raw frame bytes enter the monitoring channel along with the business information. As part of a queue entry, the raw frame bytes are passed to the sending thread and ultimately published as a hexadecimal string along with the JSON message. Business layer information and raw bytes coexist in the same monitoring record. The monitoring record contains both the "interpretation layer" (object values) and the "raw layer" (frame bytes), allowing for mutual verification and possessing both debugging and business value.

[0117] In some embodiments, bidirectional frame filtering is further provided, i.e., a method that monitors only the data stream of the target object. Object whitelist filtering logic is added to the TX / RX callback, queuing only specific (object_type, object_instance) or specific device_id, and skipping the rest. The gateway manages hundreds of objects, but operations personnel only need to focus on the temperature sensor data streams of a few key devices. After filtering, queue pressure is reduced by more than 90%, and the Redis publishing frequency of the sending thread is also reduced accordingly.

[0118] Figure 5 This is a schematic diagram illustrating the implementation process of bidirectional frame filtering provided in an embodiment of this application, as shown below. Figure 5 As shown, this can be achieved through the following steps: Step 51: RX frame callback triggered.

[0119] Step 52: Is the object instance on the monitoring whitelist?

[0120] If the object instance is not in the monitoring whitelist, proceed to step 53; if the object instance is not in the monitoring whitelist, proceed to step 54.

[0121] Step 53: Return directly without enqueuing.

[0122] Step 54: Trace table lookup to construct queue entries.

[0123] Step 55: Join the team.

[0124] Figure 5 The logic flow is as follows: When the RX frame callback is triggered, first check if the object instance is in the monitoring whitelist. If not, return directly and do not enqueue; if it is, search through the tracking table and construct the queue entry, and finally enqueue it.

[0125] In some embodiments, a method for graded aging of a tracking table is provided, enabling short timeouts for frequently acquired objects. The aging time is no longer fixed at 10 seconds, but is dynamically set according to the object's configured acquisition cycle (e.g., for objects with a 5-second acquisition cycle, the tracking timeout is set to 15 seconds; for objects with a 60-second acquisition cycle, the tracking timeout is set to 90 seconds). Dynamic timeouts ensure that the tracking window for each object matches its normal response rhythm.

[0126] In this embodiment, "MSTP frame-level hook" is replaced with the frame processing completion event of the target protocol, and "invoke_id trace table" is replaced with the transaction identifier of the target protocol.

[0127] This solution's general principles can be applied to any industrial bus / protocol that meets the following three conditions: Condition 1: The frame processing path has strict time constraints (token mechanism, real-time scheduling priority). Condition 2: The protocol uses transaction identifiers with a finite integer space to associate request-response pairs; Condition 3: Non-intrusive monitoring needs to be implemented locally on the embedded device.

[0128] This application provides a data stream monitoring method based on frame-level callback functions, applied to a gateway device. The gateway device communicates with the device to be monitored via a master-slave / token passing MSTP protocol stack. The MSTP protocol stack pre-registers send and receive callback functions, such as... Figure 6 As shown, this can be achieved through the following steps: Step S610: In response to the acquisition thread sending a request message to the MSTP protocol stack, the MSTP protocol stack calls the sending callback function during the token holding period to construct trace information based on the sending request and write it into the trace table, and at the same time constructs sending frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. Here, after the system initializes and starts the MSTP protocol stack, before the data flow monitoring module starts, it registers two callback interfaces with the MSTP protocol stack: the TX completion callback interface (sending callback function) and the RX completion callback interface (receiving callback function).

[0129] like Figure 4 As shown, the acquisition thread sends a ReadProperty(device=101, AI:3, PRESENT_VALUE) request to the MSTP protocol stack. The MSTP protocol stack processes the request: the token holding period is written to the serial port DMA. After the frame is sent, the TX callback is called, writing trace information such as [invoke_id=7, device=101, AI:3, PV] to the trace table, and enqueuing the information (sent frame information) to the circular queue. It returns immediately (<1μs) and displays the message "Token has been passed to the next node".

[0130] Step S620: The MSTP protocol stack sends the transmission frame information taken from the circular queue to the monitored device communicating with the gateway device, so that the monitored device sends the response frame information to the gateway device based on receiving the transmission frame information; During implementation, the monitoring device sends the response frame information to the gateway device based on the received transmission frame information, such as... Figure 4 As shown, frame reception is complete when the gateway device receives the response frame information.

[0131] Step S630: The MSTP protocol stack calls the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and the data stream information; like Figure 4 As shown, after the frame is received, the RX callback (receive callback function) is called to parse and obtain invoke_id=7, device=101, and return [AI:3, PV], where invoke_id is the second call identifier, device is the second device identifier, and the data stream information is [AI:3, PV].

[0132] Step S640: If the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, then writes it into the circular queue. like Figure 4 As shown, the receive callback function searches for invoke_id=7, device=101 in the circular queue, returns [AI:3, PV], and removes the entry. Here, invoke_id is the second call identifier, device is the second device identifier, and the data stream information is [AI:3, PV]. Based on the context matched in the circular queue, it constructs the receive frame information, for example, [RX frame + complete context + value = 22.5], and enqueues it into the circular queue. It returns immediately (<1μs).

[0133] Step S650: The sending thread publishes the sending frame information and the receiving frame information retrieved from the circular queue to the monitoring platform through the remote dictionary service Redis.

[0134] The sending thread is a separate thread that does not hold tokens. It retrieves the TX entry from the circular queue and publishes the request data stream (JSON) to Redis. The sending thread then retrieves the RX entry from the circular queue again. It publishes the received frame information, such as [devid:101, AI:3, action:read, value:22.5, payload: raw frame HEX], to Redis.

[0135] An independent sending thread asynchronously consumes the queue to perform time-consuming operations such as Redis publishing and JSON serialization.

[0136] In this embodiment, the monitoring capture point (callback function) is moved from the application layer to the protocol frame layer and completely decoupled through an asynchronous queue. The callback function only performs two steps: constructing trace information and writing it into the trace table, and constructing the sending frame information and writing it into the circular queue. The execution time for a single step is less than 5 microseconds. All time-consuming operations are completed asynchronously by an independent thread (sending thread). "Capture" and "publish" are separated into two independent execution contexts. The former is completed within the token time slot (microsecond level), and the latter is completed during the idle time after the token is passed (millisecond level). The two are decoupled through a lock-free / lightweight lock circular queue. In this way, the operation time during the token holding period is reduced to the microsecond level, completely eliminating the risk of token timeout. By utilizing the uniqueness of the call identifier within the lifecycle of sending and receiving, a complete causal chain of request-response is constructed. The trace table consumes the response message when it is received, naturally preventing duplicate associations. The raw bytes (sending frame information) are passed to the sending thread as part of the queue entry, and are finally published together with the received message. The business layer information (response frame information) and the raw bytes (sending frame information) coexist in the same monitoring record. The monitoring log contains both the "interpretation layer" (object values) and the "raw layer" (frame bytes), which can be mutually verified, and has both debugging and business value.

[0137] In some embodiments, this application also provides a method for registering send callback functions and receive callback functions with the MSTP protocol stack, which can be implemented through the following steps: Step A: Register the send callback function with the MSTP protocol stack, wherein the parameters of the send callback function include the first raw frame parsed from the send request message, the first physical address of the device to be monitored, and the first frame length of the first raw frame; Here, the TX completion callback is triggered after the physical frame bytes are written to the serial port direct memory access DMA. The parameters include {original frame byte array (first original frame), frame length (first frame length), and target MAC address (first physical address)}.

[0138] Step B: Register the receive callback function with the MSTP protocol stack, wherein the parameters of the receive callback function include the second original frame parsed from the response frame information, the second physical address of the device to be monitored, and the second frame length of the second original frame.

[0139] Here, the RX completion callback is triggered after the physical frame is fully received from the serial port and the CRC check passes. The parameters include {original frame byte array (second original frame), frame length (second frame length), source MAC address (second physical address), and parsed NPDU / APDU content (optional)}.

[0140] In this embodiment, lightweight callback functions (a send callback function and a receive callback function) are registered on the two events of frame transmission completion (TX) and frame reception completion (RX) at the MSTP protocol layer, thus advancing the frame capture point to the protocol layer rather than the application layer. This allows for the acquisition of complete raw frame bytes, and the capture occurs earlier than the call flag is released.

[0141] In some embodiments, the step S610 above, "the MSTP protocol stack calls the send callback function during the token holding period to construct tracking information based on the send request and write it into the tracking table, and at the same time constructs send frame information and writes it into the circular queue," can be achieved through the following steps: Step 611: During the token holding period, the MSTP protocol stack calls the send callback function to parse the first original frame, the first physical address of the device to be monitored, and determine the length of the first frame from the send request; Here, TX completes the callback (first original frame[], first frame length, first physical address).

[0142] Step 612: If the sending request passes the verification based on the first frame length and the first original frame, the sending callback function parses the first original frame to obtain service selection information, object type, object instance, attribute identifier, and first call identifier. The service selection information is used to characterize the service type of the sending request, the object type is used to characterize the type of the device to be monitored, the object instance is used to locate the device to be monitored, the attribute identifier is used to determine the attribute information of the device to be monitored, and the first call identifier is a request and response association identifier. Here, the following are parsed from the APDU: service selection information (service_choice), object type (object_type), object instance (object_instance), property identifier (property_id), first call identifier (invoke_id), and data (value, when writing). Service selection information (service_choice) identifies the type of service requested, corresponding to the service primitives defined in the BACnet standard (such as Who-Is, I-Am, ReadProperty, WriteProperty, etc.).

[0143] The object type (object_type) indicates the category of BACnet objects, such as Analog Input, Binary Output, and Device. Each type has preset attributes and behaviors. It limits the attribute range and data format of subsequent operations.

[0144] An object instance (object_instance) is a unique instance identifier within the same object type, ranging from 0 to 4194302, used to distinguish specific devices or logical units. It ensures precise location of the target object and avoids type confusion.

[0145] The property ID (property_id) is a unique identifier for an object's property, such as the present value, description, and units. The BACnet standard defines over 166 properties. It specifies the concrete property for the operation and determines the granularity of data read / write.

[0146] The invoke_id is a request-response associated identifier. The client generates a unique value (typically 1-255), which is returned verbatim in the server's response. It matches requests and responses, preventing confusion from multiple requests. It also supports session management in asynchronous communication.

[0147] Step 613: The sending callback function queries the address mapping table based on the first physical address of the device to be monitored to determine the first device identifier; During implementation, the address mapping table (local address table) is looked up from the first physical address to determine the corresponding first device identifier (device_id).

[0148] Step 614: The sending callback function constructs the tracking information based on the first device identifier, the first call identifier, the object type, the object instance, the attribute identifier, and the timestamp, and writes the tracking information into the tracking table; Here, the following trace entry (trace information) is constructed: {first device identifier device_id, first call identifier invoke_id, object type object_type, object instance object_instance, property identifier property_id, timestamp}; The tracking information is written to a tracking table, which can be set up as a linked list and can provide mutex lock protection.

[0149] Step 615: The sending callback function constructs the sending frame information based on the first device identifier, the service selection, the object type, the object instance, the attribute identifier, the first call identifier, the first physical address of the device to be monitored, and the first frame length, and writes the sending frame information into the circular queue.

[0150] Here, the queue entry (send frame information) is constructed as follows: {direction=TX, first device identifier device_id, original frame bytes, frame length, pdu_parse_info, first physical address target address}; where pdu_parse_info includes service selection, object type, object instance, attribute identifier, and first call identifier, which are structure information (trace information) stored in the trace table.

[0151] Calling queue_enqueue() creates a circular queue, where the rule is to discard items when the queue is full, and the queue does not block.

[0152] In this embodiment, the combination of frame-level sending callback function and double buffering mechanism (circular queue + tracking table) achieves high efficiency and reliability of data flow monitoring, which is particularly suitable for high-concurrency communication requirements between gateway devices and devices to be monitored, ensuring real-time performance, reliability and scalability.

[0153] In some embodiments, the above step S630, "the MSTP protocol stack calls the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and the data stream information," can be achieved through the following steps: Step 631: The MSTP protocol stack calls the receive callback function to parse the response frame information and obtain the second original frame, the second frame length, the second physical address of the device to be monitored, and the response content; Here, the callback function completes the callback (second original frame[], second frame length, second physical address (source MAC), response content (APDU content)).

[0154] Step 632: If the receiving callback function determines that the response frame information passes the verification based on the second original frame and the second frame length, the callback function parses the response content to obtain the response type, the second call identifier, and the service selection information. The receive callback function determines the response frame information based on the second original frame and the length of the second frame, and passes the verification.

[0155] Parse from APDU: response type pdu_type (ACK / Error / Abort / COV notification, etc.), second call identifier invoke_id, and service selection information service_choice; If the service type is determined to be non-target service type based on the service selection information (such as Who-Is / I-Am), return directly.

[0156] Step 633: If the callback function determines the target service type based on the service selection information, it determines the second device identifier based on the second physical address of the device to be monitored.

[0157] Here, the target service type is determined based on the service selection information.

[0158] The second device identifier is obtained by reverse lookup of the address information mapping table from the second physical address.

[0159] In this embodiment, the system determines whether the service is a target service type (e.g., ReadProperty / WriteProperty) based on service selection information. If it is a non-target service (e.g., Who-Is / I-Am broadcast service), it returns directly to avoid invalid data processing; if it is a target service, it enters the device identifier matching process. Service type filtering reduces unnecessary data processing overhead. The system combines the second call identifier (invoke_id) with the request entry in the tracking table (containing device_id + invoke_id + timestamp) to verify whether the response frame matches the sent request.

[0160] In some embodiments, step S640 above, "when the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, the corresponding tracking information is retrieved from the tracking table, and receiving frame information is constructed based on the tracking information and data stream information and written into the circular queue," can be implemented through the following steps: Step 641: If the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table. During implementation, the receiving callback function uses (device_id, invoke_id) to search for and remove the corresponding entry in the tracking table; if found, the complete request context is obtained; if not found (e.g., push frames without requests such as COV notifications), only the RX frame is recorded, and the context is left empty.

[0161] Step 642: The receiving callback function parses the response content to obtain data stream information; During implementation, the receiving callback function parses the current value (data stream information) from the APDU. Step 643: The receiving callback function generates receiving frame information based on the data stream information and the tracking information, and writes the receiving frame information into the circular queue.

[0162] During implementation, the queue entry is constructed as follows: {direction=RX, device_id, raw frame bytes, pdu_parse_info (including associated request information, source address)}; Call queue_enqueue() (discard if full, no blocking).

[0163] In this embodiment, the receiving callback function performs a double-key hash lookup in the tracking table based on the second device identifier and the second call identifier. If a match is found, the complete request context (including sending time, object type, attribute identifier, etc.) is retrieved. Data stream information is extracted from the response content and combined with the request context (such as object instance, attribute identifier) ​​in the tracking table to construct receiving frame information containing complete business semantics, thereby achieving end-to-end association between request and response frames.

[0164] In some embodiments, step S650 above, "the sending thread publishes the sending frame information and the receiving frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis," can be achieved through the following steps: Step 651: The sending thread, independent of the token loop called by the MSTP protocol stack, encapsulates serialized data information in a lightweight data exchange format based on the sent frame information and the received frame information. Here, the sending thread is blocked waiting for the queue to be non-empty (condition variable), independent of the MSTP token loop.

[0165] Sending thread loop: 1. The blocking wait queue is not empty (pthread_cond_wait). 2. Retrieve entries (send frame information and receive frame information) from the circular queue; 3. Based on the direction (TX / RX) and service type, assemble pdu_parse_info with the original frame bytes (send frame information and receive frame information) into JSON format.

[0166] Step 652: The sending thread publishes the serialized data information to the monitoring platform via Redis.

[0167] During implementation, the sending thread publishes to the upper-layer monitoring platform via Redis Publish.

[0168] In this embodiment, an independent sending thread asynchronously consumes the queue and performs time-consuming operations such as Redis publishing and JSON serialization. By using asynchronous threads, lightweight serialization, and high-speed Redis publishing, the transmission latency of data from the gateway device to the monitoring platform is controlled at the millisecond level, achieving efficient, reliable, and real-time transmission of monitoring data.

[0169] In some embodiments, this application provides a method for releasing tracking information stored in a tracking table, which can be achieved through the following steps: Step A: Traverse the tracking table and remove tracking information whose timestamps are greater than a preset time threshold; Step B: Release the resource information associated with the tracking information.

[0170] Here, we provide step five above: cleaning up timeouts in the tracking table.

[0171] Triggering timing: The main data collection loop executes once every 2 seconds.

[0172] Execution logic: Traverse the tracking table and remove entries with timestamps exceeding 10 seconds (corresponding to requests that have timed out and will never receive a response, such as when the device suddenly disconnects).

[0173] In this embodiment, timely release of tracking information corresponding to timeout requests prevents the tracking table from growing indefinitely and implicitly releases resources associated with these requests. Regular cleanup and condition removal ensure controllable memory usage of the tracking table, preventing system crashes caused by memory leaks and improving the long-term reliability of the gateway device.

[0174] In some embodiments, this application also provides a method for setting a whitelist of devices to be monitored and using the whitelist, which can be achieved through the following steps: Step A: Set up a whitelist of devices to be monitored; Step B: If the callback function determines that the first device identifier does not match the whitelist of devices to be monitored, the monitoring process ends. Step C: If the receiving callback function determines that the second device identifier does not match the whitelist of devices to be monitored, the monitoring process ends.

[0175] Here, we provide a two-way frame filtering method that monitors only the data stream of the target object. We add object whitelist filtering logic to the TX / RX callback, and only enqueue specific (object_type, object_instance) or specific device_id, and skip the rest (end the monitoring process).

[0176] In this embodiment, by setting a whitelist of devices to be monitored, maintenance personnel only need to focus on the temperature sensor data streams of a few key devices. After filtering, the queue pressure decreases, and the Redis publishing frequency of the sending thread also decreases accordingly. This achieves refined monitoring that "only focuses on key data," avoids interference from invalid data, and improves monitoring effectiveness. In some embodiments, this application also provides a method for determining the tracking table update cycle, which can be implemented through the following steps: Step A: Obtain the data acquisition period based on the configuration of the device to be monitored; Step B: Determine the update cycle of the tracking table based on the acquisition cycle.

[0177] Here, the timeout window (update cycle) is adaptively adjusted according to the acquisition cycle, rather than being a fixed value.

[0178] Scenario 1: High-frequency objects (AI: 3, collection period 5s).

[0179] At t=0s, the client sends a request, assigns invoke_id=7, and adds a new record to the tracking table; the tracking window is set to 15s (approximately 3 times the collection cycle).

[0180] If the monitored device responds within 2 seconds, invoke_id is reclaimed.

[0181] If there is no response within 15 seconds, the timeout is determined, and invoke_id=7 is forcibly reclaimed.

[0182] Scenario 2: Low-frequency objects (AI:99, acquisition cycle 60s).

[0183] At t=5s, the client sends a request, assigns invoke_id=8, and sets the tracking window to 90s (approximately 1.5 times the collection cycle).

[0184] If the device responds within 20 seconds, forcibly reclaim invoke_id=8.

[0185] If there is no response within 90 seconds, the timeout is determined, and invoke_id=8 is reclaimed. Dynamic timeouts, which match the lifecycle of each tracking entry with its business rhythm, are a key design feature for resolving the invoke_id leakage problem and can address the following technical issues: Being too lenient with high-frequency objects (i.e., configuring an excessively long timeout window) leads to the invoke_id being occupied for an extended period, eventually exhausting resources. Conversely, being too aggressive with low-frequency objects (i.e., configuring an excessively short timeout window) results in the device being incorrectly judged as having timed out while still in the process of responding normally, causing the invoke_id to be prematurely reclaimed and subsequent responses to be discarded or mismatched.

[0186] This application provides a data stream monitoring device based on frame-level callback functions. Please refer to [link to relevant documentation]. Figure 6 The device 700 includes: The first construction module 710 is used to respond to the acquisition thread sending a request message to the master-slave / token passing MSTP protocol stack, and use the MSTP protocol stack to call the send callback function during the token holding period to construct trace information based on the send request and write it into the trace table. At the same time, it constructs send frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. The sending module 720 uses the MSTP protocol stack to send the sending frame information taken from the circular queue to the monitored device communicating with the gateway device, so that the monitored terminal device sends the response frame information to the gateway device based on receiving the sending frame information; The parsing module 730 uses the MSTP protocol stack to call the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and the data stream information; The second construction module 740 uses the receiving callback function to determine that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier. Then, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, which is then written into the circular queue. The publishing module 750 uses a sending thread to publish the sending frame information and the receiving frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis.

[0187] Figure 8 This is a schematic diagram of the structure of a computer device provided in an embodiment of this application. For example, as shown... Figure 8 As shown, the computer device 800 includes: a memory 801, a processor 802, and a computer program 803 stored in the memory 801 and running on the processor 802. When the processor 802 executes the computer program 803, the computer device can execute any of the aforementioned data flow monitoring methods based on frame-level callback functions.

[0188] Furthermore, this application also protects a control device, which may include a memory and a processor. The memory stores executable program code, and the processor is used to call and execute the executable program code to perform a data flow monitoring method based on a frame-level callback function provided in this application. This application can divide the control device into functional modules based on the above method example. For example, each module can correspond to a specific function, or two or more functions can be integrated into a processing module. The integrated module can be implemented in hardware. It should be noted that the module division in this application is illustrative and only represents a logical functional division; other division methods may exist in actual implementation. It should also be noted that all relevant content of each step involved in the above method embodiment can be referenced to the functional description of the corresponding functional module, and will not be repeated here. It should be understood that the control device provided in this application is used to execute the above-mentioned data flow monitoring method based on a frame-level callback function, and therefore can achieve the same effect as the above-mentioned implementation method. When using integrated units, the control device may include a processing module and a storage module. When the control device is applied to a block device, the processing module can be used to control and manage the actions of the block device. The storage module can be used to support block devices in executing mutual program code, etc. The processing module can be a processor or controller, which can implement or execute various exemplary logic blocks, modules, and circuits described in conjunction with the disclosure of this application. The processor can also be a combination of functions that implement computing capabilities, such as a combination of one or more microprocessors, a combination of digital signal processing (DSP) and microprocessors, etc., and the storage module can be a memory.

[0189] Furthermore, the control device provided in the embodiments of this application may specifically be a chip, component, or module. The chip may include a connected processor and a memory. The memory stores instructions, and when the processor calls and executes the instructions, the chip can execute the data flow monitoring method based on a frame-level callback function provided in the above embodiments. The embodiments of this application also provide a computer-readable storage medium storing computer program code. When the computer program code is run on a computer, it causes the computer to execute the aforementioned method steps to implement the data flow monitoring method based on a frame-level callback function provided in the above embodiments.

[0190] This application also provides a computer program product. When the computer program product is run on a computer, it causes the computer to execute the aforementioned related steps to implement the data flow monitoring method based on frame-level callback functions provided in the above embodiments. The control device, computer-readable storage medium, computer program product, or chip provided in this application are all used to execute the corresponding methods provided above. Therefore, the beneficial effects they achieve can be referred to in the beneficial effects of the corresponding methods provided above, and will not be repeated here. Through the description of the above embodiments, those skilled in the art can understand that, for the sake of convenience and brevity, only the division of the above functional modules is used as an example. In actual applications, the above functions can be assigned to different functional modules as needed, that is, the internal structure of the control device can be divided into different functional modules to complete all or part of the functions described above. In the embodiments provided in this application, it should be understood that the disclosed control device and method can be implemented in other ways. For example, the control device embodiments described above are merely illustrative. For example, the division of modules or units is merely a logical functional division. In actual implementation, there may be other division methods. For example, multiple units or components can be combined or integrated into another control device, or some features can be ignored or not executed. Another point is that the mutual coupling or direct coupling or communication connection shown or discussed can be an indirect coupling or communication connection through some interface, control device or unit, and can be electrical, mechanical or other forms.

[0191] It should be noted that the order of the embodiments described above is merely for descriptive purposes and does not represent the superiority or inferiority of the embodiments. The processes depicted in the accompanying drawings do not necessarily require a specific or sequential order to achieve the desired results. In some embodiments, multiple task processing and parallel processing are possible or may be advantageous. The various embodiments in this specification are described in a progressive manner, and the same or similar parts between the various embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. The above content is only a specific implementation of this application, but the protection scope of this application is not limited thereto. Any changes or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the protection scope of this application.

Claims

1. A data flow monitoring method based on frame-level callback functions, applied to a gateway device, wherein the gateway device communicates with the device to be monitored via a master-slave / token passing MSTP protocol stack, wherein the MSTP protocol stack pre-registers send callback functions and receive callback functions, characterized in that, The method includes: In response to the acquisition thread sending a request message to the MSTP protocol stack, the MSTP protocol stack calls the sending callback function during the token holding period to construct trace information based on the sending request and write it into the trace table. At the same time, it constructs sending frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. The MSTP protocol stack will take the transmission frame information from the circular queue and send it to the monitored device that is communicating with the gateway device, so that the monitored device can send the response frame information to the gateway device based on the received transmission frame information; The MSTP protocol stack calls the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and data stream information; If the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, then writes it into the circular queue. The sending thread publishes the sending frame information and the receiving frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis.

2. The method as described in claim 1, characterized in that, The method further includes: Register the send callback function to the MSTP protocol stack, wherein the parameters of the send callback function include the first raw frame parsed from the send request message, the first physical address of the device to be monitored, and the first frame length of the first raw frame; Register the receive callback function to the MSTP protocol stack, wherein the parameters of the receive callback function include the second original frame parsed from the response frame information, the second physical address of the device to be monitored, and the second frame length of the second original frame.

3. The method as described in claim 2, characterized in that, During the token holding period, the MSTP protocol stack calls the send callback function to construct trace information based on the send request and write it to the trace table. Simultaneously, it constructs send frame information and writes it to the circular queue, including: During the token holding period, the MSTP protocol stack calls the send callback function to parse the first original frame, the first physical address of the device to be monitored, and determine the length of the first frame from the send request. If the sending request passes the verification based on the first frame length and the first original frame, the sending callback function parses the first original frame to obtain service selection information, object type, object instance, attribute identifier, and first call identifier. The service selection information is used to characterize the service type of the sending request, the object type is used to characterize the type of the device to be monitored, the object instance is used to locate the device to be monitored, the attribute identifier is used to determine the attribute information of the device to be monitored, and the first call identifier is a request and response association identifier. The callback function queries the address mapping table based on the first physical address of the device to be monitored to determine the first device identifier. The sending callback function constructs the tracking information based on the first device identifier, the first call identifier, the object type, the object instance, the attribute identifier, and the timestamp, and writes the tracking information into the tracking table; The sending callback function constructs the sending frame information based on the first device identifier, the service selection, the object type, the object instance, the attribute identifier, the first call identifier, the first physical address of the device to be monitored, and the first frame length, and writes the sending frame information into the circular queue.

4. The method as described in claim 2, characterized in that, The MSTP protocol stack calls the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and data stream information, including: The MSTP protocol stack calls the receive callback function to parse the response frame information and obtain the second original frame, the second frame length, the second physical address of the device to be monitored, and the response content. If the callback function determines that the response frame information passes the verification based on the second original frame and the second frame length, the callback function parses the response content to obtain the response type, the second call identifier, and the service selection information. When the callback function determines the target service type based on the service selection information, it determines the second device identifier based on the second physical address of the device to be monitored.

5. The method as described in claim 4, characterized in that, If the receive callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table and constructs receive frame information based on the tracking information and data stream information, then writes it into the circular queue, including: If the receiving callback function determines that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier, it retrieves the corresponding tracking information from the tracking table. The receiving callback function parses the response content to obtain data stream information; The receive callback function generates receive frame information based on the data stream information and the tracking information, and writes the receive frame information into the circular queue.

6. The method according to any one of claims 1 to 5, characterized in that, The sending thread publishes the sent frame information and received frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis, including: The sending thread is independent of the token loop called by the MSTP protocol stack, and encapsulates serialized data information in a lightweight data exchange format based on the sent frame information and the received frame information. The sending thread publishes the serialized data information to the monitoring platform via Redis.

7. The method according to any one of claims 1 to 5, characterized in that, The method further includes: Traverse the tracking table and remove tracking information whose timestamps are greater than a preset time threshold; Release resource information related to the tracking information.

8. The method according to any one of claims 1 to 5, characterized in that, The method further includes: Set a whitelist of devices to be monitored; If the callback function determines that the first device identifier does not match the whitelist of devices to be monitored, the monitoring process ends. If the receiving callback function determines that the second device identifier does not match the whitelist of devices to be monitored, the monitoring process ends.

9. The method according to any one of claims 1 to 5, characterized in that, The method further includes: Obtain the data collection period based on the configuration of the device to be monitored; The update cycle of the tracking table is determined based on the acquisition cycle.

10. A data flow monitoring device based on frame-level callback functions, characterized in that, The device includes: The first construction module is used to respond to the acquisition thread sending a request message to the master-slave / token passing MSTP protocol stack, and use the MSTP protocol stack to call the send callback function during the token holding period to construct trace information based on the send request and write it into the trace table. At the same time, it constructs send frame information and writes it into the circular queue. The trace information includes at least a first device identifier and a first call identifier. The trace information is used by the MSTP protocol stack to match response frame information. The sending module uses the MSTP protocol stack to send the sending frame information taken from the circular queue to the monitored device that communicates with the gateway device, so that the monitored terminal device can send the response frame information to the gateway device based on receiving the sending frame information; The parsing module uses the MSTP protocol stack to call the receive callback function to parse the response frame information to obtain the second device identifier, the second call identifier, and the data stream information; The second construction module uses the receiving callback function to determine that the second device identifier matches the first device identifier and the second call identifier matches the first call identifier. Then, it retrieves the corresponding tracking information from the tracking table and constructs receiving frame information based on the tracking information and data stream information, which is then written into the circular queue. The publishing module uses a sending thread to publish the sent frame information and the received frame information retrieved from the circular queue to the monitoring platform via the remote dictionary service Redis.