[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78D40C9YNSEWYS9HA2JX2VA":3,"skill-same:01M78D40C9YNSEWYS9HA2JX2VA":53},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":34,"repositoryHtmlUrl":35,"repositoryHomepageUrl":36,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M78D40C9YNSEWYS9HA2JX2VA","mavlink-integration",null,"Use this skill when a task involves MAVLink protocol communication via pymavlink, UART\u002FUDP\u002FTCP drone connections, ArduPilot SITL simulation, or telemetry message parsing in the edge service. Don't use it for raw UART hardware driver code without MAVLink framing (use embedded-systems), WebSocket transport to the web portal (use api-integration), or Docker builds (use docker-build).","atretyak1985\u002Fswarmery","atretyak1985","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1436737?v=4","01M78CTSX57YH0EYY9YGH0TWKX","Andrii Tretiak","01M78CTSXRPJPYQ7GNPMP45TYX",8,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Fplugins\u002Fuav-pack\u002Fskills\u002Fmavlink-integration\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: mavlink-integration\ndescription: \"Use this skill when a task involves MAVLink protocol communication via pymavlink, UART\u002FUDP\u002FTCP drone connections, ArduPilot SITL simulation, or telemetry message parsing in the edge service. Don't use it for raw UART hardware driver code without MAVLink framing (use embedded-systems), WebSocket transport to the web portal (use api-integration), or Docker builds (use docker-build).\"\nversion: \"1.0.0\"\nowner: \"swarmery-core\"\nallowed-tools: Read, Bash, Grep, Glob\ndocs:\n  status: reviewed\n  source_sha: a12b075c166f\n  updated: 2026-08-06\n---\n\n# Purpose\n\nProduce MAVLink protocol code for drone communication in the edge service (project.json → device; Python 3.11+ on Raspberry Pi 5). Covers pymavlink connection types (UART, UDP, TCP), message parsing for common telemetry messages, async I\u002FO patterns with `asyncio.to_thread`, ArduPilot SITL simulation setup, and `MOCK_MODE` for CI testing without hardware. For the WebSocket bridge from the edge service to the web portal, defer to `api-integration`. For Helm deployment of edge service pods, defer to the project's deployment workflow.\n\nSuccess criteria: generated code connects (or simulates connection in MOCK_MODE), sends GCS heartbeats at 1Hz, reads telemetry via `recv_match`, handles `asyncio.CancelledError` for graceful shutdown, and releases the connection on stop.\n\n# When to use\n\n- Connecting to a drone via pymavlink (UART serial, UDP simulator, TCP)\n- Parsing MAVLink telemetry messages (HEARTBEAT, GLOBAL_POSITION_INT, ATTITUDE, GPS_RAW_INT)\n- Implementing async MAVLink reader\u002Fwriter patterns in the edge service\n- Setting up ArduPilot SITL for local development or CI testing\n- Configuring `MOCK_MODE` for testing without physical hardware\n\n# When NOT to use\n\n- Raw UART hardware driver code without MAVLink framing (use `embedded-systems`)\n- WebSocket streaming from the edge service to the web portal (use `api-integration`)\n- Deploying the edge service via Helm\u002Fk3s (use the project's deployment workflow)\n- Building Docker images for the edge service (use `docker-build`)\n- Debugging Kubernetes pod health for the edge service (use `troubleshooting`)\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fmavlink-integration\u002FSKILL.md`\n- Language: Python 3.11+\n- Libraries: `pymavlink`, `asyncio`, `serial` (for `serial.SerialException`)\n- Repo: the edge service repo (project.json → device)\n- MAVLink dialect: `ardupilotmega` (superset of `common`)\n- Hardware: Raspberry Pi 5 with UART (`\u002Fdev\u002FttyAMA0` default, configurable via `MAVLINK_CONNECTION` env var)\n- Simulator: ArduPilot SITL (UDP `127.0.0.1:14550`)\n- CI testing: `MOCK_MODE=true` env var disables UART connection\n\n# Inputs\n\n- `connection_type: enum` -- one of: `uart`, `udp`, `tcp`\n- `connection_string: string` -- pymavlink connection string (e.g., `serial:\u002Fdev\u002FttyAMA0:57600`, `udp:127.0.0.1:14550`)\n- `message_types: string[]` -- MAVLink message types to read (e.g., `HEARTBEAT`, `GLOBAL_POSITION_INT`)\n\n# Outputs\n\n- Format: Python code using pymavlink with async patterns, or SITL setup commands\n- Length budget: max 100 lines for a connection manager class; max 30 lines for a telemetry parsing snippet\n- All code follows edge service standards: type hints, `asyncio.to_thread` for blocking calls, specific exception handling\n\n# Procedure\n\n1. **Determine connection type** -- UART for real hardware, UDP for SITL, TCP for remote.\n   **Checkpoint:** Connection string format matches pymavlink expectations (e.g., `serial:\u002Fdev\u002FttyAMA0:57600` for UART, `udp:127.0.0.1:14550` for SITL).\n\n2. **Check MOCK_MODE** -- If `MOCK_MODE=true`, skip real connection and return synthetic telemetry.\n   **Checkpoint:** Env var checked before attempting hardware connection.\n\n3. **Establish connection** -- Use `mavutil.mavlink_connection()` wrapped in `asyncio.to_thread`.\n   **Checkpoint:** Connection object is not None and `recv_match(type='HEARTBEAT')` succeeds.\n\n4. **Start heartbeat sender** -- Send GCS heartbeats at 1Hz minimum to maintain connection. Guard against double-start by checking if the heartbeat task already exists.\n   **Checkpoint:** Heartbeat task running with `asyncio.CancelledError` handling.\n\n5. **Read telemetry** -- Use `recv_match` with specific message types and timeouts.\n   **Checkpoint:** Message data validated before use.\n\n# Self-check\n\n\u003Cself-check>\n- [ ] I used `GLOBAL_POSITION_INT` (message #33) or `GPS_RAW_INT` (message #24), not the non-existent `GPS_POSITION`\n- [ ] Async code wraps all pymavlink blocking calls in `asyncio.to_thread`\n- [ ] The heartbeat loop handles `asyncio.CancelledError` for graceful shutdown\n- [ ] Exception handling uses specific exceptions (`serial.SerialException`, `OSError`, `ConnectionRefusedError`), not bare `except Exception`\n- [ ] `import serial` is present whenever `serial.SerialException` is referenced -- pymavlink does not bring `serial` into scope\n- [ ] Connection string is read from `MAVLINK_CONNECTION` env var, not hardcoded\n- [ ] I mentioned `MOCK_MODE=true` for CI\u002Ftesting contexts\n- [ ] I specified the MAVLink dialect (`ardupilotmega`) when referencing non-common messages\n- [ ] The `stop()` method cancels the heartbeat task AND closes the MAVLink connection\n\u003C\u002Fself-check>\n\n# Common mistakes\n\n- DO NOT use `GPS_POSITION` as a message name -- it does not exist in MAVLink; use `GLOBAL_POSITION_INT` (#33) for fused position or `GPS_RAW_INT` (#24) for raw GPS\n\n  ```python\n  # WRONG -- GPS_POSITION does not exist, recv_match returns None forever\n  msg = await reader.read_message(\"GPS_POSITION\", timeout=1.0)\n\n  # CORRECT -- use GLOBAL_POSITION_INT (#33) for fused lat\u002Flon\u002Falt\n  msg = await reader.read_message(\"GLOBAL_POSITION_INT\", timeout=1.0)\n  ```\n\n- DO NOT reference `serial.SerialException` without `import serial` -- pymavlink does not bring `serial` into scope; missing this causes `NameError` at runtime\n\n  ```python\n  # WRONG -- NameError: name 'serial' is not defined\n  from pymavlink import mavutil\n  # ... later ...\n  except (OSError, serial.SerialException) as err:\n\n  # CORRECT -- import serial explicitly\n  import serial\n  from pymavlink import mavutil\n  # ... later ...\n  except (OSError, serial.SerialException) as err:\n  ```\n\n- DO NOT hardcode `\u002Fdev\u002FttyAMA0` -- read from `MAVLINK_CONNECTION` env var; UART device paths vary across RPi models\n- DO NOT use bare `except Exception` -- catch `serial.SerialException` and `OSError` for connection errors, `ConnectionRefusedError` for SITL UDP\n- DO NOT run an infinite `while True` loop without `asyncio.CancelledError` handling -- the task will leak on shutdown and trigger Python 3.11+ warnings\n- DO NOT test against real hardware in CI -- set `MOCK_MODE=true` to disable UART and return synthetic telemetry\n- DO NOT forget to close the MAVLink connection in `stop()` -- call `self.connection.close()` after cancelling the heartbeat task\n\n# Escalation\n\n- Stop and ask when: UART device path is not `\u002Fdev\u002FttyAMA0` and the user has not specified the correct path\n- Stop and ask when: SITL is unreachable after setup and the ArduPilot firmware version is unknown\n- Stop and ask when: The user needs to send flight commands (arm, takeoff, waypoint) to a real drone -- this is a safety-critical operation requiring explicit operator confirmation\n\n# What to surface\n\n- Which connection type and string are being used\n- Whether MOCK_MODE is active\n- The MAVLink dialect assumed (common vs ardupilotmega)\n- Any baud rate or device path configuration that may need adjustment\n- SITL connection status and which messages are being received\n\n# Examples\n\n\u003Cexample name=\"async-mavlink-reader\">\n## Async MAVLink reader with proper error handling\n\n```python\nimport asyncio\nimport logging\nimport os\nimport serial\nfrom typing import Any, Optional\n\nfrom pymavlink import mavutil\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass MAVLinkReader:\n    \"\"\"Async MAVLink connection manager for the edge service.\"\"\"\n\n    def __init__(self, connection_string: Optional[str] = None) -> None:\n        self.connection_string = connection_string or os.environ.get(\n            \"MAVLINK_CONNECTION\", \"serial:\u002Fdev\u002FttyAMA0:57600\"\n        )\n        self.connection: Optional[Any] = None\n        self._heartbeat_task: Optional[asyncio.Task[None]] = None\n\n    async def connect(self) -> bool:\n        \"\"\"Establish MAVLink connection.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE active -- skipping real MAVLink connection\")\n            return True\n\n        try:\n            self.connection = await asyncio.to_thread(\n                mavutil.mavlink_connection,\n                self.connection_string,\n                source_system=255,\n                source_component=0,\n            )\n            # Wait for first heartbeat to confirm connection\n            msg = await asyncio.to_thread(\n                self.connection.recv_match,\n                type=\"HEARTBEAT\",\n                blocking=True,\n                timeout=10,\n            )\n            if msg is None:\n                logger.error(\"No heartbeat received within 10s\")\n                return False\n            logger.info(\"Connected to system %d\", msg.get_srcSystem())\n            return True\n        except serial.SerialException as err:\n            logger.error(\"Serial connection failed: %s\", err)\n            return False\n        except OSError as err:\n            logger.error(\"Connection failed: %s\", err)\n            return False\n\n    async def read_message(\n        self, msg_type: str, timeout: float = 1.0\n    ) -> Optional[Any]:\n        \"\"\"Read a specific MAVLink message type.\"\"\"\n        if MOCK_MODE:\n            return None\n        if not self.connection:\n            return None\n        try:\n            return await asyncio.to_thread(\n                self.connection.recv_match,\n                type=msg_type,\n                blocking=True,\n                timeout=timeout,\n            )\n        except OSError as err:\n            logger.error(\"Read error for %s: %s\", msg_type, err)\n            return None\n\n    async def send_heartbeat_loop(self) -> None:\n        \"\"\"Send GCS heartbeats at 1Hz. Handles cancellation for graceful shutdown.\"\"\"\n        try:\n            while True:\n                if self.connection:\n                    await asyncio.to_thread(\n                        self.connection.mav.heartbeat_send,\n                        mavutil.mavlink.MAV_TYPE_GCS,\n                        mavutil.mavlink.MAV_AUTOPILOT_INVALID,\n                        0,\n                        0,\n                        mavutil.mavlink.MAV_STATE_ACTIVE,\n                    )\n                await asyncio.sleep(1)\n        except asyncio.CancelledError:\n            logger.info(\"Heartbeat sender cancelled -- shutting down\")\n            return\n\n    async def start(self) -> bool:\n        \"\"\"Connect and start heartbeat sender.\"\"\"\n        if not await self.connect():\n            return False\n        if self._heartbeat_task is not None:\n            logger.warning(\"Heartbeat task already running -- skipping duplicate start\")\n            return True\n        self._heartbeat_task = asyncio.create_task(self.send_heartbeat_loop())\n        return True\n\n    async def stop(self) -> None:\n        \"\"\"Graceful shutdown -- cancel heartbeat and close connection.\"\"\"\n        if self._heartbeat_task:\n            self._heartbeat_task.cancel()\n            await self._heartbeat_task\n            self._heartbeat_task = None\n        if self.connection:\n            await asyncio.to_thread(self.connection.close)\n            self.connection = None\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"gps-telemetry\">\n## Reading GPS telemetry (GLOBAL_POSITION_INT #33)\n\n```python\nmsg = await reader.read_message(\"GLOBAL_POSITION_INT\", timeout=1.0)\nif msg:\n    telemetry = {\n        \"lat\": msg.lat \u002F 1e7,           # degrees\n        \"lon\": msg.lon \u002F 1e7,           # degrees\n        \"alt\": msg.alt \u002F 1000,          # meters above MSL\n        \"relative_alt\": msg.relative_alt \u002F 1000,  # meters above ground\n        \"heading\": msg.hdg \u002F 100,       # degrees\n        \"vx\": msg.vx \u002F 100,            # m\u002Fs north\n        \"vy\": msg.vy \u002F 100,            # m\u002Fs east\n        \"vz\": msg.vz \u002F 100,            # m\u002Fs down\n    }\n```\n\nFor raw GPS data use `GPS_RAW_INT` (#24) instead -- it provides `fix_type`, `satellites_visible`, `eph` (HDOP), and `epv` (VDOP).\n\u003C\u002Fexample>\n\n\u003Cexample name=\"sitl-setup\">\n## ArduPilot SITL setup\n\n```bash\n# Clone and build (one-time)\ngit clone https:\u002F\u002Fgithub.com\u002FArduPilot\u002Fardupilot.git\ncd ardupilot\ngit submodule update --init --recursive\nTools\u002Fenvironment_install\u002Finstall-prereqs-ubuntu.sh -y\n\n# Run SITL (listens on UDP:127.0.0.1:14550)\ncd ArduCopter\nsim_vehicle.py -v ArduCopter --console --map\n\n# Connect from Python\n# MAVLINK_CONNECTION=udp:127.0.0.1:14550 python your_script.py\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"mock-mode-ci\">\n## Testing without hardware (MOCK_MODE)\n\nSet `MOCK_MODE=true` in CI environments to skip UART connections:\n\n```yaml\n# Kubernetes values or CI env\nenv:\n  - name: MOCK_MODE\n    value: \"true\"\n  - name: LOG_LEVEL\n    value: \"DEBUG\"\n```\n\nIn code, check `MOCK_MODE` before attempting hardware access (see `connect()` method above). Return synthetic telemetry data for testing.\n\u003C\u002Fexample>\n\n# Failure modes\n\n| Mode | Symptom | Detection | Fix |\n|------|---------|-----------|-----|\n| Wrong message name `GPS_POSITION` | `recv_match` returns None forever | Message name is not in MAVLink common\u002Fardupilotmega dialect | Use `GLOBAL_POSITION_INT` (#33) or `GPS_RAW_INT` (#24) |\n| UART baud rate mismatch | Connection succeeds but no messages received | Serial monitor shows garbled data | Verify baud rate matches ArduPilot `SERIAL1_BAUD` parameter (typically 57600 or 115200) |\n| Heartbeat task leak on shutdown | `RuntimeWarning: coroutine was never awaited` or task pending at interpreter shutdown | No `CancelledError` handler in heartbeat loop | Add `try\u002Fexcept asyncio.CancelledError: return` and cancel the task in `stop()` |\n| SITL connection refused | `ConnectionRefusedError` on UDP connect | ArduPilot SITL is not running | Start SITL with `sim_vehicle.py`, then retry connection |\n| Missing `import serial` | `NameError: name 'serial' is not defined` at runtime | `serial.SerialException` referenced without import | Add `import serial` to import block |\n\n# Related skills\n\n- `api-integration` -- defer for the WebSocket bridge from the edge service to the web portal; compose when MAVLink data needs to reach the browser via SSE\n- The project's deployment workflow -- defer for deploying edge service pods to k3s on Raspberry Pi; `MAVLINK_CONNECTION` and `MOCK_MODE` env vars are set in Helm values there\n- `embedded-systems` -- defer for RPi hardware config (GPIO, UART enable, camera); compose when UART device path needs to be determined\n- `code-standards` -- follow its Python section for type hints, specific exceptions, and `MOCK_MODE` patterns\n\n# How to use\n\n## What it does\n\nThis skill produces MAVLink code for talking to a drone from an edge service in Python. It covers pymavlink connection strings for serial, UDP, and TCP, async patterns that wrap blocking pymavlink calls in `asyncio.to_thread`, telemetry message parsing, ArduPilot SITL setup, and a mock mode so tests run without hardware. It also encodes the mistakes that bite here — wrong message names, missing imports, leaked heartbeat tasks.\n\n## When to use it\n\n- You are opening a pymavlink connection over UART, UDP to a simulator, or TCP.\n- You are parsing telemetry — `HEARTBEAT`, `GLOBAL_POSITION_INT`, `ATTITUDE`, `GPS_RAW_INT`.\n- You are writing an async MAVLink reader or writer with a heartbeat loop and clean shutdown.\n- You are setting up ArduPilot SITL locally, or need a hardware-free mode for CI.\n\n## When not to use it\n\n- Raw serial driver code with no MAVLink framing — use `embedded-systems`.\n- Streaming telemetry onward to a browser over WebSocket or SSE — use `api-integration`.\n- Building or pushing container images for the service — use `docker-build`.\n- Diagnosing a failing pod or deployment rather than the protocol — use `troubleshooting`.\n\n## How to invoke\n\n```\nSkill(skill: \"uav-pack:mavlink-integration\")\n```\n\nInvoke it before writing the MAVLink code, then state the connection type, the connection string, and whether mock mode is on.\n\n## Inputs\n\n- `connection_type` — one of `uart`, `udp`, `tcp` — required.\n- `connection_string` — a pymavlink string such as `udp:127.0.0.1:14550` — required.\n- `message_types` — the MAVLink message names you want to read — optional; defaults to a heartbeat-only connection.\n\n## What you get back\n\nPython code with type hints and specific exception handling: a connection-manager class of up to about 100 lines, or a telemetry-parsing snippet of up to about 30, or SITL setup commands. The code reads its connection string from an environment variable rather than hard-coding a device path, sends heartbeats at 1 Hz, handles `asyncio.CancelledError`, and closes the connection on stop. You also get a short note on the dialect assumed and any baud rate or device path you may need to adjust.\n\n## Worked example\n\n```\nSkill(skill: \"uav-pack:mavlink-integration\")\n\nYou ask: \"Read GPS position from SITL and push it into the telemetry queue.\"\n\nYou get back: a reader that connects to udp:127.0.0.1:14550, waits for the\nfirst HEARTBEAT to confirm the link, then reads GLOBAL_POSITION_INT (#33) and\nscales the fields — lat and lon by 1e7, alt by 1000 — into a plain dict.\nThe skill flags that GPS_POSITION is not a real message name, so recv_match\non it would return None forever.\n```\n\n## Related\n\n- `embedded-systems` — reach for it when the question is the hardware itself: enabling UART, GPIO, or finding the right device path.\n- `api-integration` — reach for it when the MAVLink data has to leave the device and reach a browser.\n- `code-standards` — its Python section is the style the generated code follows.\n","# Purpose\n\nProduce MAVLink protocol code for drone communication in the edge service (project.json → device; Python 3.11+ on Raspberry Pi 5). Covers pymavlink connection types (UART, UDP, TCP), message parsing for common telemetry messages, async I\u002FO patterns with `asyncio.to_thread`, ArduPilot SITL simulation setup, and `MOCK_MODE` for CI testing without hardware. For the WebSocket bridge from the edge service to the web portal, defer to `api-integration`. For Helm deployment of edge service pods, defer to the project's deployment workflow.\n\nSuccess criteria: generated code connects (or simulates connection in MOCK_MODE), sends GCS heartbeats at 1Hz, reads telemetry via `recv_match`, handles `asyncio.CancelledError` for graceful shutdown, and releases the connection on stop.\n\n# When to use\n\n- Connecting to a drone via pymavlink (UART serial, UDP simulator, TCP)\n- Parsing MAVLink telemetry messages (HEARTBEAT, GLOBAL_POSITION_INT, ATTITUDE, GPS_RAW_INT)\n- Implementing async MAVLink reader\u002Fwriter patterns in the edge service\n- Setting up ArduPilot SITL for local development or CI testing\n- Configuring `MOCK_MODE` for testing without physical hardware\n\n# When NOT to use\n\n- Raw UART hardware driver code without MAVLink framing (use `embedded-systems`)\n- WebSocket streaming from the edge service to the web portal (use `api-integration`)\n- Deploying the edge service via Helm\u002Fk3s (use the project's deployment workflow)\n- Building Docker images for the edge service (use `docker-build`)\n- Debugging Kubernetes pod health for the edge service (use `troubleshooting`)\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fmavlink-integration\u002FSKILL.md`\n- Language: Python 3.11+\n- Libraries: `pymavlink`, `asyncio`, `serial` (for `serial.SerialException`)\n- Repo: the edge service repo (project.json → device)\n- MAVLink dialect: `ardupilotmega` (superset of `common`)\n- Hardware: Raspberry Pi 5 with UART (`\u002Fdev\u002FttyAMA0` default, configurable via `MAVLINK_CONNECTION` env var)\n- Simulator: ArduPilot SITL (UDP `127.0.0.1:14550`)\n- CI testing: `MOCK_MODE=true` env var disables UART connection\n\n# Inputs\n\n- `connection_type: enum` -- one of: `uart`, `udp`, `tcp`\n- `connection_string: string` -- pymavlink connection string (e.g., `serial:\u002Fdev\u002FttyAMA0:57600`, `udp:127.0.0.1:14550`)\n- `message_types: string[]` -- MAVLink message types to read (e.g., `HEARTBEAT`, `GLOBAL_POSITION_INT`)\n\n# Outputs\n\n- Format: Python code using pymavlink with async patterns, or SITL setup commands\n- Length budget: max 100 lines for a connection manager class; max 30 lines for a telemetry parsing snippet\n- All code follows edge service standards: type hints, `asyncio.to_thread` for blocking calls, specific exception handling\n\n# Procedure\n\n1. **Determine connection type** -- UART for real hardware, UDP for SITL, TCP for remote.\n   **Checkpoint:** Connection string format matches pymavlink expectations (e.g., `serial:\u002Fdev\u002FttyAMA0:57600` for UART, `udp:127.0.0.1:14550` for SITL).\n\n2. **Check MOCK_MODE** -- If `MOCK_MODE=true`, skip real connection and return synthetic telemetry.\n   **Checkpoint:** Env var checked before attempting hardware connection.\n\n3. **Establish connection** -- Use `mavutil.mavlink_connection()` wrapped in `asyncio.to_thread`.\n   **Checkpoint:** Connection object is not None and `recv_match(type='HEARTBEAT')` succeeds.\n\n4. **Start heartbeat sender** -- Send GCS heartbeats at 1Hz minimum to maintain connection. Guard against double-start by checking if the heartbeat task already exists.\n   **Checkpoint:** Heartbeat task running with `asyncio.CancelledError` handling.\n\n5. **Read telemetry** -- Use `recv_match` with specific message types and timeouts.\n   **Checkpoint:** Message data validated before use.\n\n# Self-check\n\n\u003Cself-check>\n- [ ] I used `GLOBAL_POSITION_INT` (message #33) or `GPS_RAW_INT` (message #24), not the non-existent `GPS_POSITION`\n- [ ] Async code wraps all pymavlink blocking calls in `asyncio.to_thread`\n- [ ] The heartbeat loop handles `asyncio.CancelledError` for graceful shutdown\n- [ ] Exception handling uses specific exceptions (`serial.SerialException`, `OSError`, `ConnectionRefusedError`), not bare `except Exception`\n- [ ] `import serial` is present whenever `serial.SerialException` is referenced -- pymavlink does not bring `serial` into scope\n- [ ] Connection string is read from `MAVLINK_CONNECTION` env var, not hardcoded\n- [ ] I mentioned `MOCK_MODE=true` for CI\u002Ftesting contexts\n- [ ] I specified the MAVLink dialect (`ardupilotmega`) when referencing non-common messages\n- [ ] The `stop()` method cancels the heartbeat task AND closes the MAVLink connection\n\u003C\u002Fself-check>\n\n# Common mistakes\n\n- DO NOT use `GPS_POSITION` as a message name -- it does not exist in MAVLink; use `GLOBAL_POSITION_INT` (#33) for fused position or `GPS_RAW_INT` (#24) for raw GPS\n\n  ```python\n  # WRONG -- GPS_POSITION does not exist, recv_match returns None forever\n  msg = await reader.read_message(\"GPS_POSITION\", timeout=1.0)\n\n  # CORRECT -- use GLOBAL_POSITION_INT (#33) for fused lat\u002Flon\u002Falt\n  msg = await reader.read_message(\"GLOBAL_POSITION_INT\", timeout=1.0)\n  ```\n\n- DO NOT reference `serial.SerialException` without `import serial` -- pymavlink does not bring `serial` into scope; missing this causes `NameError` at runtime\n\n  ```python\n  # WRONG -- NameError: name 'serial' is not defined\n  from pymavlink import mavutil\n  # ... later ...\n  except (OSError, serial.SerialException) as err:\n\n  # CORRECT -- import serial explicitly\n  import serial\n  from pymavlink import mavutil\n  # ... later ...\n  except (OSError, serial.SerialException) as err:\n  ```\n\n- DO NOT hardcode `\u002Fdev\u002FttyAMA0` -- read from `MAVLINK_CONNECTION` env var; UART device paths vary across RPi models\n- DO NOT use bare `except Exception` -- catch `serial.SerialException` and `OSError` for connection errors, `ConnectionRefusedError` for SITL UDP\n- DO NOT run an infinite `while True` loop without `asyncio.CancelledError` handling -- the task will leak on shutdown and trigger Python 3.11+ warnings\n- DO NOT test against real hardware in CI -- set `MOCK_MODE=true` to disable UART and return synthetic telemetry\n- DO NOT forget to close the MAVLink connection in `stop()` -- call `self.connection.close()` after cancelling the heartbeat task\n\n# Escalation\n\n- Stop and ask when: UART device path is not `\u002Fdev\u002FttyAMA0` and the user has not specified the correct path\n- Stop and ask when: SITL is unreachable after setup and the ArduPilot firmware version is unknown\n- Stop and ask when: The user needs to send flight commands (arm, takeoff, waypoint) to a real drone -- this is a safety-critical operation requiring explicit operator confirmation\n\n# What to surface\n\n- Which connection type and string are being used\n- Whether MOCK_MODE is active\n- The MAVLink dialect assumed (common vs ardupilotmega)\n- Any baud rate or device path configuration that may need adjustment\n- SITL connection status and which messages are being received\n\n# Examples\n\n\u003Cexample name=\"async-mavlink-reader\">\n## Async MAVLink reader with proper error handling\n\n```python\nimport asyncio\nimport logging\nimport os\nimport serial\nfrom typing import Any, Optional\n\nfrom pymavlink import mavutil\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass MAVLinkReader:\n    \"\"\"Async MAVLink connection manager for the edge service.\"\"\"\n\n    def __init__(self, connection_string: Optional[str] = None) -> None:\n        self.connection_string = connection_string or os.environ.get(\n            \"MAVLINK_CONNECTION\", \"serial:\u002Fdev\u002FttyAMA0:57600\"\n        )\n        self.connection: Optional[Any] = None\n        self._heartbeat_task: Optional[asyncio.Task[None]] = None\n\n    async def connect(self) -> bool:\n        \"\"\"Establish MAVLink connection.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE active -- skipping real MAVLink connection\")\n            return True\n\n        try:\n            self.connection = await asyncio.to_thread(\n                mavutil.mavlink_connection,\n                self.connection_string,\n                source_system=255,\n                source_component=0,\n            )\n            # Wait for first heartbeat to confirm connection\n            msg = await asyncio.to_thread(\n                self.connection.recv_match,\n                type=\"HEARTBEAT\",\n                blocking=True,\n                timeout=10,\n            )\n            if msg is None:\n                logger.error(\"No heartbeat received within 10s\")\n                return False\n            logger.info(\"Connected to system %d\", msg.get_srcSystem())\n            return True\n        except serial.SerialException as err:\n            logger.error(\"Serial connection failed: %s\", err)\n            return False\n        except OSError as err:\n            logger.error(\"Connection failed: %s\", err)\n            return False\n\n    async def read_message(\n        self, msg_type: str, timeout: float = 1.0\n    ) -> Optional[Any]:\n        \"\"\"Read a specific MAVLink message type.\"\"\"\n        if MOCK_MODE:\n            return None\n        if not self.connection:\n            return None\n        try:\n            return await asyncio.to_thread(\n                self.connection.recv_match,\n                type=msg_type,\n                blocking=True,\n                timeout=timeout,\n            )\n        except OSError as err:\n            logger.error(\"Read error for %s: %s\", msg_type, err)\n            return None\n\n    async def send_heartbeat_loop(self) -> None:\n        \"\"\"Send GCS heartbeats at 1Hz. Handles cancellation for graceful shutdown.\"\"\"\n        try:\n            while True:\n                if self.connection:\n                    await asyncio.to_thread(\n                        self.connection.mav.heartbeat_send,\n                        mavutil.mavlink.MAV_TYPE_GCS,\n                        mavutil.mavlink.MAV_AUTOPILOT_INVALID,\n                        0,\n                        0,\n                        mavutil.mavlink.MAV_STATE_ACTIVE,\n                    )\n                await asyncio.sleep(1)\n        except asyncio.CancelledError:\n            logger.info(\"Heartbeat sender cancelled -- shutting down\")\n            return\n\n    async def start(self) -> bool:\n        \"\"\"Connect and start heartbeat sender.\"\"\"\n        if not await self.connect():\n            return False\n        if self._heartbeat_task is not None:\n            logger.warning(\"Heartbeat task already running -- skipping duplicate start\")\n            return True\n        self._heartbeat_task = asyncio.create_task(self.send_heartbeat_loop())\n        return True\n\n    async def stop(self) -> None:\n        \"\"\"Graceful shutdown -- cancel heartbeat and close connection.\"\"\"\n        if self._heartbeat_task:\n            self._heartbeat_task.cancel()\n            await self._heartbeat_task\n            self._heartbeat_task = None\n        if self.connection:\n            await asyncio.to_thread(self.connection.close)\n            self.connection = None\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"gps-telemetry\">\n## Reading GPS telemetry (GLOBAL_POSITION_INT #33)\n\n```python\nmsg = await reader.read_message(\"GLOBAL_POSITION_INT\", timeout=1.0)\nif msg:\n    telemetry = {\n        \"lat\": msg.lat \u002F 1e7,           # degrees\n        \"lon\": msg.lon \u002F 1e7,           # degrees\n        \"alt\": msg.alt \u002F 1000,          # meters above MSL\n        \"relative_alt\": msg.relative_alt \u002F 1000,  # meters above ground\n        \"heading\": msg.hdg \u002F 100,       # degrees\n        \"vx\": msg.vx \u002F 100,            # m\u002Fs north\n        \"vy\": msg.vy \u002F 100,            # m\u002Fs east\n        \"vz\": msg.vz \u002F 100,            # m\u002Fs down\n    }\n```\n\nFor raw GPS data use `GPS_RAW_INT` (#24) instead -- it provides `fix_type`, `satellites_visible`, `eph` (HDOP), and `epv` (VDOP).\n\u003C\u002Fexample>\n\n\u003Cexample name=\"sitl-setup\">\n## ArduPilot SITL setup\n\n```bash\n# Clone and build (one-time)\ngit clone https:\u002F\u002Fgithub.com\u002FArduPilot\u002Fardupilot.git\ncd ardupilot\ngit submodule update --init --recursive\nTools\u002Fenvironment_install\u002Finstall-prereqs-ubuntu.sh -y\n\n# Run SITL (listens on UDP:127.0.0.1:14550)\ncd ArduCopter\nsim_vehicle.py -v ArduCopter --console --map\n\n# Connect from Python\n# MAVLINK_CONNECTION=udp:127.0.0.1:14550 python your_script.py\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"mock-mode-ci\">\n## Testing without hardware (MOCK_MODE)\n\nSet `MOCK_MODE=true` in CI environments to skip UART connections:\n\n```yaml\n# Kubernetes values or CI env\nenv:\n  - name: MOCK_MODE\n    value: \"true\"\n  - name: LOG_LEVEL\n    value: \"DEBUG\"\n```\n\nIn code, check `MOCK_MODE` before attempting hardware access (see `connect()` method above). Return synthetic telemetry data for testing.\n\u003C\u002Fexample>\n\n# Failure modes\n\n| Mode | Symptom | Detection | Fix |\n|------|---------|-----------|-----|\n| Wrong message name `GPS_POSITION` | `recv_match` returns None forever | Message name is not in MAVLink common\u002Fardupilotmega dialect | Use `GLOBAL_POSITION_INT` (#33) or `GPS_RAW_INT` (#24) |\n| UART baud rate mismatch | Connection succeeds but no messages received | Serial monitor shows garbled data | Verify baud rate matches ArduPilot `SERIAL1_BAUD` parameter (typically 57600 or 115200) |\n| Heartbeat task leak on shutdown | `RuntimeWarning: coroutine was never awaited` or task pending at interpreter shutdown | No `CancelledError` handler in heartbeat loop | Add `try\u002Fexcept asyncio.CancelledError: return` and cancel the task in `stop()` |\n| SITL connection refused | `ConnectionRefusedError` on UDP connect | ArduPilot SITL is not running | Start SITL with `sim_vehicle.py`, then retry connection |\n| Missing `import serial` | `NameError: name 'serial' is not defined` at runtime | `serial.SerialException` referenced without import | Add `import serial` to import block |\n\n# Related skills\n\n- `api-integration` -- defer for the WebSocket bridge from the edge service to the web portal; compose when MAVLink data needs to reach the browser via SSE\n- The project's deployment workflow -- defer for deploying edge service pods to k3s on Raspberry Pi; `MAVLINK_CONNECTION` and `MOCK_MODE` env vars are set in Helm values there\n- `embedded-systems` -- defer for RPi hardware config (GPIO, UART enable, camera); compose when UART device path needs to be determined\n- `code-standards` -- follow its Python section for type hints, specific exceptions, and `MOCK_MODE` patterns\n\n# How to use\n\n## What it does\n\nThis skill produces MAVLink code for talking to a drone from an edge service in Python. It covers pymavlink connection strings for serial, UDP, and TCP, async patterns that wrap blocking pymavlink calls in `asyncio.to_thread`, telemetry message parsing, ArduPilot SITL setup, and a mock mode so tests run without hardware. It also encodes the mistakes that bite here — wrong message names, missing imports, leaked heartbeat tasks.\n\n## When to use it\n\n- You are opening a pymavlink connection over UART, UDP to a simulator, or TCP.\n- You are parsing telemetry — `HEARTBEAT`, `GLOBAL_POSITION_INT`, `ATTITUDE`, `GPS_RAW_INT`.\n- You are writing an async MAVLink reader or writer with a heartbeat loop and clean shutdown.\n- You are setting up ArduPilot SITL locally, or need a hardware-free mode for CI.\n\n## When not to use it\n\n- Raw serial driver code with no MAVLink framing — use `embedded-systems`.\n- Streaming telemetry onward to a browser over WebSocket or SSE — use `api-integration`.\n- Building or pushing container images for the service — use `docker-build`.\n- Diagnosing a failing pod or deployment rather than the protocol — use `troubleshooting`.\n\n## How to invoke\n\n```\nSkill(skill: \"uav-pack:mavlink-integration\")\n```\n\nInvoke it before writing the MAVLink code, then state the connection type, the connection string, and whether mock mode is on.\n\n## Inputs\n\n- `connection_type` — one of `uart`, `udp`, `tcp` — required.\n- `connection_string` — a pymavlink string such as `udp:127.0.0.1:14550` — required.\n- `message_types` — the MAVLink message names you want to read — optional; defaults to a heartbeat-only connection.\n\n## What you get back\n\nPython code with type hints and specific exception handling: a connection-manager class of up to about 100 lines, or a telemetry-parsing snippet of up to about 30, or SITL setup commands. The code reads its connection string from an environment variable rather than hard-coding a device path, sends heartbeats at 1 Hz, handles `asyncio.CancelledError`, and closes the connection on stop. You also get a short note on the dialect assumed and any baud rate or device path you may need to adjust.\n\n## Worked example\n\n```\nSkill(skill: \"uav-pack:mavlink-integration\")\n\nYou ask: \"Read GPS position from SITL and push it into the telemetry queue.\"\n\nYou get back: a reader that connects to udp:127.0.0.1:14550, waits for the\nfirst HEARTBEAT to confirm the link, then reads GLOBAL_POSITION_INT (#33) and\nscales the fields — lat and lon by 1e7, alt by 1000 — into a plain dict.\nThe skill flags that GPS_POSITION is not a real message name, so recv_match\non it would return None forever.\n```\n\n## Related\n\n- `embedded-systems` — reach for it when the question is the hardware itself: enabling UART, GPIO, or finding the right device path.\n- `api-integration` — reach for it when the MAVLink data has to leave the device and reach a browser.\n- `code-standards` — its Python section is the style the generated code follows.\n",{"docs":24,"name":5,"owner":28,"version":29,"description":7,"allowed-tools":30},{"status":25,"updated":26,"source_sha":27},"reviewed",1785974400000,"a12b075c166f","swarmery-core","1.0.0","Read, Bash, Grep, Glob","main","2d9e918cc79c9b17b59356780ff0a3da38a3e98a","plugins\u002Fuav-pack\u002Fskills\u002Fmavlink-integration",5,"https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery","https:\u002F\u002Fatretyak1985.github.io\u002Fswarmery\u002F","https:\u002F\u002Fgithub.com\u002Fatretyak1985","2026-11-11 04:29:12",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add atretyak1985\u002Fswarmery --skill mavlink-integration",{"tool":45,"command":46},"bunx","bunx skills add atretyak1985\u002Fswarmery --skill mavlink-integration",{"tool":48,"command":49},"pnpm","pnpm dlx skills add atretyak1985\u002Fswarmery --skill mavlink-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Fplugins\u002Fuav-pack\u002Fskills\u002Fmavlink-integration\u002FSKILL.md",true,[],[54,61,67,74,81,88],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M78D4T1FFWFW19Z44AHH5BSY","short-desc","Too short.","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fshort-desc\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M78D4S0TWT42WXFJHC1DBN0R","no-frontmatter","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fno-frontmatter\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M78D4Q14P8DJ4W78N62F3EG2","global-skill","Fixture global skill (minimal user-scope shape, format doc §2.3).","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fglobal-skill\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M78D4N1JHGQJQ7EZ43KY5SV3","documented-skill","Fixture skill whose usage guide deliberately omits the Worked example subsection.","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fdocumented-skill\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M78D4KVNZ03GBKGDFJZWW5FJ","z","NOT auto-discovered — only skills\u002F is scanned for plugins (§2.2).","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fplugins\u002Fcache\u002Fmkt\u002Ftoolpack\u002F1.0.0\u002Fworkflow-skills\u002Fz\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M78D4JMBRZWK51HFE5RZJGHC","y","Plugin skill y from toolpack — stored as \"toolpack:y\".","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fplugins\u002Fcache\u002Fmkt\u002Ftoolpack\u002F1.0.0\u002Fskills\u002Fy\u002FSKILL.md",[],[]]