UI interface control method realized by Modbus protocol stack based on Android

By optimizing Modbus communication using a multi-threaded queue and event dispatch mechanism on the Android platform, the problems of UI thread blocking and data competition were solved, achieving efficient and stable industrial communication and improving the application capabilities of Android devices in industrial scenarios.

CN121585573APending Publication Date: 2026-02-27JINGWEI TEXTILE MASCH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511755466.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-26
Publication Date
2026-02-27

AI Technical Summary

Technical Problem

Existing technologies for implementing Modbus communication on the Android platform suffer from problems such as UI thread blocking, data competition caused by multi-threaded concurrency, poor real-time performance due to lack of priority scheduling, inefficient UI update mechanisms, and weak exception handling mechanisms, making it difficult to meet the high reliability and high efficiency requirements of industrial communication.

Method used

The system employs multi-threading technology, using ordinary queues and priority queues to handle background polling and user interaction requests respectively. It manages Modbus communication tasks through a thread pool, and combines event dispatching and data caching mechanisms to optimize UI updates and exception handling, ensuring rapid response and system stability for critical tasks.

Benefits of technology

It enables efficient and stable Modbus communication for Android devices in industrial scenarios, solves UI lag and data corruption issues, improves the response speed of critical tasks and the overall reliability of the system, and meets the real-time requirements of industrial control.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121585573A_ABST
    Figure CN121585573A_ABST
Patent Text Reader

Abstract

The invention provides an Android-based UI interface control method implemented by a Modbus protocol stack, which comprises the following steps: S1, starting equipment, constructing a common queue and a priority queue by the Modbus protocol stack, starting a background thread to wait for requests of the two queues, and subscribing related messages of the Modbus protocol stack by an application layer; s2, the application layer adds the polling requests to a common queue, and a background thread sequentially obtains and processes the requests from the common queue; s3, the UI operation initiates a request, a request command is put into the priority queue, and the Modbus protocol stack immediately executes the command of the priority queue after completing the current common request; s4, after the command of the priority queue is executed, the Modbus protocol stack continues to execute the command of the common queue; and S5, the Modbus protocol stack executes the queue command, obtains and caches the parameter state and the like involved in the command, and sends the updated state parameter to the UI interface after the parameter state and the like change. According to the method, the problem of single-thread blocking of the UI is solved by adopting a multi-thread technical design, the response speed of a key task is improved by adopting a priority queue design, and the UI or data processing can be notified only when data changes.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to a method for displaying an industrial real-time communication interface, and more particularly to a UI control method based on the Android Modbus protocol stack. Background Technology

[0002] The Modbus protocol, as a mature and open industrial communication protocol, has been widely used in industrial control, smart instruments, data acquisition, and other fields, and became a Chinese national standard (GB / T19582-2008) in 2008. This protocol supports multiple physical layers, including serial (such as RS-485) and Ethernet, and features a simple structure, ease of implementation, and strong compatibility. With the rapid development of the Industrial Internet and intelligent manufacturing, Android-based industrial terminal devices, due to their openness, customizability, and comprehensive network functions, are gradually being introduced into industrial settings for human-machine interaction, data monitoring, and equipment control.

[0003] However, the Android system itself is not designed for real-time industrial communication scenarios. Its UI thread mechanism requires that interface operations not be blocked, otherwise it is prone to causing Application Not Responding (ANR) issues. Modbus communication involves time-consuming operations such as waiting for slave responses, data verification, and timeout retries. If these operations are performed directly in the UI thread, it will severely affect system response speed and user experience. In addition, industrial environments often involve complex scenarios such as multiple slave polling, command priority differentiation, and communication exception handling. Traditional simple thread models are difficult to meet the high reliability and high real-time communication requirements.

[0004] In existing technologies, although there are a few Modbus implementations based on Android, most of them do not fully consider the separation mechanism between the UI thread and the communication thread, or lack effective command scheduling and data distribution strategies, resulting in problems such as low communication efficiency, UI lag, and imperfect error handling in practical applications.

