ADR-022: 通过 RuVector 多 BSSID 流水线增强 Windows WiFi DensePose 保真度¶
| 字段 | 值 |
|---|---|
| 状态 | 部分实现 |
| 日期 | 2026-02-28 |
| 决策者 | ruv |
| 相关 | ADR-013 (功能级感知消费级设备), ADR-014 (SOTA 信号处理), ADR-016 (RuVector 集成), ADR-018 (ESP32 开发实现), ADR-021 (生命体征检测) |
1. 背景¶
1.1 问题:单 RSSI 瓶颈¶
wifi-densepose-sensing-server 中当前的 Windows WiFi 模式(:main.rs:382-464)每 500ms 启动一个 netsh wlan show interfaces 子进程,从已连接的 AP 中提取单个 RSSI% 值。这会创建一个伪单子载波 Esp32Frame,其包含:
- 1 个幅度值(信号%)
- 0 个相位信息
- 约 2 Hz 的有效采样率(进程启动开销)
- 无空间分集(单观测点)
这对于任何有意义的 DensePose 估计都是不足的。ESP32 路径以 100+ Hz 提供 56 个带 I/Q 数据的子载波,而 Windows 路径以 2 Hz 提供 1 个标量——存在 2,800 倍的数据缺口。
1.2 机会:多 BSSID 空间分集¶
标准 Windows WiFi 环境通过 netsh wlan show networks mode=bssid 暴露 10-30+ 个 BSSID。在目标机器(Intel Wi-Fi 7 BE201 320MHz)上的测试显示:
| 属性 | 值 |
|---|---|
| 适配器 | Intel Wi-Fi 7 BE201 320MHz (NDIS 6.89) |
| 可见 BSSID | 23 |
| 频段 | 2.4 GHz(信道 3,5,8,11)、5 GHz(信道 36,48) |
| 无线电类型 | 802.11n、802.11ac、802.11ax |
| 信号范围 | 18% 到 99% |
每个 BSSID 通过环境传播时经过不同的物理路径。人体根据 AP 的相对位置、频率和信道,以不同方式反射/吸收/衍射每条路径。这创建了等效于伪子载波的空间分集。
1.3 增强:三层保真度改进¶
| 层级 | 方法 | 子载波 | 采样率 | 实现 |
|---|---|---|---|---|
| 当前 | netsh show interfaces |
1 | ~2 Hz | 子进程启动 |
| 第 1 层 | netsh show networks mode=bssid |
23 | ~2 Hz | 解析多 BSSID 输出 |
| 第 2 层 | Windows WLAN API(wlanapi.dll FFI) |
23 | 10-20 Hz | 原生 FFI,无子进程 |
| 第 3 层 | Intel Wi-Fi Sensing SDK(802.11bf) | 56+ | 100 Hz | 厂商 SDK 集成 |
本 ADR 覆盖第 1 层和第 2 层。第 3 层推迟到未来 ADR,待获得 Intel SDK 访问权限。
1.4 RuVector 提供的能力¶
vendor/ruvector crate 生态系统提供信号处理原语,将多 BSSID RSSI 向量转换为有意义的感知数据:
| RuVector 原语 | 在 Windows WiFi 增强中的作用 |
|---|---|
PredictiveLayer (nervous-system) |
抑制静态 BSSID(无人体交互),仅传输残差变化。在 23 个 BSSID 中,通常 80-95% 是静态的。 |
ScaledDotProductAttention (attention) |
学习每个环境中哪些 BSSID 对人体的敏感性最高。注意力查询 = 人体运动频谱轮廓,键 = 每个 BSSID 的方差轮廓。 |
RuvectorLayer (gnn) |
在 BSSID 上构建互相关图。节点 = BSSID,边 = 时间互相关。消息传递识别受同一个人影响的 BSSID 簇。 |
OscillatoryRouter (nervous-system) |
从多 BSSID 方差中分离呼吸频段(0.1-0.5 Hz)振荡,用于粗略呼吸感知。 |
ModernHopfield (nervous-system) |
对 BSSID 指纹模式(站立、坐着、行走、空)进行模板匹配。 |
SpectralCoherenceScore (coherence) |
测量 BSSID 相关图中的频谱间隙;强间隙 = 良好的信号分离。 |
TieredStore (temporal-tensor) |
使用自适应量化(8/5/3 位层级)存储多 BSSID 时间序列。 |
AdaptiveThresholds (ruQu) |
使用 Welford 统计、EMA 和基于结果的学习,自调存在/运动阈值。 |
DriftDetector (ruQu) |
检测环境变化(AP 电源循环、家具移动、新的干扰源)。5 种漂移配置文件:Stable、Linear、StepChange、Oscillating、VarianceExpansion。 |
FilterPipeline (ruQu) |
用于信号质量评估的三滤波器门(Structural/Shift/Evidence)。仅 PERMIT 具有统计严格置信度的读数。 |
SonaEngine (sona) |
针对每个环境对 BSSID 权重和滤波器参数进行 micro-LoRA 自适应。 |
2. 决策¶
在 wifi-densepose-sensing-server crate 内实现一个增强型 Windows WiFi 感知流水线作为新模块(并部分位于新的 wifi-densepose-wifiscan crate 中),使用带限界上下文的领域驱动设计。该流水线扫描所有可见 BSSID,构建多维伪 CSI 帧,并通过 RuVector 信号流水线处理它们,以实现与 ESP32 相当的存在/运动检测和粗略生命体征估计。
2.1 核心设计原则¶
- 多 BSSID 作为伪子载波:每个可见 BSSID 映射到现有
Esp32Frame结构中的子载波槽位,从而能够复用所有下游信号处理。 - 渐进增强:第 1 层(netsh 解析)首先发布,零新增依赖。第 2 层(wlanapi FFI)在功能标志后添加
windows-sys。 - 优雅降级:当可见 BSSID 数量较少(<5)时,系统回退到单 AP RSSI 模式,并降低置信度分数。
- 环境学习:SONA 通过 micro-LoRA 针对每次部署自适应 BSSID 权重和阈值,并存储在
TieredStore中。 - 相同 API 表面:输出是标准
SensingUpdate消息,对 UI 而言与 ESP32 模式无法区分。
3. 架构(领域驱动设计)¶
3.1 战略设计:限界上下文¶
┌─────────────────────────────────────────────────────────────────────────────┐
│ WiFi DensePose Windows Enhancement │
│ │
│ ┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────┐ │
│ │ BSSID Acquisition │ │ Signal Intelligence │ │ Sensing Output │ │
│ │ (Supporting Domain) │ │ (Core Domain) │ │ (Generic Domain) │ │
│ │ │ │ │ │ │ │
│ │ • WlanScanner │ │ • BssidAttention │ │ • FrameBuilder │ │
│ │ • BssidRegistry │ │ • SpatialCorrelator │ │ • UpdateEmitter │ │
│ │ • ScanScheduler │ │ • MotionEstimator │ │ • QualityGate │ │
│ │ • RssiNormalizer │ │ • BreathingExtractor │ │ • HistoryStore │ │
│ │ │ │ • DriftMonitor │ │ │ │
│ │ Port: WlanScanPort │ │ • EnvironmentAdapter │ │ Port: SinkPort │ │
│ │ Adapter: NetshScan │ │ │ │ Adapter: WsSink │ │
│ │ Adapter: WlanApiScan│ │ Port: SignalPort │ │ Adapter: RestSink│ │
│ └──────────────────────┘ └──────────────────────┘ └──────────────────┘ │
│ │ │ │ │
│ │ Anti-Corruption │ Anti-Corruption │ │
│ │ Layer (ACL) │ Layer (ACL) │ │
│ └────────────────────────┘────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ Shared Kernel │ │
│ │ • BssidId, RssiDbm, SignalPercent, ChannelInfo, BandType │ │
│ │ • Esp32Frame (reused as universal frame type) │ │
│ │ • SensingUpdate, FeatureInfo, ClassificationInfo │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
3.2 战术设计:聚合与实体¶
限界上下文 1:BSSID 获取(支持域)¶
聚合根:BssidRegistry
跟踪所有扫描中可见的 BSSID,并保持身份稳定性(BSSID 会随 AP 信标出现/消失)。
/// Value Object: unique BSSID identifier
#[derive(Clone, Hash, Eq, PartialEq)]
pub struct BssidId(pub [u8; 6]); // MAC address
/// Value Object: single BSSID observation
#[derive(Clone, Debug)]
pub struct BssidObservation {
pub bssid: BssidId,
pub rssi_dbm: f64,
pub signal_pct: f64,
pub channel: u8,
pub band: BandType,
pub radio_type: RadioType,
pub ssid: String,
pub timestamp: std::time::Instant,
}
#[derive(Clone, Debug, PartialEq)]
pub enum BandType { Band2_4GHz, Band5GHz, Band6GHz }
#[derive(Clone, Debug, PartialEq)]
pub enum RadioType { N, Ac, Ax, Be }
/// Aggregate Root: tracks all visible BSSIDs
pub struct BssidRegistry {
/// Known BSSIDs with sliding window of observations
entries: HashMap<BssidId, BssidEntry>,
/// Ordered list of BSSID IDs for consistent subcarrier mapping
/// (sorted by first-seen time for stability)
subcarrier_map: Vec<BssidId>,
/// Maximum tracked BSSIDs (maps to max subcarriers)
max_bssids: usize,
}
/// Entity: tracked BSSID with history
pub struct BssidEntry {
pub id: BssidId,
pub meta: BssidMeta,
/// Ring buffer of recent RSSI observations
pub history: RingBuffer<f64>,
/// Welford online stats (mean, variance)
pub stats: RunningStats,
/// Last seen timestamp (for expiry)
pub last_seen: std::time::Instant,
/// Subcarrier index in the pseudo-frame (-1 if unmapped)
pub subcarrier_idx: Option<usize>,
}
端口:WlanScanPort(六边形架构)
/// Port: abstracts WiFi scanning backend
#[async_trait::async_trait]
pub trait WlanScanPort: Send + Sync {
/// Perform a scan and return all visible BSSIDs
async fn scan(&self) -> Result<Vec<BssidObservation>>;
/// Get the connected BSSID (if any)
async fn connected(&self) -> Option<BssidObservation>;
/// Trigger an active scan (may not be supported)
async fn trigger_active_scan(&self) -> Result<()>;
}
适配器 1:NetshBssidScanner(第 1 层)
/// Tier 1 adapter: parses `netsh wlan show networks mode=bssid`
pub struct NetshBssidScanner;
#[async_trait::async_trait]
impl WlanScanPort for NetshBssidScanner {
async fn scan(&self) -> Result<Vec<BssidObservation>> {
let output = tokio::process::Command::new("netsh")
.args(["wlan", "show", "networks", "mode=bssid"])
.output()
.await?;
let text = String::from_utf8_lossy(&output.stdout);
parse_bssid_scan_output(&text)
}
// ...
}
/// Parse multi-BSSID netsh output into structured observations
fn parse_bssid_scan_output(output: &str) -> Result<Vec<BssidObservation>> {
// Parses blocks like:
// SSID 1 : MyNetwork
// BSSID 1 : aa:bb:cc:dd:ee:ff
// Signal : 84%
// Radio type : 802.11ax
// Band : 2.4 GHz
// Channel : 5
// Returns Vec<BssidObservation> with all fields populated
todo!()
}
适配器 2:WlanApiBssidScanner(第 2 层,特性门控)
/// Tier 2 adapter: uses wlanapi.dll via FFI for 10-20 Hz polling
#[cfg(all(target_os = "windows", feature = "wlanapi"))]
pub struct WlanApiBssidScanner {
handle: WlanHandle,
interface_guid: GUID,
}
#[cfg(all(target_os = "windows", feature = "wlanapi"))]
#[async_trait::async_trait]
impl WlanScanPort for WlanApiBssidScanner {
async fn scan(&self) -> Result<Vec<BssidObservation>> {
// WlanGetNetworkBssList returns WLAN_BSS_LIST with per-BSSID:
// - RSSI (i32, dBm)
// - Link quality (u32, 0-100)
// - Channel (from PHY)
// - BSS type, beacon period, IEs
// Much faster than netsh (~5ms vs ~200ms per call)
let bss_list = unsafe {
wlanapi::WlanGetNetworkBssList(
self.handle.0,
&self.interface_guid,
std::ptr::null(),
wlanapi::dot11_BSS_type_any,
0, // security disabled
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
// ... parse WLAN_BSS_ENTRY structs into BssidObservation
todo!()
}
async fn trigger_active_scan(&self) -> Result<()> {
// WlanScan triggers a fresh scan; results arrive async
unsafe { wlanapi::WlanScan(self.handle.0, &self.interface_guid, ...) };
Ok(())
}
}
领域服务:ScanScheduler
/// Coordinates scan timing and BSSID registry updates
pub struct ScanScheduler {
scanner: Box<dyn WlanScanPort>,
registry: BssidRegistry,
/// Scan interval (Tier 1: 500ms, Tier 2: 50-100ms)
interval: Duration,
/// Adaptive scan rate based on motion detection
adaptive_rate: bool,
}
impl ScanScheduler {
/// Run continuous scanning loop, updating registry
pub async fn run(&mut self, frame_tx: mpsc::Sender<MultiApFrame>) {
let mut ticker = tokio::time::interval(self.interval);
loop {
ticker.tick().await;
match self.scanner.scan().await {
Ok(observations) => {
self.registry.update(&observations);
let frame = self.registry.to_pseudo_frame();
let _ = frame_tx.send(frame).await;
}
Err(e) => tracing::warn!("Scan failed: {e}"),
}
}
}
}
限界上下文 2:信号智能(核心域)¶
正是在这里,RuVector 原语组合成感知流水线。
领域服务:WindowsWifiPipeline
/// Core pipeline that transforms multi-BSSID scans into sensing data
pub struct WindowsWifiPipeline {
// ── Stage 1: Predictive Gating ──
/// Suppresses static BSSIDs (no body interaction)
/// ruvector-nervous-system::routing::PredictiveLayer
predictive: PredictiveLayer,
// ── Stage 2: Attention Weighting ──
/// Learns BSSID body-sensitivity per environment
/// ruvector-attention::ScaledDotProductAttention
attention: ScaledDotProductAttention,
// ── Stage 3: Spatial Correlation ──
/// Cross-correlation graph over BSSIDs
/// ruvector-gnn::RuvectorLayer (nodes=BSSIDs, edges=correlation)
correlator: BssidCorrelator,
// ── Stage 4: Motion/Presence Estimation ──
/// Multi-BSSID motion score with per-AP weighting
motion_estimator: MultiApMotionEstimator,
// ── Stage 5: Coarse Vital Signs ──
/// Breathing extraction from body-sensitive BSSID oscillations
/// ruvector-nervous-system::routing::OscillatoryRouter
breathing: CoarseBreathingExtractor,
// ── Stage 6: Quality Gate ──
/// ruQu three-filter pipeline + adaptive thresholds
quality_gate: VitalCoherenceGate,
// ── Stage 7: Fingerprint Matching ──
/// Hopfield template matching for posture classification
/// ruvector-nervous-system::hopfield::ModernHopfield
fingerprint: BssidFingerprintMatcher,
// ── Stage 8: Environment Adaptation ──
/// SONA micro-LoRA per deployment
/// sona::SonaEngine
adapter: SonaEnvironmentAdapter,
// ── Stage 9: Drift Monitoring ──
/// ruQu drift detection per BSSID baseline
drift: Vec<DriftDetector>,
// ── Storage ──
/// Tiered storage for BSSID time series
/// ruvector-temporal-tensor::TieredStore
store: TieredStore,
config: WindowsWifiConfig,
}
值对象:WindowsWifiConfig
pub struct WindowsWifiConfig {
/// Maximum BSSIDs to track (default: 32)
pub max_bssids: usize,
/// Scan interval for Tier 1 (default: 500ms)
pub tier1_interval_ms: u64,
/// Scan interval for Tier 2 (default: 50ms)
pub tier2_interval_ms: u64,
/// PredictiveLayer residual threshold (default: 0.05)
pub predictive_threshold: f32,
/// Minimum BSSIDs for multi-AP mode (default: 3)
pub min_bssids: usize,
/// BSSID expiry after no observation (default: 30s)
pub bssid_expiry_secs: u64,
/// Enable coarse breathing extraction (default: true)
pub enable_breathing: bool,
/// Enable fingerprint matching (default: true)
pub enable_fingerprint: bool,
/// Enable SONA adaptation (default: true)
pub enable_adaptation: bool,
/// Breathing band (Hz) — relaxed for low sample rate
pub breathing_band: (f64, f64),
/// Motion variance threshold for presence detection
pub motion_threshold: f64,
}
impl Default for WindowsWifiConfig {
fn default() -> Self {
Self {
max_bssids: 32,
tier1_interval_ms: 500,
tier2_interval_ms: 50,
predictive_threshold: 0.05,
min_bssids: 3,
bssid_expiry_secs: 30,
enable_breathing: true,
enable_fingerprint: true,
enable_adaptation: true,
breathing_band: (0.1, 0.5),
motion_threshold: 0.15,
}
}
}
领域服务:分阶段处理
impl WindowsWifiPipeline {
pub fn process(&mut self, frame: &MultiApFrame) -> Option<EnhancedSensingResult> {
let n = frame.bssid_count;
if n < self.config.min_bssids {
return None; // Too few BSSIDs, degrade to legacy
}
// ── Stage 1: Predictive Gating ──
// Convert RSSI dBm to linear amplitude for PredictiveLayer
let amplitudes: Vec<f32> = frame.rssi_dbm.iter()
.map(|&r| 10.0f32.powf((r as f32 + 100.0) / 20.0))
.collect();
let has_change = self.predictive.should_transmit(&litudes);
self.predictive.update(&litudes);
if !has_change {
return None; // Environment static, no body present
}
// ── Stage 2: Attention Weighting ──
// Query: variance profile of breathing band per BSSID
// Key: current RSSI variance per BSSID
// Value: amplitude vector
let query = self.compute_breathing_variance_query(frame);
let keys = self.compute_bssid_variance_keys(frame);
let key_refs: Vec<&[f32]> = keys.iter().map(|k| k.as_slice()).collect();
let val_refs: Vec<&[f32]> = amplitudes.chunks(1).collect(); // per-BSSID
let weights = self.attention.compute(&query, &key_refs, &val_refs);
// ── Stage 3: Spatial Correlation ──
// Build correlation graph: edge(i,j) = pearson_r(bssid_i, bssid_j)
let correlation_features = self.correlator.forward(&frame.histories);
// ── Stage 4: Motion Estimation ──
let motion = self.motion_estimator.estimate(
&weights,
&correlation_features,
&frame.per_bssid_variance,
);
// ── Stage 5: Coarse Breathing ──
let breathing = if self.config.enable_breathing && motion.level == MotionLevel::Minimal {
self.breathing.extract_from_weighted_bssids(
&weights,
&frame.histories,
frame.sample_rate_hz,
)
} else {
None
};
// ── Stage 6: Quality Gate (ruQu) ──
let reading = PreliminaryReading {
motion,
breathing,
signal_quality: self.compute_signal_quality(n, &weights),
};
let verdict = self.quality_gate.gate(&reading);
if matches!(verdict, Verdict::Deny) {
return None;
}
// ── Stage 7: Fingerprint Matching ──
let posture = if self.config.enable_fingerprint {
self.fingerprint.classify(&litudes)
} else {
None
};
// ── Stage 8: Environment Adaptation ──
if self.config.enable_adaptation {
self.adapter.end_trajectory(reading.signal_quality);
}
// ── Stage 9: Drift Monitoring ──
for (i, drift) in self.drift.iter_mut().enumerate() {
if i < n {
drift.push(frame.rssi_dbm[i]);
}
}
// ── Stage 10: Store ──
let tick = frame.sequence as u64;
self.store.put(
ruvector_temporal_tensor::BlockKey::new(0, tick),
&litudes,
ruvector_temporal_tensor::Tier::Hot,
tick,
);
Some(EnhancedSensingResult {
motion,
breathing,
posture,
signal_quality: reading.signal_quality,
bssid_count: n,
verdict,
})
}
}
有界上下文 3:感知输出(通用领域)¶
领域服务:FrameBuilder
将 EnhancedSensingResult 转换为现有的 SensingUpdate 和 Esp32Frame 类型,以保持兼容性。
/// Converts multi-BSSID scan into Esp32Frame for downstream compatibility
pub struct FrameBuilder;
impl FrameBuilder {
pub fn to_esp32_frame(
registry: &BssidRegistry,
observations: &[BssidObservation],
) -> Esp32Frame {
let subcarrier_map = registry.subcarrier_map();
let n_sub = subcarrier_map.len();
let mut amplitudes = vec![0.0f64; n_sub];
let mut phases = vec![0.0f64; n_sub];
for obs in observations {
if let Some(idx) = registry.subcarrier_index(&obs.bssid) {
// Convert RSSI dBm to linear amplitude
amplitudes[idx] = 10.0f64.powf((obs.rssi_dbm + 100.0) / 20.0);
// Phase: encode channel as pseudo-phase (for downstream
// tools that expect phase data)
phases[idx] = (obs.channel as f64 / 48.0) * std::f64::consts::PI;
}
}
Esp32Frame {
magic: 0xC511_0002, // New magic for multi-BSSID frames
node_id: 0,
n_antennas: 1,
n_subcarriers: n_sub as u8,
freq_mhz: 2437, // Mixed; could use median
sequence: 0, // Set by caller
rssi: observations.iter()
.map(|o| o.rssi_dbm as i8)
.max()
.unwrap_or(-90),
noise_floor: -95,
amplitudes,
phases,
}
}
pub fn to_sensing_update(
result: &EnhancedSensingResult,
frame: &Esp32Frame,
registry: &BssidRegistry,
tick: u64,
) -> SensingUpdate {
let nodes: Vec<NodeInfo> = registry.subcarrier_map().iter()
.filter_map(|bssid| registry.get(bssid))
.enumerate()
.map(|(i, entry)| NodeInfo {
node_id: i as u8,
rssi_dbm: entry.stats.mean,
position: estimate_ap_position(entry),
amplitude: vec![frame.amplitudes.get(i).copied().unwrap_or(0.0)],
subcarrier_count: 1,
})
.collect();
SensingUpdate {
msg_type: "sensing_update".to_string(),
timestamp: chrono::Utc::now().timestamp_millis() as f64 / 1000.0,
source: format!("wifi:multi-bssid:{}", result.bssid_count),
tick,
nodes,
features: result.to_feature_info(),
classification: result.to_classification_info(),
signal_field: generate_enhanced_signal_field(result, tick),
}
}
}
3.3 模块结构¶
v2/crates/wifi-densepose-wifiscan/
├── Cargo.toml
└── src/
├── lib.rs # Public API, re-exports
├── domain/
│ ├── mod.rs
│ ├── bssid.rs # BssidId, BssidObservation, BandType, RadioType
│ ├── registry.rs # BssidRegistry aggregate, BssidEntry entity
│ ├── frame.rs # MultiApFrame value object
│ └── result.rs # EnhancedSensingResult, PreliminaryReading
├── port/
│ ├── mod.rs
│ ├── scan_port.rs # WlanScanPort trait
│ └── sink_port.rs # SensingOutputPort trait
├── adapter/
│ ├── mod.rs
│ ├── netsh_scanner.rs # NetshBssidScanner (Tier 1)
│ ├── wlanapi_scanner.rs # WlanApiBssidScanner (Tier 2, feature-gated)
│ └── frame_builder.rs # FrameBuilder (to Esp32Frame / SensingUpdate)
├── pipeline/
│ ├── mod.rs
│ ├── config.rs # WindowsWifiConfig
│ ├── predictive_gate.rs # PredictiveLayer wrapper for multi-BSSID
│ ├── attention_weight.rs # AttentionSubcarrierWeighter for BSSIDs
│ ├── spatial_correlator.rs # GNN-based BSSID correlation
│ ├── motion_estimator.rs # Multi-AP motion/presence estimation
│ ├── breathing.rs # CoarseBreathingExtractor
│ ├── quality_gate.rs # ruQu VitalCoherenceGate
│ ├── fingerprint.rs # ModernHopfield posture fingerprinting
│ ├── drift_monitor.rs # Per-BSSID DriftDetector
│ ├── embedding.rs # BssidEmbedding (SONA micro-LoRA per-BSSID)
│ └── pipeline.rs # WindowsWifiPipeline orchestrator
├── application/
│ ├── mod.rs
│ └── scan_scheduler.rs # ScanScheduler service
└── error.rs # WifiScanError type
3.4 Cargo.toml 依赖¶
[package]
name = "wifi-densepose-wifiscan"
version = "0.1.0"
edition = "2021"
[features]
default = []
wlanapi = ["windows-sys"] # Tier 2: native WLAN API
full = ["wlanapi"]
[dependencies]
# Internal
wifi-densepose-signal = { path = "../wifi-densepose-signal" }
# RuVector (vendored)
ruvector-nervous-system = { path = "../../../../vendor/ruvector/crates/ruvector-nervous-system" }
ruvector-attention = { path = "../../../../vendor/ruvector/crates/ruvector-attention" }
ruvector-gnn = { path = "../../../../vendor/ruvector/crates/ruvector-gnn" }
ruvector-coherence = { path = "../../../../vendor/ruvector/crates/ruvector-coherence" }
ruvector-temporal-tensor = { path = "../../../../vendor/ruvector/crates/ruvector-temporal-tensor" }
ruvector-core = { path = "../../../../vendor/ruvector/crates/ruvector-core" }
ruqu = { path = "../../../../vendor/ruvector/crates/ruQu" }
sona = { path = "../../../../vendor/ruvector/crates/sona" }
# Async runtime
tokio = { workspace = true }
async-trait = "0.1"
# Serialization
serde = { workspace = true }
serde_json = { workspace = true }
# Logging
tracing = { workspace = true }
# Time
chrono = "0.4"
# Windows native API (Tier 2, optional)
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.52", features = [
"Win32_NetworkManagement_WiFi",
"Win32_Foundation",
], optional = true }
4. 信号处理流水线详情¶
4.1 BSSID 到子载波的映射¶
Visible BSSIDs (23):
┌──────────────────┬─────┬──────┬──────┬─────────┐
│ BSSID (MAC) │ Ch │ Band │ RSSI │ SubIdx │
├──────────────────┼─────┼──────┼──────┼─────────┤
│ a6:aa:c3:52:1b:28│ 11 │ 2.4G │ -2dBm│ 0 │
│ 82:cd:d6:d6:c3:f5│ 8 │ 2.4G │ -1dBm│ 1 │
│ 16:0a:c5:39:e3:5d│ 5 │ 2.4G │-16dBm│ 2 │
│ 16:27:f5:b2:6b:ae│ 8 │ 2.4G │-17dBm│ 3 │
│ 10:27:f5:b2:6b:ae│ 8 │ 2.4G │-22dBm│ 4 │
│ c8:9e:43:47:a1:3f│ 3 │ 2.4G │-40dBm│ 5 │
│ 90:aa:c3:52:1b:28│ 11 │ 2.4G │ -2dBm│ 6 │
│ ... │ ... │ ... │ ... │ ... │
│ 92:aa:c3:52:1b:20│ 36 │ 5G │ -6dBm│ 20 │
│ c8:9e:43:47:a1:40│ 48 │ 5G │-78dBm│ 21 │
│ ce:9e:43:47:a1:40│ 48 │ 5G │-82dBm│ 22 │
└──────────────────┴─────┴──────┴──────┴─────────┘
Mapping rule: sorted by first-seen time (stable ordering).
New BSSIDs get the next available subcarrier index.
BSSIDs not seen for >30s are expired and their index recycled.
4.2 空间分集:为什么多 BSSID 有效¶
┌────[AP1: ch3]
│ │
body │ │ path A (partially blocked)
┌───┐ │ │
│ │──┤ ▼
│ P │ │ ┌──────────┐
│ │──┤ │ WiFi │
└───┘ │ │ Adapter │
│ │ (BE201) │
┌──────┤ └──────────┘
│ │ ▲
[AP2: ch11] │ │ path B (unobstructed)
│ │
└────[AP3: ch36]
│ path C (reflected off wall)
Person P attenuates path A by 3-8 dB, while paths B and C
are unaffected. This differential is the multi-BSSID body signal.
At different body positions/orientations, different AP combinations
show attenuation → spatial diversity ≈ pseudo-subcarrier diversity.
4.3 RSSI 到幅度的转换¶
/// Convert RSSI dBm to linear amplitude (normalized)
/// RSSI range: -100 dBm (noise) to -20 dBm (very strong)
fn rssi_to_linear(rssi_dbm: f64) -> f64 {
// Map -100..0 dBm to 0..1 linear scale
// Using 10^((rssi+100)/20) gives log-scale amplitude
10.0f64.powf((rssi_dbm + 100.0) / 20.0)
}
/// Convert linear amplitude back to dBm
fn linear_to_rssi(amplitude: f64) -> f64 {
20.0 * amplitude.max(1e-10).log10() - 100.0
}
4.4 伪相位编码¶
由于 RSSI 不提供相位信息,我们将信道和频段编码为伪相位,供下游工具使用:
/// Encode BSSID channel/band as pseudo-phase
/// This preserves frequency-group identity for the GNN correlator
fn encode_pseudo_phase(channel: u8, band: BandType) -> f64 {
let band_offset = match band {
BandType::Band2_4GHz => 0.0,
BandType::Band5GHz => std::f64::consts::PI,
BandType::Band6GHz => std::f64::consts::FRAC_PI_2,
};
// Spread channels across [0, PI) within each band
let ch_phase = (channel as f64 / 48.0) * std::f64::consts::FRAC_PI_2;
band_offset + ch_phase
}
5. RuVector 集成映射¶
5.1 Crate 到阶段映射¶
| 流水线阶段 | RuVector Crate | 具体类型 | 用途 |
|---|---|---|---|
| Predictive Gate | ruvector-nervous-system |
PredictiveLayer |
RMS 残差门控(阈值 0.05);抑制没有由人体引起变化的扫描 |
| Attention Weight | ruvector-attention |
ScaledDotProductAttention |
查询=呼吸方差剖面,键=每个 BSSID 的方差,值=幅度;输出每个 BSSID 的重要性权重 |
| Spatial Correlator | ruvector-gnn |
RuvectorLayer + LayerNorm |
BSSID 相关图;单层消息传递识别共变 BSSID 簇 |
| Breathing Extraction | ruvector-nervous-system |
OscillatoryRouter |
0.15 Hz 振荡器与加权 BSSID 方差中最强的呼吸分量相位锁定 |
| Fingerprint Matching | ruvector-nervous-system |
ModernHopfield |
存储 4 个模板:空房间、站立、坐姿、行走;指数容量检索 |
| Signal Quality | ruvector-coherence |
SpectralCoherenceScore |
BSSID 相关图的频谱间隙;间隙越大 = 人体信号越干净 |
| Quality Gate | ruQu |
FilterPipeline + AdaptiveThresholds |
三滤波器 PERMIT/DENY/DEFER;使用 Welford/EMA 自调阈值 |
| Drift Monitor | ruQu |
DriftDetector |
每个 BSSID 的基线跟踪;5 种剖面(Stable/Linear/StepChange/Oscillating/VarianceExpansion) |
| Environment Adapt | sona |
SonaEngine |
按部署的微 LoRA 自适应,用于注意力权重和滤波器参数 |
| Tiered Storage | ruvector-temporal-tensor |
TieredStore |
8 位热 / 5 位温 / 3 位冷;23 个 BSSID × 1024 个样本 ≈ 24 KB 热数据 |
| Pattern Search | ruvector-core |
VectorDB (HNSW) |
BSSID 指纹最近邻查找(1000 个模板 <1ms) |
5.2 数据量估算¶
| 指标 | Tier 1(netsh) | Tier 2(wlanapi) |
|---|---|---|
| 每次扫描的 BSSID 数 | 23 | 23 |
| 扫描速率 | 2 Hz | 20 Hz |
| 样本/秒 | 46 | 460 |
| 字节/秒(原始) | 184 B | 1,840 B |
| 环形缓冲区内存(1024 个样本 × 23 个 BSSID × 8 字节) | 188 KB | 188 KB |
| PredictiveLayer 节省 | 80-95% 被抑制 | 90-99% 被抑制 |
| 净处理速率 | 2-9 帧/秒 | 2-46 帧/秒 |
6. 预期保真度改进¶
6.1 量化目标¶
| 指标 | 当前(1 个 RSSI) | Tier 1(多 BSSID) | Tier 2(+ 原生 API) |
|---|---|---|---|
| 存在检测准确率 | ~70%(阈值) | ~88%(多 AP 注意力) | ~93%(时间 + 空间) |
| 存在检测延迟 | 500ms | 500ms | 50ms |
| 运动级别分类 | 2 级 | 4 级(静态/极小/中等/活跃) | 4 级 + 方向 |
| 房间级定位 | 无 | 粗略(最近 AP 簇) | 中等(3-AP 三边测量) |
| 呼吸率检测 | 无 | 边缘(0.3 置信度) | 一般(0.5-0.6 置信度) |
| 心率检测 | 无 | 无 | 无(心率需要 CSI) |
| 姿态分类 | 无 | 4 类(空房间/站立/坐姿/行走) | 4 类 + 置信度 |
| 环境漂移鲁棒性 | 无 | 良好(ruQu 自适应) | 良好(+ SONA 自适应) |
6.2 置信度分数校准¶
/// Signal quality as a function of BSSID count and variance spread
fn compute_signal_quality(
bssid_count: usize,
attention_weights: &[f32],
spectral_gap: f64,
) -> f64 {
// Factor 1: BSSID diversity (more APs = more spatial info)
let diversity = (bssid_count as f64 / 20.0).min(1.0);
// Factor 2: Attention concentration (body-sensitive BSSIDs dominate)
let max_weight = attention_weights.iter().copied().fold(0.0f32, f32::max);
let mean_weight = attention_weights.iter().sum::<f32>() / attention_weights.len() as f32;
let concentration = (max_weight / mean_weight.max(1e-6) - 1.0).min(5.0) as f64 / 5.0;
// Factor 3: Spectral gap (clean body signal separation)
let separation = spectral_gap.min(1.0);
// Combined quality
(diversity * 0.3 + concentration * 0.4 + separation * 0.3).clamp(0.0, 1.0)
}
7. 与感知服务器集成¶
7.1 修改后的数据源选择¶
// In main(), extend auto-detection:
let source = match args.source.as_str() {
"auto" => {
if probe_esp32(args.udp_port).await {
"esp32"
} else if probe_multi_bssid().await {
"wifi-enhanced" // NEW: multi-BSSID mode
} else if probe_windows_wifi().await {
"wifi" // Legacy single-RSSI
} else {
"simulate"
}
}
other => other,
};
// Start appropriate background task
match source {
"esp32" => {
tokio::spawn(udp_receiver_task(state.clone(), args.udp_port));
tokio::spawn(broadcast_tick_task(state.clone(), args.tick_ms));
}
"wifi-enhanced" => {
// NEW: multi-BSSID enhanced pipeline
tokio::spawn(enhanced_wifi_task(state.clone(), args.tick_ms));
}
"wifi" => {
tokio::spawn(windows_wifi_task(state.clone(), args.tick_ms));
}
_ => {
tokio::spawn(simulated_data_task(state.clone(), args.tick_ms));
}
}
7.2 增强型 WiFi 任务¶
async fn enhanced_wifi_task(state: SharedState, tick_ms: u64) {
let scanner: Box<dyn WlanScanPort> = {
#[cfg(feature = "wlanapi")]
{ Box::new(WlanApiBssidScanner::new().unwrap_or_else(|_| {
tracing::warn!("WLAN API unavailable, falling back to netsh");
Box::new(NetshBssidScanner)
})) }
#[cfg(not(feature = "wlanapi"))]
{ Box::new(NetshBssidScanner) }
};
let mut registry = BssidRegistry::new(32);
let mut pipeline = WindowsWifiPipeline::new(WindowsWifiConfig::default());
let mut interval = tokio::time::interval(Duration::from_millis(tick_ms));
let mut seq: u32 = 0;
info!("Enhanced WiFi multi-BSSID pipeline active (tick={}ms)", tick_ms);
loop {
interval.tick().await;
seq += 1;
let observations = match scanner.scan().await {
Ok(obs) => obs,
Err(e) => { warn!("Scan failed: {e}"); continue; }
};
registry.update(&observations);
let frame = FrameBuilder::to_esp32_frame(®istry, &observations);
// Run through RuVector-powered pipeline
let multi_frame = registry.to_multi_ap_frame();
let result = pipeline.process(&multi_frame);
let mut s = state.write().await;
s.source = format!("wifi-enhanced:{}", observations.len());
s.tick += 1;
let tick = s.tick;
let update = match result {
Some(r) => FrameBuilder::to_sensing_update(&r, &frame, ®istry, tick),
None => {
// Fallback: basic update from frame
let (features, classification) = extract_features_from_frame(&frame);
SensingUpdate {
msg_type: "sensing_update".into(),
timestamp: chrono::Utc::now().timestamp_millis() as f64 / 1000.0,
source: format!("wifi-enhanced:{}", observations.len()),
tick,
nodes: vec![],
features,
classification,
signal_field: generate_signal_field(
frame.rssi as f64, 1.0, 0.05, tick,
),
}
}
};
if let Ok(json) = serde_json::to_string(&update) {
let _ = s.tx.send(json);
}
s.latest_update = Some(update);
}
}
8. 性能考量¶
8.1 延迟预算¶
| 阶段 | Tier 1 延迟 | Tier 2 延迟 | 备注 |
|---|---|---|---|
| BSSID 扫描 | ~200ms (netsh) | ~5ms (wlanapi) | 进程启动 vs FFI |
| 注册表更新 | <1ms | <1ms | HashMap 查找 |
| PredictiveLayer 门控 | <10us | <10us | 23 元素 RMS |
| 注意力加权 | <50us | <50us | 23×64 矩阵乘法 |
| GNN 相关性 | <100us | <100us | 23 节点单层 |
| 运动估计 | <20us | <20us | 加权方差 |
| 呼吸提取 | <30us | <30us | 带通 + 峰值检测 |
| ruQu 质量门控 | <10us | <10us | 三次比较 |
| 指纹匹配 | <50us | <50us | Hopfield 检索 |
| 每 tick 总计 | ~200ms | ~5ms | 扫描主导 Tier 1 |
8.2 内存预算¶
| 组件 | 内存 |
|---|---|
| BssidRegistry(32 条目 × 历史) | ~264 KB |
| PredictiveLayer(32 元素) | <1 KB |
| 注意力权重 | ~8 KB |
| GNN 层 | ~12 KB |
| Hopfield(32 维,10 模板) | ~3 KB |
| TieredStore(256 KB 预算) | 256 KB |
| DriftDetector(32 实例) | ~32 KB |
| 总计 | ~576 KB |
9. 安全考量¶
- 不向 UI 暴露原始 BSSID 数据:仅广播聚合感知更新。单个 BSSID 的 MAC、SSID 和位置保留在服务端,以防止 WiFi 基础设施指纹识别。
- BSSID 匿名化:
NodeInfo.node_id使用顺序索引,而不是 MAC 地址。 - 仅本地处理:所有信号处理都在设备端进行。扫描数据不会对外传输。
- 扫描权限:
netsh wlan show networks不需要管理员权限。WlanGetNetworkBssList需要 WLAN 服务正在运行(Windows 默认如此)。
10. 替代方案¶
替代方案 1:仅单 AP RSSI 增强¶
在不使用多 BSSID 的情况下,通过更好的滤波和漂移检测改进当前单 RSSI 路径。
已拒绝:单个 RSSI 值缺乏空间多样性。无论多少时间滤波都无法从一维信号中恢复空间信息。多 BSSID 是实现有意义存在感知的最小可行路径。
替代方案 2:监听模式 / 数据包捕获¶
将 WiFi 适配器置于监听模式,以捕获带有每子载波 CSI 的原始 802.11 帧。
在 Windows 上已拒绝:监听模式需要专用驱动(nexmon、picoscenes),且仅适用于 Intel 适配器的 Linux。Windows NDIS 不暴露原始 CSI。Tier 3(Intel SDK)是 Windows 上获取 CSI 的正规路径。
替代方案 3:外部 USB WiFi 适配器¶
通过 WSL 在 Linux 上使用独立 USB 适配器进入监听模式。
已拒绝:增加硬件依赖、WSL USB 直通复杂性,并违背“通用设备、零配置”的价值主张。
替代方案 4:蓝牙 RSSI 增强¶
扫描 BLE 信标以获取额外空间观测。
暂缓:可补充多 BSSID,但会增加 BLE 扫描复杂性。属于未来增强,不是核心路径。
11. 后果¶
积极影响¶
- 10-20 倍数据提升:从 2 Hz 的 1 个 RSSI 到 2-20 Hz 的 23 个 BSSID
- 空间感知:不同 AP 提供不同的人体交互路径
- 复用现有流水线:
Esp32Frame和SensingUpdate保持不变;UI 无需修改即可工作 - 无需额外硬件:使用已存在的通用 WiFi 基础设施
- RuVector 组合:利用 8 个现有 crate;约 80% 的智能是预构建的
- 渐进增强:Tier 1 立即发布,Tier 2 通过功能标志添加
- 环境自适应:SONA + ruQu 按部署自调优
负面影响¶
- 仍然没有 CSI 相位:仅 RSSI 意味着无法检测心率,呼吸检测有限
- 依赖 AP 密度:可见 AP 越少 = 保真度下降(至少需要 3 个)
- 扫描延迟:Tier 1 的 netsh 较慢(约 200ms);实时需要 Tier 2 的 wlanapi
- AP 移动性:移动的 AP(手机热点)会产生虚假运动信号
- 跨平台:
wlanapi.dll仅限 Windows;Linux/macOS 需要单独适配器 - 新 crate:向 workspace 添加
wifi-densepose-wifiscan,增加编译范围
12. 实施路线图¶
阶段 1:Tier 1 基础(第 1 周)¶
- [x] 创建具有 DDD 模块结构的
wifi-densepose-wifiscancrate - [x] 实现
BssidId、BssidObservation、BandType、RadioType值对象 - [x] 实现带有环形缓冲历史和 Welford 统计的
BssidRegistry聚合 - [x] 实现
NetshBssidScanner适配器(解析netsh wlan show networks mode=bssid) - [x] 实现
MultiApFrame、EnhancedSensingResult、WlanScanPort、错误类型 - [x] 全部 42 个单元测试通过(解析器、领域类型、注册表、结果类型)
- [ ] 实现
FrameBuilder::to_esp32_frame()(多 BSSID → 伪 Esp32Frame) - [ ] 实现可配置间隔的
ScanScheduler - [ ] 集成测试:扫描 → 注册表 → 伪帧 → 现有感知流水线
- [ ] 将
enhanced_wifi_task接入感知服务器main()
阶段 2:RuVector 信号流水线(第 2-3 周)¶
- [ ] 为多 BSSID 实现
PredictiveLayer之上的PredictiveGate包装器 - [ ] 实现带有呼吸方差查询的
AttentionSubcarrierWeighter - [ ] 使用
RuvectorLayer相关图实现BssidCorrelator - [ ] 实现带加权方差的
MultiApMotionEstimator - [ ] 使用
OscillatoryRouter实现CoarseBreathingExtractor - [ ] 实现
VitalCoherenceGate(ruQu 三滤波器流水线) - [ ] 使用
ModernHopfield模板实现BssidFingerprintMatcher - [ ] 实现
WindowsWifiPipeline编排器 - [ ] 使用合成多 BSSID 数据的单元测试
阶段 3:Tier 2 + 自适应(第 4 周)¶
- [ ] 使用
windows-sysFFI 实现WlanApiBssidScanner - [ ] 基准测试:netsh 与 wlanapi 延迟
- [ ] 实现用于按部署学习的
SonaEnvironmentAdapter - [ ] 实现按 BSSID 的
DriftDetector数组 - [ ] 实现用于 BSSID 时间序列的
TieredStore包装器 - [ ] 性能基准测试(延迟预算验证)
- [ ] 在真实 Windows WiFi 上进行端到端集成测试
第 4 阶段:加固(第 5 周)¶
- [ ] 针对已知真值进行信号质量校准
- [ ] 置信度分数验证(存在/运动/呼吸)
- [ ] 输出消息中的 BSSID 匿名化
- [ ] 自适应扫描速率(检测到运动时加快)
- [ ] 文档和 API 参考
- [ ] 功能开关验证(
wlanapi开/关)
审查勘误(已应用)¶
以下问题是在针对随附的 RuVector 源代码进行代码审查时发现的,并已在本文 ADR 中修正:
| # | 问题 | 已应用的修复 |
|---|---|---|
| 1 | GnnLayer 在 ruvector-gnn 中不存在;实际导出为 RuvectorLayer |
将所有引用重命名为 RuvectorLayer |
| 2 | ScaledDotProductAttention 没有 .forward() 方法;实际 API 为 .compute(query, keys, values),参数为 &[&[f32]] 切片数组 |
更新 Stage 2 代码,使用正确参数类型调用 .compute() |
| 3 | SonaEngine::new(SonaConfig{...}) 不正确;实际构造函数为 SonaEngine::with_config(config),且 SonaConfig 使用 micro_lora_lr 而非 learning_rate |
已修正第 14 节中的构造函数和字段名 |
| 4 | apply_micro_lora 没有返回值;实际签名会写入 &mut [f32] 输出缓冲区 |
已修正为使用可变输出缓冲区模式 |
| 5 | TieredStore.put(&data) 缺少必需参数;实际签名:put(key, data, tier, tick) |
添加了 BlockKey、Tier 和 tick 参数 |
| 6 | WindowsWifiPipeline 被错误标记为“聚合根”;它实际上是领域服务/编排器 |
重新标记为“领域服务” |
审查中的未决事项(尚未处理):
- OscillatoryRouter 是为 gamma 频段(30-90 Hz)神经同步设计的;将其用于 0.15 Hz 的呼吸提取在语义上有些牵强。考虑替换为专用的 IIR 带通滤波器。
- BSSID 抖动/索引回收可能使 GNN 关联图失效;需要显式的失效逻辑。
- netsh 输出依赖于区域设置;解析器可能在非英文 Windows 上失败。考虑将基于位置的解析作为回退方案。
- 由于子进程启动的时序抖动,Tier 1 在 2 Hz 下的呼吸检测处于临界状态;呼吸功能应要求 Tier 2。
13. 测试策略¶
13.1 单元测试(TDD 伦敦学派)¶
#[cfg(test)]
mod tests {
// Domain: BssidRegistry
#[test]
fn registry_assigns_stable_subcarrier_indices();
#[test]
fn registry_expires_stale_bssids();
#[test]
fn registry_maintains_welford_stats();
// Adapter: NetshBssidScanner
#[test]
fn parse_bssid_scan_output_extracts_all_bssids();
#[test]
fn parse_bssid_scan_output_handles_multi_band();
#[test]
fn parse_bssid_scan_output_handles_empty_output();
// Pipeline: PredictiveGate
#[test]
fn predictive_gate_suppresses_static_environment();
#[test]
fn predictive_gate_transmits_body_caused_changes();
// Pipeline: MotionEstimator
#[test]
fn motion_estimator_detects_presence_from_multi_ap();
#[test]
fn motion_estimator_classifies_four_levels();
// Pipeline: BreathingExtractor
#[test]
fn breathing_extracts_rate_from_oscillating_bssid();
// Integration
#[test]
fn full_pipeline_produces_sensing_update();
#[test]
fn graceful_degradation_with_few_bssids();
}
13.2 集成测试¶
- 在 CI Windows runner 上执行真实
netsh扫描 - 使用模拟 BSSID 数据进行确定性流水线测试
- 基准测试:每个 tick 的处理延迟
14. 自定义 BSSID 嵌入与 Micro-LoRA(SONA)¶
14.1 原始 RSSI 向量的问题¶
原始 RSSI 值具有噪声、依赖设备且非平稳。AP1 在信道 3 上的 -50 dBm 读数不能直接与 AP2 在信道 36 上的 -50 dBm 读数比较(传播、天线增益和 PHY 不同)。将原始 RSSI 输入 RuVector 流水线会产生次优的注意力权重和指纹匹配。
14.2 解决方案:学习得到的 BSSID 嵌入¶
不使用原始 RSSI,而是使用 SONA 的 micro-LoRA 自适应学习一个每个 BSSID 的嵌入,以捕获每个 AP 的环境特征:
use sona::{SonaEngine, SonaConfig, TrajectoryBuilder};
/// Per-BSSID learned embedding that captures environmental signature
pub struct BssidEmbedding {
/// SONA engine for micro-LoRA parameter adaptation
sona: SonaEngine,
/// Per-BSSID embedding vectors (d_embed dimensions per BSSID)
embeddings: Vec<Vec<f32>>,
/// Embedding dimension
d_embed: usize,
}
impl BssidEmbedding {
pub fn new(max_bssids: usize, d_embed: usize) -> Self {
Self {
sona: SonaEngine::with_config(SonaConfig {
hidden_dim: d_embed,
embedding_dim: d_embed,
micro_lora_lr: 0.001,
ewc_lambda: 100.0, // Prevent forgetting previous environments
..Default::default()
}),
embeddings: vec![vec![0.0; d_embed]; max_bssids],
d_embed,
}
}
/// Encode a BSSID observation into a learned embedding
/// Combines: RSSI, channel, band, radio type, variance, history
pub fn encode(&self, entry: &BssidEntry) -> Vec<f32> {
let mut raw = vec![0.0f32; self.d_embed];
// Static features (learned via micro-LoRA)
raw[0] = rssi_to_linear(entry.stats.mean) as f32;
raw[1] = entry.stats.variance().sqrt() as f32;
raw[2] = channel_to_norm(entry.meta.channel);
raw[3] = band_to_feature(entry.meta.band);
raw[4] = radio_to_feature(entry.meta.radio_type);
// Temporal features (from ring buffer)
if entry.history.len() >= 4 {
raw[5] = entry.history.delta(1) as f32; // 1-step velocity
raw[6] = entry.history.delta(2) as f32; // 2-step velocity
raw[7] = entry.history.trend_slope() as f32;
}
// Apply micro-LoRA adaptation: raw → adapted
let mut adapted = vec![0.0f32; self.d_embed];
self.sona.apply_micro_lora(&raw, &mut adapted);
adapted
}
/// Train embeddings from outcome feedback
/// Called when presence/motion ground truth is available
pub fn train(&mut self, bssid_idx: usize, embedding: &[f32], quality: f32) {
let trajectory = self.sona.begin_trajectory(embedding.to_vec());
self.sona.end_trajectory(trajectory, quality);
// EWC++ prevents catastrophic forgetting of previous environments
}
}
14.3 Micro-LoRA 适配周期¶
Scan 1: Raw RSSI [AP1:-42, AP2:-58, AP3:-71, ...]
│
▼
BssidEmbedding.encode() → [e1, e2, e3, ...] (d_embed=16 per BSSID)
│
▼
AttentionSubcarrierWeighter (query=breathing_profile, key=embeddings)
│
▼
Pipeline produces: motion=0.7, breathing=16.2, quality=0.85
│
▼
User/system feedback: correct=true (person was present)
│
▼
BssidEmbedding.train(quality=0.85)
│
▼
SONA micro-LoRA updates embedding weights
EWC++ preserves prior environment learnings
│
▼
Scan 2: Same raw RSSI → BETTER embeddings → BETTER attention → BETTER output
14.4 自定义嵌入的优势¶
| 方面 | 原始 RSSI | 学习嵌入 |
|---|---|---|
| 设备归一化 | 否 | 是(micro-LoRA 按适配器适配) |
| AP 增益补偿 | 否 | 是(按 BSSID 学习) |
| 信道/频段编码 | 丢失 | 作为特征保留 |
| 时间动态 | 未捕获 | 速度 + 趋势特征 |
| 跨环境迁移 | 否 | EWC++ 保留学习成果 |
| 注意力质量 | 噪声大 | 干净(适配特征) |
| 指纹匹配 | 原始距离 | 语义上有意义的距离 |
14.5 与流水线阶段的集成¶
自定义嵌入在注意力和指纹阶段替换原始 RSSI:
// In WindowsWifiPipeline::process():
// Stage 2 (MODIFIED): Attention on embeddings, not raw RSSI
let bssid_embeddings: Vec<Vec<f32>> = frame.entries.iter()
.map(|entry| self.embedding.encode(entry))
.collect();
let weights = self.attention.forward(
&self.compute_breathing_query(),
&bssid_embeddings, // Learned embeddings, not raw RSSI
&litudes,
);
// Stage 7 (MODIFIED): Fingerprint on embedding space
let posture = self.fingerprint.classify_embedding(&bssid_embeddings);
实现状态(2026-02-28)¶
阶段 1:领域模型 -- 已完成¶
- 创建了
wifi-densepose-wifiscancrate,包含 DDD 限界上下文 MultiApFrame值对象,包含幅度、相位、方差、历史BssidRegistry聚合根,包含 Welford 运行统计(容量 32,30 秒过期)NetshBssidScanner适配器,解析netsh wlan show networks mode=bssid(56 个单元测试)EnhancedSensingResult输出类型,包含运动、呼吸、姿态、质量- 六边形架构:
WlanScanPorttrait 用于适配器抽象
阶段 2:信号智能流水线 -- 已完成¶
8 阶段纯 Rust 流水线,包含 125 个通过的测试:
| 阶段 | 模块 | 实现 |
|---|---|---|
| 1 | predictive_gate |
基于 EMA 的残差滤波器(替换 PredictiveLayer) |
| 2 | attention_weighter |
Softmax 点积注意力(替换 ScaledDotProductAttention) |
| 3 | correlator |
皮尔逊相关 + BFS 聚类(替换 RuvectorLayer GNN) |
| 4 | motion_estimator |
加权方差 + EMA 平滑 |
| 5 | breathing_extractor |
IIR 带通(0.1-0.5 Hz)+ 过零 |
| 6 | quality_gate |
三重滤波器门控(结构/偏移/证据),受 ruQu 启发 |
| 7 | fingerprint_matcher |
余弦相似度模板(替换 ModernHopfield) |
| 8 | orchestrator |
WindowsWifiPipeline 领域服务 |
性能:约 2.1M 帧/秒(debug),约 12M 帧/秒(release)。
阶段 3:服务器集成 -- 进行中¶
- 将
WindowsWifiPipeline接入wifi-densepose-sensing-server - Tier 2
WlanApiScanner异步适配器桩(升级到原生 WLAN API 的路径) - 扩展
SensingUpdate,增加增强运动、呼吸、姿态、质量字段
阶段 4:Tier 2 原生 WLAN API -- 计划中¶
- 原生
wlanapi.dllFFI,用于 10-20 Hz 扫描速率 - SONA 适配层,用于按环境调优
- 多环境基准测试
15. 参考资料¶
- IEEE 802.11bf WiFi 感知标准(2024)
- Adib, F. 等. "See Through Walls with WiFi!" SIGCOMM 2013
- Ali, K. 等. "Keystroke Recognition Using WiFi Signals" MobiCom 2015
- Halperin, D. 等. "Tool Release: Gathering 802.11n Traces with Channel State Information" ACM SIGCOMM CCR 2011
- Intel Wi-Fi 7 BE200/BE201 规格说明(2024)
- Microsoft WLAN API 文档:
WlanGetNetworkBssList、WlanScan - RuVector v2.0.4 crate 文档
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView