Equipment connection method and device based on MQTT, equipment and medium

By using hierarchical DNS resolution and MQTT encrypted channel authentication, the problems of long connection times and low interaction efficiency of IoT devices are solved, enabling fast, stable and secure device connection and interaction, which is suitable for multiple application scenarios of IoT devices.

CN121644260AActive Publication Date: 2026-03-10SHENZHEN LINGDECHUANG TECH CO LTD
View PDF 4 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-02-04
Publication Date
2026-03-10

AI Technical Summary

Technical Problem

IoT devices suffer from problems such as long connection times, low interaction efficiency, and high communication risks during the connection process. They are particularly unstable in complex network environments and cannot meet the requirements for high-frequency and low-latency communication.

Method used

A tiered DNS resolution strategy is adopted, prioritizing the use of native interfaces to query highly available DNS servers. If this fails, the system will resolve the DNS. Combined with the encrypted channel authentication and message identification and concurrent security mapping of the MQTT protocol, fast, stable and secure device connection and interaction are achieved.

Benefits of technology

It achieves millisecond-level connection, improves connection stability and interaction reliability, ensures communication security, and adapts to the multi-scenario application needs of IoT devices.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121644260A_ABST
    Figure CN121644260A_ABST
Patent Text Reader

Abstract

The invention discloses an MQTT-based equipment connection method and device, equipment and a medium, and relates to the technical field of Internet communication, the method is applied to an equipment end, and the method comprises the following steps: loading equipment identity configuration information; analyzing the access point information by adopting a hierarchical domain name system analysis strategy to obtain a target connection address; initiating an MQTT connection request, and completing authentication through an encryption channel; if the connection fails, the standby access point is switched to repeat the analysis and connection process; after connection is established, messages are transmitted directionally based on a set theme format, request and response interaction is achieved through a message association mechanism, overtime control is completed through MQTT delay messages, and the scheme improves the equipment connection speed, stability and interaction reliability, guarantees communication safety and adapts to the multi-scene requirements of the Internet of Things.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the technical field of Internet communication, and in particular to a device connection method and device based on MQTT, a device, and a medium. BACKGROUND

[0002] With the popularization of Internet of Things technology, terminals such as NAS devices and smart homes need to interact with the cloud and mobile applications with high-frequency instructions and data transmission, which puts strict requirements on connection speed, reliability, security, and interaction efficiency.

[0003] In related technologies, when designing an Internet of Things device connection system, HTTP / HTTPS polling needs to repeatedly establish TCP / TLS connections, which has large handshake overhead and poor real-time performance. Long polling consumes a large amount of server resources and is difficult to adapt to high-frequency low-latency scenarios. Although the standard MQTT protocol is based on long connections and has a small protocol header, it lacks a built-in RPC mechanism, and the sender cannot quickly obtain the processing result of the receiver. It only relies on TLS encryption at the transport layer, which is vulnerable to man-in-the-middle attacks or client forgery, and lacks security. In complex network environments such as DNS hijacking and slow resolution, the connection establishment speed is slow, there is no automatic switching mechanism for backup links, and the stability is poor. These problems result in long device connection time, low interaction efficiency, and high communication risk, which cannot meet the core needs of millisecond-level connection, high-reliability interaction, and secure transmission for Internet of Things devices, and there is an urgent need for an optimized MQTT connection technology to solve the above problems. SUMMARY

[0004] The embodiments of the present application provide a device connection method and device based on MQTT, which loads identity configuration information at the device end, obtains a target connection address through hierarchical DNS resolution with native priority and system fallback, initiates MQTT connection and authentication through an encrypted channel, automatically switches to a backup access point for retry in case of connection failure, and performs targeted signaling based on a topic containing a target identifier after success. The request-response interaction is realized by means of message identification and concurrent security mapping, the timeout control is completed by means of a delay message, and fast, stable, and secure device connection and interaction are realized.

[0005] In a first aspect, the embodiments of the present application provide a device connection method based on MQTT, which comprises: loading device identity configuration information; based on the device identity configuration information, resolving a device access point interface and querying a domain name of device access point information through a native domain name system, returning a public network optimal IP as a target connection address of an MQTT proxy server if the resolution is successful, and resolving the device access point interface using a system-level domain name system and returning a system-level IP as the target connection address of the MQTT proxy server if the resolution fails; initiating an MQTT connection request based on the target connection address, and completing identity authentication and connection establishment with the application end through an encrypted channel; In the case where the identity authentication and connection establishment are successful, messages are directionally delivered to the application end based on a topic format set by MQTT, wherein, in the process of directionally delivering the messages, a message identifier is generated for each request message, a concurrent secure mapping relationship between the message identifier and an asynchronous channel is established, and interaction of request and response is realized based on the secure mapping relationship; a timeout trigger message of the message identifier is published to the MQTT proxy server when a request message is sent, and a timeout control operation is performed based on the timeout trigger message.

[0006] Further, the device identity configuration information includes device identification, certificate, private key, and device access point information. The domain name of the device access point interface is resolved through the native domain name system, and device access point information is queried, if the resolution is successful, a public network optimal IP is returned as the target connection address of the MQTT proxy server, including: The device access point interface is resolved by calling the native domain name system, and a query command is initiated to the preset domain name system server for the domain name of the device access point information; If the native domain name system resolution is successful, a public network IP list is obtained based on the query command, and an optimal IP is selected as the target connection address of the MQTT proxy server according to the public network IP list; The device access point interface is resolved by using the system-level domain name system, and a system-level IP is returned as the target connection address of the MQTT proxy server, including: If the native domain name system resolution fails, the device access point interface is resolved by calling the system-level domain name system, and a degraded query is performed for the domain name of the device access point information, if the system-level domain name system resolution is successful, a system-level IP successfully returned thereby is taken as the target connection address of the MQTT proxy server; If both the native domain name system and the system-level domain name system fail to resolve, the original domain name of the device access point information is used as the target connection address of the MQTT proxy server.

[0007] Further, the messages are directionally delivered to the application end based on a topic format set by MQTT, including: A topic format containing a target identifier is defined, the topic format including a device end identifier and a target party identifier field; A request message is sent to the topic format containing the target party identifier, so that the application end subscribes to the topic format containing the target party identifier, and directional delivery of the request message is realized.

[0008] Further, the message identifier is generated for each request message, and a concurrent security mapping relationship between the message identifier and the asynchronous channel is established, and the interaction of request and response is realized based on the security mapping relationship, comprising: A message identifier is generated for each request message, and a concurrent security mapping relationship between the message identifier and the asynchronous channel is established and stored, wherein the message identifier is carried in the message load, and the message load is a structured data carrier containing request instructions, business data and the message identifier; The concurrent security mapping relationship is updated in real time, and after sending the request message, the response message of the asynchronous channel is blocked and waited; After receiving the response message sent by the application end, the concurrent security mapping relationship is searched based on the message identifier in the response message, the response data is obtained, and the blocking state of the asynchronous channel is released.

[0009] Further, the timeout trigger message of the message identifier is published to the MQTT broker server when sending the request message, and timeout control operation is performed based on the timeout trigger message, comprising: When sending the request message, a timeout trigger message is published to the delay topic of the MQTT broker server, the timeout trigger message carries the message identifier corresponding to the request message, and the timeout trigger message delay time is a preset timeout threshold; If no response message is received within the timeout threshold, the timeout trigger message is triggered, the mapping entry corresponding to the message identifier of the request message in the concurrent security mapping relationship is deleted, and a timeout error is returned through the asynchronous channel corresponding to the request message; If a response message is received within the timeout threshold, the mapping entry corresponding to the message identifier carried in the response message in the concurrent security mapping relationship is deleted, and the response data in the response message is processed normally.

[0010] Further, the identity authentication and connection establishment with the application end are completed through the encrypted channel, comprising: A transport layer encrypted channel is constructed based on the transport layer security protocol; A preset encryption algorithm is used to hash sign the message load to generate signature information, and the signature information is carried in the user attribute field of the MQTT message; The MQTT message carrying the signature information is sent to the application end through the transport layer encrypted channel, so that the application end extracts the signature information from the user attribute field of the MQTT message; The application end verifies validity of the signature information through the preset public key, confirms that the sender is legal if the verification is passed, receives the request message, extracts the message load based on the request message, and discards the request message if the verification fails.

[0011] Further, after initiating the MQTT connection request based on the target connection address, and completing the identity authentication and the connection establishment with the application end through the encrypted channel, the method further comprises: If the connection establishment fails, switching to a backup device access point, repeating the hierarchical domain name system resolution process and the MQTT connection request process until the connection establishment with the application end is completed; The switching to the backup device access point comprises: According to a list of pre-stored backup device access points, selecting other backup device access points in the order of the list to reconnect when the connection fails; Repeating the hierarchical domain name system resolution and the MQTT connection request process for each backup device access point until the connection is successful or all backup device access points in the list are traversed; If all the device access points in the list fail to connect, entering a sleep retry, and reinitiating the MQTT connection request after a preset time interval.