[0005] like Figure 1 In the illustrated technical architecture diagram, after the application layer initiates a Modbus request, the system directly hands the request over to the UI thread or a single communication thread for processing. Within this thread, the system executes the complete Modbus request process, including data encapsulation, command sending, waiting for slave station responses, data reception, and verification. Due to network latency and slow device response common in industrial communication, this waiting process can cause thread blocking. After the request is completed, the UI is updated or error handling is performed directly in the current thread based on the result, after which the thread continues executing subsequent tasks.

[0006] like Figure 2 The hardware architecture diagram shown includes the following hardware components:

[0007] 1. Application layer / main control unit (Android smart terminal), core equipment: Android smart terminal (industrial tablet computer, handheld terminal or customized Android device).

[0008] Role: As the master station in the Modbus communication network.

[0009] Functionality: The device runs an application (APP) integrating the Modbus protocol stack designed in this paper. This APP generates various Modbus commands (such as reading / writing coils and registers) by calling the APIs provided by the protocol stack and sends them out through the hardware interface. Simultaneously, it receives and processes response data from slave stations and displays it on the UI.

[0010] 2. Communication Conversion Layer (Physical Link Adaptation)

[0011] Core equipment: USB to RS-485 module (commonly used for serial communication RS-485), or directly via Ethernet switch (for Modbus / TCP).

[0012] Role: Implements the conversion between physical signals and interfaces.

[0013] Function: Android devices typically lack a standard RS-485 interface. Therefore, an external "USB to RS-485" module is needed via USB-OTG to convert the Android system's USB signal into the RS-485 signal commonly used in industrial environments. This serves as a bridge connecting the Android device and the field controller.

[0014] 3. Field Equipment Layer / Slave Station (Controlled Industrial Equipment)

[0015] Core equipment: main control PLC, single-spindle control board or other sensors, drivers, etc. that support Modbus protocol.

[0016] Role: As a slave in a Modbus communication network.

[0017] Function:

[0018] Master PLC: Usually acts as a first-level slave station, responsible for the overall logic control of the equipment, interaction with the upper-level information system, and management of the cluster of individual control boards under it.

[0019] Single-spindle control board: Each control board is responsible for the precise control and status monitoring of an independent unit (such as a spinning spindle). Each slave station must be configured with a unique station number (from 1 to 247) for the master station to address.

[0020] Network Topology: These slave devices are connected together in a daisy-chain bus topology via an RS-485 bus. Termination resistors (typically 120 ohms) need to be installed at both ends of the RS-485 bus to eliminate signal reflections and ensure communication quality.

[0021] Disadvantages of existing technology:

[0022] (1) UI thread blocking and response delay: If the Modbus communication task is executed on the UI thread, the blocking during the waiting period will directly cause the interface to fail to refresh and respond to user operations in a timely manner, which is very likely to trigger the application unresponsive (ANR) problem and seriously affect the user experience.

[0023] (2) Data contention caused by multi-threaded concurrency: If a single communication thread is used to handle multiple requests, UI blocking can be avoided, but multi-threaded concurrent requests cannot be supported. When multiple operation sources (such as interface control and background polling) initiate requests at the same time, the lack of an effective queue and scheduling mechanism can easily cause bus access conflicts, data frame interleaving or loss, and low communication reliability.

[0024] (3) Poor real-time performance due to lack of priority scheduling: The scheme does not distinguish the priority of requests. High real-time operations (such as emergency stop instructions) may be blocked by a large number of regular polling tasks, which cannot meet the needs of immediate response to key instructions in industrial control.

[0025] (4) Inefficient UI update mechanism: Regardless of whether the data changes, the UI is directly updated after each request response. Frequent redrawing operations occupy UI thread resources, causing interface lag and wasting system processing power.

[0026] (5) Weak exception handling mechanism: When the slave device communication is abnormal, the system cannot effectively identify and clear the corresponding request queue, which causes subsequent commands to wait for timeout, and the communication efficiency is greatly reduced.

[0027] In summary, existing technologies, due to the lack of systematic design for task scheduling, thread safety, data distribution, and exception recovery in Modbus communication, make it difficult to achieve highly reliable and efficient industrial-grade Modbus communication on the Android platform, thus restricting the in-depth application of Android devices in complex industrial scenarios.

