新增 DeviceSseClient 订阅 /api/v1/client/sn/online/stream,收到状态变更后刷新设备列表;保留 30 秒轮询作为断线兜底,退避重连 1/2/4/8/16 秒,超过 6 次退化为 30 秒。
109 lines
2.9 KiB
Dart
109 lines
2.9 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import '../../../app/constants/app_constants.dart';
|
|
import '../../../core/storage/token_storage.dart';
|
|
|
|
/// 家属端设备在线状态 SSE 客户端。
|
|
///
|
|
/// 与小程序共用后端 `GET /api/v1/client/sn/online/stream`。
|
|
/// 收到事件后只通知调用方刷新设备列表,不在这里直接改 UI 状态。
|
|
class DeviceSseClient {
|
|
DeviceSseClient({required this.onStatusChanged});
|
|
|
|
final void Function() onStatusChanged;
|
|
|
|
HttpClient? _client;
|
|
bool _stopped = true;
|
|
int _retry = 0;
|
|
Timer? _retryTimer;
|
|
|
|
void start() {
|
|
if (!_stopped) return;
|
|
_stopped = false;
|
|
_retry = 0;
|
|
unawaited(_connect());
|
|
}
|
|
|
|
void stop() {
|
|
_stopped = true;
|
|
_retryTimer?.cancel();
|
|
_retryTimer = null;
|
|
_client?.close(force: true);
|
|
_client = null;
|
|
}
|
|
|
|
Future<void> _connect() async {
|
|
if (_stopped) return;
|
|
|
|
final token = TokenStorage.accessToken;
|
|
if (token == null || token.isEmpty) {
|
|
_scheduleReconnect();
|
|
return;
|
|
}
|
|
|
|
final client = HttpClient();
|
|
_client = client;
|
|
try {
|
|
final uri = Uri.parse('${AppConstants.kBaseUrl}v1/client/sn/online/stream');
|
|
final request = await client.getUrl(uri);
|
|
request.headers
|
|
..set(HttpHeaders.authorizationHeader, 'Bearer $token')
|
|
..set(HttpHeaders.acceptHeader, 'text/event-stream')
|
|
..set(HttpHeaders.cacheControlHeader, 'no-store');
|
|
|
|
final response = await request.close();
|
|
if (response.statusCode != HttpStatus.ok) {
|
|
response.drain<void>();
|
|
_scheduleReconnect();
|
|
return;
|
|
}
|
|
|
|
String event = '';
|
|
final data = StringBuffer();
|
|
final lines = response.transform(utf8.decoder).transform(const LineSplitter());
|
|
await for (final line in lines) {
|
|
if (_stopped) break;
|
|
if (line.isEmpty) {
|
|
_handleEvent(event, data.toString());
|
|
event = '';
|
|
data.clear();
|
|
continue;
|
|
}
|
|
if (line.startsWith('event:')) {
|
|
event = line.substring(6).trim();
|
|
} else if (line.startsWith('data:')) {
|
|
if (data.isNotEmpty) data.writeln();
|
|
data.write(line.substring(5).trimLeft());
|
|
}
|
|
}
|
|
} catch (_) {
|
|
// 网络异常统一走退避重连
|
|
} finally {
|
|
client.close(force: true);
|
|
if (identical(_client, client)) _client = null;
|
|
}
|
|
_scheduleReconnect();
|
|
}
|
|
|
|
void _handleEvent(String event, String data) {
|
|
if (event == 'ping') {
|
|
_retry = 0;
|
|
return;
|
|
}
|
|
if (event != 'device-online-status' || data.isEmpty) return;
|
|
onStatusChanged();
|
|
}
|
|
|
|
void _scheduleReconnect() {
|
|
if (_stopped || _retryTimer != null) return;
|
|
_retry += 1;
|
|
final seconds = _retry >= 6 ? 30 : 1 << (_retry - 1);
|
|
_retryTimer = Timer(Duration(seconds: seconds), () {
|
|
_retryTimer = null;
|
|
unawaited(_connect());
|
|
});
|
|
}
|
|
}
|