[0012] In a second aspect, an embodiment of the present application provides a device connection apparatus based on MQTT, comprising: A configuration loading module configured to load device identity configuration information; A domain name resolution module configured to resolve a device access point interface and query a domain name of device access point information based on the device identity configuration information through a native domain name system, return a public network optimal IP as a target connection address of an MQTT proxy server if the resolution is successful, and use a system-level domain name system to resolve the device access point interface if the resolution fails, and return a system-level IP as the target connection address of the MQTT proxy server; A connection establishment module configured to initiate an MQTT connection request based on the target connection address, and complete identity authentication and connection establishment with an application end through an encrypted channel; A communication interaction module configured to, in a case where the identity authentication and the connection establishment are successful, direct message transmission based on a topic format set by the MQTT to the application end, wherein, in the process of the direct message transmission, a message identifier is generated for each request message, a concurrent secure mapping relationship between the message identifier and an asynchronous channel is established, and interaction of request and response is realized based on the secure mapping relationship; a timeout trigger message of the message identifier is published to the MQTT proxy server when a request message is sent, and a timeout control operation is performed based on the timeout trigger message.

[0013] In a third aspect, the embodiments of the present application provide an electronic device, comprising a memory and one or more processors; The memory is configured to store one or more programs; When the one or more programs are executed by the one or more processors, the one or more processors implement the MQTT-based device connection method as described in the first aspect.

[0014] In a fourth aspect, the embodiments of the present application provide a storage medium storing computer-executable instructions for executing the MQTT-based device connection method as described in the first aspect when executed by a computer processor.

[0015] The embodiments of the present application use a hierarchical DNS resolution strategy, preferentially call a native interface to query a high-availability DNS server, degrade to system resolution after failure, and finally fallback to an original domain name, bypassing DNS cache pollution and hijacking, reducing resolution time consumption, and combining with direct use of IP address to establish a connection, solving the problem of slow connection establishment of the traditional scheme, and realizing millisecond-level connection; because of the pre-device device access point list, the connection fails, and the connection process is automatically switched and repeated, combined with the sleep retry mechanism, to ensure that the device can still quickly recover the connection in a complex network environment, improve the connection stability, and avoid the disconnection problem caused by single access point failure; because the topic format containing the target identifier is defined, the message is delivered in a targeted manner, combined with the message identifier and the concurrent security mapping table to build an asynchronous-to-synchronous RPC mechanism, so that the device side can block and wait for a response, solving the defect that the standard MQTT lacks RPC function, and the upper-layer business can initiate a remote request like calling a local function, improving the development efficiency; because the transmission encryption channel is built through TLS, and the Ed25519 / RSA algorithm is used to sign the message load and embed it in the MQTT user attribute field, forming a double security protection, even if the TLS is cracked, message tampering and identity forgery can also be prevented, and the communication security is ensured; because the MQTT delay message is used to realize timeout control, a delay timeout signal is published synchronously when a request is sent, and if the response is not received on time, the resources are automatically cleaned up, eliminating memory leakage, and further improving the interaction reliability; in summary, the method synchronously realizes the rapidity of device connection, the efficiency of interaction, the security of communication, and the stability of operation, and adapts to the multi-scene application requirements of Internet of Things devices. BRIEF DESCRIPTION OF DRAWINGS

[0016] Figure 1 is a flowchart of an MQTT-based device connection method provided by the embodiments of the present application; Figure 2 is a flowchart of a native domain name system resolution device access point interface provided by the embodiments of the present application; Figure 3is a flow chart of a system-level domain name system resolution device access point interface provided by an embodiment of the present application; Figure 4 is a flow chart of message directional delivery based on MQTT setting topic format provided by an embodiment of the present application; Figure 5 is a flow chart of message identification and asynchronous channel synchronization mechanism provided by an embodiment of the present application; Figure 6 is a flow chart of MQTT broker server delay timeout control provided by an embodiment of the present application; Figure 7 is a flow chart of double-layer signature security provided by an embodiment of the present application; Figure 8 is a flow chart of master-backup switching retry provided by an embodiment of the present application; Figure 9 is a structural diagram of a device connection apparatus based on MQTT provided by an embodiment of the present application; Figure 10 is a structural diagram of an electronic device provided by an embodiment of the present application. DETAILED DESCRIPTION

[0017] In order to make the objects, technical solutions and advantages of the present application clearer, the following further describes specific embodiments of the present application with reference to the drawings. It should be understood that the specific embodiments described herein are only used to explain the present application, but not to limit the present application. In addition, it should be noted that, for the convenience of description, only parts related to the present application are shown in the drawings, but not all contents. Before discussing the example embodiments in more detail, it should be mentioned that some example embodiments are described as processes or methods depicted as flow charts. Although the flow chart describes each operation (or step) as a sequential process, many of the operations can be implemented in parallel, concurrently or simultaneously. In addition, the order of the operations can be rearranged. The above process can be terminated when its operations are completed, but can also have additional steps not included in the drawings. The above process can correspond to a method, function, procedure, subroutine, subprogram, etc.

[0018] The terms "first", "second", etc. in the specification and claims of the present application are used to distinguish similar objects, and are not used to describe a specific order or sequence. It should be understood that the data used in this way can be interchanged under appropriate circumstances, so that the embodiments of the present application can be implemented in an order other than that illustrated or described herein, and the objects distinguished by "first", "second", etc. are generally of a kind, and do not limit the number of objects, for example, the first object can be one or more. In addition, "and / or" in the specification and claims indicates at least one of the connected objects, and the character " / ", generally indicates that the objects before and after are in an "or" relationship.

[0019] The present application relates to the technical field of Internet communication, and is suitable for remote communication of device end and cloud end and mobile application in an Internet of Things (IoT) scenario, including but not limited to network storage (NAS) devices, smart home devices, industrial control devices, etc., and meets the communication requirements of high frequency, low delay, high security and high stability by optimizing the connection process, strengthening security protection and improving interaction reliability.

[0020] Figure 1 is a flowchart of a device connection method based on MQTT provided by an embodiment of the present application, please refer to Figure 1 The flow of the device connection method provided by the present application includes configuration loading, hierarchical DNS resolution, connection establishment, directional communication and timeout control, and forms a complete closed loop of configuration, resolution, connection and interaction, and specifically includes: Step 101, load device identity configuration information.

[0021] In an embodiment, the device identity configuration information is stored in an encrypted file system such as flash memory or EEPROM, including device identification (DeviceId), digital certificate (Cert), private key (Private Key) and device access point information (initial access point domain name, port, backup access point list), all information is stored by encryption to prevent leakage and tampering. When the device end dedicated communication service (MQTT Agent) starts, the configuration information is decrypted and read by a hardware encryption module, and the validity period of the certificate, the integrity of the private key and the legality of the access point information such as domain name format and port range are checked. If the check fails, an alarm is triggered and the process is terminated to ensure that the configuration information is legal and effective. After successful loading, the configuration information is cached in the memory to avoid repeated reading of the encrypted file system, improve the efficiency of the process execution, and support dynamic updating of the configuration by pushing update instructions from the cloud. Encryption storage and verification ensure the security of device identity configuration information, memory caching improves execution efficiency, dynamic updating supports flexible configuration, and solves the problems of easy leakage of device configuration information, low loading efficiency and complex updating.

[0022] Step 102, based on the device identity configuration information, resolve the device access point interface and query the domain name of the device access point information through the native domain name system, and if the resolution is successful, return the public network optimal IP as the target connection address of the MQTT proxy server; if the resolution fails, use the system-level domain name system to resolve the device access point interface, and return the system-level IP as the target connection address of the MQTT proxy server.

[0023] The inborn domain name system is a separate DNS resolution module built in the device firmware, which does not depend on the libc resolution library of the operating system, directly constructs a DNS query message, and initiates a query to the preset high-availability DNS server through UDP port 53, and the resolution result is directly returned as an IP list; the system-level domain name system is a DNS resolution module provided by the operating system of the device, which is used as a fallback solution for the inborn DNS resolution, uses the default DNS server configured by the current network of the device (which is allocated by the operator or manually configured), and supports local DNS cache reuse.

[0024] In one embodiment, based on the device access point information, the target connection address of the MQTT proxy server is obtained through a hierarchical strategy of inborn resolution priority, system resolution fallback and domain name fallback, to avoid DNS hijacking and slow resolution. Optionally, the inborn domain name system (DNS) resolution (Inborn Lookup) resolves the device access point interface by calling the inborn resolution interface (DNSLookupInborn) of the DNS resolution module, which can bypass the system libc resolver and directly initiate a UDP query to the preset high-availability DNS server, such as 114.114.114.114 or 8.8.8.8. If the resolution is successful, a public network IP list is obtained, and the optimal public network IP is used as the target connection address of the MQTT proxy server. The optimal public network IP is obtained by sending ICMP messages to each IP in the public network IP list, and the round-trip time (RTT) and packet loss rate are calculated, and the optimal IP is selected according to the rules of minimum RTT, minimum packet loss rate and operator matching priority. The Host field in the connection configuration is replaced with the IP, eliminating the DNS query overhead of subsequent TCP handshake; if the resolution fails, the system-level resolution process is entered.

