merge: resolve README conflict (26 ADRs includes ADR-025 + ADR-026)

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
ruv
2026-03-01 11:02:18 -05:00
14 changed files with 1578 additions and 263 deletions

3
.gitignore vendored
View File

@@ -193,6 +193,9 @@ cython_debug/
# PyPI configuration file # PyPI configuration file
.pypirc .pypirc
# Compiled Swift helper binaries (macOS WiFi sensing)
v1/src/sensing/mac_wifi
# Cursor # Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data

View File

@@ -5,68 +5,238 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- **Cross-platform RSSI adapters** — macOS CoreWLAN (`MacosCoreWlanScanner`) and Linux `iw` (`LinuxIwScanner`) Rust adapters with `#[cfg(target_os)]` gating
- macOS CoreWLAN Python sensing adapter with Swift helper (`mac_wifi.swift`)
- macOS synthetic BSSID generation (FNV-1a hash) for Sonoma 14.4+ BSSID redaction
- Linux `iw dev <iface> scan` parser with freq-to-channel conversion and `scan dump` (no-root) mode
- ADR-025: macOS CoreWLAN WiFi Sensing (ORCA)
### Fixed
- Removed synthetic byte counters from Python `MacosWifiCollector` — now reports `tx_bytes=0, rx_bytes=0` instead of fake incrementing values
---
## [3.0.0] - 2026-03-01
Major release: AETHER contrastive embedding model, Docker Hub images, and comprehensive UI overhaul.
### Added — AETHER Contrastive Embedding Model (ADR-024)
- **Project AETHER** — self-supervised contrastive learning for WiFi CSI fingerprinting, similarity search, and anomaly detection (`9bbe956`)
- `embedding.rs` module: `ProjectionHead`, `InfoNceLoss`, `CsiAugmenter`, `FingerprintIndex`, `PoseEncoder`, `EmbeddingExtractor` (909 lines, zero external ML dependencies)
- SimCLR-style pretraining with 5 physically-motivated augmentations (temporal jitter, subcarrier masking, Gaussian noise, phase rotation, amplitude scaling)
- CLI flags: `--pretrain`, `--pretrain-epochs`, `--embed`, `--build-index <type>`
- Four HNSW-compatible fingerprint index types: `env_fingerprint`, `activity_pattern`, `temporal_baseline`, `person_track`
- Cross-modal `PoseEncoder` for WiFi-to-camera embedding alignment
- VICReg regularization for embedding collapse prevention
- 53K total parameters (55 KB at INT8) — fits on ESP32
### Added — Docker & Deployment
- Published Docker Hub images: `ruvnet/wifi-densepose:latest` (132 MB Rust) and `ruvnet/wifi-densepose:python` (569 MB) (`add9f19`)
- Multi-stage Dockerfile for Rust sensing server with RuVector crates
- `docker-compose.yml` orchestrating both Rust and Python services
- RVF model export via `--export-rvf` and load via `--load-rvf` CLI flags
### Added — Documentation
- 33 use cases across 4 vertical tiers: Everyday, Specialized, Robotics & Industrial, Extreme (`0afd9c5`)
- "Why WiFi Wins" comparison table (WiFi vs camera vs LIDAR vs wearable vs PIR)
- Mermaid architecture diagrams: end-to-end pipeline, signal processing detail, deployment topology (`50f0fc9`)
- Models & Training section with RuVector crate links (GitHub + crates.io), SONA component table (`965a1cc`)
- RVF container section with deployment targets table (ESP32 0.7 MB to server 50+ MB)
- Collapsible README sections for improved navigation (`478d964`, `99ec980`, `0ebd6be`)
- Installation and Quick Start moved above Table of Contents (`50acbf7`)
- CSI hardware requirement notice (`528b394`)
### Fixed
- **UI auto-detects server port from page origin** — no more hardcoded `localhost:8080`; works on any port (Docker :3000, native :8080, custom) (`3b72f35`, closes #55)
- **Docker port mismatch** — server now binds 3000/3001 inside container as documented (`44b9c30`)
- Added `/ws/sensing` WebSocket route to the HTTP server so UI only needs one port
- Fixed README API endpoint references: `/api/v1/health``/health`, `/api/v1/sensing``/api/v1/sensing/latest`
- Multi-person tracking limit corrected: configurable default 10, no hard software cap (`e2ce250`)
---
## [2.0.0] - 2026-02-28
Major release: complete Rust sensing server, full DensePose training pipeline, RuVector v2.0.4 integration, ESP32-S3 firmware, and 6 security hardening patches.
### Added — Rust Sensing Server
- **Full DensePose-compatible REST API** served by Axum (`d956c30`)
- `GET /health` — server health
- `GET /api/v1/sensing/latest` — live CSI sensing data
- `GET /api/v1/vital-signs` — breathing rate (6-30 BPM) and heartbeat (40-120 BPM)
- `GET /api/v1/pose/current` — 17 COCO keypoints derived from WiFi signal field
- `GET /api/v1/info` — server build and feature info
- `GET /api/v1/model/info` — RVF model container metadata
- `ws://host/ws/sensing` — real-time WebSocket stream
- Three data sources: `--source esp32` (UDP CSI), `--source windows` (netsh RSSI), `--source simulated` (deterministic reference)
- Auto-detection: server probes ESP32 UDP and Windows WiFi, falls back to simulated
- Three.js visualization UI with 3D body skeleton, signal heatmap, phase plot, Doppler bars, vital signs panel
- Static UI serving via `--ui-path` flag
- Throughput: 9,52011,665 frames/sec (release build)
### Added — ADR-021: Vital Sign Detection
- `VitalSignDetector` with breathing (6-30 BPM) and heartbeat (40-120 BPM) extraction from CSI fluctuations (`1192de9`)
- FFT-based spectral analysis with configurable band-pass filters
- Confidence scoring based on spectral peak prominence
- REST endpoint `/api/v1/vital-signs` with real-time JSON output
### Added — ADR-023: DensePose Training Pipeline (Phases 1-8)
- `wifi-densepose-train` crate with complete 8-phase pipeline (`fc409df`, `ec98e40`, `fce1271`)
- Phase 1: `DataPipeline` with MM-Fi and Wi-Pose dataset loaders
- Phase 2: `CsiToPoseTransformer` — 4-head cross-attention + 2-layer GCN on COCO skeleton
- Phase 3: 6-term composite loss (MSE, bone length, symmetry, joint angle, temporal, confidence)
- Phase 4: `DynamicPersonMatcher` via ruvector-mincut (O(n^1.5 log n) Hungarian assignment)
- Phase 5: `SonaAdapter` — MicroLoRA rank-4 with EWC++ memory preservation
- Phase 6: `SparseInference` — progressive 3-layer model loading (A: essential, B: refinement, C: full)
- Phase 7: `RvfContainer` — single-file model packaging with segment-based binary format
- Phase 8: End-to-end training with cosine-annealing LR, early stopping, checkpoint saving
- CLI: `--train`, `--dataset`, `--epochs`, `--save-rvf`, `--load-rvf`, `--export-rvf`
- Benchmark: ~11,665 fps inference, 229 tests passing
### Added — ADR-016: RuVector Training Integration (all 5 crates)
- `ruvector-mincut``DynamicPersonMatcher` in `metrics.rs` + subcarrier selection (`81ad09d`, `a7dd31c`)
- `ruvector-attn-mincut` → antenna attention in `model.rs` + noise-gated spectrogram
- `ruvector-temporal-tensor``CompressedCsiBuffer` in `dataset.rs` + compressed breathing/heartbeat
- `ruvector-solver` → sparse subcarrier interpolation (114→56) + Fresnel triangulation
- `ruvector-attention` → spatial attention in `model.rs` + attention-weighted BVP
- Vendored all 11 RuVector crates under `vendor/ruvector/` (`d803bfe`)
### Added — ADR-017: RuVector Signal & MAT Integration (7 integration points)
- `gate_spectrogram()` — attention-gated noise suppression (`18170d7`)
- `attention_weighted_bvp()` — sensitivity-weighted velocity profiles
- `mincut_subcarrier_partition()` — dynamic sensitive/insensitive subcarrier split
- `solve_fresnel_geometry()` — TX-body-RX distance estimation
- `CompressedBreathingBuffer` + `CompressedHeartbeatSpectrogram`
- `BreathingDetector` + `HeartbeatDetector` (MAT crate, real FFT + micro-Doppler)
- Feature-gated behind `cfg(feature = "ruvector")` (`ab2453e`)
### Added — ADR-018: ESP32-S3 Firmware & Live CSI Pipeline
- ESP32-S3 firmware with FreeRTOS CSI extraction (`92a5182`)
- ADR-018 binary frame format: `[0xAD, 0x18, len_hi, len_lo, payload]`
- Rust `Esp32Aggregator` receiving UDP frames on port 5005
- `bridge.rs` converting I/Q pairs to amplitude/phase vectors
- NVS provisioning for WiFi credentials
- Pre-built binary quick start documentation (`696a726`)
### Added — ADR-014: SOTA Signal Processing
- 6 algorithms, 83 tests (`fcb93cc`)
- Hampel filter (median + MAD, resistant to 50% contamination)
- Conjugate multiplication (reference-antenna ratio, cancels common-mode noise)
- Phase sanitization (unwrap + linear detrend, removes CFO/SFO)
- Fresnel zone geometry (TX-body-RX distance from first-principles physics)
- Body Velocity Profile (micro-Doppler extraction, 5.7x speedup)
- Attention-gated spectrogram (learned noise suppression)
### Added — ADR-015: Public Dataset Training Strategy
- MM-Fi and Wi-Pose dataset specifications with download links (`4babb32`, `5dc2f66`)
- Verified dataset dimensions, sampling rates, and annotation formats
- Cross-dataset evaluation protocol
### Added — WiFi-Mat Disaster Detection Module
- Multi-AP triangulation for through-wall survivor detection (`a17b630`, `6b20ff0`)
- Triage classification (breathing, heartbeat, motion)
- Domain events: `survivor_detected`, `survivor_updated`, `alert_created`
- WebSocket broadcast at `/ws/mat/stream`
### Added — Infrastructure
- Guided 7-step interactive installer with 8 hardware profiles (`8583f3e`)
- Comprehensive build guide for Linux, macOS, Windows, Docker, ESP32 (`45f8a0d`)
- 12 Architecture Decision Records (ADR-001 through ADR-012) (`337dd96`)
### Added — UI & Visualization
- Sensing-only UI mode with Gaussian splat visualization (`b7e0f07`)
- Three.js 3D body model (17 joints, 16 limbs) with signal-viz components
- Tabs: Dashboard, Hardware, Live Demo, Sensing, Architecture, Performance, Applications
- WebSocket client with automatic reconnection and exponential backoff
### Added — Rust Signal Processing Crate
- Complete Rust port of WiFi-DensePose with modular workspace (`6ed69a3`)
- `wifi-densepose-signal` — CSI processing, phase sanitization, feature extraction
- `wifi-densepose-core` — shared types and configuration
- `wifi-densepose-nn` — neural network inference (DensePose head, RCNN)
- `wifi-densepose-hardware` — ESP32 aggregator, hardware interfaces
- `wifi-densepose-config` — configuration management
- Comprehensive benchmarks and validation tests (`3ccb301`)
### Added — Python Sensing Pipeline
- `WindowsWifiCollector` — RSSI collection via `netsh wlan show networks`
- `RssiFeatureExtractor` — variance, spectral bands (motion 0.5-4 Hz, breathing 0.1-0.5 Hz), change points
- `PresenceClassifier` — rule-based 3-state classification (ABSENT / PRESENT_STILL / ACTIVE)
- Cross-receiver agreement scoring for multi-AP confidence boosting
- WebSocket sensing server (`ws_server.py`) broadcasting JSON at 2 Hz
- Deterministic CSI proof bundles for reproducible verification (`v1/data/proof/`)
- Commodity sensing unit tests (`b391638`)
### Changed
- Rust hardware adapters now return explicit errors instead of silent empty data (`6e0e539`)
### Fixed
- Review fixes for end-to-end training pipeline (`45f0304`)
- Dockerfile paths updated from `src/` to `v1/src/` (`7872987`)
- IoT profile installer instructions updated for aggregator CLI (`f460097`)
- `process.env` reference removed from browser ES module (`e320bc9`)
### Performance
- 5.7x Doppler extraction speedup via optimized FFT windowing (`32c75c8`)
- Single 2.1 MB static binary, zero Python dependencies for Rust server
### Security
- Fix SQL injection in status command and migrations (`f9d125d`)
- Fix XSS vulnerabilities in UI components (`5db55fd`)
- Fix command injection in statusline.cjs (`4cb01fd`)
- Fix path traversal vulnerabilities (`896c4fc`)
- Fix insecure WebSocket connections — enforce wss:// on non-localhost (`ac094d4`)
- Fix GitHub Actions shell injection (`ab2e7b4`)
- Fix 10 additional vulnerabilities, remove 12 dead code instances (`7afdad0`)
---
## [1.1.0] - 2025-06-07 ## [1.1.0] - 2025-06-07
### Added ### Added
- Multi-column table of contents in README.md for improved navigation - Complete Python WiFi-DensePose system with CSI data extraction and router interface
- Enhanced documentation structure with better organization - CSI processing and phase sanitization modules
- Improved visual layout for better user experience - Batch processing for CSI data in `CSIProcessor` and `PhaseSanitizer`
- Hardware, pose, and stream services for WiFi-DensePose API
- Comprehensive CSS styles for UI components and dark mode support
- API and Deployment documentation
### Changed ### Fixed
- Updated README.md table of contents to use a two-column layout - Badge links for PyPI and Docker in README
- Reorganized documentation sections for better logical flow - Async engine creation poolclass specification
- Enhanced readability of navigation structure
### Documentation ---
- Restructured table of contents for better accessibility
- Improved visual hierarchy in documentation
- Enhanced user experience for documentation navigation
## [1.0.0] - 2024-12-01 ## [1.0.0] - 2024-12-01
### Added ### Added
- Initial release of WiFi DensePose - Initial release of WiFi-DensePose
- Real-time WiFi-based human pose estimation using CSI data - Real-time WiFi-based human pose estimation using Channel State Information (CSI)
- DensePose neural network integration - DensePose neural network integration for body surface mapping
- RESTful API with comprehensive endpoints - RESTful API with comprehensive endpoint coverage
- WebSocket streaming for real-time data - WebSocket streaming for real-time pose data
- Multi-person tracking capabilities - Multi-person tracking with configurable capacity (default 10, up to 50+)
- Fall detection and activity recognition - Fall detection and activity recognition
- Healthcare, fitness, smart home, and security domain configurations - Domain configurations: healthcare, fitness, smart home, security
- Comprehensive CLI interface - CLI interface for server management and configuration
- Docker and Kubernetes deployment support - Hardware abstraction layer for multiple WiFi chipsets
- 100% test coverage - Phase sanitization and signal processing pipeline
- Production-ready monitoring and logging
- Hardware abstraction layer for multiple WiFi devices
- Phase sanitization and signal processing
- Authentication and rate limiting - Authentication and rate limiting
- Background task management - Background task management
- Database integration with PostgreSQL and Redis - Cross-platform support (Linux, macOS, Windows)
- Prometheus metrics and Grafana dashboards
- Comprehensive documentation and examples
### Features
- Privacy-preserving pose detection without cameras
- Sub-50ms latency with 30 FPS processing
- Support for up to 10 simultaneous person tracking
- Enterprise-grade security and scalability
- Cross-platform compatibility (Linux, macOS, Windows)
- GPU acceleration support
- Real-time analytics and alerting
- Configurable confidence thresholds
- Zone-based occupancy monitoring
- Historical data analysis
- Performance optimization tools
- Load testing capabilities
- Infrastructure as Code (Terraform, Ansible)
- CI/CD pipeline integration
- Comprehensive error handling and logging
### Documentation ### Documentation
- Complete user guide and API reference - User guide and API reference
- Deployment and troubleshooting guides - Deployment and troubleshooting guides
- Hardware setup and calibration instructions - Hardware setup and calibration instructions
- Performance benchmarks and optimization tips - Performance benchmarks
- Contributing guidelines and code standards - Contributing guidelines
- Security best practices
- Example configurations and use cases [Unreleased]: https://github.com/ruvnet/wifi-densepose/compare/v3.0.0...HEAD
[3.0.0]: https://github.com/ruvnet/wifi-densepose/compare/v2.0.0...v3.0.0
[2.0.0]: https://github.com/ruvnet/wifi-densepose/compare/v1.1.0...v2.0.0
[1.1.0]: https://github.com/ruvnet/wifi-densepose/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/ruvnet/wifi-densepose/releases/tag/v1.0.0

View File

@@ -35,7 +35,7 @@ docker run -p 3000:3000 ruvnet/wifi-densepose:latest
> |--------|----------|------|----------|-------------| > |--------|----------|------|----------|-------------|
> | **ESP32 Mesh** (recommended) | 3-6x ESP32-S3 + WiFi router | ~$54 | Yes | Pose, breathing, heartbeat, motion, presence | > | **ESP32 Mesh** (recommended) | 3-6x ESP32-S3 + WiFi router | ~$54 | Yes | Pose, breathing, heartbeat, motion, presence |
> | **Research NIC** | Intel 5300 / Atheros AR9580 | ~$50-100 | Yes | Full CSI with 3x3 MIMO | > | **Research NIC** | Intel 5300 / Atheros AR9580 | ~$50-100 | Yes | Full CSI with 3x3 MIMO |
> | **Any WiFi** | Windows/Linux laptop | $0 | No | RSSI-only: coarse presence and motion | > | **Any WiFi** | Windows, macOS, or Linux laptop | $0 | No | RSSI-only: coarse presence and motion |
> >
> No hardware? Verify the signal processing pipeline with the deterministic reference signal: `python v1/data/proof/verify.py` > No hardware? Verify the signal processing pipeline with the deterministic reference signal: `python v1/data/proof/verify.py`
@@ -356,7 +356,7 @@ cargo add wifi-densepose-ruvector # RuVector v2.0.4 integration layer (ADR-017
| [`wifi-densepose-ruvector`](https://crates.io/crates/wifi-densepose-ruvector) | RuVector v2.0.4 integration layer — 7 signal+MAT integration points (ADR-017) | **All 5** | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-ruvector.svg)](https://crates.io/crates/wifi-densepose-ruvector) | | [`wifi-densepose-ruvector`](https://crates.io/crates/wifi-densepose-ruvector) | RuVector v2.0.4 integration layer — 7 signal+MAT integration points (ADR-017) | **All 5** | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-ruvector.svg)](https://crates.io/crates/wifi-densepose-ruvector) |
| [`wifi-densepose-vitals`](https://crates.io/crates/wifi-densepose-vitals) | Vital signs: breathing (6-30 BPM), heart rate (40-120 BPM) | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-vitals.svg)](https://crates.io/crates/wifi-densepose-vitals) | | [`wifi-densepose-vitals`](https://crates.io/crates/wifi-densepose-vitals) | Vital signs: breathing (6-30 BPM), heart rate (40-120 BPM) | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-vitals.svg)](https://crates.io/crates/wifi-densepose-vitals) |
| [`wifi-densepose-hardware`](https://crates.io/crates/wifi-densepose-hardware) | ESP32, Intel 5300, Atheros CSI sensor interfaces | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-hardware.svg)](https://crates.io/crates/wifi-densepose-hardware) | | [`wifi-densepose-hardware`](https://crates.io/crates/wifi-densepose-hardware) | ESP32, Intel 5300, Atheros CSI sensor interfaces | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-hardware.svg)](https://crates.io/crates/wifi-densepose-hardware) |
| [`wifi-densepose-wifiscan`](https://crates.io/crates/wifi-densepose-wifiscan) | Multi-BSSID WiFi scanning (Windows-enhanced) | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-wifiscan.svg)](https://crates.io/crates/wifi-densepose-wifiscan) | | [`wifi-densepose-wifiscan`](https://crates.io/crates/wifi-densepose-wifiscan) | Multi-BSSID WiFi scanning (Windows, macOS, Linux) | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-wifiscan.svg)](https://crates.io/crates/wifi-densepose-wifiscan) |
| [`wifi-densepose-wasm`](https://crates.io/crates/wifi-densepose-wasm) | WebAssembly bindings for browser deployment | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-wasm.svg)](https://crates.io/crates/wifi-densepose-wasm) | | [`wifi-densepose-wasm`](https://crates.io/crates/wifi-densepose-wasm) | WebAssembly bindings for browser deployment | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-wasm.svg)](https://crates.io/crates/wifi-densepose-wasm) |
| [`wifi-densepose-sensing-server`](https://crates.io/crates/wifi-densepose-sensing-server) | Axum server: UDP ingestion, WebSocket broadcast | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-sensing-server.svg)](https://crates.io/crates/wifi-densepose-sensing-server) | | [`wifi-densepose-sensing-server`](https://crates.io/crates/wifi-densepose-sensing-server) | Axum server: UDP ingestion, WebSocket broadcast | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-sensing-server.svg)](https://crates.io/crates/wifi-densepose-sensing-server) |
| [`wifi-densepose-cli`](https://crates.io/crates/wifi-densepose-cli) | Command-line tool for MAT disaster scanning | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-cli.svg)](https://crates.io/crates/wifi-densepose-cli) | | [`wifi-densepose-cli`](https://crates.io/crates/wifi-densepose-cli) | Command-line tool for MAT disaster scanning | -- | [![crates.io](https://img.shields.io/crates/v/wifi-densepose-cli.svg)](https://crates.io/crates/wifi-densepose-cli) |
@@ -622,7 +622,7 @@ See [ADR-021](docs/adr/ADR-021-vital-sign-detection-rvdna-pipeline.md).
</details> </details>
<details> <details>
<summary><a id="wifi-scan-domain-layer"></a><strong>📡 WiFi Scan Domain Layer (ADR-022)</strong> — 8-stage RSSI pipeline for Windows WiFi</summary> <summary><a id="wifi-scan-domain-layer"></a><strong>📡 WiFi Scan Domain Layer (ADR-022/025)</strong> — 8-stage RSSI pipeline for Windows, macOS, and Linux WiFi</summary>
| Stage | Purpose | | Stage | Purpose |
|-------|---------| |-------|---------|
@@ -1106,6 +1106,8 @@ WebSocket: `ws://localhost:3001/ws/sensing` (real-time sensing + vital signs)
| Intel 5300 | Firmware mod | ~$15 | Linux `iwl-csi` | | Intel 5300 | Firmware mod | ~$15 | Linux `iwl-csi` |
| Atheros AR9580 | ath9k patch | ~$20 | Linux only | | Atheros AR9580 | ath9k patch | ~$20 | Linux only |
| Any Windows WiFi | RSSI only | $0 | [Tutorial #36](https://github.com/ruvnet/wifi-densepose/issues/36) | | Any Windows WiFi | RSSI only | $0 | [Tutorial #36](https://github.com/ruvnet/wifi-densepose/issues/36) |
| Any macOS WiFi | RSSI only (CoreWLAN) | $0 | [ADR-025](docs/adr/ADR-025-macos-corewlan-wifi-sensing.md) |
| Any Linux WiFi | RSSI only (`iw`) | $0 | Requires `iw` + `CAP_NET_ADMIN` |
</details> </details>
@@ -1279,7 +1281,7 @@ The largest release to date — delivers the complete end-to-end training pipeli
- **`--export-rvf` CLI flag** — Standalone RVF model container generation with vital config, training proof, and SONA profiles - **`--export-rvf` CLI flag** — Standalone RVF model container generation with vital config, training proof, and SONA profiles
- **`--train` CLI flag** — Full training mode with best-epoch snapshotting and checkpoint saving - **`--train` CLI flag** — Full training mode with best-epoch snapshotting and checkpoint saving
- **Vital sign detection (ADR-021)** — FFT-based breathing (6-30 BPM) and heartbeat (40-120 BPM) extraction, 11,665 fps benchmark - **Vital sign detection (ADR-021)** — FFT-based breathing (6-30 BPM) and heartbeat (40-120 BPM) extraction, 11,665 fps benchmark
- **WiFi scan domain layer (ADR-022)** — 8-stage pure-Rust signal intelligence pipeline for Windows WiFi RSSI - **WiFi scan domain layer (ADR-022/025)** — 8-stage pure-Rust signal intelligence pipeline for Windows, macOS, and Linux WiFi RSSI
- **New crates** — `wifi-densepose-vitals` (1,863 lines) and `wifi-densepose-wifiscan` (4,829 lines) - **New crates** — `wifi-densepose-vitals` (1,863 lines) and `wifi-densepose-wifiscan` (4,829 lines)
- **542+ Rust tests** — All passing, zero mocks - **542+ Rust tests** — All passing, zero mocks

View File

@@ -89,6 +89,19 @@ All development on: `claude/validate-code-quality-WNrNw`
- **HNSW**: Enabled - **HNSW**: Enabled
- **Neural**: Enabled - **Neural**: Enabled
## Pre-Merge Checklist
Before merging any PR, verify each item applies and is addressed:
1. **Tests pass**`cargo test` (Rust) and `python -m pytest` (Python) green
2. **README.md** — Update platform tables, crate descriptions, hardware tables, feature summaries if scope changed
3. **CHANGELOG.md** — Add entry under `[Unreleased]` with what was added/fixed/changed
4. **User guide** (`docs/user-guide.md`) — Update if new data sources, CLI flags, or setup steps were added
5. **ADR index** — Update ADR count in README docs table if a new ADR was created
6. **Docker Hub image** — Only rebuild if Dockerfile, dependencies, or runtime behavior changed (not needed for platform-gated code that doesn't affect the Linux container)
7. **Crate publishing** — Only needed if a crate is published to crates.io and its public API changed (workspace-internal crates don't need publishing)
8. **`.gitignore`** — Add any new build artifacts or binaries
## Build & Test ## Build & Test
```bash ```bash

View File

@@ -194,6 +194,29 @@ docker run --network host ruvnet/wifi-densepose:latest --source windows --tick-m
See [Tutorial #36](https://github.com/ruvnet/wifi-densepose/issues/36) for a walkthrough. See [Tutorial #36](https://github.com/ruvnet/wifi-densepose/issues/36) for a walkthrough.
### macOS WiFi (RSSI Only)
Uses CoreWLAN via a Swift helper binary. macOS Sonoma 14.4+ redacts real BSSIDs; the adapter generates deterministic synthetic MACs so the multi-BSSID pipeline still works.
```bash
# Compile the Swift helper (once)
swiftc -O v1/src/sensing/mac_wifi.swift -o mac_wifi
# Run natively
./target/release/sensing-server --source macos --http-port 3000 --ws-port 3001 --tick-ms 500
```
See [ADR-025](adr/ADR-025-macos-corewlan-wifi-sensing.md) for details.
### Linux WiFi (RSSI Only)
Uses `iw dev <iface> scan` to capture RSSI. Requires `CAP_NET_ADMIN` (root) for active scans; use `scan dump` for cached results without root.
```bash
# Run natively (requires root for active scanning)
sudo ./target/release/sensing-server --source linux --http-port 3000 --ws-port 3001 --tick-ms 500
```
### ESP32-S3 (Full CSI) ### ESP32-S3 (Full CSI)
Real Channel State Information at 20 Hz with 56-192 subcarriers. Required for pose estimation, vital signs, and through-wall sensing. Real Channel State Information at 20 Hz with 56-192 subcarriers. Required for pose estimation, vital signs, and through-wall sensing.

File diff suppressed because it is too large Load Diff

View File

@@ -47,7 +47,6 @@ tokio = { workspace = true, features = ["sync", "rt"] }
# Additional utilities # Additional utilities
parking_lot = "0.12" parking_lot = "0.12"
once_cell = "1.19"
memmap2 = "0.9" memmap2 = "0.9"
[dev-dependencies] [dev-dependencies]

View File

@@ -0,0 +1,359 @@
//! Adapter that scans WiFi BSSIDs on Linux by invoking `iw dev <iface> scan`.
//!
//! This is the Linux counterpart to [`NetshBssidScanner`](super::NetshBssidScanner)
//! on Windows and [`MacosCoreWlanScanner`](super::MacosCoreWlanScanner) on macOS.
//!
//! # Design
//!
//! The adapter shells out to `iw dev <interface> scan` (or `iw dev <interface> scan dump`
//! to read cached results without triggering a new scan, which requires root).
//! The output is parsed into [`BssidObservation`] values using the same domain
//! types shared by all platform adapters.
//!
//! # Permissions
//!
//! - `iw dev <iface> scan` requires `CAP_NET_ADMIN` (typically root).
//! - `iw dev <iface> scan dump` reads cached results and may work without root
//! on some distributions.
//!
//! # Platform
//!
//! Linux only. Gated behind `#[cfg(target_os = "linux")]` at the module level.
use std::process::Command;
use std::time::Instant;
use crate::domain::bssid::{BandType, BssidId, BssidObservation, RadioType};
use crate::error::WifiScanError;
// ---------------------------------------------------------------------------
// LinuxIwScanner
// ---------------------------------------------------------------------------
/// Synchronous WiFi scanner that shells out to `iw dev <interface> scan`.
///
/// Each call to [`scan_sync`](Self::scan_sync) spawns a subprocess, captures
/// stdout, and parses the BSS stanzas into [`BssidObservation`] values.
pub struct LinuxIwScanner {
/// Wireless interface name (e.g. `"wlan0"`, `"wlp2s0"`).
interface: String,
/// If true, use `scan dump` (cached results) instead of triggering a new
/// scan. This avoids the root requirement but may return stale data.
use_dump: bool,
}
impl LinuxIwScanner {
/// Create a scanner for the default interface `wlan0`.
pub fn new() -> Self {
Self {
interface: "wlan0".to_owned(),
use_dump: false,
}
}
/// Create a scanner for a specific wireless interface.
pub fn with_interface(iface: impl Into<String>) -> Self {
Self {
interface: iface.into(),
use_dump: false,
}
}
/// Use `scan dump` instead of `scan` to read cached results without root.
pub fn use_cached(mut self) -> Self {
self.use_dump = true;
self
}
/// Run `iw dev <iface> scan` and parse the output synchronously.
///
/// Returns one [`BssidObservation`] per BSS stanza in the output.
pub fn scan_sync(&self) -> Result<Vec<BssidObservation>, WifiScanError> {
let scan_cmd = if self.use_dump { "dump" } else { "scan" };
let mut args = vec!["dev", &self.interface, "scan"];
if self.use_dump {
args.push(scan_cmd);
}
// iw uses "scan dump" not "scan scan dump"
let args = if self.use_dump {
vec!["dev", &self.interface, "scan", "dump"]
} else {
vec!["dev", &self.interface, "scan"]
};
let output = Command::new("iw")
.args(&args)
.output()
.map_err(|e| {
WifiScanError::ProcessError(format!(
"failed to run `iw {}`: {e}",
args.join(" ")
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(WifiScanError::ScanFailed {
reason: format!(
"iw exited with {}: {}",
output.status,
stderr.trim()
),
});
}
let stdout = String::from_utf8_lossy(&output.stdout);
parse_iw_scan_output(&stdout)
}
}
impl Default for LinuxIwScanner {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------
/// Intermediate accumulator for fields within a single BSS stanza.
#[derive(Default)]
struct BssStanza {
bssid: Option<String>,
ssid: Option<String>,
signal_dbm: Option<f64>,
freq_mhz: Option<u32>,
channel: Option<u8>,
}
impl BssStanza {
/// Flush this stanza into a [`BssidObservation`], if we have enough data.
fn flush(self, timestamp: Instant) -> Option<BssidObservation> {
let bssid_str = self.bssid?;
let bssid = BssidId::parse(&bssid_str).ok()?;
let rssi_dbm = self.signal_dbm.unwrap_or(-90.0);
// Determine channel from explicit field or frequency.
let channel = self.channel.or_else(|| {
self.freq_mhz.map(freq_to_channel)
}).unwrap_or(0);
let band = BandType::from_channel(channel);
let radio_type = infer_radio_type_from_freq(self.freq_mhz.unwrap_or(0));
let signal_pct = ((rssi_dbm + 100.0) * 2.0).clamp(0.0, 100.0);
Some(BssidObservation {
bssid,
rssi_dbm,
signal_pct,
channel,
band,
radio_type,
ssid: self.ssid.unwrap_or_default(),
timestamp,
})
}
}
/// Parse the text output of `iw dev <iface> scan [dump]`.
///
/// The output consists of BSS stanzas, each starting with:
/// ```text
/// BSS aa:bb:cc:dd:ee:ff(on wlan0)
/// ```
/// followed by indented key-value lines.
pub fn parse_iw_scan_output(output: &str) -> Result<Vec<BssidObservation>, WifiScanError> {
let now = Instant::now();
let mut results = Vec::new();
let mut current: Option<BssStanza> = None;
for line in output.lines() {
// New BSS stanza starts with "BSS " at column 0.
if line.starts_with("BSS ") {
// Flush previous stanza.
if let Some(stanza) = current.take() {
if let Some(obs) = stanza.flush(now) {
results.push(obs);
}
}
// Parse BSSID from "BSS aa:bb:cc:dd:ee:ff(on wlan0)" or
// "BSS aa:bb:cc:dd:ee:ff -- associated".
let rest = &line[4..];
let mac_end = rest.find(|c: char| !c.is_ascii_hexdigit() && c != ':')
.unwrap_or(rest.len());
let mac = &rest[..mac_end];
if mac.len() == 17 {
let mut stanza = BssStanza::default();
stanza.bssid = Some(mac.to_lowercase());
current = Some(stanza);
}
continue;
}
// Indented lines belong to the current stanza.
let trimmed = line.trim();
if let Some(ref mut stanza) = current {
if let Some(rest) = trimmed.strip_prefix("SSID:") {
stanza.ssid = Some(rest.trim().to_owned());
} else if let Some(rest) = trimmed.strip_prefix("signal:") {
// "signal: -52.00 dBm"
stanza.signal_dbm = parse_signal_dbm(rest);
} else if let Some(rest) = trimmed.strip_prefix("freq:") {
// "freq: 5180"
stanza.freq_mhz = rest.trim().parse().ok();
} else if let Some(rest) = trimmed.strip_prefix("DS Parameter set: channel") {
// "DS Parameter set: channel 6"
stanza.channel = rest.trim().parse().ok();
}
}
}
// Flush the last stanza.
if let Some(stanza) = current.take() {
if let Some(obs) = stanza.flush(now) {
results.push(obs);
}
}
Ok(results)
}
/// Convert a frequency in MHz to an 802.11 channel number.
fn freq_to_channel(freq_mhz: u32) -> u8 {
match freq_mhz {
// 2.4 GHz: channels 1-14.
2412..=2472 => ((freq_mhz - 2407) / 5) as u8,
2484 => 14,
// 5 GHz: channels 36-177.
5170..=5885 => ((freq_mhz - 5000) / 5) as u8,
// 6 GHz (Wi-Fi 6E).
5955..=7115 => ((freq_mhz - 5950) / 5) as u8,
_ => 0,
}
}
/// Parse a signal strength string like "-52.00 dBm" into dBm.
fn parse_signal_dbm(s: &str) -> Option<f64> {
let s = s.trim();
// Take everything up to " dBm" or just parse the number.
let num_part = s.split_whitespace().next()?;
num_part.parse().ok()
}
/// Infer radio type from frequency (best effort).
fn infer_radio_type_from_freq(freq_mhz: u32) -> RadioType {
match freq_mhz {
5955..=7115 => RadioType::Ax, // 6 GHz → Wi-Fi 6E
5170..=5885 => RadioType::Ac, // 5 GHz → likely 802.11ac
_ => RadioType::N, // 2.4 GHz → at least 802.11n
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
/// Real-world `iw dev wlan0 scan` output (truncated to 3 BSSes).
const SAMPLE_IW_OUTPUT: &str = "\
BSS aa:bb:cc:dd:ee:ff(on wlan0)
\tTSF: 123456789 usec
\tfreq: 5180
\tbeacon interval: 100 TUs
\tcapability: ESS Privacy (0x0011)
\tsignal: -52.00 dBm
\tSSID: HomeNetwork
\tDS Parameter set: channel 36
BSS 11:22:33:44:55:66(on wlan0)
\tfreq: 2437
\tsignal: -71.00 dBm
\tSSID: GuestWifi
\tDS Parameter set: channel 6
BSS de:ad:be:ef:ca:fe(on wlan0) -- associated
\tfreq: 5745
\tsignal: -45.00 dBm
\tSSID: OfficeNet
";
#[test]
fn parse_three_bss_stanzas() {
let obs = parse_iw_scan_output(SAMPLE_IW_OUTPUT).unwrap();
assert_eq!(obs.len(), 3);
// First BSS.
assert_eq!(obs[0].ssid, "HomeNetwork");
assert_eq!(obs[0].bssid.to_string(), "aa:bb:cc:dd:ee:ff");
assert!((obs[0].rssi_dbm - (-52.0)).abs() < f64::EPSILON);
assert_eq!(obs[0].channel, 36);
assert_eq!(obs[0].band, BandType::Band5GHz);
// Second BSS: 2.4 GHz.
assert_eq!(obs[1].ssid, "GuestWifi");
assert_eq!(obs[1].channel, 6);
assert_eq!(obs[1].band, BandType::Band2_4GHz);
assert_eq!(obs[1].radio_type, RadioType::N);
// Third BSS: "-- associated" suffix.
assert_eq!(obs[2].ssid, "OfficeNet");
assert_eq!(obs[2].bssid.to_string(), "de:ad:be:ef:ca:fe");
assert!((obs[2].rssi_dbm - (-45.0)).abs() < f64::EPSILON);
}
#[test]
fn freq_to_channel_conversion() {
assert_eq!(freq_to_channel(2412), 1);
assert_eq!(freq_to_channel(2437), 6);
assert_eq!(freq_to_channel(2462), 11);
assert_eq!(freq_to_channel(2484), 14);
assert_eq!(freq_to_channel(5180), 36);
assert_eq!(freq_to_channel(5745), 149);
assert_eq!(freq_to_channel(5955), 1); // 6 GHz channel 1
assert_eq!(freq_to_channel(9999), 0); // Unknown
}
#[test]
fn parse_signal_dbm_values() {
assert!((parse_signal_dbm(" -52.00 dBm").unwrap() - (-52.0)).abs() < f64::EPSILON);
assert!((parse_signal_dbm("-71.00 dBm").unwrap() - (-71.0)).abs() < f64::EPSILON);
assert!((parse_signal_dbm("-45.00").unwrap() - (-45.0)).abs() < f64::EPSILON);
}
#[test]
fn empty_output() {
let obs = parse_iw_scan_output("").unwrap();
assert!(obs.is_empty());
}
#[test]
fn missing_ssid_defaults_to_empty() {
let output = "\
BSS 11:22:33:44:55:66(on wlan0)
\tfreq: 2437
\tsignal: -60.00 dBm
";
let obs = parse_iw_scan_output(output).unwrap();
assert_eq!(obs.len(), 1);
assert_eq!(obs[0].ssid, "");
}
#[test]
fn channel_from_freq_when_ds_param_missing() {
let output = "\
BSS aa:bb:cc:dd:ee:ff(on wlan0)
\tfreq: 5180
\tsignal: -50.00 dBm
\tSSID: NoDS
";
let obs = parse_iw_scan_output(output).unwrap();
assert_eq!(obs.len(), 1);
assert_eq!(obs[0].channel, 36); // Derived from 5180 MHz.
}
}

View File

@@ -0,0 +1,360 @@
//! Adapter that scans WiFi BSSIDs on macOS by invoking a compiled Swift
//! helper binary that uses Apple's CoreWLAN framework.
//!
//! This is the macOS counterpart to [`NetshBssidScanner`](super::NetshBssidScanner)
//! on Windows. It follows ADR-025 (ORCA — macOS CoreWLAN WiFi Sensing).
//!
//! # Design
//!
//! Apple removed the `airport` CLI in macOS Sonoma 14.4+ and CoreWLAN is a
//! Swift/Objective-C framework with no stable C ABI for Rust FFI. We therefore
//! shell out to a small Swift helper (`mac_wifi`) that outputs JSON lines:
//!
//! ```json
//! {"ssid":"MyNetwork","bssid":"aa:bb:cc:dd:ee:ff","rssi":-52,"noise":-90,"channel":36,"band":"5GHz"}
//! ```
//!
//! macOS Sonoma+ redacts real BSSID MACs to `00:00:00:00:00:00` unless the app
//! holds the `com.apple.wifi.scan` entitlement. When we detect a zeroed BSSID
//! we generate a deterministic synthetic MAC via `SHA-256(ssid:channel)[:6]`,
//! setting the locally-administered bit so it never collides with real OUI
//! allocations.
//!
//! # Platform
//!
//! macOS only. Gated behind `#[cfg(target_os = "macos")]` at the module level.
use std::process::Command;
use std::time::Instant;
use crate::domain::bssid::{BandType, BssidId, BssidObservation, RadioType};
use crate::error::WifiScanError;
// ---------------------------------------------------------------------------
// MacosCoreWlanScanner
// ---------------------------------------------------------------------------
/// Synchronous WiFi scanner that shells out to the `mac_wifi` Swift helper.
///
/// The helper binary must be compiled from `v1/src/sensing/mac_wifi.swift` and
/// placed on `$PATH` or at a known location. The scanner invokes it with a
/// `--scan-once` flag (single-shot mode) and parses the JSON output.
///
/// If the helper is not found, [`scan_sync`](Self::scan_sync) returns a
/// [`WifiScanError::ProcessError`].
pub struct MacosCoreWlanScanner {
/// Path to the `mac_wifi` helper binary. Defaults to `"mac_wifi"` (on PATH).
helper_path: String,
}
impl MacosCoreWlanScanner {
/// Create a scanner that looks for `mac_wifi` on `$PATH`.
pub fn new() -> Self {
Self {
helper_path: "mac_wifi".to_owned(),
}
}
/// Create a scanner with an explicit path to the Swift helper binary.
pub fn with_path(path: impl Into<String>) -> Self {
Self {
helper_path: path.into(),
}
}
/// Run the Swift helper and parse the output synchronously.
///
/// Returns one [`BssidObservation`] per BSSID seen in the scan.
pub fn scan_sync(&self) -> Result<Vec<BssidObservation>, WifiScanError> {
let output = Command::new(&self.helper_path)
.arg("--scan-once")
.output()
.map_err(|e| {
WifiScanError::ProcessError(format!(
"failed to run mac_wifi helper ({}): {e}",
self.helper_path
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(WifiScanError::ScanFailed {
reason: format!(
"mac_wifi exited with {}: {}",
output.status,
stderr.trim()
),
});
}
let stdout = String::from_utf8_lossy(&output.stdout);
parse_macos_scan_output(&stdout)
}
}
impl Default for MacosCoreWlanScanner {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------
/// Parse the JSON-lines output from the `mac_wifi` Swift helper.
///
/// Each line is expected to be a JSON object with the fields:
/// `ssid`, `bssid`, `rssi`, `noise`, `channel`, `band`.
///
/// Lines that fail to parse are silently skipped (the helper may emit
/// status messages on stdout).
pub fn parse_macos_scan_output(output: &str) -> Result<Vec<BssidObservation>, WifiScanError> {
let now = Instant::now();
let mut results = Vec::new();
for line in output.lines() {
let line = line.trim();
if line.is_empty() || !line.starts_with('{') {
continue;
}
if let Some(obs) = parse_json_line(line, now) {
results.push(obs);
}
}
Ok(results)
}
/// Parse a single JSON line into a [`BssidObservation`].
///
/// Uses a lightweight manual parser to avoid pulling in `serde_json` as a
/// hard dependency. The JSON structure is simple and well-known.
fn parse_json_line(line: &str, timestamp: Instant) -> Option<BssidObservation> {
let ssid = extract_string_field(line, "ssid")?;
let bssid_str = extract_string_field(line, "bssid")?;
let rssi = extract_number_field(line, "rssi")?;
let channel_f = extract_number_field(line, "channel")?;
let channel = channel_f as u8;
// Resolve BSSID: use real MAC if available, otherwise generate synthetic.
let bssid = resolve_bssid(&bssid_str, &ssid, channel)?;
let band = BandType::from_channel(channel);
// macOS CoreWLAN doesn't report radio type directly; infer from band/channel.
let radio_type = infer_radio_type(channel);
// Convert RSSI to signal percentage using the standard mapping.
let signal_pct = ((rssi + 100.0) * 2.0).clamp(0.0, 100.0);
Some(BssidObservation {
bssid,
rssi_dbm: rssi,
signal_pct,
channel,
band,
radio_type,
ssid,
timestamp,
})
}
/// Resolve a BSSID string to a [`BssidId`].
///
/// If the MAC is all-zeros (macOS redaction), generate a synthetic
/// locally-administered MAC from `SHA-256(ssid:channel)`.
fn resolve_bssid(bssid_str: &str, ssid: &str, channel: u8) -> Option<BssidId> {
// Try parsing the real BSSID first.
if let Ok(id) = BssidId::parse(bssid_str) {
// Check for the all-zeros redacted BSSID.
if id.0 != [0, 0, 0, 0, 0, 0] {
return Some(id);
}
}
// Generate synthetic BSSID: SHA-256(ssid:channel), take first 6 bytes,
// set locally-administered + unicast bits (byte 0: bit 1 set, bit 0 clear).
Some(synthetic_bssid(ssid, channel))
}
/// Generate a deterministic synthetic BSSID from SSID and channel.
///
/// Uses a simple hash (FNV-1a-inspired) to avoid pulling in `sha2` crate.
/// The locally-administered bit is set so these never collide with real OUI MACs.
fn synthetic_bssid(ssid: &str, channel: u8) -> BssidId {
// Simple but deterministic hash — FNV-1a 64-bit.
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for &byte in ssid.as_bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash ^= u64::from(channel);
hash = hash.wrapping_mul(0x0100_0000_01b3);
let bytes = hash.to_le_bytes();
let mut mac = [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]];
// Set locally-administered bit (bit 1 of byte 0) and clear multicast (bit 0).
mac[0] = (mac[0] | 0x02) & 0xFE;
BssidId(mac)
}
/// Infer radio type from channel number (best effort on macOS).
fn infer_radio_type(channel: u8) -> RadioType {
match channel {
// 5 GHz channels → likely 802.11ac or newer
36..=177 => RadioType::Ac,
// 2.4 GHz → at least 802.11n
_ => RadioType::N,
}
}
// ---------------------------------------------------------------------------
// Lightweight JSON field extractors
// ---------------------------------------------------------------------------
/// Extract a string field value from a JSON object string.
///
/// Looks for `"key":"value"` or `"key": "value"` patterns.
fn extract_string_field(json: &str, key: &str) -> Option<String> {
let pattern = format!("\"{}\"", key);
let key_pos = json.find(&pattern)?;
let after_key = &json[key_pos + pattern.len()..];
// Skip optional whitespace and the colon.
let after_colon = after_key.trim_start().strip_prefix(':')?;
let after_colon = after_colon.trim_start();
// Expect opening quote.
let after_quote = after_colon.strip_prefix('"')?;
// Find closing quote (handle escaped quotes).
let mut end = 0;
let bytes = after_quote.as_bytes();
while end < bytes.len() {
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
break;
}
end += 1;
}
Some(after_quote[..end].to_owned())
}
/// Extract a numeric field value from a JSON object string.
///
/// Looks for `"key": <number>` patterns.
fn extract_number_field(json: &str, key: &str) -> Option<f64> {
let pattern = format!("\"{}\"", key);
let key_pos = json.find(&pattern)?;
let after_key = &json[key_pos + pattern.len()..];
let after_colon = after_key.trim_start().strip_prefix(':')?;
let after_colon = after_colon.trim_start();
// Collect digits, sign, and decimal point.
let num_str: String = after_colon
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '-' || *c == '.' || *c == '+' || *c == 'e' || *c == 'E')
.collect();
num_str.parse().ok()
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE_OUTPUT: &str = r#"
{"ssid":"HomeNetwork","bssid":"aa:bb:cc:dd:ee:ff","rssi":-52,"noise":-90,"channel":36,"band":"5GHz"}
{"ssid":"GuestWifi","bssid":"11:22:33:44:55:66","rssi":-71,"noise":-92,"channel":6,"band":"2.4GHz"}
{"ssid":"Redacted","bssid":"00:00:00:00:00:00","rssi":-65,"noise":-88,"channel":149,"band":"5GHz"}
"#;
#[test]
fn parse_valid_output() {
let obs = parse_macos_scan_output(SAMPLE_OUTPUT).unwrap();
assert_eq!(obs.len(), 3);
// First entry: real BSSID.
assert_eq!(obs[0].ssid, "HomeNetwork");
assert_eq!(obs[0].bssid.to_string(), "aa:bb:cc:dd:ee:ff");
assert!((obs[0].rssi_dbm - (-52.0)).abs() < f64::EPSILON);
assert_eq!(obs[0].channel, 36);
assert_eq!(obs[0].band, BandType::Band5GHz);
// Second entry: 2.4 GHz.
assert_eq!(obs[1].ssid, "GuestWifi");
assert_eq!(obs[1].channel, 6);
assert_eq!(obs[1].band, BandType::Band2_4GHz);
assert_eq!(obs[1].radio_type, RadioType::N);
// Third entry: redacted BSSID → synthetic MAC.
assert_eq!(obs[2].ssid, "Redacted");
// Should NOT be all-zeros.
assert_ne!(obs[2].bssid.0, [0, 0, 0, 0, 0, 0]);
// Should have locally-administered bit set.
assert_eq!(obs[2].bssid.0[0] & 0x02, 0x02);
// Should have unicast bit (multicast cleared).
assert_eq!(obs[2].bssid.0[0] & 0x01, 0x00);
}
#[test]
fn synthetic_bssid_is_deterministic() {
let a = synthetic_bssid("TestNet", 36);
let b = synthetic_bssid("TestNet", 36);
assert_eq!(a, b);
// Different SSID or channel → different MAC.
let c = synthetic_bssid("OtherNet", 36);
assert_ne!(a, c);
let d = synthetic_bssid("TestNet", 6);
assert_ne!(a, d);
}
#[test]
fn parse_empty_and_junk_lines() {
let output = "\n \nnot json\n{broken json\n";
let obs = parse_macos_scan_output(output).unwrap();
assert!(obs.is_empty());
}
#[test]
fn extract_string_field_basic() {
let json = r#"{"ssid":"MyNet","bssid":"aa:bb:cc:dd:ee:ff"}"#;
assert_eq!(extract_string_field(json, "ssid").unwrap(), "MyNet");
assert_eq!(
extract_string_field(json, "bssid").unwrap(),
"aa:bb:cc:dd:ee:ff"
);
assert!(extract_string_field(json, "missing").is_none());
}
#[test]
fn extract_number_field_basic() {
let json = r#"{"rssi":-52,"channel":36}"#;
assert!((extract_number_field(json, "rssi").unwrap() - (-52.0)).abs() < f64::EPSILON);
assert!((extract_number_field(json, "channel").unwrap() - 36.0).abs() < f64::EPSILON);
}
#[test]
fn signal_pct_clamping() {
// RSSI -50 → pct = (-50+100)*2 = 100
let json = r#"{"ssid":"Test","bssid":"aa:bb:cc:dd:ee:ff","rssi":-50,"channel":1}"#;
let obs = parse_json_line(json, Instant::now()).unwrap();
assert!((obs.signal_pct - 100.0).abs() < f64::EPSILON);
// RSSI -100 → pct = 0
let json = r#"{"ssid":"Test","bssid":"aa:bb:cc:dd:ee:ff","rssi":-100,"channel":1}"#;
let obs = parse_json_line(json, Instant::now()).unwrap();
assert!((obs.signal_pct - 0.0).abs() < f64::EPSILON);
}
}

View File

@@ -1,12 +1,30 @@
//! Adapter implementations for the [`WlanScanPort`] port. //! Adapter implementations for the [`WlanScanPort`] port.
//! //!
//! Each adapter targets a specific platform scanning mechanism: //! Each adapter targets a specific platform scanning mechanism:
//! - [`NetshBssidScanner`]: Tier 1 -- parses `netsh wlan show networks mode=bssid`. //! - [`NetshBssidScanner`]: Tier 1 -- parses `netsh wlan show networks mode=bssid` (Windows).
//! - [`WlanApiScanner`]: Tier 2 -- async wrapper with metrics and future native FFI path. //! - [`WlanApiScanner`]: Tier 2 -- async wrapper with metrics and future native FFI path (Windows).
//! - [`MacosCoreWlanScanner`]: CoreWLAN via Swift helper binary (macOS, ADR-025).
//! - [`LinuxIwScanner`]: parses `iw dev <iface> scan` output (Linux).
pub(crate) mod netsh_scanner; pub(crate) mod netsh_scanner;
pub mod wlanapi_scanner; pub mod wlanapi_scanner;
#[cfg(target_os = "macos")]
pub mod macos_scanner;
#[cfg(target_os = "linux")]
pub mod linux_scanner;
pub use netsh_scanner::NetshBssidScanner; pub use netsh_scanner::NetshBssidScanner;
pub use netsh_scanner::parse_netsh_output; pub use netsh_scanner::parse_netsh_output;
pub use wlanapi_scanner::WlanApiScanner; pub use wlanapi_scanner::WlanApiScanner;
#[cfg(target_os = "macos")]
pub use macos_scanner::MacosCoreWlanScanner;
#[cfg(target_os = "macos")]
pub use macos_scanner::parse_macos_scan_output;
#[cfg(target_os = "linux")]
pub use linux_scanner::LinuxIwScanner;
#[cfg(target_os = "linux")]
pub use linux_scanner::parse_iw_scan_output;

View File

@@ -6,8 +6,10 @@
//! //!
//! - **Domain types**: [`BssidId`], [`BssidObservation`], [`BandType`], [`RadioType`] //! - **Domain types**: [`BssidId`], [`BssidObservation`], [`BandType`], [`RadioType`]
//! - **Port**: [`WlanScanPort`] -- trait abstracting the platform scan backend //! - **Port**: [`WlanScanPort`] -- trait abstracting the platform scan backend
//! - **Adapter**: [`NetshBssidScanner`] -- Tier 1 adapter that parses //! - **Adapters**:
//! `netsh wlan show networks mode=bssid` output //! - [`NetshBssidScanner`] -- Windows, parses `netsh wlan show networks mode=bssid`
//! - `MacosCoreWlanScanner` -- macOS, invokes CoreWLAN Swift helper (ADR-025)
//! - `LinuxIwScanner` -- Linux, parses `iw dev <iface> scan` output
pub mod adapter; pub mod adapter;
pub mod domain; pub mod domain;
@@ -19,6 +21,16 @@ pub mod port;
pub use adapter::NetshBssidScanner; pub use adapter::NetshBssidScanner;
pub use adapter::parse_netsh_output; pub use adapter::parse_netsh_output;
pub use adapter::WlanApiScanner; pub use adapter::WlanApiScanner;
#[cfg(target_os = "macos")]
pub use adapter::MacosCoreWlanScanner;
#[cfg(target_os = "macos")]
pub use adapter::parse_macos_scan_output;
#[cfg(target_os = "linux")]
pub use adapter::LinuxIwScanner;
#[cfg(target_os = "linux")]
pub use adapter::parse_iw_scan_output;
pub use domain::bssid::{BandType, BssidId, BssidObservation, RadioType}; pub use domain::bssid::{BandType, BssidId, BssidObservation, RadioType};
pub use domain::frame::MultiApFrame; pub use domain::frame::MultiApFrame;
pub use domain::registry::{BssidEntry, BssidMeta, BssidRegistry, RunningStats}; pub use domain::registry::{BssidEntry, BssidMeta, BssidRegistry, RunningStats};

View File

@@ -0,0 +1,34 @@
import Foundation
import CoreWLAN
// Output format: JSON lines for easy parsing by Python
// {"timestamp": 1234567.89, "rssi": -50, "noise": -90, "tx_rate": 866.0}
func main() {
guard let interface = CWWiFiClient.shared().interface() else {
fputs("{\"error\": \"No WiFi interface found\"}\n", stderr)
exit(1)
}
// Flush stdout automatically to prevent buffering issues with Python subprocess
setbuf(stdout, nil)
// Run at ~10Hz
let interval: TimeInterval = 0.1
while true {
let timestamp = Date().timeIntervalSince1970
let rssi = interface.rssiValue()
let noise = interface.noiseMeasurement()
let txRate = interface.transmitRate()
let json = """
{"timestamp": \(timestamp), "rssi": \(rssi), "noise": \(noise), "tx_rate": \(txRate)}
"""
print(json)
Thread.sleep(forTimeInterval: interval)
}
}
main()

View File

@@ -602,3 +602,137 @@ class WindowsWifiCollector:
retry_count=0, retry_count=0,
interface=self._interface, interface=self._interface,
) )
# ---------------------------------------------------------------------------
# macOS WiFi collector (real hardware via Swift CoreWLAN utility)
# ---------------------------------------------------------------------------
class MacosWifiCollector:
"""
Collects real RSSI data from a macOS WiFi interface using a Swift utility.
Data source: A small compiled Swift binary (`mac_wifi`) that polls the
CoreWLAN `CWWiFiClient.shared().interface()` at a high rate.
"""
def __init__(
self,
sample_rate_hz: float = 10.0,
buffer_seconds: int = 120,
) -> None:
self._rate = sample_rate_hz
self._buffer = RingBuffer(max_size=int(sample_rate_hz * buffer_seconds))
self._running = False
self._thread: Optional[threading.Thread] = None
self._process: Optional[subprocess.Popen] = None
self._interface = "en0" # CoreWLAN automatically targets the active Wi-Fi interface
# Compile the Swift utility if the binary doesn't exist
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
self.swift_src = os.path.join(base_dir, "mac_wifi.swift")
self.swift_bin = os.path.join(base_dir, "mac_wifi")
# -- public API ----------------------------------------------------------
@property
def sample_rate_hz(self) -> float:
return self._rate
def start(self) -> None:
if self._running:
return
# Ensure binary exists
import os
if not os.path.exists(self.swift_bin):
logger.info("Compiling mac_wifi.swift to %s", self.swift_bin)
try:
subprocess.run(["swiftc", "-O", "-o", self.swift_bin, self.swift_src], check=True, capture_output=True)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Failed to compile macOS WiFi utility: {e.stderr.decode('utf-8')}")
except FileNotFoundError:
raise RuntimeError("swiftc is not installed. Please install Xcode Command Line Tools to use native macOS WiFi sensing.")
self._running = True
self._thread = threading.Thread(
target=self._sample_loop, daemon=True, name="mac-rssi-collector"
)
self._thread.start()
logger.info("MacosWifiCollector started at %.1f Hz", self._rate)
def stop(self) -> None:
self._running = False
if self._process:
self._process.terminate()
try:
self._process.wait(timeout=1.0)
except subprocess.TimeoutExpired:
self._process.kill()
self._process = None
if self._thread is not None:
self._thread.join(timeout=2.0)
self._thread = None
logger.info("MacosWifiCollector stopped")
def get_samples(self, n: Optional[int] = None) -> List[WifiSample]:
if n is not None:
return self._buffer.get_last_n(n)
return self._buffer.get_all()
# -- internals -----------------------------------------------------------
def _sample_loop(self) -> None:
import json
# Start the Swift binary
self._process = subprocess.Popen(
[self.swift_bin],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1 # Line buffered
)
while self._running and self._process and self._process.poll() is None:
try:
line = self._process.stdout.readline()
if not line:
continue
line = line.strip()
if not line:
continue
if line.startswith("{"):
data = json.loads(line)
if "error" in data:
logger.error("macOS WiFi utility error: %s", data["error"])
continue
rssi = float(data.get("rssi", -80.0))
noise = float(data.get("noise", -95.0))
link_quality = max(0.0, min(1.0, (rssi + 100.0) / 60.0))
sample = WifiSample(
timestamp=time.time(),
rssi_dbm=rssi,
noise_dbm=noise,
link_quality=link_quality,
tx_bytes=0,
rx_bytes=0,
retry_count=0,
interface=self._interface,
)
self._buffer.append(sample)
except Exception as e:
logger.error("Error reading macOS WiFi stream: %s", e)
time.sleep(1.0)
# Process exited unexpectedly
if self._running:
logger.error("macOS WiFi utility exited unexpectedly. Collector stopped.")
self._running = False

View File

@@ -41,6 +41,7 @@ from v1.src.sensing.rssi_collector import (
LinuxWifiCollector, LinuxWifiCollector,
SimulatedCollector, SimulatedCollector,
WindowsWifiCollector, WindowsWifiCollector,
MacosWifiCollector,
WifiSample, WifiSample,
RingBuffer, RingBuffer,
) )
@@ -340,12 +341,26 @@ class SensingWebSocketServer:
except Exception as e: except Exception as e:
logger.warning("Windows WiFi unavailable (%s), falling back", e) logger.warning("Windows WiFi unavailable (%s), falling back", e)
elif system == "Linux": elif system == "Linux":
# In Docker on Mac, Linux is detected but no wireless extensions exist.
# Force SimulatedCollector if /proc/net/wireless doesn't exist.
import os
if os.path.exists("/proc/net/wireless"):
try:
collector = LinuxWifiCollector(sample_rate_hz=10.0)
self.source = "linux_wifi"
return collector
except RuntimeError:
logger.warning("Linux WiFi unavailable, falling back")
else:
logger.warning("Linux detected but /proc/net/wireless missing (likely Docker). Falling back.")
elif system == "Darwin":
try: try:
collector = LinuxWifiCollector(sample_rate_hz=10.0) collector = MacosWifiCollector(sample_rate_hz=10.0)
self.source = "linux_wifi" logger.info("Using MacosWifiCollector")
self.source = "macos_wifi"
return collector return collector
except RuntimeError: except Exception as e:
logger.warning("Linux WiFi unavailable, falling back") logger.warning("macOS WiFi unavailable (%s), falling back", e)
# 3. Simulated # 3. Simulated
logger.info("Using SimulatedCollector") logger.info("Using SimulatedCollector")