No description
  • Rust 96.8%
  • Shell 3%
  • GDB 0.1%
Find a file
faicel 305fc7bfad
Some checks failed
Create tag on dev / checks-1 (push) Failing after 10s
Create tag on dev / checks (push) Failing after 0s
Create tag on dev / tag (push) Has been skipped
Merge pull request 'fix/audit-battery-feature' (#11) from fix/audit-battery-feature into dev
Reviewed-on: #11
2026-09-23 20:52:01 +00:00
.cargo fix flash and debug 2026-07-03 21:52:09 +02:00
.claude Update Cargo.toml for version bump to 0.2.1-rc.1, adjust dependencies to use local paths, and enhance .vscode/launch.json for improved workspace compatibility. Modify lora message handler to streamline key management and update install task for ECDH handshake implementation. 2026-03-26 06:58:13 +01:00
.forgejo fix(ci): enforce locked dependency resolution in cargo steps 2026-09-22 19:17:54 +02:00
.vscode fix audit 2026-09-03 13:34:42 +02:00
docs fix(battery): document permanent divider drain in acceptance checklist 2026-09-22 15:34:52 +02:00
scripts fix audit 2026-09-03 13:34:42 +02:00
src update INTERVAL_SECS 2026-09-23 21:01:45 +02:00
tests fix(tests): pin battery Reading size in memory budget suite 2026-09-22 19:47:48 +02:00
.DS_Store Update Cargo.toml for version bump to 0.2.1-rc.1, adjust dependencies to use local paths, and enhance .vscode/launch.json for improved workspace compatibility. Modify lora message handler to streamline key management and update install task for ECDH handshake implementation. 2026-03-26 06:58:13 +01:00
.gitignore Add battery telemetry feature 2026-09-22 14:10:25 +02:00
build.rs fix flash and debug 2026-07-03 21:52:09 +02:00
Cargo.lock update packages 2026-09-21 13:39:19 +02:00
Cargo.toml fix(supply-chain): clarify dependency-pin comments in Cargo.toml 2026-09-22 19:35:31 +02:00
CHANGELOG.md fix(tests): pin battery Reading size in memory budget suite 2026-09-22 19:47:48 +02:00
CLAUDE.md Synchronize docs and comments with battery telemetry 2026-09-22 14:47:35 +02:00
coverage.sh test: tighten execution-proof prefixes and refresh coverage scope 2026-08-24 10:52:39 +02:00
deploy.sh fix flash and debug 2026-07-03 21:52:09 +02:00
deploy_direct.sh fix flash and debug 2026-07-03 21:52:09 +02:00
deploy_tmp.sh fix flash and debug 2026-07-03 21:52:09 +02:00
deploy_tmp_direct.sh fix flash and debug 2026-07-03 21:52:09 +02:00
firmware_deep_sleep.bin fix flash and debug 2026-07-03 21:52:09 +02:00
LICENSE init 2026-03-11 22:58:21 +01:00
memory_bootloader.x fix flash and debug 2026-07-03 21:52:09 +02:00
memory_direct.x fix flash and debug 2026-07-03 21:52:09 +02:00
openocd.cfg init 2026-03-11 22:58:21 +01:00
openocd.gdb fix audit 2026-09-03 13:34:42 +02:00
README.md Add battery telemetry feature 2026-09-22 14:10:25 +02:00
samd21.cfg fix flash and debug 2026-07-03 21:52:09 +02:00
test.sh fix(test): use private temp file and locked deps in test script 2026-09-22 19:28:45 +02:00

SAMD21 RTIC Security Sensor

Important

The canonical repository for this project lives on Forgejo: https://code.bhk-itsolutions.com/homeiot/samd21. This GitHub repository is only a mirror and is not the primary git remote.

Embedded security sensor firmware for SAMD21 microcontroller using RTIC framework.

Overview

This firmware implements a security sensor system that monitors door state and vibration, communicates via LoRa (SX1278) with encrypted messages, and includes watchdog protection and key management.

Features

  • ✅ Door sensor monitoring: Real-time door state detection via GPIO interrupt
  • ✅ Vibration detection: Tamper detection using SW420 vibration sensor
  • ✅ LoRa communication: Long-range wireless communication via SX1278
  • ✅ Encrypted communication: ChaCha20Poly1305 encryption using Sigil protocol
  • ✅ Hardware RNG: ATECC608x for Sigil handshake and encrypted event nonces
  • ✅ Watchdog protection: 16-second watchdog timer with automatic reset detection
  • ✅ Retry logic: Automatic retry for LoRa operations with 500ms delay
  • ✅ Error handling: Comprehensive error handling with LED signaling

Hardware Requirements

  • MCU: SAMD21G18A
  • LoRa Module: SX1278
  • Sensors:
    • Door sensor (magnetic switch) on PA06
    • Vibration sensor (SW420) on PA09
  • Indicators:
    • Status LED on PA21
    • Buzzer on PA19 (GPIO, active buzzer)
    • Error LED on PA14
    • Init LED on PA18

Pin Configuration

Function Pin Description
LoRa SPI SCK PB11 SPI clock
LoRa SPI MOSI PB10 SPI data out
LoRa SPI MISO PA12 SPI data in
LoRa NSS PA15 SPI chip select
LoRa RST PA20 Reset pin
LoRa DIO0 PA07 Interrupt pin (EIC Ch7)
Door Sensor PA06 Door state (EIC Ch6)
Vibration PA09 Vibration detection (EIC Ch9)
Battery ADC PA02 1 MΩ / 1 MΩ divider, AIN0
Battery load PA17 Active-high 68 Ω test load
Status LED PA21 Alarm indicator
Buzzer PA19 Active buzzer (GPIO on/off)
Error LED PA14 Error indicator
Init LED PA18 Initialization indicator

Architecture

Battery acquisition, the LoRa payload, calibration limits and deployment order are documented in Battery telemetry.

Main Tasks

Task Priority Description
on_eic 4 External interrupt handler (LoRa DIO0, door, vibration)
watchdog_feed 2 Periodic watchdog feeding (every 4s)
process_lora_message 1 LoRa message processing (async)
send_sensor_event 1 Door state change event transmission (async)
install 1 Installation message sending (every 10s until validated)
idle - Main loop with WFI for power saving

Module Structure

src/
├── main.rs              # Main application and RTIC tasks
├── (moved)              # Business-logic config/state live in `contact_sensor`
├── device_id/           # Device UID reading (safe wrapper)
│   └── mod.rs
├── helpers/             # Helper modules
│   ├── alarm/           # Alarm control (LED/buzzer)
│   ├── lora/            # LoRa message handling
│   └── timeout/         # Timeout management utilities
├── tasks/               # RTIC tasks
│   └── install/         # Installation message sending
└── types/               # Type definitions
    └── mod.rs

Communication Protocol

The system uses the Sigil protocol for encrypted LoRa communication:

  • Install messages: Broadcast to all gateways using derived install key
  • Validate requests: Uses DEFAULT_KEY for initial validation
  • Event messages: Uses validated session key or derived session key
  • Encryption: ChaCha20Poly1305 with 12-byte nonces

Note: the firmware no longer depends on hkdf/sha2 directly; ECIES (HKDF-SHA256 + ChaCha20Poly1305) for the Sigil install handshake is handled inside the sigil crate.

Message Flow

  1. Installation:

    • Sensor sends InstallSensorRequest every 10 seconds for 5 minutes
    • Continues until gateway responds with validation
  2. Validation:

    • Gateway sends ValidateRequest using DEFAULT_KEY
    • Sensor responds with ValidateResponse containing session key
    • Session key stored in current_key with expiration
  3. Event Reporting:

    • Door state changes trigger Event messages
    • Uses validated key if available, otherwise derived session key
    • Automatic retry on failure (1 retry, 500ms delay)

Security

Key Management

  • Master Key: Stored in src/config/mod.rs (⚠️ hardcoded for development)
  • Session Keys: Derived per-communication for enhanced security
  • Install Keys: Derived without device_id for gateway compatibility

⚠️ Production Security Notes

  • Master key should be loaded from Secure Element (Atecc608x) in production
  • Never commit master keys to version control
  • Use environment variables or secure storage for keys
  • Implement key expiration verification (structure in place, logic pending)

Watchdog Timer

  • Timeout: 16 seconds
  • Feed interval: Every 4 seconds (4× safety margin)
  • Clock: GCLK4 at 1024 Hz (separate from RTC)
  • Reset detection: Reads RCAUSE register, lights error LED if watchdog reset

Building and Flashing

Prerequisites

  • Rust toolchain (stable or beta)
  • thumbv6m-none-eabi target: rustup target add thumbv6m-none-eabi
  • OpenOCD or J-Link for flashing

Build

# Development build
cargo build --target thumbv6m-none-eabi

# Release build
cargo build --release --target thumbv6m-none-eabi

Flash

./deploy.sh                    # firmware @ 0x2000 (bootloader slot, default)
./deploy.sh false              # firmware @ 0x0 (bare-metal)
./deploy_direct.sh             # shortcut for ./deploy.sh false
./deploy_tmp.sh [true|false]   # deep_sleep bench

Manual (with bootloader slot):

cargo objcopy --release --bin samd21 --target thumbv6m-none-eabi -- -O binary firmware.bin
openocd -f samd21.cfg -c "init; reset halt; program firmware.bin 0x2000 verify reset; reset run; exit"

Debug (VS Code / Cursor)

  1. Install extensions: rust-analyzer, Cortex-Debug (see .vscode/extensions.json).
  2. Connect J-Link (SWD), close any running OpenOCD session.
  3. Select Debug (OpenOCD) and press F5.

See .vscode/README.md for troubleshooting (missing SVD, OpenOCD on macOS, J-Link fallback).

Testing

See docs/TESTING_WITH_EMBEDDED_HAL_MOCK.md for testing strategy.

Unit Tests

cargo test --target thumbv6m-none-eabi

Validation Script

./scripts/run_tests.sh

Documentation

  • Code Review: see docs/history/revue.md (archived historical review)
  • Interrupt Optimizations: see docs/history/OPTIMISATIONS_INTERRUPTIONS.md (archived)
  • Testing Strategy: See docs/TESTING_WITH_EMBEDDED_HAL_MOCK.md
  • Pragmatic Testing: See docs/TESTS_PRAGMATIC_APPROACH.md

Dependencies

  • atsamd-hal: SAMD21 hardware abstraction layer
  • rtic: Real-Time Interrupt-driven Concurrency framework
  • embedded-hal: Hardware abstraction traits
  • sigil: Communication protocol library (local)
  • lora: LoRa SX1278 driver (local)
  • tools: Utility library (local, encryption, random, MAC)

License

[Add your license here]

Contributing

[Add contribution guidelines here]