[0025] In one embodiment, the system-level domain name system (DNS) resolution (System Lookup) calls the system-level DNS resolution interface (DNSLookup) to resolve the device access point interface, uses the system default DNS server such as the DNS server allocated by the operator for query, and if the resolution is successful, the IP returned by the system is used as the target connection address of the MQTT proxy server; if the system-level resolution also fails, the domain name of the original device access point is used as the target connection address of the MQTT proxy server, and the resolution is handed over to the underlying MQTT network library for processing. The hierarchical resolution strategy bypasses DNS cache pollution and hijacking, the inborn resolution directly obtains the public network IP to improve the connection speed, the multi-level fallback ensures the resolution success rate, and the problems of slow DNS resolution, easy hijacking and poor reliability are solved.

[0026] Step 103, initiating an MQTT connection request based on the target connection address, and completing identity authentication and connection establishment with the application end through an encrypted channel.

[0027] The target connection address is a network identifier used by the device end to establish a network connection with the MQTT broker server, and is used to specify the target endpoint of data transmission.

[0028] In one embodiment, after obtaining the target connection address, the MQTT Agent initiates an MQTT connection request based on the target connection address, completes identity authentication through the construction of an encrypted channel, and ensures the security and reliability of the connection. Optionally, the device end MQTT client carries the device identifier and certificate during the connection initiation stage, initiates a TCP connection to the target connection address, negotiates the MQTT protocol version (supports 3.1.1 / 5.0), heartbeat parameters, and connection timeout time. After the TCP connection is established, the client constructs a transport layer encryption channel based on the TLS1.3 protocol, exchanges certificates with the server and verifies the legality (certificate signature, validity period, domain name matching), and after verification, negotiates a session key (updated regularly, default 30 minutes) through the ECDH algorithm, constructs a transport layer encryption channel to prevent data transmission from being eavesdropped and tampered with; if the verification fails, the TCP connection is closed and error logs are recorded.

[0029] In one embodiment, the device end signs the connection request through a private key (using Ed25519 or RSA algorithm), embeds the signature information (including Key ID, signature value, and client identifier) in the User Properties field of MQTT v5.0, and sends it to the application end together with the device identifier; the application end verifies the validity of the signature through the preset device public key, and if the verification is passed, the identity is confirmed to be legal and the connection is established; if the verification fails, the connection is rejected and security logs are recorded. The TLS1.3 encryption channel guarantees the security of transmission, the application layer signature and the transport layer encryption form double protection, the two-way identity authentication prevents illegal devices from accessing, the standardized MQTT connection parameters adapt to different servers, and the problem of weak connection security and missing authentication is solved.

[0030] Step 104, in the case where the identity authentication and connection establishment are successful, the application end is directed to deliver messages based on the MQTT set topic format, wherein in the process of delivering messages, a message identifier is generated for each request message, and a concurrent security mapping relationship between the message identifier and the asynchronous channel is established, and the interaction of request and response is realized based on the security mapping relationship; a timeout trigger message of the message identifier is published to the MQTT broker server when sending a request message, and a timeout control operation is performed based on the timeout trigger message.

[0031] Wherein, the subject format is "MASTER_TOPIC / p2p / [sender identification]@@@[target identification]", the MQTT subject, wherein "MASTER_TOPIC" is a global uniform prefix, "@@@" is a special separator (ASCII code 0xE20x80 0x8B, zero-width separator), the sender identification and the target identification are 1-32 bit strings (containing letters, numbers and underscores), and the subject is ensured to meet the MQTT protocol specification to realize message targeted delivery; the message identification (MsgId) is a globally unique identifier generated for each request message, which is a 64-bit integer generated by using an atomic increment counter and a snowflake algorithm, and the structure is "1 bit sign bit+41 bit timestamp+10 bit worker node bit (device identification hash+thread ID)+12 bit sequence number", which ensures absolute uniqueness within a single machine and is used to associate request messages with response messages; the concurrent security mapping relationship is an association relationship between the message identification and the asynchronous channel based on a thread-safe data structure (Go language sync.Map), which supports multi-thread / coroutine concurrent execution of storage, reading and deletion operations; the asynchronous channel (Channel) is a communication carrier for transmitting response data or timeout error, and each request message corresponds to an independent channel, the buffer size is set to 1 to ensure instant data transmission, and the blocking waiting and wake-up mechanism is supported to realize the conversion of asynchronous communication to synchronous RPC.

[0032] In one embodiment, after the connection is established, the message is delivered based on the set subject format, and the reliable interaction is realized through the message identification mapping and the timeout control. Optionally, the subject format containing the target identification (MASTER_TOPIC + " / p2p / consumerId@@@TARGET_ID") is defined, the sender (device end) publishes the request message to the corresponding subject, and the application end subscribes to the exclusive subject (containing its own ID) to realize targeted receiving, thereby avoiding resource waste caused by message broadcasting.

[0033] In one embodiment, the RPC interaction implementation stage generates a unique message identification (MsgId) for each request message, generated by an atomic increment counter and a snowflake algorithm, through a composite key strategy of target device ID + MsgId, even if different business threads generate the same MsgId, because the target devices are different, it is still an independent entry in the mapping table, avoiding conflicts; a concurrent safe mapping relationship (based on Go language sync.Map, supporting lock-free concurrent read and write) between message identification and asynchronous channel is established, after the sender publishes the request message, it blocks and waits for the response of the asynchronous channel; after the application end receives the message, the request instruction and business data are parsed, and the corresponding business processing is performed, such as data storage and device control, and after the processing is completed, the business result and the original MsgId are encapsulated as a response message and published to the sender's exclusive response topic; after the sender receives the response, the corresponding asynchronous channel is obtained by searching the mapping relationship through the MsgId, and the response data is written and the blocking is released, completing the RPC interaction.

[0034] In one embodiment, when sending a request, a timeout trigger message (delay time = RPC timeout threshold, default 10 seconds) is published to the $delayed delay topic of the MQTT broker server, and if no response is received within the timeout threshold, the MQTT broker server triggers the timeout message and sends it to the response topic; after the sender receives it, the LoadAndDelete atomic operation is called to delete the entry corresponding to the MsgId in the mapping table, and the timeout error is returned through the asynchronous channel to prevent memory leakage; if the response is normally received within the timeout threshold, the mapping table entry is deleted in advance, and the subsequent timeout message trigger is ignored because the corresponding entry cannot be found, without side effects. The directional topic realizes accurate message delivery, the RPC mechanism solves the defects of MQTT asynchronous interaction, the concurrent safe mapping supports high concurrency scenarios, the timeout control guarantees resource release, and the overall interaction reliability and efficiency are improved, solving the problems of weak interaction, no timeout management and memory leakage risk.

[0035] The device connection method flow of the present application covers the whole process of configuration loading, hierarchical parsing, encrypted connection and directional interaction, solves the problems of slow connection, weak security and chaotic interaction through multi-level fallback and double security protection, and realizes millisecond-level connection establishment and high-concurrency reliable interaction, adapts to multiple scenarios of Internet of Things, and improves the efficiency and stability of device communication.

[0036] Figure 2 is the flowchart of the original domain name system resolving device access point interface provided by the embodiment of the present application, please refer to Figure 2 The flow of original DNS resolution is the core link of hierarchical resolution strategy, which improves the resolution speed and accuracy by directly calling high-availability DNS server query, specifically including: Step 201, calling the native domain name system to parse the device access point interface, and initiating a query command to the preset domain name system server for the domain name of the device access point information.

[0037] In one embodiment, the DNSLookupInborn interface of the DNS resolution module of the native domain name system called by the device side can bypass the system resolver and directly initiate a query to the preset server. This interface feature does not depend on the system libc resolution library and directly constructs a DNS query packet (query type A / AAAA record), supporting IPv4 / IPv6 dual stack resolution.

[0038] In one embodiment, the server selects one from the preset high-availability DNS server list (supporting 114.114.114.114, 8.8.8.8, 223.5.5.5, etc.) at random, sends a query packet through the UDP protocol (port 53), sets the timeout time to 3 seconds, switches to the next server if there is no response after timeout, and tries a maximum of 3 servers. If none of the 3 servers responds, it is determined that the native DNS resolution fails, triggering the system resolution fallback process. Bypassing the system resolver avoids cache pollution, multiple server retries improve resolution success rate, and the UDP protocol reduces transmission overhead, solving the problems of slow traditional system resolution and vulnerability to pollution.

[0039] Step 202, if the native domain name system resolution is successful, obtaining a public IP list based on the query command, and selecting the optimal IP as the target connection address of the MQTT proxy server according to the public IP list.

[0040] In one embodiment, if the native domain name system resolution is successful, a public IP list is obtained, and the optimal IP is selected as the target connection address through network quality detection. Optionally, the DNS server response packet is received, all associated public IP addresses are parsed, duplicate IPs are removed, and an available IP list (supporting IPv4 / IPv6 hybrid list) is formed.

