232 lines
8.2 KiB
Dart
232 lines
8.2 KiB
Dart
|
|
import 'dart:async';
|
|||
|
|
import 'dart:convert';
|
|||
|
|
import 'dart:io';
|
|||
|
|
import 'dart:math';
|
|||
|
|
|
|||
|
|
import 'package:flutter/foundation.dart';
|
|||
|
|
import 'package:xml/xml.dart';
|
|||
|
|
|
|||
|
|
import '../domain/entities/onvif_camera.dart';
|
|||
|
|
import 'lan_interface_selector.dart';
|
|||
|
|
|
|||
|
|
/// 原生实现 ONVIF WS-Discovery。
|
|||
|
|
///
|
|||
|
|
/// 关键点:向组播 239.255.255.250:3702 发 Probe,并且**从本机每一块网卡各发一份**
|
|||
|
|
/// (外加向该网段的定向广播 x.x.x.255 各发一份)。这样无论默认路由落在 WiFi/移动
|
|||
|
|
/// 还是以太网,总有一份 Probe 会从摄像头真正所在的那块网卡出去,摄像头收到后
|
|||
|
|
/// 会用 ProbeMatch 把它的真实 device_service 地址(含正确端口/路径)回给我们,
|
|||
|
|
/// 从根上避免"退化成盲扫猜端口"。
|
|||
|
|
///
|
|||
|
|
/// 不依赖第三方 onvif 包,便于完全掌控"搜索中 / 未发现"等提示链路。
|
|||
|
|
class OnvifDiscoveryService {
|
|||
|
|
static const String _multicastAddr = '239.255.255.250';
|
|||
|
|
static const int _multicastPort = 3702;
|
|||
|
|
|
|||
|
|
final Random _rnd = Random.secure();
|
|||
|
|
|
|||
|
|
/// 搜索局域网摄像头。[timeout] 为收集窗口时长。
|
|||
|
|
/// 返回去重后的设备列表(ip + xAddr)。搜索失败/超时返回空列表,不抛异常。
|
|||
|
|
Future<List<OnvifCamera>> discover({
|
|||
|
|
Duration timeout = const Duration(seconds: 8),
|
|||
|
|
}) async {
|
|||
|
|
final found = <String, OnvifCamera>{};
|
|||
|
|
final completer = Completer<List<OnvifCamera>>();
|
|||
|
|
final sockets = <_ProbeSocket>[];
|
|||
|
|
int rxCount = 0;
|
|||
|
|
|
|||
|
|
debugPrint('🔎 [ONVIF发现] 开始搜索 $_multicastAddr:$_multicastPort');
|
|||
|
|
|
|||
|
|
// 只挑“很可能是以太网”的网卡(本功能摄像头固定走 USB 以太网,
|
|||
|
|
// 排除 WiFi/移动网卡,避免向无关网段发 Probe / 扫错网段)。
|
|||
|
|
final lans = await selectLanInterfaces();
|
|||
|
|
|
|||
|
|
if (lans.isEmpty) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] ⚠️ 未识别到可用网卡(以太网可能未接入)');
|
|||
|
|
}
|
|||
|
|
for (final l in lans) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] 探测网卡 ${l.name} -> ${l.ip}');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
final multicast = InternetAddress(_multicastAddr);
|
|||
|
|
|
|||
|
|
// 在指定本地网卡上开一个套接字:先试 3702(能收到以组播方式回的 ProbeMatch),
|
|||
|
|
// 失败再回退临时端口。
|
|||
|
|
Future<RawDatagramSocket?> openSocket(InternetAddress local) async {
|
|||
|
|
for (final port in <int>[_multicastPort, 0]) {
|
|||
|
|
try {
|
|||
|
|
final s = await RawDatagramSocket.bind(local, port);
|
|||
|
|
s.broadcastEnabled = true;
|
|||
|
|
s.multicastLoopback = true;
|
|||
|
|
try {
|
|||
|
|
s.joinMulticast(multicast);
|
|||
|
|
} catch (e) {
|
|||
|
|
debugPrint(
|
|||
|
|
'🔎 [ONVIF发现] ${local.address} joinMulticast 失败: ${e.runtimeType}',
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
return s;
|
|||
|
|
} catch (_) {
|
|||
|
|
// 该端口不可用,尝试下一个
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 为每块网卡的每个 IPv4 各开一个 socket,并挂上共享监听
|
|||
|
|
Future<void> attach(InternetAddress local, String ipStr) async {
|
|||
|
|
final s = await openSocket(local);
|
|||
|
|
if (s == null) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] ⚠️ $ipStr 上无法建立套接字');
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
// 计算该 /24 的定向广播地址(x.x.x.255)
|
|||
|
|
String? broadcast;
|
|||
|
|
final seg = ipStr.split('.');
|
|||
|
|
if (seg.length == 4) broadcast = '${seg[0]}.${seg[1]}.${seg[2]}.255';
|
|||
|
|
sockets.add(_ProbeSocket(s, ipStr, broadcast));
|
|||
|
|
|
|||
|
|
s.listen((event) {
|
|||
|
|
if (event != RawSocketEvent.read) return;
|
|||
|
|
final dg = s.receive();
|
|||
|
|
if (dg == null) return;
|
|||
|
|
rxCount++;
|
|||
|
|
try {
|
|||
|
|
final xmlStr = utf8.decode(dg.data, allowMalformed: true);
|
|||
|
|
final cam = _parseProbeMatch(xmlStr, dg.address.address);
|
|||
|
|
debugPrint(
|
|||
|
|
'🔎 [ONVIF发现] 收到回应 from ${dg.address.address} · ${dg.data.length}字节 → ${cam?.displayName ?? "未匹配到XAddrs"}',
|
|||
|
|
);
|
|||
|
|
if (cam != null) found[cam.ip] = cam;
|
|||
|
|
} catch (e) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] 报文解析失败: $e');
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (lans.isEmpty) {
|
|||
|
|
await attach(InternetAddress.anyIPv4, InternetAddress.anyIPv4.address);
|
|||
|
|
} else {
|
|||
|
|
for (final l in lans) {
|
|||
|
|
await attach(l.address, l.ip);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (sockets.isEmpty) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] ❌ 没有任何可用网卡套接字');
|
|||
|
|
return const [];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
final probe = _buildProbeMessage();
|
|||
|
|
final probeBytes = utf8.encode(probe);
|
|||
|
|
|
|||
|
|
void sendProbe() {
|
|||
|
|
for (final ps in sockets) {
|
|||
|
|
try {
|
|||
|
|
final sent = ps.socket.send(probeBytes, multicast, _multicastPort);
|
|||
|
|
debugPrint('🔎 [ONVIF发现] 经 ${ps.ip} 发送组播 Probe 字节数=$sent');
|
|||
|
|
} catch (e) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] ${ps.ip} 发送组播 Probe 失败: $e');
|
|||
|
|
}
|
|||
|
|
// 额外向该网段定向广播一份,照顾不支持组播路由的环境
|
|||
|
|
final bc = ps.broadcast;
|
|||
|
|
if (bc != null) {
|
|||
|
|
try {
|
|||
|
|
ps.socket.send(probeBytes, InternetAddress(bc), _multicastPort);
|
|||
|
|
debugPrint('🔎 [ONVIF发现] 经 ${ps.ip} 定向广播 Probe → $bc');
|
|||
|
|
} catch (e) {
|
|||
|
|
debugPrint('🔎 [ONVIF发现] ${ps.ip} 定向广播失败: $e');
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
sendProbe();
|
|||
|
|
Timer(const Duration(milliseconds: 1000), sendProbe);
|
|||
|
|
Timer(const Duration(milliseconds: 2000), sendProbe);
|
|||
|
|
|
|||
|
|
Timer(timeout, () {
|
|||
|
|
for (final ps in sockets) {
|
|||
|
|
ps.socket.close();
|
|||
|
|
}
|
|||
|
|
debugPrint(
|
|||
|
|
'🔎 [ONVIF发现] 搜索结束:收到回应 $rxCount 条,发现摄像头 ${found.length} 个',
|
|||
|
|
);
|
|||
|
|
if (!completer.isCompleted) {
|
|||
|
|
completer.complete(found.values.toList());
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return completer.future;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
String _uuid() {
|
|||
|
|
final bytes = List<int>.generate(16, (_) => _rnd.nextInt(256));
|
|||
|
|
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
|||
|
|
return 'urn:uuid:${hex.substring(0, 8)}-${hex.substring(8, 12)}-'
|
|||
|
|
'${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
String _buildProbeMessage() {
|
|||
|
|
return '''<?xml version="1.0" encoding="UTF-8"?>
|
|||
|
|
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
|
|||
|
|
xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing"
|
|||
|
|
xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery"
|
|||
|
|
xmlns:dn="http://www.onvif.org/ver10/network/wsdl">
|
|||
|
|
<s:Header>
|
|||
|
|
<a:Action s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>
|
|||
|
|
<a:MessageID>${_uuid()}</a:MessageID>
|
|||
|
|
<a:To s:mustUnderstand="true">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>
|
|||
|
|
<d:Probe><d:Types>dn:NetworkVideoTransmitter</d:Types></d:Probe>
|
|||
|
|
</s:Header>
|
|||
|
|
<s:Body/>
|
|||
|
|
</s:Envelope>''';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
OnvifCamera? _parseProbeMatch(String xmlStr, String senderIp) {
|
|||
|
|
try {
|
|||
|
|
final doc = XmlDocument.parse(xmlStr);
|
|||
|
|
final xAddrNodes =
|
|||
|
|
doc
|
|||
|
|
.findAllElements('XAddrs')
|
|||
|
|
.map((e) => e.innerText.trim())
|
|||
|
|
.where((t) => t.isNotEmpty)
|
|||
|
|
.toList();
|
|||
|
|
if (xAddrNodes.isEmpty) return null;
|
|||
|
|
|
|||
|
|
// XAddrs 可能是空格分隔的多地址,优先取 http
|
|||
|
|
final allAddrs = xAddrNodes
|
|||
|
|
.expand((s) => s.split(RegExp(r'\s+')))
|
|||
|
|
.where((s) => s.startsWith('http'))
|
|||
|
|
.toList();
|
|||
|
|
final xAddr = allAddrs.isNotEmpty ? allAddrs.first : xAddrNodes.first;
|
|||
|
|
|
|||
|
|
final uri = Uri.parse(xAddr);
|
|||
|
|
final ip = uri.host.isNotEmpty ? uri.host : senderIp;
|
|||
|
|
final port = uri.hasPort ? uri.port : 80;
|
|||
|
|
|
|||
|
|
// 从 Scopes 里尽量提取型号(很多摄像头把 hw= / name= 放进 scope)
|
|||
|
|
String model = '';
|
|||
|
|
final scopes = doc
|
|||
|
|
.findAllElements('Scopes')
|
|||
|
|
.map((e) => e.innerText)
|
|||
|
|
.join(' ');
|
|||
|
|
final hwMatch = RegExp(r'hw=([^@\s]+)').firstMatch(scopes);
|
|||
|
|
if (hwMatch != null) {
|
|||
|
|
model = Uri.decodeComponent(hwMatch.group(1)!);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return OnvifCamera(ip: ip, port: port, xAddr: xAddr, model: model);
|
|||
|
|
} catch (_) {
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 一块网卡对应的探测套接字 + 该网卡身份/定向广播地址。
|
|||
|
|
class _ProbeSocket {
|
|||
|
|
final RawDatagramSocket socket;
|
|||
|
|
final String ip;
|
|||
|
|
final String? broadcast;
|
|||
|
|
_ProbeSocket(this.socket, this.ip, this.broadcast);
|
|||
|
|
}
|