User-defined network terminal communication protocol system and method
By customizing the network terminal communication protocol system and method, the problems of high concurrency, low latency, and complex asynchronous communication in the Internet of Things (IoT) are solved, achieving efficient and reliable terminal communication, improving the system's flexibility and stability, and making it suitable for various communication scenarios in industrial IoT platforms.
Patent Information
- Application Number
- CN202511192826.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-08-25
- Publication Date
- 2025-11-14
AI Technical Summary
Traditional TCP protocol stacks cannot meet the high concurrency, low latency, and asynchronous event-driven requirements of the Internet of Things (IoT). General protocols cannot meet the data organization and command issuance needs of specific hardware devices. Multi-frame data transmission suffers from high frame loss rates and assembly errors. Device login verification methods are simplistic. Synchronization logic in asynchronous communication is complex and carries the risk of deadlock. Traditional control methods cannot meet the requirements of modern industrial IoT systems for task scheduling flexibility and stability.
It adopts a custom network terminal communication protocol system and method, including encoders and decoders, supporting full-duplex, high concurrency, low latency, multi-frame data transmission, error checking and retransmission mechanisms, multi-device login mechanisms, asynchronous response synchronization, efficient communication through the Netty framework, and a synchronous communication mechanism combining multi-mode login methods and asynchronous result processing objects. It also features task binding channel lifecycle management, dynamic selection of I/O models and adaptive thread pool configuration, and optimized TCP parameters to improve system performance.
It enables efficient and reliable communication between the IoT platform and hardware terminals, reduces latency and frame loss rate, enhances system flexibility and scalability, simplifies asynchronous communication logic, improves system stability and task scheduling security, and adapts to different network conditions and load pressures.
Smart Images

