支持现场服务器地址配置
This commit is contained in:
@@ -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 连接已断开');
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user