A Modbus protocol processing method and slave device based on hash mapping

CN122578359APending Publication Date: 2026-08-14深圳市广能达半导体科技有限公司
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610960121.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-06-30
Publication Date
2026-08-14

AI Technical Summary

Technical Problem

[0005]为了克服现有的Modbus协议寻址效率低下与代码架构僵化的问题,本发明提供了一种基于哈希映射的Modbus协议处理方法及从站设备

Benefits of technology

1、本发明将Modbus请求帧中的寄存器地址字段直接作为哈希表的功能键,通过哈希查找(平均时间复杂度O(1))替代传统的线性比较(时间复杂度O(n)),使从站设备在接收到请求帧后能够以常数级时间定位到对应的处理函数,消除了参数数量增加带来的响应延迟累积,满足了射频电源等实时控制系统对微秒级通信响应的苛刻要求;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122578359A_ABST
    Figure CN122578359A_ABST
Patent Text Reader

Abstract

This invention discloses a Modbus protocol processing method and slave device based on hash mapping, relating to the field of Modbus protocol technology. The Modbus protocol processing method includes: receiving a request frame sent by a Modbus master station; parsing the request frame, extracting the register address field, and using the value of this field as the function key of a hash table, where the hash table pre-stores a mapping relationship between function keys and function pointers; searching for the corresponding function pointer in the hash table based on the function key, where the function pointer points to a processing function; and calling and executing the processing function to complete the business logic operation corresponding to the function key. This invention achieves constant-level addressing through hash lookup, replacing traditional linear comparison, effectively improving addressing efficiency. It also modularizes business logic into independent functions, decoupling them from the core protocol parsing, allowing for dynamic functional expansion without modifying the core code.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of Modbus communication protocol technology, and more specifically, to a Modbus protocol processing method and slave device based on hash mapping. Background Technology

[0002] The Modbus protocol, due to its simplicity, openness, and ease of implementation, has become the de facto standard for inter-device communication in industrial automation and semiconductor manufacturing equipment (such as RF generators and automatic impedance matching devices in RF power systems). In a typical Modbus slave device implementation, each accessible device parameter (e.g., output power, reflected power, matching capacitor position, etc.) is pre-assigned a fixed register address (e.g., holding registers 40001, 40025). The slave device firmware typically uses a centralized, large conditional branching structure—such as a switch-case or if-else if block—to handle read / write requests initiated by the master: after parsing the register address field in the request frame, the program compares the address with preset constant values ​​one by one; if a match is found, the corresponding parameter read or write operation is executed. Although this processing method based on static address mapping and linear branch judgment is simple to implement, its inherent defects are becoming increasingly apparent as system scale and real-time requirements continue to increase.

[0003] First, when slave devices need to expose hundreds or thousands of parameters, the register addresses carried by the master controller in the request frame require linear comparison (time complexity O(n)) to locate the target operation branch. As the number of parameters increases, the response delay increases linearly, which has become a critical bottleneck for plasma process control requiring real-time responses in the microsecond to millisecond range. Second, all business logic (reading, writing, converting, and verifying different parameters) is forced into the same branch function, resulting in extremely bloated code and high coupling. Any addition or modification of parameters requires in-depth modification of the core protocol processing function, which can easily lead to address conflicts or logical errors, resulting in poor system scalability and high maintenance costs.

[0004] Therefore, how to fundamentally improve the addressing efficiency from register addresses to business logic and achieve modularization of protocol processing code while maintaining full compatibility with the standard Modbus protocol frame format has become a pressing technical problem in this field. Summary of the Invention

[0005] To overcome the problems of low addressing efficiency and rigid code architecture in existing Modbus protocols, this invention provides a Modbus protocol processing method and slave device based on hash mapping.

[0006] The technical solution of this invention is as follows: A Modbus protocol processing method based on hash mapping includes: Receive Modbus request frames sent by the Modbus master station; The Modbus request frame is parsed, the register address field is extracted, and the value of the register address field is used as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. Based on the function key, the corresponding function pointer is searched in the hash table, and the function pointer points to the processing function; The processing function pointed to by the function pointer is called and executed to complete the business logic operation corresponding to the function key.

[0007] Preferably, the request frame includes at least a slave address field, a function code field, a register address field, a data field, and a verification field.

[0008] Preferably, the process of extracting the register address field and using the value of the register address field as the function key of the hash table includes: The register address field is a 16-bit unsigned integer with a value range of 0x0000 to 0xFFFF; The value of the 16-bit unsigned integer is directly used as the function key of the hash table without any numerical transformation or address offset correction.

