集成双 MQTT 客户端实现设备实时数据监控(未测试)
1.集成两个独立的 MQTT 客户端,支持 WebSocket 和 TCP 协议 2.实现无人机/机场 OSD 实时监控(ws://1.95.137.212:8083/mqtt) 3.实现任务状态消息订阅(tcp://1.95.137.212:59020) 4.采用清洁架构设计,分层清晰(Domain → Data → Presentation)
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../domain/interfaces/mqtt_client.dart';
|
||||
import '../../domain/models/mqtt_message.dart';
|
||||
import '../../domain/entities/drone_osd_entity.dart';
|
||||
|
||||
abstract class DroneOsdDataSource {
|
||||
Stream<DroneOsdEntity> get droneOsdStream;
|
||||
Stream<DroneOsdEntity> get stationOsdStream;
|
||||
|
||||
Future<void> startListening({
|
||||
required String deviceSn,
|
||||
required String gatewaySn,
|
||||
});
|
||||
|
||||
Future<void> stopListening();
|
||||
}
|
||||
|
||||
class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
final MqttClient mqttClient;
|
||||
final _droneOsdController = StreamController<DroneOsdEntity>.broadcast();
|
||||
final _stationOsdController = StreamController<DroneOsdEntity>.broadcast();
|
||||
|
||||
StreamSubscription<MqttMessage>? _subscription;
|
||||
String? _deviceSn;
|
||||
String? _gatewaySn;
|
||||
|
||||
DroneOsdDataSourceImpl(this.mqttClient);
|
||||
|
||||
@override
|
||||
Stream<DroneOsdEntity> get droneOsdStream => _droneOsdController.stream;
|
||||
|
||||
@override
|
||||
Stream<DroneOsdEntity> get stationOsdStream => _stationOsdController.stream;
|
||||
|
||||
@override
|
||||
Future<void> startListening({
|
||||
required String deviceSn,
|
||||
required String gatewaySn,
|
||||
}) async {
|
||||
_deviceSn = deviceSn;
|
||||
_gatewaySn = gatewaySn;
|
||||
|
||||
final droneTopic = 'thing/product/$deviceSn/osd';
|
||||
final stationTopic = 'thing/product/$gatewaySn/osd';
|
||||
|
||||
debugPrint('🛸 [DroneOsdDataSource] 开始监听:');
|
||||
debugPrint(' 无人机: $droneTopic');
|
||||
debugPrint(' 机场: $stationTopic');
|
||||
|
||||
await mqttClient.subscribe(droneTopic);
|
||||
await mqttClient.subscribe(stationTopic);
|
||||
|
||||
_subscription = mqttClient.messageStream?.listen((message) {
|
||||
_handleMessage(message);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopListening() async {
|
||||
await _subscription?.cancel();
|
||||
_subscription = null;
|
||||
|
||||
if (_deviceSn != null) {
|
||||
await mqttClient.unsubscribe('thing/product/$_deviceSn/osd');
|
||||
}
|
||||
if (_gatewaySn != null) {
|
||||
await mqttClient.unsubscribe('thing/product/$_gatewaySn/osd');
|
||||
}
|
||||
|
||||
_deviceSn = null;
|
||||
_gatewaySn = null;
|
||||
}
|
||||
|
||||
void _handleMessage(MqttMessage message) {
|
||||
try {
|
||||
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
|
||||
final osdData = DroneOsdEntity.fromJson(jsonData);
|
||||
|
||||
if (message.topic.contains(_deviceSn ?? '')) {
|
||||
debugPrint('🛸 [DroneOsdDataSource] 无人机 OSD 更新');
|
||||
_droneOsdController.add(osdData);
|
||||
} else if (message.topic.contains(_gatewaySn ?? '')) {
|
||||
debugPrint('🏢 [DroneOsdDataSource] 机场 OSD 更新');
|
||||
_stationOsdController.add(osdData);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [DroneOsdDataSource] 解析 OSD 数据失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
stopListening();
|
||||
_droneOsdController.close();
|
||||
_stationOsdController.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../domain/interfaces/mqtt_client.dart';
|
||||
import '../../domain/models/mqtt_message.dart';
|
||||
import '../../domain/entities/task_arrive_entity.dart';
|
||||
import '../../domain/entities/task_status_entity.dart';
|
||||
import '../../domain/entities/real_time_message_entity.dart';
|
||||
|
||||
abstract class TaskMessageDataSource {
|
||||
Stream<TaskStatusEntity> get taskStatusStream;
|
||||
Stream<TaskArriveEntity> get taskArriveStream;
|
||||
Stream<RealTimeMessageEntity> get realTimeMessageStream;
|
||||
|
||||
Future<void> startListening({required String deviceId});
|
||||
Future<void> stopListening();
|
||||
}
|
||||
|
||||
class TaskMessageDataSourceImpl implements TaskMessageDataSource {
|
||||
final MqttClient mqttClient;
|
||||
final _taskStatusController = StreamController<TaskStatusEntity>.broadcast();
|
||||
final _taskArriveController = StreamController<TaskArriveEntity>.broadcast();
|
||||
final _realTimeMessageController = StreamController<RealTimeMessageEntity>.broadcast();
|
||||
|
||||
StreamSubscription<MqttMessage>? _subscription;
|
||||
String? _deviceId;
|
||||
|
||||
TaskMessageDataSourceImpl(this.mqttClient);
|
||||
|
||||
@override
|
||||
Stream<TaskStatusEntity> get taskStatusStream => _taskStatusController.stream;
|
||||
|
||||
@override
|
||||
Stream<TaskArriveEntity> get taskArriveStream => _taskArriveController.stream;
|
||||
|
||||
@override
|
||||
Stream<RealTimeMessageEntity> get realTimeMessageStream =>
|
||||
_realTimeMessageController.stream;
|
||||
|
||||
@override
|
||||
Future<void> startListening({required String deviceId}) async {
|
||||
_deviceId = deviceId;
|
||||
|
||||
final taskStatusTopic = 'task/$deviceId/status';
|
||||
final taskArriveTopic = 'task/$deviceId/arrive';
|
||||
final realTimeTopic = 'device/$deviceId/realTimeMessage';
|
||||
|
||||
debugPrint('📋 [TaskMessageDataSource] 开始监听:');
|
||||
debugPrint(' 任务状态: $taskStatusTopic');
|
||||
debugPrint(' 到达通知: $taskArriveTopic');
|
||||
debugPrint(' 实时消息: $realTimeTopic');
|
||||
|
||||
await mqttClient.subscribe(taskStatusTopic);
|
||||
await mqttClient.subscribe(taskArriveTopic);
|
||||
await mqttClient.subscribe(realTimeTopic);
|
||||
|
||||
_subscription = mqttClient.messageStream?.listen((message) {
|
||||
_handleMessage(message);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopListening() async {
|
||||
await _subscription?.cancel();
|
||||
_subscription = null;
|
||||
|
||||
if (_deviceId != null) {
|
||||
await mqttClient.unsubscribe('task/$_deviceId/status');
|
||||
await mqttClient.unsubscribe('task/$_deviceId/arrive');
|
||||
await mqttClient.unsubscribe('device/$_deviceId/realTimeMessage');
|
||||
}
|
||||
|
||||
_deviceId = null;
|
||||
}
|
||||
|
||||
void _handleMessage(MqttMessage message) {
|
||||
try {
|
||||
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
|
||||
|
||||
if (message.topic.contains('/status')) {
|
||||
final taskStatus = TaskStatusEntity.fromJson(jsonData);
|
||||
debugPrint('📋 [TaskMessageDataSource] 任务状态更新: ${taskStatus.status}');
|
||||
_taskStatusController.add(taskStatus);
|
||||
} else if (message.topic.contains('/arrive')) {
|
||||
final arriveInfo = TaskArriveEntity.fromJson(jsonData);
|
||||
debugPrint('📍 [TaskMessageDataSource] 到达通知: 任务${arriveInfo.taskId}');
|
||||
_taskArriveController.add(arriveInfo);
|
||||
} else if (message.topic.contains('/realTimeMessage')) {
|
||||
final realTimeMsg = RealTimeMessageEntity.fromJson(jsonData);
|
||||
debugPrint('💬 [TaskMessageDataSource] 实时消息 - 类型: ${realTimeMsg.type}, 数据点数: ${realTimeMsg.data.length}');
|
||||
_realTimeMessageController.add(realTimeMsg);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TaskMessageDataSource] 解析任务消息失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
stopListening();
|
||||
_taskStatusController.close();
|
||||
_taskArriveController.close();
|
||||
_realTimeMessageController.close();
|
||||
}
|
||||
}
|
||||
168
lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart
Normal file
168
lib/core/network/mqtt/data/infrastructure/mqtt_client_impl.dart
Normal file
@@ -0,0 +1,168 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:mqtt_client/mqtt_client.dart' as mqtt;
|
||||
import 'package:mqtt_client/mqtt_server_client.dart' as mqtt_server;
|
||||
|
||||
import '../../domain/interfaces/mqtt_client.dart';
|
||||
import '../../domain/models/mqtt_config.dart';
|
||||
import '../../domain/models/mqtt_message.dart';
|
||||
|
||||
class MqttClientImpl implements MqttClient {
|
||||
mqtt_server.MqttServerClient? _client;
|
||||
final _messageController = StreamController<MqttMessage>.broadcast();
|
||||
MqttConfig? _currentConfig;
|
||||
bool _isConnected = false;
|
||||
|
||||
@override
|
||||
Stream<MqttMessage>? get messageStream => _messageController.stream;
|
||||
|
||||
@override
|
||||
bool get isConnected => _isConnected;
|
||||
|
||||
@override
|
||||
Future<void> connect(MqttConfig config) async {
|
||||
if (_isConnected) {
|
||||
debugPrint('⚠️ [MqttClient] 已连接,先断开');
|
||||
await disconnect();
|
||||
}
|
||||
|
||||
try {
|
||||
_currentConfig = config;
|
||||
final clientId = '${config.clientId}_${DateTime.now().millisecondsSinceEpoch}';
|
||||
|
||||
switch (config.protocol) {
|
||||
case MqttProtocol.websocket:
|
||||
_client = mqtt_server.MqttServerClient.withPort(
|
||||
config.host,
|
||||
clientId,
|
||||
config.port,
|
||||
);
|
||||
_client!.useWebSocket = true;
|
||||
break;
|
||||
case MqttProtocol.wss:
|
||||
_client = mqtt_server.MqttServerClient.withPort(
|
||||
config.host,
|
||||
clientId,
|
||||
config.port,
|
||||
);
|
||||
_client!.useWebSocket = true;
|
||||
_client!.secure = true;
|
||||
break;
|
||||
case MqttProtocol.tcp:
|
||||
default:
|
||||
_client = mqtt_server.MqttServerClient.withPort(
|
||||
config.host,
|
||||
clientId,
|
||||
config.port,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
_client!.logging(on: false);
|
||||
_client!.keepAlivePeriod = config.keepAlivePeriod;
|
||||
_client!.autoReconnect = true;
|
||||
_client!.resubscribeOnAutoReconnect = true;
|
||||
_client!.onDisconnected = _onDisconnected;
|
||||
_client!.onConnected = _onConnected;
|
||||
_client!.onSubscribed = _onSubscribed;
|
||||
|
||||
final connMessage = mqtt.MqttConnectMessage()
|
||||
.withClientIdentifier(clientId)
|
||||
.startClean()
|
||||
.withWillQos(mqtt.MqttQos.atLeastOnce);
|
||||
|
||||
_client!.connectionMessage = connMessage;
|
||||
|
||||
debugPrint('🔌 [MqttClient] 开始连接到 ${config.host}:${config.port}');
|
||||
|
||||
await _client!.connect(config.username, config.password);
|
||||
|
||||
if (_client!.connectionStatus?.state == mqtt.MqttConnectionState.connected) {
|
||||
_isConnected = true;
|
||||
debugPrint('✅ [MqttClient] 连接成功');
|
||||
_listenToMessages();
|
||||
} else {
|
||||
throw Exception('连接失败: ${_client!.connectionStatus?.returnCode}');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [MqttClient] 连接异常: $e');
|
||||
_isConnected = false;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> disconnect() async {
|
||||
debugPrint('🔌 [MqttClient] 断开连接');
|
||||
_client?.disconnect();
|
||||
_isConnected = false;
|
||||
_currentConfig = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> subscribe(String topic) async {
|
||||
if (!_isConnected || _client == null) {
|
||||
throw Exception('MQTT 未连接');
|
||||
}
|
||||
|
||||
debugPrint('📡 [MqttClient] 订阅主题: $topic');
|
||||
_client!.subscribe(topic, mqtt.MqttQos.atLeastOnce);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> unsubscribe(String topic) async {
|
||||
if (!_isConnected || _client == null) {
|
||||
throw Exception('MQTT 未连接');
|
||||
}
|
||||
|
||||
debugPrint('🔕 [MqttClient] 取消订阅: $topic');
|
||||
_client!.unsubscribe(topic);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> publish(String topic, String message) async {
|
||||
if (!_isConnected || _client == null) {
|
||||
throw Exception('MQTT 未连接');
|
||||
}
|
||||
|
||||
debugPrint('📤 [MqttClient] 发布消息到 $topic');
|
||||
final builder = mqtt.MqttClientPayloadBuilder();
|
||||
builder.addString(message);
|
||||
_client!.publishMessage(topic, mqtt.MqttQos.atLeastOnce, builder.payload!);
|
||||
}
|
||||
|
||||
void _listenToMessages() {
|
||||
_client!.updates!.listen((List<mqtt.MqttReceivedMessage<mqtt.MqttMessage>> messages) {
|
||||
for (final msg in messages) {
|
||||
final topic = msg.topic;
|
||||
final payload = mqtt.MqttPublishPayload.bytesToStringAsString((msg.payload as mqtt.MqttPublishMessage).payload.message);
|
||||
|
||||
debugPrint('📥 [MqttClient] 收到消息 [$topic]: $payload');
|
||||
|
||||
_messageController.add(MqttMessage(
|
||||
topic: topic,
|
||||
payload: payload,
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _onConnected() {
|
||||
debugPrint('✅ [MqttClient] 已连接');
|
||||
_isConnected = true;
|
||||
}
|
||||
|
||||
void _onDisconnected() {
|
||||
debugPrint('❌ [MqttClient] 已断开');
|
||||
_isConnected = false;
|
||||
}
|
||||
|
||||
void _onSubscribed(String topic) {
|
||||
debugPrint('✅ [MqttClient] 订阅成功: $topic');
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_messageController.close();
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import 'dart:async';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../../core/error/failure.dart';
|
||||
import '../datasources/drone_osd_datasource.dart';
|
||||
import '../../domain/repositories/drone_osd_repository.dart';
|
||||
import '../../domain/entities/drone_osd_entity.dart';
|
||||
|
||||
class DroneOsdRepositoryImpl implements DroneOsdRepository {
|
||||
final DroneOsdDataSource dataSource;
|
||||
|
||||
DroneOsdRepositoryImpl(this.dataSource);
|
||||
|
||||
@override
|
||||
Stream<DroneOsdEntity> get droneOsdStream => dataSource.droneOsdStream;
|
||||
|
||||
@override
|
||||
Stream<DroneOsdEntity> get stationOsdStream => dataSource.stationOsdStream;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, void>> startListening({
|
||||
required String deviceSn,
|
||||
required String gatewaySn,
|
||||
}) async {
|
||||
try {
|
||||
await dataSource.startListening(
|
||||
deviceSn: deviceSn,
|
||||
gatewaySn: gatewaySn,
|
||||
);
|
||||
return right(null);
|
||||
} catch (e) {
|
||||
return left(Failure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopListening() async {
|
||||
await dataSource.stopListening();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import 'dart:async';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../../core/error/failure.dart';
|
||||
import '../datasources/task_message_datasource.dart';
|
||||
import '../../domain/repositories/task_message_repository.dart';
|
||||
import '../../domain/entities/task_arrive_entity.dart';
|
||||
import '../../domain/entities/task_status_entity.dart';
|
||||
import '../../domain/entities/real_time_message_entity.dart';
|
||||
|
||||
class TaskMessageRepositoryImpl implements TaskMessageRepository {
|
||||
final TaskMessageDataSource dataSource;
|
||||
|
||||
TaskMessageRepositoryImpl(this.dataSource);
|
||||
|
||||
@override
|
||||
Stream<RealTimeMessageEntity> get realTimeMessageStream =>
|
||||
dataSource.realTimeMessageStream;
|
||||
|
||||
@override
|
||||
Stream<TaskArriveEntity> get taskArriveStream => dataSource.taskArriveStream;
|
||||
|
||||
@override
|
||||
Stream<TaskStatusEntity> get taskStatusStream => dataSource.taskStatusStream;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, void>> startListening({required String deviceId}) async {
|
||||
try {
|
||||
await dataSource.startListening(deviceId: deviceId);
|
||||
return right(null);
|
||||
} catch (e) {
|
||||
return left(Failure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopListening() async {
|
||||
await dataSource.stopListening();
|
||||
}
|
||||
}
|
||||
18
lib/core/network/mqtt/domain/entities/drone_osd_entity.dart
Normal file
18
lib/core/network/mqtt/domain/entities/drone_osd_entity.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class DroneOsdEntity extends Equatable {
|
||||
final Map<String, dynamic> rawData;
|
||||
|
||||
const DroneOsdEntity({required this.rawData});
|
||||
|
||||
factory DroneOsdEntity.fromJson(Map<String, dynamic> json) {
|
||||
return DroneOsdEntity(rawData: json);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return rawData;
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [rawData];
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class RealTimeMessageEntity extends Equatable {
|
||||
final List<DeviceDataPoint> data;
|
||||
final String type;
|
||||
|
||||
const RealTimeMessageEntity({
|
||||
required this.data,
|
||||
required this.type,
|
||||
});
|
||||
|
||||
factory RealTimeMessageEntity.fromJson(Map<String, dynamic> json) {
|
||||
final dataList = json['data'] as List<dynamic>? ?? [];
|
||||
return RealTimeMessageEntity(
|
||||
data: dataList.map((item) => DeviceDataPoint.fromJson(item)).toList(),
|
||||
type: json['type'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
double? getValueByName(String name) {
|
||||
final point = data.firstWhere(
|
||||
(p) => p.name == name,
|
||||
orElse: () => DeviceDataPoint(name: '', value: '', unit: ''),
|
||||
);
|
||||
if (point.value.isEmpty) return null;
|
||||
return double.tryParse(point.value);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'data': data.map((e) => e.toJson()).toList(),
|
||||
'type': type,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [data, type];
|
||||
}
|
||||
|
||||
class DeviceDataPoint extends Equatable {
|
||||
final String name;
|
||||
final String value;
|
||||
final String unit;
|
||||
|
||||
const DeviceDataPoint({
|
||||
required this.name,
|
||||
required this.value,
|
||||
required this.unit,
|
||||
});
|
||||
|
||||
factory DeviceDataPoint.fromJson(Map<String, dynamic> json) {
|
||||
return DeviceDataPoint(
|
||||
name: json['name'] as String? ?? '',
|
||||
value: json['value'] as String? ?? '',
|
||||
unit: json['unit'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'name': name,
|
||||
'value': value,
|
||||
'unit': unit,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [name, value, unit];
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class TaskArriveEntity extends Equatable {
|
||||
final String type;
|
||||
final String deviceId;
|
||||
final int taskId;
|
||||
final dynamic status;
|
||||
final ArriveLocation entity;
|
||||
|
||||
const TaskArriveEntity({
|
||||
required this.type,
|
||||
required this.deviceId,
|
||||
required this.taskId,
|
||||
this.status,
|
||||
required this.entity,
|
||||
});
|
||||
|
||||
factory TaskArriveEntity.fromJson(Map<String, dynamic> json) {
|
||||
return TaskArriveEntity(
|
||||
type: json['type'] as String? ?? '',
|
||||
deviceId: json['deviceId'] as String? ?? '',
|
||||
taskId: json['taskId'] as int? ?? 0,
|
||||
status: json['status'],
|
||||
entity: ArriveLocation.fromJson(json['entity'] as Map<String, dynamic>? ?? {}),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'deviceId': deviceId,
|
||||
'taskId': taskId,
|
||||
'status': status,
|
||||
'entity': entity.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [type, deviceId, taskId, status, entity];
|
||||
}
|
||||
|
||||
class ArriveLocation extends Equatable {
|
||||
final double lat;
|
||||
final double lng;
|
||||
|
||||
const ArriveLocation({
|
||||
required this.lat,
|
||||
required this.lng,
|
||||
});
|
||||
|
||||
factory ArriveLocation.fromJson(Map<String, dynamic> json) {
|
||||
return ArriveLocation(
|
||||
lat: (json['lat'] as num?)?.toDouble() ?? 0.0,
|
||||
lng: (json['lng'] as num?)?.toDouble() ?? 0.0,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'lat': lat,
|
||||
'lng': lng,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [lat, lng];
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class TaskStatusEntity extends Equatable {
|
||||
final String type;
|
||||
final String deviceId;
|
||||
final int taskId;
|
||||
final String? status;
|
||||
final Map<String, dynamic>? extraData;
|
||||
|
||||
const TaskStatusEntity({
|
||||
required this.type,
|
||||
required this.deviceId,
|
||||
required this.taskId,
|
||||
this.status,
|
||||
this.extraData,
|
||||
});
|
||||
|
||||
factory TaskStatusEntity.fromJson(Map<String, dynamic> json) {
|
||||
return TaskStatusEntity(
|
||||
type: json['type'] as String? ?? '',
|
||||
deviceId: json['deviceId'] as String? ?? '',
|
||||
taskId: json['taskId'] as int? ?? 0,
|
||||
status: json['status'] as String?,
|
||||
extraData: json,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'deviceId': deviceId,
|
||||
'taskId': taskId,
|
||||
'status': status,
|
||||
if (extraData != null) ...extraData!,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [type, deviceId, taskId, status, extraData];
|
||||
}
|
||||
14
lib/core/network/mqtt/domain/interfaces/mqtt_client.dart
Normal file
14
lib/core/network/mqtt/domain/interfaces/mqtt_client.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'dart:async';
|
||||
import '../models/mqtt_config.dart';
|
||||
import '../models/mqtt_message.dart';
|
||||
|
||||
abstract class MqttClient {
|
||||
Stream<MqttMessage>? get messageStream;
|
||||
|
||||
Future<void> connect(MqttConfig config);
|
||||
Future<void> disconnect();
|
||||
Future<void> subscribe(String topic);
|
||||
Future<void> unsubscribe(String topic);
|
||||
Future<void> publish(String topic, String message);
|
||||
bool get isConnected;
|
||||
}
|
||||
90
lib/core/network/mqtt/domain/models/mqtt_config.dart
Normal file
90
lib/core/network/mqtt/domain/models/mqtt_config.dart
Normal file
@@ -0,0 +1,90 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
enum MqttProtocol { tcp, websocket, wss }
|
||||
|
||||
class MqttConfig extends Equatable {
|
||||
final String host;
|
||||
final int port;
|
||||
final String username;
|
||||
final String password;
|
||||
final MqttProtocol protocol;
|
||||
final String clientId;
|
||||
final bool cleanSession;
|
||||
final int keepAlivePeriod;
|
||||
final int reconnectDelayMs;
|
||||
|
||||
const MqttConfig({
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.username,
|
||||
required this.password,
|
||||
required this.protocol,
|
||||
required this.clientId,
|
||||
this.cleanSession = true,
|
||||
this.keepAlivePeriod = 60,
|
||||
this.reconnectDelayMs = 3000,
|
||||
});
|
||||
|
||||
factory MqttConfig.droneOsd() {
|
||||
return const MqttConfig(
|
||||
host: '1.95.137.212',
|
||||
port: 8083,
|
||||
username: 'maibu',
|
||||
password: 'jsmbzn520',
|
||||
protocol: MqttProtocol.websocket,
|
||||
clientId: 'drone_osd_client',
|
||||
cleanSession: true,
|
||||
reconnectDelayMs: 3000,
|
||||
);
|
||||
}
|
||||
|
||||
factory MqttConfig.taskMessage() {
|
||||
return const MqttConfig(
|
||||
host: '1.95.137.212',
|
||||
port: 59020,
|
||||
username: 'maibu',
|
||||
password: 'jsmbzn520',
|
||||
protocol: MqttProtocol.tcp,
|
||||
clientId: 'task_message_client',
|
||||
cleanSession: true,
|
||||
reconnectDelayMs: 3000,
|
||||
);
|
||||
}
|
||||
|
||||
MqttConfig copyWith({
|
||||
String? host,
|
||||
int? port,
|
||||
String? username,
|
||||
String? password,
|
||||
MqttProtocol? protocol,
|
||||
String? clientId,
|
||||
bool? cleanSession,
|
||||
int? keepAlivePeriod,
|
||||
int? reconnectDelayMs,
|
||||
}) {
|
||||
return MqttConfig(
|
||||
host: host ?? this.host,
|
||||
port: port ?? this.port,
|
||||
username: username ?? this.username,
|
||||
password: password ?? this.password,
|
||||
protocol: protocol ?? this.protocol,
|
||||
clientId: clientId ?? this.clientId,
|
||||
cleanSession: cleanSession ?? this.cleanSession,
|
||||
keepAlivePeriod: keepAlivePeriod ?? this.keepAlivePeriod,
|
||||
reconnectDelayMs: reconnectDelayMs ?? this.reconnectDelayMs,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
host,
|
||||
port,
|
||||
username,
|
||||
password,
|
||||
protocol,
|
||||
clientId,
|
||||
cleanSession,
|
||||
keepAlivePeriod,
|
||||
reconnectDelayMs,
|
||||
];
|
||||
}
|
||||
24
lib/core/network/mqtt/domain/models/mqtt_message.dart
Normal file
24
lib/core/network/mqtt/domain/models/mqtt_message.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class MqttMessage extends Equatable {
|
||||
final String topic;
|
||||
final String payload;
|
||||
final DateTime timestamp;
|
||||
|
||||
MqttMessage({
|
||||
required this.topic,
|
||||
required this.payload,
|
||||
DateTime? timestamp,
|
||||
}) : timestamp = timestamp ?? DateTime.now();
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'topic': topic,
|
||||
'payload': payload,
|
||||
'timestamp': timestamp.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [topic, payload, timestamp];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'dart:async';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../../core/error/failure.dart';
|
||||
import '../entities/drone_osd_entity.dart';
|
||||
|
||||
abstract class DroneOsdRepository {
|
||||
Stream<DroneOsdEntity> get droneOsdStream;
|
||||
Stream<DroneOsdEntity> get stationOsdStream;
|
||||
|
||||
Future<Either<Failure, void>> startListening({
|
||||
required String deviceSn,
|
||||
required String gatewaySn,
|
||||
});
|
||||
|
||||
Future<void> stopListening();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'dart:async';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../../core/error/failure.dart';
|
||||
import '../entities/task_arrive_entity.dart';
|
||||
import '../entities/task_status_entity.dart';
|
||||
import '../entities/real_time_message_entity.dart';
|
||||
|
||||
abstract class TaskMessageRepository {
|
||||
Stream<RealTimeMessageEntity> get realTimeMessageStream;
|
||||
Stream<TaskArriveEntity> get taskArriveStream;
|
||||
Stream<TaskStatusEntity> get taskStatusStream;
|
||||
|
||||
Future<Either<Failure, void>> startListening({required String deviceId});
|
||||
Future<void> stopListening();
|
||||
}
|
||||
54
lib/core/network/mqtt/mqtt_manager.dart
Normal file
54
lib/core/network/mqtt/mqtt_manager.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
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';
|
||||
|
||||
class MqttManager {
|
||||
static final MqttManager _instance = MqttManager._internal();
|
||||
factory MqttManager() => _instance;
|
||||
MqttManager._internal();
|
||||
|
||||
bool _isInitialized = false;
|
||||
|
||||
Future<void> initialize() async {
|
||||
if (_isInitialized) {
|
||||
debugPrint('⚠️ [MqttManager] 已初始化,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
debugPrint('🔧 [MqttManager] 开始初始化 MQTT 连接...');
|
||||
|
||||
final droneOsdClient = sl<MqttClient>(instanceName: 'droneOsdClient');
|
||||
final taskMessageClient = sl<MqttClient>(instanceName: 'taskMessageClient');
|
||||
|
||||
await droneOsdClient.connect(MqttConfig.droneOsd());
|
||||
await taskMessageClient.connect(MqttConfig.taskMessage());
|
||||
|
||||
_isInitialized = true;
|
||||
debugPrint('✅ [MqttManager] MQTT 初始化完成');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [MqttManager] MQTT 初始化失败: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
debugPrint('🔌 [MqttManager] 断开所有 MQTT 连接...');
|
||||
|
||||
final droneOsdClient = sl<MqttClient>(instanceName: 'droneOsdClient');
|
||||
final taskMessageClient = sl<MqttClient>(instanceName: 'taskMessageClient');
|
||||
|
||||
await droneOsdClient.disconnect();
|
||||
await taskMessageClient.disconnect();
|
||||
|
||||
_isInitialized = false;
|
||||
debugPrint('✅ [MqttManager] 所有 MQTT 连接已断开');
|
||||
}
|
||||
|
||||
bool get isInitialized => _isInitialized;
|
||||
}
|
||||
Reference in New Issue
Block a user