[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78D3WBWBD2X2ZRTSFMRDPDS":3,"skill-same:01M78D3WBWBD2X2ZRTSFMRDPDS":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},"01M78D3WBWBD2X2ZRTSFMRDPDS","embedded-systems",null,"Use this skill when writing or reviewing Python code for Raspberry Pi 5 edge devices -- UART hardware drivers, camera streaming via picamera2, GPIO control, systemd services, or resource monitoring. Don't use it for MAVLink protocol parsing (use mavlink-integration), web portal server code, or Helm work.","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\u002Fembedded-systems\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: embedded-systems\ndescription: \"Use this skill when writing or reviewing Python code for Raspberry Pi 5 edge devices -- UART hardware drivers, camera streaming via picamera2, GPIO control, systemd services, or resource monitoring. Don't use it for MAVLink protocol parsing (use mavlink-integration), web portal server code, or Helm work.\"\nversion: \"1.0.0\"\nowner: \"swarmery-core\"\nallowed-tools: Read, Edit, Bash, Grep, Glob\ndocs:\n  status: reviewed\n  source_sha: 36398d0f597c\n  updated: 2026-08-06\n---\n\n# Purpose\n\nProduce and review Python code for Raspberry Pi 5 edge devices running the edge service. Covers UART serial communication, picamera2 camera streaming, GPIO control, resource monitoring, and systemd service configuration. All generated code passes `mypy`, handles `MOCK_MODE` for CI, and releases hardware resources on exit. For MAVLink protocol parsing (message IDs, dialects, command sequences), compose with `mavlink-integration`.\n\nSuccess criteria: generated code imports without hardware attached (`MOCK_MODE=true`), passes `mypy` with zero errors, and releases every acquired resource in a `finally` block.\n\n# When to use\n\n- Writing or reviewing Python code that interfaces with RPi5 hardware (UART, GPIO, camera)\n- Configuring systemd services for the edge service on edge devices\n- Debugging hardware communication issues (serial port, camera initialization)\n- Implementing resource monitoring (CPU temperature, memory, throttling) on edge devices\n\n# When NOT to use\n\n- Web portal server-side TypeScript code (use `api-integration` or `code-standards`)\n- Infrastructure or Helm chart work (use the project's deployment workflow)\n- MAVLink message parsing, dialect selection, or command sequencing (use `mavlink-integration`)\n- Docker image building for the edge service (use `docker-build`)\n- Python dependency auditing (use `deps-check`)\n- Any Python code in the edge service that is purely MAVLink protocol without hardware driver concerns (use `mavlink-integration`)\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fembedded-systems\u002FSKILL.md`\n- Tools\u002Flibraries: Python 3.11+, `serial_asyncio`, `picamera2`, `psutil`, `asyncio`\n- Hardware: Raspberry Pi 5 (or `MOCK_MODE=true` for CI\u002Fdev without hardware)\n- Code standards: `mypy` for type checking, `black` (line length 100), `isort`, `flake8` (max complexity 10)\n\n# Inputs\n\n- `component: \"uart\" | \"camera\" | \"gpio\" | \"systemd\" | \"monitoring\"` -- which hardware subsystem to work with\n- `mock_mode: boolean` -- if true, generate code that works without physical hardware (for CI testing)\n\n# Outputs\n\n- Format: Python code with type hints, specific exception handling, and `MOCK_MODE` support. All code passes `mypy` without errors.\n- Length budget: max 120 lines per class; max 40 lines per standalone function; systemd unit files under 25 lines.\n\n# Procedure\n\n1. **Check mock mode** -- Determine if the code should support running without hardware. If `MOCK_MODE` is set in the environment, all hardware interfaces return simulated data.\n\n   ```python\n   import os\n   MOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n   ```\n\n   **Checkpoint:** `MOCK_MODE` check is present at module level. The check reads from the environment at runtime, never hardcoded to a literal `\"false\"`.\n\n2. **Import required modules** -- Always include explicit imports. Never assume modules are available in scope. If using `serial.EIGHTBITS` or `serial.SerialException`, you must `import serial` separately -- `serial_asyncio` does not bring `serial` constants into scope.\n\n   ```python\n   import asyncio\n   import logging\n   import serial          # required for serial.EIGHTBITS, serial.SerialException\n   import serial_asyncio\n   from typing import Optional\n\n   logger = logging.getLogger(__name__)\n   ```\n\n   **Checkpoint:** `logger` and all type imports are explicitly defined. `import serial` is present if any `serial.*` constant or exception is referenced.\n\n3. **Implement with specific exceptions** -- Use specific exception types, not bare `except Exception`. Hardware code handles known failure modes:\n\n   - UART: `serial.SerialException`, `OSError`, `asyncio.TimeoutError`\n   - Camera: `RuntimeError` (picamera2 init failure), `OSError` (device not found)\n   - GPIO: `PermissionError`, `FileNotFoundError` (sysfs access)\n\n   **Checkpoint:** Every `except` block catches a specific exception type.\n\n4. **Add cleanup in `finally` blocks** -- Hardware resources (serial ports, camera) are released on exit.\n\n   **Checkpoint:** Every `connect`\u002F`initialize` has a corresponding `close`\u002F`cleanup` in a `finally` block.\n\n5. **Add exit conditions to loops** -- Streaming loops accept a stop signal.\n\n   **Checkpoint:** Every `while` loop checks a `stop_event: asyncio.Event` or equivalent.\n\n6. **Show diff before applying Edit** -- Before applying any Edit to an existing file, show the operator a before\u002Fafter diff of the code change and confirm the target hardware component.\n\n   **Checkpoint:** Diff shown; operator has context on which hardware subsystem is affected.\n\n7. **Test with MOCK_MODE** -- Verify the code runs in CI without hardware by setting `MOCK_MODE=true`.\n\n   **Checkpoint:** `mypy` passes, and the module can be imported without hardware attached.\n\n# Self-check\n\n\u003Cself-check>\n- [ ] All Python code has type hints on parameters and return types\n- [ ] `logger` is explicitly created via `logging.getLogger(__name__)`, not used as an undefined name\n- [ ] `serial` module is imported before referencing `serial.EIGHTBITS`, `serial.SerialException`, etc. -- `serial_asyncio` does NOT bring these into scope\n- [ ] Every `except` block catches a specific exception, not bare `Exception`\n- [ ] Every streaming loop has an exit condition (e.g., `stop_event.is_set()`)\n- [ ] Hardware resources are released in `finally` blocks\n- [ ] `MOCK_MODE` support is present for CI compatibility -- the check reads `os.environ`, never hardcoded\n- [ ] No hardcoded paths like `\u002Fhome\u002Fpi\u002F` -- use environment variables or systemd specifiers\n- [ ] `mypy` would pass on the generated code\n- [ ] Systemd service templates use `MOCK_MODE=${MOCK_MODE:-false}`, not a hardcoded literal\n- [ ] Before\u002Fafter diff was shown for every Edit applied to existing files\n\u003C\u002Fself-check>\n\n# Common mistakes\n\n- DO NOT use bare `except Exception` -- always catch specific exceptions (`serial.SerialException`, `OSError`, `RuntimeError`)\n- DO NOT reference `logger` without defining it -- always add `logger = logging.getLogger(__name__)` at module level\n- DO NOT reference `serial.EIGHTBITS` without `import serial` -- the `serial_asyncio` import does not bring `serial` constants into scope\n- DO NOT write infinite loops without exit conditions -- always use `while not stop_event.is_set()` or a cancellation token\n- DO NOT hardcode `\u002Fhome\u002Fpi\u002F` in systemd service files -- use `%h` (home directory specifier) or environment variables; the deploy user may be `ubuntu` (as on the staging environment)\n- DO NOT use `raspi-config` menu instructions for camera enable -- on Raspberry Pi OS Bookworm (2024+), use `dtoverlay=camera_auto_detect` in `\u002Fboot\u002Ffirmware\u002Fconfig.txt`\n- DO NOT call `self.camera.capture_file()` without checking `self.camera is not None` first\n- DO NOT open UART without a corresponding `finally` block to release the port\n- DO NOT hardcode `MOCK_MODE=false` in systemd service templates -- use `MOCK_MODE=${MOCK_MODE:-false}` so environment-specific overrides work via drop-in files\n\n# Escalation\n\n- Stop and ask when: The target RPi model is not RPi5 (GPIO pinout and UART assignments differ)\n- Stop and ask when: Multiple services need the same UART port (serial port contention)\n- Stop and ask when: Camera resolution exceeds 1920x1080 at 30fps (may exceed RPi5 ISP throughput)\n- Stop and ask when: The code must interact with MAVLink messages (hand off to `mavlink-integration`)\n\n# What to surface\n\n- Whether `MOCK_MODE` is being used (affects test validity)\n- Hardware-specific side effects: UART monopolizes the serial port, camera locks the CSI interface\n- The systemd service user and working directory (must match the target device)\n- Any `asyncio.to_thread()` calls wrapping blocking I\u002FO (pymavlink, picamera2 capture)\n\n# Examples\n\n\u003Cexample name=\"uart-reader\">\n**Scenario**: Implement a UART reader for serial communication on the edge service\n\n```python\nimport asyncio\nimport logging\nimport os\nimport serial\nimport serial_asyncio\nfrom typing import Optional\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass UARTReader:\n    \"\"\"Async UART reader for serial communication with flight controller.\"\"\"\n\n    def __init__(self, port: str = \"\u002Fdev\u002FttyAMA0\", baudrate: int = 57600) -> None:\n        self.port = port\n        self.baudrate = baudrate\n        self.reader: Optional[asyncio.StreamReader] = None\n        self.writer: Optional[asyncio.StreamWriter] = None\n\n    async def connect(self) -> bool:\n        \"\"\"Establish UART connection. Returns True on success.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE: Simulating UART connection on %s\", self.port)\n            return True\n\n        try:\n            self.reader, self.writer = await serial_asyncio.open_serial_connection(\n                url=self.port,\n                baudrate=self.baudrate,\n                bytesize=serial.EIGHTBITS,\n                parity=serial.PARITY_NONE,\n                stopbits=serial.STOPBITS_ONE,\n            )\n            logger.info(\"Connected to UART: %s\", self.port)\n            return True\n        except serial.SerialException as err:\n            logger.error(\"UART serial error on %s: %s\", self.port, err)\n            return False\n        except OSError as err:\n            logger.error(\"UART OS error on %s: %s\", self.port, err)\n            return False\n\n    async def read_bytes(self, size: int, timeout: float = 1.0) -> Optional[bytes]:\n        \"\"\"Read bytes from UART with timeout.\"\"\"\n        if MOCK_MODE:\n            return b\"\\x00\" * size\n\n        if self.reader is None:\n            return None\n\n        try:\n            data = await asyncio.wait_for(self.reader.read(size), timeout=timeout)\n            return data\n        except asyncio.TimeoutError:\n            logger.debug(\"UART read timeout after %.1fs\", timeout)\n            return None\n        except serial.SerialException as err:\n            logger.error(\"UART read serial error: %s\", err)\n            return None\n        except OSError as err:\n            logger.error(\"UART read OS error: %s\", err)\n            return None\n\n    async def close(self) -> None:\n        \"\"\"Release UART resources.\"\"\"\n        if self.writer is not None:\n            try:\n                self.writer.close()\n                await self.writer.wait_closed()\n            except OSError as err:\n                logger.warning(\"Error closing UART writer: %s\", err)\n            finally:\n                self.writer = None\n                self.reader = None\n        logger.info(\"UART connection closed on %s\", self.port)\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"camera-streamer\">\n**Scenario**: Camera streaming with exit condition and cleanup\n\n```python\nimport asyncio\nimport logging\nimport os\nfrom io import BytesIO\nfrom typing import Awaitable, Callable, Optional\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass CameraStreamer:\n    \"\"\"Async camera streamer using picamera2.\"\"\"\n\n    def __init__(self, width: int = 640, height: int = 480, fps: int = 30) -> None:\n        self.width = width\n        self.height = height\n        self.fps = fps\n        self._camera: Optional[object] = None  # Picamera2 instance\n\n    async def initialize(self) -> bool:\n        \"\"\"Initialize camera. Returns True on success.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE: Simulating camera initialization\")\n            return True\n\n        try:\n            from picamera2 import Picamera2\n\n            self._camera = Picamera2()\n            config = self._camera.create_still_configuration(\n                main={\"size\": (self.width, self.height)}\n            )\n            self._camera.configure(config)\n            self._camera.start()\n            logger.info(\"Camera initialized: %dx%d @ %dfps\", self.width, self.height, self.fps)\n            return True\n        except RuntimeError as err:\n            logger.error(\"Camera init runtime error: %s\", err)\n            return False\n        except OSError as err:\n            logger.error(\"Camera device not found: %s\", err)\n            return False\n\n    async def capture_jpeg(self) -> Optional[bytes]:\n        \"\"\"Capture a single JPEG frame.\"\"\"\n        if MOCK_MODE:\n            return b\"\\xff\\xd8\\xff\\xe0\" + b\"\\x00\" * 100 + b\"\\xff\\xd9\"\n\n        if self._camera is None:\n            logger.warning(\"Camera not initialized, cannot capture\")\n            return None\n\n        try:\n            buffer = BytesIO()\n            await asyncio.to_thread(self._camera.capture_file, buffer, format=\"jpeg\")\n            return buffer.getvalue()\n        except RuntimeError as err:\n            logger.error(\"Camera capture error: %s\", err)\n            return None\n\n    async def stream_loop(\n        self,\n        callback: Callable[[bytes], Awaitable[None]],\n        stop_event: asyncio.Event,\n    ) -> None:\n        \"\"\"Stream JPEG frames until stop_event is set.\"\"\"\n        logger.info(\"Starting camera stream loop\")\n        try:\n            while not stop_event.is_set():\n                jpeg_data = await self.capture_jpeg()\n                if jpeg_data:\n                    await callback(jpeg_data)\n                await asyncio.sleep(1.0 \u002F self.fps)\n        finally:\n            logger.info(\"Camera stream loop stopped\")\n\n    async def cleanup(self) -> None:\n        \"\"\"Release camera resources.\"\"\"\n        if self._camera is not None:\n            try:\n                self._camera.stop()\n                self._camera.close()\n            except RuntimeError as err:\n                logger.warning(\"Error closing camera: %s\", err)\n            finally:\n                self._camera = None\n        logger.info(\"Camera resources released\")\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"systemd-service\">\n**Scenario**: Systemd service template (parameterized, 12-factor compliant)\n\n```ini\n# \u002Fetc\u002Fsystemd\u002Fsystem\u002F\u003Cdevice>@.service\n[Unit]\nDescription=Edge Control Box Service\nAfter=network.target\n\n[Service]\nType=simple\nUser=%i\nWorkingDirectory=%h\u002F\u003Cdevice>\nExecStart=%h\u002F\u003Cdevice>\u002Fvenv\u002Fbin\u002Fpython src\u002Fsend_data.py\nRestart=always\nRestartSec=10\nEnvironment=\"PYTHONUNBUFFERED=1\"\nEnvironment=\"LOG_LEVEL=INFO\"\nEnvironment=\"MOCK_MODE=${MOCK_MODE:-false}\"\n\n[Install]\nWantedBy=multi-user.target\n```\n\nUsage: `sudo systemctl enable \u003Cdevice>@ubuntu` (where `ubuntu` is the deploy user).\n\nTo override `MOCK_MODE` for a specific device, create a drop-in:\n```bash\nsudo systemctl edit \u003Cdevice>@ubuntu\n# Add: [Service]\n# Add: Environment=\"MOCK_MODE=true\"\n```\n\u003C\u002Fexample>\n\n# Failure modes\n\n| Mode | Symptom | Detection | Fix |\n|------|---------|-----------|-----|\n| UART permission denied | `PermissionError` on `\u002Fdev\u002FttyAMA0` | Exception caught in `connect()` | Add user to `dialout` group (`sudo usermod -a -G dialout $USER`), then log out and back in |\n| Camera not detected | `RuntimeError` during `Picamera2()` init | Exception caught in `initialize()` | Verify `dtoverlay=camera_auto_detect` in `\u002Fboot\u002Ffirmware\u002Fconfig.txt` and reboot; check CSI cable connection |\n| CPU thermal throttling | Performance degradation, CPU temp > 80C | `get_cpu_temperature()` returns > 80.0 | Add heatsink, reduce camera resolution, or reduce telemetry polling rate |\n| Serial port contention | `serial.SerialException` with \"device busy\" | Another process holds `\u002Fdev\u002FttyAMA0` | Check for other UART consumers (`lsof \u002Fdev\u002FttyAMA0`), stop conflicting service |\n\n# Related skills\n\n- `mavlink-integration` -- compose for MAVLink protocol handling; embedded-systems provides the UART transport layer, mavlink-integration provides message parsing and command sequences\n- `docker-build` -- defer for creating the edge service Docker image (ARM64)\n- `code-standards` -- code-standards defines Python style rules (black, isort, flake8, mypy) that apply to all edge service code\n- `api-integration` -- the edge service WebSocket server (port 8081) that the web portal connects to is documented in api-integration\n\n# How to use\n\n## What it does\n\nThis skill writes and reviews Python that talks to real hardware on a single-board edge computer — serial ports, camera capture, GPIO lines, resource monitoring, and the service unit that keeps it running. It bakes in the habits that hardware code fails without: explicit imports, specific exception types, cleanup in `finally`, loops that can be stopped, and a mock path so the module still imports on a CI box with no hardware attached.\n\n## When to use it\n\n- You are writing or reviewing Python that opens a serial port, drives GPIO pins, or captures frames from a CSI camera.\n- You need a service unit file for the edge service, parameterized by user and home directory rather than hardcoded paths.\n- A hardware call is failing — the port is busy, the camera never initializes, the process holds a device after exit.\n- You are adding CPU temperature, memory, or throttling checks to a device agent.\n\n## When not to use it\n\n- Parsing MAVLink messages, choosing dialects, or sequencing commands — use `mavlink-integration`; this skill only supplies the transport underneath it.\n- Server-side TypeScript for a web portal — use `api-integration` or `code-standards`.\n- Building the container image for the edge service — use `docker-build`.\n- Auditing Python dependencies — use `deps-check`.\n\n## How to invoke\n\n```\nSkill(skill: \"uav-pack:embedded-systems\")\n```\n\nInvoke it before you write the code, not after. Tell it which subsystem you are on — `uart`, `camera`, `gpio`, `systemd`, or `monitoring` — and whether the result must run without hardware.\n\n## Inputs\n\n- `component` — which subsystem: `uart`, `camera`, `gpio`, `systemd`, or `monitoring` — required.\n- `mock_mode` — whether the generated code must run with no hardware attached, for CI — optional, defaults to supporting it.\n\n## What you get back\n\nTyped Python with a module-level logger, a runtime `MOCK_MODE` check, specific `except` clauses, and every acquired resource released in a `finally` block. Classes stay under 120 lines, standalone functions under 40, service unit files under 25. Before any edit to an existing file you get a before\u002Fafter diff and a note on which hardware subsystem it touches.\n\n## Worked example\n\n```\nSkill(skill: \"uav-pack:embedded-systems\")\n\"Add a camera streamer to the edge service that pushes JPEG frames to a callback.\"\n```\n\nYou get an async class with `initialize`, `capture_jpeg`, a `stream_loop` that runs `while not stop_event.is_set()`, and a `cleanup` that stops and closes the device. Blocking capture is wrapped in `asyncio.to_thread`. With `MOCK_MODE=true` the module imports and returns a stub JPEG, so the test suite passes on a machine with no camera.\n\n## Related\n\n- `mavlink-integration` — compose with it when the bytes on the wire are MAVLink frames rather than raw serial.\n- `code-standards` — the underlying style rules (formatting, import order, lint, type checking) for all Python here.\n- `api-integration` — for the socket server the portal connects to, rather than the device-side driver.\n","# Purpose\n\nProduce and review Python code for Raspberry Pi 5 edge devices running the edge service. Covers UART serial communication, picamera2 camera streaming, GPIO control, resource monitoring, and systemd service configuration. All generated code passes `mypy`, handles `MOCK_MODE` for CI, and releases hardware resources on exit. For MAVLink protocol parsing (message IDs, dialects, command sequences), compose with `mavlink-integration`.\n\nSuccess criteria: generated code imports without hardware attached (`MOCK_MODE=true`), passes `mypy` with zero errors, and releases every acquired resource in a `finally` block.\n\n# When to use\n\n- Writing or reviewing Python code that interfaces with RPi5 hardware (UART, GPIO, camera)\n- Configuring systemd services for the edge service on edge devices\n- Debugging hardware communication issues (serial port, camera initialization)\n- Implementing resource monitoring (CPU temperature, memory, throttling) on edge devices\n\n# When NOT to use\n\n- Web portal server-side TypeScript code (use `api-integration` or `code-standards`)\n- Infrastructure or Helm chart work (use the project's deployment workflow)\n- MAVLink message parsing, dialect selection, or command sequencing (use `mavlink-integration`)\n- Docker image building for the edge service (use `docker-build`)\n- Python dependency auditing (use `deps-check`)\n- Any Python code in the edge service that is purely MAVLink protocol without hardware driver concerns (use `mavlink-integration`)\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fembedded-systems\u002FSKILL.md`\n- Tools\u002Flibraries: Python 3.11+, `serial_asyncio`, `picamera2`, `psutil`, `asyncio`\n- Hardware: Raspberry Pi 5 (or `MOCK_MODE=true` for CI\u002Fdev without hardware)\n- Code standards: `mypy` for type checking, `black` (line length 100), `isort`, `flake8` (max complexity 10)\n\n# Inputs\n\n- `component: \"uart\" | \"camera\" | \"gpio\" | \"systemd\" | \"monitoring\"` -- which hardware subsystem to work with\n- `mock_mode: boolean` -- if true, generate code that works without physical hardware (for CI testing)\n\n# Outputs\n\n- Format: Python code with type hints, specific exception handling, and `MOCK_MODE` support. All code passes `mypy` without errors.\n- Length budget: max 120 lines per class; max 40 lines per standalone function; systemd unit files under 25 lines.\n\n# Procedure\n\n1. **Check mock mode** -- Determine if the code should support running without hardware. If `MOCK_MODE` is set in the environment, all hardware interfaces return simulated data.\n\n   ```python\n   import os\n   MOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n   ```\n\n   **Checkpoint:** `MOCK_MODE` check is present at module level. The check reads from the environment at runtime, never hardcoded to a literal `\"false\"`.\n\n2. **Import required modules** -- Always include explicit imports. Never assume modules are available in scope. If using `serial.EIGHTBITS` or `serial.SerialException`, you must `import serial` separately -- `serial_asyncio` does not bring `serial` constants into scope.\n\n   ```python\n   import asyncio\n   import logging\n   import serial          # required for serial.EIGHTBITS, serial.SerialException\n   import serial_asyncio\n   from typing import Optional\n\n   logger = logging.getLogger(__name__)\n   ```\n\n   **Checkpoint:** `logger` and all type imports are explicitly defined. `import serial` is present if any `serial.*` constant or exception is referenced.\n\n3. **Implement with specific exceptions** -- Use specific exception types, not bare `except Exception`. Hardware code handles known failure modes:\n\n   - UART: `serial.SerialException`, `OSError`, `asyncio.TimeoutError`\n   - Camera: `RuntimeError` (picamera2 init failure), `OSError` (device not found)\n   - GPIO: `PermissionError`, `FileNotFoundError` (sysfs access)\n\n   **Checkpoint:** Every `except` block catches a specific exception type.\n\n4. **Add cleanup in `finally` blocks** -- Hardware resources (serial ports, camera) are released on exit.\n\n   **Checkpoint:** Every `connect`\u002F`initialize` has a corresponding `close`\u002F`cleanup` in a `finally` block.\n\n5. **Add exit conditions to loops** -- Streaming loops accept a stop signal.\n\n   **Checkpoint:** Every `while` loop checks a `stop_event: asyncio.Event` or equivalent.\n\n6. **Show diff before applying Edit** -- Before applying any Edit to an existing file, show the operator a before\u002Fafter diff of the code change and confirm the target hardware component.\n\n   **Checkpoint:** Diff shown; operator has context on which hardware subsystem is affected.\n\n7. **Test with MOCK_MODE** -- Verify the code runs in CI without hardware by setting `MOCK_MODE=true`.\n\n   **Checkpoint:** `mypy` passes, and the module can be imported without hardware attached.\n\n# Self-check\n\n\u003Cself-check>\n- [ ] All Python code has type hints on parameters and return types\n- [ ] `logger` is explicitly created via `logging.getLogger(__name__)`, not used as an undefined name\n- [ ] `serial` module is imported before referencing `serial.EIGHTBITS`, `serial.SerialException`, etc. -- `serial_asyncio` does NOT bring these into scope\n- [ ] Every `except` block catches a specific exception, not bare `Exception`\n- [ ] Every streaming loop has an exit condition (e.g., `stop_event.is_set()`)\n- [ ] Hardware resources are released in `finally` blocks\n- [ ] `MOCK_MODE` support is present for CI compatibility -- the check reads `os.environ`, never hardcoded\n- [ ] No hardcoded paths like `\u002Fhome\u002Fpi\u002F` -- use environment variables or systemd specifiers\n- [ ] `mypy` would pass on the generated code\n- [ ] Systemd service templates use `MOCK_MODE=${MOCK_MODE:-false}`, not a hardcoded literal\n- [ ] Before\u002Fafter diff was shown for every Edit applied to existing files\n\u003C\u002Fself-check>\n\n# Common mistakes\n\n- DO NOT use bare `except Exception` -- always catch specific exceptions (`serial.SerialException`, `OSError`, `RuntimeError`)\n- DO NOT reference `logger` without defining it -- always add `logger = logging.getLogger(__name__)` at module level\n- DO NOT reference `serial.EIGHTBITS` without `import serial` -- the `serial_asyncio` import does not bring `serial` constants into scope\n- DO NOT write infinite loops without exit conditions -- always use `while not stop_event.is_set()` or a cancellation token\n- DO NOT hardcode `\u002Fhome\u002Fpi\u002F` in systemd service files -- use `%h` (home directory specifier) or environment variables; the deploy user may be `ubuntu` (as on the staging environment)\n- DO NOT use `raspi-config` menu instructions for camera enable -- on Raspberry Pi OS Bookworm (2024+), use `dtoverlay=camera_auto_detect` in `\u002Fboot\u002Ffirmware\u002Fconfig.txt`\n- DO NOT call `self.camera.capture_file()` without checking `self.camera is not None` first\n- DO NOT open UART without a corresponding `finally` block to release the port\n- DO NOT hardcode `MOCK_MODE=false` in systemd service templates -- use `MOCK_MODE=${MOCK_MODE:-false}` so environment-specific overrides work via drop-in files\n\n# Escalation\n\n- Stop and ask when: The target RPi model is not RPi5 (GPIO pinout and UART assignments differ)\n- Stop and ask when: Multiple services need the same UART port (serial port contention)\n- Stop and ask when: Camera resolution exceeds 1920x1080 at 30fps (may exceed RPi5 ISP throughput)\n- Stop and ask when: The code must interact with MAVLink messages (hand off to `mavlink-integration`)\n\n# What to surface\n\n- Whether `MOCK_MODE` is being used (affects test validity)\n- Hardware-specific side effects: UART monopolizes the serial port, camera locks the CSI interface\n- The systemd service user and working directory (must match the target device)\n- Any `asyncio.to_thread()` calls wrapping blocking I\u002FO (pymavlink, picamera2 capture)\n\n# Examples\n\n\u003Cexample name=\"uart-reader\">\n**Scenario**: Implement a UART reader for serial communication on the edge service\n\n```python\nimport asyncio\nimport logging\nimport os\nimport serial\nimport serial_asyncio\nfrom typing import Optional\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass UARTReader:\n    \"\"\"Async UART reader for serial communication with flight controller.\"\"\"\n\n    def __init__(self, port: str = \"\u002Fdev\u002FttyAMA0\", baudrate: int = 57600) -> None:\n        self.port = port\n        self.baudrate = baudrate\n        self.reader: Optional[asyncio.StreamReader] = None\n        self.writer: Optional[asyncio.StreamWriter] = None\n\n    async def connect(self) -> bool:\n        \"\"\"Establish UART connection. Returns True on success.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE: Simulating UART connection on %s\", self.port)\n            return True\n\n        try:\n            self.reader, self.writer = await serial_asyncio.open_serial_connection(\n                url=self.port,\n                baudrate=self.baudrate,\n                bytesize=serial.EIGHTBITS,\n                parity=serial.PARITY_NONE,\n                stopbits=serial.STOPBITS_ONE,\n            )\n            logger.info(\"Connected to UART: %s\", self.port)\n            return True\n        except serial.SerialException as err:\n            logger.error(\"UART serial error on %s: %s\", self.port, err)\n            return False\n        except OSError as err:\n            logger.error(\"UART OS error on %s: %s\", self.port, err)\n            return False\n\n    async def read_bytes(self, size: int, timeout: float = 1.0) -> Optional[bytes]:\n        \"\"\"Read bytes from UART with timeout.\"\"\"\n        if MOCK_MODE:\n            return b\"\\x00\" * size\n\n        if self.reader is None:\n            return None\n\n        try:\n            data = await asyncio.wait_for(self.reader.read(size), timeout=timeout)\n            return data\n        except asyncio.TimeoutError:\n            logger.debug(\"UART read timeout after %.1fs\", timeout)\n            return None\n        except serial.SerialException as err:\n            logger.error(\"UART read serial error: %s\", err)\n            return None\n        except OSError as err:\n            logger.error(\"UART read OS error: %s\", err)\n            return None\n\n    async def close(self) -> None:\n        \"\"\"Release UART resources.\"\"\"\n        if self.writer is not None:\n            try:\n                self.writer.close()\n                await self.writer.wait_closed()\n            except OSError as err:\n                logger.warning(\"Error closing UART writer: %s\", err)\n            finally:\n                self.writer = None\n                self.reader = None\n        logger.info(\"UART connection closed on %s\", self.port)\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"camera-streamer\">\n**Scenario**: Camera streaming with exit condition and cleanup\n\n```python\nimport asyncio\nimport logging\nimport os\nfrom io import BytesIO\nfrom typing import Awaitable, Callable, Optional\n\nlogger = logging.getLogger(__name__)\n\nMOCK_MODE = os.environ.get(\"MOCK_MODE\", \"false\").lower() == \"true\"\n\n\nclass CameraStreamer:\n    \"\"\"Async camera streamer using picamera2.\"\"\"\n\n    def __init__(self, width: int = 640, height: int = 480, fps: int = 30) -> None:\n        self.width = width\n        self.height = height\n        self.fps = fps\n        self._camera: Optional[object] = None  # Picamera2 instance\n\n    async def initialize(self) -> bool:\n        \"\"\"Initialize camera. Returns True on success.\"\"\"\n        if MOCK_MODE:\n            logger.info(\"MOCK_MODE: Simulating camera initialization\")\n            return True\n\n        try:\n            from picamera2 import Picamera2\n\n            self._camera = Picamera2()\n            config = self._camera.create_still_configuration(\n                main={\"size\": (self.width, self.height)}\n            )\n            self._camera.configure(config)\n            self._camera.start()\n            logger.info(\"Camera initialized: %dx%d @ %dfps\", self.width, self.height, self.fps)\n            return True\n        except RuntimeError as err:\n            logger.error(\"Camera init runtime error: %s\", err)\n            return False\n        except OSError as err:\n            logger.error(\"Camera device not found: %s\", err)\n            return False\n\n    async def capture_jpeg(self) -> Optional[bytes]:\n        \"\"\"Capture a single JPEG frame.\"\"\"\n        if MOCK_MODE:\n            return b\"\\xff\\xd8\\xff\\xe0\" + b\"\\x00\" * 100 + b\"\\xff\\xd9\"\n\n        if self._camera is None:\n            logger.warning(\"Camera not initialized, cannot capture\")\n            return None\n\n        try:\n            buffer = BytesIO()\n            await asyncio.to_thread(self._camera.capture_file, buffer, format=\"jpeg\")\n            return buffer.getvalue()\n        except RuntimeError as err:\n            logger.error(\"Camera capture error: %s\", err)\n            return None\n\n    async def stream_loop(\n        self,\n        callback: Callable[[bytes], Awaitable[None]],\n        stop_event: asyncio.Event,\n    ) -> None:\n        \"\"\"Stream JPEG frames until stop_event is set.\"\"\"\n        logger.info(\"Starting camera stream loop\")\n        try:\n            while not stop_event.is_set():\n                jpeg_data = await self.capture_jpeg()\n                if jpeg_data:\n                    await callback(jpeg_data)\n                await asyncio.sleep(1.0 \u002F self.fps)\n        finally:\n            logger.info(\"Camera stream loop stopped\")\n\n    async def cleanup(self) -> None:\n        \"\"\"Release camera resources.\"\"\"\n        if self._camera is not None:\n            try:\n                self._camera.stop()\n                self._camera.close()\n            except RuntimeError as err:\n                logger.warning(\"Error closing camera: %s\", err)\n            finally:\n                self._camera = None\n        logger.info(\"Camera resources released\")\n```\n\u003C\u002Fexample>\n\n\u003Cexample name=\"systemd-service\">\n**Scenario**: Systemd service template (parameterized, 12-factor compliant)\n\n```ini\n# \u002Fetc\u002Fsystemd\u002Fsystem\u002F\u003Cdevice>@.service\n[Unit]\nDescription=Edge Control Box Service\nAfter=network.target\n\n[Service]\nType=simple\nUser=%i\nWorkingDirectory=%h\u002F\u003Cdevice>\nExecStart=%h\u002F\u003Cdevice>\u002Fvenv\u002Fbin\u002Fpython src\u002Fsend_data.py\nRestart=always\nRestartSec=10\nEnvironment=\"PYTHONUNBUFFERED=1\"\nEnvironment=\"LOG_LEVEL=INFO\"\nEnvironment=\"MOCK_MODE=${MOCK_MODE:-false}\"\n\n[Install]\nWantedBy=multi-user.target\n```\n\nUsage: `sudo systemctl enable \u003Cdevice>@ubuntu` (where `ubuntu` is the deploy user).\n\nTo override `MOCK_MODE` for a specific device, create a drop-in:\n```bash\nsudo systemctl edit \u003Cdevice>@ubuntu\n# Add: [Service]\n# Add: Environment=\"MOCK_MODE=true\"\n```\n\u003C\u002Fexample>\n\n# Failure modes\n\n| Mode | Symptom | Detection | Fix |\n|------|---------|-----------|-----|\n| UART permission denied | `PermissionError` on `\u002Fdev\u002FttyAMA0` | Exception caught in `connect()` | Add user to `dialout` group (`sudo usermod -a -G dialout $USER`), then log out and back in |\n| Camera not detected | `RuntimeError` during `Picamera2()` init | Exception caught in `initialize()` | Verify `dtoverlay=camera_auto_detect` in `\u002Fboot\u002Ffirmware\u002Fconfig.txt` and reboot; check CSI cable connection |\n| CPU thermal throttling | Performance degradation, CPU temp > 80C | `get_cpu_temperature()` returns > 80.0 | Add heatsink, reduce camera resolution, or reduce telemetry polling rate |\n| Serial port contention | `serial.SerialException` with \"device busy\" | Another process holds `\u002Fdev\u002FttyAMA0` | Check for other UART consumers (`lsof \u002Fdev\u002FttyAMA0`), stop conflicting service |\n\n# Related skills\n\n- `mavlink-integration` -- compose for MAVLink protocol handling; embedded-systems provides the UART transport layer, mavlink-integration provides message parsing and command sequences\n- `docker-build` -- defer for creating the edge service Docker image (ARM64)\n- `code-standards` -- code-standards defines Python style rules (black, isort, flake8, mypy) that apply to all edge service code\n- `api-integration` -- the edge service WebSocket server (port 8081) that the web portal connects to is documented in api-integration\n\n# How to use\n\n## What it does\n\nThis skill writes and reviews Python that talks to real hardware on a single-board edge computer — serial ports, camera capture, GPIO lines, resource monitoring, and the service unit that keeps it running. It bakes in the habits that hardware code fails without: explicit imports, specific exception types, cleanup in `finally`, loops that can be stopped, and a mock path so the module still imports on a CI box with no hardware attached.\n\n## When to use it\n\n- You are writing or reviewing Python that opens a serial port, drives GPIO pins, or captures frames from a CSI camera.\n- You need a service unit file for the edge service, parameterized by user and home directory rather than hardcoded paths.\n- A hardware call is failing — the port is busy, the camera never initializes, the process holds a device after exit.\n- You are adding CPU temperature, memory, or throttling checks to a device agent.\n\n## When not to use it\n\n- Parsing MAVLink messages, choosing dialects, or sequencing commands — use `mavlink-integration`; this skill only supplies the transport underneath it.\n- Server-side TypeScript for a web portal — use `api-integration` or `code-standards`.\n- Building the container image for the edge service — use `docker-build`.\n- Auditing Python dependencies — use `deps-check`.\n\n## How to invoke\n\n```\nSkill(skill: \"uav-pack:embedded-systems\")\n```\n\nInvoke it before you write the code, not after. Tell it which subsystem you are on — `uart`, `camera`, `gpio`, `systemd`, or `monitoring` — and whether the result must run without hardware.\n\n## Inputs\n\n- `component` — which subsystem: `uart`, `camera`, `gpio`, `systemd`, or `monitoring` — required.\n- `mock_mode` — whether the generated code must run with no hardware attached, for CI — optional, defaults to supporting it.\n\n## What you get back\n\nTyped Python with a module-level logger, a runtime `MOCK_MODE` check, specific `except` clauses, and every acquired resource released in a `finally` block. Classes stay under 120 lines, standalone functions under 40, service unit files under 25. Before any edit to an existing file you get a before\u002Fafter diff and a note on which hardware subsystem it touches.\n\n## Worked example\n\n```\nSkill(skill: \"uav-pack:embedded-systems\")\n\"Add a camera streamer to the edge service that pushes JPEG frames to a callback.\"\n```\n\nYou get an async class with `initialize`, `capture_jpeg`, a `stream_loop` that runs `while not stop_event.is_set()`, and a `cleanup` that stops and closes the device. Blocking capture is wrapped in `asyncio.to_thread`. With `MOCK_MODE=true` the module imports and returns a stub JPEG, so the test suite passes on a machine with no camera.\n\n## Related\n\n- `mavlink-integration` — compose with it when the bytes on the wire are MAVLink frames rather than raw serial.\n- `code-standards` — the underlying style rules (formatting, import order, lint, type checking) for all Python here.\n- `api-integration` — for the socket server the portal connects to, rather than the device-side driver.\n",{"docs":24,"name":5,"owner":28,"version":29,"description":7,"allowed-tools":30},{"status":25,"updated":26,"source_sha":27},"reviewed",1785974400000,"36398d0f597c","swarmery-core","1.0.0","Read, Edit, Bash, Grep, Glob","main","2d9e918cc79c9b17b59356780ff0a3da38a3e98a","plugins\u002Fuav-pack\u002Fskills\u002Fembedded-systems",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 embedded-systems",{"tool":45,"command":46},"bunx","bunx skills add atretyak1985\u002Fswarmery --skill embedded-systems",{"tool":48,"command":49},"pnpm","pnpm dlx skills add atretyak1985\u002Fswarmery --skill embedded-systems","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Fplugins\u002Fuav-pack\u002Fskills\u002Fembedded-systems\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",[],[]]