[0009] Preferably, the process of looking up the corresponding function pointer in the hash table based on the function key includes: If the hash lookup is successful, the function pointer corresponding to the function key is obtained, and the processing function is directly called and executed through the function pointer; If the hash lookup fails, an exception response code is returned to the main site, indicating that the function key is not registered or is invalid.

[0010] Preferably, the processing function encapsulates the business logic operation corresponding to the function key. The business logic operation includes, but is not limited to, reading physical registers, writing physical registers, performing data calculations or status judgments, and the execution result of the processing function is encapsulated into a response frame according to the Modbus protocol format and returned to the master station.

[0011] Preferably, reading the physical register specifically includes: The address of the target physical register to be read is determined based on the function key. The target physical register is a storage unit inside the slave device used to store real-time acquired data or status information. The raw data is read from the target physical register through the underlying hardware driver interface; The read raw data is validated, including checking whether the raw data is within a reasonable range of values ​​and whether it meets physical constraints. The verified data is organized according to the Modbus response frame format, and a CRC check is added before being returned to the master station.

[0012] Preferably, writing to the physical register specifically includes: Extract the data value to be written from the data field of the Modbus request frame; The address of the target physical register is determined according to the function key. The target physical register is a storage unit inside the slave device used to store configuration parameters or control commands. Perform write permission verification to determine whether the current operation allows writing to the target physical register; Write the data value into the target physical register, and immediately read back the written value for verification. If the read value matches the write value, a successful response frame is constructed and returned to the main station; if they do not match or the permission verification fails, a write failure exception response code is returned.

[0013] Preferably, the hash table stores a mapping relationship between function keys and function pointers, and the mapping relationship supports dynamic registration and updating, specifically including: When a new function is needed, the new function key and the function pointer of the new processing function are inserted into the hash table as a key-value pair by calling the unified registration interface function. If a hash collision occurs during the insertion process, open addressing or chaining is used to resolve the collision. After registration, the Modbus slave device can respond to request frames containing the newly added function keys without modifying the original protocol parsing core code.

[0014] Preferably, when the hash table needs to unload a registered function, the key-value pair corresponding to the function key is deleted from the hash table by calling a unified unregistration interface function, thereby releasing the corresponding storage resources; after unloading, the main station will send a request frame containing the function key, which will trigger a hash lookup failure and return an exception response code.

[0015] A second aspect of the present invention also provides a Modbus slave device, comprising a communication interface module, a protocol parsing module, a hash lookup module, and a function execution module, wherein: The communication interface module is used to receive Modbus request frames sent by the Modbus master station. The protocol parsing module is used to parse the Modbus request frame, extract the register address field, and use the value of the register address field as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. The hash lookup module is used to look up the corresponding function pointer in the hash table based on the function key, and the function pointer points to the processing function. The function execution module is used to call and execute the processing function pointed to by the function pointer to complete the business logic operation corresponding to the function key.

[0016] The Modbus protocol processing method and slave device based on the above scheme, which is based on hash mapping, have the following advantages: 1. This invention uses the register address field in the Modbus request frame as the function key of the hash table. It replaces the traditional linear comparison (time complexity O(n)) with hash lookup (average time complexity O(1)). This enables the slave device to locate the corresponding processing function in constant time after receiving the request frame, eliminating the cumulative response delay caused by the increase in the number of parameters and meeting the stringent requirements of real-time control systems such as RF power supplies for microsecond-level communication response. 2. This invention decouples function keys from processing function pointers through a hash table, allowing business logic such as reading, writing, calculating, and verifying different parameters to be encapsulated into independent functions. The protocol parsing core only needs to perform hash lookups and function calls, completely eliminating the bloated centralized branching statements. When adding or modifying device parameters, it is only necessary to implement the corresponding processing function and register the function key in the hash table, without modifying the protocol parsing core code. This avoids the risk of address conflicts and logical errors, greatly reduces maintenance costs, and supports dynamic registration and unregistration of functions, providing an architectural foundation for plug-and-play devices and modular system evolution. 3. This invention does not change the frame format, function code, or communication process of the Modbus request frame. It only reconstructs the protocol parsing and distribution mechanism inside the slave device. Therefore, existing Modbus master devices can communicate normally with the slave devices of this invention without any modifications, reducing the threshold and cost of technology upgrades. Attached Figure Description