Figure CN120956767A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of Internet of Things (IoT) communication technology, and in particular to a custom network terminal communication protocol system and method. Background Technology
[0002] With the rapid development of IoT technology, the data transmission requirements between hardware devices and platforms are becoming increasingly complex. The interaction between network front-end modules (platforms) and a large number of network terminals often faces many problems: (1) The traditional TCP protocol stack cannot meet the requirements of high concurrency, low latency and asynchronous event-driven operation in the Internet of Things.
[0003] (2) The general protocol cannot meet the data organization, command issuance, status reporting and other requirements of specific hardware devices.
[0004] (3) Existing solutions have problems such as high frame loss rate and assembly error when transmitting multi-frame data at the terminal. (4) Difficulty in processing multi-frame data: For large data such as power waveform data and firmware upgrade files, there is a lack of effective frame sequence number management, cache reorganization and integrity verification mechanisms.
[0005] (5) Single device login verification method: lacks a flexible identity authentication mechanism and cannot adapt to the security requirements of different deployment environments.
[0006] (6) Synchronization logic is complex in asynchronous communication: HTTP requests obtain information from terminal devices in real time. Due to cross-thread and asynchronous responses, the mechanism for converting asynchronous to synchronous communication is complex, which may lead to deadlock risk, uncontrollable timeouts, and poor maintainability. The logic is complex and prone to errors when implementing periodic and delayed tasks.
[0007] Traditional manual control methods based on time difference comparison can no longer meet the requirements of modern industrial IoT systems for task scheduling flexibility and stability, thus limiting the system's scalability and maintainability. Summary of the Invention
[0008] To address the aforementioned problems, this invention proposes a custom network terminal communication protocol system and method, which features full-duplex operation, high concurrency, low latency, multi-frame data transmission, error checking and retransmission mechanisms, multi-device login mechanisms, asynchronous response synchronization, and flexible setting of periodic and delayed tasks. It is suitable for efficient communication between IoT platforms and hardware terminals.
[0009] To achieve the above objectives, the present invention adopts the following technical solution: Firstly, a custom network terminal communication protocol system is proposed, including a platform and a terminal; The platform includes encoders and decoders; The encoder is used to serialize message data objects into data frames that conform to the downlink protocol, which are then sent to the terminal as downlink messages. The decoder is used to receive uplink information sent by the terminal via the uplink protocol, and to verify the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.
[0010] Furthermore, the downlink protocol structure includes a start character, version number, total protocol frame length, function code, function code type, terminal number, number of terminals, pre-delay time, information time, post-delay time, data content, and CRC checksum. The uplink protocol structure includes a start character, version number, total protocol frame length, function code, terminal number, data content, and CRC checksum.
[0011] Furthermore, the decoder performs the following process to verify the length and integrity of the data frame: Determine the starting character of the frame; Determine the start position of the frame based on the start character; Retrieve data of the same length as all protocol frames in the data frame, starting from the beginning of the frame, and calculate the CRC checksum of the data. Compare the calculated CRC checksum with the CRC checksum in the data frame; If both are the same, it indicates that the integrity verification of the data frame has passed.
[0012] Furthermore, the decoder determines the length of the data frame based on the version number in the data frame.
[0013] Furthermore, the encoder is used to set a frame sequence number for each data frame and add the frame sequence number to the data frame before sending it to the terminal.
[0014] Furthermore, the platform employs multiple login modes, including login based on IP address and login based on host number.
[0015] Furthermore, the process by which the encoder encodes the data into data frames conforming to the downlink protocol includes: Determine the data-related content required for the protocol structure, excluding the CRC checksum; Write all data-related content, except for the CRC checksum, into the buffer sequentially; Determine the CRC checksum of the content written in the buffer; Write the CRC checksum into the buffer to form a data frame that conforms to the protocol; Write data frames that conform to the protocol to the output buffer.
[0016] Furthermore, the platform is also used to create various types of tasks and manage all tasks through a unified scheduling interface.
[0017] Furthermore, the platform also uses a task-bound channel lifecycle approach, registering a listener to the asynchronous callback object when the channel is closed when each task is created, and automatically canceling the relevant task when the connection is broken.
[0018] Secondly, a custom network terminal communication protocol method is proposed, including: The encoder serializes the message data object into a data frame conforming to the downlink protocol, which is then sent to the terminal as a downlink message. The decoder receives uplink information sent by the terminal through the uplink protocol, and verifies the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.
[0019] Compared with the prior art, the beneficial effects of the present invention are as follows: This invention proposes a custom network terminal communication protocol system and method. The system includes a platform and a terminal. The platform implements a custom network terminal communication protocol based on the Netty framework. The platform includes an encoder and a decoder. The encoder serializes message data objects into data frames conforming to the downlink protocol, which are then sent to the terminal as downlink messages. The decoder receives uplink information from the terminal and verifies the length and integrity of the received uplink messages to determine the data content of the verified uplink messages. It features full-duplex operation and error checking, ensuring efficient and accurate communication between the terminal and the platform.
[0020] Advantages of additional aspects of the invention will be set forth in part in the description which follows, and in part will be obvious from the description, or may be learned by practice of the invention. Attached Figure Description
[0021] The accompanying drawings, which form part of this application, are used to provide a further understanding of this application. The illustrative embodiments of this application and their descriptions are used to explain this application and do not constitute an undue limitation of this application.
[0022] Figure 1 This is a flowchart of a custom network terminal communication protocol disclosed in an embodiment. Detailed Implementation
[0023] The present invention will be further described below with reference to the accompanying drawings and embodiments.
[0024] It should be noted that the following detailed descriptions are illustrative and intended to provide further explanation of this application. Unless otherwise specified, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application pertains.
[0025] Where there is no conflict, the embodiments and features in the embodiments of the present invention can be combined with each other.
[0026] Example 1 In this embodiment, a custom network terminal communication protocol system is disclosed, such as... Figure 1 As shown, it includes the platform and the terminal; The platform includes encoders and decoders; The encoder is used to serialize message data objects into data frames that conform to the downlink protocol, which are then sent to the terminal as downlink messages. The decoder is used to receive uplink information sent by the terminal via the uplink protocol, and to verify the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.
[0027] In this embodiment, the platform refers to the network front-end program, which only interacts with hardware device terminals and is part of the Internet of Things (IoT). The platform and the terminal communicate through a network terminal protocol, which includes downlink and uplink protocols. The encoder in the platform sends message data to the terminal through the downlink protocol, and the decoder in the platform decodes the data sent by the terminal through the uplink protocol. This embodiment also defines a complete uplink and downlink protocol structure, supporting multiple frame length representation methods based on the version number (VERSION field) to ensure protocol compatibility and scalability. The reasons for the differences between uplink and downlink functions are as follows: The downlink protocol structure includes a start character, version number, total protocol frame length, function code, function code type, terminal number, number of terminals, pre-delay time, message time, post-delay time, data content, and CRC checksum. The uplink protocol structure includes a start character, version number, total protocol frame length, function code, terminal number, data content, and CRC checksum.
[0028] The uplink protocol structure is shown in the table below.
[0029] The downlink protocol structure is shown in the table below:
[0030] According to the protocol definition, this embodiment creates a custom encoder and decoder. During the data interaction between the platform and the terminal, the encoder and decoder perform serialization and deserialization operations on messages, supporting the processing of incomplete packets and packet merging.
[0031] The system features a complete set of function codes, with each operation having a one-to-one correspondence between uplink and downlink commands. The request content can be determined based on the downlink function code, and specific processing can be carried out based on the data content. The corresponding uplink function code is then used to report the data to the platform.
[0032] Data error verification and retransmission mechanism: Each frame of data is verified based on a custom CRC16 verification algorithm. Once a data error is detected, it is logged and the data is discarded.
[0033] Big Data Multi-Frame Sequential Transmission Mechanism: For big data transmission scenarios such as waveform recording in power equipment, this mechanism enables the sequential transmission of data across multiple frames. During waveform recording or synchronous timed acquisition, the platform can initiate a waveform retrieval process via a waveform recording request command, retrieving data frame by frame sequentially. The host responds accordingly frame by frame, and the platform caches each frame. If a retrieved frame does not return within a timeout period, the retrieval process can be restarted. Finally, upon receiving a waveform recording completion command, all cached data is reported to the terminal at once, such as the real-time application service platform terminal, ensuring data integrity and business continuity. The terminal firmware upgrade process is similar. During the upgrade, the total number of frames used is calculated, and frames are sent to the terminal device one by one. The system ensures that each frame receives a successful response from the terminal before sending the next frame; if no response is received, the upgrade frame can be resent.
[0034] The decoder verifies the length and integrity of the data frame as follows: Determine the starting character of the frame; Determine the start position of the frame based on the start character; Retrieve data of the same length as all protocol frames in the data frame, starting from the beginning of the frame, and calculate the CRC checksum of the data. Compare the calculated CRC checksum with the CRC checksum in the data frame; If both are the same, it indicates that the integrity verification of the data frame has passed.
[0035] Optionally, the decoder determines the length of the data frame based on the version number in the data frame.
[0036] The decoder receives uplink information from the terminal via the uplink protocol and decodes the received uplink information. (11) Find the starting character First, the start character (0x7E) is found in the input buffer to determine the start position of a data frame.
[0037] (12) Determine the version number and parse the frame length. Based on the first byte (VERSION) after the found start character, determine whether the data type of the LEN field is BYTE or WORD, and read the value of the LEN field accordingly to determine the data frame length.
[0038] (13) Verify the frame length and read the complete frame. Once the value of LEN is known, it can be verified whether the remaining data is long enough to contain the entire frame. If the data is insufficient, wait for more data to arrive; otherwise, read the complete data frame content.
[0039] (14) CRC16 check The last two bytes are the CRC16 checksum, used to verify the integrity of the data frame. We need to calculate the CRC16 value of the frame content (excluding the CRC16 itself) and compare it with the CRC16 value at the end of the frame. If they match, the frame is considered valid.
[0040] (15) Based on the above, a complete and valid frame is obtained. The data content is read according to the length of each field of the protocol. The custom message model is encapsulated. The encapsulated message entity class object is added to the ChannelPipeline of Netty (Netty is a high-performance, asynchronous event-driven network application framework). It is captured by the downstream processor and processed for business logic.
[0041] For example, when receiving a terminal search response command [7e 01 18 83 01 00 00 01 6e e7 05 0e 0000 05 01 22 b8 07 e8 0a 0a ea f4], after being parsed by the decoder, the entire frame data is read according to the total frame length, and then set into a custom message entity according to the protocol definition. / / Read the entire frame stream data ByteBuf fullFrame = in.readBytes(lengthField); try { / / Convert the complete frame data into a custom message model TermReceiveMessage receiveMessage = TermReceiveMessageParse.parseReceivedMessages(fullFrame); if (receiveMessage != null) { / / Send to downstream processors for business logic processing.
[0042] out.add(receiveMessage); } finally { ReferenceCountUtil.safeRelease(fullFrame); } Uplink custom message model content: public class TermReceiveMessage implements Serializable,AutoCloseable { private static final long serialVersionUID = 1L; / ** Start character Byte * / private static final byte soi = (byte) 0x7E; / ** Host protocol version 0x01-0xFF ** / private int version; / ** Total protocol frame length (including CRC) * / private int len = 0; / ** Function code command word Byte * / private int cid = 0; / **Terminal ID* / private int cno; / **Data content* / private ByteBuf data; / ** CRC16 checksum, the result of checking all content preceding this field (Word) * / private int crc; } The final parsed content is as follows: TermReceiveMessage{ Start character = 0x7e Version=1 Named by 83: TDM terminal search results Length = 24 Terminal number = 1 Data = 00 00 01 6e e7 05 0e 00 00 05 01 22 b8 07 e8 0a 0a CRC=0xeaf4 } import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; / ** * A pipeline of processors used to initialize the Netty server-side channel.
[0043] Whenever a new client connection is established, Netty calls the initChannel method to set up the processing flow for that connection.
[0044] / public class TermProtocolServerInitializer extends ChannelInitializer <socketchannel>{ / ** * Initialize the Channel's Pipeline and add various Handlers to process network data and business logic.
[0045] * * @param socketChannel A newly created SocketChannel representing a connection to the client. * @throws Exception Exceptions may be thrown during initialization. / @Override protected void initChannel(SocketChannel socketChannel) throwsException { / / Get the ChannelPipeline corresponding to the current Channel ChannelPipeline pipeline = socketChannel.pipeline(); / / The decoder decodes the binary byte stream (ByteBuf) read from the network into a message object of a custom protocol (such as TermReceiveMessage). / / Inbound direction: Decode data received from the client. pipeline.addLast(new TermProtocolMessageDecoder()); / / The encoder encodes the message object to be sent (TermSendMessage) into binary format (ByteBuf) for transmission over the network. / / Outbound direction: Encode data when sending it to the client pipeline.addLast(new TermProtocolMessageEncoder()); / / The [Business Processor] is responsible for handling specific business logic, such as parsing requests, executing commands, and returning results. / / It receives inbound messages after decoding and processes outbound messages before encoding. pipeline.addLast(new TermProtocolServerHandler()); } } Use design patterns to process the specific messages received: The business logic layer calls different commands through a unified interface. / / Obtain the processor for this function based on the function code, and perform parsing processing. ITermCommand command = termCommandFactory.getTermCommand(receiveMessage.getCid()); command.parse(ctx.channel(), receiveMessage, myComb); 1. Command Pattern public interface ITermCommand { void parse(Channel channel, TermReceiveMessage termReceiveMessage,MyComb myComb); } Each specific command handler (such as ...) is an implementation of the ITermCommand interface. Each command object encapsulates the processing logic for a specific CID (function code). 2. Factory Pattern TermCommandFactory, as the factory for command objects, maintains a mapping table between function codes and command objects. public class TermCommandFactory { private Map<TermProtocolCidEnum, ITermCommand> commandMap; @PostConstructpublic void init() { / / TDM terminal search results (0x83) commandMap.put(TermProtocolCidEnum. CMD_TDM_ SRH_RESP , termSearchHandler); } public ITermCommand getTermCommand(int cid) { TermProtocolCidEnum cidEnum = TermProtocolCidEnum.getEnumByCode(cid); return commandMap.get(cidEnum); } } (16) The downstream processor develops a specific functional processor by using the combination of the factory and command patterns in the design pattern according to the function code.
[0046] The process by which the encoder encodes data into data frames conforming to the downlink protocol includes: Determine the data-related content required for the protocol structure, excluding the CRC checksum; Write all data-related content, except for the CRC checksum, into the buffer sequentially; Determine the CRC checksum of the content written in the buffer; Write the CRC checksum into the buffer to form a data frame that conforms to the protocol; Write data frames that conform to the protocol to the output buffer.
[0047] The downlink protocol encoder is responsible for serializing the command message object constructed on the platform side into binary data frames that conform to the hardware terminal communication protocol specifications, and sending them to the target terminal through Netty's data channel.
[0048] This encoder is implemented based on the MessageToByteEncoder (Message Object to Byte Encoder) abstract class provided by the Netty framework. It can convert the TermsendMessage message entity class, which is encapsulated by the upper-layer business logic, into a protocol frame byte stream with a fixed structure, ensuring that the communication format between the encoder and the terminal is consistent.
[0049] The encoder's data frame encoding process includes the following steps: (21) Receive the message object TermsendMessage class from the upper layer, which contains fields such as protocol version number, function code, terminal number, and data content; (22) Dynamically determine the data type (BYTE or WORD) of the frame length field (LEN) based on the protocol version number, and calculate the total length of the entire protocol frame; (23) Write the following fields into the buffer in sequence: Start character (SOI), Version number (VERSION), Frame length (LEN), Function code (CID), Function code type (cidType), Terminal number (CNO), Number of terminals (Count), Delay parameter, Data content (DATA); (24) Use the CRC16 algorithm to perform integrity verification on the content of the current frame, and append the verification result as the last two bytes to the end of the frame; (25) Write the completed protocol frame into the Netty output buffer for asynchronous transmission by subsequent network modules.
[0050] In order to improve the system's concurrent processing capability and response speed, this embodiment of the invention adopts the following specific measures: (31) Dynamically select I / O model Depending on the operating system's support, this invention determines whether to enable the Linux-specific Epoll I / O model by checking the `Epoll.isAvailable` (event polling availability) method. Compared to the traditional NIO model (non-blocking I / O model), Epoll exhibits better performance when handling a large number of concurrent connections. Once the Epoll model is determined, `EpollEventLoopGroup` (Epoll event loop group) and `EpollServerSocketChannel` (Epoll server socket channel) are selected accordingly, and edge-triggered mode is configured to further improve the efficiency of I / O operations. The relevant code is as follows: / ** * Check if the operating system supports the Epoll event polling model.
[0051] If the operating system is Linux and supports Epoll, it returns true.
[0052] Otherwise, return false, indicating that Epoll is not supported.
[0053] * * @return boolean Returns true if Epoll is available, otherwise returns false.
[0054] / private boolean useNative() { / / Check if Epoll event polling model is supported return Epoll.isAvailable(); } / ** * Initialize the Channel type, determining which type of server channel to use based on whether Epoll is supported.
[0055] * If Epoll is supported, use the Epoll server socket channel; otherwise, use the traditional NIO server socket channel.
[0056] / private void initChannelType() { / / The choice of ServerSocketChannel depends on whether the operating system supports Epoll. this.channelType = this.useNative() ?EpollServerSocketChannel.class :NioServerSocketChannel.class; } (32) Adaptive thread pool configuration During the initialization phase, this invention obtains the number of CPU cores on the current machine by acquiring the number of available processors at runtime, and sets the size of the worker thread group to 2 * the number of CPU cores (no more than 64 threads). This method ensures that the system can fully utilize physical resources while avoiding the context switching overhead caused by too many threads. An example is shown below: / ** * Create worker thread groups * Used to handle network I / O events, such as read and write operations.
[0057] / private EventLoopGroup buildWorkerEventLoopGroup() { / / Calculate the number of worker threads: take the smaller value between twice the number of CPU cores and 64. / / To avoid excessive context switching overhead due to too many threads int workerThreads = Math.min( Runtime.getRuntime().availableProcessors() * 2, 64); / / Create the corresponding event loop group based on whether the local Epoll model is used. / / EpollEventLoopGroup: A high-performance I / O thread group used in Linux / / NioEventLoopGroup: A general-purpose NIO thread group for cross-platform use. return this.useNative() ? new EpollEventLoopGroup(workerThreads, this.workerThreadFactory) / / Use Epoll model : new NioEventLoopGroup(workerThreads, this.workerThreadFactory); / / Use NIO model } (33) Optimization of key TCP parameters: Building upon the above configuration, this invention further optimizes performance by setting key TCP parameters. For example, disabling Nagle's Algorithm reduces network latency, thereby improving real-time data transmission efficiency; simultaneously, a Pooled ByteBuf Allocator is employed to reduce the performance overhead caused by frequent memory allocation, thus improving system throughput. Example code is shown below: / / Disable Nagle's algorithm to reduce network latency serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); / / Set up a pooled byte buffer allocator for the server channel serverBootstrap.option(ChannelOption.ALLOCATOR,PooledByteBufAllocator.DEFAULT); / / Set up a pooled byte buffer allocator for the client connection channel serverBootstrap.childOption(ChannelOption.ALLOCATOR,PooledByteBufAllocator.DEFAULT); Through the aforementioned series of optimization measures, this system not only maintains efficient and stable operation in high-concurrency environments but also significantly reduces latency, meeting the needs of application scenarios with extremely high real-time requirements. Compared to the traditional TCP protocol stack, this solution offers greater flexibility and scalability, enabling it to quickly adapt to different network conditions and load pressures, truly achieving the goal of high concurrency and low latency.
[0058] (41) Message boundary identification mechanism based on length field To address the issue that the TCP protocol itself cannot identify message boundaries, this invention introduces a buffer reassembly mechanism based on the protocol length field in the Netty decoder TermProtocolMessageDecoder. This mechanism locates the message start position based on the protocol-defined message start byte (e.g., 0x7E) and reads the version number field to determine the length field size (1 byte or 2 bytes), thereby obtaining the entire frame length. Only when the receive buffer contains a complete data frame is it extracted and passed to subsequent processing flows.
[0059] / / Find the position of the starting byte int startByteIndex = in.bytesBefore(START_BYTE); if (startByteIndex == -1) { / / If the starting character is not found, discard all data in.clear(); return;} … if (in.readableBytes() <lengthField) { / / Insufficient data received, waiting for the next reception. return; } / / Read a complete frame of data ByteBuf fullFrame = in.readBytes(lengthField); If the current receive buffer does not contain a complete frame, the current data is retained and waited for the next receive to complete it, thus achieving efficient buffer reassembly.
[0060] (42) CRC16 data integrity verification mechanism After extracting the data frame, a CRC16 integrity check is performed on the received data. The CRC value of all data from the starting position to the beginning of the CRC field is calculated. The data is then compared with the received CRC field. If the verification fails, the frame is discarded to prevent erroneous data from spreading further.
[0061] / / Calculate CRC value for the frame data portion int calculatedCrc = CRC16Util.calculateCRC16ForBufferWithOffset(frame, startIndex, length - 2); / / Received CRC value int crc = MyByteBufUtil.readWord(frame); / / Compare the calculated value and the received value to see if they are the same; if they are not. if (calculatedCrc != crc) { / / When there are discrepancies, record the error log and error data content. log.error("CRC check failed, data discarded. Calculated value {}, reported value {} ", calculatedCrc, crc); termReceiveMessage = buildErrorMessage(version, length, cid, cno,serialNumber, receivedCrc, dataByteBuf); log.error("CRC check failed, data content => {}", termReceiveMessage.getPrintHexString()); return null; } The CRC16 algorithm uses a predefined lookup table method to accelerate the calculation process, ensuring efficient verification without affecting performance.
[0062] (43) Multi-frame sequential transmission and retransmission mechanism For large data transmission scenarios such as power line waveform recording and firmware upgrades, this invention employs a multi-frame sequential transmission mechanism. Large data is divided into multiple data frames and sent sequentially, with frame sequence numbers ensuring correct assembly at the receiving end. The platform can request and cache data frame by frame, ensuring data integrity and order.
[0063] The encoder in this embodiment is used to set a frame sequence number for each data frame and add the frame sequence number to the data frame before sending it to the terminal.
[0064] In addition, an automatic retransmission mechanism is introduced to prevent data loss. For example, during DMA data transfer, a timed task is set to periodically check for frames that have timed out and not responded to; if one is found, a retransmission operation is triggered. / / Check DMA waveform data response every second channel.eventLoop().scheduleAtFixedRate(() ->{ if (isDmaRunning(myFsu.getId())) { / / It is only necessary to check the DMA operation information obtained from the host number during DMA. DmaInfo dmaInfo = getDmaInfo(myFsu.getId()); / / The statistic increments by 1 per second. There is a reset to 0 upon receiving a response. dmaInfo.setSendCount(dmaInfo.getSendCount() + 1); if (dmaInfo.getSendCount()>12) { / / DMA response timeout 12s, clear this DMA waveform recording process, this process is complete, waiting for the next restart. clearDmaCache(myFsu.getId()); } else if (dmaInfo.getSendCount() == 3 ||dmaInfo.getSendCount() == 6|| dmaInfo.getSendCount() == 9) { / / DMA response timeout prompts a re-initiation of the current frame request command. Only 3 re-requests are made to avoid frequent requests.
[0065] TermSendMessage termSendMessage = TermDmaHandler.termDmaRequest(dmaInfo); netFrontOnlineClient.getOnlineClient(myFsu.getId()).addMessageToQueue(termSendMessage); } } }, 1, 1, TimeUnit.SECONDS); For critical services such as terminal upgrades, a scheduled task is also set up to check for response timeouts and support multiple retries until success or the maximum number of retries is reached. @Scheduled(fixedRate = 5_000) public void checkUpgradeTimeout() { upgradeInfoMap.forEach((fsuId, info) ->{ / / Determine if a host is undergoing terminal upgrade, is waiting for a response, and meets the retransmission criteria; if no response is received within 10 seconds. if (info.getUpgradeStatus() == TermUpgradeStatusEnum.UPGRADING&& info.isWaitingResponse()&& info.shouldRetry()) { / / Perform resend upgrade frame processing resendLastFrame(fsuId, info); } }); } / / Method for sending the last upgrade frame private void resendLastFrame(Long fsuId, TermUpgradeInfo info) { / / If the number of resends has exceeded 5 if (info.getRetryCount().get()>= TermUpgradeInfo.MAX_RETRIES) { log.warn("Terminal upgrade retransmission limit exceeded, upgrade aborted,[{}][{}][{}]", fsuId,info.getCombId(), info.getFrameIndex()); / / Remove upgrade information resetUpgradeInfo(fsuId); / / SSE reports upgrade failure to the front end broadcastFailure(fsuId); return; } / / Perform send processing sendUpgradeRequest(fsuId, info.getFrameIndex()); } The above mechanism effectively ensures the reliable transmission of big data in complex network environments, reduces the risk of data loss, and improves the overall system robustness.
[0066] The platform in this embodiment adopts a multi-mode login method to enhance the system's flexibility and adaptability, making it easier for different types of hardware terminals to access the platform; the multi-mode login method includes login based on IP address and login based on host number.
[0067] This invention supports two main device login methods: - IP address-based login method: Applicable to wired devices (such as network port devices) with fixed IP addresses. After the Netty connection is established, the system obtains the device's IP address and checks whether a corresponding record exists in the preset host table. If it exists, the device is considered a legitimate device and is allowed to go online.
[0068] - Host ID-based login: Applicable to 4G wireless devices, whose IP addresses are not fixed and cannot be uniquely identified by IP. After establishing a connection, these devices will proactively send a login request command (such as the 0xF1 command), which includes information such as the host ID, device type, and MAC address. The system searches for the corresponding record in the host table based on the received host ID, completes authentication, and establishes a connection.
[0069] / / After the Netty connection is established, try to look up the host record based on the IP address. MyFsu myFsu = fsuLoginService.loadFsuInfo(FsuLoginCheckTypeEnum.IP,ip); if (myFsu == null) { / / If not found, wait for login instructions. log.info("No host information found for the IP address, awaiting login instructions..."); } else { / / Locate the host information, confirm it's a wired device, and connect it directly. channelHolder.register(ctx.channel(), myFsu); / / Perform successful login processing such as retrieving the request structure fsuLoginDeal(); } The login command parsing and authentication process includes: For wireless devices, a login command (0xF1) must be sent after the connection is established to complete authentication. The login command format is as follows:
[0070] After receiving the instruction, the system extracts the host ID and matches it in the host table. If a match is found, the current connection is bound to that host, completing the online operation. MyFsu myFsu = null; / / 1. Login type Byte int loginType = MyByteBufUtil.readByte(dataBuf); / / 2. Unit Number => Host ID int fsuId = MyByteBufUtil.readWord(dataBuf); IProtocolClient client = clientManager.getClient(ChannelUtil.getChannelId(channel)); int response = LOGIN_FAILURE; if (loginType == LOGIN_IN) { / / Perform number detection login myFsu = fsuLoginService.loadFsuInfo(FsuLoginCheckTypeEnum.STANDARD_CODE, String.valueOf(fsuId)); if (myFsu != null&&myFsu.getId() != null) { / / Successful login was detected after obtaining the data ID. response = LOGIN_SUCCESS; } else { / / Retrieve data ID to detect login failure } The login response mechanism refers to the system returning a login response instruction (such as 0x71) to the device after completing authentication. The response fields are defined as follows:
[0071] This mechanism allows the device to determine whether it has successfully connected to the system, facilitating subsequent communication control and status synchronization.
[0072] Dynamic connection management and state maintenance include: Once a device completes login, the system establishes a unique connection channel for it and incorporates it into the online device management module. The system supports device logout operations (such as sending the 0xF1 command, with login type 00), updates the device's online status, and releases related resources.
[0073] In addition, the system also supports a heartbeat detection mechanism to regularly check the online status of devices and prevent resource leaks caused by abnormal disconnections.
[0074] Retrieving real-time terminal device information via HTTP requests is a frequent operation in industrial IoT platforms. To improve communication efficiency and system stability, this embodiment uses a combination of asynchronous result processing objects (CompletableFuture) and channel attribute keys (AttributeKey) to replace the traditional synchronized + wait / notify synchronous waiting mechanism, achieving a simpler, more flexible synchronous communication method with timeout control capabilities.
[0075] The following example illustrates the specific implementation process of the platform requesting the structure of terminal devices: (51) Creation and binding of asynchronous tasks When the server receives a terminal query or control command request, the system creates an asynchronous task object through a CompleteableFuture (asynchronous result processing object) and binds it to the current communication channel and a specific command identifier (such as CMD_STRUCT_RESP) for triggering task completion after receiving response data.
[0076] CompletableFuture <List <mytermparam>>responseFuture =getResponseFuture(TermProtocolCidEnum.CMD_STRUCT_RESP, comb.getId(),channel); The internal implementation of the above method is as follows: public <t>CompletableFuture <t>getResponseFuture(String commandKey,Long requestId, Channel channel) { / / Create a key based on the command and request number String key = HttpResponseKey.getKey(commandKey, requestId); CompletableFuture <t>future = new CompletableFuture<>(); channelHolder.setSessionAttribute(channel, key, future); Return to the future; } The `channelHolder.setSessionAttribute(...)` method saves the asynchronous task object to a custom attribute of the Netty Channel, ensuring that the request and response correspond one-to-one.
[0077] (52) Sending requests and asynchronously waiting for results After the asynchronous task is created, the system sends a request instruction (such as a structure information retrieval instruction) to the terminal device and enters a blocking waiting state by calling the CompletableFuture.get(timeout, unit) method to wait for the response data to be returned.
[0078] / / Send structure retrieval request termStructService.sendStructRequest(comb); / / Here, we wait for the terminal response and then directly obtain the hierarchical result set. List <mytermparam>result = responseFuture.get(15, TimeUnit.SECONDS); This mechanism replaces the traditional method of manually maintaining thread locks, flags, and notification mechanisms, making asynchronous communication logic simpler and more readable.
[0079] (53) Response processing and task completion triggering After the terminal device returns response data, the decoder parses it and hands it over to the corresponding processor for processing. Taking the processing of structured information responses as an example, after parsing, the system looks up the previously bound CompletableFuture (asynchronous result processing object) in the Channel and calls its complete(...) method to complete the asynchronous task. CompletableFuture <List <mytermparam>>future = channelHolder.getSessionAttribute(channel, key, CompletableFuture.class); / / After obtaining the CompletableFuture object from the channel, manually complete the asynchronous task and set the result value. if (future != null) { future.complete(termParamsParse); } In this way, the precise binding and release of asynchronous tasks with specific communication connections is achieved, avoiding resource leakage problems.
[0080] (54) Timeout control and exception handling mechanism To prevent threads from being blocked for extended periods due to terminal unresponsiveness, this invention uses the `CompletableFuture.get(timeout, unit)` method to set a maximum waiting time. Once the timeout occurs, a `TimeoutException` is thrown, which can be caught by the upper-level logic to handle the exception or implement a retry strategy.
[0081] } catch (TimeoutException e) { throw new PlatformException("Terminal response timed out 15s")); } Compared to the traditional method of manually determining time difference, this solution is simpler, safer, and more controllable, effectively improving the stability and robustness of the system.
[0082] (55) Modular design and applicability to multiple scenarios This invention adopts a modular design, with all core logic for asynchronous communication encapsulated in general components (such as ChannelHolder, HttpResponseKey, and the CompletableFuture utility class), providing a unified interface suitable for various types of request-response interaction scenarios, including but not limited to: - Device status query; - Command issuance confirmation; - Parameter configuration updated; - Firmware upgrade progress feedback, etc.
[0083] In addition, it supports dynamic registration of CompletableFuture corresponding to different command types, which facilitates subsequent feature expansion and maintenance.
[0084] In summary, this invention effectively solves the problems of complex thread management, poor code readability, and error susceptibility in traditional asynchronous programming by introducing CompletableFuture to build an asynchronous communication synchronization mechanism. This mechanism not only simplifies the development process but also improves the stability and responsiveness of the system. It is particularly suitable for high-frequency, high-concurrency terminal interaction scenarios in industrial IoT platforms, and has good application prospects and promotional value.
[0085] To address the issues of complex scheduling logic, difficult control, and error susceptibility of periodic and delayed tasks in existing industrial IoT scenarios, the platform in this embodiment is also used to create various types of tasks and manage all tasks through a unified scheduling interface.
[0086] Preferably, all tasks are managed uniformly through Netty's EventLoop scheduling interface to achieve unified task scheduling based on the Netty framework.
[0087] The platform also uses a task-bound channel lifecycle approach, registering a listener to the asynchronous callback object (Channel.closeFuture) when each task is created, and automatically canceling the relevant task when the connection is broken.
[0088] Specifically: After the device successfully logs into the platform, it dynamically creates various types of periodic tasks based on configuration parameters, including but not limited to: forced inspection tasks, synchronous data acquisition tasks, clock synchronization tasks, and terminal online status detection tasks. All tasks are uniformly managed through Netty's EventLoop scheduling interface, eliminating the need for additional thread pools or timer components. Furthermore, this invention employs a task-bound channel lifecycle approach, registering a listener to the Channel.closeFuture callback object when each task is created. When the connection is broken, the relevant task is automatically canceled, thus achieving automatic task recycling and cleanup, avoiding memory leaks and task residue issues. This invention proposes a task scheduling mechanism based on the Netty framework for unified management of the execution of various periodic and delayed tasks in an industrial IoT platform. By integrating Netty's EventLoop scheduling interface and binding the task lifecycle to a communication channel, unified, automated, and resource-efficient task scheduling is achieved.
[0089] (61) Task scheduling mechanism based on EventLoop (Event Loop Scheduler) In traditional solutions, periodic or delayed tasks typically rely on independent thread pools or timer components, which not only increases system complexity but also easily leads to thread contention and task conflicts. This invention, however, uses the EventLoop interface provided by Netty as a unified task scheduling engine, completing task scheduling without introducing additional components, thereby simplifying the system structure and improving the security and controllability of task scheduling.
[0090] The following uses the "clock synchronization task" as an example to illustrate the specific implementation process: / ** * Start a periodic clock synchronization task.
[0091] This method is used to periodically send time synchronization commands to terminal devices to ensure that the time of the terminal devices is consistent with that of the server.
[0092] * Task scheduling is managed by Netty's EventLoop and is bound to the Channel lifecycle; tasks are automatically canceled when the connection is lost.
[0093] / private void clockSyncTask() { / / Obtain the clock synchronization period (in minutes) from the host information. Integer clockSyncPeriod = myFsu.getExtendparams().getClockSyncPeriod(); / / Check if the period is valid (not empty and greater than 0). Only start the scheduled task if the period is valid. if (clockSyncPeriod != null&&clockSyncPeriod>0) { / / Use Netty's EventLoop to create a scheduled task that executes at a fixed frequency / / Parameter description: / / - The first parameter is the task logic (Runnable) -> The syncTimeSyncType method is called during execution to perform time synchronization. / / - The second parameter is the initial delay time (0 means start immediately) / / - The third parameter is the execution interval (clockSyncPeriod) / / - The fourth parameter is the time unit (TimeUnit.MINUTES means in minutes). ScheduledFuture<?> future = ctx.channel().eventLoop() .scheduleAtFixedRate(() ->termSyncTimeService.syncTimeSyncType(this),0, clockSyncPeriod, TimeUnit.MINUTES); / / Add a Channel and close the listener to automatically cancel the scheduled task when the client disconnects. / / Avoid resource waste or errors caused by continuing to execute tasks after a connection has been lost. ctx.channel().closeFuture().addListener(f ->{ / / Cancel the scheduled task; false indicates that the currently executing task will not be interrupted. future.cancel(false); }); } } The code above demonstrates the following key technical implementations: - Create a periodic task using ctx.channel().eventLoop().scheduleAtFixedRate(...); - All tasks are executed by Netty's I / O thread, avoiding additional thread resource consumption; - Save the task object and bind it to the current communication channel; Register a listener in Channel.closeFuture().addListener(...) to ensure that tasks are canceled in a timely manner when the connection is closed, preventing memory leaks and task remnants.
[0094] This approach replaces the traditional, complex logic of manually maintaining thread pools and checking flags, significantly improving the stability and maintainability of the system.
[0095] (62) Unified scheduling framework for multiple task types In addition to "clock synchronization tasks", this invention can also be applied to various types of periodic or delayed tasks, including but not limited to: - Mandatory inspection task: Periodically triggers equipment parameter collection; - Synchronous data acquisition task: Perform data synchronization operations according to a set period; - Terminal online status detection task: Periodically determine whether the device is online and update the status information; - Heartbeat keep-alive task: Maintain active communication with the terminal device; - Data retransmission task: Resend messages when the network is unstable.
[0096] The creation and scheduling methods for these tasks are the same as those for the "clock synchronization task" mentioned above. Only their execution logic and scheduling cycle need to be defined to reuse the same scheduling mechanism.
[0097] (63) Task and Channel lifecycle binding mechanism To further improve system controllability and resource utilization, this invention binds all tasks to the lifecycle of the communication channel. Each task registers a listener with the Channel.closeFuture callback object upon creation; once the connection is broken, the associated task will be automatically canceled.
[0098] This design effectively solves the memory leak problem caused by uncleaned tasks due to connection interruption in traditional task scheduling, and is especially suitable for high-concurrency environments in industrial IoT scenarios where devices frequently come online / offline.
[0099] (64) High-efficiency concurrent execution and resource optimization Since all tasks are scheduled and executed by Netty's EventLoop thread, tasks share Netty's I / O thread resources, reducing the performance overhead caused by context switching and thread creation and destruction. Furthermore, task scheduling and I / O event processing occur within the same thread, avoiding cross-thread lock contention and improving overall execution efficiency.
[0100] (65) Maintainability and scalability design This invention employs a modular design, separating task scheduling logic from business logic. This allows adding new task types to only require defining their execution logic and scheduling strategy, without modifying the underlying scheduling mechanism. For example, when adding a new device status reporting task, only: - Define the task execution body; - Set the scheduling period; - Register a Channel and close the listener.
[0101] This design greatly improves the maintainability and scalability of the system and reduces the cost of later feature iterations.
[0102] In summary, this invention deeply integrates task scheduling logic with Netty's EventLoop and Channel lifecycles, constructing a unified, efficient, and secure task scheduling system. This system has the following advantages: - Simplify task scheduling logic: avoid introducing external thread pools or timer components; - Improve system stability: Bind tasks through Channel lifecycle and automatically reclaim invalid tasks; - Improve resource utilization: Reuse Netty's I / O threads to reduce thread contention; - Enhanced maintainability and scalability: Task scheduling logic is decoupled from business logic, facilitating subsequent feature expansion.
[0103] It is particularly suitable for scenarios involving a large number of connected devices and high-concurrency task management in industrial IoT platforms, and has good engineering practicality and promotional value.
[0104] The present invention proposes a custom network terminal communication protocol system that can effectively solve several key technical problems in the communication between existing industrial IoT platforms and hardware devices, and demonstrates significant technical advantages and good practical value in practical applications.
[0105] 1. High-concurrency, low-latency communication architecture enhances system performance. Based on Netty's asynchronous non-blocking I / O model and event-driven mechanism, combined with dynamic switching of NIO / Epoll I / O models and adaptive adjustment of thread pool size according to the number of CPU cores, the system's concurrent processing capability and response speed are significantly improved, meeting the real-time requirements of large-scale terminal access scenarios and solving the problem that traditional TCP protocol stacks cannot meet high concurrency and low latency.
[0106] 2. It makes up for the shortcomings of general protocols in specific application scenarios. This invention achieves efficient and reliable data interaction between an industrial IoT platform and hardware terminals by defining a complete, standardized, and scalable uplink and downlink communication protocol format. The protocol supports multi-version compatibility and differentiates the uplink and downlink frame structures according to different functional directions, exhibiting good flexibility, scalability, and practicality. A standardized protocol field arrangement makes the structure of each frame data clear and easy to parse. Communication between the platform and terminal uses a unified message format, reducing parsing errors caused by protocol inconsistencies and improving overall communication efficiency. Enhancing the protocol's scalability and adaptability, this invention fully considers the possibility of future functional expansion in its protocol design. The function code field reserves expansion space to facilitate the addition of new command types, and the data content field supports variable-length structures to adapt to different types of data loads. Improving protocol security and integrity, each frame data includes a CRC checksum field to verify the integrity of the entire frame data, preventing data corruption due to network interference or transmission errors. Simultaneously, the start character field is used to quickly locate the frame header, avoiding frame boundary judgment errors during parsing and improving the system's robustness and fault tolerance. The uplink and downlink frame structures are designed differently to fit actual application scenarios. Addressing the asymmetric roles between the platform and the terminal, this invention features a differentiated design for the uplink and downlink protocol structures: Downlink protocol (platform → terminal): More comprehensive functionality, supporting multi-terminal control, scheduled delivery, and pre / post latency configuration, suitable for complex remote command delivery scenarios; Uplink protocol (terminal → platform): Simpler structure, focusing on status reporting and data feedback, reducing terminal resource consumption and improving response efficiency. This differentiated design reduces development and maintenance costs, ensuring powerful control capabilities on the platform side while also accommodating the lightweight processing needs of the terminal side, enhancing the overall applicability of the system.
[0107] A unified and standardized protocol structure enables developers to quickly understand message formats and field meanings, reducing the development difficulty of communication modules. At the same time, standardized design also facilitates later debugging, log analysis, and troubleshooting, improving system maintainability.
[0108] 3. Data integrity and reliability assurance By introducing a buffer reassembly mechanism based on the protocol length field into the decoder, the receiver can accurately identify the boundaries of each message, avoiding frame loss or reassembly errors caused by TCP transmission characteristics, thus improving the reliability of data transmission.
[0109] A custom CRC16 checksum mechanism is used to ensure data transmission integrity. Any transmission errors are detected and discarded promptly, preventing incomplete data transmission from impacting the system. Furthermore, a data retransmission mechanism ensures no data loss during transmission, especially in high-volume data transmission scenarios. Multi-frame transmission and retransmission effectively guarantee data integrity. For high-volume data transmission scenarios such as power line waveform recording and firmware upgrades, a multi-frame sequential transmission mechanism is employed to ensure data arrives in order and is transmitted completely. The platform can request and cache data frame by frame, ensuring reliable data transmission and avoiding problems such as frame loss and data corruption that may occur in traditional methods.
[0110] 4. Enhance the security and flexibility of device login verification. It supports multiple device login methods, including those based on IP address and terminal number, enhancing the system's flexibility and adaptability.
[0111] It can meet the access requirements of different terminals and improve the system's adaptability in various industrial IoT scenarios.
[0112] 5. Simplify the synchronization logic in asynchronous communication and reduce the probability of errors.
[0113] Simplifying asynchronous communication logic and reducing development complexity: In traditional asynchronous communication, developers need to manually maintain thread locks, waiting flags, notification mechanisms, etc., resulting in complex code structure and poor readability. This invention utilizes the chained calling feature of CompletableFuture to encapsulate asynchronous operations into a call format similar to synchronous methods, greatly simplifying the development process and improving code readability and maintainability. Supporting flexible timeout control mechanisms: Using CompletableFuture, the maximum waiting time for a task can be easily set, and exception or retry logic can be automatically triggered after a timeout, thus avoiding thread blocking problems caused by unresponsive terminals. Compared to the traditional method of manually judging system time differences to implement timeout control, this solution is simpler, safer, and more controllable. Strong compatibility, easy to extend and maintain: This mechanism does not depend on specific business logic and is suitable for various types of request-response interaction scenarios (such as device status queries, command issuance confirmations, etc.), exhibiting good versatility and extensibility. At the same time, the modular design facilitates later functional iteration and debugging optimization. In industrial IoT platforms, real-time acquisition of terminal device information is a high-frequency operation. This mechanism, through an efficient and stable asynchronous-to-synchronous communication method, ensures that the platform can quickly and accurately obtain device feedback information, improves the overall system response speed and stability, and thus enhances the user experience.
[0114] 6. Unify the scheduling of periodic and delayed tasks to improve system controllability.
[0115] Simplifying task scheduling logic and reducing system complexity: Traditional periodic and delayed task scheduling typically relies on external thread pools or timer components, which not only increases system complexity but also easily leads to errors in thread management and scheduling logic. This invention, however, utilizes Netty's EventLoop scheduling interface for task scheduling, avoiding the introduction of additional components and simplifying task management complexity. In this way, task scheduling and thread pool management are unified, making the system simpler, clearer, and easier to maintain. Binding tasks to channel lifecycles for automatic recycling and cleanup: This invention binds tasks to the channel lifecycle. Each task registers a listener to the Channel.closeFuture callback object upon creation; when the connection is broken, the relevant task is automatically canceled. This mechanism solves the problem of uncleaned or residual tasks, effectively avoiding the waste of system resources caused by memory leaks and task remnants. For the connection and task management of a large number of devices in industrial IoT scenarios, this design can significantly reduce the risk of task remnants and memory leaks, improving system stability and reliability. Efficient Task Scheduling and Execution: Netty's EventLoop scheduling interface schedules tasks through a thread pool, fully leveraging Netty's I / O event loop mechanism to enable efficient concurrent task scheduling and execution. In industrial IoT applications, there are various task types, including mandatory inspection tasks, synchronous data acquisition tasks, clock synchronization tasks, and terminal online status detection tasks. Through a unified scheduling mechanism, these tasks can be efficiently managed within the same framework, avoiding conflicts and complex resource contention issues found in traditional methods, ensuring efficient system operation under high concurrency conditions. Avoiding Memory Leaks and Task Residue: Traditional task scheduling systems, without a suitable cleanup mechanism, may lead to memory leaks, especially in high-concurrency environments where devices frequently connect and disconnect, making task management and cleanup prone to errors. This invention uses the Channel.closeFuture callback object to automatically cancel tasks, ensuring that each task is promptly cleaned up when the device disconnects, thereby avoiding memory leaks and task residue issues, effectively improving system resource utilization and memory management capabilities. Improved system maintainability and scalability: By using the Netty framework and event-driven scheduling mechanism, the various parts of task scheduling are decoupled, separating business logic from scheduling logic, thereby improving system maintainability. When it is necessary to expand to new task types or add support for new devices, only configuration modifications or the addition of new task management logic are required, without large-scale modifications to existing code. This high degree of flexibility and scalability enables the system to better cope with future changes in business needs, reducing the cost of later maintenance and upgrades.
[0116] Example 2 In this embodiment, a method for a custom network terminal communication protocol is disclosed, including: The encoder serializes the message data object into a data frame conforming to the downlink protocol, which is then sent to the terminal as a downlink message. The decoder receives uplink information sent by the terminal through the uplink protocol, and verifies the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.
[0117] While the specific embodiments of the present invention have been described above in conjunction with the accompanying drawings, this is not intended to limit the scope of protection of the present invention. Those skilled in the art should understand that various modifications or variations that can be made by those skilled in the art without creative effort based on the technical solutions of the present invention are still within the scope of protection of the present invention.< / mytermparam> < / mytermparam> < / t> < / t> < / t> < / mytermparam> < / socketchannel>
Claims
1. A custom network terminal communication protocol system, comprising a platform and a terminal, characterized in that, The platform includes encoders and decoders; The encoder is used to serialize message data objects into data frames that conform to the downlink protocol, which are then sent to the terminal as downlink messages. The decoder is used to receive uplink information sent by the terminal via the uplink protocol, and to verify the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.
2. The custom network terminal communication protocol system as described in claim 1, characterized in that, The downlink protocol structure includes a start character, version number, total protocol frame length, function code, function code type, terminal number, number of terminals, pre-delay time, message time, post-delay time, data content, and CRC checksum. The uplink protocol structure includes a start character, version number, total protocol frame length, function code, terminal number, data content, and CRC checksum.
3. The custom network terminal communication protocol system as described in claim 1, characterized in that, The decoder performs the following process to verify the length and integrity of data frames: Determine the starting character of the frame; Determine the start position of the frame based on the start character; Retrieve data of the same length as all protocol frames in the data frame, starting from the beginning of the frame, and calculate the CRC checksum of the data. Compare the calculated CRC checksum with the CRC checksum in the data frame; If both are the same, it indicates that the integrity verification of the data frame has passed.
4. A custom network terminal communication protocol system as described in claim 3, characterized in that, The decoder determines the length of the data frame based on the version number in the data frame.
5. A custom network terminal communication protocol system as described in claim 1, characterized in that, The encoder is used to set a frame sequence number for each data frame and add the frame sequence number to the data frame before sending it to the terminal.
6. A custom network terminal communication protocol system as described in claim 1, characterized in that, The platform adopts multiple login modes, including login based on IP address and login based on host number.
7. A custom network terminal communication protocol system as described in claim 1, characterized in that, The process by which the encoder encodes data into data frames conforming to the downlink protocol includes: Determine the data-related content required for the protocol structure, excluding the CRC checksum; Write all data-related content, except for the CRC checksum, into the buffer sequentially; Determine the CRC checksum of the content written to the buffer; Write the CRC checksum into the buffer to form a data frame that conforms to the protocol; Write data frames that conform to the protocol to the output buffer.
8. A custom network terminal communication protocol system as described in claim 1, characterized in that, The platform is also used to create various types of tasks and manage all tasks through a unified scheduling interface.
9. A custom network terminal communication protocol system as described in claim 1, characterized in that, The platform also uses a task-bound channel lifecycle approach, registering listeners to the asynchronous callback object when the channel is closed when each task is created, and automatically canceling the relevant task when the connection is broken.
10. A method for a custom network terminal communication protocol, characterized in that, include: The encoder serializes the message data object into a data frame conforming to the downlink protocol, which is then sent to the terminal as a downlink message. The decoder receives uplink information sent by the terminal through the uplink protocol, and verifies the length and integrity of the received uplink messages to determine the data content of the uplink messages that pass the verification.