majal-edge 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,6 @@
1
+ majal-edge
2
+ Copyright 2026 ScaleX Innovation
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It depends on pymavlink (LGPL-3.0), pyserial (BSD-3-Clause) and paho-mqtt
6
+ (EPL-2.0 / EDL-1.0), which are installed separately and keep their own licences.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: majal-edge
3
+ Version: 0.1.0
4
+ Summary: Majal edge agent: connects PX4 and ArduPilot drones to the Majal UTM platform by ScaleX Innovation
5
+ Author-email: ScaleX Innovation <support@scalexi.ai>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://scalexi.ai
8
+ Keywords: UTM,drone,MAVLink,PX4,ArduPilot,telemetry,Majal
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Classifier: Environment :: No Input/Output (Daemon)
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: pymavlink<3,>=2.4.41
20
+ Requires-Dist: pyserial<4,>=3.5
21
+ Requires-Dist: paho-mqtt<3,>=2.1
22
+ Dynamic: license-file
23
+
24
+ # majal-edge
25
+
26
+ Connects a PX4 or ArduPilot drone to **Majal**, the UAS traffic management (UTM) platform by
27
+ [ScaleX Innovation](https://scalexi.ai). It runs on the drone's companion computer (Raspberry Pi,
28
+ Jetson, …) or on a ground laptop with a telemetry radio, and sends the vehicle's live MAVLink 2
29
+ telemetry to Majal over MQTT with TLS.
30
+
31
+ ## Connect a drone
32
+
33
+ 1. In Majal, open **Fleet**, choose the aircraft and click **Connect**. You get a one-time code,
34
+ valid for 15 minutes.
35
+ 2. On the companion computer, wired to the flight controller (TELEM2 or USB):
36
+
37
+ ```bash
38
+ pip install majal-edge
39
+ sudo majal-edge enroll https://<your-majal-address> ABCD-2345
40
+ sudo majal-edge install-service # start now and on every boot (Linux / systemd)
41
+ ```
42
+
43
+ The aircraft appears on the live map once the autopilot has a position fix.
44
+
45
+ ## What it does
46
+
47
+ - **Finds the flight controller**: USB flight controllers (Pixhawk, Cube, Holybro, CUAV, …), the
48
+ companion computer's UART (`/dev/serial0`, `/dev/ttyAMA0`, `/dev/ttyTHS1`) at 921600 / 57600 /
49
+ 115200 baud, then MAVLink UDP 14540 / 14550. It only listens while probing.
50
+ `majal-edge detect` shows what it finds; `enroll --autopilot /dev/ttyACM0` skips detection.
51
+ - **Gets its identity from the server**: the code is exchanged over HTTPS for a device id and a
52
+ broker login that belong to this device only. The device id, not the MAVLink system id,
53
+ identifies the aircraft, so drones left on system id 1 never collide.
54
+ - **Sends telemetry only**: position, altitude, speed, heading, battery, mode and armed state
55
+ (requested at 4 Hz / 1 Hz to save mobile data). Nothing from the platform is forwarded to the
56
+ autopilot.
57
+ - **Handles weak links**: reconnects by itself; while offline, telemetry is dropped rather than
58
+ queued, because a stale position is worse than a gap.
59
+
60
+ ## Security
61
+
62
+ - Enrollment needs `https://` (plain `http://` only for local / private test addresses or with
63
+ `--allow-http`). Codes are single-use and expire after 15 minutes.
64
+ - The broker login can only publish this device's own telemetry topic. It can be revoked from
65
+ the Fleet page at any time, which disconnects the device immediately.
66
+ - The configuration file holding the login is readable by its owner only
67
+ (`/etc/majal-edge/config.json` as root, otherwise `~/.config/majal-edge/config.json`). The
68
+ systemd service runs as an unprivileged `majal-edge` user with the `dialout` group.
69
+
70
+ ## Commands
71
+
72
+ | Command | |
73
+ |---|---|
74
+ | `majal-edge enroll <server> <code>` | redeem the code from Fleet → Connect |
75
+ | `majal-edge run` | forward telemetry (what the service runs) |
76
+ | `sudo majal-edge install-service` | install and start the systemd service |
77
+ | `majal-edge detect` | find the flight controller |
78
+ | `majal-edge status` | show the configuration and test the broker login |
79
+
80
+ Requires Python 3.9+. Licensed under Apache 2.0. © ScaleX Innovation. Support: support@scalexi.ai
@@ -0,0 +1,57 @@
1
+ # majal-edge
2
+
3
+ Connects a PX4 or ArduPilot drone to **Majal**, the UAS traffic management (UTM) platform by
4
+ [ScaleX Innovation](https://scalexi.ai). It runs on the drone's companion computer (Raspberry Pi,
5
+ Jetson, …) or on a ground laptop with a telemetry radio, and sends the vehicle's live MAVLink 2
6
+ telemetry to Majal over MQTT with TLS.
7
+
8
+ ## Connect a drone
9
+
10
+ 1. In Majal, open **Fleet**, choose the aircraft and click **Connect**. You get a one-time code,
11
+ valid for 15 minutes.
12
+ 2. On the companion computer, wired to the flight controller (TELEM2 or USB):
13
+
14
+ ```bash
15
+ pip install majal-edge
16
+ sudo majal-edge enroll https://<your-majal-address> ABCD-2345
17
+ sudo majal-edge install-service # start now and on every boot (Linux / systemd)
18
+ ```
19
+
20
+ The aircraft appears on the live map once the autopilot has a position fix.
21
+
22
+ ## What it does
23
+
24
+ - **Finds the flight controller**: USB flight controllers (Pixhawk, Cube, Holybro, CUAV, …), the
25
+ companion computer's UART (`/dev/serial0`, `/dev/ttyAMA0`, `/dev/ttyTHS1`) at 921600 / 57600 /
26
+ 115200 baud, then MAVLink UDP 14540 / 14550. It only listens while probing.
27
+ `majal-edge detect` shows what it finds; `enroll --autopilot /dev/ttyACM0` skips detection.
28
+ - **Gets its identity from the server**: the code is exchanged over HTTPS for a device id and a
29
+ broker login that belong to this device only. The device id, not the MAVLink system id,
30
+ identifies the aircraft, so drones left on system id 1 never collide.
31
+ - **Sends telemetry only**: position, altitude, speed, heading, battery, mode and armed state
32
+ (requested at 4 Hz / 1 Hz to save mobile data). Nothing from the platform is forwarded to the
33
+ autopilot.
34
+ - **Handles weak links**: reconnects by itself; while offline, telemetry is dropped rather than
35
+ queued, because a stale position is worse than a gap.
36
+
37
+ ## Security
38
+
39
+ - Enrollment needs `https://` (plain `http://` only for local / private test addresses or with
40
+ `--allow-http`). Codes are single-use and expire after 15 minutes.
41
+ - The broker login can only publish this device's own telemetry topic. It can be revoked from
42
+ the Fleet page at any time, which disconnects the device immediately.
43
+ - The configuration file holding the login is readable by its owner only
44
+ (`/etc/majal-edge/config.json` as root, otherwise `~/.config/majal-edge/config.json`). The
45
+ systemd service runs as an unprivileged `majal-edge` user with the `dialout` group.
46
+
47
+ ## Commands
48
+
49
+ | Command | |
50
+ |---|---|
51
+ | `majal-edge enroll <server> <code>` | redeem the code from Fleet → Connect |
52
+ | `majal-edge run` | forward telemetry (what the service runs) |
53
+ | `sudo majal-edge install-service` | install and start the systemd service |
54
+ | `majal-edge detect` | find the flight controller |
55
+ | `majal-edge status` | show the configuration and test the broker login |
56
+
57
+ Requires Python 3.9+. Licensed under Apache 2.0. © ScaleX Innovation. Support: support@scalexi.ai
@@ -0,0 +1,68 @@
1
+ # majal-edge — edge agent and bridge
2
+
3
+ Forwards a vehicle's MAVLink telemetry to the UTM. One small Python package
4
+ ([`majal-edge` on PyPI](https://pypi.org/project/majal-edge/)), the same in simulation and on a
5
+ real drone.
6
+
7
+ **Customers: plug and play.** Fleet → *Connect* on the aircraft gives a one-time code, then on the
8
+ companion computer:
9
+
10
+ ```bash
11
+ pip install majal-edge
12
+ sudo majal-edge enroll https://<majal-host> ABCD-2345 # finds the autopilot, gets its own login
13
+ sudo majal-edge install-service # systemd, starts on boot
14
+ ```
15
+
16
+ The server assigns the device id (`edge-…`), which identifies the aircraft (`edge_bridge:<device_id>`),
17
+ so the MAVLink system id does not matter. User guide: `PYPI.md`. Release: bump
18
+ `majal_edge/__version__`, `python -m build`, `twine upload dist/*`.
19
+
20
+ **Developers / operators: the bridge on its own** (`python -m majal_edge.bridge`, configured by
21
+ environment variables). Two uplinks, chosen by `EDGE_UTM`:
22
+
23
+ | Uplink | `EDGE_UTM` | Use |
24
+ |---|---|---|
25
+ | MQTT over TLS (recommended on the internet) | `mqtts://<utm-host>:8883` | Drone on 4G/LTE. Own broker login per drone, TLS, reconnects by itself |
26
+ | MQTT, plain | `mqtt://rabbitmq:1883` | Inside the stack's network only (the SITL drones use this) |
27
+ | UDP | `udpout:<utm-host>:14560` | LAN, or the internet inside a VPN (no encryption or login of its own) |
28
+
29
+ | Where | `EDGE_AUTOPILOT` |
30
+ |---|---|
31
+ | SITL container (compose profile `sitl`) | `udpin:0.0.0.0:14540` |
32
+ | Companion computer wired to a Pixhawk (TELEM2) | `/dev/ttyAMA0` + `EDGE_BAUD=921600` |
33
+ | Laptop with a SiK telemetry radio | `/dev/ttyUSB0` + `EDGE_BAUD=57600` |
34
+
35
+ ## A drone over the internet without enrollment (MQTT, manual login)
36
+
37
+ 1. On the UTM host, create the drone's broker login (prints the four settings below once):
38
+ `scripts/setup/edge-device.sh add <device-id>`. Revoke with `remove`; the drone is cut off at once.
39
+ 2. The broker needs the TLS listener: `docker-compose.mqtts.yml` overlay with a certificate in
40
+ `infra/rabbitmq/certs/` (development: `scripts/setup/mqtt-dev-certs.sh`).
41
+ 3. On the companion computer:
42
+
43
+ ```bash
44
+ pip install -r requirements.txt
45
+ EDGE_AUTOPILOT=/dev/ttyAMA0 EDGE_BAUD=921600 \
46
+ EDGE_UTM=mqtts://utm.example.com:8883 EDGE_DEVICE_ID=<device-id> \
47
+ EDGE_MQTT_USERNAME=<device-id> EDGE_MQTT_PASSWORD=<password> \
48
+ python -m majal_edge.bridge
49
+ ```
50
+
51
+ 4. Register the aircraft in the Fleet page with its MAVLink system id (connection: MAVLink). The same
52
+ registration works over UDP or MQTT. Prefer enrollment: manual logins rely on system ids, which
53
+ collide when two drones keep the factory default.
54
+
55
+ Frames are published unmodified to `utm/mavlink/<device-id>`, batched every `EDGE_MQTT_BATCH_MS`
56
+ (default 100 ms). While the link is down they are dropped, not queued: a stale position is worse
57
+ than a gap. A drone's login may only publish to its own topic. The gateway also pins each MAVLink
58
+ system id to the first device that sends it, so one drone cannot report as another.
59
+ `EDGE_MQTT_CA` points to a private CA bundle (development certificates); empty uses the system
60
+ trust store.
61
+
62
+ The bridge is one-way (vehicle → UTM). It requests a small stream set (position 4 Hz, status 1 Hz)
63
+ with `MAV_CMD_SET_MESSAGE_INTERVAL`, which PX4 and ArduPilot both support, and forwards only the
64
+ message types the UTM uses. Nothing from the UTM reaches the autopilot.
65
+
66
+ ## Licence
67
+
68
+ Apache License 2.0 (`LICENSE`, `NOTICE`). The agent is open source; the Majal cloud service is not.
@@ -0,0 +1,3 @@
1
+ """Majal edge agent: connects a PX4 / ArduPilot drone to the Majal UTM platform."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,251 @@
1
+ """
2
+ Majal edge bridge — runs next to the autopilot and forwards its MAVLink to the UTM.
3
+
4
+ autopilot (serial / UDP) ──► bridge ──► UTM, over one of two uplinks (EDGE_UTM):
5
+ udpout:<host>:<port> raw MAVLink UDP to telemetry-gateway (14550, host 14560 locally);
6
+ for a LAN, or the internet inside a VPN
7
+ mqtts://<host>:8883 MAVLink frames published to utm/mavlink/<EDGE_DEVICE_ID> on the
8
+ mqtt://<host>:1883 RabbitMQ MQTT plugin, with this drone's own broker login
9
+ (EDGE_MQTT_USERNAME / EDGE_MQTT_PASSWORD); TLS for the internet
10
+
11
+ The same program runs in three places:
12
+ * SITL — in the simulator's network namespace (EDGE_AUTOPILOT=udpin:0.0.0.0:14540)
13
+ * real drone — on a companion computer wired to the flight controller
14
+ (EDGE_AUTOPILOT=/dev/ttyAMA0, EDGE_BAUD=921600)
15
+ * ground — on a laptop with a telemetry radio (EDGE_AUTOPILOT=/dev/ttyUSB0, EDGE_BAUD=57600)
16
+
17
+ What it does:
18
+ 1. Asks the autopilot for the streams the UTM needs at a fixed rate (MAV_CMD_SET_MESSAGE_INTERVAL,
19
+ understood by PX4 and ArduPilot) so the link budget does not depend on autopilot defaults.
20
+ 2. Forwards only those message types, unmodified, so the vehicle's own system id reaches the UTM.
21
+ 3. UDP: re-resolves the UTM host periodically (UDP has no connection to notice a moved endpoint).
22
+ MQTT: reconnects with back-off; frames produced while the link is down are dropped, not
23
+ queued (live telemetry: a stale position is worse than a gap). Frames are batched for
24
+ EDGE_MQTT_BATCH_MS (MAVLink frames are self-delimiting) to save cellular overhead.
25
+ 4. Never forwards anything from the UTM to the autopilot. Uplink (geofence push, return-to-home)
26
+ is a separate, approved capability (design §uplink) and is not implemented in the bridge.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import logging
32
+ import os
33
+ import re
34
+ import ssl
35
+ import time
36
+ from dataclasses import dataclass, field
37
+ from urllib.parse import urlparse
38
+
39
+ os.environ.setdefault("MAVLINK20", "1")
40
+ from pymavlink import mavutil # noqa: E402
41
+
42
+ logger = logging.getLogger("majal_edge.bridge")
43
+ M = mavutil.mavlink
44
+
45
+ # Message → interval requested from the autopilot (Hz). Kept small for cellular links.
46
+ STREAMS_HZ = {
47
+ M.MAVLINK_MSG_ID_GLOBAL_POSITION_INT: 4.0,
48
+ M.MAVLINK_MSG_ID_SYS_STATUS: 1.0,
49
+ M.MAVLINK_MSG_ID_GPS_RAW_INT: 1.0,
50
+ M.MAVLINK_MSG_ID_EXTENDED_SYS_STATE: 1.0,
51
+ M.MAVLINK_MSG_ID_HOME_POSITION: 0.2,
52
+ }
53
+ # Forwarded types: the streams above + identity, events and Remote ID
54
+ FORWARD = {
55
+ "HEARTBEAT",
56
+ "GLOBAL_POSITION_INT",
57
+ "SYS_STATUS",
58
+ "GPS_RAW_INT",
59
+ "EXTENDED_SYS_STATE",
60
+ "HOME_POSITION",
61
+ "STATUSTEXT",
62
+ "AUTOPILOT_VERSION",
63
+ "OPEN_DRONE_ID_BASIC_ID",
64
+ "OPEN_DRONE_ID_LOCATION",
65
+ "OPEN_DRONE_ID_SYSTEM",
66
+ "OPEN_DRONE_ID_OPERATOR_ID",
67
+ }
68
+ DEVICE_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$") # MQTT topic level; RabbitMQ maps "." to "/"
69
+ VEHICLE_TYPES_EXCLUDED = {M.MAV_TYPE_GCS, M.MAV_TYPE_ONBOARD_CONTROLLER, M.MAV_TYPE_GIMBAL, M.MAV_TYPE_CAMERA, M.MAV_TYPE_ADSB}
70
+
71
+
72
+ @dataclass
73
+ class BridgeConfig:
74
+ autopilot: str = "udpin:0.0.0.0:14540"
75
+ baud: int = 57600
76
+ utm: str = "udpout:telemetry-gateway:14550"
77
+ resolve_seconds: int = 30
78
+ stream_request_seconds: int = 10
79
+ source_system: int = 245 # this bridge's own MAVLink id (onboard computer range)
80
+ device_id: str = "" # MQTT: topic utm/mavlink/<device_id>; defaults to the broker username
81
+ mqtt_username: str = ""
82
+ mqtt_password: str = ""
83
+ mqtt_ca: str = "" # MQTTS: CA bundle for a private CA; empty = system trust store
84
+ mqtt_batch_ms: int = 100
85
+
86
+ @classmethod
87
+ def from_env(cls) -> "BridgeConfig":
88
+ username = os.environ.get("EDGE_MQTT_USERNAME", "")
89
+ return cls(
90
+ autopilot=os.environ.get("EDGE_AUTOPILOT", cls.autopilot),
91
+ baud=int(os.environ.get("EDGE_BAUD", cls.baud)),
92
+ utm=os.environ.get("EDGE_UTM", cls.utm),
93
+ resolve_seconds=int(os.environ.get("EDGE_RESOLVE_SECONDS", cls.resolve_seconds)),
94
+ device_id=os.environ.get("EDGE_DEVICE_ID", username),
95
+ mqtt_username=username,
96
+ mqtt_password=os.environ.get("EDGE_MQTT_PASSWORD", ""),
97
+ mqtt_ca=os.environ.get("EDGE_MQTT_CA", ""),
98
+ mqtt_batch_ms=int(os.environ.get("EDGE_MQTT_BATCH_MS", cls.mqtt_batch_ms)),
99
+ )
100
+
101
+
102
+ @dataclass
103
+ class BridgeStats:
104
+ received: int = 0
105
+ forwarded: int = 0
106
+ dropped: int = 0
107
+ vehicles: set[int] = field(default_factory=set)
108
+
109
+
110
+ def should_forward(msg) -> bool:
111
+ kind = msg.get_type()
112
+ if kind not in FORWARD:
113
+ return False
114
+ if kind == "HEARTBEAT" and msg.type in VEHICLE_TYPES_EXCLUDED:
115
+ return False
116
+ return True
117
+
118
+
119
+ def interval_us(rate_hz: float) -> int:
120
+ return int(1_000_000 / rate_hz)
121
+
122
+
123
+ class UdpUplink:
124
+ """Raw MAVLink over UDP to the telemetry gateway (LAN, or the internet inside a VPN)."""
125
+
126
+ def __init__(self, config: BridgeConfig):
127
+ self.config = config
128
+ self.conn = self._connect()
129
+ self.connected_at = time.monotonic()
130
+
131
+ def _connect(self):
132
+ return mavutil.mavlink_connection(self.config.utm, source_system=self.config.source_system, dialect="common")
133
+
134
+ def write(self, frame: bytes) -> None:
135
+ self.conn.write(frame)
136
+
137
+ def tick(self) -> None:
138
+ if time.monotonic() - self.connected_at > self.config.resolve_seconds:
139
+ self.conn.close()
140
+ self.conn, self.connected_at = self._connect(), time.monotonic()
141
+
142
+ def describe(self) -> str:
143
+ return self.config.utm
144
+
145
+
146
+ class MqttUplink:
147
+ """MAVLink frames published to the UTM broker (RabbitMQ MQTT plugin), one topic per drone."""
148
+
149
+ def __init__(self, config: BridgeConfig):
150
+ import paho.mqtt.client as mqtt
151
+
152
+ url = urlparse(config.utm)
153
+ if not DEVICE_ID.match(config.device_id):
154
+ raise SystemExit("EDGE_DEVICE_ID (or EDGE_MQTT_USERNAME) must be 1-64 of A-Z a-z 0-9 _ -")
155
+ self.topic = f"utm/mavlink/{config.device_id}"
156
+ self.batch_seconds = config.mqtt_batch_ms / 1000
157
+ self.buffer = bytearray()
158
+ self.flushed_at = time.monotonic()
159
+ self.dropped = 0
160
+ self.host, self.port = url.hostname, url.port or (8883 if url.scheme == "mqtts" else 1883)
161
+ self.scheme = url.scheme
162
+ self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"edge-{config.device_id}", clean_session=True)
163
+ self.client.username_pw_set(config.mqtt_username or url.username or "", config.mqtt_password or url.password or "")
164
+ if url.scheme == "mqtts":
165
+ self.client.tls_set(ca_certs=config.mqtt_ca or None, cert_reqs=ssl.CERT_REQUIRED)
166
+ self.client.reconnect_delay_set(min_delay=1, max_delay=30)
167
+ self.client.on_connect = lambda c, u, f, rc, p: logger.info("MQTT %s (%s)", "connected" if not rc.is_failure else "refused", rc)
168
+ self.client.on_disconnect = lambda c, u, f, rc, p: logger.warning("MQTT disconnected (%s); reconnecting", rc)
169
+ self.client.connect_async(self.host, self.port, keepalive=30)
170
+ self.client.loop_start() # network thread: connects, reconnects with back-off
171
+
172
+ def write(self, frame: bytes) -> None:
173
+ self.buffer += frame
174
+ self.tick()
175
+
176
+ def tick(self) -> None:
177
+ if not self.buffer or time.monotonic() - self.flushed_at < self.batch_seconds:
178
+ return
179
+ if self.client.is_connected():
180
+ self.client.publish(self.topic, bytes(self.buffer), qos=0)
181
+ else:
182
+ self.dropped += 1
183
+ self.buffer.clear()
184
+ self.flushed_at = time.monotonic()
185
+
186
+ def describe(self) -> str:
187
+ return f"{self.scheme}://{self.host}:{self.port} {self.topic}"
188
+
189
+
190
+ def make_uplink(config: BridgeConfig):
191
+ return MqttUplink(config) if urlparse(config.utm).scheme in ("mqtt", "mqtts") else UdpUplink(config)
192
+
193
+
194
+ class Bridge:
195
+ def __init__(self, config: BridgeConfig):
196
+ self.config = config
197
+ self.stats = BridgeStats()
198
+ self.autopilot = mavutil.mavlink_connection(
199
+ config.autopilot, baud=config.baud, source_system=config.source_system,
200
+ source_component=M.MAV_COMP_ID_ONBOARD_COMPUTER, dialect="common",
201
+ )
202
+ self.utm = make_uplink(config)
203
+ self.last_stream_request: dict[int, float] = {}
204
+
205
+ def request_streams(self, sysid: int, compid: int) -> None:
206
+ """Ask for the UTM stream set; repeated because autopilots forget it after a reboot."""
207
+ now = time.monotonic()
208
+ if now - self.last_stream_request.get(sysid, 0) < self.config.stream_request_seconds:
209
+ return
210
+ self.last_stream_request[sysid] = now
211
+ for msg_id, rate in STREAMS_HZ.items():
212
+ self.autopilot.mav.command_long_send(
213
+ sysid, compid, M.MAV_CMD_SET_MESSAGE_INTERVAL, 0, msg_id, interval_us(rate), 0, 0, 0, 0, 0
214
+ )
215
+
216
+ def step(self) -> None:
217
+ msg = self.autopilot.recv_match(blocking=True, timeout=0.1)
218
+ self.utm.tick()
219
+ if msg is None or msg.get_type() == "BAD_DATA":
220
+ return
221
+ self.stats.received += 1
222
+ if msg.get_type() == "HEARTBEAT" and msg.type not in VEHICLE_TYPES_EXCLUDED:
223
+ self.stats.vehicles.add(msg.get_srcSystem())
224
+ self.request_streams(msg.get_srcSystem(), msg.get_srcComponent())
225
+ if not should_forward(msg):
226
+ self.stats.dropped += 1
227
+ return
228
+ self.utm.write(msg.get_msgbuf())
229
+ self.stats.forwarded += 1
230
+
231
+ def run(self) -> None:
232
+ logger.info("Edge bridge %s → %s", self.config.autopilot, self.utm.describe())
233
+ last_log = time.monotonic()
234
+ while True:
235
+ self.step()
236
+ if time.monotonic() - last_log > 30:
237
+ last_log = time.monotonic()
238
+ logger.info(
239
+ "vehicles=%s received=%d forwarded=%d dropped=%d uplink_dropped_batches=%d",
240
+ sorted(self.stats.vehicles), self.stats.received, self.stats.forwarded, self.stats.dropped,
241
+ getattr(self.utm, "dropped", 0),
242
+ )
243
+
244
+
245
+ def main() -> None:
246
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
247
+ Bridge(BridgeConfig.from_env()).run()
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()