[0017] To more clearly illustrate the technical solutions in the embodiments of the present invention, 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 the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0018] Figure 1This is a flowchart illustrating the Modbus protocol processing method provided by the present invention. Detailed Implementation

[0019] To make the technical problems to be solved, the technical solutions, and the beneficial effects of the present invention clearer, the present invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are only used to explain the present invention and are not intended to limit the present invention.

[0020] It should be noted that when a component is referred to as "fixed," "set," or "connected" to another component, it may be located directly or indirectly on that other component. The terms "upper," "lower," "left," "right," "front," "rear," "vertical," "horizontal," "top," "bottom," "inner," and "outer," etc., indicate the orientation or position based on the accompanying drawings, and are for ease of description only, and should not be construed as limiting the technical solution. The terms "first," "second," etc., are used for ease of description only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features. "Many" means two or more, unless otherwise explicitly specified. "Several" means one or more, unless otherwise explicitly specified.

[0021] See Figure 1 This invention provides a Modbus protocol processing method based on hash mapping, specifically including: S1. Receive Modbus request frames sent by the Modbus master station; S2. Parse the Modbus request frame, extract the register address field, and use the value of the register address field as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. S3. Based on the function key, find the corresponding function pointer in the hash table, and the function pointer points to the processing function; S4. Call and execute the processing function pointed to by the function pointer to complete the business logic operation corresponding to the function key.

[0022] In some embodiments, the process of performing step S1 includes: S1.1 Communication link monitoring and detection; S1.2, Frame start detection; S1.3, Byte-by-byte reception and buffering; S1.4 Integrity verification; S1.5, Frame Submission.

[0023] Specifically, during step S1.1, the Modbus slave device monitors signals on the physical link in real time through its hardware communication interface (such as an RS-485 serial interface, Ethernet interface, or fiber optic interface). These communication interfaces correspond to either the Modbus RTU protocol or the Modbus TCP protocol. After the slave device is powered on, the communication interface module enters a continuous receiving state, waiting for data transmission on the bus.

[0024] In some embodiments, the execution of step S1.2 includes Modbus RTU mode and Modbus TCP mode: In Modbus RTU mode, the slave device determines the start of a frame by detecting the bus idle time. The Modbus RTU protocol specifies that the first byte received after a bus idle time (i.e., the time interval without data transmission) reaches at least 3.5 character times marks the start of a data frame. The slave device uses a timer or a hardware inter-character timer to monitor this condition. Once the idle condition is met, the receive logic enters the frame reception state.

[0025] In Modbus TCP mode, since data is carried on TCP / IP packets, frame start detection is automatically handled by the TCP / IP protocol stack. When the underlying network interface receives a new TCP segment, the slave device's protocol stack resolves the IP address and port number, and reports the data belonging to the Modbus service port (default 502) to the Modbus protocol resolution layer.

[0026] Furthermore, during step S1.3, the process includes: upon detecting the start of a frame, the slave device sequentially stores the subsequently received bytes into a pre-allocated receive buffer using either interrupt mode or DMA (Direct Memory Access). To handle the maximum possible frame length, the buffer capacity is typically set to 256 bytes or larger. During reception, the time interval between every two bytes is monitored: for RTU mode, if the interval between adjacent bytes exceeds 1.5 character times, the current frame is considered to have ended, and reception is stopped; for TCP mode, frame boundaries are determined based on the TCP payload length field.

[0027] Specifically, during the execution of step S1.4, the process includes: after a complete frame of data is received, the slave device performs a preliminary integrity check according to the protocol type.

[0028] For RTU mode, first check if the frame length is at least 4 bytes (including slave address, function code, and CRC). Then, calculate the CRC check value of the entire frame content (excluding the last two CRC bytes) and compare the calculated result with the received CRC value. If they match, it indicates that no data error occurred during frame transmission; if they do not match, discard the frame, do not clear the receive buffer, do not send any response, and directly return to the listening state to wait for the next frame.

[0029] In TCP mode, since the TCP protocol itself provides reliable transmission and verification mechanisms, Modbus TCP frames do not require additional CRC checks. However, it is necessary to check whether the length field in the MBAP header matches the actual length of the received protocol data unit. If they do not match, the frame is considered invalid, discarded, and the system restarts listening.

[0030] Further, in step S1.5, after the integrity check passes, the original data frame in the receive buffer, along with the frame length information, is submitted to the protocol parsing layer. At the same time, the buffer is cleared or the buffer pointer is reset to prepare for receiving the next frame.