[0028] Therefore, there is an urgent need for a technical solution that can run the Modbus protocol stack efficiently and stably on the Android platform, which can meet the real-time and reliability requirements of industrial communication, while also taking into account the UI responsiveness of the Android system, thereby promoting the wider application of Android devices in the industrial field. Summary of the Invention

[0029] This invention provides a UI control method based on the Android Modbus protocol stack, which solves the problems of low communication efficiency, UI lag, and incomplete error handling in current Android-based Modbus implementations. The technical solution is as follows:

[0030] A UI control method based on the Android Modbus protocol stack includes the following steps:

[0031] S1: Start the device, the Modbus protocol stack constructs a normal queue and a priority queue, starts a background thread to wait for requests from the two queues, and the application layer subscribes to relevant messages from the Modbus protocol stack;

[0032] S2: The application layer adds polling requests to a regular queue, and the background thread retrieves and processes the requests sequentially from the regular queue;

[0033] S3: When a UI operation initiates a request, the request command is placed in a priority queue. The Modbus protocol stack then executes the command in the priority queue immediately after completing the current normal request.

[0034] S4: After executing the commands in the priority queue, the Modbus protocol stack continues to execute commands in the normal queue;

[0035] S5: After the Modbus protocol stack finishes executing the queue command, it obtains and caches the parameters and statuses involved in the command. When there are any changes, it sends the updated status parameters to the UI.

[0036] Furthermore, in step S1, in the Modbus protocol stack, a request queue is defined through the abstract class CommandManager. The request queue includes a normal queue cmdListNormal and a priority queue cmdListPriority.

[0037] ModbusCommandManager is derived from CommandManager and implements the start() interface. It also provides four data request APIs for the Modbus protocol to the application layer: putCoilsCmd, putInputsCmd, putInputRegisterCmd, and putHoldingRegisterCmd. Based on the station number, address, data, read / write, and priority provided by the application layer, it generates a Modbus request array and adds the request array to either the priority queue cmdListPriority or the normal queue cmdListNormal.

[0038] The application layer sends requests through the ModbusCommandManager, which provides four data request APIs for the Modbus protocol. The application layer becomes a subscriber through EventBus.getDefault.register() and defines a callback function, void onMessage(HoldingRegister holdingRegister), through the @Subscribe annotation. The threadMode parameter is used to select the thread in which the callback function is executed, specifying that the callback function is executed on the main thread.

[0039] Furthermore, in step S2, after the application layer adds the polling requests to the ordinary queue, the background thread obtains a request array according to the priority rule, creates a ModbusCallable object, and submits it to the executorService thread pool for execution. The get() method of Future returns a ModbusData object. Then, the CommandAction interface is executed, which implements the act() interface through ModbusAction. Based on the data provided by ModbusData, readSucceed(), readFailed(), writeSucceed(), and writeFailed() of PLCData are executed respectively, and the data is cached in a Map. If the data changes, the data is distributed through EventBus. The application layer registers with EventBus and subscribes to specific data types to receive the data.

[0040] Furthermore, in step S3, after the UI submits a request through the functions putCoilsCmd, putInputsCmd, putInputRegisterCmd, and putHoldingRegisterCmd, the UI task continues. The UI's request is placed in the priority queue cmdPriorityList. After the background thread thead completes the current request, it first retrieves the request from the priority queue. The UI's request will be executed first and a response will be obtained quickly.

[0041] Furthermore, in step S5, the Modbus protocol stack caches the response data in four types of Maps of PLCData. When the response data and the cached data are not equal, the data has changed. The data is cached and the corresponding object is constructed, and then sent through EventBus. When the response data and the cached data are equal, the data has not changed, and no caching operation is performed.

[0042] Furthermore, for ordinary queues or priority queues, when there are no errors or timeouts, the device receives data from Modbus communication requests, verifies and processes the data, and directly dispatches messages to update the UI in the current thread based on the results. After that, the thread continues to execute subsequent tasks.

[0043] Furthermore, when a timeout occurs, by implementing the `act()` interface of `CommandAction`, if the success flag in `ModbusData` is set to failure, `act()` returns `CLEAR_ID`, and all request commands sent to this slave are removed from the queue, thereby improving command execution efficiency.

[0044] The UI control method based on the Android Modbus protocol stack has the following advantages:

