Protocol conversion method, storage medium and computer device
Patent Information
- Application Number
- CN202611478671.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-22
- Publication Date
- 2026-10-30
AI Technical Summary
[0005]本申请主要提供一种协议转换方法、存储介质及计算机设备,旨在解决现有的物联网协议转换方法中协议转换逻辑与业务处理逻辑扩展维护困难,以及协议转换能力依赖云端服务器的规则下发、难以适应智慧畜牧物联网系统中网络波动或断线场景的技术问题
[0016]本申请的有益效果是:区别于现有技术的情况,本申请公开了一种协议转换方法、存储介质及计算机设备。本申请通过扫描标注有组件注解的协议转换器类并实例化收集,根据源协议类型与目标协议类型生成注册键注册至转换器注册表,并依次在转换器缓存、转换器注册表与全局转换器列表中逐级查找目标协议转换器,由目标协议转换器根据转换方向标识执行正向转换流程或反向转换流程,实现了协议转换逻辑与业务逻辑的完全解耦,业务层仅需通过一次调用即可完成协议转换,底层协议差异对业务层完全透明,解决了协议转换逻辑与业务处理逻辑扩展维护困难的技术问题;通过在同一个协议转换器中同时支持正向转换流程与反向转换流程,消除了传统方案中上行转换与下行转换分别编写两套代码的冗余问题;通过逐级查找机制,在大多数场景下通过缓存命中即可获取目标协议转换器,避免了线性遍历的性能开销;通过同一注册键下多个版本的协议转换器共存并按优先级排序,以及在转换失败时自动降级至下一优先级的协议转换器实例,实现了协议版本的平滑演进,单一版本的协议转换器出现兼容性缺陷或运行异常时不会中断协议转换服务,保障了协议转换的连续性;此外,协议转换器类及其类型信息均部署并确定于边缘计算节点本地,协议转换无需从服务器下载协议转换规则配置文件,即使在与云端服务器通信中断的场景下,边缘计算节点仍能够在本地完成设备侧与平台侧之间的协议转换,解决了协议转换能力依赖云端服务器的规则下发、难以适应网络波动或断线场景的技术问题。通过本申请方法提高了协议转换系统的可维护性和可扩展性,有利于在智慧畜牧等物联网场景下实现高效、稳定的异构协议适配。
Smart Images