[0031] In some embodiments, the process of performing step S2 includes: S2.1 Frame Structure Analysis; S2.2, Register address extraction; S2.3 Function key generation.

[0032] Specifically, the process of executing step S2.1 includes: obtaining a complete Modbus request frame that has passed CRC verification from the receive buffer. Different parsing strategies are used depending on the communication protocol type.

[0033] For Modbus RTU mode, the request frame sequentially includes the slave address (1 byte), function code (1 byte), high byte of register address, low byte of register address, data field (variable length), and CRC checksum (2 bytes). During parsing, the first byte is read as the slave address and compared with the local address; if the addresses do not match and are not broadcast address 0x00, the frame is discarded and no further processing is performed; then the second byte is read as the function code, which supports standard function codes such as reading holding registers, writing a single register, and writing multiple registers; next, the third and fourth bytes are read and combined into a 16-bit register address value; the data field begins from the fifth byte, and its length depends on the function code and the number of subsequent bytes; the last two bytes are the CRC checksum value.

[0034] In Modbus TCP mode, the request frame encapsulates an MBAP header (containing a transaction identifier, protocol identifier, length field, and unit identifier) ​​on top of the TCP / IP message. During parsing, the first 7 bytes of the MBAP header are removed, the unit identifier is extracted as the slave address for matching, and then the function code and register address are extracted in a manner similar to RTU. TCP mode does not include CRC checksums, but relies on TCP's own checksum mechanism.

[0035] Furthermore, the byte order issue needs to be addressed during the parsing process. The Modbus protocol uses big-endian byte order (high byte first, low byte last). For slave devices running on little-endian processors, when extracting the register address, the high byte needs to be shifted left by 8 bits and then ORed with the low byte to obtain the correct master-endian value.

[0036] In fact, if the request frame length is insufficient to contain the complete register address field (e.g., the total length is less than 4 bytes), it will be judged as an illegal frame, discarded directly, and an abnormal response will be returned; if the slave address is the broadcast address (0x00), the request will be processed normally but no response frame will be returned.

[0037] Specifically, during the execution of step S2.2, the register address field has the following technical features: the register address field is a 16-bit unsigned integer, with a value range of 0x0000 to 0xFFFF, totaling 65536 possible values. This is consistent with the traditional Modbus protocol where register addresses are typically limited to the range of 0x0000-0xFFFF, but this invention does not prune or restrict the address range in any way; all 65536 address values ​​can be used as valid function keys.

[0038] During extraction, the combined 16-bit value is directly stored in a temporary variable without any numerical transformation or modification of the data in the original receive buffer. This temporary variable will be passed to the next sub-step as the original value of the function key.

[0039] For broadcast frames, although no response is returned, the register address still needs to be extracted normally in order to perform the corresponding function operation.

[0040] Furthermore, the core of step S2.3 is to directly use the extracted register address value as the function key of the hash table without performing any form of numerical conversion or address remapping.

[0041] In traditional Modbus protocol processing, it is usually necessary to subtract an offset (e.g., 40001) from the register address (e.g., 40001) to convert it into an internal index, and then process it using switch-case or if-else branches. This approach increases the processing steps and lacks an intuitive correspondence between the address and the internal logic.

[0042] This invention eliminates this conversion step. Regardless of whether the register address sent by the master station is 0x0001, 0x1001, or 0xFFFF, the slave station retains it as is and uses it directly as the key for hash lookup. The advantages of this approach include: First, maintaining protocol transparency; the register address seen through network packet capture tools is completely consistent with the slave station's internal lookup key, facilitating debugging and troubleshooting. Second, simplifying configuration; there is no need to maintain an additional address offset mapping table, and engineers do not need to memorize complex address translation rules. Third, fully utilizing the entire address space; all address values ​​from 0x0000 to 0xFFFF can be independently registered as different function keys, preventing address overlap or unavailability due to offset calculations.

[0043] In practice, function keys can be assigned names with business meanings. For example, 0x1001 can be used as the function key for "reading RF output power", 0x1002 as the function key for "reading reflected power", and 0x2001 as the function key for "setting target power". The mapping relationship between these function keys and processing functions is pre-registered in a hash table, which decouples the logical address from the business logic.

[0044] In some embodiments, the process of performing step S3 includes: S3.1 Data structure and initialization of the command hash table; S3.2 Design of the hash function; S3.3, Function Registration; S3.4, Solutions to hash collisions; S3.5, Hash Lookup; S3.6, Search result branch processing.