[0041] In one embodiment, 3 ICMP probe packets are sent for each IP, the round-trip time (RTT) and packet loss rate are measured, the detection time for each IP does not exceed 1 second to avoid occupying too much time. According to the rules of ascending delay → descending packet loss rate → operator matching priority, the first ranked IP is selected as the target connection address of the MQTT proxy server; if the delays of all IPs are similar (difference ≤ 50 ms), the IP of the same network operator as the device is selected as the target connection address of the MQTT proxy server to improve connection stability. Network quality detection ensures the selection of the optimal IP, and operator matching improves connection stability, avoiding the problems of slow and easily interrupted connection caused by blind selection, further optimizing connection speed.

[0042] The native domain name system resolution bypasses the system resolver to directly connect to a high-availability DNS server, selects the optimal IP through multi-node retry and network quality screening, avoids DNS hijacking and cache pollution, improves resolution speed, saves DNS query overhead for TCP handshake, and is the basis for realizing fast connection.

[0043] Figure 3 is the flowchart of the system-level domain name system resolution device access point interface provided by the embodiment of the present application, please refer to Figure 3 , the flow of system-level DNS resolution, as a bottom solution for native resolution, ensures that the resolution process is not interrupted, specifically including: Step 2011, if the native domain name system resolution fails, the system-level domain name system resolution device access point interface is called, and the domain name of the device access point information is queried in a degraded manner.

[0044] In one embodiment, after the DNS resolution module of the native domain name system fails, the system-level domain name system resolution calls the system-level DNS resolution interface for degraded query. Optionally, the system resolution library such as Linux glibc and Windows dnsapi.dll is relied on to call the DNSLookup system interface, the device access point domain name is followed, the query type is consistent with the native resolution (A / AAAA record), the query timeout is set to 5 seconds, and the system is allowed to use the local DNS cache. If the system returns a valid IP list (non-empty and legal format), the IP screening process is entered; if it returns empty or is in an incorrect format, such as a non-existent domain name, it is determined that the system-level domain name system resolution fails, triggering the domain name fallback logic. Relying on the system resolution library ensures compatibility, a longer timeout improves the success rate of query, and as a bottom solution, it ensures that the resolution process is not interrupted and solves the problem of no alternative solution after native resolution fails.

[0045] Step 2012, if the system-level domain name system resolution is successful, the system-level IP returned by the success is taken as the target connection address of the MQTT broker server.

[0046] In one embodiment, if the system-level domain name system resolution is successful, the IP is screened as the target connection address of the MQTT broker server. Optionally, the IP screening rules of the native domain name system resolution are consistent, the network quality is detected through ICMP probe, and the optimal IP is selected as the target connection address to ensure the consistency of connection quality.

[0047] In one embodiment, if the system-level resolution fails (no valid IP), the device end sets the target connection address as the original access point domain name, and the subsequent DNS resolution is handled by the underlying MQTT network library itself, such as calling system resolution or third-party resolution library, to avoid complete interruption of the resolution process. Whether the resolution is successful or not, the resolution failure reason is recorded, such as DNS server unresponsive, domain name does not exist, and number of attempts, and is reported to the cloud through logs, facilitating network problem troubleshooting by operation and maintenance personnel. Unified IP filtering rules ensure connection quality, domain name fallback mechanism avoids resolution interruption, state reporting improves operation and maintenance convenience, and solves the problem of direct disconnection after resolution failure.

[0048] As a bottom solution for native resolution, the reuse IP filtering logic ensures connection quality, and falls back to the original domain name to avoid process interruption when resolution fails; effectively deals with resolution exceptions in complex network environments, improves resolution success rate, and ensures connection process continuity.

[0049] Figure 4 is the flowchart of the message format directional delivery provided by the MQTT setting embodiment of the present application, please refer to Figure 4 , the implementation process of directional message delivery, which realizes accurate message delivery by defining a standardized topic format, specifically including: Step 301, defining a topic format containing target identification, the topic format including device end identification and target party identification field.

[0050] In one embodiment, the topic format containing target identification is designed, the field composition and meaning are clear, and the device end and application end are consistent in cognition. Optionally, the topic format is "MASTER_TOPIC / p2p / [sender identification]@@@[target identification]", wherein MASTER_TOPIC is a global unified prefix, such as "iot / devices", the sender identification is the unique ID of the device end / application end, the target identification is the unique ID of the receiver, "@@@" is a special separator to avoid identification confusion and support identification containing letters, numbers and underscores.

[0051] In one embodiment, the length of the sender identification and the target identification is limited to 1-32 characters, and the length of the MASTER_TOPIC is limited to 1-64 characters, to ensure that the topic conforms to the MQTT protocol specification (maximum length 65535 characters). The device end and the application end both have built-in topic format verification logic, which verifies the integrity of the topic field (whether it contains a separator and whether the identification is empty) before sending a message. If the format is not correct, it will be rejected and an error log will be recorded to avoid invalid message delivery. The standardized topic format ensures compatibility between the two parties, precise routing is achieved by clear field division, and format verification avoids message delivery errors, solving the problem of message broadcast and delivery confusion.

[0052] Step 302, sending a request message to the topic format containing the target party identification, so that the application end subscribes to the topic format containing the target party identification, realizing the targeted delivery of the request message.

[0053] In one embodiment, the device end sends messages in the topic format, and the application end subscribes to the exclusive topic, realizing the targeted interaction. Optionally, the device end generates a request message (containing instructions, business data, MsgId), splices the topic according to the target party identification, such as "iot / devices / p2p / Device001@@@CloudService001", publishes the message through the MQTT client, sets the QoS level to 1 (ensures that the message is delivered at least once), and avoids message loss; the application end subscribes to the topic containing its own identification when starting, such as "iot / devices / p2p / +@@@CloudService001", + is an MQTT single-level wildcard, only receives messages with the target party identification being itself, filters irrelevant messages, and reduces resource consumption. After the MQTT broker server, such as EMQX, receives the message, it parses the target party identification in the topic, accurately forwards the message to the application end subscribing to the topic through the topic routing mechanism, does not push to other devices, saves bandwidth resources. The QoS level guarantees the reliable delivery of messages, the exclusive subscription filters irrelevant messages, the broker server accurately routes, realizes the targeted delivery of messages, improves the communication efficiency and security, and solves the problems of message flooding and waste of bandwidth.

[0054] Through the topic format containing the target identification, the message is accurately delivered, avoiding the waste of resources caused by broadcast flooding; the application end subscribes to the exclusive topic to filter irrelevant messages, reduces invalid data processing, and improves the communication efficiency and data security.

[0055] Figure 5 is the flowchart of the message identification and asynchronous channel synchronization mechanism provided by the embodiment of the application, please refer to Figure 5 , the mapping interaction mechanism of the message identification and the asynchronous channel is the core of realizing the RPC synchronous interaction, specifically including: Step 401, generating a message identification for each request message, establishing a concurrent and secure mapping relationship between the message identification and the asynchronous channel and storing, wherein the message identification is carried in the message load, and the message load is a structured data carrier containing a request instruction, business data and the message identification.

[0056] In one embodiment, a unique identifier is generated for each request message, a concurrent security mapping relationship is established and stored. Optionally, the identifier generation adopts an atomic increment counter and a snowflake algorithm to generate a 64-bit MsgId (structure of "1-bit sign bit + 41-bit timestamp (millisecond level) + 10-bit work node bit (device identifier hash + thread ID) + 12-bit sequence number") to ensure uniqueness within a single machine; the key of the concurrent security mapping relationship adopts a composite key "TargetPeerId:MsgId" (format such as "CloudService001:1234512345123451234") to avoid MsgId conflicts of different target devices. An independent asynchronous channel (Channel) is created for each request to deliver response data or timeout errors, and the channel is set to a buffer size of 1 to ensure immediate data delivery. The sync.Map of the Go language standard library is used as a storage carrier, which internally implements a read-write separation mechanism, supports multiple Goroutines to simultaneously perform Store (storage), Load (reading), and Delete (deletion) operations, and does not require additional mutual exclusion locks in the business layer to avoid lock competition bottlenecks under high concurrency and ensure nanosecond-level operation performance. The composite key avoids identifier conflicts, sync.Map guarantees concurrent security, atomic increment and snowflake algorithm ensure identifier uniqueness, and the problems of identifier duplication and concurrency conflicts are solved.

[0057] Step 402, updating the concurrent security mapping relationship in real time, and blocking and waiting for the response message of the asynchronous channel after sending the request message.

[0058] In one embodiment, after sending the message, the business layer blocks and waits for the response of the asynchronous channel to achieve a synchronous calling experience. Optionally, the device-side MQTT client publishes the message carrying the MsgId to the target topic, blocks the current business thread (blocked by Goroutine or thread suspension) after successful publication, and waits for channel data. An independent coroutine is started to monitor the blocking time, and if it exceeds the preset timeout threshold (default 10 seconds, configurable), a timeout error (error code Timeout_001, description "request timeout not responded") is written to the channel, and the blocking is released to avoid infinite waiting.

[0059] In one embodiment, the channel state (waiting for response / has responded / has timed out) is recorded in the mapping table, which facilitates subsequent problem troubleshooting, such as querying the MsgId of the unresponsive request through logs. Blocking and waiting achieves a synchronous RPC experience, an independent coroutine monitors the timeout to avoid business thread blocking and deadlocks, and solves the problem that traditional MQTT asynchronous interaction cannot synchronously obtain results.

