A method and apparatus for parsing object model commands
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-23
- Publication Date
- 2026-08-11
AI Technical Summary
当多条命令共享相同的校验逻辑(如数据格式校验、权限校验)时,这些校验代码被重复编写,导致代码冗余
[0018]本申请实施例提供的一种物模型命令解析方法,包括:读取命令数据到接收缓冲区,所述接收缓冲区初始指向一大缓冲区,所述发送缓冲区初始指向一小缓冲区;若接收数据的长度小于或等于所述小缓冲区的容量,则将所述大缓冲区中的接收数据拷贝至所述小缓冲区,并交换接收缓冲区指针和发送缓冲区指针,使接收缓冲区指向所述小缓冲区、发送缓冲区指向所述大缓冲区;逐条检索命令数据并匹配命令解析器,调用匹配到的命令解析器中的CHECK函数对所述命令数据执行合法性检查;若出现错误则发送错误应答并终止解析,否则,逐条检索命令数据并匹配命令解析器,调用匹配到的命令解析器中的VALID函数对所述命令数据进行有效性检验,所述有效性检验包括关联性校验和约束条件校验;若出现错误则发送错误应答并终止解析,否则,逐条检索命令数据并匹配命令解析器,调用匹配到的命令解析器中的EXECUTE函数对所述命令数据执行实际读写操作,并在本轮所有命令执行完毕后发送应答数据;逐条检索命令数据并匹配命令解析器,调用匹配到的命令解析器中的APPLY函数使操作生效;其中,所述逐条检索命令数据并匹配命令解析器,包括:判断命令数据的操作类型,根据命令码的首字节确定命令数据所属的命令表,所述命令表包括控制命令表、通用命令表、配置命令表、状态命令表;在确定的命令表内,按照所述命令码和操作类型进行命令匹配;匹配成功时获得对应的命令解析器结构体。本申请的方案能够在有限资源的约束下高效实现物模型命令解析。
Smart Images