[0045] Specifically, during the execution of step S3.1, the slave device maintains a global command hash table. This hash table is an array of entries, each containing at least two core fields: a function key (i.e., the unsigned integer key value generated in step S2) and a function pointer (pointing to the function that processes the business logic corresponding to that function key). In addition, entries may also contain optional fields, such as the associated physical register base address, access permissions (read-only, write-only, or read-write), and flags indicating whether the entry is valid.

[0046] The hash table itself also maintains information such as the table size (i.e., the number of buckets), the number of currently registered entries, and the load factor threshold. The load factor is used to control the filling rate of the hash table. When the ratio of the number of registered entries to the table size exceeds the threshold, new registrations can be rejected or a resizing operation can be triggered.

[0047] During the power-on or protocol stack initialization phase of the slave device, a command hash table needs to be created. Initialization operations include: allocating an array of entries of a certain size (e.g., 256 entries), setting the valid flag for all entries to invalid, resetting the current entry count to zero, and setting the load factor threshold (e.g., 0.75). After initialization, the hash table is empty and awaits subsequent function registration.

[0048] Specifically, during step S3.2, the hash function maps a 16-bit function key to an index position (i.e., array index) in the hash table. This invention provides various implementations of the hash function, allowing for flexible selection based on the performance characteristics and memory constraints of the target platform.

[0049] A simple and efficient method is the direct modulo method, which uses the function key modulo the hash table size to obtain the index. If the hash table size is chosen to be a power of 2, the modulo operation can be further optimized into a bitwise AND operation, which is extremely fast.

[0050] Another approach is multiplicative hashing, which multiplies the function key by a golden ratio constant (usually approximated as 0x9E37), and then takes the high-order bits of the product modulo the table size. This method achieves good distribution uniformity even when the table size is not a power of 2.

[0051] The third method is hybrid hashing, which involves multiple shift, XOR, and multiplication operations on the function key so that even if the input key value changes very little, the output index will be significantly different, thereby reducing the probability of hash collisions.

[0052] In some preferred embodiments, multiplicative hashing is used because it has moderate computational overhead and good uniformity in embedded environments.

[0053] Furthermore, during step S3.3, the following steps are included: In the slave device firmware, each function that needs to be exposed externally (such as reading power, setting parameters, etc.) needs to be pre-registered in the hash table. The specific registration process is as follows: First, a hash function is used to calculate the index position corresponding to the function key; then, it is checked whether the position is already occupied (i.e., a hash collision has occurred). If the position is free, the function key and function pointer are directly stored in the entry, the valid flag is marked as valid, and the entry count is incremented by one. If the position is occupied, a free position needs to be found through the collision resolution mechanism. If the hash table is full (the number of entries reaches the load factor threshold), the registration fails, and expansion or an error return needs to be selected according to the system design.

[0054] Specifically, step S3.4 includes: Since the size of the hash table is usually much smaller than the potential range of function keys (65536 possibilities), multiple different function keys may be hashed to the same index position; this phenomenon is called a hash collision. This invention provides two collision resolution methods, which can be selected according to actual needs.

[0055] The first approach is open addressing. When the target index position is already occupied, the search continues according to a certain probing sequence (e.g., linear probing, i.e., checking index +1, +2, etc. sequentially) until a free position is found or the entire table is traversed. Linear probing is simple to implement, but it can lead to clustering under high load. Quadratic probing or double hashing can also be used to improve the distribution.

[0056] The second approach is chaining. Each entry in the hash table is no longer a single element, but the head node of a linked list. When multiple function keys hash to the same index, they are chained together as linked list nodes. Searching requires traversing the linked list. Chaining is more tolerant of load factors, but requires additional memory overhead to maintain the linked list pointers.

[0057] In some preferred embodiments, for embedded devices, due to limited memory resources and the need to ensure deterministic lookup time, open addressing is used and an appropriate table size (such as 256 or 512) is selected to maintain a low load factor (such as no more than 0.5), thereby ensuring a low probability of hash collisions.

[0058] Specifically, during step S3.5, the process includes: after the slave device completes step S2 and obtains the function key, it calls the hash lookup function. The lookup process is similar to the registration process: first, the index is calculated using the same hash function, and then the validity of the entry at that index position is checked. If valid and the key value of the entry is equal to the function key being searched, the lookup is successful, and the function pointer stored in the entry is returned. If the key values ​​are not equal, the subsequent positions are checked using the same conflict resolution strategy as during registration (such as linear probing) until a matching key value is found or a free entry is encountered (indicating no match is found). If no match is found after traversing all possible positions, the lookup fails, and a null pointer is returned.