[0060] Step 403, after receiving the response message sent by the application end, the concurrent security mapping relationship is found based on the message identification in the response message, the response data is obtained, and the blocking state of the asynchronous channel is released.

[0061] In one embodiment, after the application end receives the message, the business logic is processed and the original MsgId is returned with the response. Optionally, the application end subscribes to the exclusive topic, extracts the MsgId, instruction, and business data after receiving the request message, verifies the message integrity, such as checking the CRC32 check code, to prevent message tampering or damage. According to the instruction, the corresponding business logic is executed, such as data storage, device control, and parameter query, and the processing result is generated. If the processing fails, error information such as business logic exception and illegal parameters is recorded. The processing result (success / failure identifier, business data / error information) and the original MsgId are encapsulated as a response message, the response topic is spliced according to “MASTER_TOPIC / p2p / [application end identifier]@@@[device end identifier]”, and is published to the MQTT broker server. The message integrity check ensures data reliability, the separation of business processing and response encapsulation improves scalability, and the response topic carries the original identifier to ensure accurate association, solving the problem of response and request association.

[0062] In one embodiment, the device end subscribes to its own exclusive response topic (such as “iot / devices / p2p / CloudService001@@@Device001”), extracts the MsgId and processing result after receiving the response message. According to the “device end identifier: MsgId” composite key, the sync.Map is searched, the corresponding asynchronous channel is obtained, if not found, it is determined as a timeout or invalid message, such as MsgId error, response delay for too long, directly discarded and recorded in the log. The processing result is written into the channel to wake up the blocked business thread, and the LoadAndDelete atomic operation is called to retrieve the channel object while physically deleting the entry from the Map, avoiding memory leakage and ensuring that each request is processed only once. The exclusive response topic ensures accurate message reception, the composite key lookup improves association efficiency, the atomic operation releases resources to avoid memory leakage, and the complete closed loop of request and response is realized, solving the problems of response loss and resource waste.

[0063] The composite key strategy avoids MsgId conflict, sync.Map supports lock-free concurrent read and write, and realizes asynchronous to synchronous interaction; solves the defect of no response feedback in traditional MQTT asynchronous communication, supports non-blocking for ten thousand-level concurrent requests, and guarantees the orderliness and reliability of interaction.

[0064] Figure 6 is the flowchart of the MQTT broker server delay timeout control provided by the embodiments of the present application, please refer to Figure 6, the timeout control flow based on the MQTT delay topic is a key mechanism to prevent resource leakage, and specifically includes: In step 501, when sending a request message, a timeout trigger message is published to the delay topic of the MQTT broker server, and the timeout trigger message carries the message identifier corresponding to the request message. The delay time of the timeout trigger message is a preset timeout threshold.

[0065] In an embodiment, when the device sends a request message, a timeout trigger message is published to the delay topic of the MQTT broker server synchronously. Optionally, the delay topic adopts a format of “$delayed / [timeout time] / [response topic]”, wherein the timeout time is a preset threshold, such as 10 seconds, which is consistent with the RPC timeout threshold, and the response topic is a dedicated response topic of the device, such as “iot / devices / p2p / CloudService001@@@Device001”. The timeout trigger message is in JSON format and carries the corresponding MsgId, trigger type (timeout), and sending timestamp. The business request message is published as an atomic operation (ensured by transaction or synchronization lock), ensuring that the two operations are either both successful or both failed, thereby avoiding logical inconsistency, such as the business message being sent successfully but the timeout message not being published, resulting in the timeout being unable to be triggered. The atomic operation guarantees logical consistency, the standardized delay topic format is adapted to the MQTT broker server, such as EMQX and Mosquitto, the timeout trigger message carries key identifiers for easy association, and the problem of unsynchronized timeout control and business message is solved.

[0066] In step 502, if no response message returned for the request message is received within the timeout threshold, the timeout trigger message is triggered, the mapping entry corresponding to the message identifier of the request message in the concurrent security mapping relationship is deleted, and a timeout error is returned through the asynchronous channel corresponding to the request message.

[0067] In an embodiment, if no business response message is received within the timeout, the delay message is triggered, the device cleans up the concurrent security mapping relationship and returns a timeout error. Optionally, the MQTT broker server forwards the timeout trigger message to the response topic of the device, such as “iot / devices / p2p / CloudService001@@@Device001”, after a preset timeout time. The device receives the message, identifies it as a timeout message through the “type: timeout” field, extracts the MsgId, and ignores other irrelevant messages.

[0068] In one embodiment, according to MsgId, the sync.Map is searched, the Delete operation is called to delete the corresponding mapping entry (if it exists), a timeout error is written to the corresponding asynchronous channel, the blocked business thread is woken up, and resource release is ensured. The timeout event (MsgId, timeout time, trigger time, and current network state) is recorded to facilitate subsequent analysis of network delay or slow application end processing. The delay topic realizes precise timeout triggering, resource cleaning avoids memory leakage, and the timeout log facilitates problem troubleshooting, solving the problem of no timeout processing or processing not in time.

[0069] Step 503, if a response message returned for the request message is received within the timeout threshold, the mapping entry corresponding to the message identifier carried by the response message in the concurrent security mapping relationship is deleted, and the response data in the response message is normally processed.

[0070] In one embodiment, if a business response message is received before the timeout, the device end ignores the subsequent triggered timeout message. Optionally, after receiving the business response message, the device end searches the mapping according to the process, writes the result, deletes the entry, and unblocks to ensure normal processing of the business. When the timeout trigger message corresponding to the MsgId is received subsequently, the sync.Map is searched and no corresponding entry is found, which is determined as a "processed completed timeout message", which is directly discarded without any side effects, such as repeated error return. The message filtering mechanism avoids repeated processing, ensures that the timeout control does not affect the normal response process, improves the system robustness, and solves the problem of conflict between timeout message and normal response.

[0071] The delay topic is used to realize automatic timeout triggering, the mapping entry cleaning mechanism is used to eliminate memory leakage, the timeout response time is accurately controlled within the preset threshold, resource long-term occupation is avoided, and the stability and resource utilization rate of long-term operation of the system are improved.

[0072] Figure 7 is the flowchart of the double-layer signature security provided by the embodiment of the present application, please refer to Figure 7 , the double-layer security mechanism of transmission layer encryption and application layer signature, which comprehensively guarantees communication security, specifically including: Step 601, a transmission layer encryption channel is constructed based on a transmission layer security protocol.

[0073] In one embodiment, the encrypted channel is constructed based on the TLS 1.3 protocol to ensure security during data transmission. Optionally, after the TCP connection is established, the device end and the MQTT broker server / application end negotiate the TLS version (preferably TLS 1.3, and downgrade to compatible TLS 1.2), and the encryption suite, such as TLS_AES_256_GCM_SHA384, preferably selects a suite with high security and performance. Both parties exchange digital certificates (X.509 v3 format), the device end verifies the signature authority, validity period, and domain name matching of the server certificate, and the server / application end verifies the legality of the device end certificate, and rejects invalid or fake certificates, such as self-signed certificates not in the trust list.

[0074] In one embodiment, the session key is negotiated by the ECDH (Elliptic Curve Diffie-Hellman) algorithm, which is used for subsequent data encryption transmission, and the key is updated regularly (default 30 minutes) to reduce the risk of key leakage; the AEAD (Authenticated Encryption) mode is used during transmission to ensure data confidentiality and integrity. The TLS 1.3 protocol takes into account security and performance, strong encryption suite ensures data confidentiality, certificate verification prevents man-in-the-middle attacks, session key is updated regularly to improve security, and the problem of weak traditional transmission layer security is solved.

[0075] Step 602, using a preset encryption algorithm to hash sign the message load to generate signature information, and carrying the signature information in the user attribute field of the MQTT message.

[0076] In one embodiment, the device end uses a preset algorithm to sign the message load, and embeds the signature information in the user attribute field of the MQTT message. Optionally, the algorithm supports Ed25519 (performance priority) and RSA (compatibility priority) algorithms, and the device end defaults to the Ed25519 algorithm (LoadX25519Secure), which can be switched to RSA-2048 / 4096 through configuration. Among them, Ed25519 is suitable for embedded devices with limited computing power, such as low-end NAS, IoT gateway or high-frequency communication scenarios, the signature / verification speed is fast (several dozen times faster than RSA), the signature length is only 64 bytes, reducing network transmission overhead, and naturally resisting side channel attacks. RSA is suitable for devices that need to interface with old systems or have integrated RSA hardware acceleration engines, and the industrial standard supports are complete, the verification speed is relatively fast, but the signature generation time is long (soft solution may cause CPU occupancy rate to rise under high concurrency).

