import 'dart:convert'; import 'package:fis_common/logger/logger.dart'; import 'package:fis_jsonrpc/services/notificationdecoder.dart'; import 'connection.dart'; import 'core/center.dart'; import 'core/interface/connection.dart'; import 'handler.dart'; /// WebSocket消息中心 class WsNotificationCenter extends NotificationCenter { String? _host; WsConnection? _connection; WsNotificationCenter() { NotificationDecoder.setup(); } @override IConnection get connection => _connection!; String get host => _host ?? ''; /// 设置主机地址 /// /// [host] 主机地址 void setHost(String host) { _host = host; } /// 注册消息处理器 /// /// [handler] 消息处理器 void register(NotificationHandler handler) { handlerDispatcher.register(handler); } @override void start() { logger.i("Start WsNotificationCenter"); _buildConnection(); super.start(); } @override void stop() { if (_connection == null) return; logger.i("Stop WsNotificationCenter"); super.stop(); } @override void process(String data) { final jsonMap = jsonDecode(data); final typeInt = jsonMap['NotificationType'] as int; logger.i('WsNotificationCenter received a message, type: $typeInt.'); final handler = handlerProvider.getHandler(typeInt); if (handler != null) { final message = NotificationDecoder.decode(jsonMap); handler.execute(message); logger.i('WsNotificationCenter message[type-$typeInt] handled.'); } } void _buildConnection() { if (_host == null || _host!.isEmpty) { throw Exception("WsNotificationCenter host is not valid."); } if (_connection == null) { _connection = WsConnection(_host!); } else { if (_connection!.host != _host) { _connection!.close(); _connection = WsConnection(_host!); } } } } enum WSType { Main, Consultation, QRCodeLogin, }