[0059] In fact, since the average time complexity of hash lookup is O(1) and is independent of the number of registered functions, even if the slave device supports hundreds or even thousands of function keys, the lookup speed remains constant and fast, far superior to the O(n) method of traditional linear lookup.

[0060] Further, in step S3.6, when the hash lookup returns a non-null function pointer, it indicates that the function key has been pre-registered and the current request is valid. At this point, the following operations are performed: First, the obtained function pointer is temporarily stored in a local variable. Then, based on the function code and data field in the request frame, the parameters required to call the processing function are prepared. Parameters typically include: operation type (read or write operation), the data value to be written (if it's a write operation), the data buffer pointer, and the data length, etc. After preparation, control is transferred to step S4, which is responsible for actually calling the processing function pointed to by the function pointer. Step S3 itself does not perform a function call; it only completes the lookup and parameter preparation.

[0061] When a hash lookup returns a null pointer, it indicates that the function key is not registered in the current slave device, meaning there is no corresponding handler function for the register address requested by the master. In this case, an exception handling procedure needs to be executed.

[0062] First, an exception response frame is constructed according to the Modbus protocol specification. The structure of the exception response frame is as follows: the first byte is the slave address (same as the original request), the second byte is the highest bit of the original function code set to 1 (i.e., 0x80 is added), and the third byte is the exception code. For scenarios where the lookup fails, this invention preferably returns exception code 0x02, which means "illegal data address," indicating that the register address requested by the master station is invalid or not supported in the slave station.

[0063] Secondly, the constructed exception response frame is returned to the master station through the communication interface. For RTU mode, a CRC checksum needs to be appended to the end of the frame; for TCP mode, the MBAP header needs to be re-encapsulated.

[0064] Then, the current protocol processing flow ends. Specifically, this includes: clearing temporary variables for this request, releasing any dynamically occupied memory (if any), and returning to the main loop or event loop to wait for the next request frame to arrive. Note that step S4 is not executed (i.e., no processing function is called) if the lookup fails.

[0065] In some embodiments, an optional logging function can also be added. In the event of a failed search, an error message, such as "Received unregistered register address: 0xXXXX", is output via the debug serial port or system log to help engineers quickly locate the problem during on-site debugging or remote diagnostics.

[0066] In practice, in some embodiments, when a function no longer needs to be exposed, or when the system needs to dynamically adjust the set of available functions, the slave device supports deregistering the registered function key and its corresponding processing function from the hash table.

[0067] The deregistration process is as follows: First, the index position of the function key to be deregistered is calculated using the same hash function as during registration. Then, the entry corresponding to the function key is searched in the hash table using the same collision resolution strategy (e.g., linear probing) as during registration. During the search, each position in the probe sequence is checked sequentially until a matching key value is found or a free entry is encountered. If a matching entry is found, the valid flag of the entry is set to invalid, and the current entry count is decremented by one. Optionally, any dynamic resources occupied by the entry are released (e.g., dynamically allocated memory buffers associated with the processing function are also released). If no matching function key is found after traversing the entire table, an error is returned (indicating that the function key has not been registered or has been deregistered).

[0068] To ensure the hash table maintains high search efficiency after multiple registration and deregistration operations, in some embodiments, the deregistration operation does not immediately compact or rearrange the hash table; instead, it simply marks the entry as invalid. This avoids large amounts of data movement caused by frequent deregistrations. When a new entry is subsequently registered, an invalid entry encountered during the probing process can occupy that position. If too many invalid entries cause a decrease in search performance, a global rebuild or reorganization operation can be triggered.

[0069] Through this dynamic deregistration mechanism, slave devices can flexibly enable or disable specific functions without restarting or modifying the core code, further enhancing the system's flexibility and maintainability.

[0070] In some embodiments, the process of performing step S4 includes: S4.1 Obtain the function pointer and prepare to call it; S4.2, The specific execution process of the read operation; S4.3, The specific execution process of the write operation; S4.4 Other business logic operations; S4.5, Sending and receiving response frames.

[0071] Specifically, the execution of step S4.1 includes: after step S3 successfully finds and obtains a valid function pointer, step S4 retrieves the function pointer and the previously prepared calling parameters. The processing functions are modular, independent functions, each encapsulating a specific business logic operation, such as reading from a physical register, writing to a physical register, performing data calculations, or determining a status.

[0072] In some embodiments, step S4 first checks whether the function pointer is null (defensive programming). If it is null, an exception response is returned directly. If it is not null, the function code in the request frame determines whether it is a read or write operation, and the corresponding opcode is passed to the processing function accordingly.

[0073] Specifically, during the execution of step S4.2, for a read operation request (function code 0x03), the processing function executes the following business process: First, determine the address of the target physical register to be read based on the function key. The target physical register is a storage unit inside the slave device used to store real-time acquired data or status information, such as RF output power, reflected power, matching capacitor position, temperature, voltage, etc.

[0074] Secondly, raw data is read from the target physical register through the underlying hardware driver interface. This raw data can be ADC sample values, sensor values, or status flag bits.

[0075] Then, the read raw data undergoes necessary processing. This processing includes, but is not limited to: data validation (checking whether the raw data is within a reasonable range and meets physical constraints), filtering (such as average filtering and median filtering), and unit conversion (such as converting ADC code values ​​to watts or percentages). The processed data becomes the final response data to be returned to the main station.

[0076] Finally, the processed data is organized according to the Modbus response frame format. For read holding register operations, the response frame includes the slave address, function code, number of data bytes, and actual data content (2 bytes per register). In RTU mode, a CRC check is also required. After organization, the response frame is returned to the master station via the communication interface.

[0077] Specifically, during the execution of step S4.3, for a write operation request (function code 0x06 or 0x10), the processing function executes the following business process: First, the data value to be written is extracted from the data field of the Modbus request frame. For a single register write operation (0x06), the data field contains 2 bytes of the write value; for multiple register write operations (0x10), the data field contains the number of registers to be written, the number of bytes, and the actual data.

[0078] Secondly, the address of the target physical register is determined based on the function key. The target physical register is a storage unit inside the slave device used to store configuration parameters or control commands, such as target power settings, operating mode selection, and enable control bits.

[0079] Next, a write permission check is performed. This step, combined with the permission check in step S3.6, ensures that the current operation has permission to write to the register. If permissions are insufficient, an exception response code is returned.

[0080] After successful authorization verification, the data value to be written is written to the target physical register. The write operation is completed through the underlying hardware driver interface, which may involve I2C, SPI, or direct memory access.

[0081] In some embodiments, a readback verification can be performed after the write operation is complete (this is an optional extension of the present invention and not a necessary step). Readback verification refers to immediately reading back the value just written from the same physical register and comparing it with the original written value. If they match, the write operation is confirmed as successful; if they do not match, the write operation is determined to have failed.

[0082] Finally, a response frame is constructed based on the execution result. For a single register write operation, the original request frame should be returned as the response frame upon success (as specified in the standard Modbus specification); for multiple register write operations, the slave address, function code, register address, and number of registers written should be returned upon success. If the write fails or the permission check fails, the corresponding exception response code (e.g., 0x03 illegal data value or 0x04 slave device failure) should be returned.

[0083] Specifically, during the execution of step S4.4, in addition to reading and writing physical registers, the processing function can also execute business logic operations that do not directly correspond to physical registers. For example: Perform self-diagnostic operation: When the function key corresponds to the "Device Self-Test" function, the processing function executes the internal self-diagnostic process (such as checking memory, communication interface, sensors, etc.) and packages the diagnostic results and returns them to the main station.

[0084] Execution state switching: When the function key corresponds to the "start / stop" function, the processing function modifies the device's running state machine, starts or stops the RF output, and then returns a status confirmation frame.

[0085] Perform data calculations: When the function key corresponds to the "Calculate Average" function, the processing function reads multiple sample values ​​over a period of time, calculates the average value, and returns it, without relying on a single physical register.

[0086] These processing functions exist as independent modular units, associated with register addresses via function keys in a hash table.

[0087] Further, in step S4.5, after the processing function completes, the generated response frame (including normal or abnormal response) is sent back to the master station through the communication interface. For RTU mode, a CRC checksum needs to be appended to the end of the frame; for TCP mode, the MBAP header needs to be re-encapsulated, including an incrementing transaction identifier.

[0088] After the request is sent, step S4 clears the temporary variables for this request, releases any dynamically occupied memory, and returns to the main loop or event loop to wait for the next frame request. The slave device then re-enters the listening state of step S1.

[0089] A second aspect of the present invention also provides a Modbus slave device, comprising a communication interface module, a protocol parsing module, a hash lookup module, and a function execution module, wherein: The communication interface module is used to receive Modbus request frames sent by the Modbus master station. The protocol parsing module is used to parse the Modbus request frame, extract the register address field, and use the value of the register address field as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. The hash lookup module is used to look up the corresponding function pointer in the hash table based on the function key, and the function pointer points to the processing function. The function execution module is used to call and execute the processing function pointed to by the function pointer to complete the business logic operation corresponding to the function key.

[0090] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A Modbus protocol processing method based on hash mapping, characterized in that, include: Receive Modbus request frames sent by the Modbus master station; The Modbus request frame is parsed, the register address field is extracted, and the value of the register address field is used as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. Based on the function key, the corresponding function pointer is searched in the hash table, and the function pointer points to the processing function; The processing function pointed to by the function pointer is called and executed to complete the business logic operation corresponding to the function key.

2. The Modbus protocol processing method based on hash mapping as described in claim 1, characterized in that, The request frame includes at least a slave address field, a function code field, a register address field, a data field, and a verification field.

3. The Modbus protocol processing method based on hash mapping as described in claim 1, characterized in that, The process of extracting the register address field and using its value as the function key of the hash table includes: The register address field is a 16-bit unsigned integer with a value range of 0x0000 to 0xFFFF; The value of the 16-bit unsigned integer is directly used as the function key of the hash table without any numerical transformation or address offset correction.

4. The Modbus protocol processing method based on hash mapping as described in claim 1, characterized in that, The process of looking up the corresponding function pointer in the hash table based on the function key includes: If the hash lookup is successful, the function pointer corresponding to the function key is obtained, and the processing function is directly called and executed through the function pointer; If the hash lookup fails, an exception response code is returned to the main site, indicating that the function key is not registered or is invalid.

5. The Modbus protocol processing method based on hash mapping as described in claim 1, characterized in that, The processing function encapsulates the business logic operation corresponding to the function key. The business logic operation includes, but is not limited to, reading physical registers, writing physical registers, performing data calculations or status judgments. The execution result of the processing function is encapsulated into a response frame according to the Modbus protocol format and returned to the master station.

6. The Modbus protocol processing method based on hash mapping according to claim 5, characterized in that, The reading of the physical register specifically includes: The address of the target physical register to be read is determined based on the function key. The target physical register is a storage unit inside the slave device used to store real-time acquired data or status information. The raw data is read from the target physical register through the underlying hardware driver interface; The read raw data is validated, including checking whether the raw data is within a reasonable range of values ​​and whether it meets physical constraints. The verified data is organized according to the Modbus response frame format, and a CRC check is added before being returned to the master station.

7. The Modbus protocol processing method based on hash mapping according to claim 6, characterized in that, The writing to the physical register specifically includes: Extract the data value to be written from the data field of the Modbus request frame; The address of the target physical register is determined according to the function key. The target physical register is a storage unit inside the slave device used to store configuration parameters or control commands. Perform write permission verification to determine whether the current operation allows writing to the target physical register; Write the data value into the target physical register, and immediately read back the written value for verification. If the read value matches the write value, a successful response frame is constructed and returned to the main station; if they do not match or the permission verification fails, a write failure exception response code is returned.

8. The Modbus protocol processing method based on hash mapping as described in claim 1, characterized in that, The hash table stores a mapping relationship between function keys and function pointers, and this mapping relationship supports dynamic registration and updating, specifically including: When a new function is needed, the new function key and the function pointer of the new processing function are inserted into the hash table as a key-value pair by calling the unified registration interface function. If a hash collision occurs during the insertion process, open addressing or chaining is used to resolve the collision. After registration, the Modbus slave device can respond to request frames containing the newly added function keys without modifying the original protocol parsing core code.

9. The Modbus protocol processing method based on hash mapping according to claim 8, characterized in that, When the hash table needs to unload a registered function, the key-value pair corresponding to the function key is deleted from the hash table by calling a unified unregistration interface function, thus releasing the corresponding storage resources. After unloading, the main station will send a request frame containing the function key, which will trigger a hash lookup failure and return an exception response code.

10. A Modbus slave device, characterized in that, It includes a communication interface module, a protocol parsing module, a hash lookup module, and a function execution module, among which: The communication interface module is used to receive Modbus request frames sent by the Modbus master station. The protocol parsing module is used to parse the Modbus request frame, extract the register address field, and use the value of the register address field as the function key of the hash table. The hash table pre-stores the mapping relationship between function keys and function pointers. The hash lookup module is used to look up the corresponding function pointer in the hash table based on the function key, and the function pointer points to the processing function. The function execution module is used to call and execute the processing function pointed to by the function pointer to complete the business logic operation corresponding to the function key.