[0045] (1) Multi-threading technology is used to solve the problem of UI single-threaded blocking;

[0046] (2) The priority queue design can improve the UI operation experience, improve the response speed of critical tasks, and realize mutual exclusion between requests to solve the problem of data corruption.

[0047] (3) Optimize the data update mechanism so that the UI or data processing is notified only when the data changes, which greatly reduces the system resource consumption;

[0048] (4) Abnormal handling design: In a multi-slave system, if a slave cannot communicate, the request of the relevant slave can be deleted from the request queue and an alarm will be triggered to ensure the overall availability of the system. Attached Figure Description

[0049] Figure 1 This is a schematic diagram of the existing Modbus implementation based on Android.

[0050] Figure 2 This is a schematic diagram of the existing Android-based Modbus implementation hardware structure;

[0051] Figure 3 This is a schematic diagram of the Modbus master process;

[0052] Figure 4 This is a flowchart illustrating the UI control method implemented using the Android-based Modbus protocol stack.

[0053] Figure 5 This is the UML architecture diagram of the Modbus protocol stack. Detailed Implementation

[0054] like Figure 3As shown, the Modbus protocol is a master / slave architecture protocol. The master sends a request and waits for the slave to respond. If there is no response within a specified time or the verification fails, error handling is performed. If the verification is successful, the data is processed and a data interaction is completed. In Android application development, the following issues need to be considered: (1) There are waiting operations in the process, which cannot be executed in the UI thread, as this will block the UI thread; (2) For serial communication, this process cannot be executed by multiple threads, which will cause bus data to be disordered; (3) Sending request actions may occur in the UI thread or background thread, such as interface operations and polling operations; (4) Request commands need to be prioritized, otherwise a large number of polling operations will cause the interface operations to wait; (5) The UI should be updated only after the data changes, otherwise a large number of polling operations will cause the UI to freeze, or even ANR (Application Not Responding, which is an error message in the Android system indicating that the application is unresponsive, usually caused by the main thread performing time-consuming operations).

[0055] Therefore, the following solutions are used to address the above issues: (1) Start a background thread to retrieve requests from cmdPriorityList or cmdNormalList according to priority. Retrieve one request at a time, and retrieve the next one after completing the task. This will not block the UI thread, and the requests will be mutually exclusive, preventing multiple requests from being sent at the same time and causing data corruption. (2) To improve the UI operation experience, UI requests are placed in cmdPriorityList, and background requests are placed in cmdNormalList. This way, UI requests will be executed first and receive a response quickly. (3) Cache the response data in the four types of Maps of PLCData. When the response data and the cached data are not equal, the data has changed. Cache the data and build the corresponding object, such as HoldingRegister, and send it through EventBus. (4) UI or data processing objects that subscribe to HoldingRegister messages can execute the corresponding callback functions to display or process the data change.

[0056] like Figure 4 As shown, the UI control method based on the Android Modbus protocol stack includes the following steps:

[0057] S1: Start the device, the Modbus protocol stack constructs a normal queue and a priority queue, starts a background thread to wait for requests from the two queues, and the application layer subscribes to relevant messages from the Modbus protocol stack;

[0058] like Figure 5As shown in the Modbus protocol stack UML architecture diagram, ModbusCommandManager (Modbus Command Manager) is derived from CommandManager and implements the start() interface to start a background thread. It also provides four data request interface APIs for the application layer: putCoilsCmd, putInputsCmd, putInputRegisterCmd, and putHoldingRegisterCmd. Based on the station number, address, data, read / write, and priority provided by the application layer, it generates a Modbus request array and calls putPriorityCmd or putNormalCmd according to the priority to add the request array to the priority queue cmdListPriority or the normal queue cmdListNormal.

[0059] The application layer sends requests through the ModbusCommandManager, which provides four data request APIs for the Modbus protocol. The application layer becomes a subscriber using EventBus.getDefault.register() and defines a callback function `void onMessage(HoldingRegister holdingRegister)` using the `@Subscribe` annotation. Taking the holding register as an example, data distributed by PLCData (Programmable Logic Controller Data) will trigger this callback function call. The `threadMode` parameter allows selection of the thread on which the callback function executes; for example, `@Subscribe(threadMode = ThreadMode.MAIN)` specifies that the callback function should execute on the main thread.