[0077] In one embodiment, the message load (containing instructions, business data, MsgId) is hashed (Ed25519 with SHA-512, RSA with SHA-256), the hash value is signed using the device private key, and a Base64 encoded signature information is generated. The signature information (Key ID, Base64 encoded signature value, device identification) is packaged as a key-value pair and stored in the User Properties field of MQTT v5.0, with Key as "sign", without affecting the message load structure. The double algorithm is adapted to different scenarios, the SHA-512 / SHA-256 hash improves the anti-collision ability, the Base64 encoding ensures the compatibility of signature transmission, the User Properties field does not affect the message load, and the problem of no signature and difficult to confirm identity at the application layer is solved.

[0078] Step 603, sending the MQTT message carrying the signature information to the application end through the transmission layer encryption channel, so that the application end extracts the signature information from the user attribute field of the MQTT message.

[0079] In one embodiment, the device end sends messages through an encrypted channel to ensure double security of transmission and content. Optionally, the message load (JSON format), User Properties (containing signature information) is packaged as an MQTT message, the QoS level (default 1) and the reserved flag (default not reserved) are set to avoid message duplication or residual. The message is sent to the application end through the TLS encryption channel, and the data is encrypted during transmission. Even if the channel is cracked, the signature can still guarantee that the message has not been tampered with and the sender's identity is legal. Wait for the publication confirmation (QoS1 level) of the MQTT broker server to confirm that the message has been successfully delivered, and if no confirmation is received, retry (default 3 times, interval 1 second) to ensure reliable message sending. The QoS level guarantees message delivery, the encrypted channel and the application layer signature realize double protection, the retry mechanism improves the sending reliability, and the problem of easy loss and tampering of messages is solved.

[0080] Step 604, the application end verifies the validity of the signature information through the pre-set public key, if the verification is passed, it confirms that the sender's identity is legal and receives the request message, and extracts the message load based on the request message, if the verification fails, it determines that the sender's identity is not legal and discards the request message.

[0081] In one embodiment, the application end extracts signature information to verify validity and only processes legal messages. Optionally, the application end extracts signature information corresponding to the "sign" key from the User Properties field after receiving the MQTT message, and parses the KeyID, signature value, and client identifier. According to the Key ID, the corresponding device public key is obtained from the public key library (pre-registered storage, supporting dynamic update), and if the Key ID does not exist, it is determined as an illegal message and discarded directly. The same hash calculation is performed on the message load (consistent with the device end algorithm), the public key is used to verify the validity of the signature value, and if the verification is passed, it is confirmed that the message is complete and the sender's identity is legal, and the business processing flow is entered; if the verification fails, such as hash value mismatch or invalid signature, the message is discarded, and a security alarm is recorded (including sender identifier, message content summary, and failure reason). The public key library centrally manages to improve maintenance efficiency, the signature verification ensures the message integrity and identity legality, the security alarm facilitates timely detection of attack behavior, and the problem of lacking content security verification is solved.

[0082] The TLS transmission encryption and the application layer signature form double protection, support Ed25519 / RSA dual algorithms to adapt to different scenes; effectively resist man-in-the-middle attacks and data tampering, accurate identity authentication, and protect the whole link security of device communication.

[0083] Figure 8 is the flowchart of the master-slave switching retry provided by the embodiment of the application, please refer to Figure 8 The master-slave switching and retry process after connection failure improves the connection stability in a complex network environment, and specifically includes the following steps. Step 701, according to the pre-stored list of backup device access points, select other backup device access points in the order of the list to reconnect when the connection fails.

[0084] In one embodiment, when the current device access point connection fails, the next backup device access point is selected in the pre-stored list order. Optionally, connection timeout (more than 15 seconds), TLS handshake failure, identity authentication failure, MQTT protocol negotiation failure and the like are determined as connection failure, and the failure reason and failure times are recorded. The backup device access point list is read from the device configuration (pre-stored in the encrypted file system, supporting dynamic update), and the list contains the domain name, port and priority of multiple access points, arranged in descending order of priority (default configuration order). The next untried device access point is selected in the list order, and if the current device access point is the last one, it is cycled to the first one (at most 3 times), avoiding infinite loop attempts. Multi-scene failure determination ensures no omission, priority sorting ensures priority use of high-quality device access points, and loop attempt improves the connection success rate, solving the problem of no backup device access point.

[0085] Step 702: Repeat the hierarchical domain name system resolution and MQTT connection request process for each backup device access point until the connection is successful or all backup device access points in the list are traversed.

[0086] In one embodiment, the hierarchical DNS resolution and MQTT connection process is repeated for the selected backup device access point. Optionally, for the domain name of the backup device access point, the target connection address of the MQTT proxy server is obtained according to the hierarchical DNS resolution strategy (native resolution → system resolution → domain name fallback), ensuring that the backup connection also receives DNS acceleration, rather than a simple retrieval. Based on the new target connection address, the connection establishment and authentication process is repeated, using the same device identity configuration information, without the need to reload the configuration. If the backup device access point connection also fails, the failure information (access point domain name, target IP, failure reason) is recorded, and the next backup device access point is selected until the connection is successful or all backup device access points are traversed. This reuses existing resolution and connection logic, reduces development complexity, ensures the connection quality of backup device access points, and solves the problem of non-optimized resolution after switching backup device access points.

[0087] Step 703: If all the device access points in the list fail to connect, then enter sleep mode and retry, and re-initiate the MQTT connection request after a preset interval.

[0088] In one embodiment, if all backup device access points fail to connect, a hibernation and retry process is initiated to avoid frequent retries consuming resources. Optionally, an exponential backoff algorithm is used to calculate the hibernation time, with an initial hibernation time of 5 seconds, doubling after each retry (5 seconds, 10 seconds, 20 seconds, ...), and a maximum hibernation time of 300 seconds (5 minutes) to avoid infinite waiting. The device enters a hibernation state, suspending connection attempts. During this period, some non-essential modules, such as the network detection module, are shut down to reduce CPU and network resource consumption, maintaining only the core processes running.

[0089] In one embodiment, after the hibernation period ends, the connection attempt is restarted from the initial device access point, repeating the primary / backup switchover, hierarchical resolution, and connection process until the connection is successful or the maximum number of retries (default 10) is reached. After reaching the maximum number of retries, the device enters a low-power standby state, periodically (every 30 minutes) to retry, and triggers an alarm (indicator light flashing, log reporting). The exponential backoff algorithm avoids resource waste, the maximum hibernation time prevents infinite waiting, and the cyclic retries ensure eventual connection success, solving the resource exhaustion problem caused by frequent retries.

[0090] Automatically switching to backup access points based on priority, hierarchical resolution process reuse to ensure connection quality, exponential backoff and hibernation to avoid resource waste, and addressing access point failures and network fluctuations, thereby improving connection recovery success rate and enhancing the system's fault tolerance.

[0091] Figure 9 This is a structural diagram of a device connection apparatus based on MQTT provided in an embodiment of this application. Please refer to [link / reference]. Figure 9 The functional modules of the device connection apparatus of this application include a configuration loading module 801, a domain name resolution module 802, a connection establishment module 803, and a communication interaction module 804. These modules work together to achieve complete connection and interaction functions, specifically including: The configuration loading module 801 is used to load and verify device identity configuration information, providing data for subsequent processes. It reads configuration information from encrypted storage media, verifies the integrity and legitimacy of the configuration, caches it in memory, and supports dynamic configuration updates.

[0092] The configuration reading unit reads configuration data from encrypted storage media (flash memory / EEPROM) via a hardware driver interface (SPI / I2C), supporting multiple storage formats (JSON / binary). The configuration verification unit verifies the uniqueness of the device identifier, certificate format and validity period, private key and certificate matching, and access point information legitimacy (domain name format, port range). Verification failure triggers an alarm. The configuration caching unit caches legitimate configuration information in memory (supporting LRU eviction to avoid memory overflow), provides a fast read interface, and supports dynamic configuration updates (receiving configuration update commands pushed from the cloud, verifying signatures, and updating the cache and storage). Multiple storage media adapt to different devices, verification ensures configuration security, memory caching improves access efficiency, and dynamic updates support flexible configuration adjustments, solving the problems of single configuration loading and lack of verification.

[0093] The domain name resolution module 802 is used to implement a hierarchical DNS resolution strategy to obtain the optimal target connection address. Optionally, it can filter the optimal IP and record the resolution status by performing native DNS resolution, system-level DNS resolution, and domain name fallback.

[0094] The native resolution unit implements the DNSLookupInborn interface, initiating queries to pre-configured high-availability DNS servers, handling IP list filtering and optimal IP selection, and supporting IPv4 / IPv6 dual-stack. The system resolution unit calls the system DNS interface, handling fallback queries and result judgment, reusing IP filtering logic. The fallback processing unit, when both native and system resolution fail, falls back to the original domain name, records the reason for failure, and reports it. The resolution log unit records the resolution process (DNS servers attempted, resolution results, IP filtering data, and reasons for failure), and the log supports local storage and cloud reporting. Tiered resolution improves resolution speed and reliability, resolution logs facilitate operation and maintenance, fallback processing ensures process continuity, and solves the problem of a single resolution strategy.

[0095] The connection establishment module 803 is used to initiate an MQTT connection, build an encrypted channel, and complete authentication. Optionally, it initiates a TCP / MQTT connection, negotiates connection parameters, builds a TLS encrypted channel, performs two-way authentication, and handles connection failures.

