From c284aefc7dcd423f8e5aacf8770d6ae92751bfb1 Mon Sep 17 00:00:00 2001 From: Songzex <2402265378@qq.com> Date: Sat, 21 Nov 2026 14:26:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=8E=B0=E5=9C=BA=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E5=9C=B0=E5=9D=80=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/languages/en-US.json | 25 ++ assets/languages/zh-CN.json | 25 ++ lib/core/di/injection.dart | 2 + lib/core/env/env_config.dart | 72 +++- lib/core/env/server_configuration.dart | 177 ++++++++++ lib/core/network/dio_client.dart | 25 +- .../data/infrastructure/mqtt_client_impl.dart | 68 ++-- .../mqtt/domain/models/mqtt_config.dart | 32 +- lib/core/network/mqtt/mqtt_manager.dart | 57 +++- lib/core/router/app_router.dart | 9 +- lib/core/router/route_paths.dart | 1 + lib/core/update/version_check_service.dart | 4 +- .../ai/presentation/bloc/ai_cubit.dart | 10 +- .../auth/presentation/bloc/auth_cubit.dart | 13 +- .../presentation/pages/login_page_v2.dart | 11 + .../impl/path_http_datasource_impl.dart | 4 +- .../home/presentation/pages/dj_page.dart | 11 +- .../widgets/map/geoserver_suzhou_layer.dart | 64 +++- .../widgets/map/testmap_pages.dart | 4 +- .../home/presentation/widgets/video.dart | 7 +- .../pages/machine_details_page.dart | 4 +- .../widgets/webrtc/webrtc_local_player.dart | 7 +- .../server_configuration_page.dart | 319 ++++++++++++++++++ .../widgets/robot_header_card.dart | 4 +- .../pages/system_settings_page.dart | 11 + test/server_configuration_test.dart | 301 +++++++++++++++++ 26 files changed, 1162 insertions(+), 105 deletions(-) create mode 100644 lib/core/env/server_configuration.dart create mode 100644 lib/features/server_configuration/presentation/server_configuration_page.dart create mode 100644 test/server_configuration_test.dart diff --git a/assets/languages/en-US.json b/assets/languages/en-US.json index 23ea7136..1fa4f6e4 100644 --- a/assets/languages/en-US.json +++ b/assets/languages/en-US.json @@ -1,4 +1,29 @@ { + "servers": { + "title": "Server configuration", + "help": "Enter a shared IP address or hostname. Each service accepts a port, host:port, or full address. Leave a field blank to use the address shown below it.", + "shared_host": "Shared IP or hostname", + "http": "HTTP backend", + "tcp": "TCP control", + "mqtt": "Business MQTT", + "advanced": "Advanced settings", + "webRtc": "WebRTC video", + "droneMqtt": "Drone MQTT", + "geoServer": "GeoServer", + "pathPlanning": "Path planning", + "ai": "AI analysis", + "update": "App updates", + "stationWeb": "Station website", + "relogin": "Saving changed addresses will require you to sign in again.", + "invalid_host": "Enter a valid IP address or hostname", + "invalid_address": "Check the protocol, host, and port (1–65535)", + "test_ports": "Test ports", + "reachable": "Port reachable · {address}", + "unreachable": "Port unreachable · {address}", + "save": "Save", + "saved": "Server configuration saved", + "save_failed": "Could not apply server configuration. Try again." + }, "legal": {"open_failed": "Unable to open the document. Please try again later."}, "device_task_control": { diff --git a/assets/languages/zh-CN.json b/assets/languages/zh-CN.json index d7b278eb..4e5f3915 100644 --- a/assets/languages/zh-CN.json +++ b/assets/languages/zh-CN.json @@ -1,4 +1,29 @@ { + "servers": { + "title": "服务器配置", + "help": "填写公共 IP 或域名。各服务可填端口、主机:端口或完整地址。留空使用下方显示的地址。", + "shared_host": "公共 IP 或域名", + "http": "HTTP 后端", + "tcp": "TCP 控制", + "mqtt": "业务 MQTT", + "advanced": "高级配置", + "webRtc": "WebRTC 视频", + "droneMqtt": "无人机 MQTT", + "geoServer": "GeoServer", + "pathPlanning": "路径规划", + "ai": "AI 分析", + "update": "App 更新", + "stationWeb": "电站网页", + "relogin": "保存新的服务地址后需要重新登录。", + "invalid_host": "请输入有效的 IP 或域名", + "invalid_address": "请检查协议、主机和端口(1–65535)", + "test_ports": "测试端口", + "reachable": "端口可达 · {address}", + "unreachable": "端口未连通 · {address}", + "save": "保存", + "saved": "服务器配置已保存", + "save_failed": "无法应用服务器配置,请重试" + }, "legal": {"open_failed": "暂时无法打开协议页面,请稍后重试。"}, "device_task_control": { diff --git a/lib/core/di/injection.dart b/lib/core/di/injection.dart index 57551fdd..9d568ec2 100644 --- a/lib/core/di/injection.dart +++ b/lib/core/di/injection.dart @@ -198,6 +198,7 @@ import '../network/mqtt/domain/repositories/mower_realtime_repository.dart'; import '../network/mqtt/data/repositories/drone_osd_repository_impl.dart'; import '../network/mqtt/data/repositories/task_message_repository_impl.dart'; import '../network/mqtt/data/repositories/mower_realtime_repository_impl.dart'; +import '../env/env_config.dart'; import '../router/app_router.dart'; import '../storage/impl/user_storage_impl.dart'; import '../storage/user_storage.dart'; @@ -248,6 +249,7 @@ Future init() async { /// 1.2 --- 本地存储 (LocalStorage) --- /// 1.2.1 SharedPreferences:本地存储库 final sharedPrefs = await SharedPreferences.getInstance(); + EnvConfig.loadServerConfiguration(sharedPrefs); sl.registerLazySingleton(() => sharedPrefs); /// 1.2.2 UserStorage:用户存储库 diff --git a/lib/core/env/env_config.dart b/lib/core/env/env_config.dart index 74fa9ae4..af344f3e 100644 --- a/lib/core/env/env_config.dart +++ b/lib/core/env/env_config.dart @@ -1,3 +1,9 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import 'server_configuration.dart'; + class EnvConfig { static const String environment = String.fromEnvironment( 'ENV', @@ -14,18 +20,62 @@ class EnvConfig { static const bool isProduction = environment == 'prod'; - // ─── 服务器 IP(测试/生产共用同一台机器) ─── - static const String serverHost = '1.95.137.212'; + static const _serverConfigurationKey = 'server_configuration_$environment'; + static ServerConfiguration _configuration = ServerConfiguration( + production: isProduction, + ); - // ─── TCP 控制长连接 ─── - static String get tcpIp => serverHost; - static int get tcpPort => isProduction ? 9001 : 59004; + static ServerConfiguration get serverConfiguration => _configuration; - // ─── HTTP 接口 ─── - static int get httpPort => isProduction ? 8081 : 59003; - static String get baseUrl => 'http://$serverHost:$httpPort'; + static void loadServerConfiguration(SharedPreferences preferences) { + try { + final saved = preferences.getString(_serverConfigurationKey); + if (saved != null) { + _configuration = ServerConfiguration.fromJson( + jsonDecode(saved) as Map, + production: isProduction, + ); + return; + } + } on FormatException { + // Malformed preferences fall back to the build's endpoints. + } on TypeError { + // Older or invalid preference values may have a different type. + } + _configuration = ServerConfiguration(production: isProduction); + } - // ─── MQTT(一方后端:任务消息 / 割草机实时状态,prod=1883 / test=59007)─── - // 注:第三方无人机 OSD(droneOsd,WebSocket 8083)不纳入环境管理,保持硬编码 - static int get mqttPort => isProduction ? 1883 : 59007; + static Future saveServerConfiguration( + SharedPreferences preferences, + ServerConfiguration configuration, + ) async { + final saved = await preferences.setString( + _serverConfigurationKey, + jsonEncode(configuration.toJson()), + ); + if (!saved) throw StateError('Unable to save server configuration'); + _configuration = configuration; + } + + static Uri address(ServerService service) => _configuration.address(service); + + static String baseAddress(ServerService service) => + address(service).toString().replaceFirst(RegExp(r'/+$'), ''); + + static String get tcpIp => address(ServerService.tcp).host; + static int get tcpPort => address(ServerService.tcp).port; + static String get baseUrl => baseAddress(ServerService.http); + + static String get webRtcStreamAuthority => + Uri(scheme: 'webrtc', host: address(ServerService.webRtc).host).authority; + + static Uri webRtcPlayAddress(Uri stream) { + final configured = address(ServerService.webRtc); + return stream.host == configured.host + ? configured + : ServerService.webRtc.defaultAddress( + production: isProduction, + commonHost: stream.host, + ); + } } diff --git a/lib/core/env/server_configuration.dart b/lib/core/env/server_configuration.dart new file mode 100644 index 00000000..5813cbcc --- /dev/null +++ b/lib/core/env/server_configuration.dart @@ -0,0 +1,177 @@ +enum ServerService { + http, + tcp, + mqtt, + webRtc, + droneMqtt, + geoServer, + pathPlanning, + ai, + update, + stationWeb; + + bool get isCore => this == http || this == tcp || this == mqtt; + + Uri defaultAddress({required bool production, required String commonHost}) { + return switch (this) { + http => Uri( + scheme: 'http', + host: commonHost, + port: production ? 8081 : 59003, + ), + tcp => Uri( + scheme: 'tcp', + host: commonHost, + port: production ? 9001 : 59004, + ), + mqtt => Uri( + scheme: 'mqtt', + host: commonHost, + port: production ? 1883 : 59007, + ), + webRtc => Uri( + scheme: 'http', + host: commonHost, + port: 1985, + path: '/rtc/v1/play/', + ), + droneMqtt => Uri.parse('ws://1.95.137.212:8083/mqtt'), + geoServer => Uri.parse('http://1.95.137.212:7900/geoserver'), + pathPlanning => Uri.parse('https://servicepathplan.satabot.com/api/path'), + ai => Uri.parse('http://1.95.137.212:30009'), + update => Uri.parse('http://8.159.134.0:8012/api/update/check'), + stationWeb => Uri.parse('https://pvs.satabot.com/'), + }; + } + + /// A port uses the shared host. An explicit address can use another host. + Uri resolve( + String input, { + required bool production, + required String commonHost, + }) { + final fallback = defaultAddress( + production: production, + commonHost: commonHost, + ); + if (input.isEmpty) return fallback; + + final port = int.tryParse(input); + if (port != null) { + if (port < 1 || port > 65535) throw const FormatException('Invalid port'); + return fallback.replace(host: commonHost, port: port); + } + + final url = input.contains('://') ? input : '${fallback.scheme}://$input'; + final address = Uri.tryParse(url); + final authority = url + .substring(url.indexOf('://') + 3) + .split(RegExp(r'[/#?]')) + .first; + if (address == null || + !ServerConfiguration.isHost(address.host) || + address.userInfo.isNotEmpty || + address.hasFragment || + address.hasQuery || + RegExp(r':0+$').hasMatch(authority)) { + throw const FormatException('Invalid server address'); + } + + final schemes = switch (this) { + tcp => const ['tcp'], + mqtt => const ['mqtt'], + droneMqtt => const ['ws', 'wss'], + _ => const ['http', 'https'], + }; + if (!schemes.contains(address.scheme) || + ((this == tcp || this == mqtt) && address.path.isNotEmpty)) { + throw const FormatException('Invalid protocol or path'); + } + + final effectivePort = address.hasPort || address.port != 0 + ? address.port + : switch (address.scheme) { + 'ws' => 80, + 'wss' => 443, + _ => fallback.port, + }; + if (effectivePort < 1 || effectivePort > 65535) { + throw const FormatException('Invalid port'); + } + return address.replace( + port: effectivePort, + path: address.path.isEmpty || address.path == '/' + ? fallback.path + : address.path, + ); + } +} + +class ServerConfiguration { + static const defaultHost = '1.95.137.212'; + + final String sharedHost; + final Map overrides; + final Map _addresses; + + ServerConfiguration._(this.sharedHost, this.overrides, this._addresses); + + factory ServerConfiguration({ + required bool production, + String sharedHost = '', + Map overrides = const {}, + }) { + final host = sharedHost.trim(); + if (host.isNotEmpty && !isHost(host)) { + throw const FormatException('Invalid shared host'); + } + final inputs = { + for (final entry in overrides.entries) + if (entry.value.trim().isNotEmpty) entry.key: entry.value.trim(), + }; + final effectiveHost = host.isEmpty ? defaultHost : host; + return ServerConfiguration._(host, Map.unmodifiable(inputs), { + for (final service in ServerService.values) + service: service.resolve( + inputs[service] ?? '', + production: production, + commonHost: effectiveHost, + ), + }); + } + + factory ServerConfiguration.fromJson( + Map json, { + required bool production, + }) => ServerConfiguration( + production: production, + sharedHost: json['host'] as String? ?? '', + overrides: { + for (final service in ServerService.values) + if (json[service.name] case final String input) service: input, + }, + ); + + Uri address(ServerService service) => _addresses[service]!; + + Map toJson() => { + if (sharedHost.isNotEmpty) 'host': sharedHost, + for (final entry in overrides.entries) entry.key.name: entry.value, + }; + + static bool isHost(String input) { + if (RegExp( + r'^[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9.])?$', + ).hasMatch(input)) { + return !input.contains('..'); + } + try { + final host = input.startsWith('[') && input.endsWith(']') + ? input.substring(1, input.length - 1) + : input; + return host.contains(':') && Uri.parseIPv6Address(host).length == 16; + } on FormatException { + return false; + } + } +} diff --git a/lib/core/network/dio_client.dart b/lib/core/network/dio_client.dart index 76b9f2e1..fa70c852 100644 --- a/lib/core/network/dio_client.dart +++ b/lib/core/network/dio_client.dart @@ -5,16 +5,30 @@ import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart'; class DioClient { + static const _requestBackend = 'requestBackend'; + static Dio create() { + final initialBaseUrl = HttpApiConsts.baseUrl; final dio = Dio( BaseOptions( - baseUrl: HttpApiConsts.baseUrl, + baseUrl: initialBaseUrl, connectTimeout: const Duration(seconds: 20), receiveTimeout: const Duration(seconds: 20), headers: {'Content-Type': 'application/json'}, ), ); + dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) { + final backend = HttpApiConsts.baseUrl; + if (options.baseUrl == initialBaseUrl) options.baseUrl = backend; + options.extra[_requestBackend] = backend; + handler.next(options); + }, + ), + ); + dio.interceptors.add( LogInterceptor( requestBody: true, @@ -37,7 +51,9 @@ class DioClient { }, onResponse: (response, handler) { - if (response.data is Map) { + if (response.requestOptions.extra[_requestBackend] == + HttpApiConsts.baseUrl && + response.data is Map) { final code = response.data['code']; if (code == 401 || code == 403) { // 🔥 仅在当前确实处于登录态时,才把 401 当作「登录过期」弹窗。 @@ -57,7 +73,10 @@ class DioClient { }, onError: (DioException e, handler) async { - if (e.response?.statusCode == 401 || e.response?.statusCode == 403) { + if (e.requestOptions.extra[_requestBackend] == + HttpApiConsts.baseUrl && + (e.response?.statusCode == 401 || + e.response?.statusCode == 403)) { // 🔥 同上:已退出登录(user==null)时不再触发过期弹窗 if (sl().state.user != null) { print( diff --git a/lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart b/lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart index 042f6441..a7bf7b80 100644 --- a/lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart +++ b/lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart @@ -23,6 +23,7 @@ class MqttClientImpl implements MqttClient { bool _isConnected = false; bool _isConnecting = false; bool _manualDisconnect = false; + int _connectionGeneration = 0; MqttClientImpl({this.clientName = 'MqttClient'}); @@ -39,11 +40,12 @@ class MqttClientImpl implements MqttClient { return; } - if (_isConnected) { - debugPrint('[MqttClient] already connected, disconnect first'); - await disconnect(); - } - + final generation = ++_connectionGeneration; + final previousClient = _client; + final previousUpdates = _updatesSubscription; + _client = null; + _updatesSubscription = null; + _isConnected = false; _manualDisconnect = false; _currentConfig = config; _reconnectTimer?.cancel(); @@ -51,33 +53,45 @@ class MqttClientImpl implements MqttClient { _isConnecting = true; try { - await _updatesSubscription?.cancel(); - _updatesSubscription = null; - _client = _createClient(config); - _configureClient(_client!, config); + await previousUpdates?.cancel(); + previousClient?.disconnect(); + if (generation != _connectionGeneration) return; - debugPrint('${LogTime.now()} 🔌 [$clientName] 正在连接 ${config.connectionAddress}:${config.port} (clientId=${config.clientId})'); - await _client!.connect(config.username, config.password); + final client = _createClient(config); + _client = client; + _configureClient(client, config); - if (_client!.connectionStatus?.state == + debugPrint( + '${LogTime.now()} 🔌 [$clientName] 正在连接 ${config.connectionAddress}:${config.port} (clientId=${config.clientId})', + ); + await client.connect(config.username, config.password); + if (generation != _connectionGeneration) { + client.disconnect(); + return; + } + + if (client.connectionStatus?.state == mqtt.MqttConnectionState.connected) { _isConnected = true; - debugPrint('${LogTime.now()} ✅ [$clientName] 连接成功 ${config.connectionAddress}:${config.port}'); + debugPrint( + '${LogTime.now()} ✅ [$clientName] 连接成功 ${config.connectionAddress}:${config.port}', + ); _listenToMessages(); _resubscribeAll(); } else { throw Exception( - 'MQTT connect failed: ${_client!.connectionStatus?.returnCode}', + 'MQTT connect failed: ${client.connectionStatus?.returnCode}', ); } } catch (e) { + if (generation != _connectionGeneration) return; debugPrint('${LogTime.now()} ❌ [$clientName] 连接失败: $e'); _isConnected = false; _isConnecting = false; _scheduleReconnect(); rethrow; } finally { - _isConnecting = false; + if (generation == _connectionGeneration) _isConnecting = false; } } @@ -113,9 +127,15 @@ class MqttClientImpl implements MqttClient { client.keepAlivePeriod = config.keepAlivePeriod; client.autoReconnect = false; client.resubscribeOnAutoReconnect = false; - client.onDisconnected = _onDisconnected; - client.onConnected = _onConnected; - client.onSubscribed = _onSubscribed; + client.onDisconnected = () { + if (identical(_client, client)) _onDisconnected(); + }; + client.onConnected = () { + if (identical(_client, client)) _onConnected(); + }; + client.onSubscribed = (topic) { + if (identical(_client, client)) _onSubscribed(topic); + }; var connMessage = mqtt.MqttConnectMessage() .withClientIdentifier(client.clientIdentifier) @@ -131,16 +151,19 @@ class MqttClientImpl implements MqttClient { @override Future disconnect() async { debugPrint('[MqttClient] disconnect'); + _connectionGeneration++; + final client = _client; + final updates = _updatesSubscription; _manualDisconnect = true; _reconnectTimer?.cancel(); _reconnectTimer = null; - await _updatesSubscription?.cancel(); _updatesSubscription = null; - _client?.disconnect(); _client = null; _isConnected = false; _isConnecting = false; _currentConfig = null; + await updates?.cancel(); + client?.disconnect(); } @override @@ -196,8 +219,10 @@ class MqttClientImpl implements MqttClient { } void _listenToMessages() { - _updatesSubscription = _client!.updates!.listen( + final client = _client!; + _updatesSubscription = client.updates!.listen( (List> messages) { + if (!identical(_client, client)) return; for (final msg in messages) { final topic = msg.topic; final payload = mqtt.MqttPublishPayload.bytesToStringAsString( @@ -209,6 +234,7 @@ class MqttClientImpl implements MqttClient { } }, onError: (Object error) { + if (!identical(_client, client)) return; debugPrint('[MqttClient] updates stream error: $error'); _isConnected = false; _scheduleReconnect(); diff --git a/lib/core/network/mqtt/domain/models/mqtt_config.dart b/lib/core/network/mqtt/domain/models/mqtt_config.dart index 77cae25d..ce7ff77f 100644 --- a/lib/core/network/mqtt/domain/models/mqtt_config.dart +++ b/lib/core/network/mqtt/domain/models/mqtt_config.dart @@ -1,6 +1,7 @@ import 'package:equatable/equatable.dart'; import '../../../../env/env_config.dart'; +import '../../../../env/server_configuration.dart'; /// MQTT 传输协议类型 enum MqttProtocol { @@ -45,9 +46,13 @@ class MqttConfig extends Equatable { String get connectionAddress { switch (protocol) { case MqttProtocol.websocket: - return 'ws://$host:$port${wsPath ?? '/mqtt'}'; case MqttProtocol.wss: - return 'wss://$host:$port${wsPath ?? '/mqtt'}'; + return Uri( + scheme: protocol == MqttProtocol.wss ? 'wss' : 'ws', + host: host, + port: port, + path: wsPath ?? '/mqtt', + ).toString(); case MqttProtocol.tcp: default: return host; @@ -56,14 +61,17 @@ class MqttConfig extends Equatable { /// 无人机/机场 OSD 数据(WebSocket MQTT) factory MqttConfig.droneOsd() { - return const MqttConfig( - host: '1.95.137.212', - port: 8083, + final address = EnvConfig.address(ServerService.droneMqtt); + return MqttConfig( + host: address.host, + port: address.port, username: 'maibu', password: 'jsmbzn520', - protocol: MqttProtocol.websocket, + protocol: address.scheme == 'wss' + ? MqttProtocol.wss + : MqttProtocol.websocket, clientId: 'drone_osd_client', - wsPath: '/mqtt', + wsPath: address.path, cleanSession: true, reconnectDelayMs: 3000, ); @@ -71,9 +79,10 @@ class MqttConfig extends Equatable { /// 任务状态消息(TCP MQTT)——端口随环境切换(prod=1883 / test=59007) factory MqttConfig.taskMessage() { + final address = EnvConfig.address(ServerService.mqtt); return MqttConfig( - host: EnvConfig.serverHost, - port: EnvConfig.mqttPort, + host: address.host, + port: address.port, username: 'maibu', password: 'jsmbzn520', protocol: MqttProtocol.tcp, @@ -86,9 +95,10 @@ class MqttConfig extends Equatable { /// 🔥 割草机机器状态(TCP MQTT)——独立连接,端口随环境切换(prod=1883 / test=59007) /// 仅用于 mower/{sn}/property/realtime/post 和 mower/{sn}/property/location/post factory MqttConfig.mowerRealtime() { + final address = EnvConfig.address(ServerService.mqtt); return MqttConfig( - host: EnvConfig.serverHost, - port: EnvConfig.mqttPort, + host: address.host, + port: address.port, username: 'maibu', password: 'jsmbzn520', protocol: MqttProtocol.tcp, diff --git a/lib/core/network/mqtt/mqtt_manager.dart b/lib/core/network/mqtt/mqtt_manager.dart index 9bfaf123..c0a23040 100644 --- a/lib/core/network/mqtt/mqtt_manager.dart +++ b/lib/core/network/mqtt/mqtt_manager.dart @@ -1,9 +1,8 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; -import 'package:get_it/get_it.dart'; import '../../di/injection.dart'; -import 'data/datasources/drone_osd_datasource.dart'; -import 'data/datasources/task_message_datasource.dart'; import 'domain/interfaces/mqtt_client.dart'; import 'domain/models/mqtt_config.dart'; @@ -12,25 +11,36 @@ class MqttManager { factory MqttManager() => _instance; MqttManager._internal(); + Future? _initialization; + int _generation = 0; bool _isInitialized = false; - Future initialize() async { - if (_isInitialized) { - debugPrint('⚠️ [MqttManager] 已初始化,跳过'); - return; - } + Future initialize() => _initialization ??= _initialize(_generation); + Future _initialize(int generation) async { debugPrint('🔧 [MqttManager] 开始初始化 MQTT 连接...'); final droneOsdClient = sl(instanceName: 'droneOsdClient'); final taskMessageClient = sl(instanceName: 'taskMessageClient'); - final mowerRealtimeClient = sl(instanceName: 'mowerRealtimeClient'); + final mowerRealtimeClient = sl( + instanceName: 'mowerRealtimeClient', + ); - // 独立连接三个 MQTT 客户端,互不影响 - await _connectClient(droneOsdClient, MqttConfig.droneOsd(), 'droneOsdClient'); - await _connectClient(taskMessageClient, MqttConfig.taskMessage(), 'taskMessageClient'); - await _connectClient(mowerRealtimeClient, MqttConfig.mowerRealtime(), 'mowerRealtimeClient'); + await Future.wait([ + _connectClient(droneOsdClient, MqttConfig.droneOsd(), 'droneOsdClient'), + _connectClient( + taskMessageClient, + MqttConfig.taskMessage(), + 'taskMessageClient', + ), + _connectClient( + mowerRealtimeClient, + MqttConfig.mowerRealtime(), + 'mowerRealtimeClient', + ), + ]); + if (generation != _generation) return; _isInitialized = true; debugPrint('✅ [MqttManager] MQTT 初始化完成'); } @@ -50,18 +60,29 @@ class MqttManager { } } + Future reconnect() async { + await dispose(); + unawaited(initialize()); + } + Future dispose() async { + _generation++; + _initialization = null; + _isInitialized = false; debugPrint('🔌 [MqttManager] 断开所有 MQTT 连接...'); final droneOsdClient = sl(instanceName: 'droneOsdClient'); final taskMessageClient = sl(instanceName: 'taskMessageClient'); - final mowerRealtimeClient = sl(instanceName: 'mowerRealtimeClient'); + final mowerRealtimeClient = sl( + instanceName: 'mowerRealtimeClient', + ); - await droneOsdClient.disconnect(); - await taskMessageClient.disconnect(); - await mowerRealtimeClient.disconnect(); + await Future.wait([ + droneOsdClient.disconnect(), + taskMessageClient.disconnect(), + mowerRealtimeClient.disconnect(), + ]); - _isInitialized = false; debugPrint('✅ [MqttManager] 所有 MQTT 连接已断开'); } diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart index 96d38d95..94cff78b 100644 --- a/lib/core/router/app_router.dart +++ b/lib/core/router/app_router.dart @@ -2,7 +2,7 @@ import 'package:flutter/foundation.dart'; import 'package:go_router/go_router.dart'; import 'package:maibu_satabot_v2/core/router/route_paths.dart'; import 'package:maibu_satabot_v2/features/ai/presentation/routes/ai_routes.dart'; -import 'package:maibu_satabot_v2/features/auth/presentation/pages/login_page.dart'; +import 'package:maibu_satabot_v2/features/server_configuration/presentation/server_configuration_page.dart'; import 'package:maibu_satabot_v2/features/auth/presentation/routes/auth_routes.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/home/presentation/routes/home_routes.dart'; @@ -40,7 +40,7 @@ GoRouter createRouter(AuthCubit authCubit) { final registering = state.matchedLocation == RoutePaths.register; // 启动屏:交给 SplashPage 自己根据就绪信号跳转,路由层不干预 - if (onSplash) { + if (onSplash || state.matchedLocation == RoutePaths.serverConfiguration) { return null; } @@ -92,6 +92,11 @@ GoRouter createRouter(AuthCubit authCubit) { ], ), + GoRoute( + path: RoutePaths.serverConfiguration, + builder: (context, state) => const ServerConfigurationPage(), + ), + ...AuthRoutes.routes, ...HomeRoutes.routes, ...AiRoutes.routes, diff --git a/lib/core/router/route_paths.dart b/lib/core/router/route_paths.dart index 90952a01..a6fb3a81 100644 --- a/lib/core/router/route_paths.dart +++ b/lib/core/router/route_paths.dart @@ -5,6 +5,7 @@ class RoutePaths { /// 账号相关页面 static const login = '/auth/login'; static const register = '/auth/register'; + static const serverConfiguration = '/server-configuration'; /// 一级页面 static const home = '/home'; diff --git a/lib/core/update/version_check_service.dart b/lib/core/update/version_check_service.dart index 1a324cc9..6ec847c1 100644 --- a/lib/core/update/version_check_service.dart +++ b/lib/core/update/version_check_service.dart @@ -1,4 +1,6 @@ import 'package:dio/dio.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_patcher/flutter_patcher.dart'; import 'package:logger/logger.dart'; @@ -60,7 +62,7 @@ class VersionCheckService { validateStatus: (status) => true, )); - static const String apiUrl = 'http://8.159.134.0:8012/api/update/check'; + static String get apiUrl => EnvConfig.address(ServerService.update).toString(); static const String _patchVersionFileName = '.patch_version'; /// 检查版本更新 diff --git a/lib/features/ai/presentation/bloc/ai_cubit.dart b/lib/features/ai/presentation/bloc/ai_cubit.dart index 2ad63ac8..24c1d127 100644 --- a/lib/features/ai/presentation/bloc/ai_cubit.dart +++ b/lib/features/ai/presentation/bloc/ai_cubit.dart @@ -3,6 +3,8 @@ import 'dart:convert'; import 'dart:io'; import 'package:bloc/bloc.dart'; import 'package:dio/dio.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; import 'package:image_picker/image_picker.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; @@ -20,13 +22,13 @@ class AiCubit extends Cubit { final Dio _dio = Dio(); final ImagePicker _picker = ImagePicker(); - static const String BASE_URL = 'http://1.95.137.212:30009'; + static String get _baseUrl => EnvConfig.baseAddress(ServerService.ai); String get _userId => appUserCubit.state.user?.userId ?? '1'; //final String _userId = '1'; Future fetchSessions() async { try { - final response = await _dio.get('$BASE_URL/sessions', queryParameters: {'userId': _userId}); + final response = await _dio.get('$_baseUrl/sessions', queryParameters: {'userId': _userId}); if (response.statusCode == 200 && response.data['code'] == 0) { final sessionsData = response.data['sessions'] as List; emit(state.copyWith(sessions: sessionsData.map((data) => Session.fromJson(data)).toList())); @@ -52,7 +54,7 @@ class AiCubit extends Cubit { emit(state.copyWith(status: AiStatus.loading, messages: [], sessionId: sessionId)); try { - final response = await _dio.get('$BASE_URL/history', queryParameters: {'sessionId': sessionId}); + final response = await _dio.get('$_baseUrl/history', queryParameters: {'sessionId': sessionId}); if (response.statusCode == 200 && response.data['code'] == 0) { final messagesData = response.data['messages'] as List; final historyMessages = messagesData.map((data) { @@ -95,7 +97,7 @@ class AiCubit extends Cubit { try { final response = await _dio.post( - '$BASE_URL/analyze', + '$_baseUrl/analyze', data: {'userId': _userId, 'sessionId': state.sessionId, 'userPrompt': prompt, 'imageBase64': imageBase64}, options: Options(responseType: ResponseType.stream), ); diff --git a/lib/features/auth/presentation/bloc/auth_cubit.dart b/lib/features/auth/presentation/bloc/auth_cubit.dart index 568ace65..9f08d619 100644 --- a/lib/features/auth/presentation/bloc/auth_cubit.dart +++ b/lib/features/auth/presentation/bloc/auth_cubit.dart @@ -237,7 +237,12 @@ class AuthCubit extends Cubit { } /// 退出登录 (主动或被动) - Future logout() async { + Future logout() => _logout(); + + /// 先清除旧会话,再应用新地址,最后返回登录页。 + Future logoutForServerChange(Future Function() apply) => _logout(apply); + + Future _logout([Future Function()? beforeSignedOut]) async { print('>>> [AUTH] 🚨🚨🚨 logout() 被调用!时间: ${DateTime.now()}'); print('>>> [AUTH] 调用栈:\n${StackTrace.current}'); @@ -247,7 +252,11 @@ class AuthCubit extends Cubit { await storage.deleteUser(); tcp.forceDisconnect(); // 🔥 修复:彻底断开连接,禁止自动重连 appCubit.clearAuth(); - emit(AuthUnauthenticated()); + try { + if (beforeSignedOut != null) await beforeSignedOut(); + } finally { + emit(AuthUnauthenticated()); + } } /// 🔥 Token 过期处理:弹出提示后退出登录 diff --git a/lib/features/auth/presentation/pages/login_page_v2.dart b/lib/features/auth/presentation/pages/login_page_v2.dart index 2ffe629e..26f01129 100644 --- a/lib/features/auth/presentation/pages/login_page_v2.dart +++ b/lib/features/auth/presentation/pages/login_page_v2.dart @@ -209,6 +209,17 @@ class _LoginPageV2State extends State animation: _interval(0.26, 0.63), child: _buildFormCard(), ), + Center( + child: BlocBuilder( + builder: (context, state) => TextButton.icon( + onPressed: state is LoginLoading + ? null + : () => context.push(RoutePaths.serverConfiguration), + icon: const Icon(Icons.settings_ethernet), + label: Text(l10n.translate('servers.title')), + ), + ), + ), // 暂时隐藏登录页的帮助与客服入口。 // const SizedBox(height: 12), // _Entrance( diff --git a/lib/features/devices/data/datasources/impl/path_http_datasource_impl.dart b/lib/features/devices/data/datasources/impl/path_http_datasource_impl.dart index 7757c21f..9d8b277e 100644 --- a/lib/features/devices/data/datasources/impl/path_http_datasource_impl.dart +++ b/lib/features/devices/data/datasources/impl/path_http_datasource_impl.dart @@ -2,6 +2,8 @@ import 'dart:convert'; import 'package:get_it/get_it.dart'; import 'package:maibu_satabot_v2/common.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; import '../../../../../core/logging/i_logger_service.dart'; import '../../../../../core/storage/user_storage.dart'; @@ -57,7 +59,7 @@ class PathHttpDatasourceImpl implements PathHttpDatasource { // print(requestBody); //print('🔍 [路径规划请求] ====== 请求体结束 ======'); final response = await http.post( - Uri.parse('https://servicepathplan.satabot.com/api/path'), + EnvConfig.address(ServerService.pathPlanning), headers: {'Content' '-Type': 'application/json', 'Authorization': token}, body: requestBody, diff --git a/lib/features/home/presentation/pages/dj_page.dart b/lib/features/home/presentation/pages/dj_page.dart index 0ee05550..d24c8e00 100644 --- a/lib/features/home/presentation/pages/dj_page.dart +++ b/lib/features/home/presentation/pages/dj_page.dart @@ -1,6 +1,8 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/core/router/route_paths.dart'; import 'package:webview_flutter/webview_flutter.dart'; @@ -25,7 +27,12 @@ class _DjPageState extends State { void initState() { super.initState(); - final url = "https://pvs.satabot.com/?platform=flutter&t=${DateTime.now().millisecondsSinceEpoch}"; + final url = EnvConfig.address(ServerService.stationWeb).replace( + queryParameters: { + 'platform': 'flutter', + 't': DateTime.now().millisecondsSinceEpoch.toString(), + }, + ); controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) @@ -35,7 +42,7 @@ class _DjPageState extends State { _handleJsMessage(message.message); }, ) - ..loadRequest(Uri.parse(url)); + ..loadRequest(url); } /// 处理 H5 返回的数据 diff --git a/lib/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart b/lib/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart index 3df2770a..96b9abef 100644 --- a/lib/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart +++ b/lib/features/home/presentation/widgets/map/geoserver_suzhou_layer.dart @@ -4,6 +4,8 @@ import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:http/http.dart' as http; @@ -12,7 +14,7 @@ import 'package:path_provider/path_provider.dart'; import 'package:xml/xml.dart'; /// GeoServer 基地址(公司端) -const String kGeoserverBase = 'http://1.95.137.212:7900/geoserver'; +String get kGeoserverBase => EnvConfig.baseAddress(ServerService.geoServer); /// GeoServer 工作区名(后端 siteMapName 形如 workSpace:suzhou) const String kGeoWorkspace = 'workSpace'; @@ -22,6 +24,9 @@ const String kGeoWorkspace = 'workSpace'; /// 返回透明图导致“一直出不来”。故放宽到 90s,并配合下方并发闸门分批取图。 const Duration kWmsTileTimeout = Duration(seconds: 90); +/// 保持地图瓦片覆盖范围和逻辑尺寸不变,以双倍像素取图供高密度屏显示。 +const int kWmsTilePixelSize = 512; + /// 各场站高清图层的真实范围(取自 GeoServer GetCapabilities,原生 EPSG:4326) /// key = 后端下发的 siteMapName(形如 workSpace:suzhou) final Map kStationLayerBounds = { @@ -77,7 +82,7 @@ class GeoWmsProvider extends TileProvider { GeoWmsProvider({ required this.layerName, required this.bounds, - this.maxLevel = 21, + this.maxLevel = 22, }); final String layerName; @@ -129,10 +134,10 @@ class GeoWmsProvider extends TileProvider { 'REQUEST': 'GetMap', 'VERSION': '1.1.1', 'LAYERS': layerName, - 'BBOX': '${westLng.toStringAsFixed(6)},${southLat.toStringAsFixed(6)},' - '${eastLng.toStringAsFixed(6)},${northLat.toStringAsFixed(6)}', - 'WIDTH': '256', - 'HEIGHT': '256', + 'BBOX': '${westLng.toStringAsFixed(9)},${southLat.toStringAsFixed(9)},' + '${eastLng.toStringAsFixed(9)},${northLat.toStringAsFixed(9)}', + 'WIDTH': '$kWmsTilePixelSize', + 'HEIGHT': '$kWmsTilePixelSize', 'FORMAT': 'image/png', 'TRANSPARENT': 'true', 'SRS': 'EPSG:4326', @@ -150,7 +155,7 @@ class GeoSuzhouOverlay extends StatelessWidget { super.key, this.siteMapName, this.minZoom = 16, - this.maxZoom = 21, + this.maxZoom = 22, }); /// 当前选中场站对应的 GeoServer 图层名(形如 workSpace:suzhou) @@ -210,12 +215,12 @@ final List kAllStationTileLayers = kStationLayerBounds.entries tileProvider: GeoWmsProvider( layerName: entry.key, bounds: entry.value, - maxLevel: 21, + maxLevel: 22, ), userAgentPackageName: 'com.example.app', minZoom: 16, - maxZoom: 21, - maxNativeZoom: 21, + maxZoom: 22, + maxNativeZoom: 22, tileBounds: entry.value, ), ) @@ -395,15 +400,31 @@ class StationLayerRepo { Map _bounds = Map.of(kStationLayerBounds); + String _baseAddress = kGeoserverBase; bool _dynamicLoaded = false; Future? _inflight; final List _listeners = []; /// 当前生效的范围表(动态成功后为最新;否则为内置兜底) - Map get bounds => _bounds; + Map get bounds { + _syncBaseAddress(); + return _bounds; + } /// 范围表是否来自动态拉取 - bool get isDynamic => _dynamicLoaded; + bool get isDynamic { + _syncBaseAddress(); + return _dynamicLoaded; + } + + void _syncBaseAddress() { + final current = kGeoserverBase; + if (_baseAddress == current) return; + _baseAddress = current; + _bounds = Map.of(kStationLayerBounds); + _dynamicLoaded = false; + _inflight = null; + } void addListener(void Function() cb) { if (!_listeners.contains(cb)) _listeners.add(cb); @@ -419,14 +440,22 @@ class StationLayerRepo { /// 拉取 GetCapabilities 刷新范围表;并发调用自动合并;失败保持兜底不变 Future refresh() { - return _inflight ??= _doRefresh().whenComplete(() => _inflight = null); + _syncBaseAddress(); + final inflight = _inflight; + if (inflight != null) return inflight; + + late final Future request; + request = _doRefresh(_baseAddress).whenComplete(() { + if (identical(_inflight, request)) _inflight = null; + }); + return _inflight = request; } - Future _doRefresh() async { + Future _doRefresh(String baseAddress) async { final sw = Stopwatch()..start(); try { // 用工作区专用端点:只返回 workSpace 下图层,XML 小、快、稳(全局端点图层多易超时) - final url = Uri.parse('$kGeoserverBase/$kGeoWorkspace/wms').replace( + final url = Uri.parse('$baseAddress/$kGeoWorkspace/wms').replace( queryParameters: { 'SERVICE': 'WMS', 'VERSION': '1.1.1', @@ -435,6 +464,7 @@ class StationLayerRepo { ); debugPrint('🌐 [StationLayerRepo] 拉取 GetCapabilities...'); final resp = await http.get(url).timeout(const Duration(seconds: 20)); + if (baseAddress != kGeoserverBase) return; if (resp.statusCode != 200) { debugPrint( '⚠️ [StationLayerRepo] status=${resp.statusCode},保持兜底', @@ -472,8 +502,8 @@ class StationLayerRepo { } /// 基于当前范围表构建全部场站叠加图层(滑到哪个场站区域就叠加哪个) - List buildLayers({double minZoom = 16, double maxZoom = 21}) { - return _bounds.entries.map((entry) { + List buildLayers({double minZoom = 16, double maxZoom = 22}) { + return bounds.entries.map((entry) { // 自愈兜底:万一范围表里仍残留非法 bounds(历史污染等),回退到内置兜底的同名范围, // 避免生成“框不住任何瓦片”的坏图层导致该场站整体不显示 final b = _isValidLayerBounds(entry.value) diff --git a/lib/features/home/presentation/widgets/map/testmap_pages.dart b/lib/features/home/presentation/widgets/map/testmap_pages.dart index 3c155aad..c9508808 100644 --- a/lib/features/home/presentation/widgets/map/testmap_pages.dart +++ b/lib/features/home/presentation/widgets/map/testmap_pages.dart @@ -18,7 +18,7 @@ import 'package:maibu_satabot_v2/components/confrim_dialog.dart'; import 'package:maibu_satabot_v2/components/toast.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_cubit.dart'; -import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; @@ -4483,7 +4483,7 @@ class _MapPageEnterpriseState extends State { userState.user != null && userState.user!.token != null) { _videoStreamUrl = - "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=${userState.user!.token}"; + "webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/$deviceId?token=${userState.user!.token}"; } else { _videoStreamUrl = ''; } diff --git a/lib/features/home/presentation/widgets/video.dart b/lib/features/home/presentation/widgets/video.dart index e341f1dd..992bdac8 100644 --- a/lib/features/home/presentation/widgets/video.dart +++ b/lib/features/home/presentation/widgets/video.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:ui'; import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'package:http/http.dart' as http; @@ -89,11 +90,11 @@ class _WebRTCMapPlayerState extends State { await _peerConnection!.setLocalDescription(offer); final uri = Uri.parse(widget.streamUrl.replaceFirst('webrtc://', 'http://')); - final apiUrl = "http://${uri.host}:1985/rtc/v1/play/"; + final apiUrl = EnvConfig.webRtcPlayAddress(uri); final response = await http.post( - Uri.parse(apiUrl), + apiUrl, headers: {'Content-Type': 'application/json'}, - body: jsonEncode({"api": apiUrl, "streamurl": widget.streamUrl, "clientip": null, "sdp": offer.sdp}), + body: jsonEncode({"api": apiUrl.toString(), "streamurl": widget.streamUrl, "clientip": null, "sdp": offer.sdp}), ); if (response.statusCode == 200) { diff --git a/lib/features/machine_details/presentation/pages/machine_details_page.dart b/lib/features/machine_details/presentation/pages/machine_details_page.dart index c009c1c2..b267c360 100644 --- a/lib/features/machine_details/presentation/pages/machine_details_page.dart +++ b/lib/features/machine_details/presentation/pages/machine_details_page.dart @@ -5,7 +5,7 @@ import 'package:go_router/go_router.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/components/control_mode_text.dart'; -import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:maibu_satabot_v2/core/router/route_paths.dart'; import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart'; import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart'; @@ -78,7 +78,7 @@ class _MachineDetailsPageState extends State { if (_deviceId.isNotEmpty && userState.user != null && userState.user!.token != null) { setState(() { - _videoStreamUrl = "webrtc://${TCPConsts.TCP_IP}/live/livestream/$_deviceId?token=${userState.user!.token}"; + _videoStreamUrl = "webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/$_deviceId?token=${userState.user!.token}"; }); debugPrint('✅ [MachineDetails] 视频URL初始化成功: $_videoStreamUrl'); } else { diff --git a/lib/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart b/lib/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart index 85c8b165..5206d614 100644 --- a/lib/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart +++ b/lib/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:ui'; import 'package:flutter/material.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'package:http/http.dart' as http; @@ -268,13 +269,13 @@ class _WebRTCLocalPlayerState extends State { Uri uri = Uri.parse( widget.streamUrl.replaceFirst('webrtc://', 'http://'), ); - String apiUrl = "http://${uri.host}:1985/rtc/v1/play/"; + final apiUrl = EnvConfig.webRtcPlayAddress(uri); final response = await http.post( - Uri.parse(apiUrl), + apiUrl, headers: {'Content-Type': 'application/json'}, body: jsonEncode({ - "api": apiUrl, + "api": apiUrl.toString(), "streamurl": widget.streamUrl, "clientip": null, "sdp": offer.sdp, diff --git a/lib/features/server_configuration/presentation/server_configuration_page.dart b/lib/features/server_configuration/presentation/server_configuration_page.dart new file mode 100644 index 00000000..0046cf97 --- /dev/null +++ b/lib/features/server_configuration/presentation/server_configuration_page.dart @@ -0,0 +1,319 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:go_router/go_router.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../core/di/injection.dart'; +import '../../../core/env/env_config.dart'; +import '../../../core/env/server_configuration.dart'; +import '../../../core/localization/app_localizations.dart'; +import '../../../core/network/mqtt/mqtt_manager.dart'; +import '../../../core/router/route_paths.dart'; +import '../../auth/presentation/bloc/auth_cubit.dart'; +import '../../auth/presentation/bloc/auth_state.dart'; + +class ServerConfigurationPage extends StatefulWidget { + const ServerConfigurationPage({super.key}); + + @override + State createState() => + _ServerConfigurationPageState(); +} + +class _ServerConfigurationPageState extends State { + final _host = TextEditingController(); + final _inputs = { + for (final service in ServerService.values) + service: TextEditingController(), + }; + final _advanced = ExpansibleController(); + final _invalidServices = {}; + Map _results = {}; + bool _invalidHost = false; + bool _saving = false; + bool _testing = false; + + bool get _busy => _saving || _testing; + + @override + void initState() { + super.initState(); + final config = EnvConfig.serverConfiguration; + _host.text = config.sharedHost; + for (final entry in config.overrides.entries) { + _inputs[entry.key]!.text = entry.value; + } + } + + @override + void dispose() { + _host.dispose(); + for (final controller in _inputs.values) { + controller.dispose(); + } + _advanced.dispose(); + super.dispose(); + } + + ServerConfiguration? _readDraft() { + final host = _host.text.trim(); + final invalidHost = host.isNotEmpty && !ServerConfiguration.isHost(host); + final effectiveHost = host.isEmpty || invalidHost + ? ServerConfiguration.defaultHost + : host; + final invalidServices = {}; + final inputs = {}; + for (final entry in _inputs.entries) { + final input = entry.value.text.trim(); + inputs[entry.key] = input; + try { + entry.key.resolve( + input, + production: EnvConfig.isProduction, + commonHost: effectiveHost, + ); + } on FormatException { + invalidServices.add(entry.key); + } + } + + setState(() { + _invalidHost = invalidHost; + _invalidServices + ..clear() + ..addAll(invalidServices); + }); + if (invalidServices.any((service) => !service.isCore)) _advanced.expand(); + if (invalidHost || invalidServices.isNotEmpty) return null; + return ServerConfiguration( + production: EnvConfig.isProduction, + sharedHost: host, + overrides: inputs, + ); + } + + Future _testConnection() async { + FocusScope.of(context).unfocus(); + final draft = _readDraft(); + if (draft == null) return; + setState(() { + _testing = true; + _results = {}; + }); + final results = await Future.wait( + ServerService.values.map((service) async { + final address = draft.address(service); + var reachable = false; + try { + final socket = await Socket.connect( + address.host, + address.port, + timeout: const Duration(seconds: 3), + ); + socket.destroy(); + reachable = true; + } on SocketException { + // A failed reachability check does not prevent saving the address. + } + return MapEntry(service, (address: address, reachable: reachable)); + }), + ); + if (!mounted) return; + setState(() { + _testing = false; + _results = Map.fromEntries(results); + }); + } + + Future _save() async { + FocusScope.of(context).unfocus(); + final draft = _readDraft(); + if (draft == null) return; + final l10n = AppLocalizations.of(context); + final previous = EnvConfig.serverConfiguration; + bool changed(ServerService service) => + previous.address(service) != draft.address(service); + final auth = context.read(); + final relogin = + auth.state is AuthAuthenticated && ServerService.values.any(changed); + final reconnectMqtt = + relogin || + changed(ServerService.mqtt) || + changed(ServerService.droneMqtt); + setState(() => _saving = true); + + Future applyConfiguration() async { + try { + await EnvConfig.saveServerConfiguration(sl(), draft); + } finally { + if (reconnectMqtt) await MqttManager().reconnect(); + } + } + + try { + if (relogin) { + await auth.logoutForServerChange(applyConfiguration); + } else { + await applyConfiguration(); + } + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(l10n.translate('servers.saved')))); + if (!relogin && context.canPop()) { + context.pop(); + } else { + context.go( + auth.state is AuthAuthenticated ? RoutePaths.home : RoutePaths.login, + ); + } + } catch (_) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.translate('servers.save_failed'))), + ); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final loggedIn = context.select( + (AuthCubit auth) => auth.state is AuthAuthenticated, + ); + return Scaffold( + appBar: AppBar(title: Text(l10n.translate('servers.title'))), + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(l10n.translate('servers.help')), + const SizedBox(height: 12), + TextField( + controller: _host, + enabled: !_busy, + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => setState(() { + _invalidHost = false; + _results = {}; + }), + decoration: InputDecoration( + border: const OutlineInputBorder(), + labelText: l10n.translate('servers.shared_host'), + hintText: ServerConfiguration.defaultHost, + errorText: _invalidHost + ? l10n.translate('servers.invalid_host') + : null, + ), + ), + for (final service in ServerService.values.where( + (service) => service.isCore, + )) + _serviceField(service, l10n), + const SizedBox(height: 12), + ExpansionTile( + controller: _advanced, + title: Text(l10n.translate('servers.advanced')), + tilePadding: EdgeInsets.zero, + children: [ + for (final service in ServerService.values.where( + (service) => !service.isCore, + )) + _serviceField(service, l10n), + ], + ), + if (loggedIn) ...[ + const SizedBox(height: 12), + Text(l10n.translate('servers.relogin')), + ], + if (_saving || _testing) ...[ + const SizedBox(height: 12), + const LinearProgressIndicator(), + ], + ], + ), + ), + ), + ), + ), + bottomNavigationBar: SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: Wrap( + alignment: WrapAlignment.center, + spacing: 12, + runSpacing: 8, + children: [ + OutlinedButton( + onPressed: _busy ? null : _testConnection, + child: Text(l10n.translate('servers.test_ports')), + ), + FilledButton( + onPressed: _busy ? null : _save, + child: Text(l10n.translate('servers.save')), + ), + ], + ), + ), + ); + } + + Widget _serviceField(ServerService service, AppLocalizations l10n) { + final input = _inputs[service]!; + final host = _host.text.trim(); + final sharedHost = ServerConfiguration.isHost(host) + ? host + : ServerConfiguration.defaultHost; + Uri address; + try { + address = service.resolve( + input.text.trim(), + production: EnvConfig.isProduction, + commonHost: sharedHost, + ); + } on FormatException { + address = service.defaultAddress( + production: EnvConfig.isProduction, + commonHost: sharedHost, + ); + } + final result = _results[service]; + final text = result == null + ? address.toString() + : l10n.translate( + result.reachable ? 'servers.reachable' : 'servers.unreachable', + {'address': result.address.toString()}, + ); + return Padding( + padding: const EdgeInsets.only(top: 12), + child: TextField( + controller: input, + enabled: !_busy, + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => setState(() { + _invalidServices.remove(service); + _results = {}; + }), + decoration: InputDecoration( + border: const OutlineInputBorder(), + labelText: l10n.translate('servers.${service.name}'), + helperText: text, + helperMaxLines: 2, + errorText: _invalidServices.contains(service) + ? l10n.translate('servers.invalid_address') + : null, + ), + ), + ); + } +} diff --git a/lib/features/v2/device_list/presentation/widgets/robot_header_card.dart b/lib/features/v2/device_list/presentation/widgets/robot_header_card.dart index 3a67d132..695e8e6e 100644 --- a/lib/features/v2/device_list/presentation/widgets/robot_header_card.dart +++ b/lib/features/v2/device_list/presentation/widgets/robot_header_card.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; import 'package:maibu_satabot_v2/core/app/app_user_state.dart'; // 🔥 导入 AppUserState -import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; import 'package:maibu_satabot_v2/core/theme/AppTheme.dart'; import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart'; @@ -58,7 +58,7 @@ class _RobotHeaderCardState extends State { if (deviceId == null || deviceId.isEmpty || token == null) { return ''; } - return "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=$token"; + return "webrtc://${EnvConfig.webRtcStreamAuthority}/live/livestream/$deviceId?token=$token"; } /// 🔥 点击播放按钮 diff --git a/lib/features/v2/my/presentation/pages/system_settings_page.dart b/lib/features/v2/my/presentation/pages/system_settings_page.dart index 189a99b8..95f862fb 100644 --- a/lib/features/v2/my/presentation/pages/system_settings_page.dart +++ b/lib/features/v2/my/presentation/pages/system_settings_page.dart @@ -83,6 +83,17 @@ class _SystemSettingsPageState extends State { _buildUpdateSection(), ], const SizedBox(height: 12), + Card( + margin: EdgeInsets.zero, + color: context.appColors.cardBackground, + child: ListTile( + leading: const Icon(Icons.settings_ethernet), + title: Text(AppLocalizations.of(context).translate('servers.title')), + trailing: const Icon(Icons.chevron_right), + onTap: () => context.push(RoutePaths.serverConfiguration), + ), + ), + const SizedBox(height: 12), // 退出登录(已挪至“我的”页面最下边,此处注释掉) // _buildLogoutButton(context), // const SizedBox(height: 20), diff --git a/test/server_configuration_test.dart b/test/server_configuration_test.dart new file mode 100644 index 00000000..813fb6c7 --- /dev/null +++ b/test/server_configuration_test.dart @@ -0,0 +1,301 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/core/env/env_config.dart'; +import 'package:maibu_satabot_v2/core/env/server_configuration.dart'; +import 'package:maibu_satabot_v2/core/localization/app_localizations.dart'; +import 'package:maibu_satabot_v2/core/network/dio_client.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/interfaces/mqtt_client.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/domain/models/mqtt_config.dart'; +import 'package:maibu_satabot_v2/core/network/mqtt/mqtt_manager.dart'; +import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart'; +import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_state.dart'; +import 'package:maibu_satabot_v2/features/server_configuration/presentation/server_configuration_page.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'support/region_test_localizations.dart'; + +class _SignedOutAuth extends Fake implements AuthCubit { + @override + AuthState get state => AuthUnauthenticated(); + + @override + Stream get stream => const Stream.empty(); +} + +class _MqttClient extends Fake implements MqttClient { + final initialConnection = Completer(); + final attempts = []; + int disconnects = 0; + + @override + Future connect(MqttConfig config) async { + attempts.add(config); + if (attempts.length == 1) await initialConnection.future; + } + + @override + Future disconnect() async => disconnects++; +} + +class _HttpAdapter extends Fake implements HttpClientAdapter { + final requests = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options.uri); + return ResponseBody.fromString('{}', 200, headers: { + Headers.contentTypeHeader: [Headers.jsonContentType], + }); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(RegionTestLocalizations.loadAssets); + + late SharedPreferences prefs; + setUp(() async { + SharedPreferences.setMockInitialValues({}); + prefs = await SharedPreferences.getInstance(); + EnvConfig.loadServerConfiguration(prefs); + sl.registerSingleton(prefs); + }); + tearDown(() => sl.reset()); + + test('keeps the existing addresses for test and production', () { + final testConfig = ServerConfiguration(production: false); + final productionConfig = ServerConfiguration(production: true); + expect(ServerService.values, hasLength(10)); + expect( + testConfig.address(ServerService.http).toString(), + 'http://1.95.137.212:59003', + ); + expect(testConfig.address(ServerService.tcp).port, 59004); + expect(testConfig.address(ServerService.mqtt).port, 59007); + expect(productionConfig.address(ServerService.http).port, 8081); + expect(productionConfig.address(ServerService.tcp).port, 9001); + expect(productionConfig.address(ServerService.mqtt).port, 1883); + expect( + testConfig.address(ServerService.webRtc).toString(), + 'http://1.95.137.212:1985/rtc/v1/play/', + ); + expect( + testConfig.address(ServerService.droneMqtt).toString(), + 'ws://1.95.137.212:8083/mqtt', + ); + expect( + testConfig.address(ServerService.geoServer).toString(), + 'http://1.95.137.212:7900/geoserver', + ); + expect( + testConfig.address(ServerService.pathPlanning).toString(), + 'https://servicepathplan.satabot.com/api/path', + ); + expect( + testConfig.address(ServerService.ai).toString(), + 'http://1.95.137.212:30009', + ); + expect( + testConfig.address(ServerService.update).toString(), + 'http://8.159.134.0:8012/api/update/check', + ); + expect( + testConfig.address(ServerService.stationWeb).toString(), + 'https://pvs.satabot.com/', + ); + }); + + test( + 'saved overrides are applied to HTTP, TCP, MQTT and WebRTC after reload', + () async { + const host = '192.168.1.31'; + await EnvConfig.saveServerConfiguration( + prefs, + ServerConfiguration( + production: EnvConfig.isProduction, + sharedHost: host, + overrides: const { + ServerService.http: '8800', + ServerService.tcp: '192.168.1.32:9002', + ServerService.mqtt: '1884', + ServerService.webRtc: 'http://192.168.1.33:1986', + ServerService.droneMqtt: 'wss://drone.local/stream/mqtt', + ServerService.pathPlanning: 'http://192.168.1.34:8088', + }, + ), + ); + EnvConfig.loadServerConfiguration(prefs); + expect(EnvConfig.baseUrl, 'http://$host:8800'); + expect(EnvConfig.tcpIp, '192.168.1.32'); + expect(EnvConfig.tcpPort, 9002); + expect(MqttConfig.taskMessage().host, host); + expect(MqttConfig.mowerRealtime().port, 1884); + expect(MqttConfig.droneOsd().port, 443); + expect(MqttConfig.droneOsd().wsPath, '/stream/mqtt'); + expect(EnvConfig.webRtcStreamAuthority, '192.168.1.33'); + expect( + EnvConfig.webRtcPlayAddress( + Uri.parse('webrtc://192.168.1.33/live/test'), + ).port, + 1986, + ); + expect(EnvConfig.address(ServerService.pathPlanning).path, '/api/path'); + expect( + EnvConfig.address(ServerService.geoServer).host, + ServerConfiguration.defaultHost, + ); + }, + ); + + test('rejects malformed settings and resolves IPv6 addresses', () { + for (final value in [ + '0', + '65536', + 'host:0', + 'https://host:9001', + 'host:9001/api', + ]) { + expect( + () => ServerService.tcp.resolve( + value, + production: false, + commonHost: 'localhost', + ), + throwsFormatException, + ); + } + final config = ServerConfiguration(production: false, sharedHost: '::1'); + expect(config.address(ServerService.http).toString(), 'http://[::1]:59003'); + expect(config.address(ServerService.tcp).host, '::1'); + }); + + test('an existing HTTP client sends new requests to the saved endpoint', () async { + final user = AppUserCubit(); + sl.registerSingleton(user, dispose: (cubit) => cubit.close()); + final adapter = _HttpAdapter(); + final dio = DioClient.create()..httpClientAdapter = adapter; + final previous = EnvConfig.baseUrl; + await dio.get('/status'); + await EnvConfig.saveServerConfiguration( + prefs, + ServerConfiguration( + production: EnvConfig.isProduction, + overrides: const {ServerService.http: 'http://192.168.1.35:8800/api'}, + ), + ); + await dio.get('/status'); + await dio.get('https://example.com/absolute'); + expect(adapter.requests.map((uri) => uri.toString()), [ + '$previous/status', + 'http://192.168.1.35:8800/api/status', + 'https://example.com/absolute', + ]); + }); + + test( + 'MQTT applies new endpoints while an old connection is pending', + () async { + final clients = { + for (final name in [ + 'droneOsdClient', + 'taskMessageClient', + 'mowerRealtimeClient', + ]) + name: _MqttClient(), + }; + for (final entry in clients.entries) { + sl.registerSingleton(entry.value, instanceName: entry.key); + } + final manager = MqttManager(); + final startup = manager.initialize(); + try { + await EnvConfig.saveServerConfiguration( + prefs, + ServerConfiguration( + production: EnvConfig.isProduction, + sharedHost: '192.168.1.35', + overrides: const {ServerService.mqtt: '1884'}, + ), + ); + await manager.reconnect(); + for (final name in ['taskMessageClient', 'mowerRealtimeClient']) { + expect(clients[name]!.disconnects, 1); + expect(clients[name]!.attempts.last.host, '192.168.1.35'); + expect(clients[name]!.attempts.last.port, 1884); + } + expect(clients['droneOsdClient']!.attempts.last.port, 8083); + } finally { + for (final client in clients.values) { + client.initialConnection.complete(); + } + await startup; + await manager.dispose(); + } + }, + ); + + testWidgets('signed-out user can edit and save the shared host', ( + tester, + ) async { + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, _) => Scaffold( + body: TextButton( + onPressed: () => context.push('/servers'), + child: const Text('Configure'), + ), + ), + ), + GoRoute( + path: '/servers', + builder: (_, _) => const ServerConfigurationPage(), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + BlocProvider.value( + value: _SignedOutAuth(), + child: MaterialApp.router( + routerConfig: router, + locale: AppLocalizations.english, + supportedLocales: AppLocalizations.supportedLocales, + localizationsDelegates: const [RegionTestLocalizations()], + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Configure')); + await tester.pumpAndSettle(); + final hostField = find.widgetWithText(TextField, 'Shared IP or hostname'); + await tester.enterText(hostField, 'http://bad-host'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(find.text('Enter a valid IP address or hostname'), findsOneWidget); + + // Keep both MQTT clients on their original brokers in this widget test. + await tester.enterText(hostField, '192.168.1.35'); + await tester.enterText( + find.widgetWithText(TextField, 'Business MQTT'), + EnvConfig.address(ServerService.mqtt).authority, + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(find.text('Configure'), findsOneWidget); + expect(EnvConfig.address(ServerService.http).host, '192.168.1.35'); + }); +}