[0060] in,

[0061] putCoilsCmd is a Modbus protocol instruction used to control coils (coils). It is typically used in PLCs or industrial automation equipment to send commands via serial or Ethernet ports to set the status of digital outputs (such as relays, switches, etc.).

[0062] putInputsCmd is a Modbus protocol instruction used to read input signals (Input). It is typically used in PLCs or industrial automation equipment to send commands via serial port or network port to read the status of input signals (such as switches, buttons, etc.).

[0063] putInputRegisterCmd is a Modbus protocol instruction used to read input registers. It is typically used in PLCs or industrial automation equipment to send commands via serial or network ports to read values ​​from input registers (such as temperature and pressure).

[0064] putHoldingRegisterCmd is a Modbus protocol instruction used to read and write holding registers. It is typically used in PLCs or industrial automation equipment to send commands via serial or network ports to read and write holding registers (such as setpoints, alarm points, etc.).

[0065] The putPriorityCmd pointer points to the priority queue for adding requests.

[0066] The putNormalCmd pointer points to the normal queue for adding requests.

[0067] EventBus.getDefault().register() is the standard method for registering event subscribers. The core process includes finding the subscription method, caching, and registering it to the event mapping table.

[0068] The `threadMode` parameter determines the thread on which the callback function executes. `ThreadMode.MAIN`: Executes on the main thread; `ThreadMode.POSTING`: Executes on the thread where the message publisher resides; `ThreadMode.BACKGROUND`: Executes on a background thread; `ThreadMode.ASYNC`: Executes on a separate thread, different from both the publisher and the main thread.

[0069] S2: The application layer adds polling requests to a regular queue, and the background thread retrieves and processes the requests sequentially from the regular queue.

[0070] The background thread `thread` retrieves an array of requests according to a priority rule, creates a `ModbusCallable` object, and submits it to the `executorService` thread pool for execution. `executorService` then executes the `call()` interface, which implements... Figure 3 The process returns to Future. <modbusdata>For objects of type `Future`, the `get()` method returns a `ModbusData` object. For details regarding thread pools, please refer to the Java thread pool documentation. The `ModbusData` object contains a send array, a receive array, and a success flag.

[0071] Next, the CommandAction interface is executed. ModbusAction implements the act() interface. Based on the data provided by ModbusData, it executes PLCData's readSucceed(), readFailed(), writeSucceed(), and writeFailed() methods respectively, caching the data in a Map. If the data changes, it is distributed through EventBus. The application layer registers with EventBus and subscribes to specific data types to receive the data. For details on using EventBus, please refer to the Square official documentation. act() returns ActionType, which determines how to operate on the request queue. REPEAT means do not delete, NEXT means delete, CLEAR means delete all, and CLEAR_ID means delete all commands with the same station number as the request. The process then continues to retrieve the next command and execute the above steps.

[0072] in:

[0073] In Java, Future is an interface that represents the result of an asynchronous computation. It provides methods for checking whether a computation is complete, waiting for the computation to complete, and retrieving the result. When performing a time-consuming computation task, using Future allows you to obtain the result after the computation is complete, while other tasks can continue to be executed.

[0074] CommandAction refers to the command processing interface, and ModbusAction refers to the Modbus command processing class, which is derived from CommandAction and implements the act() interface.

[0075] S3: When a UI operation initiates a request, the request command is placed in a priority queue. The Modbus protocol stack then executes the command in the priority queue immediately after completing the current normal request.

[0076] To ensure a smooth UI, Android does not allow time-consuming operations to be executed on the UI thread. Time-consuming operations can cause UI lag and even Application Not Responding (ANR) issues. Therefore, the following improvements have been made to Android: To enhance the UI experience, after the UI submits a request using the functions `putCoilsCmd`, `putInputsCmd`, `putInputRegisterCmd`, and `putHoldingRegisterCmd`, it continues its UI tasks. Time-consuming tasks are executed by a background thread in the Modbus protocol stack, avoiding UI execution of time-consuming operations. UI requests are placed in a priority queue `cmdPriorityList`. After the background thread `thead` completes its current request, it retrieves a request from the priority queue, ensuring that UI requests are executed first and receive a fast response. Requests are executed sequentially, achieving mutual exclusion and preventing data corruption.