[0096] The connection initiation unit creates an MQTT client instance, configures the protocol version, heartbeat parameters, and timeout, and initiates a TCP connection and MQTT CONNECT request to the target connection address. The encryption channel unit initializes the TLS context, negotiates the TLS version and cipher suite, verifies certificate validity, negotiates the session key, and builds an encrypted channel. The authentication unit generates application-layer signature information, embeds it into the User Properties field of the MQTT message, receives and verifies the authentication response from the server / application, and handles authentication failures, such as retries and switching access points. The connection monitoring unit monitors the connection status in real time, detects connection drops, and triggers a reconnection process if the heartbeat times out. This standardized connection process adapts to different MQTT servers, strong encryption and authentication ensure connection security, and connection monitoring enables automatic reconnection after a disconnection, resolving issues of connection instability and weak security.

[0097] The communication interaction module 804 is used to implement targeted message passing, RPC interaction, and timeout control to ensure reliable and efficient interaction. Optionally, it constructs targeted topics, generates MsgId and concurrent security mappings, handles request / response interactions, and executes timeout control.

[0098] The topic management unit defines and validates topic formats, generates request / response topics, and manages subscription relationships, such as subscribing to dedicated response topics. The RPC interaction unit generates a unique MsgId (atomic increment + snowflake algorithm), establishes a concurrent safety mapping (sync.Map), and implements asynchronous-to-synchronous interaction (blocking wait - response wake-up). The timeout control unit publishes timeout trigger messages, handles timeout events (cleaning up mappings, returning errors), and filters invalid timeout messages. The message processing unit receives response messages, extracts the MsgId and result, finds the mapping relationship, wakes up the business thread, and cleans up resources. Topic management ensures targeted message delivery, the RPC interaction unit addresses the asynchronous limitations of MQTT, the timeout control unit prevents resource leaks, and the message processing unit ensures accurate result feedback, thus improving the overall reliability and efficiency of interaction.

[0099] Each module has a clear division of labor and a loosely coupled design, supporting independent updates and extensions. Configuration loading ensures information security, domain name resolution improves connection speed, connection establishment strengthens security protection, communication interaction ensures reliable interaction, and collaboration enables efficient and stable device connection.

[0100] Figure 10 This is a structural diagram of an electronic device provided in an embodiment of this application. Please refer to it. Figure 10The hardware structure of the electronic device described in this application, which can integrate the MQTT-based device connection device of this application, ensures efficient system operation through the collaborative work of hardware components, specifically including: The electronic device includes a processor 901, a memory 902, an input device 903, an output device 904, and a communication module (integrating network communication and MQTT communication functions). All components are connected via industrial-grade buses, such as PCIe, USB 3.0, and SPI, to achieve data transmission and command interaction. Processor 901 is used to run software programs and modules in memory 902, coordinate the work of various hardware components, and realize MQTT-based device connection functions. Optionally, an appropriate processor is selected according to the device type. On the device side, such as NAS and IoT gateway, a high-performance multi-core CPU, such as Intel Core i5 / i7, AMD Ryzen 5 / 7, ARM Cortex-A53 / A72, is used to support multi-threaded concurrent processing and meet the high-performance requirements of parsing, encoding, encryption, and instruction execution. Cloud servers use server-grade CPUs, such as Intel Xeon and AMD EPYC, with ≥16 cores and a main frequency ≥2.4GHz, supporting millions of concurrent device access and data relay.

[0101] It runs software programs for configuration loading, domain name resolution, connection establishment, and communication interaction, and controls the collaborative work of various modules. For example, it coordinates the data flow transmission between the configuration loading module and the memory, schedules the network connection and data transmission and reception of the communication module, and allocates hardware resources, such as GPU for TLS acceleration and encryption module for signature / verification acceleration, to ensure that the various functions of the system are implemented efficiently and collaboratively.

[0102] It supports hardware acceleration technology. On the device side, GPUs, such as NVIDIA CUDA and AMD OpenCL, are used to accelerate TLS encryption and decryption, video encoding and decoding, and reduce CPU utilization. On the server side, network card multi-queue and hardware interrupt balancing technologies are used to improve network data processing efficiency. On the device side, DSPs (Digital Signal Processors) are used to accelerate speech recognition and noise filtering (if voice control is involved), improving processing speed and accuracy. Differentiated processor selection adapts to different device requirements, multi-threading and hardware acceleration ensure high-performance system operation, and resource scheduling optimization improves component collaboration efficiency, solving the problems of insufficient hardware performance and unreasonable resource allocation in traditional devices.

[0103] The memory 902 is used to store software programs, configuration information, cached data, log data, etc., providing data support for the processor 901 and functional modules. Optionally, an appropriate memory is configured according to the device type. For devices, RAM ≥ 4GB (high-speed DDR4 / DDR5), SSD ≥ 128GB, or flash memory ≥ 32GB are configured to ensure the storage and fast access requirements of configuration information, cached data, and software programs; for servers, RAM ≥ 64GB and SSD ≥ 2TB are configured to meet the needs of large amounts of session data, data stream caching, and log storage.

[0104] The storage is divided into a system area (storing the operating system and core software), an application area (storing the storage device connection program), a cache area (storing DNS resolution results, concurrent mapping tables, and message cache), a log area (storing connection logs, interaction logs, and error logs), and a configuration area (storing the storage device identity configuration information and a list of backup access points). This partitioned management improves the orderliness and security of storage and avoids interference between different types of data.

[0105] It supports encrypted data storage, such as SSD hardware encryption and software AES-256 encryption, protecting configuration information, log data, and cached sensitive data from unauthorized access. It also supports data backup and recovery functions, automatically backing up critical configurations and log data periodically to prevent data loss. The server adopts a distributed storage architecture to ensure high availability of session data and data streams. Large-capacity, high-speed storage meets the storage needs of different devices, partition management improves storage orderliness, encryption and backup ensure data security, and distributed storage enhances server data availability, solving the problems of insufficient storage and lack of data security in traditional devices.

[0106] Input device 903 is used to receive user input or external configuration data and provide a parameter configuration interface for device connection. Optionally, the device-side input device includes buttons, a touch screen, a USB interface, and a network interface. Users can configure access point information, timeout thresholds, and other parameters through buttons or the touch screen, import certificates and private keys through the USB interface, and receive configuration update commands pushed from the cloud through the network interface.

[0107] Server input devices include a keyboard, mouse, and remote management terminal, such as an SSH client. Administrators can configure server parameters, such as the maximum number of concurrent connections, latency topic prefix, log storage policy, monitor server operating status, and troubleshoot problems through the remote management terminal.

[0108] It receives user-input parameters, such as access point domain name, port, and timeout, converts them into electrical signals recognizable by the device, and transmits them to the processor 901 to update the configuration. It supports parameter verification, such as port range 1-65535 and timeout ≥ 1 second, to prevent illegal input from causing system anomalies. Diverse input methods adapt to different configuration scenarios, parameter verification ensures configuration legitimacy, and configuration updates are convenient and flexible, solving the problems of traditional devices having limited configuration methods and complex operations.

[0109] Output device 904 is used to output device operating status, configuration information, and alarm information, providing users with visual feedback. Optionally, the device-side output device includes indicator lights, a display screen, a buzzer, and a network interface. The indicator lights are used to display the connection status (solid green light = normal connection, solid red light = connection failure, flashing yellow light = retrying), the display screen is used to display configuration information, parsing results, and log summaries, the buzzer is used for alarms, such as sounding when authentication fails or configuration is abnormal, and the network interface is used to report operating status and logs to the cloud.

[0110] The server output devices include a monitor, indicator lights, and a log server interface. The monitor displays the server operation monitoring interface (CPU / memory usage, concurrent connections, data transfer rate), the indicator lights display the server operating status (power light, network light, fault light), and the log server interface synchronizes logs to a dedicated log server for centralized management and analysis.

[0111] It outputs real-time device operating status (parsing status, connection status, interaction status), configuration information (device identifier, access point address, timeout threshold), and alarm information (failure reason, error code), facilitating user viewing and troubleshooting. It supports alarm tiering (general alarms = log notifications, critical alarms = indicator lights + buzzers + cloud reporting), improving fault response efficiency. Multiple output formats meet diverse feedback needs; real-time status display facilitates monitoring; and the alarm mechanism promptly alerts to anomalies, solving the problems of opaque device status and difficult fault diagnosis inherent in traditional devices.

[0112] Differentiated hardware selection adapts to terminals and servers, large-capacity high-speed storage ensures data security, diversified inputs and outputs facilitate configuration and monitoring, hardware acceleration technology reduces CPU utilization, distributed storage improves server availability, and provides stable hardware support for device connectivity.