Figure CN123020680A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of Internet of Things (IoT) technology, and in particular to a protocol conversion method, storage medium, and computer device. Background Technology
[0002] In modern smart livestock IoT systems, a three-tier "cloud-edge-device" architecture is commonly adopted to establish a data link between on-site equipment and upper-level management platforms. As a crucial hub bridging the gap between upstream and downstream, edge computing nodes need to connect to various heterogeneous hardware devices within the farm, such as smart feeders and environmental sensors based on low-power Bluetooth mesh networks. These devices typically communicate using custom, compact data protocols. Upstream, they need to interface with multiple cloud management platforms with varying functions or origins, such as livestock management platforms, smart agriculture platforms, or third-party collaborative platforms. Because the device and platform sides evolve independently, their agreed-upon data formats, field hierarchies, enumeration definitions, and semantic mappings differ, creating a complex situation of heterogeneous bidirectional protocols. For example, the message type encoding and status field values of alarm status messages reported by the device are completely inconsistent with the data structure expected by the platform. To achieve bidirectional data flow in such a heterogeneous environment, the most common approach in the industry is for developers to manually write tightly coupled procedural conversion logic in the business code of each message processor for each specific data format conversion requirement. This logic uses field-by-field assignment and conditional branching to translate and assemble data between the two heterogeneous protocols.
[0003] However, the current implementation method of tightly coupling protocol conversion logic with business processing logic through hard coding has exposed many obvious limitations and technical problems in practical applications. First, the conversion logic is scattered and embedded in dozens of different message processors, resulting in high code coupling. Even a small change in the protocol on any side requires multiple processors to be checked and modified one by one, leading to a large scope of regression testing and extremely high maintenance risks. Second, redundancy is serious. A large number of common basic conversion logics (such as time format conversion and enumeration value mapping) are repeatedly written in different processors, which not only increases the amount of code but also reduces the overall consistency of the system. Furthermore, conventional development often only focuses on the one-way conversion of data reporting. When the reverse conversion of downlink commands is required, a set of code with reverse logic but similar functionality must be rewritten, resulting in low efficiency of repetitive development. In addition, the system's scalability is obviously insufficient. When it is necessary to interface with a new platform or adapt to a new device protocol, it is often only possible to add more conditional branches to the existing code or create new processing classes, resulting in an increasingly bloated system and a long time to launch new features. Finally, regarding the high availability of the system, this hard-coded mode does not support the coexistence of multiple historical versions under the same conversion path, cannot achieve seamless upgrades of the protocol, and any adjustment or addition / deletion of conversion logic requires recompiling and deploying the entire service, resulting in interruption of ongoing device communication and making it difficult to meet the service continuity requirements in livestock farming scenarios.
[0004] In addition, another existing IoT protocol conversion solution uses cloud-based rule distribution to expand protocol support: a server deployed in the cloud maintains the protocol conversion rule configuration file, and the edge gateway downloads and updates the configuration file from the server before each protocol conversion, then parses the file to generate the corresponding converter. While this solution expands the protocol compatibility range, its protocol conversion capability relies on real-time communication between the edge and cloud servers. In application scenarios with limited network conditions, such as farms, protocol conversion will fail to execute properly if network fluctuations or disconnections occur. Furthermore, in this type of solution, one conversion path typically corresponds to only one converter generated from the configuration file, making it impossible to retain multiple versions of the converter under the same conversion path, and difficult to automatically switch when conversion fails. This is not conducive to meeting the business continuity requirements of hundreds of devices continuously online in farms. Summary of the Invention
[0005] This application mainly provides a protocol conversion method, storage medium, and computer device, aiming to solve the technical problems of existing Internet of Things (IoT) protocol conversion methods, such as the difficulty in expanding and maintaining the protocol conversion logic and business processing logic, and the difficulty in adapting to network fluctuations or disconnection scenarios in smart livestock IoT systems due to the reliance on cloud server rule distribution for protocol conversion capabilities.
[0006] To solve the above-mentioned technical problems, the technical solution adopted in this application is: to provide a protocol conversion method, which is applied to the edge computing node in the smart livestock Internet of Things system, wherein the edge computing node communicates with the equipment in the farm and multiple heterogeneous cloud platforms on the platform side. The protocol conversion method includes: during the system initialization phase, scanning protocol converter classes annotated with component annotations, instantiating the protocol converter classes into protocol converter instances and collecting them into a list of discovered converters; the protocol converter classes are deployed locally on the edge computing node, and the protocol converter instances correspond to source protocol type and target protocol type, which are determined by the generic parent class type information of the protocol converter class; the protocol converter instances are instantiated locally by the edge computing node without downloading protocol conversion rule configuration files from the server; for each protocol converter instance in the list of discovered converters, a registration key is generated based on the source protocol type and target protocol type of the protocol converter instance, and the protocol converter instance is registered to the converter list corresponding to the registration key in the converter registry and added to the global converter list; wherein, protocol converter instances in the converter list corresponding to the same registration key correspond to different version numbers and are sorted from high to low priority; receiving protocol conversion requests; the protocol conversion requests carry source protocol objects, target protocol type identifiers, and conversion direction identifiers; according to the... The source protocol object type and the target protocol type identifier are sequentially searched in the converter cache, the converter registry, and the global converter list for the target protocol converter. When a converter matching the registration key is found precisely in the converter registry, the target protocol converter is the highest-priority protocol converter instance in that list. Using the found target protocol converter, a forward or reverse conversion process is executed according to the conversion direction identifier, outputting the converted protocol object. The forward conversion process converts the source protocol object to the target protocol object, and the reverse conversion process converts the target protocol object back to the source protocol object. Executing the forward or reverse conversion process includes: when the target protocol converter fails to convert, recording a degradation log and switching to the next highest-priority protocol converter instance in the converter list according to priority from high to low to continue conversion; until conversion succeeds, or all protocol converter instances in the converter list fail to convert, an exception carrying an error code, source protocol type, target protocol type, and failure reason information is thrown.
[0007] In some embodiments, the forward conversion process and the reverse conversion process are defined through a template method base class; the template method base class declares the forward conversion process and the reverse conversion process as non-overridable, and sequentially includes pre-validation, preprocessing, core conversion, post-processing, and post-validation; the core conversion includes core forward conversion and core reverse conversion, implemented by subclasses of the template method base class; the pre-validation, preprocessing, post-processing, and post-validation are provided with default implementations by the template method base class, and the subclasses override them as needed; the execution of the forward conversion process or the reverse conversion process, outputting the converted protocol object, includes: when the conversion direction is identified as forward conversion, sequentially executing pre-validation of the source protocol object, preprocessing of the source protocol object, execution of core forward conversion, post-processing of the target protocol object, and post-validation of the target protocol object; when the conversion direction is identified as reverse conversion, sequentially executing pre-validation of the target protocol object, preprocessing of the target protocol object, execution of core reverse conversion, post-processing of the source protocol object, and post-validation of the source protocol object.
[0008] In some embodiments, obtaining the generic parent class type information of the protocol converter class through reflection to determine the source protocol type and the target protocol type includes: determining whether the generic parent class type is a parameterized type; when it is determined to be a parameterized type, extracting the actual type parameters in the parameterized type, setting the first type parameter as the source protocol type, and setting the second type parameter as the target protocol type; when it is determined not to be a parameterized type, throwing an exception to prompt the protocol converter class that generic parameters must be specified.
[0009] In some embodiments, registering the protocol converter instance to the converter list corresponding to the registration key in the converter registry and adding it to the global converter list includes: in the initialization callback, iterating through each protocol converter instance in the discovered converter list; checking if the protocol converter instance is empty, and skipping if it is empty; checking the enabled status of the protocol converter instance, and skipping if it is disabled; generating a registration key through the source protocol type and target protocol type of the protocol converter instance; adding the protocol converter instance to the converter list corresponding to the registration key in the converter registry and sorting them from high to low priority; and adding the protocol converter instance to the global converter list.
[0010] In some embodiments, the stepwise search for the target protocol converter includes: generating a cache key based on the type of the source protocol object and the target protocol type identifier; searching in the converter cache using the cache key; if a cache match is found, directly returning the cached protocol converter; if a cache miss is not found, performing an exact match search in the converter registry using the cache key; if a corresponding converter list is found, retrieving the highest priority protocol converter from the converter list, writing it into the converter cache, and returning; if no exact match is found, traversing the global converter list, performing a compatibility check on each protocol converter, selecting the highest priority among all compatible protocol converters, writing it into the converter cache, and returning; if no match is found in any stepwise search, throwing an exception; the exception carries an error code and source protocol type and target protocol type information.
[0011] In some embodiments, after registering the converters corresponding to the registration keys in the converter registry and adding them to the global converter list, the method further includes at least one of the following: receiving new protocol converter instances, generating registration keys and adding them to the converter registry and the global converter list, sorting them from high to low priority; the new protocol converter instances take effect immediately; receiving protocol converter instances to be removed, removing them from the converter registry and the global converter list, and clearing the converter cache to prevent dirty reads; clearing the converter registry, the converter cache, and the global converter list, and re-executing the initialization callback for full re-registration.
[0012] In some embodiments, before receiving the protocol conversion request, the method further includes: receiving a message through a message processor, parsing the message payload and performing business logic processing, and determining whether protocol conversion is required; if so, generating the protocol conversion request; after outputting the converted protocol object, the method further includes: sending the converted protocol object to the other system; wherein the message processor shares the same protocol converter instance when executing the forward conversion process and the reverse conversion process.
[0013] In some embodiments, the stepwise search for the target protocol converter includes: when the converter list corresponding to the registration key is precisely matched in the converter registry, returning the highest priority protocol converter instance in the converter list; when the highest priority protocol converter instance is removed, returning the next highest priority protocol converter instance in the converter list when searching again.
[0014] To address the aforementioned technical problems, another technical solution adopted in this application is to provide a storage medium. This storage medium stores program data, which, when executed by a processor, implements the steps of the aforementioned protocol conversion method.
[0015] To solve the above-mentioned technical problems, another technical solution adopted in this application is to provide a computer device. This computer device includes a processor and a memory interconnected, the memory storing a computer program, and when the processor executes the computer program, it implements the steps of the above-described protocol conversion method.
[0016] The beneficial effects of this application are as follows: Unlike existing technologies, this application discloses a protocol conversion method, storage medium, and computer device. This application collects and instantiates protocol converter classes annotated with component annotations, generates registration keys based on the source and target protocol types, registers them in the converter registry, and sequentially searches for the target protocol converter in the converter cache, converter registry, and global converter list. The target protocol converter then executes either a forward or reverse conversion process based on the conversion direction identifier. This achieves complete decoupling of protocol conversion logic and business logic. The business layer only needs to complete the protocol conversion with a single call, and the underlying protocol differences are completely transparent to the business layer, solving the technical problem of difficult expansion and maintenance of protocol conversion logic and business processing logic. By supporting both forward and reverse conversion processes simultaneously within the same protocol converter, it eliminates the redundancy problem of writing two separate sets of code for uplink and downlink conversion in traditional solutions. Through the step-by-step search mechanism, in most scenarios… The target protocol converter can be obtained by caching, avoiding the performance overhead of linear traversal. By allowing multiple versions of protocol converters under the same registration key to coexist and be prioritized, and by automatically downgrading to the next lower priority protocol converter instance when a conversion fails, smooth evolution of protocol versions is achieved. Protocol conversion services are not interrupted when a single version of the protocol converter has compatibility defects or malfunctions, ensuring the continuity of protocol conversion. Furthermore, the protocol converter class and its type information are deployed and determined locally on the edge computing node. Protocol conversion does not require downloading protocol conversion rule configuration files from the server. Even in scenarios where communication with the cloud server is interrupted, the edge computing node can still complete the protocol conversion between the device side and the platform side locally, solving the technical problems of protocol conversion capabilities relying on cloud server rule distribution and difficulty adapting to network fluctuations or disconnection scenarios. This application's method improves the maintainability and scalability of the protocol conversion system, which is beneficial for achieving efficient and stable heterogeneous protocol adaptation in IoT scenarios such as smart animal husbandry. Attached Figure Description
[0017] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort, wherein: Figure 1 This is a flowchart illustrating an embodiment of the protocol conversion method provided in this application; Figure 2 This is a schematic diagram of the structure of an embodiment of the storage medium provided in this application; Figure 3 This is a schematic diagram of the structure of an embodiment of the computer device provided in this application. Detailed Implementation
[0018] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of the embodiments. Based on the embodiments of this application, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the scope of protection of this application.
[0019] The terms "first," "second," and "third" used in the embodiments of this application are for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Thus, a feature defined as "first," "second," or "third" may explicitly or implicitly include at least one of that feature. In the description of this application, "multiple" means at least two, such as two, three, etc., unless otherwise explicitly specified. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion. For example, a process, method, system, product, or device that includes a series of steps or units is not limited to the listed steps or units, but may optionally include steps or units not listed, or may optionally include other steps or units inherent to these processes, methods, products, or devices.
[0020] In this document, the term "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of this application. The appearance of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a mutually exclusive, independent, or alternative embodiment. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.
[0021] This application provides a protocol conversion method, see reference. Figure 1 , Figure 1 This is a flowchart illustrating an embodiment of the protocol conversion method provided in this application. The protocol conversion method is applied to an edge computing node in a smart livestock IoT system. This edge computing node communicates with equipment within the farm and multiple heterogeneous cloud platforms on the platform side. The protocol conversion method includes: Step 10: During system initialization, scan for protocol converter classes annotated with component annotations, instantiate these classes into protocol converter instances, and collect them into the list of discovered converters. Each protocol converter instance corresponds to a source protocol type and a target protocol type. The protocol converter class and its conversion logic are deployed locally on the edge computing node. The protocol converter instance is instantiated locally by the edge computing node, and the source and target protocol types are determined by the generic parent class type information of the protocol converter class, eliminating the need to download protocol conversion rule configuration files from the server.
[0022] In this embodiment, the system initialization phase refers to the stage during application startup where container construction, component scanning, and instance injection are completed. Taking an edge computing node as an example, upon startup, it enters the system initialization phase. The component management framework traverses all class files under the classpath, identifies classes annotated with component annotations, and completes instantiation and dependency injection. At this time, the protocol converter has not yet participated in protocol conversion; it is only in the discovery and collection state. The system initialization phase is not limited to edge computing nodes; other computing devices such as IoT gateways and servers also enter the system initialization phase upon startup, completing the discovery and collection of protocol converters.
[0023] In this embodiment, the protocol converter class and its corresponding conversion logic are deployed locally on the edge computing node. The edge computing node completes the scanning, instantiation, and type inference locally. The protocol conversion does not rely on downloading the protocol conversion rule configuration file from the server, nor does it rely on real-time communication between the edge computing node and the cloud server. Therefore, in scenarios where the farm network fluctuates, bandwidth is limited, or there is a temporary disconnection, the data reported by the device side and the instructions issued by the platform side can still be converted locally on the edge computing node, ensuring the continuity of the protocol conversion service in the smart livestock IoT system.
[0024] In this embodiment, the protocol converter class is a program class that encapsulates the bidirectional conversion logic between a pair of protocol types. Each protocol converter class corresponds to a source protocol type and a target protocol type. The source protocol type represents the protocol data type before conversion, and the target protocol type represents the protocol data type after conversion. The protocol converter class declares its corresponding source and target protocol types at compile time using generic parameters, enabling type checking to be completed at compile time and avoiding runtime type conversion exceptions. A protocol converter instance is an object instantiated from the protocol converter class at runtime, supporting forward conversion (denoted as convert(S)→T) and reverse conversion (denoted as reverseConvert(T)→S). The forward conversion process converts the source protocol object to the target protocol object, and the reverse conversion process converts the target protocol object back to the source protocol object. By supporting both forward and reverse conversions simultaneously within the same protocol converter instance, the redundancy problem of writing two separate sets of code for uplink and downlink conversions in traditional solutions is eliminated.
[0025] In this embodiment, component annotations are metadata markers used to mark a class as a component that can be managed by the component management framework. Classes annotated with component annotations are automatically discovered by the component management framework during system initialization. The framework calls the class's constructor to instantiate the class and incorporates the instantiated object into the framework's container management. Component annotations can be implemented in various ways. For example, the first type is annotation-based component marking (such as the `@Component` annotation in the Spring framework), marking components by adding annotations to class declarations; the second type is configuration file-based component declaration, marking components by declaring the fully qualified name of the class in the configuration file. Both of these implementations enable the component management framework to automatically discover and instantiate the protocol converter class during system initialization.
[0026] In this embodiment, scanning refers to the process of traversing class files under a specified package path during the system initialization phase and identifying classes annotated with component annotations. The specific implementation of scanning is as follows: the component management framework reads class files under the specified package path, parses the annotation information of the class files, and identifies the class as a manageable component when it is annotated with a component annotation. During the scanning process, the component management framework loads class files through a class loader and reads the annotation information of the classes through reflection, without requiring manual registration or configuration by developers. The scanning can be implemented in several ways. For example, the first type of implementation is a recursive scan based on the package path, traversing all class files under the specified package and its sub-packages; the second type of implementation is a scan based on the class path index, quickly locating classes annotated with component annotations through a pre-built class path index. Scanning solves the problem in traditional solutions where adding a converter requires manual registration in a configuration file or factory class, achieving automatic discovery of protocol converters.
[0027] In this embodiment, instantiation refers to the process of creating a protocol converter instance by calling the constructor of the protocol converter class. During instantiation, the component management framework first obtains the constructor of the protocol converter class through reflection, and then calls the constructor to create the protocol converter instance. The constructor of the template method base class is called during this process, and the generic parameter types declared by the subclass are obtained through reflection to determine the source protocol type and the target protocol type and cache them in the instance's member variables. Instantiation solves the problem of manually coding the creation of converter objects and the setting of type information in traditional solutions, with the framework uniformly completing object creation and type information initialization.
[0028] In this embodiment, the discovered converter list is a collection of all protocol converter instances collected during the scanning and instantiation process. The specific implementation of the discovered converter list can employ various data structures. For example, a first type of implementation is a list-based implementation, storing all discovered protocol converter instances in an ordered set, supporting iterative access; a second type of implementation is a set-based implementation, storing all discovered protocol converter instances in an unordered set, supporting quick determination of whether an instance already exists. The component management framework instantiates all protocol converter classes annotated with component annotations and injects them into the discovered converter list for subsequent registration process iteration. Through the component management framework's automatic discovery mechanism, developers only need to create protocol converter classes and annotate them with component annotations, without modifying any existing code or configuration files, to automatically discover and collect protocol converters.
[0029] In this embodiment, taking a smart livestock IoT system as an example, the overall architecture of the edge computing node is divided into a cloud platform layer, a platform communication layer, a message processing layer, a protocol converter layer, a device communication layer, and a device layer from top to bottom. The cloud platform layer includes a livestock management platform and a smart agriculture platform, etc. The platform communication layer subscribes to platform topics and receives platform instructions through a message queue telemetry transmission protocol. The message processing layer distributes messages and processes business logic. The protocol converter layer deploys multiple protocol converter instances to achieve bidirectional protocol conversion. The device communication layer subscribes to device topics and receives device messages through a message queue telemetry transmission protocol. The device layer includes hardware devices such as smart feeders and low-power Bluetooth mesh network gateways. The protocol converter layer, as the core hub connecting device-side protocols and platform-side protocols, achieves complete separation of protocol conversion from business logic and communication logic through the above layered architecture. Specifically, the protocol converter layer is internally divided into three layers: the converter interface layer defines a generic unified interface to standardize the behavior of all protocol converters; the converter template layer provides a template method base class to standardize the conversion process through the template method pattern; and the converter management layer provides a protocol converter manager responsible for registration, lookup, caching, and lifecycle management. The message dispatcher (denoted as MessageDispatcher) in the message processing layer is responsible for distributing received messages to the corresponding message handlers (denoted as AbstractMessageHandler). The message dispatcher uses a strategy pattern to route messages to the appropriate message handlers based on message type. Each message handler corresponds to one message type. Message handlers are registered with the message dispatcher in key-value pairs. When a message arrives, the corresponding message handler instance is found based on the message type. When a new message type is added, only the corresponding message handler class needs to be added and annotated with component annotations; the message dispatcher automatically discovers it and includes it in the distribution route. In actual deployments, the message processing layer contains more than 45 message handlers, covering various business scenarios for device messages and platform messages. After completing business logic processing, the message handler calls the protocol converter layer to complete protocol conversion. The device communication layer (denoted as MqttSubscriberDevice) and the platform communication layer (denoted as MqttSubscriberPlatform) subscribe to device topics and platform topics respectively through the message queue telemetry transport protocol to receive device messages and platform instructions. The device communication layer and the platform communication layer subscribe to different message topics and implement message routing based on topics. The device communication layer subscribes to device-side topics to receive messages reported by the device, and the platform communication layer subscribes to platform-side topics to receive instructions issued by the platform.Furthermore, edge computing nodes can trigger protocol conversions via scheduled tasks and a representation state transition interface (i.e., a REST interface), and persist the conversion results to a database (denoted as openGauss) for subsequent querying and analysis. The persisted conversion results are used for device status tracing, protocol conversion auditing, and historical data backtracking analysis. In case of protocol conversion anomalies, the persistent records can be queried to quickly locate the problem. Scheduled tasks are used to periodically trigger protocol conversions (such as periodically reporting device status), and the representation state transition interface is used to receive protocol conversion requests from external systems. Both supplement the message processor triggering method, enriching the triggering scenarios for protocol conversions. The various cloud platforms on the platform side are heterogeneous, with different data formats, field names, and enumeration definitions. Edge computing nodes perform protocol conversions for each cloud platform through a protocol converter layer, and add corresponding protocol converter classes for newly added cloud platform access or device protocol adaptation.
[0030] This embodiment automatically discovers and collects protocol converter instances through the component scanning mechanism of the component management framework, realizing zero-configuration access to protocol converters. To add a new protocol converter, you only need to create a class and mark it with component annotations. Developers do not need to modify the manager code or write configuration files, and the access cycle is shortened from days to hours.
[0031] Optionally, in some embodiments, the protocol converter instance also provides metadata information such as converter name (denoted as getConverterName), version number (denoted as getVersion), priority (denoted as getPriority, default value is 100), and enable status (denoted as isEnabled, default is enabled). The converter name is a unique string identifier for the protocol converter, used for log output and operational monitoring. The version number is the version string of the protocol converter, used for version identification in scenarios where multiple versions coexist. The priority is an integer value; the smaller the value, the higher the priority, with a default value of 100. The enable status is a boolean value indicating whether the protocol converter is enabled, with the default being enabled. Through the priority mechanism, multiple protocol converter instances can be registered under the same conversion path and sorted by priority, with the highest priority instance being used first. Through the enable status mechanism, developers can dynamically disable a protocol converter without deleting code; for example, if a protocol converter has known issues that need fixing, the registration of that protocol converter can be skipped by setting its enable status to disabled.
[0032] In this optional embodiment, taking a smart livestock IoT system as an example, the source protocol type can be the message protocol type on the device side, and the target protocol type can be the message protocol type on the platform side. The device side uses a custom protocol based on Message Queuing Telemetry Transport (MQTT) (i.e., JSON-over-MQTT protocol), using integer codes to identify message types (denoted as msgType). For example, message type 10 indicates field parameter distribution, message type 202 indicates feeding plan distribution, message type 300 indicates device alarm, etc., totaling more than 35 message types. The platform side uses various custom data structures, such as feeding plan data and alarm report data, with field naming, nesting levels, and enumeration definitions different from those on the device side. Through a protocol converter, a protocol converter instance can be defined for each pair of protocol type combinations that need to be converted, realizing bidirectional conversion between device protocols and platform protocols.
[0033] In this optional embodiment, the protocol converter instance also provides a compatibility check (denoted as supports) to check whether the protocol converter supports the conversion from the specified source type to the target type. The default judgment logic of the compatibility check is to determine whether the source protocol type declared by the protocol converter is a parent class or the same type as the input source type, and whether the target protocol type declared by the protocol converter is a parent class or the same type as the input target type, supporting subclass matching. The protocol converter can override the compatibility check to provide custom compatibility judgment logic. The compatibility check is called in the subsequent third-level compatibility matching search, used to find a compatible protocol converter when there is no exact match.
[0034] This optional embodiment achieves fine-grained lifecycle management of the protocol converter through a priority and activation status mechanism, supporting multi-version coexistence and dynamic start / stop, and flexibly controlling the participation status of the protocol converter without deleting code. Through subclass matching capabilities for compatibility checks, when no exact matching protocol converter is found, a protocol converter supporting the source type parent class to the target type parent class can be searched, avoiding the redundancy of writing a separate protocol converter for each subtype.
[0035] Step 20: For each protocol converter instance in the discovered converter list, generate a registration key based on the source and target protocol types of the protocol converter instance. Register the protocol converter instance to the converter list corresponding to the registration key in the converter registry and add it to the global converter list. Protocol converter instances in the converter list corresponding to the same registration key correspond to different version numbers and are sorted from high to low priority.
[0036] In this embodiment, the Protocol Converter Manager is the central hub of the entire protocol conversion framework, responsible for the registration, lookup, caching, and lifecycle management of protocol converters. Internally, the Protocol Converter Manager maintains three core data structures: a converter registry, a converter cache, and a global converter list.
[0037] In this embodiment, the registration key is a string key that uniquely identifies a conversion path. It is formed by concatenating the fully qualified names of the source protocol type and the target protocol type using an arrow separator. The registration key is generated as follows: obtain the fully qualified names of the source protocol type (denoted as `sourceClass.getName()`) and the target protocol type (denoted as `targetClass.getName()`) from the protocol converter instance, and then concatenate them using an arrow separator to form the registration key. For example, when the source protocol type is a device message publishing type and the target protocol type is a platform alarm message type, the registration key is a string concatenated with the fully qualified names of the source and target protocol types using an arrow symbol. The purpose of the registration key is to establish a mapping relationship between a conversion path (i.e., a pair of source and target protocol types) and the corresponding protocol converter instance, allowing for quick location of the corresponding protocol converter during a search.
[0038] In this embodiment, registration refers to the process of storing protocol converter instances in the converter registry and the global converter list according to the registration key. The specific implementation of registration is as follows: In the initialization callback, the protocol converter manager iterates through each protocol converter instance in the discovered converter list, generates a registration key for each instance, adds the instance to the converter list corresponding to the registration key in the converter registry, and adds the instance to the global converter list. During the registration process, the protocol converter manager sorts the converter lists under the same registration key from highest to lowest priority, placing the highest priority protocol converter at the top of the list. Registration solves the problem of strong binding between converters and business code and the inability to manage them uniformly in traditional solutions. By maintaining the registry and the global list, it provides a data foundation for subsequent hierarchical searches.
[0039] In this embodiment, the converter registry is a concurrent mapping table with registration keys as keys and converter lists as values, storing all registered conversion paths and their corresponding protocol converter lists. Each entry in the converter registry corresponds to a conversion path, and its value is a list of protocol converters under that conversion path, sorted by priority. The converter registry supports the coexistence of multiple protocol converter instances under the same registration key, providing a data foundation for the parallel operation of multiple versions. The converter cache is a concurrent mapping table with registration keys as keys and individual protocol converters as values, used to cache the protocol converters that have been searched. The cache stores the highest priority protocol converter under the corresponding conversion path. The converter cache is written during the search process, so that subsequent searches for the same conversion path can directly retrieve the protocol converter from the cache, avoiding duplicate searches. The global converter list is an ordered set storing all registered protocol converter instances, used for compatibility matching traversal. The global converter list is traversed in the third-level compatibility matching search, used to find compatible protocol converters when no exact match is found. Among them, each protocol converter instance in the converter list corresponding to the same registration key corresponds to a different version number and has its own priority value. The protocol converter instances are sorted from high to low priority, with the protocol converter instance with the highest priority located at the beginning of the converter list.
[0040] In this embodiment, the protocol converter manager implements the initialization callback interface of the component management framework. Upon system startup, the component management framework injects all protocol converter instances annotated with component annotations into the list of discovered converters. In the initialization callback, the protocol converter manager iterates through each protocol converter instance in the list of discovered converters, executes the registration logic for each instance, registers the protocol converter instance to the converter registry, and adds it to the global converter list.
[0041] This embodiment provides a data foundation for subsequent step-by-step searches by maintaining three core data structures: the converter registry, the converter cache, and the global converter list.
[0042] Optionally, in some embodiments, registering the protocol converter instance to the converter list corresponding to the registration key in the converter registry and adding it to the global converter list includes: in the initialization callback, iterating through each protocol converter instance in the discovered converter list; checking if the protocol converter instance is empty, and skipping if it is empty; checking the enabled status of the protocol converter instance, and skipping if it is disabled; generating a registration key through the source protocol type and target protocol type of the protocol converter instance; adding the protocol converter instance to the converter list corresponding to the registration key in the converter registry and sorting it from high to low priority; and adding the protocol converter instance to the global converter list.
[0043] In this optional embodiment, the registration process for a single protocol converter instance includes the following steps: First, check if the protocol converter instance is null. If it is null, skip the instance to prevent null pointer exceptions. Second, check the enabled status of the protocol converter instance (call isEnabled). If it is disabled, skip the instance, allowing temporary disabling of a protocol converter without deleting code. Third, obtain the source protocol type (call getSourceType) and target protocol type (call getTargetType) from the protocol converter instance and generate a registration key. Fourth, add the protocol converter instance to the converter list corresponding to the registration key in the converter registry. Fifth, sort the converter list from highest to lowest priority (call getPriority to obtain the priority value), placing the highest priority protocol converter at the top of the list. Sixth, add the protocol converter instance to the global converter list for subsequent compatibility matching traversal. After registration, a registration log is output, including the protocol converter name, source protocol type, target protocol type, and priority information, for operation and maintenance monitoring and troubleshooting.
[0044] In this optional embodiment, during the registration process, if a list of converters with the same registration key already exists in the converter registry, the new protocol converter instance is appended to the existing list, and then the entire list is reordered from highest to lowest priority. After sorting, the protocol converter with the highest priority is at the top of the list and will be returned first in subsequent searches. If the registration key does not exist in the converter registry, a new converter list is created, and the protocol converter instance is added to the list. This design supports the coexistence of multiple protocol converters under the same conversion path, providing a foundation for parallel operation and smooth switching of multiple versions.
[0045] This optional embodiment achieves fine-grained lifecycle management of the protocol converter by checking the activation status and the registration process sorted by priority. It supports the coexistence of multiple versions and dynamic start and stop. At the same time, the list appending and reordering mechanism allows multiple versions of the protocol converter to exist simultaneously under the same conversion path.
[0046] Optionally, in some embodiments, after registering the converters corresponding to the registration keys in the converter registry and adding them to the global converter list, the method further includes at least one of the following: receiving new protocol converter instances, generating registration keys and adding them to the converter registry and the global converter list, sorting them by priority from high to low; the new protocol converter instances take effect immediately; receiving protocol converter instances to be removed, removing them from the converter registry and the global converter list, and clearing the converter cache to prevent dirty reads; clearing the converter registry, converter cache, and global converter list, and re-executing the initialization callback to perform a full re-registration.
[0047] In this optional embodiment, runtime hot management includes three functions: dynamic registration, dynamic removal, and hot reload. The specific process of dynamic registration (denoted as registerConverter) is as follows: A new protocol converter instance is received; its status (empty or enabled) is checked; a registration key is generated using the instance's source and target protocol types; the instance is added to the converter list corresponding to the registration key in the converter registry, sorted by priority from high to low; and the instance is added to the global converter list. After dynamic registration, the new protocol converter instance takes effect immediately without requiring a service restart. The specific process of dynamic removal (denoted as unregisterConverter) is as follows: A protocol converter instance to be removed is received; a registration key is generated using the instance's source and target protocol types; the instance is removed from the converter list corresponding to the registration key in the converter registry, and the entire registration key is deleted if the converter list is empty; the instance is removed from the global converter list, and the converter cache is cleared to prevent dirty reads. After dynamic removal, the removed protocol converter instance no longer participates in subsequent lookups. The specific process of hot reload (denoted as reload) is as follows: clear all data in the converter registry, converter cache, and global converter list, and re-execute the initialization callback (denoted as afterPropertiesSet) to re-register all converters. Hot reload is suitable for scenarios that require batch updating of protocol converters, eliminating the need for dynamic registration or removal of each converter individually.
[0048] In this optional embodiment, the converter registry, converter cache, and global converter list are all implemented using concurrent mapping tables. Dynamic registration and removal operations are completed through atomic operations of the concurrent mapping tables, without blocking ongoing protocol conversion requests. Hot reload is performed by first clearing and then re-registering. There is a brief window between clearing and re-registering, during which received protocol conversion requests may throw exceptions due to the inability to find the required converter. Therefore, hot reload is suitable for scenarios where protocol converters are updated in batches and brief interruptions are acceptable. For scenarios where interruptions are not allowed, it is recommended to use dynamic registration and dynamic removal to replace converters one by one.
[0049] In this optional embodiment, the converter registry and converter cache are implemented using a concurrent mapping table, and the global converter list is implemented using a copy-on-write concurrent list. During registration, the protocol converter instance is added to the converter list corresponding to the registration key through an atomic creation operation of the concurrent mapping table. During deregistration, the corresponding protocol converter instance is removed through an atomic update operation of the concurrent mapping table, and the corresponding registration key is deleted when the converter list is empty. The maintenance of the converter cache follows these rules: when dynamically registering a new protocol converter instance, the converter cache can be optionally cleared so that the newly registered protocol converter instance takes effect immediately; when dynamically removing a protocol converter instance, the converter cache is cleared to prevent the removed protocol converter instance from being hit again and causing dirty reads; when performing hot reload, the converter cache is cleared; during the window period between clearing and re-registration, the lookup operation of the protocol conversion request can be blocked to avoid returning inconsistent lookup results; for scenarios where interruption is not allowed, hot reload can be omitted, and updates can be completed by dynamically registering and dynamically removing one by one.
[0050] This optional embodiment supports the dynamic registration, removal, and reloading of protocol converters without restarting the service through a runtime hot management mechanism, ensuring uninterrupted connection of online devices.
[0051] Step 30: Receive protocol conversion request; the protocol conversion request carries the source protocol object, the target protocol type identifier, and the conversion direction identifier.
[0052] In this embodiment, the protocol conversion request is a conversion request initiated by the business layer to the protocol converter manager after completing business logic processing. It carries the source protocol object, the target protocol type identifier, and the conversion direction identifier. The protocol conversion request is received by the conversion interface of the protocol converter manager. The parameters of the conversion interface include the source protocol object and the class object of the target protocol type.
[0053] In this embodiment, the source protocol object is the protocol data object that needs to be converted, serving as the input data for protocol conversion. The specific content of the source protocol object depends on the message type received by the message processor. For example, when the device reports an alarm event, the source protocol object is the device alarm message object, containing fields such as device identifier, message type code, and alarm status enumeration value; when the cloud platform issues a feeding plan instruction, the source protocol object is the platform feeding plan data object, containing fields such as pig status, plan change stage, and meal details.
[0054] In this embodiment, the target protocol type identifier is identification information used to specify the target protocol type after conversion. The target protocol type identifier can take several forms. For example, a first type is a type identifier based on a class object, uniquely identifying the target type through a class object of the target protocol type; a second type is a type identifier based on a string, identifying the target type through the fully qualified name string of the target protocol type. Both implementations enable the protocol converter manager to generate a cache key or registration key based on the target protocol type identifier during lookup.
[0055] In this embodiment, the conversion direction identifier is used to specify whether a forward or reverse conversion is performed. When the conversion direction identifier is a forward conversion, the target protocol converter performs a forward conversion process, converting the source protocol object into a target protocol object; when the conversion direction identifier is a reverse conversion, the target protocol converter performs a reverse conversion process, converting the target protocol object back into the source protocol object. The conversion direction identifier can be implemented in various ways. For example, the first type of implementation is based on an enumerated value, using two enumerated values, forward and reverse, to identify the conversion direction; the second type of implementation is based on a Boolean value, using a true value to indicate a forward conversion and a false value to indicate a reverse conversion. The introduction of the conversion direction identifier allows forward and reverse conversions to share the same lookup and call process, eliminating the need to design different interfaces for different directions.
[0056] In this embodiment, taking a smart livestock IoT system as an example, when a device reports an alarm event, the message processor receives the alarm message from the device, performs business logic processing, and then converts the device alarm message into a platform alarm message format before reporting it to the cloud platform. At this time, the source protocol object is the device alarm message object, the target protocol type is the platform alarm message type, and the conversion direction is forward conversion. Conversely, when the cloud platform issues a feeding plan instruction, the message processor receives the platform's feeding plan data, performs business logic processing, and then converts the platform feeding plan data into a message format from the device and sends it to the feeder. At this time, the source protocol object is the platform feeding plan data object, the target protocol type is the device message type, and the conversion direction is reverse conversion.
[0057] This embodiment uses a unified protocol conversion request format so that the business layer code is completely unaware of protocol differences and can complete the conversion with just one call. The introduction of the conversion direction identifier allows forward and reverse conversions to share the same lookup and call process.
[0058] Step 40: Based on the type of the source protocol object and the target protocol type identifier, search for the target protocol converter in the converter cache, converter registry, and global converter list level by level.
[0059] In this embodiment, the hierarchical lookup is the core mechanism of the protocol converter manager in locating the target protocol converter. Through a progressively degraded strategy, it ensures both search performance and flexibility. The hierarchical lookup is performed sequentially in three data structures: the converter cache, the converter registry, and the global converter list. Upon successful lookup at each level, the result is returned directly, and subsequent levels are not searched. The design principle of the hierarchical lookup is as follows: in most scenarios, the same conversion path will be repeatedly searched; cache hits can reduce the search time complexity to constant level; when the cache misses, exact matching in the registry can quickly locate the corresponding converter in the list; when no exact match is found, compatibility matching in the global list can search for converters that support the parent type, providing flexible subclass matching capabilities.
[0060] In this embodiment, the cache key is a string key used during the lookup process to search in the converter cache and converter registry. The cache key has the same format as the registration key, consisting of the fully qualified name of the source protocol object's type and the fully qualified name of the target protocol type identifier concatenated with an arrow separator. The cache key is dynamically generated based on the source protocol object's type and the target protocol type identifier during the lookup, ensuring that lookup requests for the same conversion path generate the same cache key, thus achieving a cache hit.
[0061] In this embodiment, the first level involves searching in the converter cache. The converter cache stores the highest-priority protocol converters for the searched conversion paths. Since the converter cache is implemented using a concurrent mapping table, the time complexity of the search is constant (O(1)), making it the most efficient of the three search methods. The second level involves searching in the converter registry. The converter registry stores a list of all registered conversion paths and their corresponding protocol converters. An exact match search is performed using the registration key as an index, and the time complexity of this search is also constant. The third level involves searching in the global converter list. The global converter list stores all registered protocol converter instances. The search is performed by traversing the global converter list and performing compatibility checks on each protocol converter. The time complexity of this search is linear, making it the slowest of the three search methods, but it is only executed when neither the cache nor the exact match is found.
[0062] This embodiment employs a step-by-step search mechanism, enabling the acquisition of the target protocol converter through cache hits in most scenarios, thus avoiding the performance overhead of linear traversal. Simultaneously, the compatibility matching search provides flexible subclass matching capabilities; when no exact matching protocol converter is found, it can search for protocol converters that support the transformation from the source type parent class to the target type parent class, enhancing the framework's flexibility.
[0063] Optionally, in some embodiments, the step-by-step search for the target protocol converter includes: generating a cache key based on the type of the source protocol object and the target protocol type identifier; searching in the converter cache using the cache key; if a cache match is found, directly returning the cached protocol converter; if a cache miss is not found, performing an exact match search in the converter registry using the cache key; if a corresponding converter list is found, retrieving the highest priority protocol converter from the list, writing it to the converter cache, and returning; if no exact match is found, traversing the global converter list, performing a compatibility check on each protocol converter, selecting the highest priority among all compatible protocol converters, writing it to the converter cache, and returning; if no match is found in any step-by-step search, throwing an exception; the exception carries an error code and source protocol type and target protocol type information.
[0064] In this optional embodiment, the first-level cache lookup searches the converter cache using the cache key. If a cache match is found, the cached protocol converter is returned directly. The second-level exact match lookup searches the converter registry using the cache key. If a corresponding converter list is found, the highest-priority protocol converter in the list is retrieved, written to the converter cache, and returned. The third-level compatibility match lookup iterates through the global converter list, performs a compatibility check on each protocol converter, selects the highest-priority protocol converter from all compatible converters, writes it to the converter cache, and returns.
[0065] In this optional embodiment, the default judgment logic of the compatibility check (calling supports) adopts a type assignment compatibility check (i.e., isAssignableFrom), which determines whether the source protocol type declared by the protocol converter is a parent class or the same type as the input source type, and whether the target protocol type declared by the protocol converter is a parent class or the same type as the input target type. This judgment logic supports subclass matching. For example, when the source protocol type declared by the protocol converter is a device message base class, and the input source protocol object is a device alarm message subclass, the compatibility check passes. The protocol converter can override the compatibility check to provide custom compatibility judgment logic.
[0066] In this optional embodiment, during the initial stage of system operation, the converter cache is empty, and all lookup requests will penetrate to the second or third level of lookup. As the number of lookup requests increases, the converter cache is gradually filled, and most lookup requests can be completed through the first-level cache hit, thus gradually improving lookup performance. When the protocol converter is dynamically removed or hot-reloaded, the converter cache is cleared, and lookup performance temporarily decreases. However, as the number of lookup requests increases, the converter cache is filled again, and lookup performance recovers.
[0067] In this optional embodiment, if the target protocol converter is not found after a step-by-step search, a protocol conversion exception (denoted as ProtocolConversionException) is thrown. The exception carries an error code (denoted as CONVERTER_NOT_FOUND) and information about the source and target protocol types. The error code indicates that the converter was not found, and the source and target protocol type information helps developers quickly locate the problem. For example, if a developer forgets to write a protocol converter for a certain pair of protocol types, an exception carrying the source and target protocol type information will be thrown at runtime, allowing the developer to identify which protocol converter needs to be added.
[0068] This optional embodiment provides flexible type compatibility support while ensuring search performance through the unified format design of cache keys and the subclass matching capability of compatibility checks. The cache warm-up and autofill mechanism gradually improves the search performance of the system during operation, and the exception handling mechanism provides detailed error information when the search fails, which facilitates quick location and repair of problems.
[0069] Optionally, in some embodiments, the compatibility check logic can be implemented in multiple ways. For example, the first type of implementation is a type assignment compatibility check, which determines whether the source protocol type declared by the protocol converter is a parent class or the same type as the input source type, and whether the target protocol type declared by the protocol converter is a parent class or the same type as the input target type, supporting subclass matching; the second type of implementation is an interface implementation check, which determines whether the input source type implements the source protocol interface declared by the protocol converter, and whether the input target type implements the target protocol interface declared by the protocol converter, supporting flexible matching based on interfaces; the third type of implementation is a custom rule check, where the protocol converter rewrites the compatibility check and defines custom compatibility judgment rules according to business requirements, such as matching rules based on annotations, configuration, or protocol version numbers. These three implementation methods can be selected or combined according to actual needs, enhancing the applicability and flexibility of the protocol conversion method.
[0070] In this optional embodiment, the type assignment compatibility check is applicable to scenarios where the type declared by the protocol converter and the input type have an inheritance relationship. For example, if the protocol converter declares the source protocol type as the device message base class, and the input source type is the device alarm message subclass, the compatibility check passes. The interface implementation check is applicable to scenarios where the type declared by the protocol converter is an interface rather than a concrete class. For example, if the protocol converter declares the source protocol type as the device message interface, and the input source type implements this interface, the compatibility check passes. The custom rule check is applicable to scenarios where compatibility needs to be flexibly determined based on business logic. For example, compatibility can be determined based on the protocol version number; when the protocol version number of the input source type is within the version range supported by the protocol converter, the compatibility check passes.
[0071] This optional embodiment provides multiple compatibility check implementation methods, enabling the protocol conversion method to adapt to different type matching requirements. The type assignment compatibility check supports subclass matching under the inheritance hierarchy, the interface implementation check supports flexible matching based on the interface, and the custom rule check supports customized matching based on business logic, thereby enhancing the applicability and extensibility of the protocol conversion method.
[0072] Optionally, in some embodiments, the step-by-step search for the target protocol converter includes: when a converter list corresponding to a registration key is precisely matched in the converter registry, returning the highest priority protocol converter instance in the converter list; when the highest priority protocol converter instance is removed, returning the next highest priority protocol converter instance in the converter list when searching again.
[0073] In this optional embodiment, multiple versions of protocol converter instances can be registered under the same conversion path, each with a different version number and priority. Newer version protocol converter instances are assigned a higher priority (e.g., a smaller value) for priority use, while older version instances are assigned a lower priority (e.g., a larger value) as fallback options. During the hierarchical search, the highest-priority protocol converter instance in the returned converter list is precisely matched; this is the newer version instance, thus ensuring priority use of the newer version and fallback options for the older version.
[0074] In this optional embodiment, taking the device alarm message conversion of a smart livestock IoT system as an example, when the device alarm protocol is upgraded from version 1 to version 2, protocol converters for both version 1 and version 2 can be registered simultaneously. Version 2 is given a higher priority, and version 1 is given a lower priority. During normal operation, the version 2 protocol converter is used. When version 2 has problems, the version 2 protocol converter can be dynamically removed, and the version 1 protocol converter is automatically returned during the search, achieving a smooth protocol version downgrade. Once the problems with version 2 are fixed, a new version of the protocol converter can be dynamically registered, and the new version protocol converter is automatically returned during the search, achieving a smooth protocol version upgrade.
[0075] This optional embodiment avoids the problem of having to completely replace the protocol when upgrading through a multi-version coexistence mechanism, supports the parallel operation and smooth switching of new and old versions, and automatically selects the highest priority version through a priority mechanism, and automatically downgrades to the next version after it is removed, making the whole process transparent to the business.
[0076] Step 50: Using the found target protocol converter, execute either a forward or reverse conversion process based on the conversion direction identifier, and output the converted protocol object. The forward conversion process converts the source protocol object to the target protocol object, while the reverse conversion process converts the target protocol object back to the source protocol object. The target protocol converter is the highest-priority protocol converter instance in the converter list. When the target protocol converter fails, a degradation log is recorded, and the process switches to the next highest-priority protocol converter instance in the converter list according to priority from highest to lowest until the conversion succeeds. Alternatively, if all protocol converter instances in the converter list fail, an exception is thrown, carrying the error code, source protocol type, target protocol type, and failure reason information.
[0077] In this embodiment, after locating the target protocol converter through a step-by-step search, a forward conversion process or a reverse conversion process is executed based on the conversion direction identifier carried in the protocol conversion request. The forward conversion process converts the source protocol object into the target protocol object, corresponding to the uplink data direction from the device side to the platform side. The reverse conversion process converts the target protocol object back into the source protocol object, corresponding to the downlink command direction from the platform side to the device side. When the conversion direction identifier is forward, the target protocol converter executes the forward conversion process, converting the source protocol object into the target protocol object and outputting the target protocol object. When the conversion direction identifier is reverse, the target protocol converter executes the reverse conversion process, converting the target protocol object back into the source protocol object and outputting the source protocol object. The forward and reverse conversion processes share the same protocol converter instance.
[0078] In this embodiment, both the forward and reverse conversion processes sequentially include five steps: pre-verification, preprocessing, core conversion, post-processing, and post-verification. Pre-verification checks the validity of the input protocol object before core conversion; preprocessing preprocesses the input protocol object before core conversion; core conversion converts the preprocessed input protocol object into the target protocol object; post-processing performs post-processing on the output protocol object after core conversion; and post-verification checks the validity of the output protocol object after core conversion. The specific details of each step are described in detail in subsequent optional embodiments.
[0079] In this embodiment, taking a smart livestock IoT system as an example, when performing a forward conversion (device to platform direction), the converted platform protocol object is published to the cloud platform through the platform communication layer; when performing a reverse conversion (platform to device direction), the converted device protocol object is sent to the device through the device communication layer. After receiving the converted protocol object, the message processor sends the protocol object to the counterpart system. The counterpart system refers to the system opposite to the side where the source protocol object is located; during forward conversion, the counterpart system is the platform side, and during reverse conversion, the counterpart system is the device side.
[0080] This embodiment drives the forward or reverse conversion process by using a conversion direction identifier, enabling the same protocol converter instance to support bidirectional conversion.
[0081] Optionally, in some embodiments, the process of recording a degradation log when the target protocol converter fails to convert and switching to the next highest priority protocol converter instance to continue the conversion in order of priority from high to low, also includes the content of the degradation log and the handling methods when the conversion is successful and all conversions fail after the switch.
[0082] In this optional embodiment, the degradation process when the conversion fails as described in step 50 is further explained. When the next highest priority protocol converter instance successfully completes the conversion, the conversion result of that instance is output, and the degradation process remains transparent to the business layer. The degradation log includes the degradation occurrence time, the name and version number of the protocol converter before and after the degradation, and the failure reason information of the current conversion, which is used by operation and maintenance personnel to trace the degradation process and locate version compatibility defects. When all protocol converter instances in the converter list fail to convert, a protocol conversion exception is thrown. This exception carries an error code, source protocol type, target protocol type, and failure reason information for each conversion. All of the above fields can be obtained directly at runtime: the error code identifies the exception type, the source protocol type and target protocol type come from the protocol conversion request, and the failure reason information summarizes the exception information of each conversion during the degradation process.
[0083] In this optional embodiment, a protocol conversion exception is thrown in two scenarios: failure of step-by-step search and failure of all conversions. The error codes carried include: converter not found (corresponding to no target protocol converter found in any step-by-step search); verification failure (corresponding to failure of pre-verification or post-verification); conversion failure (corresponding to failure of core forward conversion or core reverse conversion); and all converters failed (corresponding to all protocol converter instances in the converter list failing conversion). The protocol conversion exception also carries the source protocol type, target protocol type, protocol converter name, and the reasons for each conversion failure recorded in the degradation scenario, facilitating quick identification of whether the issue is a missing protocol converter, invalid protocol data, or an abnormal conversion logic based on the exception information.
[0084] In this optional embodiment, taking the conversion of device alarm messages in a smart livestock IoT system as an example, when the device alarm protocol is upgraded from version 1 to version 2, the protocol converter of version 2 is set to a higher priority and used first. If the protocol converter of version 2 fails to convert alarm messages reported by older feeders that have not been upgraded due to missing fields, the protocol converter manager automatically downgrades to the protocol converter of version 1 to continue the conversion, avoiding the inability to report alarm messages due to compatibility defects of a single version. The maintenance personnel can locate the compatibility defects of version 2 according to the downgrade log, fix them, and dynamically register the new version of the protocol converter to restore the use of the high-priority version.
[0085] This optional embodiment automatically downgrades to the next priority protocol converter instance when a conversion fails, ensuring that the protocol conversion service is not interrupted when a single version of the protocol converter has compatibility defects or malfunctions. Furthermore, the downgrade process is logged in a traceable manner, guaranteeing the continuity of device reporting and instruction issuance in the smart livestock IoT system.
[0086] Optionally, in some embodiments, the forward conversion process and the reverse conversion process are defined through a template method base class; the template method base class declares the forward conversion process and the reverse conversion process as non-overridable, and includes pre-validation, preprocessing, core conversion, post-processing and post-validation in sequence; the core conversion includes core forward conversion and core reverse conversion, which are implemented by subclasses of the template method base class; the pre-validation, preprocessing, post-processing and post-validation are provided with default implementations by the template method base class, and subclasses override them as needed.
[0087] In this optional embodiment, the template method base class is an abstract base class that implements the protocol converter interface (denoted as AbstractProtocolConverter). In this optional embodiment, the forward conversion process includes five steps in sequence: pre-validation of the source protocol object, preprocessing of the source protocol object, execution of the core forward conversion, post-processing of the target protocol object, and post-validation of the target protocol object. The pre-validation of the source protocol object (denoted as validateSourceProtocol) checks whether the source protocol object meets the pre-conversion conditions, such as non-empty checks, required field checks, and data type checks. If the validation fails, a protocol conversion exception is thrown. The preprocessing of the source protocol object (denoted as preprocessSource) performs preprocessing operations on the source protocol object before conversion, such as field completion, format standardization, and default value filling. The execution of the core forward conversion (denoted as doConvert) converts the preprocessed source protocol object into the target protocol object. This step is implemented by a subclass with specific conversion logic. The post-processing of the target protocol object (denoted as postprocessTarget) performs post-processing operations on the converted target protocol object, such as field cleanup, format standardization, and removal of redundant fields. The post-validation of the target protocol object (denoted as validateTargetProtocol) checks whether the target protocol object meets the post-conversion conditions, such as integrity checks and consistency checks. If the validation fails, a protocol conversion exception is thrown.
[0088] In this optional embodiment, the reverse conversion process also includes five steps in sequence, in the opposite direction to the forward conversion: pre-validation of the target protocol object (denoted as validateTargetProtocol), preprocessing of the target protocol object (denoted as preprocessTarget), execution of the core reverse conversion (denoted as doReverseConvert), post-processing of the source protocol object (denoted as postprocessSource), and post-validation of the source protocol object (denoted as validateSourceProtocol). Of these five steps, pre-validation, preprocessing, post-processing, and post-validation are hook steps, provided by the template method base class with default implementations, which subclasses can override as needed. In the default implementation, pre-validation checks if the object is null, preprocessing and postprocessing perform no operations by default, and post-validation checks if the object is null. The core conversion is a core step, including core forward conversion and core reverse conversion, implemented by subclasses of the template method base class; subclasses must implement the specific conversion logic.
[0089] In this optional embodiment, subclasses can override the hook steps according to the specific protocol's validation requirements. For example, mandatory field checks and data range checks can be added to the pre-validation stage; timestamp formatting and enumeration value mapping can be added to the preprocessing stage; redundant field removal and format normalization can be added to the post-processing stage; and field integrity checks and cross-field consistency checks can be added to the post-validation stage. Through the default implementation and rewriteable design of the hook steps, the uniformity of the conversion process is ensured, while providing flexible extension points for subclasses.
[0090] This optional embodiment defines a standardized five-step conversion process through a template method base class, ensuring consistent behavior across all protocol converters and reducing code review and debugging costs. Subclasses only need to implement the core conversion logic, without needing to worry about common processes such as validation, preprocessing, and postprocessing, thus reducing code duplication. The non-overrideable declaration ensures that the framework of the conversion process cannot be modified by subclasses, and no subclass can skip the validation step, guaranteeing data integrity.
[0091] Optionally, in some embodiments, a forward conversion process or a reverse conversion process is executed to output the converted protocol object, including: when the conversion direction is identified as forward conversion, sequentially executing the pre-verification source protocol object, preprocessing the source protocol object, executing the core forward conversion, post-processing the target protocol object, and post-verification the target protocol object; when the conversion direction is identified as reverse conversion, sequentially executing the pre-verification target protocol object, preprocessing the target protocol object, executing the core reverse conversion, post-processing the source protocol object, and post-verification the source protocol object.
[0092] In this optional embodiment, the conversion of device alarm messages in a smart livestock IoT system is used as an example to illustrate the specific implementation process of the template method conversion process. The source protocol type of the device alarm message is the device message publishing type, and the target protocol type is the platform alarm message type. During forward conversion, the pre-verification checks whether the message type field in the device alarm message is an alarm type and whether the device identifier is not empty; the preprocessing converts the alarm status enumeration value in the device alarm message from device-side encoding to internal unified encoding; the core forward conversion maps the fields of the device alarm message to the corresponding fields of the platform alarm message, including device identifier mapping, alarm type mapping, alarm time format conversion, and alarm status enumeration conversion; the post-processing removes unnecessary intermediate fields in the platform alarm message; and the post-verification checks whether the required fields of the platform alarm message are complete. During reverse conversion, the pre-verification checks whether the alarm status field in the platform alarm message is valid; the preprocessing converts the alarm status enumeration value in the platform alarm message from platform-side encoding to internal unified encoding; the core reverse conversion maps the fields of the platform alarm message to the corresponding fields of the device alarm message; the post-processing supplements the necessary verification fields in the device alarm message; and the post-verification checks whether the message type field of the device alarm message is correct.
[0093] In this optional embodiment, the alarm status enumeration codes on the device side and the platform side are different. On the device side, 0 represents an alarm and 1 represents recovery, while on the platform side, 2 represents no recovery and 1 represents recovery. In the preprocessing step of the forward conversion, 0 on the device side is converted to the internally unified code "alarm," and 1 is converted to "recovery." In the core forward conversion step, "alarm" is converted to 2 on the platform side, and "recovery" is converted to 1 on the platform side. In the preprocessing step of the reverse conversion, 2 on the platform side is converted to "alarm," and 1 is converted to "recovery." In the core reverse conversion step, "alarm" is converted to 0 on the device side, and "recovery" is converted to 1 on the device side. Through the intermediate encoding conversion of the enumeration values in the preprocessing step, the core conversion step only needs to focus on the field mapping and does not need to worry about the differences in the enumeration values, reducing the complexity of the conversion logic.
[0094] In this optional embodiment, the data structure differences between the device side and the platform side are not only reflected in the enumeration encoding, but also in the field hierarchy and data format. Regarding the field hierarchy, the platform side's feeding plan adopts a three-level nested structure of "pig status → plan change stage → meal details," while the device side expects a flat key-value pair format. In the core forward conversion step, the three-level nested structure on the platform side needs to be expanded into flat key-value pairs on the device side; in the core reverse conversion step, the flat key-value pairs on the device side need to be assembled back into the three-level nested structure on the platform side. Regarding the data format, timestamps are represented as integer seconds on the device side and as strings on the platform side. In the preprocessing step, the integer seconds on the device side are formatted into a string format on the platform side; in the preprocessing step of the core reverse conversion, the string format on the platform side is parsed into integer seconds on the device side. By uniformly handling the data format differences through the preprocessing step, the core conversion step only needs to focus on the field mapping logic, further reducing the complexity of the conversion logic.
[0095] This optional embodiment illustrates the implementation process of the template method conversion process through specific application scenario examples, demonstrating the specific operations of the five steps of pre-verification, preprocessing, core conversion, post-processing and post-verification in the conversion of device alarm messages, as well as the preprocessing mechanism for the conversion of enumerated value intermediate encoding.
[0096] Optionally, in some embodiments, before executing the forward conversion process or the reverse conversion process, the method further includes: obtaining the generic parent class type information of the subclass through reflection to determine the source protocol type and the target protocol type.
[0097] In this optional embodiment, the template method base class obtains the generic parent class type information of the subclass through reflection in the constructor to determine the source protocol type and the target protocol type. Specifically, the template method base class obtains the generic parameter information declared by the subclass when inheriting the template method base class through reflection in the constructor, extracts the source protocol type and the target protocol type from it, and caches them in the member variables of the protocol converter instance for use in the subsequent registration process when generating registration keys.
[0098] In this optional embodiment, the specific process of obtaining information via reflection is as follows: The `getClass` method of the subclass instance is called to obtain the runtime class object. The generic superclass type information (`getGenericSuperclass`) is then obtained through the runtime class object. This generic superclass type information describes the generic parameters declared when the subclass inherits the template method base class. It is then determined whether the generic superclass type information is a parameterized type (`ParameterizedType`). If the generic superclass type is a parameterized type, the actual type parameter array is extracted using the `getActualTypeArguments` method of the parameterized type. The first element of the array is the source protocol type, and the second element is the target protocol type. If the generic superclass type is not a parameterized type, it indicates that the subclass did not specify generic parameters when inheriting the template method base class, and an exception is thrown indicating that the protocol converter class must specify generic parameters.
[0099] In this optional embodiment, the process of obtaining the generic parameter type via reflection is executed once during the construction of the protocol converter instance. The deduction result is cached in the member variables of the protocol converter instance. Subsequent calls to the source protocol type retrieval method and the target protocol type retrieval method directly return the cached result, without repeating the reflection operation. Therefore, it has no significant impact on runtime performance. When a subclass inherits the template method base class in a non-generic manner, i.e., the subclass does not specify the specific type of the generic parameter during inheritance, reflection cannot extract the actual type parameter from the generic parent class type information. In this case, an exception is thrown to prompt the developer to correct the generic declaration of the subclass. This mechanism ensures that all protocol converters have clear source and target protocol types during registration, avoiding registration key generation errors or lookup failures due to missing type information.
[0100] This optional embodiment uses reflection to obtain the generic parent class type information of the subclass to determine the source protocol type and the target protocol type. This allows the subclass to obtain the correct type information simply by specifying the generic parameter in the class declaration, without having to manually override the type retrieval method, thus reducing boilerplate code in the subclass. Furthermore, the combination of generic parameterization and reflection allows type mismatch errors to be detected at compile time, avoiding runtime type conversion exceptions and ensuring type safety.
[0101] Optionally, in some embodiments, the generic parent class type information of the subclass is obtained by reflection to determine the source protocol type and the target protocol type, including: determining whether the generic parent class type is a parameterized type; when it is determined to be a parameterized type, extracting the actual type parameters in the parameterized type, setting the first type parameter as the source protocol type, and setting the second type parameter as the target protocol type; when it is determined not to be a parameterized type, throwing an exception and prompting the protocol converter class to specify generic parameters.
[0102] In this optional embodiment, the specific implementation process of obtaining generic parameter types through reflection is illustrated using a device alarm converter in a smart livestock IoT system as an example. When the device alarm converter inherits from the template method base class, it declares generic parameters. The source protocol type is the device message publishing type, and the target protocol type is the platform alarm message type. In the constructor of the device alarm converter, the template method base class obtains the generic parent class type information of the device alarm converter through reflection, determines that the generic parent class type is a parameterized type, extracts the actual type parameter array, where the first element is the device message publishing type and the second element is the platform alarm message type. The device message publishing type is set as the source protocol type, and the platform alarm message type is set as the target protocol type, both cached in the member variables of the device alarm converter instance. The subsequent registration process obtains the cached type information through the source protocol type acquisition method and the target protocol type acquisition method, generating a registration key.
[0103] This optional embodiment demonstrates how a subclass can obtain the correct type information by inheriting the template method base class and declaring generic parameters, thus eliminating the burden of manually overriding the type acquisition method.
[0104] Optionally, in some embodiments, before receiving the protocol conversion request, the method further includes: receiving a message through a message processor, parsing the message payload and performing business logic processing, and determining whether protocol conversion is required; if required, generating a protocol conversion request; after outputting the converted protocol object, the method further includes: sending the protocol object to the other side system; wherein the message processor shares the same protocol converter instance when executing the forward conversion process and the reverse conversion process.
[0105] In this optional embodiment, the message processor is the core component for message processing in the business layer, and the abstract base class integrates the protocol converter manager. After receiving a message, the message processor executes the following process: First, it receives the message from the device side or platform side; second, it parses the message payload and extracts business data; third, it executes business logic processing; fourth, it determines whether protocol conversion is needed; fifth, if protocol conversion is needed, it calls the conversion interface of the protocol converter manager, passing in the source protocol object, the target protocol type identifier, and the conversion direction identifier to generate a protocol conversion request; sixth, the protocol converter manager locates the target protocol converter through a step-by-step search; seventh, the target protocol converter completes the conversion by executing a forward or reverse conversion process according to the conversion direction identifier; eighth, it sends the converted protocol object to the other system.
[0106] In this optional embodiment, the determination of whether protocol conversion is needed is implemented through a conversion hook (denoted as `shouldConvertProtocol`) defined in the message processor abstract base class. The conversion hook returns "conversion needed" by default. Subclasses of the message processor can override the conversion hook according to the message type and business requirements. For internal messages that do not require protocol conversion, the overridden conversion hook returns "no conversion needed". In the message processor abstract base class, the protocol converter manager is automatically injected through the component management framework. The message processor abstract base class provides a unified protocol conversion call interface. Subclasses do not need to directly manipulate the protocol converter manager; they only need to call the conversion method (denoted as `convert`) provided by the base class at the appropriate location and pass in the source protocol object, the target protocol type identifier, and the conversion direction identifier. This design further reduces the coupling between the business layer code and the protocol conversion framework; the business layer code does not even need to be aware of the existence of the protocol converter manager.
[0107] In this optional embodiment, the message processor shares the same protocol converter instance when performing forward and reverse conversions. Taking device alarm message conversion as an example, the device alarm converter supports both forward conversion (device alarm message → platform alarm message) and reverse conversion (platform alarm message → device alarm message). When performing uplink conversion, the message processor calls the forward conversion process of the device alarm converter, and when performing downlink conversion, it calls the reverse conversion process of the same device alarm converter, without needing to look up different protocol converters for uplink and downlink conversions.
[0108] This optional embodiment achieves transparent integration between the business layer and protocol conversion by integrating a protocol converter manager into the message processor abstract base class. The business layer code only needs to focus on business logic processing, while the protocol conversion is automatically handled by the framework. The design of the conversion decision hook allows subclasses to flexibly control whether protocol conversion is needed, and the conversion process can be skipped directly for internal messages that do not require conversion.
[0109] To more clearly illustrate the complete application process of the protocol conversion method of this application in the smart livestock IoT system, the following detailed explanation is based on the example of the uplink conversion of device alarm messages.
[0110] During system startup, the component management framework scans for device alarm converter classes annotated with component annotations, instantiates these classes into device alarm converter instances, and injects them into the list of discovered converters. In its initialization callback, the protocol converter manager iterates through the list of discovered converters, checks the enabled status of the device alarm converter instance (if enabled), retrieves the source protocol type (device message publishing type) and target protocol type (platform alarm message type) of the device alarm converter using reflection, generates a registration key, registers the device alarm converter instance to the converter registry, and adds it to the global converter list.
[0111] When a device reports an alarm event, the message processor receives the device alarm message, parses the message payload, executes business logic processing, determines that protocol conversion is required, and calls the conversion interface of the protocol converter manager, passing in the device alarm message object, the platform alarm message type identifier, and the forward conversion direction identifier. The protocol converter manager generates a cache key; if it is not found in the converter cache, it precisely matches and finds the device alarm converter in the converter registry, writes it to the converter cache, and returns. The template method flow for the device alarm converter to perform forward conversion is as follows: pre-verification checks the message type and device identifier of the device alarm message; preprocessing converts the alarm status enumeration value from the device-side encoding to the internal unified encoding; core forward conversion maps the fields of the device alarm message to the corresponding fields of the platform alarm message; post-processing removes unnecessary intermediate fields; and post-verification checks the required fields of the platform alarm message. After the conversion is completed, the platform alarm message object is output, and the message processor publishes the platform alarm message object to the cloud platform through the platform communication layer.
[0112] In the reverse conversion scenario, when the cloud platform issues an alarm confirmation command, the message processor receives the platform's alarm confirmation message, determines that protocol conversion is required, and calls the conversion interface of the protocol converter manager, passing in the platform alarm confirmation message object, the device message type identifier, and the reverse conversion direction identifier. The protocol converter manager locates the device alarm converter through a step-by-step search. The device alarm converter executes the template method flow of the reverse conversion: pre-verification checks the alarm identifier and confirmation status fields of the platform alarm confirmation message; preprocessing converts the confirmation status enumeration value from the platform-side encoding to the internal unified encoding; core reverse conversion maps the fields of the platform alarm confirmation message to the corresponding fields of the device alarm confirmation message; post-processing supplements the verification fields required by the device protocol; and post-verification checks the message type field of the device alarm confirmation message. After the conversion is completed, the device alarm confirmation message object is output, and the message processor sends the device alarm confirmation message object to the device through the device communication layer.
[0113] In the actual deployment of the smart livestock IoT system, a total of 11 protocol converters were deployed, covering a complete conversion matrix between device protocols, internal protocols, and platform protocols. Four protocol converters were deployed in the device-to-platform direction (data uplink): a device alarm converter, which converts alarm messages from the device message protocol into platform alarm messages for reporting device alarm events to the cloud platform; a device pig status converter, which converts pig status messages from the device message protocol into platform pig status messages for reporting pig status changes to the cloud platform; a device cleaning data converter, which converts cleaning data messages from the device message protocol into platform cleaning data messages for reporting feed hopper cleaning results to the cloud platform; and a device status converter, which converts device status messages from the device message protocol into platform device status messages for reporting device start / stop status to the cloud platform. Six protocol converters are deployed on the platform-to-device side (downlink commands): a platform feeding plan converter, which converts platform feeding plan data into device message protocol message type 202 for sending feeding plans to feeders; a platform parameter adjustment converter, which converts platform parameter adjustment data into device message protocol message type 204 for sending feeding parameter adjustments; a platform cleaning command converter, which converts platform cleaning commands into device message protocol message type 255 for sending one-click feed hopper cleaning commands; a platform calibration command converter, which converts platform calibration commands into device message protocol message type 402 for sending feeder calibration commands; a platform device status command converter, which converts platform device status commands into device message protocol message type 10 for sending device start / stop commands; and a platform pig status command converter, which converts platform pig status commands into device message protocol message type 10 for sending pig status change commands. One protocol converter is deployed across platforms: a third-party platform converter, which converts third-party platform protocols into device message protocol message type 5 for third-party platform protocol integration.
[0114] In this actual deployment, 11 protocol converters covered bidirectional conversion of more than 35 device message types, processing over 100,000 protocol conversion requests daily. Through converter caching, over 95% of lookup requests were completed via the first-level cache, with an average lookup time in the microsecond range. The protocol converter manager's memory usage remained stable at several megabytes, without significantly pressuring the resources of edge computing nodes. During operation, a runtime hot management mechanism was used to dynamically update the protocol converters multiple times, including adding new protocol converters to support newly connected device models, dynamically removing protocol converters with known issues to trigger degradation, and hot reloading all protocol converters to complete batch version upgrades. All operations did not interrupt the connection of running devices, enabling 24 / 7 uninterrupted operation, with approximately 40% less code compared to traditional solutions. During protocol converter version upgrades, a smooth upgrade and fault degradation mechanism was achieved through multiple versions coexisting under the same registration key, priority sorting, and automatic degradation upon conversion failure, without interrupting device connections.
[0115] In this actual deployment, the three core data structures of the protocol converter manager—the converter registry, the converter cache, and the global converter list—are all implemented using concurrent mapping tables, ensuring thread safety in a multi-threaded environment. During peak periods, multiple message handlers may initiate protocol conversion requests simultaneously. The atomic operations of the concurrent mapping table ensure the thread safety of registration, lookup, and cache write operations, eliminating the need for additional synchronization lock mechanisms. Simultaneously, because the converter cache is frequently read and written during lookups, the lock-free read characteristic of the concurrent mapping table ensures that cache lookups do not block lookup requests from other threads, guaranteeing lookup performance in high-concurrency scenarios. In runtime hot management operations, dynamic registration and dynamic removal are completed through atomic operations of the concurrent mapping table, without blocking ongoing protocol conversion requests. Hot reload operations are completed by first clearing and then re-registering. There is a brief window between clearing and re-registering, during which received protocol conversion requests may throw exceptions due to the inability to find a protocol converter. Therefore, hot reload is suitable for scenarios where protocol converters are updated in batches and short interruptions are acceptable. For scenarios where interruptions are not allowed, dynamic registration and dynamic removal are used for replacement one by one.
[0116] This application, through the above embodiments and optional embodiments, automatically discovers and collects protocol converter instances through the component scanning mechanism of the component management framework; by simultaneously supporting both forward and reverse conversion processes within the same protocol converter, it eliminates the redundancy of writing two sets of code for bidirectional conversion; by defining a standardized five-step conversion process through a template method base class, it ensures consistent behavior across all protocol converters; by using reflection to obtain the generic parent class type information of subclasses to determine the source and target protocol types, it eliminates the burden of manually declaring type information in subclasses; through a hierarchical search mechanism, in most scenarios, the target protocol converter can be obtained through cache hits, avoiding the performance overhead of linear traversal; through a runtime hot management mechanism, it supports dynamic registration, removal, and reloading of protocol converters without restarting the service, ensuring uninterrupted connection for online devices; through a priority mechanism, it supports simultaneous registration and priority sorting of multiple versions of protocol converters under the same conversion path, achieving smooth upgrades of protocol versions; and by integrating the protocol converter manager into the message processor abstract base class, it achieves transparent integration between the business layer and protocol conversion. The above-mentioned protocol conversion methods of this application significantly improve the scalability and maintenance efficiency of protocol conversion. By employing a mechanism that eliminates the need to download protocol conversion rule configuration files from the server and allows edge computing nodes to perform protocol conversion locally, the continuity of protocol conversion services is ensured in scenarios of network fluctuations or outages. Furthermore, by prioritizing multiple version protocol converters under the same registration key and automatically downgrading upon conversion failure, a smooth evolution of protocol versions is achieved.
[0117] See Figure 2 , Figure 2 This is a schematic diagram of the structure of an embodiment of the storage medium provided in this application.
[0118] The storage medium 60 stores program data 61, which, when executed by the processor, implements, as follows: Figure 1 The described protocol conversion method.
[0119] The program data 61 is stored in a storage medium 60 and includes several instructions for causing a network device (such as a router, personal computer, or server) or processor to execute all or part of the steps of the methods described in the various embodiments of this application.
[0120] Optionally, the storage medium 60 can be any medium capable of storing program data 61, such as a USB flash drive, external hard drive, read-only memory (ROM), random access memory (RAM), disk, or optical disc.
[0121] See Figure 3 , Figure 3 This is a schematic diagram of the structure of an embodiment of the computer device provided in this application.
[0122] The computer device 70 includes a processor 72 and a memory 71 interconnected. The memory 71 stores a computer program, and when the processor 72 executes the computer program, it implements, for example, Figure 1 The described protocol conversion method. The memory 71 may include the storage medium 60, or it may be another separately developed memory.
[0123] The computer device 70 can specifically be an edge computing node, an IoT gateway, a server, or a combination of the above. For example, in a smart livestock IoT system, the computer device 70 can be an edge computing node deployed within a farm. It connects downwards to multiple smart feeders and a low-power Bluetooth mesh network gateway via a local area network, and upwards to a cloud platform via the Internet. The edge computing node runs program data for a protocol conversion method, enabling bidirectional conversion between device protocols and platform protocols. When the cloud platform or device protocols change, the protocol converter is updated online through a runtime hot management mechanism, eliminating the need for manual on-site operation at the farm and significantly reducing maintenance costs. This application does not specifically limit the specific form and deployment method of the computer device 70. As long as the computer device 70 can execute the aforementioned protocol conversion method and achieve decoupling and bidirectional conversion between protocol conversion logic and business logic, it is understood to be within the scope of protection of this application.
[0124] Unlike existing technologies, this application discloses a protocol conversion method, storage medium, and computer device. By scanning and instantiating protocol converter classes annotated with component annotations, a registration key is generated based on the source and target protocol types and registered in the converter registry. The target protocol converter is then searched sequentially in the converter cache, converter registry, and global converter list. The target protocol converter executes either a forward or reverse conversion process based on the conversion direction identifier. This achieves complete decoupling of protocol conversion logic from business logic. The business layer only needs to complete the protocol conversion with a single call, and the underlying protocol differences are completely transparent to the business layer. By supporting both forward and reverse conversion processes simultaneously within the same protocol converter, the traditional approach of writing two separate sets of code for uplink and downlink conversion is eliminated. This invention addresses the redundancy issue of code by employing a hierarchical search mechanism. In most scenarios, the target protocol converter can be obtained simply by hitting the cache, avoiding the performance overhead of linear traversal. By allowing multiple versions of protocol converters under the same registration key to coexist and be prioritized, and automatically downgrading to the next lower priority protocol converter instance when conversion fails, it achieves smooth evolution of protocol versions and ensures the continuity of protocol conversion services. Furthermore, the protocol converter class and its type information are deployed and determined locally on the edge computing node. Protocol conversion does not require downloading the protocol conversion rule configuration file from the server. Even in scenarios where communication with the cloud server is interrupted, the edge computing node can still complete the protocol conversion between the device side and the platform side locally. This method improves the maintainability and scalability of the protocol conversion system, facilitating efficient and stable heterogeneous protocol adaptation in IoT scenarios such as smart animal husbandry.
[0125] The various embodiments in this specification are described in a progressive manner. Similar or identical parts between embodiments can be referred to interchangeably. Each embodiment focuses on its differences from other embodiments. In particular, the storage medium embodiments and computer device embodiments are basically similar to the method embodiments, so the descriptions are relatively simple; relevant parts can be referred to the descriptions of the method embodiments.
[0126] The above description is merely an embodiment of this application and does not limit the patent scope of this application. Any equivalent structural or procedural transformations made using the content of this application's specification and drawings, or direct or indirect applications in other related technical fields, are similarly included within the patent protection scope of this application.
Claims
1. A protocol conversion method applied to an edge computing node in a smart livestock IoT system, wherein the edge computing node communicates with equipment within the farm and multiple heterogeneous cloud platforms on the platform side, characterized in that, include: During the system initialization phase, the system scans for protocol converter classes annotated with component annotations, instantiates the protocol converter classes into protocol converter instances, and collects them into the list of discovered converters. The protocol converter class is deployed locally on the edge computing node. The protocol converter instance corresponds to the source protocol type and the target protocol type. The source protocol type and the target protocol type are determined by the generic parent class type information of the protocol converter class. The protocol converter instance is instantiated locally by the edge computing node without downloading the protocol conversion rule configuration file from the server. For each protocol converter instance in the discovered converter list, a registration key is generated based on the source protocol type and target protocol type of the protocol converter instance. The protocol converter instance is then registered in the converter registry to the converter list corresponding to the registration key and added to the global converter list. Protocol converter instances in the converter list corresponding to the same registration key correspond to different version numbers and are sorted from high to low priority. Receive a protocol conversion request; the protocol conversion request carries the source protocol object, the target protocol type identifier, and the conversion direction identifier; Based on the type of the source protocol object and the identifier of the target protocol type, the target protocol converter is searched sequentially in the converter cache, the converter registry, and the global converter list; wherein, when the converter list corresponding to the registration key is precisely matched in the converter registry, the target protocol converter is the protocol converter instance with the highest priority in the converter list. By finding the target protocol converter, a forward conversion process or a reverse conversion process is executed according to the conversion direction identifier, and the converted protocol object is output; wherein, the forward conversion process converts the source protocol object into the target protocol object, and the reverse conversion process converts the target protocol object into the source protocol object; The execution of the forward or reverse conversion process includes: when the target protocol converter fails to convert, recording a degradation log and switching to the next highest priority protocol converter instance in the converter list in descending order of priority to continue the conversion; until the conversion is successful, or when all protocol converter instances in the converter list fail to convert, throwing an exception carrying an error code, source protocol type, target protocol type and failure reason information.
2. The protocol conversion method according to claim 1, characterized in that, The forward and reverse conversion processes are defined through a template method base class. The template method base class declares the forward and reverse conversion processes as non-overridable and sequentially includes pre-validation, preprocessing, core conversion, post-processing, and post-validation. The core conversion includes core forward conversion and core reverse conversion, implemented by subclasses of the template method base class. The pre-validation, preprocessing, post-processing, and post-validation are provided with default implementations by the template method base class, which are then overridden by the subclasses as needed. The execution of the forward or reverse conversion process outputs the converted protocol object, including: When the conversion direction is identified as a forward conversion, the following steps are executed sequentially: pre-verification of the source protocol object, pre-processing of the source protocol object, execution of the core forward conversion, post-processing of the target protocol object, and post-verification of the target protocol object. When the conversion direction is identified as reverse conversion, the following steps are executed sequentially: pre-verification of the target protocol object, pre-processing of the target protocol object, execution of the core reverse conversion, post-processing of the source protocol object, and post-verification of the source protocol object.
3. The protocol conversion method according to claim 1, characterized in that, By obtaining the generic parent class type information of the protocol converter class through reflection, the source protocol type and the target protocol type are determined, including: Determine whether the generic parent class type is a parameterized type; if it is a parameterized type, extract the actual type parameters from the parameterized type, set the first type parameter as the source protocol type, and set the second type parameter as the target protocol type; if it is not a parameterized type, throw an exception and prompt the protocol converter class that a generic parameter must be specified.
4. The protocol conversion method according to claim 1, characterized in that, The step of registering the protocol converter instance to the converter list corresponding to the registration key in the converter registry and adding it to the global converter list includes: In the initialization callback, each protocol converter instance in the list of discovered converters is iterated over; Check if the protocol converter instance is empty; if it is empty, skip this step. Check the enabled status of the protocol converter instance; if it is disabled, skip this step. A registration key is generated using the source protocol type and target protocol type of the protocol converter instance; Add the protocol converter instance to the converter list corresponding to the registration key in the converter registry, and sort them from high to low priority; Add the protocol converter instance to the global converter list.
5. The protocol conversion method according to claim 1, characterized in that, The step-by-step target protocol converter includes: Generate a cache key based on the type of the source protocol object and the identifier of the target protocol type; The converter cache is searched using the cache key. If the cache is hit, the cached protocol converter is returned directly. If the cache is not hit, perform an exact match search in the converter registry using the cache key. If a corresponding converter list is found, take the highest priority protocol converter in the converter list, write it into the converter cache, and return. If no exact match is found, iterate through the global converter list, perform a compatibility check on each protocol converter, select the highest priority among all compatible protocol converters, write it into the converter cache, and return. If the protocol is not found after searching at each level, an exception is thrown; the exception carries an error code and information about the source protocol type and the target protocol type.
6. The protocol conversion method according to claim 1, characterized in that, After registering the converters to the list corresponding to the registration key in the converter registry and adding them to the global converter list, the system also includes at least one of the following: Upon receiving a new protocol converter instance, a registration key is generated and added to the converter registry and the global converter list, sorted by priority from high to low; the new protocol converter instance takes effect immediately. Receive the protocol converter instance to be removed, remove it from the converter registry and the global converter list, and clear the converter cache to prevent dirty reads; Clear the converter registry, the converter cache, and the global converter list, and re-execute the initialization callback to perform a full re-registration.
7. The protocol conversion method according to claim 1, characterized in that, Before receiving the protocol conversion request, the method further includes: receiving a message through a message processor, parsing the message payload and performing business logic processing, and determining whether protocol conversion is required; if so, generating the protocol conversion request. Following the output of the converted protocol object, the method further includes: sending the converted protocol object to the counterpart system; The message processor shares the same protocol converter instance when executing the forward conversion process and the reverse conversion process.
8. The protocol conversion method according to claim 1, characterized in that, The step-by-step search for the target protocol converter includes: when the converter list corresponding to the registration key is precisely matched in the converter registry, returning the highest priority protocol converter instance in the converter list; when the highest priority protocol converter instance is removed, returning the next highest priority protocol converter instance in the converter list when searching again.
9. A storage medium storing program data thereon, characterized in that, When the program data is executed by the processor, it implements the steps of the protocol conversion method as described in any one of claims 1 to 8.
10. A computer device, characterized in that, It includes an interconnected processor and a memory, the memory storing a computer program, and the processor executing the computer program to implement the steps of the protocol conversion method as described in any one of claims 1 to 8.