[0077] S4: After executing the commands in the priority queue, the Modbus protocol stack continues to execute commands in the normal queue;

[0078] After the Modbus protocol stack finishes executing the UI recovery task, it executes the commands for the normal queue to continue the application layer's polling requests.

[0079] S5: After the Modbus protocol stack finishes executing the queue command, it obtains and caches the parameters and statuses involved in the command. When there are any changes, it sends the updated status parameters to the UI.

[0080] The ModbusAction class, which performs caching actions, caches the response data in four types of Maps within PLCData. When the response data and the cached data are not equal, the data has changed. The cached data is then used to construct a corresponding object, such as HoldingRegister, which is sent via EventBus. UI or data processing objects that subscribe to HoldingRegister messages can execute corresponding callback functions to display or process the data change. When the response data and the cached data are equal, the data has not changed, no caching operation is performed, and no message is sent, reducing CPU and memory resource consumption.

[0081] Furthermore, regardless of whether it is a regular queue or a priority queue, when there are no errors or timeouts, the device receives data from Modbus communication requests, verifies and processes the data, and directly dispatches messages to update the UI in the current thread based on the results. After that, the thread continues to execute subsequent tasks.

[0082] When a timeout occurs, such as in a multi-PLC control system with multiple slaves, if one slave goes offline, all request commands sent to that slave will time out. This can be mitigated by implementing the `act()` interface of `CommandAction`. If the success flag in `ModbusData` is set to failure, `act()` returns `CLEAR_ID`, thus removing all request commands sent to that slave from the queue and improving command execution efficiency. When an error occurs, such as electromagnetic interference causing data corruption, the current request can be re-executed by implementing the `act()` interface and returning `REPEAT`.

[0083] In an embodiment of the present invention, protocol stack testing is performed:

[0084] The test system consists of Android devices connected to a PC via a serial bus. The Android device implements the Master using a protocol stack, while the PC uses ModSim software to simulate multiple Slaves. In the test system, the Android Master sends requests, the protocol stack converts application-layer data into protocol data, sends it to the PC, waits for a response from ModSim, parses the response data, and completes data caching and distribution. The tests include functional and performance testing. Functional tests include read / write tests for four command types and Slave disconnection tests. Performance tests assess UI smoothness and communication success rate.

[0085] When the Android Master polls four Slaves, the data is completely consistent between the Android device's UI data and ModSim data. Disconnecting one Slave does not affect the other three. With the UI thread and background thread simultaneously sending 5000 requests, UI data updates are smooth. Monitoring the communication status via ModSim shows a 100% success rate for 10000 requests, with zero dropped or incorrect frames.

[0086] The test system is built as follows:

[0087] Android Master: An industrial tablet PC that runs a monitoring app that integrates this protocol stack.

[0088] PLC and Single Ingot Simulator: Run ModSim software on PC to simulate 1 master PLC (station number 1) and 128 single ingot control board slave stations (station numbers 2-129).

[0089] Test results:

[0090] Functional testing: The APP can correctly read and write the PLC's holding registers (such as setting the machine speed) and the input registers of individual spindles (such as reading the output). Simulating any single spindle going offline, the APP can quickly identify it and mark it as offline on the UI, without affecting the monitoring of other single spindles.

[0091] Performance testing: While continuously polling 128 single-spindle plates, UI operations such as swiping and button clicking were performed. The UI showed no lag whatsoever. After extended testing, the communication success rate reached 100%, with no dropped or misaligned frames, meeting the stringent stability requirements of the textile industry.

[0092] The relevant terms are as follows:

[0093] 1. UI Thread (Main Thread): This refers to the main thread created by the system when an Android application starts. In this invention, this thread is responsible for handling the refresh and interaction response of the user interface (UI). To ensure a smooth UI, this protocol stack architecture explicitly stipulates that all time-consuming Modbus communication operations must not be executed in this thread.

[0094] 2. Command Queues (cmdListNormal / cmdListPriority): These are data structures that follow a first-in, first-out (FIFO) rule, used to cache pending request commands. In this invention, two command queues are set up: a normal queue (cmdListNormal) for storing regular requests such as background polling; and a priority queue (cmdListPriority) for storing high-real-time requests triggered by user interaction (such as emergency stops and parameter modifications). This dual-queue mechanism ensures that high-priority commands are processed first.

