feat(sender): 设备指纹固定、/watch 实时刷新、中继连接与文件子协议上传
- 新增 PinStore:首次连接记录被控端签名指纹,变化时弹窗确认 - 新增 SignalingWatch:订阅 /watch,300ms 去抖后重拉设备列表 - 设置页新增"连接走信令中继",主控端按该开关走 ttstd_relay_start - 中继模式禁用投屏并提示原因,状态卡区分直连/中继 - 新增 ControlFileClient:通过 msgType=7 分片上传/列目录,文件页加入口 - NativeCore/Bridge 暴露 relayStart/relayStop/sendFileRequest
This commit is contained in:
1 parent
22bac28914
commit
a9ba4bb7bc
9 files changed
+752
-8
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
@@ -51,6 +52,24 @@ class SenderBridge {
|
||||
/// 事件形如 `{"type":8,"action":2,"text":""}`,`type` 是 msgType。
|
||||
Map<String, dynamic>? nextInboundEvent() => _native?.pollEvent();
|
||||
|
||||
/// 控制通道文件子协议(`msg_type=7`):发一条 JSON 请求并等响应。
|
||||
///
|
||||
/// FFI 那一层是阻塞的(等被控端响应),所以放到独立 isolate 里跑,
|
||||
/// 避免上传时把界面卡住几秒。
|
||||
Future<Map<String, dynamic>> sendFileRequest(Map<String, dynamic> request) async {
|
||||
if (_native == null) {
|
||||
throw StateError('当前平台没有原生控制通道');
|
||||
}
|
||||
return Isolate.run(() {
|
||||
final core = NativeCore();
|
||||
try {
|
||||
return core.fileRequest(request);
|
||||
} finally {
|
||||
core.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _handleVideoCall(MethodCall call) async {
|
||||
switch (call.method) {
|
||||
case 'windowClosed':
|
||||
@@ -186,12 +205,37 @@ class SenderBridge {
|
||||
Future<void> disconnect() async {
|
||||
final native = _native;
|
||||
if (native != null) {
|
||||
native.stopRelay();
|
||||
native.stopDemoServer();
|
||||
return;
|
||||
}
|
||||
await _invokeIgnoringMissing('disconnect');
|
||||
}
|
||||
|
||||
/// 通过信令服务器建立中继控制会话(跨网段用)。
|
||||
///
|
||||
/// 成功返回 null,失败返回原因。中继只承载控制帧,视频/音频仍需同网段直连。
|
||||
String? startRelay(DeviceInfo device, String signalingUrl) {
|
||||
final native = _native;
|
||||
if (native == null) return '中继需要桌面端原生 Core';
|
||||
if (device.id.trim().isEmpty) return '这台设备没有信令 id,无法走中继';
|
||||
if (signalingUrl.trim().isEmpty) return '没有配置信令服务器地址';
|
||||
return native.startRelay(signalingUrl.trim(), device.id.trim());
|
||||
}
|
||||
|
||||
void stopRelay() => _native?.stopRelay();
|
||||
|
||||
/// 当前控制通道是否走中继(读 Rust 侧状态,避免界面自己记状态)。
|
||||
bool get isRelayActive {
|
||||
final native = _native;
|
||||
if (native == null) return false;
|
||||
try {
|
||||
return native.demoStatus()['relay'] == true;
|
||||
} on Object {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sendControl(String type, Map<String, dynamic> payload) async {
|
||||
final native = _native;
|
||||
if (native != null) {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
/// 控制通道文件子协议(`msg_type=7`)的客户端。
|
||||
///
|
||||
/// 与 `FileClient`(HTTP `53317`)的区别:这里复用已加密的控制通道,
|
||||
/// 适合文件服务端口被防火墙拦掉、或只连了 relay 的场景。
|
||||
/// 协议是一问一答的 JSON:
|
||||
/// - `{"op":"prepare","body":"<{\"files\":[...]}>"}`
|
||||
/// - `{"op":"chunk",...,"dataB64":"<base64>"}`
|
||||
/// - `{"op":"progress","sessionId":...}` / `{"op":"cancel",...}` / `{"op":"list","path":...}`
|
||||
class ControlFileClient {
|
||||
ControlFileClient({required this.send});
|
||||
|
||||
/// 发一条请求并等响应;由调用方负责把它放到后台执行(FFI 调用是阻塞的)。
|
||||
final Future<Map<String, dynamic>> Function(Map<String, dynamic> request) send;
|
||||
|
||||
/// 单个分片大小:256 KiB。再大 base64 后单帧会超过控制通道的 1 MiB 上限附近,
|
||||
/// 再小则请求次数多、往返开销明显。
|
||||
static const int chunkSize = 256 * 1024;
|
||||
|
||||
/// 浏览被控端目录(返回被控端 `FileBrowser` 的原始结构)。
|
||||
Future<Map<String, dynamic>> list(String path) async {
|
||||
final response = await send({'op': 'list', 'path': path});
|
||||
_throwIfError(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
/// 上传本地文件到被控端 `file-inbox` 目录,返回被控端保存的文件名。
|
||||
Future<String> upload(
|
||||
String localPath, {
|
||||
void Function(int sent, int total)? onProgress,
|
||||
}) async {
|
||||
final file = File(localPath);
|
||||
if (!await file.exists()) {
|
||||
throw const ControlFileException('本地文件不存在');
|
||||
}
|
||||
final length = await file.length();
|
||||
final name = localPath.split(RegExp(r'[\\/]')).last;
|
||||
final fileId = 'f-${DateTime.now().microsecondsSinceEpoch}';
|
||||
|
||||
final prepared = await send({
|
||||
'op': 'prepare',
|
||||
// 被控端沿用 LocalSend 风格:body 是一段 JSON 字符串。
|
||||
'body': jsonEncode({
|
||||
'files': [
|
||||
{
|
||||
'id': fileId,
|
||||
'name': name,
|
||||
'size': length,
|
||||
'mime': 'application/octet-stream',
|
||||
// 没有 crypto 依赖,算不了摘要;被控端只在续传判断时用它。
|
||||
'sha256': '',
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
_throwIfError(prepared);
|
||||
final sessionId = prepared['sessionId']?.toString() ?? '';
|
||||
if (sessionId.isEmpty) throw const ControlFileException('被控端没有返回 sessionId');
|
||||
final tokens = prepared['tokens'];
|
||||
final token = tokens is Map ? tokens[fileId]?.toString() ?? '' : '';
|
||||
if (token.isEmpty) throw const ControlFileException('被控端拒绝了该文件(没有返回令牌)');
|
||||
|
||||
var offset = 0;
|
||||
final handle = await file.open();
|
||||
try {
|
||||
while (offset < length) {
|
||||
await handle.setPosition(offset);
|
||||
final bytes = await handle.read(math.min(chunkSize, length - offset));
|
||||
if (bytes.isEmpty) break;
|
||||
final ack = await send({
|
||||
'op': 'chunk',
|
||||
'sessionId': sessionId,
|
||||
'fileId': fileId,
|
||||
'token': token,
|
||||
'offset': offset,
|
||||
'dataB64': base64Encode(bytes),
|
||||
});
|
||||
_throwIfError(ack);
|
||||
offset += bytes.length;
|
||||
onProgress?.call(offset, length);
|
||||
}
|
||||
} on Object {
|
||||
// 传输中断时通知被控端清理会话,避免它一直占着临时文件。
|
||||
try {
|
||||
await send({'op': 'cancel', 'sessionId': sessionId});
|
||||
} on Object {
|
||||
// 取消失败也只能作罢:连接多半已经断了。
|
||||
}
|
||||
rethrow;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/// 查询会话进度(`files: [{fileId, received, total}]`)。
|
||||
Future<Map<String, dynamic>> progress(String sessionId) async {
|
||||
final response = await send({'op': 'progress', 'sessionId': sessionId});
|
||||
_throwIfError(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
static void _throwIfError(Map<String, dynamic> response) {
|
||||
final error = response['error'];
|
||||
if (error is String && error.isNotEmpty) {
|
||||
throw ControlFileException(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ControlFileException implements Exception {
|
||||
const ControlFileException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
@@ -125,6 +125,8 @@ class AppSettings {
|
||||
final int filePort;
|
||||
/// 被控端文件服务访问令牌,被控端主界面会显示。
|
||||
final String fileToken;
|
||||
/// 连接时是否走信令中继(跨网段)。中继只承载控制通道,不能投屏。
|
||||
final bool relayEnabled;
|
||||
|
||||
const AppSettings({
|
||||
this.signalingUrl = '',
|
||||
@@ -138,6 +140,7 @@ class AppSettings {
|
||||
this.bitrateMbps = 8,
|
||||
this.filePort = 53317,
|
||||
this.fileToken = '',
|
||||
this.relayEnabled = false,
|
||||
});
|
||||
|
||||
static const defaults = AppSettings();
|
||||
@@ -156,6 +159,7 @@ class AppSettings {
|
||||
int? bitrateMbps,
|
||||
int? filePort,
|
||||
String? fileToken,
|
||||
bool? relayEnabled,
|
||||
}) {
|
||||
return AppSettings(
|
||||
signalingUrl: signalingUrl ?? this.signalingUrl,
|
||||
@@ -169,6 +173,7 @@ class AppSettings {
|
||||
bitrateMbps: bitrateMbps ?? this.bitrateMbps,
|
||||
filePort: filePort ?? this.filePort,
|
||||
fileToken: fileToken ?? this.fileToken,
|
||||
relayEnabled: relayEnabled ?? this.relayEnabled,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -187,6 +192,7 @@ class AppSettings {
|
||||
bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(),
|
||||
filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(),
|
||||
fileToken: (json['fileToken'] ?? defaults.fileToken).toString(),
|
||||
relayEnabled: json['relayEnabled'] as bool? ?? defaults.relayEnabled,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,5 +208,6 @@ class AppSettings {
|
||||
'bitrateMbps': bitrateMbps,
|
||||
'filePort': filePort,
|
||||
'fileToken': fileToken,
|
||||
'relayEnabled': relayEnabled,
|
||||
};
|
||||
}
|
||||
@@ -94,11 +94,20 @@ class NativeCore {
|
||||
late final DartDemoStatusFn _demoStatus = _library
|
||||
.lookup<NativeFunction<NativeDemoStatusFn>>('ttstd_demo_status')
|
||||
.asFunction();
|
||||
late final DartRelayStartFn _relayStart = _library
|
||||
.lookup<NativeFunction<NativeRelayStartFn>>('ttstd_relay_start')
|
||||
.asFunction();
|
||||
late final DartRelayStopFn _relayStop = _library
|
||||
.lookup<NativeFunction<NativeRelayStopFn>>('ttstd_relay_stop')
|
||||
.asFunction();
|
||||
late final DartDemoSendControlFn _demoSendControl = _library
|
||||
.lookup<NativeFunction<NativeDemoSendControlFn>>('ttstd_demo_send_control')
|
||||
.asFunction();
|
||||
/// 老版本 Core 没有这个导出,缺失时降级成「没有上行事件」。
|
||||
late final DartEventNextFn? _eventNext = _resolveEventNext();
|
||||
late final DartFileRequestFn _fileRequest = _library
|
||||
.lookup<NativeFunction<NativeFileRequestFn>>('ttstd_file_request')
|
||||
.asFunction();
|
||||
late final DartDiscoveryStartFn _discoveryStart = _library
|
||||
.lookup<NativeFunction<NativeDiscoveryStartFn>>('ttstd_discovery_start')
|
||||
.asFunction();
|
||||
@@ -209,6 +218,42 @@ class NativeCore {
|
||||
|
||||
void stopDemoServer() => _demoStop();
|
||||
|
||||
/// 通过信令服务器建立中继控制会话(只承载控制帧,不支持投屏)。
|
||||
///
|
||||
/// 成功返回 null;失败返回可直接展示的原因。
|
||||
String? startRelay(String baseUrl, String peerId) {
|
||||
final urlBytes = utf8.encode(baseUrl);
|
||||
final peerBytes = utf8.encode(peerId);
|
||||
const capacity = 4096;
|
||||
final out = calloc<Uint8>(capacity);
|
||||
try {
|
||||
return _withUtf8(baseUrl, (urlPtr) {
|
||||
return _withUtf8(peerId, (peerPtr) {
|
||||
final written = _relayStart(
|
||||
urlPtr,
|
||||
urlBytes.length,
|
||||
peerPtr,
|
||||
peerBytes.length,
|
||||
out,
|
||||
capacity,
|
||||
);
|
||||
if (written < 0) return '中继启动失败(错误码 $written)';
|
||||
final text = utf8.decode(_copy(out, written));
|
||||
final decoded = jsonDecode(text);
|
||||
if (decoded is Map && decoded['ok'] == true) return null;
|
||||
if (decoded is Map && decoded['error'] != null) {
|
||||
return decoded['error'].toString();
|
||||
}
|
||||
return text;
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
}
|
||||
|
||||
void stopRelay() => _relayStop();
|
||||
|
||||
Map<String, dynamic> demoStatus() {
|
||||
final out = calloc<Uint8>(65536);
|
||||
try {
|
||||
@@ -244,6 +289,24 @@ class NativeCore {
|
||||
.asFunction();
|
||||
}
|
||||
|
||||
/// 文件子协议(msgType=7):把 JSON 请求发给被控端并返回响应。
|
||||
///
|
||||
/// **阻塞调用**(最长 5 秒等待被控端响应),界面侧必须放到独立 isolate 里执行。
|
||||
Map<String, dynamic> fileRequest(Map<String, dynamic> request) {
|
||||
final bytes = utf8.encode(jsonEncode(request));
|
||||
const capacity = 1 << 20;
|
||||
return _withBytes(bytes, (ptr) {
|
||||
final out = calloc<Uint8>(capacity);
|
||||
try {
|
||||
final written = _fileRequest(ptr, bytes.length, out, capacity);
|
||||
_check(written, 'ttstd_file_request');
|
||||
return jsonDecode(utf8.decode(_copy(out, written))) as Map<String, dynamic>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 启动同网段自动发现(UDP 41003 信标),幂等。
|
||||
bool startDiscovery({
|
||||
int controlPort = 41001,
|
||||
@@ -457,6 +520,13 @@ typedef NativeDemoStatusFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeEventNextFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartEventNextFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeFileRequestFn = Int32 Function(
|
||||
Pointer<Uint8>,
|
||||
UintPtr,
|
||||
Pointer<Uint8>,
|
||||
UintPtr,
|
||||
);
|
||||
typedef DartFileRequestFn = int Function(Pointer<Uint8>, int, Pointer<Uint8>, int);
|
||||
typedef NativeDemoSendControlFn = Int32 Function(
|
||||
Uint16, Uint8, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
@@ -469,3 +539,21 @@ typedef NativeDiscoveryDevicesFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDiscoveryDevicesFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeDiscoveryConnectFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDiscoveryConnectFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeRelayStartFn = Int32 Function(
|
||||
Pointer<Uint8>,
|
||||
UintPtr,
|
||||
Pointer<Uint8>,
|
||||
UintPtr,
|
||||
Pointer<Uint8>,
|
||||
UintPtr,
|
||||
);
|
||||
typedef DartRelayStartFn = int Function(
|
||||
Pointer<Uint8>,
|
||||
int,
|
||||
Pointer<Uint8>,
|
||||
int,
|
||||
Pointer<Uint8>,
|
||||
int,
|
||||
);
|
||||
typedef NativeRelayStopFn = Void Function();
|
||||
typedef DartRelayStopFn = void Function();
|
||||
@@ -0,0 +1,77 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// 设备指纹归档(TOFU pinning)。
|
||||
///
|
||||
/// 落盘位置与诊断日志一致:可执行文件所在目录优先,失败再退到当前目录/临时目录。
|
||||
/// 键是设备 id(拿不到时用 `ip:端口`),值是被控端公布的 `sha256:` 指纹。
|
||||
class PinStore {
|
||||
PinStore({this.fileName = 'ttstd_pinned_devices.json'});
|
||||
|
||||
final String fileName;
|
||||
final Map<String, String> _pins = <String, String>{};
|
||||
File? _file;
|
||||
|
||||
bool get isReady => _file != null;
|
||||
|
||||
String get path => _file?.path ?? '';
|
||||
|
||||
/// 读取已有记录;目录不可写时保持空空如也(只是这次运行不做持久化)。
|
||||
void load() {
|
||||
for (final directory in _directories()) {
|
||||
try {
|
||||
final candidate = File('${directory.path}${Platform.pathSeparator}$fileName');
|
||||
if (!candidate.existsSync()) {
|
||||
// 先写一次空表验证目录可写,避免后面 save 时才失败。
|
||||
candidate.writeAsStringSync('{}', flush: true);
|
||||
}
|
||||
final decoded = jsonDecode(candidate.readAsStringSync());
|
||||
if (decoded is Map) {
|
||||
_pins.clear();
|
||||
decoded.forEach((key, value) {
|
||||
if (key is String && value is String && value.isNotEmpty) {
|
||||
_pins[key] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
_file = candidate;
|
||||
return;
|
||||
} on Object {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String? pinOf(String key) => _pins[key];
|
||||
|
||||
void pin(String key, String fingerprint) {
|
||||
_pins[key] = fingerprint;
|
||||
_flush();
|
||||
}
|
||||
|
||||
void unpin(String key) {
|
||||
if (_pins.remove(key) != null) _flush();
|
||||
}
|
||||
|
||||
/// 两个指纹是否是同一个(忽略大小写、`sha256:` 前缀与分隔冒号)。
|
||||
static bool same(String left, String right) => normalize(left) == normalize(right);
|
||||
|
||||
static String normalize(String value) =>
|
||||
value.trim().toLowerCase().replaceFirst('sha256:', '').replaceAll(':', '');
|
||||
|
||||
void _flush() {
|
||||
final file = _file;
|
||||
if (file == null) return;
|
||||
try {
|
||||
file.writeAsStringSync(jsonEncode(_pins), flush: true);
|
||||
} on Object {
|
||||
// 落盘失败不影响本次运行:校验仍然按内存里的记录走。
|
||||
}
|
||||
}
|
||||
|
||||
static List<Directory> _directories() => <Directory>[
|
||||
File(Platform.resolvedExecutable).parent,
|
||||
Directory.current,
|
||||
Directory.systemTemp,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// 信令服务器 `WS /watch` 的客户端。
|
||||
///
|
||||
/// 服务器在连接建立后先推一条 `{"event":"snapshot","devices":[...]}`,之后推
|
||||
/// `online` / `offline` / `heartbeat`。这里只把事件翻译成「设备列表可能变了」,
|
||||
/// 具体拉取交给调用方:`online` 事件里没有完整设备信息(端口/指纹/分辨率),
|
||||
/// 与其在这里补一套字段解析,不如让调用方复用已有的 `/list` + 信标发现逻辑。
|
||||
class SignalingWatch {
|
||||
SignalingWatch({
|
||||
required this.signalingUrl,
|
||||
required this.onChanged,
|
||||
this.onStateChanged,
|
||||
});
|
||||
|
||||
/// 信令服务基地址(http/https),内部会换成 ws/wss。
|
||||
final String signalingUrl;
|
||||
|
||||
/// 设备列表可能发生变化(snapshot / online / offline)。
|
||||
final void Function() onChanged;
|
||||
|
||||
/// 连接状态变化,用于界面提示与诊断日志。
|
||||
final void Function(bool connected)? onStateChanged;
|
||||
|
||||
static const Duration _maxBackoff = Duration(seconds: 15);
|
||||
static const Duration _connectTimeout = Duration(seconds: 5);
|
||||
|
||||
WebSocket? _socket;
|
||||
StreamSubscription<dynamic>? _subscription;
|
||||
Timer? _reconnectTimer;
|
||||
Duration _backoff = const Duration(seconds: 1);
|
||||
bool _stopped = false;
|
||||
bool _connected = false;
|
||||
|
||||
bool get isConnected => _connected;
|
||||
|
||||
/// 把信令基地址换成 `/watch` 的 WebSocket 地址。
|
||||
///
|
||||
/// 支持带前缀的部署(`https://host/api/` → `wss://host/api/watch`)。
|
||||
static Uri? watchUri(String base) {
|
||||
final trimmed = base.trim();
|
||||
if (trimmed.isEmpty) return null;
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri == null || uri.host.isEmpty) return null;
|
||||
final scheme = switch (uri.scheme) {
|
||||
'https' || 'wss' => 'wss',
|
||||
'http' || 'ws' => 'ws',
|
||||
_ => null,
|
||||
};
|
||||
if (scheme == null) return null;
|
||||
final path = uri.path.endsWith('/') ? '${uri.path}watch' : '${uri.path}/watch';
|
||||
return uri.replace(scheme: scheme, path: path);
|
||||
}
|
||||
|
||||
void start() {
|
||||
_stopped = false;
|
||||
_backoff = const Duration(seconds: 1);
|
||||
unawaited(_connect());
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
if (_stopped) return;
|
||||
final uri = watchUri(signalingUrl);
|
||||
if (uri == null) {
|
||||
_scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final socket = await WebSocket.connect(uri.toString()).timeout(_connectTimeout);
|
||||
if (_stopped) {
|
||||
await socket.close();
|
||||
return;
|
||||
}
|
||||
_socket = socket;
|
||||
_backoff = const Duration(seconds: 1);
|
||||
_setConnected(true);
|
||||
_subscription = socket.listen(
|
||||
_handleMessage,
|
||||
onDone: _handleClosed,
|
||||
onError: (Object _) => _handleClosed(),
|
||||
cancelOnError: true,
|
||||
);
|
||||
} on Object {
|
||||
_scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleMessage(dynamic data) {
|
||||
if (data is! String) return;
|
||||
Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(data);
|
||||
} on FormatException {
|
||||
return;
|
||||
}
|
||||
if (decoded is! Map) return;
|
||||
final event = decoded['event']?.toString();
|
||||
if (event == 'snapshot' || event == 'online' || event == 'offline') {
|
||||
onChanged();
|
||||
}
|
||||
// heartbeat 不触发拉取:设备信息没变,只会白刷一遍 /list。
|
||||
}
|
||||
|
||||
void _handleClosed() {
|
||||
_subscription?.cancel();
|
||||
_subscription = null;
|
||||
_socket = null;
|
||||
_setConnected(false);
|
||||
_scheduleReconnect();
|
||||
}
|
||||
|
||||
void _setConnected(bool value) {
|
||||
if (_connected == value) return;
|
||||
_connected = value;
|
||||
onStateChanged?.call(value);
|
||||
}
|
||||
|
||||
void _scheduleReconnect() {
|
||||
if (_stopped) return;
|
||||
_reconnectTimer?.cancel();
|
||||
// 指数退避,避免信令服务器没启动时每秒重连一次。
|
||||
_reconnectTimer = Timer(_backoff, () {
|
||||
_backoff = _backoff * 2 > _maxBackoff ? _maxBackoff : _backoff * 2;
|
||||
unawaited(_connect());
|
||||
});
|
||||
}
|
||||
|
||||
void stop() {
|
||||
_stopped = true;
|
||||
_reconnectTimer?.cancel();
|
||||
_reconnectTimer = null;
|
||||
_subscription?.cancel();
|
||||
_subscription = null;
|
||||
final socket = _socket;
|
||||
_socket = null;
|
||||
_connected = false;
|
||||
if (socket != null) unawaited(socket.close());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user