The rapid formalization of the low-altitude economy as a national strategic emerging industry has catalyzed the large-scale deployment of Unmanned Aerial Vehicles (UAVs or drones) across diverse sectors including logistics, precision agriculture, and infrastructure inspection. Consequently, the low-altitude airspace is evolving into a complex operational environment characterized by multiple dynamic agents and high-density traffic. This paradigm shift presents formidable challenges for airspace safety regulation. Critical issues such as mid-air conflicts, unauthorized incursions into sensitive zones, and operational interference with manned aviation have emerged as pivotal constraints on the sustainable exploitation of low-altitude resources. To address these challenges, the concept of dynamic airspace management has gained prominence, wherein geofencing serves as a cornerstone technology for digital airspace governance. UAV geofencing systems are fundamentally designed to enforce virtual spatial boundaries, thereby constraining drone flight paths and ensuring operational compliance with predefined rules.

Substantial research has been dedicated to developing UAV low-altitude digital supervision platforms. Previous systems have integrated functionalities such as user administration, geofence configuration, and data replay. Ground station software has been built upon platforms like Google Earth, incorporating geofencing modules. More advanced architectures adopt hierarchical designs, situating geofence management within a system control layer to support the dynamic addition, deletion, and modification of temporary no-fly zones directly on map interfaces, backed by database technology for persistent storage and retrieval. Innovations extend to integrating 5G communication and blockchain technology within UAV cloud platforms, where geofences dynamically delineate blockchain-managed airspace boundaries. In such models, a central authority manages critical restricted airspace, while a blockchain oversees public airspace, aiming to enhance utilization efficiency. Real-time flight safety alert systems for multiple drones have also been developed, covering a spectrum of warnings from heading errors and GPS failure to zone proximity, intrusion, connectivity loss, and battery status. Furthermore, ground station software engineered with frameworks like WPF and MVVMLight incorporates features for path planning, real-time trajectory display, and geofencing. Some research explores the fusion of game theory and deep learning within 5G-enabled UAV cloud platforms to augment the intelligent collaborative capabilities of supervision systems. Commercially, platforms like DJI’s FlightHub 2 achieve deep integration with drone flight controllers, embedding geofence data for remote dynamic updates, while others focus on pre-flight plan validation and compliance monitoring.
While existing systems and platforms offer a range of functionalities, they often exhibit limitations when applied to small and medium-scale supervision scenarios typical of agricultural fields, industrial plants, or logistics parks. Common drawbacks include functional redundancy, lack of portability, and insufficient emphasis on real-time, localized processing capabilities. Deploying a full-scale cloud monitoring solution for a single factory or farm can be impractical and cost-ineffective. To overcome these limitations, this paper proposes a novel, portable, and lightweight UAV drone geofencing monitoring solution based on terminal intelligence. The core idea is to shift the computational burden of geofence violation detection from a centralized cloud to a powerful mobile device, leveraging local processing for low-latency response. The system is architected on the HarmonyOS platform, utilizing its distributed capabilities and the ArkTS development framework. Data communication is established via 5G networks and the MQTT protocol, ensuring efficient and reliable transmission of UAV telemetry data. For the geofencing algorithm, which is the intellectual core, we designed a method centered on Ear-Clipping Triangulation. This algorithm handles complex polygons containing multiple no-fly zones (holes) by first constructing a pseudo-simple polygon. It then performs triangulation as a preprocessing step. During real-time operation, a graph-based spatial search algorithm employing Breadth-First Search (BFS) over the triangular mesh, augmented with a starting-point caching mechanism, enables highly efficient and accurate point-in-polygon (PIP) determination. This paper details the system’s overall design, the intricacies of the proposed geofencing algorithm, its implementation on HarmonyOS, and presents comprehensive experimental results validating its performance and accuracy.
System Architecture and Workflow
The proposed UAV drone monitoring system is designed as a lightweight mobile application (APP) for HarmonyOS. Its primary objective is to provide field operators or safety personnel with a portable tool for real-time awareness of drone operations within a specific airspace and instant alerts for geofence violations. The system architecture is logically decomposed into four core modules, ensuring modularity and clear separation of concerns.
The Data Communication Module forms the data ingress/egress layer. It is responsible for establishing and maintaining a bidirectional link with the target UAV drone. Utilizing the MQTT protocol over 5G connectivity, this module subscribes to a specific topic (e.g., uavs/state/flying) on an MQTT broker server to receive real-time telemetry data published by the drone, which typically includes GPS coordinates (latitude, longitude, altitude), timestamps, and other status information. The module implements essential robustness features such as automatic reconnection mechanisms upon link failure, parsing of JSON-formatted messages, and deduplication of data packets based on timestamps to ensure data consistency and reliability.
The UAV Management Module acts as the central hub for drone entity management. It handles the lifecycle of monitored drones, including registration upon first connection, maintenance of real-time status (position, velocity), storage and update of historical flight trajectories, and deregistration upon disconnection. It receives parsed data from the Communication Module and updates the internal state of corresponding UavObject instances. Crucially, this module orchestrates the geofence violation check by asynchronously invoking the computational core in the Geofence Management Module whenever a new position update is received for a drone.
The Geofence Management Module is the computational engine of the system. It encapsulates all logic related to geofence processing. Its responsibilities include loading geofence definitions (e.g., from JSON configuration files), which may consist of complex polygons with multiple holes, and performing the necessary geometric preprocessing. This preprocessing is where the Ear-Clipping Triangulation algorithm is applied offline or during initialization. The module also manages the data structures resulting from triangulation (e.g., triangle list, adjacency graph) and provides the interface for the real-time PIP query—the三角空间搜索 (Triangular Spatial Search) algorithm. The results of this query determine whether a given UAV drone’s position is inside or outside the permissible area.
The Alert Management Module is responsible for generating operator notifications. Upon receiving a violation signal from the Geofence Management Module (via the UAV Management Module), it triggers multi-modal alerts. In the implemented system, this involves activating the device’s speaker to emit an audible beep and changing an on-screen visual indicator to red, providing immediate and unambiguous feedback to the user.
The integrated workflow of the HarmonyOS APP is as follows. The system initializes, establishing a connection to the MQTT broker. Upon successful UAV drone connection and authentication, the APP begins a continuous loop of receiving telemetry data, updating the drone’s visualized trajectory on the map interface, and performing the geofence violation check for each new position fix. If a violation is detected, the alert is triggered immediately and persists until the drone re-enters a permissible zone or the connection is terminated. The implementation adopts a hybrid development approach. The main application logic, UI components, and module orchestration are written in ArkTS, benefiting from its declarative syntax and seamless HarmonyOS integration. The performance-critical geometric algorithms (triangulation and search) are implemented in C++11 for optimal execution speed. Cross-language invocation between ArkTS and C++ is efficiently handled through the HarmonyOS Native API (NAPI) framework, ensuring that computational efficiency does not compromise the development agility of the high-level application layer.
Algorithm Design: Ear-Clipping Triangulation and Spatial Search
The core algorithmic challenge is the Point-in-Polygon (PIP) problem for complex geofences. Our design goal was to achieve high accuracy and real-time performance on a mobile device for geofences defined as polygons potentially containing multiple holes (no-fly zones). We selected a triangulation-based approach as it offers an excellent balance between preprocessing complexity, memory footprint, and query speed.
Preprocessing: From Complex Polygon to Triangular Mesh
The preprocessing stage transforms the input geofence—a polygon potentially with holes—into a set of triangles and an adjacency graph. For a simple polygon (without holes), the standard ear-clipping algorithm is applied directly. The vertices of the simple polygon, assumed to be ordered counter-clockwise (CCW) for the outer boundary, are processed. An “ear” is defined as a convex vertex $V_i$ such that the triangle formed by $(V_{i-1}, V_i, V_{i+1})$ lies entirely inside the polygon and contains no other vertices. The algorithm iteratively identifies and removes these ears, storing each removed triangle $(V_{i-1}, V_i, V_{i+1})$ in a list. This process continues until the polygon is reduced to a single triangle. The result is a list of triangles $\mathcal{T} = \{T_1, T_2, …, T_m\}$ that exactly partition the original polygon.
Handling complex polygons with $q$ holes requires an additional step. The holes are defined as polygons with vertices ordered clockwise (CW). The goal is to merge the outer boundary and all holes into a single, connected pseudo-simple polygon suitable for ear-clipping. This is achieved by constructing “bridges” between the outer polygon and each hole. The process for connecting one hole is as follows:
1. Identify the leftmost vertex $M$ of the hole polygon.
2. Shoot a ray from $M$ in the negative X-direction.
3. Find the closest intersection point $I$ of this ray with the (current) outer polygon’s edges. Let the edge containing $I$ be $(V_j, V_{j+1})$, and let $P$ be the endpoint of this edge with the smaller x-coordinate (i.e., the leftmost point of the intersected edge).
4. If the segment $MP$ is not directly visible (i.e., intersects the polygon), a search is conducted within triangle $\triangle MIP$ to find the vertex $P’$ on the outer polygon that forms the smallest angle $\angle MIP’$ and is mutually visible to $M$. This vertex becomes the new bridge endpoint $P$.
5. The hole is connected by inserting its vertex sequence into the outer polygon’s vertex list between $P$ and the successor of $P$, effectively creating a “bridge” and eliminating the hole. The vertex ordering is adjusted to maintain a consistent CCW orientation for the resulting pseudo-simple polygon.
For multiple holes, the process is repeated sequentially. Special care is taken when a bridge endpoint (a vertex on the outer polygon) is shared or used for connecting subsequent holes. The algorithm must ensure that the insertion point for a new hole’s vertex sequence preserves the global CCW order of the pseudo-simple polygon. This is managed by carefully tracking the index of the bridge endpoint after previous insertions and verifying the geometric orientation.
The pseudocode for the core ear-clipping triangulation and pseudo-simple polygon construction is summarized below.
Algorithm 1: Ear-Clipping Triangulation for a Simple Polygon
Input: polygon: A doubly-linked list of vertices in CCW order.
Output: True if successful, False otherwise; triangles: List of triangular cells.
1: Initialize an empty list `triangles`.
2: while number of vertices in `polygon` >= 3 do
3: Set `earFound ← false`.
4: for each vertex `V_i` in the current `polygon` list do
5: if `V_i` is a convex vertex and triangle (`V_{i-1}`, `V_i`, `V_{i+1}`) is an ear then
6: `earFound ← true`.
7: Append triangle (`V_{i-1}`, `V_i`, `V_{i+1}`) to `triangles`.
8: Remove vertex `V_i` from the `polygon` list.
9: break from the inner for-loop.
10: end for
11: if `earFound` is `false` then
12: return `False` // Not a simple polygon or algorithm stuck.
13: end while
14: return `True`, `triangles`.
Algorithm 2: Bridge Finding for Connecting a Hole
Input: outerPoly: CCW outer polygon list, hole: CW hole polygon list.
Output: Updated outerPoly with hole integrated, bridge endpoint index.
1: Find the leftmost vertex `M` in the `hole` list.
2: Initialize `minDist ← INF`, `bestBridgeVertex ← null`, `bestIndex ← -1`.
3: for each edge (`V_j`, `V_{j+1}`) of `outerPoly` do
4: // Check if ray from M (leftwards) intersects edge and M is to the left of the edge.
5: if edge is candidate for intersection with the ray from M then
6: Compute intersection point `I`.
7: Compute distance `d` between `M` and `I`.
8: if `d < minDist` then
9: `minDist ← d`.
10: Let `P` be the leftmost endpoint of edge (`V_j`, `V_{j+1}`).
11: `bestBridgeVertex ← P`, `bestIndex ←` index of `P`.
12: end for
13: // Refinement step if MP is not mutually visible
14: if segment `M`-`bestBridgeVertex` is not clear then
15: Search vertices in `outerPoly` around `bestIndex` to find vertex `P'` forming smallest ∠MIP' that is visible to M.
16: Update `bestBridgeVertex ← P'` and its `bestIndex`.
17: Insert the sequence of vertices from `hole` into `outerPoly` at position `bestIndex`, connecting M to `bestBridgeVertex`.
18: return `outerPoly`, `bestIndex`.
Runtime Query: Triangular Spatial Search with BFS
After preprocessing, the geofence is represented as a set of triangles $\mathcal{T}$ and an adjacency graph $G$. The graph $G = (V_G, E_G)$ is constructed where each vertex in $V_G$ corresponds to a triangle $T_i \in \mathcal{T}$, and an edge $(T_i, T_j) \in E_G$ exists if triangles $T_i$ and $T_j$ share a common polygon edge (not a bridge edge).
The PIP query for a point $Q$ (the UAV drone’s current location) proceeds as follows. The core test for a single triangle $T$ with vertices $A, B, C$ uses the barycentric technique or equivalently, checking the signs of cross products. For CCW vertices, point $Q$ is inside $T$ if and only if:
$$( (B – A) \times (Q – A) )_z \geq 0 \ \land \ ( (C – B) \times (Q – B) )_z \geq 0 \ \land \ ( (A – C) \times (Q – C) )_z \geq 0$$
All comparisons are inclusive of the edge, meaning a point on the boundary is considered “inside” the geofence (or a no-fly zone, depending on context).
To locate which triangle contains $Q$, a graph search is performed. A naive approach would check $Q$ against all $m$ triangles, yielding $O(m)$ complexity. We improve this by leveraging spatial coherence: a UAV drone’s position changes continuously between updates. We employ a Breadth-First Search (BFS) strategy starting from a cached “last known triangle” $T_{cache}$.
1. First, check if $Q$ is inside $T_{cache}$. If yes, return “Inside/Outside” based on the type of geofence (permissible area or no-fly zone) and update $T_{cache}$.
2. If not, initiate a BFS from $T_{cache}$ in graph $G$. For each neighboring triangle $T_{neigh}$ visited, check if $Q$ is inside $T_{neigh}$.
3. If such a triangle is found, the search stops, the result is returned, and $T_{cache}$ is updated to $T_{neigh}$.
4. If the BFS exhausts all triangles reachable from $T_{cache}$ without success, it implies $Q$ is outside the entire triangular mesh. A fallback global search or a direct “outside” result can be returned, and the cache is invalidated or reset to a default triangle (e.g., the first triangle in $\mathcal{T}$).
This caching mechanism capitalizes on the temporal locality of UAV drone flight paths. In the common case where the drone moves between adjacent or nearby triangles between consecutive samples (e.g., at 1 Hz update rate), the query completes in constant or near-constant time $O(1)$ or $O(k)$ where $k$ is a small number of adjacent triangles. The worst-case complexity, occurring after a large jump (e.g., connection loss and regain), is $O(m)$, but $m$ is proportional to the number of polygon vertices $n$ (specifically, $m = n – 2 + 2q$ for a polygon with $q$ holes after bridge insertion).
Complexity Analysis
Let $p$ be the total number of vertices from both the outer boundary and all $q$ holes. After constructing bridges, the pseudo-simple polygon has $n = p + 2q$ vertices. The preprocessing stage involves building bridges and triangulation.
– Bridge Construction for $q$ holes has a worst-case complexity of $O(q \cdot n)$, which simplifies to $O(n^2)$ in pathological cases but is typically much lower.
– Ear-Clipping Triangulation for a simple polygon of $n$ vertices has an average time complexity of $O(n^2)$, though optimized implementations can achieve $O(n \log n)$.
Thus, the overall preprocessing complexity is dominated by $O(n^2)$. This is a one-time cost incurred during system initialization or geofence update.
The runtime query complexity depends on the search strategy:
– Without caching (brute-force): $O(m) \approx O(n)$.
– With BFS from a cached point: Best-case $O(1)$, Average-case $O(k)$ (small constant related to local movement), Worst-case $O(m) \approx O(n)$ after a large displacement.
A comparison of time complexities with other common PIP algorithms highlights the efficiency of our approach, especially with the caching optimization.
| Algorithm | Preprocessing Complexity | Query Complexity (Average/Worst) | Notes |
|---|---|---|---|
| Ray Casting | $O(1)$ | $O(n)$ | Simple, no preprocessing, slow for complex polygons. |
| Winding Number | $O(1)$ | $O(n)$ | Accurate but computationally heavier per query. |
| Grid Method | $O(n)$ (grid build) | $O(1)$ (cell lookup) / $O(n)$ (fine-grain) | Memory intensive, accuracy depends on grid resolution. |
| BSP Tree | $O(n \log n)$ | $O(\log n)$ | Complex to implement, can degrade for non-convex shapes. |
| Our Method (Triangulation + BFS Cache) | $O(n^2)$ | $O(1)$ / $O(n)$ | Efficient queries due to locality, handles complex polygons with holes. |
System Implementation on HarmonyOS
The system was implemented as a proof-of-concept application for HarmonyOS, following a hybrid ArkTS/C++ architecture. The development environment and key tools are listed below.
| Component | Specification / Version |
|---|---|
| Server (MQTT Broker) | Ubuntu 22.04, EMQX (MQTT 5.0) |
| Map SDK | Baidu Maps HarmonyOS NEXT API 1.2.8 |
| IDE | DevEco Studio 5.0.7.100 |
| Primary Language | ArkTS |
| Native Library Language | C++11 |
| HarmonyOS SDK | API Version 13 |
| Test Device | Huawei Nova 14 (HarmonyOS 5.1.0) |
The application’s data flow is designed for efficiency and modularity. The MQTT module runs on a background thread, listening for incoming messages. Parsed JSON data is segregated into UAV state messages and geofence configuration messages, placed into respective ring buffers or message queues. The UAV Management and Geofence Management modules act as service-layer consumers of these queues. They process the data, update internal models, and push the results to the UI layer via HarmonyOS’s state management decorators (e.g., @State, @Prop), which automatically trigger re-rendering of relevant UI components.
The User Interface, built with ArkUI’s declarative syntax, centers around a map display. Key UI components include:
– A connection status indicator (button turning blue when connected to MQTT broker).
– A dynamic list panel showing all connected UAV drones.
– Visual rendering of the active geofence polygon(s) (permissible area in one color, holes/no-fly zones in another).
– Real-time plotting of drone trajectories as polylines, with color coding (e.g., green inside the permissible area, red inside a no-fly zone).
– A status area displaying live telemetry data (coordinates, speed, altitude).
– Visual and auditory alarm indicators that activate upon geofence violation detection.
The integration of the native C++ geofencing library is crucial for performance. The core algorithms (Algorithms 1 & 2, and the BFS search) are compiled into a native library (.so file). An NAPI interface is created, exposing functions like loadGeofence(jsonString), triangulate(), and queryPoint(lat, lon) to the ArkTS context. The ArkTS modules call these native functions asynchronously to avoid blocking the UI thread. This architecture ensures that the computationally intensive geometric calculations are performed at native speed, while the application logic and responsive UI are managed by the efficient ArkTS runtime.
Experimental Testing and Performance Analysis
To validate the system’s accuracy and performance, a series of tests were conducted using a simulated UAV drone flight control unit. The testbed comprised: 1) A UAV simulator (STM32-based controller with a 5G module) pre-programmed with a specific flight trajectory, publishing data at 1 Hz; 2) An MQTT broker on an Alibaba Cloud server; 3) The HarmonyOS geofencing APP running on a Huawei Nova 14 smartphone.
Algorithm Accuracy Test
Prior to full system testing, the core geofencing algorithm’s accuracy was verified independently within the APP. A test function was implemented that generated $N = 5000$ random points within the bounding box of a complex geofence (containing holes). Each point was processed by the triangulation-based query algorithm and visually marked: green for “inside permissible area”, red for “inside a no-fly zone” (i.e., outside the permissible area). Manual inspection and coordinate analysis confirmed that the algorithm’s classification matched the geometric ground truth with near 100% accuracy for points not exactly on boundaries. Points precisely on edges were correctly classified as “inside” based on our inclusive-edge policy. This test validated the correctness of the pseudo-simple polygon construction, triangulation, and point-in-triangle search logic.
End-to-End System Latency Test
This test measured the total delay from the moment the UAV drone simulator published a position fix to the moment the APP completed its geofence check and was ready to render/alert. The simulator tagged each outgoing message with a UTC timestamp $t_1$. The APP, upon receiving and processing the message, recorded its current UTC timestamp $t_2$. The latency for sample $i$ is $\Delta t_i = t_2^{(i)} – t_1^{(i)}$. Data was collected over an 80-second flight, resulting in 80 latency samples.
The results are summarized statistically and visually in the table and description below. The latency was found to be stable and within acceptable bounds for monitoring applications targeting low to medium-speed drones.
| Metric | Value (seconds) |
|---|---|
| Mean Latency | 1.18 |
| Median Latency | 1.15 |
| Standard Deviation | 0.23 |
| Minimum Latency | 0.82 |
| Maximum Latency | 2.01 |
| 95th Percentile | 1.67 |
The latency distribution was tightly clustered around the mean. Occasional spikes (e.g., up to 2.01s) were observed, attributable to transient network jitter in the 5G link or brief background processes on the mobile device. Crucially, in over 95% of the samples, the latency was under 1.7 seconds, and the median was around 1.15 seconds. This performance demonstrates that the system can provide timely alerts for UAV drone operations, where a sub-2 second delay is sufficient for human operators to react or for automated systems to initiate contingency procedures in many non-critical scenarios.
Integrated Functional Test
A comprehensive flight test was conducted to validate the entire system workflow: data reception, trajectory display, real-time geofence judgment, and alarm triggering. The simulated UAV drone followed a predetermined path that entered and exited both the main permissible area and internal no-fly zones (holes). The APP successfully visualized the flight path, coloring segments green (inside safe zone) and red (inside no-fly zone) in real-time. The audible and visual alarms activated immediately when the simulated drone’s path crossed into a restricted zone. The sequence of states matched the expected geofence configuration perfectly, as detailed below.
| Flight Time Segment (s) | Expected UAV State | Displayed Trajectory Color | Alarm Triggered | Result |
|---|---|---|---|---|
| 1 – 17 | Outside main geofence | Red | Yes | Correct |
| 18 – 27 | Inside permissible area | Green | No | Correct |
| 28 – 34 | Inside triangular no-fly zone (hole) | Red | Yes | Correct |
| 35 – 44 | Inside permissible area | Green | No | Correct |
| 45 – 49 | Inside rectangular no-fly zone (hole) | Red | Yes | Correct |
| 50 – 57 | Inside permissible area | Green | No | Correct |
| 58 – 80 | Outside main geofence | Red | Yes | Correct |
The test confirmed 100% accuracy in state detection and alarm triggering for this scenario. All telemetry points were received, processed, and correctly classified. No false positives or missed violations occurred. This validates the integrity of the entire chain: MQTT communication, data parsing, UAV state management, geofence algorithm query, and alert management.
Conclusion
This paper presented the design, implementation, and evaluation of a portable UAV drone geofencing monitoring system based on the HarmonyOS platform. The system addresses the need for lightweight, real-time airspace supervision in small to medium-scale operational contexts, such as industrial sites or agricultural fields, where deploying a full-fledged cloud monitoring center may be impractical. By leveraging the processing power of modern smartphones and the efficient HarmonyOS development framework, we demonstrated a shift towards edge intelligence for drone safety applications.
The core technical contribution is a robust geofencing algorithm capable of handling complex polygons with multiple no-fly zones. By combining Ear-Clipping Triangulation for preprocessing with a graph-based BFS search strategy enhanced by a spatial coherence cache, the algorithm achieves high accuracy and efficient real-time query performance suitable for mobile devices. The hybrid ArkTS/C++ implementation via HarmonyOS NAPI ensures an optimal balance between development productivity and computational efficiency.
Experimental results from both algorithmic validation and integrated system testing confirm the effectiveness of the approach. The algorithm demonstrated near-perfect accuracy in point-in-polygon classification. The end-to-end system latency averaged around 1.2 seconds, proving its capability for timely monitoring and alerting of UAV drone operations. The system successfully performed real-time trajectory visualization and correct violation detection throughout a simulated flight path involving multiple entries and exits from permissible and restricted zones.
Future work could explore several enhancements. Extending the geofence definition to include altitude layers for true 3D volumetric geofences is a logical next step. Integrating with official dynamic airspace information services (e.g., to automatically download temporary flight restriction zones) would increase the system’s utility. Furthermore, implementing lightweight local communication protocols (like Bluetooth or Wi-Fi Direct) for direct communication with drones in absence of cellular networks could enhance robustness. Finally, porting the core geofencing library to other mobile platforms (Android, iOS) would broaden the applicability of the presented algorithmic approach. In summary, this research provides a practical and effective mobile-centric solution for enhancing the safety and regulatory compliance of UAV drone operations in the evolving low-altitude economy.