[0095] 3. Thread Pool (executorService): This refers to a management tool that can reuse multiple threads to avoid the performance overhead caused by frequently creating and destroying threads. In this invention, a fixed thread pool (usually a single thread) is used to sequentially execute Modbus communication tasks retrieved from the queue, thereby ensuring the order of data frames on the serial bus (such as RS-485) and avoiding data corruption caused by concurrent transmission by multiple threads.

[0096] 4. ModbusCallable: Refers to a class that implements the Callable interface, which encapsulates a complete Modbus communication process. In this invention, this object is created by the protocol stack and submitted to the thread pool for execution. It is responsible for execution. Figure 3 The Modbus master station process shown includes protocol data encapsulation, sending requests, waiting for responses, verifying data, etc., and returns a ModbusData object containing the communication results (success / failure, sent / received data).

[0097] 5. Data Cache (Map): This refers to a data structure that stores data in key-value pairs. In this invention, the protocol stack caches the latest data (such as register values) returned by the slave device in a Map. The key is typically a combination of the device station number and the register address, and the value is the corresponding data value. This mechanism is used to compare whether the data has changed.

[0098] 6. Event Bus: Refers to a message passing library based on a publish / subscribe pattern. In this invention, when the protocol stack determines that the data in the cache has changed, it does not directly update the UI, but instead publishes an event containing the new data through the Event Bus. Application layer components (such as UI Activities) only need to subscribe to the data types they are interested in to receive the event callback in a designated thread (such as the UI thread), thereby achieving decoupling and thread-safe UI updates.

[0099] 7. ActionType: This is an enumeration type used to define the subsequent operation strategy for the request queue after a communication is completed. In this invention, it includes: NEXT (delete the current request and process the next one), REPEAT (do not delete, repeat the current request for retrying), CLEAR_ID (delete all requests in the queue pointing to the same slave address, used for quick cleanup when the slave goes offline), and CLEAR (clear the entire queue). This provides flexible error handling and flow control capabilities.

[0100] 8. Slave Device Disconnection Handling (CLEAR_ID): This refers to the specific handling strategy when a communication failure (such as a timeout) is detected in a slave device. In this invention, after determining the communication failure through the `act()` method of the `CommandAction` interface, it can return the `CLEAR_ID` action type. This instruction clears all pending commands sent to the failed slave in the request queue, preventing subsequent commands from being blocked while waiting for a response from the slave, thereby significantly improving the overall communication efficiency of the system.

[0101] The relevant literature is as follows:

[0102] 1. National Standard: GB / T19582-2008 "Industrial Automation Network Specification Based on Modbus Protocol";

[0103] Relevance Note: This standard is the standardized document for the Modbus protocol in China, providing the fundamental protocol specification basis for this invention. Any Modbus protocol stack implemented on the Android system must conform to the data model, function codes, and communication flow defined in this standard. This invention is fully compatible with this specification at the protocol layer.

[0104] 2. Wang Pei, Chen Jinying, Tong Jiaolong. Analysis and Implementation of Embedded Modbus Protocol for IoT Applications. Instrumentation Technology and Sensors, 2018(7):102-106;

[0105] Relevance Note: This document introduces a method for implementing the Modbus protocol on embedded devices, representing a common approach to implementing industrial communication on resource-constrained devices. Its implementation may involve simple task scheduling and data processing, which are highly relevant to the technical field of this invention.

[0106] 3. greenrobot. EventBus: Events for Android;

[0107] Relevance Note: EventBus is a widely used event publish / subscribe library on the Android platform. This invention employs EventBus as the notification mechanism for data changes in its architecture to achieve decoupling and thread switching. This document represents the prior art upon which the implementation components of this invention rely.

[0108] 4. Oracle. ExecutorService (Java Platform SE 8);

[0109] Relevance Note: Java's ExecutorService provides the basic framework for managing thread pools. This invention utilizes ExecutorService to execute specific Modbus communication tasks (i.e., ModbusCallable), achieving concurrent management and resource control of communication tasks.< / modbusdata>

Claims

1. A UI control method based on the Android Modbus protocol stack, comprising the following steps: S1: Start the device, the Modbus protocol stack constructs a normal queue and a priority queue, starts a background thread to wait for requests from the two queues, and the application layer subscribes to relevant messages from the Modbus protocol stack; S2: The application layer adds polling requests to a regular queue, and the background thread retrieves and processes the requests sequentially from the regular queue; S3: When a UI operation initiates a request, the request command is placed in a priority queue. The Modbus protocol stack then executes the command in the priority queue immediately after completing the current normal request. S4: After executing the commands in the priority queue, the Modbus protocol stack continues to execute commands in the normal queue; S5: After the Modbus protocol stack finishes executing the queue command, it obtains and caches the parameters and statuses involved in the command. When there are any changes, it sends the updated status parameters to the UI.

2. The UI interface control method based on the Android Modbus protocol stack according to claim 1, characterized in that: In step S1, in the Modbus protocol stack, a request queue is defined through the abstract class CommandManager. The request queue includes a normal queue cmdListNormal and a priority queue cmdListPriority.

3. The UI control method based on the Android Modbus protocol stack according to claim 2, characterized in that: ModbusCommandManager is derived from CommandManager and implements the start() interface. It also provides four data request APIs for the Modbus protocol to the application layer: putCoilsCmd, putInputsCmd, putInputRegisterCmd, and putHoldingRegisterCmd. Based on the station number, address, data, read / write, and priority provided by the application layer, it generates a Modbus request array and adds the request array to either the priority queue cmdListPriority or the normal queue cmdListNormal.

4. The UI control method based on the Android Modbus protocol stack according to claim 3, characterized in that: The application layer sends requests through the ModbusCommandManager, which provides four data request APIs for the Modbus protocol. The application layer becomes a subscriber through EventBus.getDefault.register() and defines a callback function, void onMessage(HoldingRegister holdingRegister), through the @Subscribe annotation. The threadMode parameter is used to select the thread in which the callback function is executed, specifying that the callback function is executed on the main thread.

5. The UI control method based on the Android Modbus protocol stack according to claim 1, characterized in that: In step S2, after the application layer adds the polling requests to the ordinary queue, the background thread obtains a request array according to the priority rule, creates a ModbusCallable object, and submits it to the executorService thread pool for execution. The get() method of Future returns a ModbusData object. Then, the CommandAction interface is executed, which implements the act() interface through ModbusAction. Based on the data provided by ModbusData, readSucceed(), readFailed(), writeSucceed(), and writeFailed() of PLCData are executed respectively, and the data is cached in a Map. If the data changes, the data is distributed through EventBus. The application layer registers with EventBus and subscribes to specific data types to receive the data.

6. The UI interface control method based on the Android Modbus protocol stack according to claim 1, characterized in that: In step S3, after the UI submits a request through the functions putCoilsCmd, putInputsCmd, putInputRegisterCmd, and putHoldingRegisterCmd, the UI task continues. The UI's request is placed in the priority queue cmdPriorityList. After the background thread thead completes the current request, it first retrieves the request from the priority queue. The UI's request will be executed first and a response will be obtained quickly.

7. The UI interface control method based on the Android Modbus protocol stack according to claim 1, characterized in that: In step S5, the Modbus protocol stack caches the response data into four types of Maps in PLCData. When the response data and the cached data are not equal, the data has changed. The data is cached and the corresponding object is constructed, and then sent through EventBus. When the response data and the cached data are equal, the data has not changed, and no caching operation is performed.

8. The UI control method based on the Android Modbus protocol stack according to claim 1, characterized in that: For ordinary queues or priority queues, when there are no errors or timeouts, the device receives data from Modbus communication requests, verifies and processes the data, and dispatches messages to update the UI directly in the current thread based on the results. After that, the thread continues to execute subsequent tasks.

9. The UI interface control method based on the Android Modbus protocol stack according to claim 8, characterized in that: When a timeout occurs, by implementing the `act()` interface of `CommandAction`, if the success flag in `ModbusData` is set to failure, `act()` returns `CLEAR_ID`, and all request commands sent to this slave are removed from the queue, thereby improving command execution efficiency.