支持现场服务器地址配置
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';
|
||||
|
||||
/// 检查版本更新
|
||||
|
||||
Reference in New Issue
Block a user