[0113] In one embodiment, the computer-readable storage medium provided in this application adopts a high-speed Flash memory, SSD, or cloud storage medium with a capacity of ≥32GB (device-side) or ≥2TB (server), supports a wide operating temperature range of -40℃ to 85℃ (industrial-grade scenarios), and has characteristics such as power failure prevention, electromagnetic interference resistance, and high durability (flash memory ≥100,000 erase and write cycles). The storage medium stores computer-readable instructions, which are organized in a modular structure and include execution code for core functions such as configuration loading, domain name resolution, connection establishment, communication interaction, and security protection. At the same time, it stores basic data such as system configuration parameters, instruction mapping library, device identification information, session token, and log template.

[0114] When the processor executes the above instructions, it starts the corresponding functional module according to the device type (device / server). Optionally, the device-side initialization configuration loading module loads and verifies the device identity configuration information; the domain name resolution module starts, performs hierarchical DNS resolution to obtain the target connection address; the connection establishment module starts, initiates an MQTT connection and authenticates through a two-layer security mechanism; the communication interaction module starts, transmits messages based on targeted topics, achieves synchronous interaction through the RPC mechanism, and uses delayed messages to complete timeout control; if the connection fails, it initiates the primary / backup switchover and sleep retry process to ensure connection stability.

[0115] The server-side initializes the session management module to maintain device connection status and session association; it starts the data relay module to forward messages (business messages, timeout trigger messages) between the device and the application; it starts the command routing module to accurately forward response messages based on MsgId and device identifier; and it starts the log module to record device connection, interaction, and error logs, supporting log querying and export. This storage medium supports hot-swapping (device-side) and online expansion (server-side) to adapt to deployment needs of different scales; encrypted storage and backup mechanisms ensure data security and prevent leakage and loss; it is compatible with multiple operating systems such as Windows, Linux, Android, iOS, and VxWorks, and can be directly deployed on various electronic devices without additional driver installation, effectively supporting the stable implementation of MQTT-based device connection functions and improving device deployment flexibility and maintenance convenience.

[0116] The above description is merely a preferred embodiment and the technical principles employed in this application. This application is not limited to the specific embodiments provided herein, and various obvious changes, readjustments, and substitutions that can be made by those skilled in the art will not depart from the scope of protection of this application. Therefore, although this application has been described in detail through the above embodiments, this application is not limited to the above embodiments, and may include many other equivalent embodiments without departing from the concept of this application, the scope of which is determined by the scope of the claims.

Claims

1. A method for connecting devices based on MQTT, characterized in that, The method comprises: loading device identity configuration information; based on the device identity configuration information, resolving the device access point interface through the native domain name system and querying the domain name of the device access point information, if the resolution is successful, returning the public network optimal IP as the target connection address of the MQTT proxy server; if the resolution fails, resolving the device access point interface using the system-level domain name system, and returning the system-level IP as the target connection address of the MQTT proxy server; based on the target connection address, initiating an MQTT connection request, and completing identity authentication and connection establishment with the application end through an encrypted channel; in the case of successful identity authentication and connection establishment, directing the message transmission based on the MQTT set topic format with the application end, wherein, in the process of directing the message transmission, a message identifier is generated for each request message, a concurrent secure mapping relationship between the message identifier and the asynchronous channel is established, and the interaction of request and response is realized based on the secure mapping relationship; a timeout trigger message of the message identifier is published to the MQTT proxy server when sending a request message, and a timeout control operation is performed based on the timeout trigger message.

2. The MQTT-based device connection method of claim 1, wherein, The device identity configuration information includes device identification, certificate, private key and device access point information; The native domain name system is called to resolve the device access point interface, and a query command is initiated to the domain name of the device access point information to the preset domain name system server; If the native domain name system resolution is successful, the public network IP list is obtained based on the query command, and the optimal IP is selected as the target connection address of the MQTT proxy server according to the public network IP list; If the native domain name system resolution fails, the system-level domain name system is called to resolve the device access point interface, and a degraded query is performed on the domain name of the device access point information; If the system-level domain name system resolution is successful, the system-level IP returned by the system-level domain name system is used as the target connection address of the MQTT proxy server; If the native domain name system and the system-level domain name system both fail to resolve, the original domain name of the device access point information is used as the target connection address of the MQTT proxy server. The message is directed and transmitted based on the MQTT set topic format with the application end, comprising: defining a topic format containing a target identifier, the topic format including a device end identifier and a target party identifier field; 3. The MQTT-based device connection method of claim 1, wherein, sending a request message to the topic format containing the target party identifier, so that the application end subscribes to the topic format containing the target party identifier, and realizes the directed transmission of the request message. ​ ​ 4. The MQTT-based device connection method of claim 1, wherein, The message identifier is generated for each request message, and a concurrent security mapping relationship between the message identifier and the asynchronous channel is established, and the interaction of request and response is realized based on the security mapping relationship, including: A message identifier is generated for each request message, and a concurrent security mapping relationship between the message identifier and the asynchronous channel is established and stored, wherein the message identifier is carried in the message load, and the message load is a structured data carrier containing request instructions, business data and the message identifier; The concurrent security mapping relationship is updated in real time, and after sending the request message, the response message of the asynchronous channel is blocked and waited; After receiving the response message sent by the application end, the message identifier in the response message is used to search the concurrent security mapping relationship, obtain the response data and release the blocking state of the asynchronous channel.

5. The MQTT-based device connection method of claim 1, wherein, The timeout trigger message of the message identifier is published to the MQTT broker server when sending the request message, and timeout control operation is performed based on the timeout trigger message, including: When sending the request message, a timeout trigger message is published to the delay topic of the MQTT broker server, the timeout trigger message carries the message identifier corresponding to the request message, and the delay time of the timeout trigger message is a preset timeout threshold; If no response message is received within the timeout threshold, the timeout trigger message is triggered, the corresponding mapping entry in the concurrent security mapping relationship corresponding to the message identifier of the request message is deleted, and a timeout error is returned through the asynchronous channel corresponding to the request message; If a response message is received within the timeout threshold, the mapping entry in the concurrent security mapping relationship corresponding to the message identifier carried in the response message is deleted, and the response data in the response message is processed normally.

6. The MQTT-based device connection method of claim 1, wherein, The identity authentication and connection establishment with the application end are completed through the encrypted channel, including: A transport layer encryption channel is constructed based on the transport layer security protocol; A preset encryption algorithm is used to hash sign the message load to generate signature information, and the signature information is carried in the user attribute field of the MQTT message; The MQTT message carrying the signature information is sent to the application end through the transport layer encryption channel, so that the application end extracts the signature information from the user attribute field of the MQTT message; The application end verifies the validity of the signature information through the preset public key, and if the verification is passed, it confirms that the sender's identity is legal and receives the request message, extracts the message load based on the request message, and if the verification fails, it is determined that the sender's identity is illegal and the request message is discarded.

7. The MQTT-based device connection method according to any one of claims 1-5, wherein, After initiating the MQTT connection request based on the target connection address and completing the identity authentication and connection establishment with the application end through the encrypted channel, it further includes: If the connection establishment fails, switch to the backup device access point, repeat the hierarchical domain name system resolution process and the MQTT connection request process to complete the connection establishment with the application end; The switching to the backup device access point includes: According to a pre-stored list of backup device access points, when a connection fails, other backup device access points are selected in the order of the list for reconnection; The hierarchical domain name system resolution and the MQTT connection request process are repeated for each backup device access point until a connection is successful or all backup device access points in the list are traversed; If all device access points in the list fail to connect, a sleep retry is entered, and after a preset time interval, an MQTT connection request is reinitiated.

8. An MQTT-based device connection apparatus, characterized by, Comprise: A configuration loading module for loading device identity configuration information; A domain name resolution module for resolving a device access point interface and querying a domain name of device access point information based on the device identity configuration information, returning a public network optimal IP as a target connection address of an MQTT proxy server if the resolution is successful, and using a system-level domain name system to resolve the device access point interface and returning a system-level IP as the target connection address of the MQTT proxy server if the resolution fails; A connection establishment module for initiating an MQTT connection request based on the target connection address and completing identity authentication and connection establishment with an application end through an encrypted channel; A communication interaction module for, in the case that the identity authentication and connection establishment are successful, directing message delivery based on a topic format set by MQTT with the application end, wherein, in the process of the directed message delivery, a message identifier is generated for each request message, a concurrent secure mapping relationship between the message identifier and an asynchronous channel is established, and the secure mapping relationship is used to realize request and response interaction; a timeout trigger message of the message identifier is published to the MQTT proxy server when a request message is sent, and a timeout control operation is performed based on the timeout trigger message.

9. An electronic device, comprising: Comprise: A memory and one or more processors; The memory is configured to store one or more programs; When the one or more programs are executed by the one or more processors, the one or more processors implement the MQTT-based device connection method according to any one of claims 1-7.

10. A computer-readable storage medium, characterized in that, The computer readable storage medium stores computer readable instructions, and the computer readable instructions are executed by a processor to implement the MQTT-based device connection method according to any one of claims 1-7.

Citation Information

Patent Citations

  • MQTT server concurrent test method, system, device and medium

    CN116527537A

  • Method and system for MQTT to bear VPN

    CN119449528A

  • MQTT message security protection method and device based on multilayer protection mechanism, and medium

    CN120979824A

  • Dynamic message theme adaptation method, system and device and storage medium

    CN121309629A