feat(discovery): 被控端免填 IP,UDP 信标自动发现
- Rust: 新增 discovery::beacon(UDP 41003),被动接收 offer、用包源地址作设备 IP、单播回 host;FFI 增加 ttstd_discovery_start/devices/connect/stop(ABI 3) - Android: 新增 HostBeacon 广播自身并解析 host 应答;ReceiverSession 在 host 为空时等信标再拨号;主界面移除 IP/信令输入框,改为显示发现状态 - Flutter: discover 优先取同网段信标结果并与信令合并去重;connect 先起监听再通知设备拨号;设备卡片标注「UDP 自动发现」 - 视频诊断: 缺少 SPS/PPS 的提示改为收到关键帧后才告警,避免刚接入就误报 - 文档: DEMO 增加发现流程、防火墙与模拟器 NAT 说明及实测截图
This commit is contained in:
1 parent
df2affa9e2
commit
5442dbff2c
13 files changed
+835
-74
No files matched your search
@@ -0,0 +1,340 @@
|
||||
//! 同网段自动发现(UDP 41003 信标)。
|
||||
//!
|
||||
//! 协议只有两种报文,都是单行 JSON:
|
||||
//!
|
||||
//! - `offer`:被控端周期性广播的设备自述(含 id/名称/端口/型号/分辨率)。
|
||||
//! - `host`:主控端对 offer 的单播应答(含主控端控制/媒体端口,可选 `connect` 请求)。
|
||||
//!
|
||||
//! 关键点:**双方都用「数据包的源地址」当作对方 IP**。
|
||||
//! 因此主控端不需要枚举/扫描本机所有网卡,被控端也不需要任何人手工填写主控端地址;
|
||||
//! 一次 UDP 往返就能让两端互相认识。广播由被控端发起,主控端只被动监听 + 单播回包,
|
||||
//! 所以主控端多网卡(有线 + 无线 + 虚拟网卡)时也不会漏收。
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::json::{self, JsonValue};
|
||||
|
||||
/// 信标 UDP 端口(与 Android 侧 `HostBeacon.PORT` 一致)。
|
||||
pub const BEACON_PORT: u16 = 41003;
|
||||
/// 协议标识,出现在每个报文的 `ttstd` 字段里。
|
||||
pub const PROTOCOL: &str = "disc/1";
|
||||
/// 设备超过该时长没有任何广播即从列表剔除。
|
||||
const DEVICE_TTL: Duration = Duration::from_secs(12);
|
||||
/// 单个对端的最小应答间隔,避免 offer 密集时回包风暴。
|
||||
const REPLY_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// 已发现的被控端。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BeaconDevice {
|
||||
pub device_id: String,
|
||||
pub name: String,
|
||||
pub ip: String,
|
||||
pub control_port: u16,
|
||||
pub media_port: u16,
|
||||
pub audio_port: u16,
|
||||
pub fingerprint: String,
|
||||
pub capabilities: Vec<String>,
|
||||
pub model: String,
|
||||
pub resolution: String,
|
||||
}
|
||||
|
||||
/// 解析被控端广播;`ip` 由调用方用数据包源地址填入。
|
||||
pub fn parse_offer(text: &str, ip: &str) -> Option<BeaconDevice> {
|
||||
let value = json::parse(text).ok()?;
|
||||
if value.get("ttstd").and_then(JsonValue::as_str) != Some(PROTOCOL) {
|
||||
return None;
|
||||
}
|
||||
if value.get("kind").and_then(JsonValue::as_str) != Some("offer") {
|
||||
return None;
|
||||
}
|
||||
Some(BeaconDevice {
|
||||
device_id: text_field(&value, "id").unwrap_or_else(|| ip.to_string()),
|
||||
name: text_field(&value, "name").unwrap_or_else(|| "Android 设备".to_string()),
|
||||
ip: ip.to_string(),
|
||||
control_port: port_field(&value, "ctrl").unwrap_or(41001),
|
||||
media_port: port_field(&value, "media").unwrap_or(41000),
|
||||
audio_port: port_field(&value, "audio").unwrap_or(41002),
|
||||
fingerprint: text_field(&value, "fp").unwrap_or_default(),
|
||||
capabilities: value
|
||||
.get("cap")
|
||||
.and_then(JsonValue::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(JsonValue::as_str)
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
model: text_field(&value, "model").unwrap_or_default(),
|
||||
resolution: text_field(&value, "res").unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 构造主控端应答报文。
|
||||
pub fn encode_host(connect: bool, control_port: u16, media_port: u16, audio_port: u16) -> String {
|
||||
let mut value = JsonValue::object();
|
||||
value.insert("ttstd", JsonValue::from(PROTOCOL));
|
||||
value.insert("kind", JsonValue::from("host"));
|
||||
value.insert("ctrl", JsonValue::from(control_port as u64));
|
||||
value.insert("media", JsonValue::from(media_port as u64));
|
||||
value.insert("audio", JsonValue::from(audio_port as u64));
|
||||
value.insert("connect", JsonValue::from(connect));
|
||||
value.encode()
|
||||
}
|
||||
|
||||
fn text_field(value: &JsonValue, key: &str) -> Option<String> {
|
||||
value
|
||||
.get(key)
|
||||
.and_then(JsonValue::as_str)
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn port_field(value: &JsonValue, key: &str) -> Option<u16> {
|
||||
let number = value.get(key).and_then(JsonValue::as_u64)?;
|
||||
if number == 0 || number > u16::MAX as u64 {
|
||||
return None;
|
||||
}
|
||||
Some(number as u16)
|
||||
}
|
||||
|
||||
struct Beacon {
|
||||
socket: UdpSocket,
|
||||
control_port: u16,
|
||||
media_port: u16,
|
||||
audio_port: u16,
|
||||
devices: Mutex<HashMap<String, (BeaconDevice, Instant)>>,
|
||||
replies: Mutex<HashMap<String, Instant>>,
|
||||
running: AtomicBool,
|
||||
}
|
||||
|
||||
static BEACON: OnceLock<Option<&'static Beacon>> = OnceLock::new();
|
||||
|
||||
/// 启动信标监听(幂等)。返回是否处于运行状态。
|
||||
pub fn start(control_port: u16, media_port: u16, audio_port: u16) -> bool {
|
||||
if let Some(existing) = BEACON.get() {
|
||||
return existing.is_some();
|
||||
}
|
||||
let created = match UdpSocket::bind(("0.0.0.0", BEACON_PORT)) {
|
||||
Ok(socket) => {
|
||||
let _ = socket.set_broadcast(true);
|
||||
let beacon: &'static Beacon = Box::leak(Box::new(Beacon {
|
||||
socket,
|
||||
control_port,
|
||||
media_port,
|
||||
audio_port,
|
||||
devices: Mutex::new(HashMap::new()),
|
||||
replies: Mutex::new(HashMap::new()),
|
||||
running: AtomicBool::new(true),
|
||||
}));
|
||||
beacon.spawn_receiver();
|
||||
Some(beacon)
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
let available = created.is_some();
|
||||
let _ = BEACON.set(created);
|
||||
available
|
||||
}
|
||||
|
||||
/// 停止接收(释放端口,供测试与退出使用)。
|
||||
pub fn stop() {
|
||||
if let Some(Some(beacon)) = BEACON.get() {
|
||||
beacon.running.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// 已发现设备列表 JSON,字段与信令 `/list` 的 devices 保持一致。
|
||||
pub fn devices_json() -> String {
|
||||
let Some(Some(beacon)) = BEACON.get() else {
|
||||
return "{\"devices\":[]}".to_string();
|
||||
};
|
||||
let mut root = JsonValue::object();
|
||||
let mut list = Vec::new();
|
||||
for device in beacon.snapshot() {
|
||||
let mut value = JsonValue::object();
|
||||
value.insert("deviceId", JsonValue::from(device.device_id.as_str()));
|
||||
value.insert("name", JsonValue::from(device.name.as_str()));
|
||||
value.insert("ip", JsonValue::from(device.ip.as_str()));
|
||||
value.insert("controlPort", JsonValue::from(device.control_port as u64));
|
||||
value.insert("mediaPort", JsonValue::from(device.media_port as u64));
|
||||
value.insert("audioPort", JsonValue::from(device.audio_port as u64));
|
||||
value.insert("fp", JsonValue::from(device.fingerprint.as_str()));
|
||||
value.insert(
|
||||
"cap",
|
||||
JsonValue::Array(device.capabilities.iter().map(JsonValue::from).collect()),
|
||||
);
|
||||
value.insert("model", JsonValue::from(device.model.as_str()));
|
||||
value.insert("res", JsonValue::from(device.resolution.as_str()));
|
||||
list.push(value);
|
||||
}
|
||||
root.insert("devices", JsonValue::Array(list));
|
||||
root.encode()
|
||||
}
|
||||
|
||||
/// 通知指定设备:主控端已就绪,请拨号接入。
|
||||
pub fn connect(ip: &str) -> bool {
|
||||
let Some(Some(beacon)) = BEACON.get() else {
|
||||
return false;
|
||||
};
|
||||
let trimmed = ip.trim();
|
||||
if trimmed.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Ok(mut addresses) = (trimmed, BEACON_PORT).to_socket_addrs() else {
|
||||
return false;
|
||||
};
|
||||
let Some(address) = addresses.next() else {
|
||||
return false;
|
||||
};
|
||||
// 连发三次,抵消单次丢包。
|
||||
for attempt in 0..3 {
|
||||
beacon.send_host(address, true);
|
||||
if attempt < 2 {
|
||||
thread::sleep(Duration::from_millis(80));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
impl Beacon {
|
||||
fn spawn_receiver(self: &'static Beacon) {
|
||||
thread::spawn(move || {
|
||||
let mut buffer = [0u8; 4096];
|
||||
while self.running.load(Ordering::Relaxed) {
|
||||
match self.socket.recv_from(&mut buffer) {
|
||||
Ok((length, from)) => {
|
||||
let text = String::from_utf8_lossy(&buffer[..length]).to_string();
|
||||
self.handle(&text, from);
|
||||
}
|
||||
Err(_) => thread::sleep(Duration::from_millis(100)),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn handle(&self, text: &str, from: SocketAddr) {
|
||||
let source_ip = from.ip().to_string();
|
||||
let Some(device) = parse_offer(text, &source_ip) else {
|
||||
return;
|
||||
};
|
||||
{
|
||||
let mut devices = match self.devices.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
devices.insert(source_ip.clone(), (device, Instant::now()));
|
||||
}
|
||||
// 收到 offer 立即应答,让被控端即使「先开投屏」也能马上知道主控端地址;
|
||||
// 但同源 1 秒内只回一次,避免设备高频广播时互相刷包。
|
||||
let now = Instant::now();
|
||||
let allowed = {
|
||||
let mut replies = match self.replies.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
match replies.get(&source_ip) {
|
||||
Some(last) if now.duration_since(*last) < REPLY_INTERVAL => false,
|
||||
_ => {
|
||||
replies.insert(source_ip, now);
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
if allowed {
|
||||
self.send_host(from, false);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_host(&self, address: SocketAddr, connect: bool) {
|
||||
let payload = encode_host(
|
||||
connect,
|
||||
self.control_port,
|
||||
self.media_port,
|
||||
self.audio_port,
|
||||
);
|
||||
let _ = self.socket.send_to(payload.as_bytes(), address);
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> Vec<BeaconDevice> {
|
||||
let now = Instant::now();
|
||||
let mut devices = match self.devices.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
devices.retain(|_, (_, seen)| now.duration_since(*seen) < DEVICE_TTL);
|
||||
let mut list: Vec<BeaconDevice> = devices.values().map(|(device, _)| device.clone()).collect();
|
||||
list.sort_by(|left, right| left.ip.cmp(&right.ip));
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn offer_is_parsed_and_source_ip_wins() {
|
||||
let raw = r#"{"ttstd":"disc/1","kind":"offer","id":"uuid-1","name":"客厅手机",
|
||||
"model":"Pixel 8","res":"1920x1080","ctrl":41001,"media":41000,"audio":41002,
|
||||
"fp":"","cap":["h264","opus"]}"#;
|
||||
let device = parse_offer(raw, "192.168.1.23").expect("应当解析成功");
|
||||
assert_eq!(device.ip, "192.168.1.23");
|
||||
assert_eq!(device.name, "客厅手机");
|
||||
assert_eq!(device.control_port, 41001);
|
||||
assert!(device.capabilities.contains(&"h264".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_packets_are_ignored() {
|
||||
assert!(parse_offer(r#"{"ttstd":"disc/1","kind":"host"}"#, "1.2.3.4").is_none());
|
||||
assert!(parse_offer("not json", "1.2.3.4").is_none());
|
||||
assert!(parse_offer(r#"{"ttstd":"other","kind":"offer"}"#, "1.2.3.4").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_packet_carries_ports_and_connect_flag() {
|
||||
let text = encode_host(true, 41001, 41000, 41002);
|
||||
let value = json::parse(&text).expect("应当是合法 JSON");
|
||||
assert_eq!(value.get("kind").and_then(JsonValue::as_str), Some("host"));
|
||||
assert_eq!(value.get("connect").and_then(JsonValue::as_bool), Some(true));
|
||||
assert_eq!(value.get("ctrl").and_then(JsonValue::as_u64), Some(41001));
|
||||
}
|
||||
|
||||
/// 端到端:设备发出的 offer 应当收到带端口的 host 应答。
|
||||
#[test]
|
||||
fn beacon_replies_to_offer_with_source_routing() {
|
||||
if !start(41001, 41000, 41002) {
|
||||
// 端口被占用(例如主程序正在运行)时跳过,避免干扰交互式调试。
|
||||
return;
|
||||
}
|
||||
let device = UdpSocket::bind(("127.0.0.1", 0)).expect("设备端 socket");
|
||||
device
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("设置超时");
|
||||
let offer = r#"{"ttstd":"disc/1","kind":"offer","id":"uuid-9","name":"测试机",
|
||||
"ctrl":41001,"media":41000,"audio":41002,"cap":["h264"]}"#;
|
||||
device
|
||||
.send_to(
|
||||
offer.as_bytes(),
|
||||
("127.0.0.1", BEACON_PORT),
|
||||
)
|
||||
.expect("发送 offer");
|
||||
|
||||
let mut buffer = [0u8; 1024];
|
||||
let (length, _) = device.recv_from(&mut buffer).expect("应当收到 host 应答");
|
||||
let text = String::from_utf8_lossy(&buffer[..length]).to_string();
|
||||
let value = json::parse(&text).expect("应答应当是 JSON");
|
||||
assert_eq!(value.get("kind").and_then(JsonValue::as_str), Some("host"));
|
||||
assert_eq!(value.get("ctrl").and_then(JsonValue::as_u64), Some(41001));
|
||||
|
||||
let listed = devices_json();
|
||||
assert!(listed.contains("uuid-9"), "设备应当出现在列表里:{listed}");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod beacon;
|
||||
pub mod device;
|
||||
pub mod mdns;
|
||||
pub mod signaling;
|
||||
|
||||
Reference in new issue
Block a user