Figure CN122547404A_ABST
Abstract
Description
Technical Field
[0001] This application belongs to the field of Internet of Things (IoT) communication technology, specifically relating to a method and apparatus for parsing object model commands. Background Technology
[0002] IoT devices typically interact with cloud platforms or control terminals through object model protocols, involving command types such as attribute configuration, status reporting, service calls, and device management. These commands are numerous and varied, placing high demands on the command parsing system in the embedded device firmware: it must ensure parsing efficiency, communication security, and also take into account the limited memory and computing resources of the embedded device.
[0003] Currently, command parsing systems in IoT device firmware generally adopt the following technical solutions: all commands supported by the device are stored in a command table, and the matching command processing function is searched by linear traversal; the command processing flow uses a single function to complete all operations such as parsing, verification, and execution; the security mechanism mainly relies on simple password verification; and the communication buffer is allocated with a fixed size.
[0004] However, the above-mentioned existing technical solutions have the following shortcomings in practical applications: (i) The command processing flow is linear and simple, with high code coupling. Existing solutions typically assign a processing function to each command, which sequentially performs parameter parsing, validity checks, and business logic execution. When multiple commands share the same validation logic (such as data format validation and permission checks), this validation code is repeatedly written, leading to code redundancy. If the validation logic for a command needs to be modified, it may involve changes to multiple processing functions, resulting in poor system maintainability. Furthermore, because validation and execution logic are mixed together, a unified security check cannot be performed before command execution, making it easy to introduce security vulnerabilities.
[0005] (ii) Command search is inefficient and lacks hierarchical classification. Traditional solutions list all commands (including control commands, configuration commands, status reporting commands, etc.) in a single command table. When a device receives a command, the parser needs to traverse the entire command table from beginning to end, comparing command codes one by one until a match is found. As device functionality increases, the number of commands can reach dozens or even hundreds, and the time complexity of command lookup increases linearly (O(n)), severely impacting parsing performance. Furthermore, mixing different types of commands in the same table makes it impossible to implement hierarchical security strategies (for example, control commands require strict authentication, while status reporting commands do not), resulting in either overly lenient security controls or unnecessary overhead imposed on all commands.
[0006] (iii) Low memory resource utilization efficiency Embedded devices have extremely limited memory resources (RAM is typically only tens of KB). Existing solutions generally use fixed-size transmit and receive buffers, such as allocating a fixed-length array for receiving and sending. This design is inefficient when the amount of data in a single communication varies drastically: when transmitting small data (such as reading a sequence number, which only requires a few bytes), most of the space in the fixed buffer is wasted; when transmitting large data (such as firmware upgrade packages or exporting historical records, which may reach several KB), the fixed buffer may be insufficient, causing data to be truncated or requiring fragmented transmission, increasing protocol complexity.
[0007] In summary, how to achieve efficient parsing of IoT device object model commands under limited resource constraints is a technical problem that urgently needs to be solved in this field. Summary of the Invention
[0008] To achieve efficient parsing of IoT device object model commands under limited resource constraints, in a first aspect, embodiments of this application provide an object model command parsing method, including: Command data is read into the receive buffer, which initially points to a large buffer, and the send buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, the received data in the large buffer is copied to the small buffer, and the receive buffer pointer and the send buffer pointer are swapped, so that the receive buffer points to the small buffer and the send buffer points to the large buffer. Search for each command data item and match it with the command parser. Then, call the CHECK function in the matched command parser to perform a validity check on the command data. If an error occurs, an error response is sent and parsing is terminated; otherwise, command data is retrieved one by one and matched with command parsers. The VALID function in the matched command parser is called to perform a validity check on the command data. The validity check includes correlation check and constraint check. If an error occurs, an error response is sent and parsing is terminated; otherwise, command data is retrieved one by one and matched with command parsers. The EXECUTE function in the matched command parser is called to perform actual read and write operations on the command data, and response data is sent after all commands in this round have been executed. Search for each command data item and match it with the command parser. Then, call the APPLY function in the matched command parser to make the operation take effect. The step of retrieving command data line by line and matching command parser includes: Determine the operation type of the command data, and determine the command table to which the command data belongs based on the first byte of the command code. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Within the defined command list, commands are matched according to the command code and operation type. When a match is successful, the corresponding command parser structure is obtained.
[0009] In one possible implementation, the method further includes: Four types of command tables are constructed based on command code, operation type, and processing function; the range of the control command table is 0xE0-0xFF, the range of the general command table is 0xB0-0xDF, the range of the configuration command table is 0x60-0xAF, and the range of the status command table is 0x00-0x5F.
[0010] In one possible implementation, the call to the CHECK function in the matched command parser to perform a validity check on the command data includes: The CHECK function in the matched command parser is invoked to perform a validity check on the format, length, and value range of the command data; Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
[0011] In one possible implementation, the invocation of the EXECUTE function in the matched command parser performs actual read and write operations on the command data, and sends response data after all commands in this round have been executed, including: If it is a read command, the EXECUTE function in the matched command parser is called to read the parameters from the device and write the result to the send buffer; If it is a write command, the EXECUTE function in the matched command parser is called to write the data to the device's temporary variable; Once all commands in this round have been executed, the response data will be sent out through the communication channel.
[0012] In one possible implementation, the invocation of the APPLY function in the matched command parser to make the operation take effect includes: Write the data in the temporary variable to non-volatile memory; Trigger a callback notification or device restart.
[0013] In one possible implementation, the method further includes: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
[0014] Secondly, embodiments of this application provide a device for parsing object model commands, comprising: The reading module is used to read command data into the receiving buffer, which initially points to a large buffer and the sending buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, the received data in the large buffer is copied to the small buffer, and the pointers of the receiving buffer and the sending buffer are swapped, so that the receiving buffer points to the small buffer and the sending buffer points to the large buffer. The legality check module is used to retrieve command data one by one and match it with the command parser, and call the CHECK function in the matched command parser to perform legality checks on the command data; The validity verification module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, and calls the VALID function in the matched command parser to perform validity verification on the command data. The validity verification includes correlation verification and constraint verification. The execution module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, calls the EXECUTE function in the matched command parser to perform actual read and write operations on the command data, and sends response data after all commands in this round have been executed. The activation module is used to retrieve command data one by one and match command parsers, and call the APPLY function in the matched command parser to make the operation take effect; The step of retrieving command data line by line and matching command parser includes: Determine the operation type of the command data, and determine the command table to which the command data belongs based on the first byte of the command code. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Within the defined command list, commands are matched according to the command code and operation type. When a match is successful, the corresponding command parser structure is obtained.
[0015] In one possible implementation, the legality checking module is specifically used for: The CHECK function in the matched command parser is invoked to perform a validity check on the format, length, and value range of the command data; Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
[0016] In one possible implementation, the apparatus further includes a batch reading module for: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
[0017] Thirdly, embodiments of this application provide a computer-readable storage medium storing a computer program, which, when executed by a processor, implements any of the above-described object model command parsing methods.
[0018] This application provides a method for parsing object model commands, comprising: reading command data into a receiving buffer, wherein the receiving buffer initially points to a large buffer and the sending buffer initially points to a small buffer; if the length of the received data is less than or equal to the capacity of the small buffer, copying the received data from the large buffer to the small buffer, and swapping the pointers of the receiving buffer and the sending buffer, so that the receiving buffer points to the small buffer and the sending buffer points to the large buffer; retrieving command data line by line and matching it with a command parser, and calling the CHECK function in the matched command parser to perform a validity check on the command data; if an error occurs, sending an error response and terminating the parsing; otherwise, retrieving command data line by line and matching it with a command parser, and calling the VALID function in the matched command parser to perform a validity check on the command data. The validity check includes correlation verification and constraint verification. If an error occurs, an error response is sent and parsing is terminated. Otherwise, command data is retrieved line by line and matched with command parsers. The EXECUTE function in the matched command parser is called to perform actual read and write operations on the command data, and a response is sent after all commands in this round have been executed. Command data is then retrieved line by line and matched with command parsers, and the APPLY function in the matched command parser is called to make the operation effective. The process of retrieving command data line by line and matching command parsers includes: determining the operation type of the command data; determining the command table to which the command data belongs based on the first byte of the command code; the command table includes a control command table, a general command table, a configuration command table, and a status command table; within the determined command table, command matching is performed according to the command code and operation type; and when a match is successful, the corresponding command parser structure is obtained. The solution of this application can efficiently realize object model command parsing under the constraint of limited resources. Attached Figure Description
[0019] Figure 1 A flowchart illustrating the object model command parsing method provided in this application embodiment; Figure 2 This is a system architecture diagram of the object model command parsing method provided in the embodiments of this application. Detailed Implementation
[0020] Firstly, see [the following] Figure 1 A command parsing method provided in this application includes: S101, read command data into the receive buffer. The receive buffer initially points to a large buffer, and the send buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, copy the received data in the large buffer to the small buffer, and swap the receive buffer pointer and the send buffer pointer, so that the receive buffer points to the small buffer and the send buffer points to the large buffer.
[0021] This application uses two FIFO (First In First Out) buffers, one large and one small, dynamically allocated according to the actual data volume at both the sending and receiving ends. When the received data volume is small, the smaller buffer is automatically used and the larger buffer is allocated to the sending end; conversely, when the received data volume is large, the smaller buffer is used. This design maximizes data throughput under limited memory conditions and avoids the waste of fixed buffers.
[0022] Before reading command data into the receive buffer, a specified source / destination channel is opened. A local data structure is created by allocating memory and initializing default values. Local data for all commands is initialized, and external registration of custom read / write callback functions (tsl_stream_t) is supported, enabling flexible data source access. By registering different stream callbacks, the same parser can seamlessly access various communication channels such as UART serial port data, NFC readers / writers, BLE GATT feature values, LoRaWAN downlink data, and 4G cellular network data without modifying the core parsing logic. Raw data is read from the stream callback into the receive buffer. The length of the received data is determined: if it is ≤256B, the data in the larger buffer is copied to the smaller buffer. The receive buffer pointer and transmit buffer pointer are swapped, and the command processing main loop is entered. The main loop contains four iterations. Within each iteration, tsl_req() is used to retrieve commands one by one and match them with the corresponding command parser.
[0023] This adaptive switching strategy is based on a core assumption: in a complete send-receive interaction, the amount of data received and sent will inevitably differ significantly. By dynamically allocating buffers, the data throughput of a single communication is maximized without increasing the total memory. When the send buffer is about to fill up, the system automatically triggers a partial send (flush) to free up space for continued writing, ensuring that the continuous transmission of extremely large amounts of data is not limited by the buffer size.
[0024] S102, retrieve command data one by one and match command parsers, and call the CHECK function in the matched command parser to perform a validity check on the command data.
[0025] Most IoT devices rely solely on simple password verification to protect command security. This mechanism has a significant flaw: attackers can intercept legitimate command messages by monitoring the wireless communication link and then repeatedly send those messages at any time, thereby gaining unauthorized control of the device (such as repeatedly executing dangerous operations like reboots or upgrades). While some anti-replay schemes exist in existing technologies (such as maintaining device whitelists and command ID lists), these schemes typically require substantial storage and computing resources, making them difficult to deploy on resource-constrained embedded devices.
[0026] Therefore, the aforementioned call to the CHECK function in the matched command parser performs a validity check on the command data. Specifically, this may include: calling the CHECK function in the matched command parser to check the format, length, and value range of the command data for validity. Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
[0027] Based on the command's data source, a decision is made as to whether password verification is required. If password verification is required, the initial state is error=TSL_ERROR_PASSWD; if password verification is not required, the initial state is error=TSL_ERROR_NONE. After successful password verification, the error flag is cleared, allowing subsequent commands with a higher priority than password verification (such as firmware upgrades or batch operations) to continue execution.
[0028] Each control command carries an incrementing sequence number. The parser maintains the previously received sequence number and compares it when a new command is received. This algorithm uses the wraparound property of unsigned integers to determine the order of the sequence numbers by comparing the difference with 128. This not only prevents replay but also correctly handles the case where the sequence number wraps back to 0 after 255.
[0029] The command parser moves the read pointer to the beginning of the receive buffer and checks if there is any data after the current read position (i.e., if there are any unprocessed commands). If there is no data, the current round ends directly. If there is data, the parser attempts to parse a complete command from the current position: first, it determines whether the command is a read or write operation; then, based on the first byte of the command code, it determines whether it belongs to the control command table, general command table, configuration command table, or status command table; in the corresponding command table, based on the complete content of the command code and the operation type, it precisely matches the parser of the command (which includes the command's processing function pointer). If the match fails (e.g., command code does not exist, operation type does not match, data length is insufficient), it immediately constructs a "command not found" error response, sends it to the requester, and terminates the entire parsing process (no second or subsequent rounds).
[0030] If a match is found, the command parser checks whether password verification is required for the current session. If password verification is required and the currently parsed command is not a password verification command, a password error is returned, and parsing terminates. If password verification is required and the current command is a password verification command, the command's processing function (the checking phase) is called to verify the password. Verification fails, and the process terminates.
[0031] If the command belongs to the control command table, the command parser will also perform a sequence number anti-replay check: extract the sequence number carried in the command data and compare it with the last successful sequence number stored in the device's internal storage; if the new sequence number is invalid (smaller than or the same as the old sequence number), a sequence number error is returned and parsing is terminated; if it is valid, the last sequence number stored in the internal storage is updated to the new sequence number.
[0032] After completing the above security checks, the parser calls the check phase processing function for the current command. This function is responsible for: checking whether the command data format is correct (e.g., whether the length matches the declaration); and checking whether the parameter range is valid (e.g., whether the set acquisition period is between 1 and 86400 seconds). If the check phase returns failure, the parser constructs the corresponding error response and sends it, then terminates the entire parsing process. If the check phase returns success, the parser moves the read pointer to the beginning of the next command and repeats the above steps until all commands in the buffer have been processed.
[0033] S103, if an error occurs, an error response is sent and parsing is terminated; otherwise, command data is retrieved one by one and matched with command parsers. The VALID function in the matched command parser is called to perform a validity check on the command data. The validity check includes correlation check and constraint check.
[0034] The command parser moves the read pointer back to the beginning of the receive buffer (starting from the beginning again) and checks if there are any unprocessed commands. If not, the current round ends. Like the previous round, the parser parses a command, finds the corresponding command parser (again, through first-byte location and table matching), and calls the validity check function for that command. This stage differs from the first round's check stage; it focuses on the interrelationships between commands, rather than the data format of a single command. For example, if the device receives two commands simultaneously: "Set the acquisition period to 60 seconds" and "Set the reporting interval to 30 seconds," the validity check will find that the acquisition period (60 seconds) is greater than the reporting interval (30 seconds), which violates the business logic (the acquisition period should be less than or equal to the reporting interval), and therefore determines it to be invalid. Or, if it receives two conflicting commands: "Enable low-power mode" and "Enable real-time data stream," the validity check will detect the contradiction and reject the command.
[0035] If a success is returned, the parser moves on to the next command and repeats the above steps until all commands have been processed.
[0036] S104. If an error occurs, an error response is sent and parsing is terminated. Otherwise, command data is retrieved one by one and matched with command parsers. The EXECUTE function in the matched command parser is called to perform actual read and write operations on the command data. After all commands in this round have been executed, response data is sent.
[0037] Specifically, this may include: if it is a read command, calling the EXECUTE function in the matched command parser to read parameters from the device and writing the result into the send buffer; If it is a write command, the EXECUTE function in the matched command parser is called to write the data to the device's temporary variable; Once all commands in this round have been executed, the response data will be sent out through the communication channel.
[0038] Error responses are constructed according to the following format: Fatal error (UNKNOWN / ORDER / PASSWD): Send a 2-byte response [0xEF, error<<4] without a command code; General error: Sending [0xEF,(error<<4)|cmd_len,command code...].
[0039] The command parser moves the read pointer back to the beginning of the receive buffer, checks for any unprocessed commands, and ends the current round if none are found; otherwise, it parses a command and locates the corresponding command parser. The parser then calls the execution phase processing function for that command. This phase performs the actual business operations: for read commands, it reads parameter values (e.g., serial number, current acquisition cycle) from the device's memory or hardware, and then writes the read data into the transmit buffer (organized according to the protocol format); for write commands, it writes the values carried in the command data into the device's temporary variables (note that this is not yet permanently saved to Flash; it only modifies runtime variables). For some action commands (such as reboot or factory reset), the execution phase records the actions to be performed, but also does not immediately execute irreversible operations.
[0040] If a success response is received, the parser moves on to the next command and repeats the above steps until all commands have been processed. Once the execution phase of all commands has been successfully completed, the parser will send all the accumulated response data in the send buffer to the requester all at once via the external communication interface.
[0041] After the third round, all read and write operations have been completed, and responses have been sent. However, the values modified by the write operations still exist only in temporary variables and have not been permanently saved; action commands (such as reboots) have not yet been actually executed. The advantage of this design is that if an error occurs in the fourth round, it can prevent the device from entering an inconsistent state.
[0042] S105: Search for command data line by line and match command parsers, then call the APPLY function in the matched command parser to make the operation take effect.
[0043] Specifically, this can include: writing data from a temporary variable into non-volatile memory; Trigger a callback notification or device restart.
[0044] The command parser moves the read pointer back to the beginning of the receive buffer and checks if there are any unprocessed commands. If not, the current round ends; otherwise, a command is parsed and the corresponding command parser is found.
[0045] The parser calls the command's activation phase processing function. This phase is responsible for: For write commands: The new value stored in the temporary variable is written to a non-volatile memory (such as Flash or EEPROM) to ensure that the configuration is not lost after the device is powered off.
[0046] For commands that require a reboot to take effect (such as changing network mode or completing firmware upgrades): trigger a device reboot after completing the necessary data writing. Note that it is usually ensured that the response has been sent before rebooting.
[0047] For commands that require callback notifications: call the externally registered callback function to inform other modules that the configuration has changed.
[0048] If the activation phase fails (e.g., write to Flash fails), the parser logs the error, but since the response has already been sent, it is usually not possible to notify the requester again. In this case, the device may take internal remedial measures (such as retrying the write or restoring the old value), but the parsing process will continue to process the remaining commands. The parser moves to the next command and repeats the above steps until all commands have been processed.
[0049] After the fourth round, all command modifications have taken permanent effect, and the device status has been updated. The entire main parsing loop is complete.
[0050] In the `tsl_parser_handler` function, the parser uses multiple loops to sequentially drive all commands through all stages: Round 1: Traverse all commands → Execute the CHECK phase; if an error is encountered, the process will be interrupted and subsequent commands will be skipped; Round 2: Traverse all commands → Execute the VALID phase; if an error is encountered, the process is interrupted and subsequent commands are skipped; Round 3: Traverse all commands → Execute EXECUTE phase; execute normally and generate response data; Round 4: Traverse all commands → Execute the APPLY phase; persist the execution results and trigger relevant callbacks.
[0051] The key value of this design lies in the fact that each command's processing function only needs to implement the stages it cares about; other stages are automatically skipped by the framework. For example, a "reboot device" command only needs to execute `system_reboot()` in the `APPLY` stage; other stages do not need to be implemented and will be automatically ignored by the framework.
[0052] Finally, tsl_parser_close() is called to reset all status variables, and handle(DESTROY) is called on each of the common[], config[], and status[] commands to release local data and release thread locks.
[0053] In one example, `tsl_parser_get()` can be called to initiate proactive reporting within the device, constructing command data into a request-response format and writing it into the receive buffer for direct scheduling and execution. `tsl_parser_put()` can be called to proactively send buffered response data within the device. `tsl_cmd_try()` / `tsl_ack_try()` are similar to memory allocation operations, obtaining space of a specified length from the receive / transmit buffer, returning the actual available length if insufficient; when the transmit buffer is full, partial transmission is automatically triggered.
[0054] The step of retrieving command data line by line and matching command parser includes: Step 1: Determine the operation type of the command data. Based on the first byte of the command code, determine the command table to which the command data belongs. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Step two: Within the determined command table, perform command matching according to the command code and operation type; Step 3: Obtain the corresponding command parser structure when a match is successful.
[0055] The operation type includes: TSL_OPERATE_READ (allows read operations), TSL_OPERATE_WRITE (allows write operations), and TSL_OPERATE_RDWR (allows both read and write operations). When searching for a command function, the parser matches the current operation type (read or write) with the command's permissions to prevent unauthorized operations.
[0056] This application provides a method for parsing object model commands, comprising: reading command data into a receiving buffer, wherein the receiving buffer initially points to a large buffer and the sending buffer initially points to a small buffer; if the length of the received data is less than or equal to the capacity of the small buffer, copying the received data from the large buffer to the small buffer, and swapping the pointers of the receiving buffer and the sending buffer, so that the receiving buffer points to the small buffer and the sending buffer points to the large buffer; retrieving command data line by line and matching it with a command parser, and calling the CHECK function in the matched command parser to perform a validity check on the command data; if an error occurs, sending an error response and terminating the parsing; otherwise, retrieving command data line by line and matching it with a command parser, and calling the VALID function in the matched command parser to perform a validity check on the command data. The validity check includes correlation verification and constraint verification. If an error occurs, an error response is sent and parsing is terminated. Otherwise, command data is retrieved line by line and matched with command parsers. The EXECUTE function in the matched command parser is called to perform actual read and write operations on the command data, and a response is sent after all commands in this round have been executed. Command data is then retrieved line by line and matched with command parsers, and the APPLY function in the matched command parser is called to make the operation effective. The process of retrieving command data line by line and matching command parsers includes: determining the operation type of the command data; determining the command table to which the command data belongs based on the first byte of the command code; the command table includes a control command table, a general command table, a configuration command table, and a status command table; within the determined command table, command matching is performed according to the command code and operation type; and when a match is successful, the corresponding command parser structure is obtained. The solution in this application can efficiently implement command parsing under limited resource constraints.
[0057] In one example, the method further includes: Four types of command tables are constructed based on command code, operation type, and processing function; the range of the control command table is 0xE0-0xFF, the range of the general command table is 0xB0-0xDF, the range of the configuration command table is 0x60-0xAF, and the range of the status command table is 0x00-0x5F.
[0058] Define a command parser structure (tsl_parser_t), which contains: parser_version: Protocol version number (4-byte string, such as "0106" representing v1.6). control / common / config / status: Pointers to four command resolution tables; control_size / common_size / config_size / status_size: The number of entries in each command table; order: Current command sequence number (to prevent replay); operate / operate_record: Current operation type and operation record (records all operation types throughout the entire parsing process bitwise); error: Current error status; source / dest: The source and destination of command data; fifo_max[] / fifo_min[]: Large buffer (default 4KB) and small buffer (default 256B); recv / send: A pointer to the currently used send / receive buffer; recv_len / send_len: The total length of data received / sent; recv_offset / send_offset: Current read / write offset position; recv_position / send_position: Current read / write reference position; cmd_read / ack_write: pointers to external read / write stream callback functions; lock / unlock: Thread-safe protection callbacks; During initialization, the configuration command table and status command table are passed in through external parameters, while the control command table and general command table are maintained internally by the module (and cannot be modified externally).
[0059] Each command entry (tsl_cmd_parser_t) contains the following fields: cmd[]: Command code (1-5 bytes, supports variable-length command codes); operate: Operation type (READ / WRITE / RDWR / BATCH); cmd_len: Command code length; data_len: The length of data during write operations; handle: A pointer to the command processing function, with the signature tsl_result_t (*handle)(parser, cmd_parser, method).
[0060] The default entries in the control command table (system-level control operations) include: index verification (0xFF), sequence verification (0xFE), new password verification, new password modification, old password verification, old password modification, firmware upgrade (0xEE), pre-configuration, history export, production test commands, request and response, batch operations, timestamp, debugging commands, etc.
[0061] The default entries in the general command table (general attributes) include: resolver version, custom name / PN (Production Number) / SN (Serial Number), device serial number, firmware version (0xDA), OEM (Original Equipment Manufacturer) identifier, region information, product information, module version, LoRaWAN configuration, cellular network configuration, random key, device status, time zone (0xC7), daylight saving time, history configuration (0xC5), automatic power-on configuration, as well as server downlink service commands (reset / reboot / history clear / history query / device query / time synchronization / reconnect) and uplink status commands (LoRaWAN status / cellular status / time status / battery status / Bluetooth event / Bluetooth service).
[0062] The configuration command table (application layer configurable attributes) includes the following preset items (defined by specific products): collection period, reporting interval, threshold, etc.
[0063] The status command table (uplink status reporting) includes the following preset entries (defined by the specific product): sensor values, battery level, signal strength, etc.
[0064] After the parser structure is initialized and the command parsing table is defined, the parser startup and lifecycle initialization are executed. tsl_parser_open(source,dest) performs the following operations: clears all buffers; resets the states of operate, error, offset, position, etc.; sets source and dest (identifying the data source and destination of this communication); sets recv to initially point to the large buffer (fifo_max) and send to initially point to the small buffer (fifo_min); calls handle(CREATE) on common[], config[], and status[] commands one by one to complete local data initialization; and determines whether password verification is required based on the source type (UART / NFC / BLE / WiFi sources require verification, LoRaWAN / PRECONFIG / INTERNAL sources do not require verification).
[0065] Currently, when it's necessary to read or write all configuration parameters of a device in batches, existing solutions require the requester to send commands one by one, and the device to respond one by one. For example, reading 50 configuration items requires 50 downlink requests and 50 uplink responses, totaling 100 over-the-air interactions. In low-power wide-area network (LPWAN) scenarios (such as LoRaWAN and NB-IoT), frequent uplink and downlink communications significantly increase device power consumption, consume a large amount of channel resources, and prolong the total latency. For some battery-powered IoT devices deployed in remote areas, this one-by-one interaction method severely shortens the device's lifespan.
[0066] In one example, the method further includes: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
[0067] When a batch read command (BATCH+READ) is received, the parser enters batch mode: 1. Save the current recv_offset position; 2. Set operate to TSL_OPERATE_BATCH; 3. Traverse the common[] command table: Replace the position of the previous command with the current command code, and call handle(EXECUTE) to execute the reading; 4. Traverse the config[] command table: Replace the position of the previous command with the current command code, and call handle(EXECUTE) to execute the reading; 5. Traverse the status[] command table: Replace the position of the previous command with the current command code, and call handle(EXECUTE) to execute the reading; 6. Restore recv_offset and recv_len.
[0068] By reusing the execution channel of a single command, the read results of all configuration / status commands are sequentially written to the sending buffer and responded to the requester all at once. This method compresses N interactions of "request-response" into a single interaction, which can significantly save communication time and power consumption in low-power scenarios such as LoRaWAN.
[0069] For the BATCH WRITE command, the process includes the following: 1. Receive Command: The device receives a BATCH command with command code 0xEE and operation type WRITE. The command's data area contains multiple key-value pairs of "command code + value to be written".
[0070] 2. Save the current state (same as batch read).
[0071] 3. Parse the data area: Parse each command code to be written and its corresponding value from the data area in sequence.
[0072] 4. Write command sequentially: For each command to be written, the parser finds the corresponding command parser as if handling a regular write command; it calls the execution phase (EXECUTE) of the command and writes the value to the device's temporary variable (not immediately saved to Flash). If any write operation fails (e.g., command code does not exist, value is out of range), the batch operation is immediately terminated, an error response is returned, and the subsequent activation phase is not executed (to prevent partial success).
[0073] 5. Apply Phase: If all writes are successful, the parser will call the apply phase for all modified commands to permanently save the values of temporary variables to Flash.
[0074] 6. Restore context and send response: Restore the receive buffer and then return a "bulk write successful" response or a response containing the results of each command execution.
[0075] The complete application of the lifecycle model is demonstrated using the firmware upgrade command (UPGRADE) as an example: CHECK phase: cmd=WRITE_START: Verify the starting parameters of the firmware package (type, size, CRC, etc.) and reply with the maximum acceptable single packet size; cmd=WRITE_DATA: Verify the consistency between the data packet length and the declared length, and write the data to the temporary storage area; cmd=WRITE_END: Perform firmware package integrity verification; cmd=WRITE_CONTINUE: Verify the data for resuming transmission after differential upgrade; APPLY stage: cmd=WRITE_START: Confirm to begin preparations for the upgrade; cmd=WRITE_DATA: Writes the temporarily stored data to Flash; cmd=WRITE_END: Triggers a device reboot to apply the new firmware after writing is complete; cmd=WRITE_CONTINUE: Complete the write operation for differential upgrade; If all checks pass, the application phase begins; if any check fails, the process terminates immediately and the application phase is not executed.
[0076] This design, which separates verification and execution, ensures that irreversible Flash write operations are only performed after the data integrity verification is passed, thus guaranteeing the security of the upgrade process.
[0077] See Figure 2 The diagram below shows the system architecture of this application. The command parsing system includes external data sources (UART, NFC, BLE, WIFI, LoRaWAN, 4G / Cell, PowerBus), a parser core (fifo_max, fifo_min, source / dest, order / error, operate), a four-level command table registry center (control command table, general command table, configuration command table, status command table), command entries (command code, operation type, command code length, data length, processing function), a six-level processing method scheduler (CREATE initialization, CHECK validity, VALID validity, EXECUTE execution, APPLY activation, DESTROY destruction), and a security control module (serial number anti-replay, hierarchical password verification, operation type control).
[0078] This application introduces a six-stage command processing method (CREATE→CHECK→VALID→EXECUTE→APPLY→DESTROY) of "Creation-Verification-Validity Check-Execution-Effectiveness-Destruction," decoupling the command processing into multiple independent stages. Each command only needs to implement the processing function for its corresponding stage. The parsing framework uniformly schedules each stage, resulting in a clear code structure that is easy to extend and maintain. Commands are divided into four levels: control commands (0xE0-0xFF), general commands (0xB0-0xDF), configuration commands (0x60-0xAF), and status commands (0x00-0x5F). The corresponding command table is directly located based on the numerical range of the command code, and then a precise match is performed within the table. Compared to a full table traversal, this significantly reduces the time overhead of command lookup and achieves hierarchical security control: control commands can be subject to password and sequence number verification, while configuration / status commands do not require these overheads. A multi-dimensional security protection system is provided: (a) Sequence number anti-replay mechanism: Each control command carries an incrementing sequence number. The parser records the previous sequence number and rejects commands with backdated or duplicated sequence numbers, effectively preventing replay attacks. (b) Hierarchical password policy: Based on the command source (UART local / NFC / BLE / WiFi, etc. require password verification, while internal sources such as LoRaWAN / pre-configuration do not), it automatically determines whether to perform password verification. (c) Source and destination recording: Records the data source and access purpose of each command, providing a basis for auditing and security traceability. Two FIFO buffers, one large and one small, are used and dynamically allocated according to the actual data volume at both ends. When the received data volume is small, the small buffer is automatically used and the large buffer is allocated to the sending end; when the received data volume is large, the opposite is true. This design maximizes data throughput under limited memory conditions and avoids the waste of fixed buffers. It supports the BATCH command to trigger the execution of all configuration / status commands with one click, scheduling and executing all commands one by one and merging the results into a response. Only one uplink and downlink interaction is needed to complete the reading or writing of the full device configuration, greatly reducing the number of communications, which is particularly suitable for low-power and low-bandwidth scenarios.
[0079] In summary, this application has the following beneficial effects: Decoupling and scalability: The six-stage lifecycle model highly decouples command processing logic. Adding a new command only requires implementing the processing function of the relevant stage and registering it in the corresponding command table, without modifying the framework code.
[0080] Security: Multi-dimensional security controls (serial number anti-replay + hierarchical password + source control + operation permissions) provide defense in depth, effectively preventing replay attacks and unauthorized access.
[0081] Memory efficiency: The adaptive double buffer mechanism maximizes data throughput with limited memory resources and supports communication scenarios involving mixed large and small data.
[0082] Low power consumption friendly: The batch operation mechanism compresses N communication interactions into 1, significantly reducing device power consumption and communication costs in low power wide area network scenarios such as LoRaWAN.
[0083] High compatibility: Through the stream callback (tsl_stream_t) abstraction layer, it supports transparent access to multiple communication channels such as UART, NFC, BLE, WiFi, LoRaWAN, and 4G cellular networks without modifying the core parsing logic.
[0084] Performance optimization: The four-level command range matching mechanism reduces command lookup time from O(N) to O(M) (where M is the number of entries in a single command table). In practical applications, the control command table contains approximately 14 entries and the general command table contains approximately 35 entries, resulting in a significant reduction in lookup time.
[0085] Secondly, embodiments of this application provide a device for parsing object model commands, comprising: The reading module is used to read command data into the receiving buffer, which initially points to a large buffer and the sending buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, the received data in the large buffer is copied to the small buffer, and the pointers of the receiving buffer and the sending buffer are swapped, so that the receiving buffer points to the small buffer and the sending buffer points to the large buffer. The legality check module is used to retrieve command data one by one and match it with the command parser, and call the CHECK function in the matched command parser to perform legality checks on the command data; The validity verification module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, and calls the VALID function in the matched command parser to perform validity verification on the command data. The validity verification includes correlation verification and constraint verification. The execution module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, calls the EXECUTE function in the matched command parser to perform actual read and write operations on the command data, and sends response data after all commands in this round have been executed. The activation module is used to retrieve command data one by one and match command parsers, and call the APPLY function in the matched command parser to make the operation take effect; The step of retrieving command data line by line and matching command parser includes: Determine the operation type of the command data, and determine the command table to which the command data belongs based on the first byte of the command code. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Within the defined command list, commands are matched according to the command code and operation type. When a match is successful, the corresponding command parser structure is obtained.
[0086] In one possible implementation, the legality checking module is specifically used for: The CHECK function in the matched command parser is invoked to perform a validity check on the format, length, and value range of the command data; Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
[0087] In one possible implementation, the apparatus further includes a batch reading module for: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
[0088] Thirdly, embodiments of this application provide a computer-readable storage medium storing a computer program, which, when executed by a processor, implements any of the above-described object model command parsing methods.
[0089] In the above embodiments, implementation can be achieved entirely or partially through software, hardware, firmware, or any combination thereof. When implemented using software, it can be implemented entirely or partially as a computer program product. The computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, all or part of the processes or functions described in the embodiments of this application are generated. The computer can be a general-purpose computer, a special-purpose computer, a computer network, or other programmable device. The computer instructions can be stored in a computer-readable storage medium or transmitted from one computer-readable storage medium to another. For example, the computer instructions can be transmitted from one website, computer, server, or data center to another website, computer, server, or data center via wired (e.g., coaxial cable, fiber optic, digital subscriber line (DSL)) or wireless (e.g., infrared, wireless, microwave, etc.) means. The computer-readable storage medium can be any available medium that a computer can access or a data storage device such as a server or data center that integrates one or more available media. The available medium can be a magnetic medium (e.g., floppy disk, hard disk, magnetic tape), an optical medium (e.g., DVD), or a semiconductor medium (e.g., solid state disk (SSD)).
[0090] It should be noted that, in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes said element.
[0091] The various embodiments in this specification are described in a related manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. In particular, the device embodiments are described simply because they are similar to the method embodiments; relevant parts can be referred to the descriptions of the method embodiments.
[0092] Although embodiments of the present invention have been shown and described above, it is understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Those skilled in the art can make changes to the above embodiments within the scope of the present invention without departing from the principles and spirit of the present invention.
Claims
1. A method for parsing object model commands, characterized in that, include: Command data is read into the receive buffer, which initially points to a large buffer, and the send buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, the received data in the large buffer is copied to the small buffer, and the receive buffer pointer and the send buffer pointer are swapped, so that the receive buffer points to the small buffer and the send buffer points to the large buffer. Search for each command data item and match it with the command parser. Then, call the CHECK function in the matched command parser to perform a validity check on the command data. If an error occurs, an error response is sent and parsing is terminated; otherwise, command data is retrieved one by one and matched with command parsers. The VALID function in the matched command parser is called to perform a validity check on the command data. The validity check includes correlation check and constraint check. If an error occurs, an error response is sent and parsing is terminated; otherwise, command data is retrieved one by one and matched with command parsers. The EXECUTE function in the matched command parser is called to perform actual read and write operations on the command data, and response data is sent after all commands in this round have been executed. Search for each command data item and match it with the command parser. Then, call the APPLY function in the matched command parser to make the operation take effect. The step of retrieving command data line by line and matching command parser includes: Determine the operation type of the command data, and determine the command table to which the command data belongs based on the first byte of the command code. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Within the defined command list, commands are matched according to the command code and operation type. When a match is successful, the corresponding command parser structure is obtained.
2. The method according to claim 1, characterized in that, The method further includes: Four types of command tables are constructed based on command code, operation type, and processing function; the range of the control command table is 0xE0-0xFF, the range of the general command table is 0xB0-0xDF, the range of the configuration command table is 0x60-0xAF, and the range of the status command table is 0x00-0x5F.
3. The method according to claim 1, characterized in that, The call to the CHECK function in the matched command parser performs a validity check on the command data, including: The CHECK function in the matched command parser is invoked to perform a validity check on the format, length, and value range of the command data; Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
4. The method according to claim 1, characterized in that, The call to the EXECUTE function in the matched command parser performs actual read and write operations on the command data, and sends response data after all commands in this round have been executed, including: If it is a read command, the EXECUTE function in the matched command parser is called to read the parameters from the device and write the result to the send buffer; If it is a write command, the EXECUTE function in the matched command parser is called to write the data to the device's temporary variable; Once all commands in this round have been executed, the response data will be sent out through the communication channel.
5. The method according to claim 4, characterized in that, The process of invoking the APPLY function in the matched command parser to make the operation take effect includes: Write the data in the temporary variable to non-volatile memory; Trigger a callback notification or device restart.
6. The method according to claim 1, characterized in that, The method further includes: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
7. A device for parsing object model commands, characterized in that, include: The reading module is used to read command data into the receiving buffer, which initially points to a large buffer and the sending buffer initially points to a small buffer. If the length of the received data is less than or equal to the capacity of the small buffer, the received data in the large buffer is copied to the small buffer, and the pointers of the receiving buffer and the sending buffer are swapped, so that the receiving buffer points to the small buffer and the sending buffer points to the large buffer. The legality check module is used to retrieve command data one by one and match it with the command parser, and call the CHECK function in the matched command parser to perform legality checks on the command data; The validity verification module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, and calls the VALID function in the matched command parser to perform validity verification on the command data. The validity verification includes correlation verification and constraint verification. The execution module is used to send an error response and terminate parsing if an error occurs; otherwise, it retrieves command data one by one and matches it with the command parser, calls the EXECUTE function in the matched command parser to perform actual read and write operations on the command data, and sends response data after all commands in this round have been executed. The activation module is used to retrieve command data one by one and match command parsers, and call the APPLY function in the matched command parser to make the operation take effect; The step of retrieving command data line by line and matching command parser includes: Determine the operation type of the command data, and determine the command table to which the command data belongs based on the first byte of the command code. The command table includes a control command table, a general command table, a configuration command table, and a status command table. Within the defined command list, commands are matched according to the command code and operation type. When a match is successful, the corresponding command parser structure is obtained.
8. The apparatus according to claim 7, characterized in that, The legality check module is specifically used for: The CHECK function in the matched command parser is invoked to perform a validity check on the format, length, and value range of the command data; Determine whether password verification is required based on the data source, and perform password verification for command data that requires password verification; For control commands, a sequence number anti-replay mechanism is used for verification. The anti-replay mechanism includes verifying if the current command sequence number or the previous command sequence number is 0; otherwise, calculating the difference between the current command sequence number and the previous command sequence number, and verifying if the difference is not 0 and is less than 128.
9. The apparatus according to claim 7, characterized in that, The device also includes a batch reading module for: If a batch read command is received, save the current read position and data length in the receive buffer; Each command in the general command table, configuration command table, and status command table is traversed sequentially. The command code that originally stored the batch read command in the receiving buffer is replaced with the command code of the currently traversed command, and the command length indicator field in the receiving buffer is adjusted accordingly. For each command, match the corresponding command parser and call its EXECUTE function to perform a read operation on the command, and write the result to the send buffer; After completing the traversal of the general command table, configuration command table, and status command table, restore the previously saved read position and data length of the receive buffer; The data in the send buffer is sent to the requester.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the method described in any one of claims 1-6.