Serial port single-wire multi-party communication system and method
Patent Information
- Application Number
- CN202611460018.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-20
- Publication Date
- 2026-10-27
AI Technical Summary
在此阻塞期间,即使队列中存在更高优先级的任务,也无法被处理;即使物理串口总线处于空闲状态(从设备正在处理命令尚未回复),总线也无法被其他任务利用
本发明采用非阻塞发送机制,数据帧通过物理串口发送完成后立即返回,不等待从设备回复。串口总线在等待回复的空闲时段可被其他待发送任务利用,将"占用总线的时间"从"等待回复的时间"中彻底剥离,使单条串口总线在单位时间内能够服务更多的通讯请求,总线利用率接近物理极限。在光伏储能系统中,该机制使得BMS电池包状态轮询、PD快充协议握手及锂电保护板状态监测等多类任务可共享同一总线而互不阻塞,显著提升了多从设备并发访问场景下的数据吞吐能力;
Smart Images

Figure CN122985668A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of data communication technology, and in particular to a serial port single-wire multi-party communication system and method. Background Technology
[0002] In applications such as network communication equipment, PD fast charging, 5G terminals, photovoltaic energy storage, and smart lithium battery terminals, the equipment typically contains multiple functional units (such as protocol processing units, status monitoring units, protection control units, and human-machine interaction units). These functional units need to interact with the internal power management unit or external expansion modules through the same physical serial bus (such as UART, RS485, or isolated serial port). Because the serial bus has the physical characteristic that "only one device can send a message on the bus at any given time," when multiple units concurrently access the same serial port, a data proxy system must uniformly manage the communication channel.
[0003] In the existing technology, various serial communication proxy solutions have emerged. For example, Chinese patent CN115328836A proposes a multi-APP serial port time-division multiplexing method. When multiple micro-applications access the terminal device through the serial port management APP, the physical serial port is time-division multiplexed according to the principles of "preemption" and "priority". Specifically, the requests sent by each APP carry priority parameters. The serial port management APP inserts the requests into the data sending queue according to priority, and then processes the requests in the queue in sequence. Each request carries independent "frame timeout" and "byte timeout" parameters.
[0004] For example, Chinese patent CN1774696B discloses a method for implementing asynchronous serial communication between devices through a main processor. This method establishes task blocks for serial port device processing, protocol encapsulation, and low-level communication, with each task block assigned a priority. Its core scheduling logic is: the next high-priority task is triggered only after a low-priority task is completed.
[0005] For example, Chinese patent CN116527770A proposes a data proxy system and method for multi-mode communication. It opens up designated threads and priority queues for different types of communication methods, creates a mapping table based on threads and priority queues, stores the communication data sent by the APP into the priority queue, takes the single data with the highest priority and performs synchronous blocking processing, and only processes the next data after the processing is completed.
[0006] The aforementioned existing technical solutions still have the following shortcomings in the "serial port single-wire multi-party communication" scenario: (a) Synchronous blocking I / O leads to low bus utilization. In solutions such as CN116527770A and CN115328836A, a thread must synchronously wait for a response from the slave device while processing a request—after sending data, the thread enters a blocked state and only continues processing the next request after receiving a response or a timeout. During this blocking period, even if there are higher-priority tasks in the queue, they cannot be processed; even if the physical serial bus is idle (the slave device is processing a command and has not yet responded), the bus cannot be used by other tasks. This results in a severe waste of the "single-line" physical bandwidth, and the real-time performance of high-priority tasks is constrained by the I / O waiting time of low-priority tasks. In scenarios with extremely high real-time requirements, such as PD fast charging protocol negotiation or photovoltaic energy storage BMS (Battery Management System) data acquisition, this blocking processing method may lead to response delays for critical instructions, affecting the timeliness of charging protocol handshakes or battery protection triggering.
[0007] (ii) Actively reported data can only be processed in exclusive mode. CN116527770A explicitly limits its "real-time monitoring mechanism for communication ports" to use only for communication devices in exclusive mode. However, in industrial and energy equipment scenarios using shared bus modes (one master and multiple slaves) such as RS485, slave devices (such as energy storage battery packs, photovoltaic inverters, lithium battery protection boards, etc.) may proactively report data (such as alarm information, sudden readings, and fault status) to the master at any time. Existing solutions cannot effectively handle proactive reporting in shared mode, resulting in reported data being ignored or lost, seriously affecting the system's real-time monitoring and fault early warning capabilities. In smart lithium battery terminals, if sudden alarms such as over-temperature and over-voltage from the battery protection board cannot be reported in a timely manner, it may cause serious safety hazards.
[0008] (iii) The receiving, processing and scheduling decisions are independent of each other, lacking cross-layer collaboration. In existing technologies, the data receiving module and the scheduling module are independent of each other—the asynchronous receiver, after receiving data, is only responsible for forwarding it to the corresponding functional unit and does not interfere with the scheduler's decision-making. When a slave device actively reports data, the scheduler is unaware of what is happening on the bus and still sends requests according to the predetermined queue order. This easily leads to bus data collisions—the host sends a command while the slave device is reporting, causing data conflicts on the bus and resulting in communication failure. In 5G terminals and network communication equipment, bus data collisions may lead to the loss of critical status information, affecting the device's network management monitoring and remote operation and maintenance capabilities.
[0009] (iv) The retry mechanism and priority scheduling are independent of each other and lack dynamic linkage. The data packet carries two independent parameters: "maximum number of transmissions" and "priority." Retry logic and priority scheduling are independent of each other—regardless of how many times a task has retried or how many "survival" opportunities remain, its scheduling priority remains unchanged. This means that a "dying task" on the verge of being discarded and a newly joined ordinary task are treated equally in scheduling, neither receiving priority for rescue. In photovoltaic energy storage systems, if battery status query requests are repeatedly retried due to bus interference but fail to receive priority scheduling, the energy storage scheduling strategy may not be updated in a timely manner, affecting the overall energy management efficiency of the system.
[0010] (v) Priority is static, and low-priority tasks are at risk of being starved. The existing solution determines priorities only when a task is enqueued and does not change thereafter. When a continuous influx of high-priority tasks occurs (e.g., ongoing fast-charging protocol handshakes or frequent BMS status polling), low-priority tasks (such as routine status log reporting and periodic maintenance queries) may be permanently blocked and remain unprocessed, a problem known as "task starvation." In the long run, this can lead to missing equipment maintenance data, failure of remote diagnostic functions, and impact the full lifecycle management capabilities of network power adapters and energy storage devices.
[0011] To address the shortcomings of the existing technology, this invention provides a data proxy system and method for serial port single-line multi-party communication. Summary of the Invention
[0012] The purpose of this invention is to provide a serial port single-wire multi-party communication system and method to solve the problems mentioned in the background art.
[0013] To achieve the above objectives, the present invention provides the following technical solution: a serial port single-wire multi-party communication method, comprising the following steps: Step S1: Receive communication requests sent by multiple application function modules, and store the communication requests in the queue to be sent corresponding to the same physical serial port according to priority; Step S2: Select the highest priority communication request from the queue to be sent, and send the data frame of the communication request in a non-blocking manner through the physical serial port. Return immediately after sending without waiting for the reply data of the communication request. Step S3: After the transmission in S2 is completed, return to execute S2 to process the next communication request in the queue to be sent; and, During the execution of S2, if a new high-priority communication request is detected to be enqueued, the waiting state of the current communication request is paused, and the sending process of the new high-priority communication request is executed first.
[0014] The serial port single-line multi-party communication method of the present invention, wherein "returning to execute S2 to process the next communication request in the queue to be sent" in S3 specifically means: after each transmission is completed, the queue to be sent is rescanned, and the communication request with the highest current priority is selected for transmission until the queue to be sent is empty.
[0015] The serial port single-wire multi-party communication method of the present invention further includes an asynchronous receiving step: S4: The input data of the physical serial port is monitored in real time through an independent asynchronous receiving thread, the received data frame is parsed, and the data frame is identified as a reply data frame or an active reporting data frame. If it is a reply data frame, the corresponding communication request is matched according to the frame identifier, and the reply data is forwarded to the application function module that initiated the request; If it is an actively reported data frame, its source device address is parsed and the reported data is forwarded to the application function module that has subscribed to the reported event of that device.
[0016] In the serial port single-line multi-party communication method of the present invention, after identifying the actively reported data frame in step S4, an address lock operation is also performed: Parse the source device address of the actively reported data frame and freeze all pending communication requests in the pending transmission queue whose destination address is the same as the source device address; After the actively reported data frame is distributed to the corresponding application function module, and it is confirmed that the physical serial port has returned to an idle state, the address lock is released, and the normal queuing and sending of the frozen communication requests are restored.
[0017] In the serial port single-line multi-party communication method of the present invention, in step S4, during the period when the address lock is in effect, the timeout timer of the frozen communication request is paused and resumed after the address lock is released.
[0018] The serial port single-wire multi-party communication method of the present invention further includes a bus load statistics step in step S4: The number of actively reported data frames received on the physical serial port per unit time is counted, and the current bus busy index is calculated. After a communication request is sent in S2, the timeout waiting time of the communication request is dynamically set according to the bus busy index, and the timeout waiting time is positively correlated with the bus busy index.
[0019] The serial port single-wire multi-party communication method of the present invention includes a communication request carrying a preset priority parameter and a maximum retry count parameter; step S2 further includes a retry control step. If no reply data frame is received within the timeout period after a communication request is sent, the transmission is deemed to have failed. If the number of retries for the communication request is less than the maximum number of retries, the communication request is put back into the queue to be sent and waited to be sent again; if the number of retries reaches the maximum number of retries, the communication request is moved into the dead letter queue and the application function module that initiated the request is notified.
[0020] The serial port single-wire multi-party communication method of the present invention, wherein the current scheduling priority of the communication request is dynamically calculated by the following formula: Current priority = preset priority + aging gain + emergency retry offset; The waiting time aging gain increases as the waiting time of the communication request in the queue to be sent increases; the retry emergency offset = (maximum number of retries - number of retries already completed) × emergency weight coefficient, and the retry emergency offset increases by one emergency weight coefficient for each retry of the communication request.
[0021] In the serial port single-line multi-party communication method of the present invention, when the number of retries of the communication request reaches the maximum number of retries minus one, the retry emergency offset raises the current scheduling priority of the communication request to a higher priority than all communication requests in the queue to be sent that have not undergone retries.
[0022] Furthermore, the present invention also provides a serial port single-wire multi-party communication system, the system comprising: The queue management module is used to receive communication requests sent by multiple application function modules and store the communication requests in the queue to be sent corresponding to the same physical serial port according to priority. The non-blocking sending module is used to select the highest priority communication request from the queue to be sent, send the data frame of the communication request in a non-blocking manner through the physical serial port, return immediately after sending without waiting for the reply data of the communication request, and continue to process the next communication request in the queue to be sent. The preemptive scheduling module is used to pause the waiting state of the current communication request and prioritize the non-blocking sending module to execute the sending process of the new high-priority communication request if a new high-priority communication request is detected during the sending process of the non-blocking sending module. The asynchronous receiving module is used to monitor the input data of the physical serial port in real time through an independent asynchronous receiving thread, and to parse and distribute the received data frames; The address lock module is used to parse the source device address of the actively reported data frame when the asynchronous receiving module identifies it, freeze all pending communication requests in the pending transmission queue whose destination address is the same as the source device address, and unfreeze the active reported data frame after it has been processed. The retry management module is used to perform retry control based on the maximum number of retries for a communication request after the communication request has timed out. The priority dynamic calculation module is used to dynamically calculate the current scheduling priority based on the preset priority of the communication request, the waiting time aging gain, and the retry emergency offset. Furthermore, the priority of each communication request in the queue to be sent is updated in real time by the priority dynamic calculation module, and the non-blocking sending module selects the communication request with the highest current priority from the queue to be sent each time.
[0023] Compared with the prior art, the beneficial effects of the present invention are reflected in the following three aspects: 1. Bus utilization has been significantly improved. This invention employs a non-blocking transmission mechanism. Data frames are sent via the physical serial port and immediately returned, without waiting for a response from the slave device. During the idle period while waiting for a response, the serial bus can be utilized by other tasks, completely separating the "time spent occupying the bus" from the "time spent waiting for a response." This allows a single serial bus to serve more communication requests per unit time, bringing bus utilization close to its physical limit. In photovoltaic energy storage systems, this mechanism enables multiple tasks, such as BMS battery pack status polling, PD fast charging protocol handshake, and lithium battery protection board status monitoring, to share the same bus without blocking each other, significantly improving data throughput in scenarios with multiple slave devices accessing the system concurrently. 2. The real-time performance of high-priority tasks is fundamentally guaranteed. This invention achieves true task-level preemptive scheduling—after each transmission, the queue is rescanned, and the highest priority task is selected for processing; if a new high-priority task joins the queue during transmission, the current task's waiting state can be immediately paused, and the high-priority task is sent first. The real-time performance of high-priority tasks is no longer constrained by the I / O waiting time of low-priority tasks, meeting the stringent real-time requirements in scenarios such as rapid issuance of key instructions during PD fast charging protocol negotiation, immediate response to photovoltaic inverter protection trigger signals, and priority reporting of lithium battery protection board over-temperature / over-voltage alarms. 3. The system architecture has transitioned from "synchronous blocking" to "asynchronous non-blocking + preemptive". This invention breaks away from the traditional synchronous paradigm of "first-come, first-served, sequential execution" in serial communication proxies, constructing a novel architecture centered on non-blocking transmission and using dynamic priority reordering for scheduling. This provides fundamental architectural support for the subsequent introduction of advanced mechanisms such as proactive reporting, dynamic timeout, and priority aging. This architecture enables various functional units (protocol processing unit, status monitoring unit, protection control unit, human-machine interface unit, etc.) within 5G terminal devices and network power adapters to achieve real-time capture of proactive device alarms, autonomous avoidance of bus conflicts, and adaptive timeout adjustment under congestion conditions when sharing the same physical serial bus. This provides a reliable communication foundation for the full lifecycle management of smart lithium battery terminals and energy storage devices. Attached Figure Description
[0024] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.
[0025] Figure 1 This is a flowchart of the method steps of the present invention. Detailed Implementation
[0026] The terms "first," "second," "third," and "fourth," etc., used in the specification, claims, and accompanying drawings of this invention are used to distinguish different objects, not to describe a specific order. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion. For example, a process, method, system, product, or apparatus that includes a series of steps or units is not limited to the listed steps or units, but may optionally include steps or units not listed, or may optionally include other steps or units inherent to these processes, methods, products, or apparatuses.
[0027] In this document, the term "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of the invention. The appearance of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a separate or alternative embodiment mutually exclusive with other embodiments. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.
[0028] "Multiple" refers to two or more. "And / or" describes the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A alone, A and B simultaneously, or B alone. The character " / " generally indicates that the preceding and following related objects have an "or" relationship.
[0029] Furthermore, the terms indicating orientation, such as "up," "down," "left," "right," "upper end," "lower end," and "longitudinal," are all based on the posture and position of the device or equipment described in this solution during normal use.
[0030] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, a clear and complete description will be provided below in conjunction with the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. All other embodiments obtained by those skilled in the art based on the embodiments of the present invention without creative effort are within the protection scope of the present invention.
[0031] like Figure 1 As shown, this invention provides a specific embodiment of a serial port single-wire multi-party communication system and method. In this embodiment, an RS485 physical serial bus is used as the physical communication medium. Multiple slave devices are connected to this bus, such as energy storage battery packs (BMS), photovoltaic inverters, PD fast charging protocol controllers, lithium battery protection boards, etc. At the same time, multiple application function modules (such as protocol processing units, status monitoring units, protection control units, human-machine interaction units, etc. - based on Linux system) run within the system. Each function module has the need to interact with its corresponding slave device through the RS485 bus.
[0032] In this embodiment, the method first executes step S1: the system receives communication requests from multiple application function modules through the queue management module. Each communication request includes at least the destination device address, the content of the data frame to be sent, a preset priority parameter, and a maximum number of retries parameter. The queue management module stores all received communication requests in the pending-send queue corresponding to the same physical serial port according to their priority.
[0033] Specifically, when a communication request is stored in the queue to be sent, the higher the priority of the communication request, the closer it is to the queue's exit position. If multiple communication requests have the same priority, they are arranged according to the first-in, first-out (FIFO) principle, meaning that the communication request that arrives in the queue first is closer to the queue's exit. The data structure of this priority queue can be implemented using a priority queue based on heap sort or an ordered queue based on a linked list; this invention does not specifically limit this approach. Through this step, the convergence management of communication requests from multiple applications on a single physical serial port is achieved, laying the foundation for subsequent serial scheduling.
[0034] Then, step S2 is executed: the non-blocking sending module selects the highest priority communication request from the queue to be sent, sends the data frame of the communication request in a non-blocking manner through the physical serial port, and returns immediately after the sending is completed without waiting for the reply data of the communication request.
[0035] Specifically, non-blocking transmission refers to calling the asynchronous write interface provided by the serial port driver (such as the write system call in Linux with the O_NONBLOCK flag, or using the non-blocking write method of the libserial library), writing the data frame to the serial port transmit buffer, and returning immediately. It does not block the current thread to wait for the data to be completely sent from the buffer, nor does it wait for the slave device to return a reply. After the write operation is completed, the system immediately records the timestamp and status information of the communication request and starts an independent timeout timer for subsequent timeout detection. Through this non-blocking transmission method, the system completely separates the "time spent occupying the bus" from the "time spent waiting for a reply"—after the data frame is sent to the slave device via the physical bus (usually in milliseconds or even microseconds), the physical bus enters an idle state. At this time, the system does not need to passively wait for the slave device to process the command and return a reply, but can immediately use the bus idle period to process other communication requests to be sent. This allows more communication requests to be served per unit time on the same physical serial port, bringing the bus utilization close to the physical limit.
[0036] It should be noted that the "transmission completion" described in this embodiment has a clear physical layer definition standard: when the non-blocking transmission module calls the asynchronous write interface of the serial port driver layer, the system does not immediately consider the physical bus to be idle. Instead, it confirms that the last bit of the current data frame has been completely sent from the TX pin of the physical serial port by checking the transmit completion interrupt provided by the serial port driver or by polling the transmit holding register (THR Empty) and transmit shift register (TSR Empty) states. Only then is a complete physical transmission considered complete. At the same time, the system maintains the busy / idle status flag of the physical serial port in real time by using the carrier sensing mechanism of the serial port driver layer or the direction control pin status of the RS485 transceiver, combined with the bus idle timer (i.e., determining that the bus is idle after detecting a certain number of consecutive bit transitions without level changes on the bus). Before sending a new communication request, the non-blocking transmission module must first check the busy / idle status flag to confirm that the physical serial port bus is in an idle state before allowing the next data frame transmission operation to be performed. If the bus is in a busy state, the transmission module enters a brief polling wait or is woken up by an event until the bus returns to an idle state. Through the dual guarantee mechanism of "physical transmission completion confirmation + bus idle detection", the problem of data frames overlapping and colliding at the physical layer due to relying solely on the return of write() is completely avoided.
[0037] Then, step S3 is executed: After the sending in step S2 is completed, the process returns to step S2 to process the next communication request in the queue to be sent. Specifically, after each sending is completed, the system rescans the queue to be sent, selects the communication request with the highest current priority for sending, and repeats this operation until the queue to be sent is empty.
[0038] Simultaneously, during step S2, if a new high-priority communication request is detected being enqueued, the waiting state of the current communication request is paused, and the sending process of the new high-priority communication request is executed first. Here, "pausing the waiting state of the current communication request" means: When a communication request waiting for a reply is preempted by a new request with higher priority, the system does not cancel or discard the current request. Instead, it keeps the request in its original position in the queue to be sent (or marks its status as "to be continued"), while pausing its timeout timer. The waiting status and timeout timer of the request will be restored after the high-priority request is sent.
[0039] This preemptive scheduling mechanism ensures that the real-time performance of high-priority tasks is no longer constrained by the I / O latency of low-priority tasks. Even if a response to a low-priority request is pending, the bus can be immediately preempted to send a high-priority request once it arrives. This is of significant value for scenarios such as the issuance of critical instructions during the PD fast charging protocol handshake, the rapid response of battery protection trigger signals in photovoltaic energy storage systems, and the real-time processing of network management instructions in 5G terminal devices. Furthermore, by rescanning the queue and selecting the highest-priority request after each transmission, the mechanism ensures that every bus transmission opportunity serves the most important task at hand, achieving globally optimal scheduling.
[0040] During the preemption scheduling process, to fully manage the status of suspended requests on the slave side, the system maintains a state machine for each communication request waiting for a reply. This state machine includes four states: "Sent Awaiting Reply," "Pending Waiting," "Resuming Waiting," and "Reply Received." When a high-priority request preempts the current request, the current request's status changes from "Sent Awaiting Reply" to "Pending Waiting," its timeout timer is paused, and the system retains the request's context information (including copies of the sent data frames, the destination device address, the transaction identifier, and the waiting time). If, during the high-priority request's sending and waiting for a reply, the asynchronous receiving module receives a slave reply data frame corresponding to the suspended request, the system does not discard the reply but temporarily stores it in the reply buffer bound to the request and marks the request's status as "Reply Received." When the high-priority request is processed and the system resumes the suspended request, it first checks its status: if it is "Reply Received," the request is directly marked as completed, and the cached reply data is forwarded to the initiating APP without resending; if it is "Pending Waiting," its timeout timer is resumed, and it continues to wait for a slave reply. This state machine enables rapid response to high-priority tasks in preemptive scenarios while ensuring that response data for preempted requests is not lost or resent.
[0041] Based on the above method, this embodiment also provides an asynchronous receiving and processing mechanism, the specific working method of which is as follows.
[0042] The system monitors the input data of the physical serial port in real time through an independent asynchronous receiving thread. This asynchronous receiving thread runs in a different execution context from the aforementioned non-blocking sending module, and the two work in parallel without blocking each other. The asynchronous receiving thread uses an event-driven approach (e.g., using the epoll or select system calls to listen for readable events on the serial port file descriptor). When data arrives on the physical serial port, the thread is awakened and reads the data. For received data frames, the asynchronous receiving thread first performs frame parsing to identify whether the data frame is a reply frame or an active reporting frame.
[0043] Specifically, frame parsing is performed according to a preset communication protocol. For example, in the Modbus protocol, it is determined by parsing the function code and device address, combined with whether there are any pending communication requests. If there is a communication request awaiting a reply, and the device address and transaction identifier in the received data frame match the request, then it is determined to be a reply data frame; If there is no matching request to be replied to, or if the function code in the received data frame indicates an active reporting type, then it is determined to be an active reporting data frame.
[0044] If it is a reply data frame, the corresponding communication request is matched according to the frame identifier, and the reply data is forwarded to the application function module that initiated the request.
[0045] If it is an actively reported data frame, its source device address is parsed and the reported data is forwarded to the application function module that has subscribed to the reported event of that device.
[0046] Through this independent asynchronous receiving thread, the system's receiving and sending processes are completely decoupled. Receiving no longer blocks the sending thread, and sending no longer needs to synchronously wait for receiving to complete; both can operate independently on their respective time scales. More importantly, this mechanism makes the processing of proactively reported data independent of specific communication modes—whether in exclusive or shared mode, as long as the slave actively sends a data frame when the bus is idle, the asynchronous receiving thread can capture and process it in real time. This expands the scope of proactive reporting support from the existing exclusive mode to all operating modes, completely solving the technical problem of sudden data loss such as slave alarms in shared bus mode.
[0047] Furthermore, this embodiment also provides an address lock operation mechanism based on the above asynchronous reception processing mechanism.
[0048] When the asynchronous receiving thread identifies the currently received data frame as an actively reported data frame, in addition to forwarding the reported data to the corresponding application function module, it also parses the source device address of the actively reported data frame, and then freezes all pending communication requests in the pending transmission queue whose destination address is the same as the source device address.
[0049] During the address lock's effective period, if the preemptive scheduling module detects a new high-priority communication request being enqueued, and the destination address of this new request is the same as the device address currently locked by the address lock, the system will determine priority according to the following rules: Since the address lock is established to avoid bus collisions with slave devices actively reporting, its security priority is higher than the regular task-level scheduling priority. Therefore, even if a newly enqueued request has a higher preset priority, it will not be sent immediately before the address lock is released. Instead, it will be placed in a "high-priority temporary storage area" bound to the lock address. Requests in this temporary storage area will not participate in the scanning of the main pending transmission queue until the address lock is released. When the address lock is released and the physical serial port becomes idle again, the system will prioritize retrieving delayed high-priority requests from this temporary storage area for transmission, and then restore other frozen requests in the main pending transmission queue. This decision rule ensures that bus security constraints (address locks) strictly take precedence over task-level priority scheduling, while high-priority requests receive compensatory priority transmission rights after the lock is released, preventing high-priority tasks from being indefinitely delayed due to address locks.
[0050] The term "freeze" refers to: These marked communication requests are temporarily excluded from priority selection and scheduling in step S2. That is, the non-blocking sending module skips frozen requests when scanning the queue to be sent until the freeze is lifted. During the freeze, the timeout timer for the frozen communication requests is paused and resumes after the address lock is released. The timeout waiting time is not consumed during the freeze, thus avoiding the master end's misjudgment of a timeout due to the slave device's active reporting occupying the bus for too long. After the actively reported data frame is distributed to the corresponding application function module, the asynchronous receiving thread waits for an acknowledgment signal. When it receives an acknowledgment response from the APP or confirms within a certain time that the reported data processing is complete and that the physical serial port has returned to an idle state, the address lock is released, and the normal queuing and sending state of the frozen communication requests is restored.
[0051] The so-called "confirmation that the physical serial port has returned to an idle state" can be achieved by detecting the serial port's carrier detection signal or by determining that no new actively reported data has arrived within a certain period of time. This address locking mechanism fundamentally avoids data collisions on the physical bus between "master-issued commands" and "slave-initiated reporting"—when a slave is actively reporting data, the master will not send any requests to that slave, and only one device can be sending messages on the bus at a time. This ensures that even in shared bus mode, the slave's actively reported data can be transmitted completely and without collisions. Simultaneously, by pausing the timeout timer, unnecessary retry traffic is avoided from further occupying the bus, improving the system's fault tolerance accuracy.
[0052] To implement the pause and resume function of the timeout timer, this embodiment does not directly rely on the hardware timer provided by the operating system (such as timerfd, setitimer, etc., which do not support pause operations), but adopts the "accumulated waiting time" model. Specifically, each communication request records two time base fields when it is created: start_timestamp (the timestamp when the request enters the queue to be sent or begins to wait for a reply) and accumulated_wait (the accumulated waiting time, initially 0).
[0053] When a request begins waiting for a response, the system records the current system monotonic clock value as start_timestamp. When it is necessary to pause the timer (such as when an address lock takes effect or the request is preempted), the system calculates the time difference from start_timestamp to the current time, adds this difference to the accumulated_wait field, and then clears the start_timestamp flag.
[0054] When the timing needs to be resumed, the system rereads the current system clock value, updates `start_timestamp` to the current value, and calculates the total waiting time based on `accumulated_wait + (current clock - start_timestamp)` to determine if a timeout has occurred. The timeout judgment logic is unified as follows: If accumulated_wait + (current clock - start_timestamp, if start_timestamp is valid) ≥ the current valid timeout waiting time of the communication request (the specific value of the timeout waiting time is calculated in real time by the bus load statistics and dynamic timeout adjustment mechanism described below, rather than a fixed preset value), then it is determined to be a timeout.
[0055] This model does not rely on the pause capability of any operating system timer hardware. It can perform any number of pause / resume operations simply by reading the system monotonic clock. It has good portability and determinism, and works independently and collaboratively with the dynamic timeout adjustment mechanism described below—the former manages the accumulation method of time, and the latter manages the timeout judgment threshold.
[0056] Furthermore, this embodiment also provides a bus load statistics and dynamic timeout adjustment mechanism based on the above asynchronous reception processing mechanism.
[0057] During operation, the asynchronous receiving thread counts the number of actively reported data frames received on the physical serial port per unit time. This number reflects the current bus busyness level due to slave device active reporting. Based on this statistic, the system calculates the current bus busy index. As a specific implementation, the bus busy index can be calculated using the following formula: BusyIndex=min(N_active / N_threshold,1.0), Where N_active is the number of actively reported data frames received within the current statistics window, N_threshold is the preset busy threshold (e.g., 10 frames per second), and BusyIndex ranges from 0 to 1. Subsequently, after sending the communication request in step S2, the timeout waiting time of the communication request is dynamically set according to the bus busy index, and the timeout waiting time is positively correlated with the bus busy index.
[0058] To more accurately reflect the true busy level of the physical serial bus, this embodiment expands the calculation of the bus busy index, taking into account not only the number of data frames actively reported by the slave devices but also the number of communication requests sent by the master device. Specifically, the system maintains two counters simultaneously within the statistics window: N_report (number of actively reported data frames received) and N_request (number of communication request data frames sent by the non-blocking transmission module). The bus busy index is calculated using the following extended formula: BusyIndex=min((N_report×W_report+N_request×W_request) / N_threshold,1.0) W_report and W_request are the weighting coefficients for proactive reporting and host-issued requests, respectively (configurable according to actual bus characteristics, e.g., W_report=1.0, W_request=0.8, as proactive reporting typically consumes more processing time on the slave). Through this extended statistic, when host-issued requests are concentrated, the bus busy index increases accordingly, and the timeout waiting time automatically extends, avoiding misjudgments of timeouts caused by underestimating bus load due to only counting proactive reporting. Simultaneously, the system updates the above counters using a sliding time window (e.g., sliding every 200ms) to ensure that the bus busy index can quickly respond to transient changes in bus load, achieving more accurate adaptive timeout adjustment.
[0059] Specifically, the dynamic timeout waiting time can be calculated using the following formula: Timeout=BaseTimeout×(1+BusyIndex×α), BaseTimeout is the basic timeout period set in the communication protocol or configuration file (e.g., 200ms), and α is a preset adjustment coefficient (e.g., 1.5). When the bus busy index is high, the timeout waiting time is automatically extended, avoiding the situation where frequent reports from slave devices occupy the bus, causing the master request to fail to receive a timely response and thus being incorrectly judged as a timeout and triggering a retry. The reduction in retry traffic further avoids additional bus occupation, thereby forming a positive feedback loop of "bus busy → extended timeout → reduced invalid retries → reduced bus load". Through this mechanism, the system has congestion awareness and adaptive adjustment capabilities, and can dynamically adjust its own behavior parameters according to the real-time bus status without manual configuration.
[0060] Based on the above method, this embodiment also provides a graded retry control mechanism.
[0061] As mentioned earlier, each communication request carries a maximum retry count parameter when enqueued. Specifically, after sending a communication request in step S2, the system starts an independent timeout timer for that request, with a timeout duration calculated based on the dynamic timeout adjustment mechanism described above. If no reply data frame is received within the timeout period after the communication request is sent, the transmission is deemed to have failed. After determining that the transmission has failed, the system checks the current number of retries for that communication request: If the number of retries is less than the maximum number of retries, the communication request will be put back into the queue to be sent and will be sent again. If the maximum number of retries has been reached, the communication request is moved to a dead-letter queue, and the application module that initiated the request is notified. The notification includes at least the reason for failure (timeout) and the number of retries. When the communication request is re-entered into the queue, the system can reorder the position of the request. Specifically, the re-entered request can be inserted into the corresponding position of the queue according to its current scheduling priority, rather than simply being placed at the end of the queue, to ensure that the retry request can obtain an appropriate scheduling priority based on its urgency. Through this hierarchical retry mechanism, the crude "discard upon failure" approach in the prior art is upgraded to configurable multiple rescues, significantly reducing the data loss rate caused by network transient fluctuations or brief periods of slave device busyness (e.g., the slave device is processing a previous command and is not yet ready). At the same time, through the dead-letter queue and APP notification, even if the final processing fails, the data and the reason for failure are still traceable, facilitating troubleshooting by maintenance personnel.
[0062] Furthermore, this embodiment, based on the retry control mechanism described above, deeply couples the retry parameters with priority scheduling. Specifically, the system maintains the current scheduling priority of each communication request in real time. This priority is not fixed but dynamically calculated using the following formula: P_current=P_base+P_aging+P_retry in: P_current represents the current scheduling priority of the communication request; the larger the value, the higher the priority. P_base represents the preset priority parameter of the communication request, which is specified by the application function module that initiated the request when creating the communication request, and the value range is, for example, 0 to 63; P_aging represents the aging gain for the waiting time, which increases as the waiting time of the communication request in the queue to be sent increases.
[0063] Specifically, P_aging = min(floor(T_wait / T_aging) × G_aging, G_aging_max), where T_wait is the cumulative waiting time of the request that has been queued, T_aging is the aging time step (e.g., 500ms), G_aging is the aging gain for each step (e.g., 1), and G_aging_max is the maximum value of the aging gain (e.g., 10). This aging gain ensures that any request, after waiting long enough, will have its priority increased to a level sufficient for scheduling, thus preventing low-priority tasks from being permanently starved due to the continuous influx of high-priority tasks. P_retry represents the urgent retry offset, and its calculation formula is as follows: P_retry=(N_max-N_current)×G_emergency, Where N_max is the preset maximum number of retries for this communication request, N_current is the current number of retries for this communication request, and G_emergency is the preset urgency weight coefficient (e.g., 5). The physical meaning of this formula is: Each time a communication request is retried, the remaining number of retries decreases by one, and P_retry increases by an offset of G_emergency. Since this offset is directly added to the current scheduling priority, each retry will give the request a step-by-step priority increase. Through this dynamic priority calculation formula, the two concerns of starvation prevention (via P_aging) and near-death rescue (via P_retry) are unified under the same mathematical model, achieving precise quantification of scheduling strategies.
[0064] Furthermore, based on the above dynamic priority calculation, this embodiment also provides a highest priority guarantee mechanism for near-death missions.
[0065] Specifically, when the number of retries for a communication request reaches the maximum number of retries minus one (i.e., N_current = N_max - 1, with only one retry opportunity remaining), the P_retry value of the request will reach its maximum, i.e., (N_max - (N_max - 1)) × G_emergency = G_emergency. Since the value of G_emergency is sufficiently large (e.g., 5), and the typical range of the preset priority P_base is 0 to 63, and the typical maximum value of the aging gain P_aging is 10, when G_emergency is set to a value greater than the maximum possible value of P_base + P_aging, the current scheduling priority P_current of the request will be higher than the priority of all communication requests in the queue that have not undergone retries. This means that the task on the verge of being discarded receives the highest scheduling privilege in its last chance to survive, and even if there are a large number of high-priority requests that have not been retried in the queue, the dying task will be sent first. This mechanism minimizes the risk of communication requests being moved to the dead letter queue due to lack of opportunity to be sent, thus ensuring the reliability of the system's data even in extreme congestion scenarios.
[0066] Based on the above method, this invention also provides a serial port single-wire multi-party communication system. This system specifically includes a queue management module, a non-blocking transmission module, a preemptive scheduling module, an asynchronous reception module, an address lock module, a retry management module, and a priority dynamic calculation module. The connection relationships and working processes of each module are as follows: The queue management module receives communication requests from multiple application modules and stores these requests in a queue corresponding to the same physical serial port according to their priority. Specifically, the queue management module provides a unified API interface, through which each application submits communication requests. Internally, the queue management module maintains a global priority queue data structure and is responsible for ensuring the first-in-first-out order when priorities are the same.
[0067] The non-blocking transmission module is connected to the queue management module and is used to select the highest priority communication request from the queue to be sent. It then sends the data frame of this communication request in a non-blocking manner through the physical serial port. After transmission, it returns immediately without waiting for a reply and continues processing the next communication request in the queue. Specifically, the non-blocking transmission module interacts with the physical serial port driver layer through the operating system's asynchronous I / O interface. After each transmission, it triggers a queue scan operation in the queue management module to obtain the next request to be sent.
[0068] The preemptive scheduling module is connected to both the queue management module and the non-blocking transmission module. During the transmission process of the non-blocking transmission module, if a new high-priority communication request is detected being enqueued, the module pauses the waiting state of the current communication request and prioritizes the non-blocking transmission module in processing the new high-priority communication request. Specifically, the preemptive scheduling module monitors the enqueueing event of the queue management module to achieve real-time detection of new request arrivals, and sends a preemptive signal to the non-blocking transmission module when a high-priority request is detected being enqueued.
[0069] The asynchronous receiving module is used to monitor the input data of the physical serial port in real time through an independent asynchronous receiving thread, and to parse and distribute the received data frames. Specifically, the asynchronous receiving module includes an independent event loop thread, which listens for read events of the serial port file descriptor through the epoll mechanism. When data arrives, it is read and parsed according to the protocol. Based on the parsing result, the data frame is routed to the corresponding APP or the operation of the address lock module is triggered.
[0070] The address locking module is connected to both the asynchronous receiving module and the queue management module. When the asynchronous receiving module identifies an actively reported data frame, it parses the source device address, freezes all pending communication requests in the transmission queue whose destination address matches the source device address, and unfreezes the requests after the actively reported data frame has been processed. Specifically, the address locking module maintains a global "address lock table" that records the currently locked device addresses and their corresponding frozen request lists. The queue management module skips frozen requests when scanning the queue for priority sorting.
[0071] The retry management module is connected to the non-blocking sending module and is used to perform retry control based on the maximum number of retries for a communication request after the sending timeout. Specifically, the retry management module includes a timeout detection wheel that periodically checks whether all communication requests waiting for a reply have timed out. For timed-out requests, it determines whether to re-enqueue or move them to the dead-letter queue based on the number of retries already made.
[0072] The priority dynamic calculation module is connected to the queue management module and is used to dynamically calculate the current scheduling priority based on the preset priority of the communication request, the aging gain of the waiting time, and the retry emergency offset. Specifically, the priority dynamic calculation module performs real-time calculation using the aforementioned formula P_current=P_base+P_aging+P_retry. The priority of each communication request in the queue to be sent in the queue management module is updated in real time by this module. The non-blocking sending module selects the communication request with the highest current priority from the queue to be sent each time.
[0073] In a multi-threaded concurrent environment, the preset priority, aging gain, and retry emergency offset of the same communication request may be accessed and modified simultaneously by the queue management thread, timeout monitoring thread, and retry management thread, respectively. To ensure data consistency in priority calculation and queue operations, the system employs a fine-grained read-write locking mechanism: each communication request object maintains a lightweight spinlock or mutex. Any thread must acquire the lock of the request object before reading or updating its priority-related fields (P_base, P_aging, P_retry), and releases it immediately after the operation is complete. Simultaneously, the overall structure of the queue to be sent (such as node swapping operations in heap sort) is maintained by a global mutex by the queue management module. When the non-blocking sending module scans the queue to select the highest priority request, it only holds this global lock while reading the head element of the queue, releasing it immediately after reading to reduce lock holding time and avoid becoming a performance bottleneck. This fine-grained locking mechanism ensures the accuracy of priority calculation and the atomicity of queue operations in high-concurrency scenarios, preventing priority errors or queue structure damage due to data race conditions.
[0074] Through the coordinated operation of the aforementioned functional modules, the system embodiment of the present invention can fully implement all the steps of the aforementioned method embodiment and achieve the same technical effect, which will not be repeated here. The modular architecture of the system clearly reflects the complete functional stack from hardware serial port driver to upper-layer scheduling algorithm.
[0075] The above embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features, and such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A serial port single-wire multi-party communication method, characterized in that, Includes the following steps: Step S1: Receive communication requests sent by multiple application function modules, and store the communication requests in the queue to be sent corresponding to the same physical serial port according to priority; Step S2: Select the highest priority communication request from the queue to be sent, and send the data frame of the communication request in a non-blocking manner through the physical serial port. Return immediately after sending without waiting for the reply data of the communication request. Step S3: After the transmission in S2 is completed, return to execute S2 to process the next communication request in the queue to be sent; and, During the execution of S2, if a new high-priority communication request is detected to be enqueued, the waiting state of the current communication request is paused, and the sending process of the new high-priority communication request is executed first.
2. The serial port single-wire multi-party communication method according to claim 1, characterized in that, The phrase "return to execute S2 to process the next communication request in the queue to be sent" in S3 specifically means: after each transmission is completed, rescan the queue to be sent, select the communication request with the highest current priority and send it, until the queue to be sent is empty.
3. The serial port single-wire multi-party communication method according to claim 2, characterized in that, It also includes an asynchronous receiving step: S4: The input data of the physical serial port is monitored in real time through an independent asynchronous receiving thread, the received data frame is parsed, and the data frame is identified as a reply data frame or an active reporting data frame. If it is a reply data frame, the corresponding communication request is matched according to the frame identifier, and the reply data is forwarded to the application function module that initiated the request; If it is an actively reported data frame, its source device address is parsed and the reported data is forwarded to the application function module that has subscribed to the reported event of that device.
4. The serial port single-wire multi-party communication method according to claim 3, characterized in that, After identifying the actively reported data frame in step S4, an address lock operation is also performed: Parse the source device address of the actively reported data frame and freeze all pending communication requests in the pending transmission queue whose destination address is the same as the source device address; After the actively reported data frame is distributed to the corresponding application function module, and it is confirmed that the physical serial port has returned to an idle state, the address lock is released, and the normal queuing and sending of the frozen communication requests are restored.
5. The serial port single-wire multi-party communication method according to claim 4, characterized in that, In step S4, during the period when the address lock is in effect, the timeout timer for the frozen communication request is paused and resumes counting after the address lock is released.
6. The serial port single-wire multi-party communication method according to claim 3, characterized in that, S4 also includes a bus load statistics step: The number of actively reported data frames received on the physical serial port per unit time is counted, and the current bus busy index is calculated. After a communication request is sent in S2, the timeout waiting time of the communication request is dynamically set according to the bus busy index, and the timeout waiting time is positively correlated with the bus busy index.
7. The serial port single-wire multi-party communication method according to claim 1, characterized in that, The communication request carries a preset priority parameter and a maximum number of retries parameter; S2 also includes a retry control step: If no reply data frame is received within the timeout period after a communication request is sent, the transmission is deemed to have failed. If the number of retries for the communication request is less than the maximum number of retries, the communication request is put back into the queue to be sent and waited to be sent again; if the number of retries reaches the maximum number of retries, the communication request is moved into the dead letter queue and the application function module that initiated the request is notified.
8. The serial port single-wire multi-party communication method according to claim 7, characterized in that, The current scheduling priority of the communication request is dynamically calculated using the following formula: Current priority = Preset priority + Waiting time aging gain + Retry emergency offset; The waiting time aging gain increases as the waiting time of the communication request in the queue to be sent increases; the retry urgent offset = (maximum number of retries - number of retries already tried) × urgent weight coefficient, and the retry urgent offset increases by one urgent weight coefficient for each retry of the communication request.
9. The serial port single-wire multi-party communication method according to claim 8, characterized in that, When the number of retries for the communication request reaches the maximum number of retries minus one, the retry emergency offset raises the current scheduling priority of the communication request to a higher priority than all communication requests in the queue that have not undergone retries.
10. A serial port single-wire multi-party communication system, characterized in that, include: The queue management module is used to receive communication requests sent by multiple application function modules and store the communication requests in the queue to be sent corresponding to the same physical serial port according to priority. The non-blocking sending module is used to select the highest priority communication request from the queue to be sent, send the data frame of the communication request in a non-blocking manner through the physical serial port, return immediately after sending without waiting for the reply data of the communication request, and continue to process the next communication request in the queue to be sent. The preemptive scheduling module is used to pause the waiting state of the current communication request and prioritize the non-blocking sending module to execute the sending process of the new high-priority communication request if a new high-priority communication request is detected during the sending process of the non-blocking sending module. The asynchronous receiving module is used to monitor the input data of the physical serial port in real time through an independent asynchronous receiving thread, and to parse and distribute the received data frames; The address lock module is used to parse the source device address of the actively reported data frame when the asynchronous receiving module identifies it, freeze all pending communication requests in the pending transmission queue whose destination address is the same as the source device address, and unfreeze the active reported data frame after it has been processed. The retry management module is used to perform retry control based on the maximum number of retries for a communication request after the communication request has timed out. The priority dynamic calculation module is used to dynamically calculate the current scheduling priority based on the preset priority of the communication request, the waiting time aging gain, and the retry emergency offset. Furthermore, the priority of each communication request in the queue to be sent is updated in real time by the priority dynamic calculation module, and the non-blocking sending module selects the communication request with the highest current priority from the queue to be sent each time.
Citation Information
Patent Citations
Multi-serial port communication management method based on time division multiplexing mechanism
CN115328836A
Multi-mode communication data proxy system and method
CN116527770A
Method and system for asynchronous serial communications between equipments through main processor
CN1774696B