支持现场服务器地址配置
This commit is contained in:
@@ -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<void> init() async {
|
||||
/// 1.2 --- 本地存储 (LocalStorage) ---
|
||||
/// 1.2.1 SharedPreferences:本地存储库
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
EnvConfig.loadServerConfiguration(sharedPrefs);
|
||||
sl.registerLazySingleton<SharedPreferences>(() => sharedPrefs);
|
||||
|
||||
/// 1.2.2 UserStorage:用户存储库
|
||||
|
||||
72
lib/core/env/env_config.dart
vendored
72
lib/core/env/env_config.dart
vendored
@@ -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<String, dynamic>,
|
||||
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<void> 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
177
lib/core/env/server_configuration.dart
vendored
Normal file
177
lib/core/env/server_configuration.dart
vendored
Normal file
@@ -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<ServerService, String> overrides;
|
||||
final Map<ServerService, Uri> _addresses;
|
||||
|
||||
ServerConfiguration._(this.sharedHost, this.overrides, this._addresses);
|
||||
|
||||
factory ServerConfiguration({
|
||||
required bool production,
|
||||
String sharedHost = '',
|
||||
Map<ServerService, String> overrides = const {},
|
||||
}) {
|
||||
final host = sharedHost.trim();
|
||||
if (host.isNotEmpty && !isHost(host)) {
|
||||
throw const FormatException('Invalid shared host');
|
||||
}
|
||||
final inputs = <ServerService, String>{
|
||||
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<String, dynamic> 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<String, String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, dynamic>) {
|
||||
if (response.requestOptions.extra[_requestBackend] ==
|
||||
HttpApiConsts.baseUrl &&
|
||||
response.data is Map<String, dynamic>) {
|
||||
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<AppUserCubit>().state.user != null) {
|
||||
print(
|
||||
|
||||
@@ -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<void> 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<mqtt.MqttReceivedMessage<mqtt.MqttMessage>> 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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<void>? _initialization;
|
||||
int _generation = 0;
|
||||
bool _isInitialized = false;
|
||||
|
||||
Future<void> initialize() async {
|
||||
if (_isInitialized) {
|
||||
debugPrint('⚠️ [MqttManager] 已初始化,跳过');
|
||||
return;
|
||||
}
|
||||
Future<void> initialize() => _initialization ??= _initialize(_generation);
|
||||
|
||||
Future<void> _initialize(int generation) async {
|
||||
debugPrint('🔧 [MqttManager] 开始初始化 MQTT 连接...');
|
||||
|
||||
final droneOsdClient = sl<MqttClient>(instanceName: 'droneOsdClient');
|
||||
final taskMessageClient = sl<MqttClient>(instanceName: 'taskMessageClient');
|
||||
final mowerRealtimeClient = sl<MqttClient>(instanceName: 'mowerRealtimeClient');
|
||||
final mowerRealtimeClient = sl<MqttClient>(
|
||||
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<void> reconnect() async {
|
||||
await dispose();
|
||||
unawaited(initialize());
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
_generation++;
|
||||
_initialization = null;
|
||||
_isInitialized = false;
|
||||
debugPrint('🔌 [MqttManager] 断开所有 MQTT 连接...');
|
||||
|
||||
final droneOsdClient = sl<MqttClient>(instanceName: 'droneOsdClient');
|
||||
final taskMessageClient = sl<MqttClient>(instanceName: 'taskMessageClient');
|
||||
final mowerRealtimeClient = sl<MqttClient>(instanceName: 'mowerRealtimeClient');
|
||||
final mowerRealtimeClient = sl<MqttClient>(
|
||||
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 连接已断开');
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
/// 检查版本更新
|
||||
|
||||
@@ -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<AiState> {
|
||||
|
||||
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<void> 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<AiState> {
|
||||
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<AiState> {
|
||||
|
||||
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),
|
||||
);
|
||||
|
||||
@@ -237,7 +237,12 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
}
|
||||
|
||||
/// 退出登录 (主动或被动)
|
||||
Future<void> logout() async {
|
||||
Future<void> logout() => _logout();
|
||||
|
||||
/// 先清除旧会话,再应用新地址,最后返回登录页。
|
||||
Future<void> logoutForServerChange(Future<void> Function() apply) => _logout(apply);
|
||||
|
||||
Future<void> _logout([Future<void> Function()? beforeSignedOut]) async {
|
||||
print('>>> [AUTH] 🚨🚨🚨 logout() 被调用!时间: ${DateTime.now()}');
|
||||
print('>>> [AUTH] 调用栈:\n${StackTrace.current}');
|
||||
|
||||
@@ -247,7 +252,11 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
await storage.deleteUser();
|
||||
tcp.forceDisconnect(); // 🔥 修复:彻底断开连接,禁止自动重连
|
||||
appCubit.clearAuth();
|
||||
emit(AuthUnauthenticated());
|
||||
try {
|
||||
if (beforeSignedOut != null) await beforeSignedOut();
|
||||
} finally {
|
||||
emit(AuthUnauthenticated());
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔥 Token 过期处理:弹出提示后退出登录
|
||||
|
||||
@@ -209,6 +209,17 @@ class _LoginPageV2State extends State<LoginPageV2>
|
||||
animation: _interval(0.26, 0.63),
|
||||
child: _buildFormCard(),
|
||||
),
|
||||
Center(
|
||||
child: BlocBuilder<LoginCubit, LoginState>(
|
||||
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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<DjPage> {
|
||||
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<DjPage> {
|
||||
_handleJsMessage(message.message);
|
||||
},
|
||||
)
|
||||
..loadRequest(Uri.parse(url));
|
||||
..loadRequest(url);
|
||||
}
|
||||
|
||||
/// 处理 H5 返回的数据
|
||||
|
||||
@@ -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<String, LatLngBounds> 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<TileLayer> 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<String, LatLngBounds> _bounds =
|
||||
Map<String, LatLngBounds>.of(kStationLayerBounds);
|
||||
String _baseAddress = kGeoserverBase;
|
||||
bool _dynamicLoaded = false;
|
||||
Future<void>? _inflight;
|
||||
final List<void Function()> _listeners = [];
|
||||
|
||||
/// 当前生效的范围表(动态成功后为最新;否则为内置兜底)
|
||||
Map<String, LatLngBounds> get bounds => _bounds;
|
||||
Map<String, LatLngBounds> 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<void> refresh() {
|
||||
return _inflight ??= _doRefresh().whenComplete(() => _inflight = null);
|
||||
_syncBaseAddress();
|
||||
final inflight = _inflight;
|
||||
if (inflight != null) return inflight;
|
||||
|
||||
late final Future<void> request;
|
||||
request = _doRefresh(_baseAddress).whenComplete(() {
|
||||
if (identical(_inflight, request)) _inflight = null;
|
||||
});
|
||||
return _inflight = request;
|
||||
}
|
||||
|
||||
Future<void> _doRefresh() async {
|
||||
Future<void> _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<TileLayer> buildLayers({double minZoom = 16, double maxZoom = 21}) {
|
||||
return _bounds.entries.map((entry) {
|
||||
List<TileLayer> buildLayers({double minZoom = 16, double maxZoom = 22}) {
|
||||
return bounds.entries.map((entry) {
|
||||
// 自愈兜底:万一范围表里仍残留非法 bounds(历史污染等),回退到内置兜底的同名范围,
|
||||
// 避免生成“框不住任何瓦片”的坏图层导致该场站整体不显示
|
||||
final b = _isValidLayerBounds(entry.value)
|
||||
|
||||
@@ -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<MapPageEnterprise> {
|
||||
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 = '';
|
||||
}
|
||||
|
||||
@@ -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<WebRTCMapPlayer> {
|
||||
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) {
|
||||
|
||||
@@ -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<MachineDetailsPage> {
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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<WebRTCLocalPlayer> {
|
||||
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,
|
||||
|
||||
@@ -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<ServerConfigurationPage> createState() =>
|
||||
_ServerConfigurationPageState();
|
||||
}
|
||||
|
||||
class _ServerConfigurationPageState extends State<ServerConfigurationPage> {
|
||||
final _host = TextEditingController();
|
||||
final _inputs = {
|
||||
for (final service in ServerService.values)
|
||||
service: TextEditingController(),
|
||||
};
|
||||
final _advanced = ExpansibleController();
|
||||
final _invalidServices = <ServerService>{};
|
||||
Map<ServerService, ({Uri address, bool reachable})> _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 = <ServerService>{};
|
||||
final inputs = <ServerService, String>{};
|
||||
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<void> _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<void> _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<AuthCubit>();
|
||||
final relogin =
|
||||
auth.state is AuthAuthenticated && ServerService.values.any(changed);
|
||||
final reconnectMqtt =
|
||||
relogin ||
|
||||
changed(ServerService.mqtt) ||
|
||||
changed(ServerService.droneMqtt);
|
||||
setState(() => _saving = true);
|
||||
|
||||
Future<void> applyConfiguration() async {
|
||||
try {
|
||||
await EnvConfig.saveServerConfiguration(sl<SharedPreferences>(), 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,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<RobotHeaderCard> {
|
||||
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";
|
||||
}
|
||||
|
||||
/// 🔥 点击播放按钮
|
||||
|
||||
@@ -83,6 +83,17 @@ class _SystemSettingsPageState extends State<SystemSettingsPage> {
|
||||
_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),
|
||||
|
||||
Reference in New Issue
Block a user