一次大的提交
This commit is contained in:
448
lib/core/bluetooth/ble_manager.dart
Normal file
448
lib/core/bluetooth/ble_manager.dart
Normal file
@@ -0,0 +1,448 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'bytes_util.dart';
|
||||
import 'protocol_parser.dart';
|
||||
|
||||
class BleManager {
|
||||
static final BleManager instance = BleManager._internal();
|
||||
BleManager._internal();
|
||||
|
||||
BluetoothDevice? _connectedDevice;
|
||||
BluetoothDevice? _connectingDevice;
|
||||
BluetoothCharacteristic? _writeCharacteristic;
|
||||
BluetoothCharacteristic? _readCharacteristic;
|
||||
|
||||
/// 有状态的协议解析器(支持 BLE 分片)
|
||||
final ProtocolParser _parser = ProtocolParser();
|
||||
|
||||
final Map<DeviceIdentifier, ScanResult> _scanResults = {};
|
||||
final StreamController<List<ScanResult>> _scanController =
|
||||
StreamController.broadcast();
|
||||
final StreamController<BlePacket> _packetController =
|
||||
StreamController.broadcast();
|
||||
final StreamController<BluetoothDevice?> _connectionController =
|
||||
StreamController.broadcast();
|
||||
final StreamController<BluetoothDevice?> _connectingController =
|
||||
StreamController.broadcast();
|
||||
|
||||
StreamSubscription<List<ScanResult>>? _scanSubscription;
|
||||
StreamSubscription<List<int>>? _readSubscription;
|
||||
StreamSubscription<BluetoothAdapterState>? _adapterStateSubscription;
|
||||
StreamSubscription<BluetoothConnectionState>? _deviceConnectionSubscription;
|
||||
|
||||
/// 防止异步竞态:stopScan() 后 in-flight 的 startScan() 不应生效
|
||||
int _scanGen = 0;
|
||||
|
||||
/// 协商后的 MTU 值,用于分片写入
|
||||
int _negotiatedMtu = 23;
|
||||
|
||||
/// 已收到的数据包存储(跨页面持久化)
|
||||
final List<BlePacket> receivedPacketStore = [];
|
||||
static const int _maxStoredPackets = 100;
|
||||
|
||||
void clearReceivedPackets() {
|
||||
receivedPacketStore.clear();
|
||||
}
|
||||
|
||||
bool get isConnected => _connectedDevice != null;
|
||||
BluetoothDevice? get connectedDevice => _connectedDevice;
|
||||
BluetoothDevice? get connectingDevice => _connectingDevice;
|
||||
Stream<List<ScanResult>> get scanResults => _scanController.stream;
|
||||
Stream<BlePacket> get packetStream => _packetController.stream;
|
||||
Stream<BluetoothAdapterState> get adapterState =>
|
||||
FlutterBluePlus.adapterState;
|
||||
|
||||
/// 连接状态变化流:连接成功时发出 device,断开时发出 null
|
||||
Stream<BluetoothDevice?> get connectionStream => _connectionController.stream;
|
||||
|
||||
/// 连接中状态流:开始连接时发出 device,连接完成/失败时发出 null
|
||||
Stream<BluetoothDevice?> get connectingStream => _connectingController.stream;
|
||||
|
||||
Future<bool> checkBluetooth() async {
|
||||
final state = await FlutterBluePlus.adapterState.first;
|
||||
return state == BluetoothAdapterState.on;
|
||||
}
|
||||
|
||||
Future<bool> requestPermissions() async {
|
||||
final connStatus = await Permission.bluetoothConnect.status;
|
||||
developer.log(
|
||||
'[BLE] bluetoothConnect status: $connStatus',
|
||||
name: 'BleManager',
|
||||
);
|
||||
if (connStatus.isDenied) {
|
||||
developer.log('[BLE] requesting bluetoothConnect...', name: 'BleManager');
|
||||
await Permission.bluetoothConnect.request();
|
||||
}
|
||||
|
||||
final scanStatus = await Permission.bluetoothScan.status;
|
||||
developer.log(
|
||||
'[BLE] bluetoothScan status: $scanStatus',
|
||||
name: 'BleManager',
|
||||
);
|
||||
if (scanStatus.isDenied) {
|
||||
developer.log('[BLE] requesting bluetoothScan...', name: 'BleManager');
|
||||
await Permission.bluetoothScan.request();
|
||||
}
|
||||
|
||||
final locStatus = await Permission.locationWhenInUse.status;
|
||||
developer.log(
|
||||
'[BLE] locationWhenInUse status: $locStatus',
|
||||
name: 'BleManager',
|
||||
);
|
||||
if (locStatus.isDenied) {
|
||||
developer.log(
|
||||
'[BLE] requesting locationWhenInUse...',
|
||||
name: 'BleManager',
|
||||
);
|
||||
await Permission.locationWhenInUse.request();
|
||||
}
|
||||
|
||||
final allGranted =
|
||||
await Permission.bluetoothConnect.isGranted &&
|
||||
await Permission.bluetoothScan.isGranted;
|
||||
developer.log(
|
||||
'[BLE] all permissions granted: $allGranted',
|
||||
name: 'BleManager',
|
||||
);
|
||||
return allGranted;
|
||||
}
|
||||
|
||||
Future<void> openBluetooth() async {
|
||||
try {
|
||||
await FlutterBluePlus.turnOn();
|
||||
} catch (e) {
|
||||
await _goToSystemSettings();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _goToSystemSettings() async {
|
||||
await openAppSettings();
|
||||
}
|
||||
|
||||
Future<void> _openLocationSettings() async {
|
||||
await openAppSettings();
|
||||
}
|
||||
|
||||
Future<bool> _checkLocationService() async {
|
||||
final locStatus = await Permission.location.serviceStatus;
|
||||
developer.log(
|
||||
'[BLE] location service status: $locStatus',
|
||||
name: 'BleManager',
|
||||
);
|
||||
return locStatus == ServiceStatus.enabled;
|
||||
}
|
||||
|
||||
Future<void> startScan({bool continuous = true}) async {
|
||||
final int myGen = ++_scanGen;
|
||||
developer.log(
|
||||
'[BLE] startScan called, gen=$myGen, continuous=$continuous',
|
||||
name: 'BleManager',
|
||||
);
|
||||
// 先停止任何残留扫描,确保干净启动
|
||||
try { await FlutterBluePlus.stopScan(); } catch (_) {}
|
||||
_scanResults.clear();
|
||||
_scanController.add([]);
|
||||
|
||||
final isOn = await checkBluetooth();
|
||||
if (myGen != _scanGen) return;
|
||||
developer.log('[BLE] Bluetooth adapter on: $isOn', name: 'BleManager');
|
||||
if (!isOn) {
|
||||
developer.log(
|
||||
'[BLE] Bluetooth is OFF, aborting scan',
|
||||
name: 'BleManager',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final granted = await requestPermissions();
|
||||
if (myGen != _scanGen) return;
|
||||
developer.log('[BLE] Permissions granted: $granted', name: 'BleManager');
|
||||
if (!granted) {
|
||||
developer.log(
|
||||
'[BLE] Permissions not granted, aborting scan',
|
||||
name: 'BleManager',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final locEnabled = await _checkLocationService();
|
||||
if (myGen != _scanGen) return;
|
||||
if (!locEnabled) {
|
||||
developer.log(
|
||||
'[BLE] Location service OFF, directing to settings',
|
||||
name: 'BleManager',
|
||||
);
|
||||
await _openLocationSettings();
|
||||
return;
|
||||
}
|
||||
|
||||
_scanSubscription?.cancel();
|
||||
_scanSubscription = FlutterBluePlus.scanResults.listen(
|
||||
(results) {
|
||||
for (final result in results) {
|
||||
_scanResults[result.device.remoteId] = result;
|
||||
}
|
||||
developer.log(
|
||||
'[BLE] 📡 扫描到 ${results.length} 个设备: ${results.map((r) => '${r.device.platformName.isNotEmpty ? r.device.platformName : r.device.advName.isNotEmpty ? r.device.advName : r.device.remoteId} (${r.rssi}dBm)').join(', ')}',
|
||||
name: 'BleManager',
|
||||
);
|
||||
_scanController.add(_scanResults.values.toList());
|
||||
},
|
||||
onError: (e) {
|
||||
developer.log('[BLE] scanResults error: $e', name: 'BleManager');
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
if (continuous) {
|
||||
developer.log('[BLE] Starting continuous scan...', name: 'BleManager');
|
||||
await FlutterBluePlus.startScan(
|
||||
timeout: const Duration(days: 1),
|
||||
androidUsesFineLocation: true,
|
||||
androidScanMode: AndroidScanMode.lowLatency,
|
||||
androidLegacy: true,
|
||||
);
|
||||
} else {
|
||||
developer.log('[BLE] Starting 10s scan...', name: 'BleManager');
|
||||
await FlutterBluePlus.startScan(
|
||||
timeout: const Duration(seconds: 10),
|
||||
androidUsesFineLocation: true,
|
||||
androidScanMode: AndroidScanMode.lowLatency,
|
||||
androidLegacy: true,
|
||||
);
|
||||
}
|
||||
developer.log('[BLE] startScan completed', name: 'BleManager');
|
||||
} catch (e, stackTrace) {
|
||||
developer.log(
|
||||
'[BLE] startScan error: $e\n$stackTrace',
|
||||
name: 'BleManager',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> refreshScan() async {
|
||||
await stopScan();
|
||||
await Future.delayed(const Duration(milliseconds: 200));
|
||||
await startScan(continuous: true);
|
||||
}
|
||||
|
||||
Future<void> stopScan() async {
|
||||
_scanGen++;
|
||||
developer.log('[BLE] stopScan, gen=$_scanGen', name: 'BleManager');
|
||||
_scanSubscription?.cancel();
|
||||
await FlutterBluePlus.stopScan();
|
||||
}
|
||||
|
||||
/// 连接设备,返回 null 表示成功,返回错误信息字符串表示失败
|
||||
Future<String?> connect(BluetoothDevice device) async {
|
||||
// 标记正在连接,通知所有监听者
|
||||
_connectingDevice = device;
|
||||
_connectingController.add(device);
|
||||
try {
|
||||
await device
|
||||
.connect(license: License.nonprofit, mtu: 512)
|
||||
.timeout(const Duration(seconds: 15));
|
||||
_connectedDevice = device;
|
||||
// 连接成功,立即停止扫描(避免扫描射频干扰导致连接断开)
|
||||
await stopScan();
|
||||
// 清除连接中状态
|
||||
_connectingDevice = null;
|
||||
_connectingController.add(null);
|
||||
// 监听设备连接状态,任何一方断开都能感知
|
||||
_deviceConnectionSubscription?.cancel();
|
||||
_deviceConnectionSubscription = device.connectionState.listen((state) {
|
||||
developer.log(
|
||||
'[BLE] device connectionState: $state',
|
||||
name: 'BleManager',
|
||||
);
|
||||
if (state == BluetoothConnectionState.disconnected) {
|
||||
_onDeviceDisconnected();
|
||||
}
|
||||
});
|
||||
_connectionController.add(device);
|
||||
await _discoverServices(device);
|
||||
// 确认协商后的 MTU
|
||||
try {
|
||||
final mtu = await device.requestMtu(512);
|
||||
_negotiatedMtu = mtu;
|
||||
developer.log('[BLE] MTU: $mtu', name: 'BleManager');
|
||||
} catch (e) {
|
||||
developer.log('[BLE] requestMtu failed: $e', name: 'BleManager');
|
||||
}
|
||||
return null; // 成功
|
||||
} catch (e) {
|
||||
// 连接失败,清除连接中状态
|
||||
_connectingDevice = null;
|
||||
_connectingController.add(null);
|
||||
// 返回具体的错误原因
|
||||
if (e is TimeoutException) {
|
||||
return '连接超时(15秒),请确认设备在附近且已开启';
|
||||
}
|
||||
return '连接失败: $e';
|
||||
}
|
||||
}
|
||||
|
||||
void _onDeviceDisconnected() {
|
||||
_connectedDevice = null;
|
||||
_connectingDevice = null;
|
||||
_writeCharacteristic = null;
|
||||
_readCharacteristic = null;
|
||||
_negotiatedMtu = 23;
|
||||
_readSubscription?.cancel();
|
||||
_deviceConnectionSubscription?.cancel();
|
||||
_connectionController.add(null);
|
||||
_connectingController.add(null);
|
||||
// 清空协议解析器缓冲区
|
||||
_parser.clear();
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
final device = _connectedDevice;
|
||||
if (device == null) return;
|
||||
developer.log('[BLE] 发起断开连接...', name: 'BleManager');
|
||||
await device.disconnect();
|
||||
// 等待连接状态流确认已断开,设置超时防止无限等待
|
||||
try {
|
||||
await device.connectionState
|
||||
.firstWhere((s) => s == BluetoothConnectionState.disconnected)
|
||||
.timeout(const Duration(seconds: 3));
|
||||
developer.log('[BLE] 连接已确认断开', name: 'BleManager');
|
||||
} catch (_) {
|
||||
developer.log('[BLE] 等待断开超时,强制清理', name: 'BleManager');
|
||||
}
|
||||
_onDeviceDisconnected();
|
||||
}
|
||||
|
||||
Future<void> _discoverServices(BluetoothDevice device) async {
|
||||
final services = await device.discoverServices();
|
||||
for (final service in services) {
|
||||
for (final characteristic in service.characteristics) {
|
||||
if (characteristic.properties.write) {
|
||||
_writeCharacteristic = characteristic;
|
||||
}
|
||||
if (characteristic.properties.notify) {
|
||||
_readCharacteristic = characteristic;
|
||||
await characteristic.setNotifyValue(true);
|
||||
_readSubscription?.cancel();
|
||||
_readSubscription = characteristic.lastValueStream.listen((value) {
|
||||
_onDataReceived(value);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _onDataReceived(List<int> data) {
|
||||
developer.log(
|
||||
'[BLE] 📩 收: ${data.length}B ${_bytesToHex(data)}',
|
||||
name: 'BleManager',
|
||||
);
|
||||
_parser.append(data);
|
||||
final packets = _parser.parse();
|
||||
developer.log(
|
||||
'[BLE] 📦 解析 ${packets.length}包 (buf ${_parser.bufferLength}B)',
|
||||
name: 'BleManager',
|
||||
);
|
||||
if (packets.isEmpty && data.isNotEmpty) {
|
||||
developer.log(
|
||||
'[BLE] ⚠️ 非标准帧 raw(${data.length}B)',
|
||||
name: 'BleManager',
|
||||
);
|
||||
final packet = BlePacket(
|
||||
command: 0x00,
|
||||
payload: Uint8List.fromList(data),
|
||||
);
|
||||
_storePacket(packet);
|
||||
_packetController.add(packet);
|
||||
return;
|
||||
}
|
||||
for (final packet in packets) {
|
||||
developer.log(
|
||||
'[BLE] cmd=0x${packet.command.toRadixString(16).toUpperCase().padLeft(2, '0')} '
|
||||
'payload(${packet.payload.length}B): ${_bytesToHex(packet.payload)}',
|
||||
name: 'BleManager',
|
||||
);
|
||||
_storePacket(packet);
|
||||
_packetController.add(packet);
|
||||
}
|
||||
}
|
||||
|
||||
void _storePacket(BlePacket packet) {
|
||||
receivedPacketStore.insert(0, packet);
|
||||
if (receivedPacketStore.length > _maxStoredPackets) {
|
||||
receivedPacketStore.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
String _bytesToHex(List<int> bytes) {
|
||||
if (bytes.isEmpty) return '';
|
||||
return bytes
|
||||
.map((b) => b.toRadixString(16).toUpperCase().padLeft(2, '0'))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
Future<void> sendCommand(int command, List<int> payload) async {
|
||||
final char = _writeCharacteristic;
|
||||
if (char == null) {
|
||||
developer.log('[BLE] ❌ 写特征为空,无法发送', name: 'BleManager');
|
||||
return;
|
||||
}
|
||||
final frame = ProtocolParser.pack(command, payload);
|
||||
final crc = frame.length >= 5
|
||||
? 'CRC16=0x${frame[frame.length - 4].toRadixString(16).padLeft(2, '0')}${frame[frame.length - 3].toRadixString(16).padLeft(2, '0')}'
|
||||
: '';
|
||||
developer.log(
|
||||
'[BLE] 📤 发送: 0x${command.toRadixString(16).toUpperCase().padLeft(2, '0')}, '
|
||||
'帧(${frame.length}B) $crc\n'
|
||||
' ${_bytesToHex(frame)}',
|
||||
name: 'BleManager',
|
||||
);
|
||||
// 分片写入:每次最多写 (MTU - 3) 字节,全部走 withResponse 确保可靠性
|
||||
final maxWriteLen = _negotiatedMtu - 3;
|
||||
final totalChunks = (frame.length + maxWriteLen - 1) ~/ maxWriteLen;
|
||||
if (totalChunks > 1) {
|
||||
developer.log(
|
||||
'[BLE] 🔀 分${totalChunks}片写入 (MTU=$_negotiatedMtu, 每片≤${maxWriteLen}B)',
|
||||
name: 'BleManager',
|
||||
);
|
||||
}
|
||||
for (int offset = 0; offset < frame.length; offset += maxWriteLen) {
|
||||
final end = (offset + maxWriteLen <= frame.length)
|
||||
? offset + maxWriteLen
|
||||
: frame.length;
|
||||
final chunk = frame.sublist(offset, end);
|
||||
if (totalChunks > 1) {
|
||||
final chunkIdx = offset ~/ maxWriteLen + 1;
|
||||
developer.log(
|
||||
'[BLE] 片$chunkIdx/$totalChunks: offset=$offset len=${chunk.length}B ${_bytesToHex(chunk)}',
|
||||
name: 'BleManager',
|
||||
);
|
||||
}
|
||||
await char.write(chunk, withoutResponse: false);
|
||||
}
|
||||
developer.log('[BLE] ✅ 写入完成', name: 'BleManager');
|
||||
}
|
||||
|
||||
Future<void> sendRawBytes(List<int> bytes) async {
|
||||
if (_writeCharacteristic == null) return;
|
||||
await _writeCharacteristic!.write(bytes, withoutResponse: false);
|
||||
}
|
||||
|
||||
Future<void> sendHeartbeat() async {
|
||||
await sendCommand(0xFF, []);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_scanSubscription?.cancel();
|
||||
_readSubscription?.cancel();
|
||||
_adapterStateSubscription?.cancel();
|
||||
_deviceConnectionSubscription?.cancel();
|
||||
_scanController.close();
|
||||
_packetController.close();
|
||||
_connectionController.close();
|
||||
_connectingController.close();
|
||||
}
|
||||
}
|
||||
722
lib/core/bluetooth/ble_protocol_decoder.dart
Normal file
722
lib/core/bluetooth/ble_protocol_decoder.dart
Normal file
@@ -0,0 +1,722 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:typed_data';
|
||||
import '../protocol/machine_protocol_constants.dart';
|
||||
import 'mc700_device_config.dart';
|
||||
|
||||
/// BLE 协议解析出的单个字段
|
||||
class BleField {
|
||||
final String label;
|
||||
final String value;
|
||||
const BleField({required this.label, required this.value});
|
||||
}
|
||||
|
||||
/// BLE 协议解析结果
|
||||
class BleDecodedResult {
|
||||
final List<BleField> fields;
|
||||
final String rawHex;
|
||||
|
||||
/// 0x05 读配置时携带的配置实体(可修改后回写)
|
||||
final Mc700DeviceConfig? configEntity;
|
||||
const BleDecodedResult({
|
||||
required this.fields,
|
||||
required this.rawHex,
|
||||
this.configEntity,
|
||||
});
|
||||
bool get isEmpty => fields.isEmpty;
|
||||
}
|
||||
|
||||
/// BLE 协议解析器
|
||||
/// 与 TCP net_message_dispatcher 使用相同的协议格式:AB AA cmd [payload] ... AA AB
|
||||
/// payload 通常为 UTF-8 逗号分隔文本,部分指令为二进制
|
||||
class BleProtocolDecoder {
|
||||
/// 入口:按命令类型分发解析
|
||||
static BleDecodedResult decode(int command, Uint8List payload) {
|
||||
final hex = _bytesToHex(payload);
|
||||
try {
|
||||
switch (command) {
|
||||
case MachineProtocolConstants.cmdStatusInfo:
|
||||
return _decodeStatusInfo(payload, hex);
|
||||
case MachineProtocolConstants.cmdRemoteControl:
|
||||
return _decodeRemoteControl(payload, hex);
|
||||
case MachineProtocolConstants.cmdGetId:
|
||||
return _decodeGetId(payload, hex);
|
||||
case MachineProtocolConstants.cmdGetAuth:
|
||||
return _decodeGetAuth(payload, hex);
|
||||
case MachineProtocolConstants.cmdReadConfig:
|
||||
return _decodeReadConfig(payload, hex);
|
||||
case MachineProtocolConstants.cmdWriteConfig:
|
||||
return _decodeWriteConfig(payload, hex);
|
||||
case MachineProtocolConstants.cmdHeartbeat:
|
||||
return _decodeHeartbeat(payload, hex);
|
||||
case MachineProtocolConstants.cmdPathPlanning:
|
||||
return _decodePathPlanning(payload, hex);
|
||||
case MachineProtocolConstants.cmdObstacleAvoid:
|
||||
return _decodeObstacleAvoid(payload, hex);
|
||||
default:
|
||||
return _decodeGeneric(command, payload, hex);
|
||||
}
|
||||
} catch (e) {
|
||||
return BleDecodedResult(
|
||||
fields: [const BleField(label: '解析错误', value: '异常')],
|
||||
rawHex: hex,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 0x02 状态信息(与 TCP RunningStatusEntity.fromFields 一致,24字段逗号分隔) ───
|
||||
static BleDecodedResult _decodeStatusInfo(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
|
||||
try {
|
||||
final text = utf8.decode(data);
|
||||
if (text.contains(',')) {
|
||||
final parts = text.split(',');
|
||||
return BleDecodedResult(fields: _parseStatusFields(parts), rawHex: hex);
|
||||
}
|
||||
} catch (e) {
|
||||
try {
|
||||
final text = latin1.decode(data);
|
||||
if (text.contains(',')) {
|
||||
final parts = text.split(',');
|
||||
return BleDecodedResult(
|
||||
fields: _parseStatusFields(parts),
|
||||
rawHex: hex,
|
||||
);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (data.isNotEmpty) {
|
||||
final status = data[0];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '状态码',
|
||||
value: '0x${status.toRadixString(16).toUpperCase().padLeft(2, '0')}',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.length >= 2) {
|
||||
final mode = data[1];
|
||||
const modes = {0x00: '待机', 0x01: '遥控', 0x02: '自动', 0x03: '急停'};
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '控制模式',
|
||||
value: modes[mode] ?? '未知(0x${mode.toRadixString(16)})',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.length >= 3)
|
||||
fields.add(BleField(label: '电量', value: '${data[2]}%'));
|
||||
if (data.length >= 4) {
|
||||
final fault = data[3];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '故障状态',
|
||||
value: fault == 0
|
||||
? '无故障'
|
||||
: '故障码: 0x${fault.toRadixString(16).toUpperCase().padLeft(2, '0')}',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.length >= 6) {
|
||||
final speed = (data[5] << 8) | data[4];
|
||||
fields.add(BleField(label: '速度', value: '$speed'));
|
||||
}
|
||||
if (data.length > 8) {
|
||||
try {
|
||||
final text = String.fromCharCodes(data.sublist(8));
|
||||
if (text.isNotEmpty && !text.contains('\x00')) {
|
||||
fields.add(BleField(label: '附加', value: text));
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
/// 解析逗号分隔的 24 字段状态数据(与 RunningStatusEntity.fromFields 完全一致)
|
||||
static List<BleField> _parseStatusFields(List<String> parts) {
|
||||
while (parts.length < 24) {
|
||||
parts.add('');
|
||||
}
|
||||
|
||||
String controlModeText(String v) {
|
||||
return switch (v) {
|
||||
'0' => '待机',
|
||||
'1' => '遥控',
|
||||
'2' => '自动',
|
||||
'3' => '急停',
|
||||
_ => v.isNotEmpty ? v : '--',
|
||||
};
|
||||
}
|
||||
|
||||
String qualText(String v) {
|
||||
final q = int.tryParse(v) ?? -1;
|
||||
return switch (q) {
|
||||
0 => '无效',
|
||||
1 => '单点定位',
|
||||
2 => '差分定位',
|
||||
4 => '固定解',
|
||||
5 => '浮点解',
|
||||
_ => v.isNotEmpty ? v : '--',
|
||||
};
|
||||
}
|
||||
|
||||
String headingText(String v) {
|
||||
final h = int.tryParse(v) ?? -1;
|
||||
return switch (h) {
|
||||
0 => '未初始化',
|
||||
1 => '已初始化',
|
||||
_ => v.isNotEmpty ? v : '--',
|
||||
};
|
||||
}
|
||||
|
||||
String obstacleText(String v) {
|
||||
final o = int.tryParse(v) ?? -1;
|
||||
return switch (o) {
|
||||
0 => '无障碍',
|
||||
1 => '有障碍',
|
||||
_ => v.isNotEmpty ? v : '--',
|
||||
};
|
||||
}
|
||||
|
||||
return [
|
||||
BleField(label: '电压', value: '${_tryParseDouble(parts[0])} V'),
|
||||
BleField(label: '左目标速度', value: _tryParseDouble(parts[1])),
|
||||
BleField(label: '右目标速度', value: _tryParseDouble(parts[2])),
|
||||
BleField(label: '左实测速度', value: _tryParseDouble(parts[3])),
|
||||
BleField(label: '右实测速度', value: _tryParseDouble(parts[4])),
|
||||
BleField(label: '左电流', value: '${_tryParseDouble(parts[5])} A'),
|
||||
BleField(label: '右电流', value: '${_tryParseDouble(parts[6])} A'),
|
||||
BleField(label: '左电机温度', value: '${_tryParseDouble(parts[7])} ℃'),
|
||||
BleField(label: '右电机温度', value: '${_tryParseDouble(parts[8])} ℃'),
|
||||
BleField(label: '芯片温度', value: '${_tryParseDouble(parts[9])} ℃'),
|
||||
BleField(label: '偏航角', value: '${_tryParseDouble(parts[10])} °'),
|
||||
BleField(label: '俯仰角', value: '${_tryParseDouble(parts[11])} °'),
|
||||
BleField(label: '翻滚角', value: '${_tryParseDouble(parts[12])} °'),
|
||||
BleField(label: '卫星数量', value: parts[13].isNotEmpty ? parts[13] : '--'),
|
||||
BleField(label: '定位质量', value: qualText(parts[14])),
|
||||
BleField(label: '航向状态', value: headingText(parts[15])),
|
||||
BleField(label: '纬度', value: parts[16].isNotEmpty ? parts[16] : '--'),
|
||||
BleField(label: '经度', value: parts[17].isNotEmpty ? parts[17] : '--'),
|
||||
BleField(label: '时间戳', value: parts[18].isNotEmpty ? parts[18] : '--'),
|
||||
BleField(
|
||||
label: '割刀速度',
|
||||
value: parts[19].isNotEmpty ? '${parts[19]} rpm' : '--',
|
||||
),
|
||||
BleField(label: '控制模式', value: controlModeText(parts[20])),
|
||||
BleField(
|
||||
label: '电量',
|
||||
value: parts[21].isNotEmpty ? '${parts[21]}%' : '--',
|
||||
),
|
||||
BleField(label: '工作面积', value: parts[22].isNotEmpty ? parts[22] : '--'),
|
||||
BleField(label: '障碍物', value: obstacleText(parts[23])),
|
||||
];
|
||||
}
|
||||
|
||||
static String _tryParseDouble(String s) {
|
||||
if (s.isEmpty) return '--';
|
||||
final v = double.tryParse(s);
|
||||
if (v == null) return s;
|
||||
if (v == v.roundToDouble() && v.abs() < 10000) return v.toInt().toString();
|
||||
return v.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
// ─── 0x00 远程遥控 ───
|
||||
static BleDecodedResult _decodeRemoteControl(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
try {
|
||||
final text = utf8.decode(data, allowMalformed: true);
|
||||
if (text.contains(',')) {
|
||||
final parts = text.split(',');
|
||||
while (parts.length < 5) parts.add('');
|
||||
fields.add(
|
||||
BleField(label: '左右速度', value: parts[0].isNotEmpty ? parts[0] : '--'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '前后速度', value: parts[1].isNotEmpty ? parts[1] : '--'),
|
||||
);
|
||||
final modeStr = switch (parts[2]) {
|
||||
'0' => '停止',
|
||||
'1' => '遥控',
|
||||
'2' => '自动',
|
||||
_ => parts[2].isNotEmpty ? parts[2] : '--',
|
||||
};
|
||||
fields.add(BleField(label: '控制模式', value: modeStr));
|
||||
if (parts.length > 3 && parts[3].isNotEmpty)
|
||||
fields.add(BleField(label: '参数4', value: parts[3]));
|
||||
if (parts.length > 4 && parts[4].isNotEmpty)
|
||||
fields.add(BleField(label: '参数5', value: parts[4]));
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
if (data.length >= 5) {
|
||||
fields.add(BleField(label: '左右速度', value: '${(data[1] << 8) | data[0]}'));
|
||||
fields.add(BleField(label: '前后速度', value: '${(data[3] << 8) | data[2]}'));
|
||||
const modes = {0: '停止', 1: '遥控', 2: '自动'};
|
||||
fields.add(
|
||||
BleField(label: '控制模式', value: modes[data[4]] ?? '未知(${data[4]})'),
|
||||
);
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0x03 查询ID ───
|
||||
static BleDecodedResult _decodeGetId(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
try {
|
||||
final text = utf8.decode(data, allowMalformed: true);
|
||||
if (text.replaceAll('\x00', '').trim().isNotEmpty) {
|
||||
fields.add(
|
||||
BleField(label: '设备ID', value: text.replaceAll('\x00', '').trim()),
|
||||
);
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
} catch (_) {}
|
||||
try {
|
||||
final ascii = String.fromCharCodes(data);
|
||||
if (RegExp(r'^[\x20-\x7E]+$').hasMatch(ascii)) {
|
||||
fields.add(BleField(label: '设备ID', value: ascii));
|
||||
} else {
|
||||
fields.add(BleField(label: '设备ID(Hex)', value: hex));
|
||||
}
|
||||
} catch (_) {
|
||||
fields.add(BleField(label: '设备ID(Hex)', value: hex));
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0x04 获取授权 ───
|
||||
static BleDecodedResult _decodeGetAuth(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
try {
|
||||
final text = utf8.decode(data, allowMalformed: true);
|
||||
final trimmed = text.replaceAll('\x00', '').trim();
|
||||
if (trimmed == '1' || trimmed.toLowerCase() == 'true') {
|
||||
fields.add(const BleField(label: '授权状态', value: '已授权'));
|
||||
} else if (trimmed == '0' || trimmed.toLowerCase() == 'false') {
|
||||
fields.add(const BleField(label: '授权状态', value: '未授权'));
|
||||
} else if (trimmed.isNotEmpty) {
|
||||
fields.add(BleField(label: '授权状态', value: trimmed));
|
||||
}
|
||||
if (fields.isNotEmpty)
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
} catch (_) {}
|
||||
|
||||
if (data.isNotEmpty) {
|
||||
if (data[0] == 0x01) {
|
||||
fields.add(const BleField(label: '授权状态', value: '已授权'));
|
||||
} else if (data[0] == 0x00) {
|
||||
fields.add(const BleField(label: '授权状态', value: '未授权'));
|
||||
} else {
|
||||
fields.add(
|
||||
BleField(label: '授权状态(Hex)', value: '0x${data[0].toRadixString(16)}'),
|
||||
);
|
||||
}
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0x05 读配置(按嵌入式协议规范精确解析,171字节) ───
|
||||
static BleDecodedResult _decodeReadConfig(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
if (data.isEmpty) {
|
||||
fields.add(const BleField(label: '状态', value: '空数据'));
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
final bd = ByteData.sublistView(data);
|
||||
final len = data.length;
|
||||
|
||||
// 1. UID固化标志 @payload[0] (帧字节3)
|
||||
if (len >= 1) {
|
||||
fields.add(
|
||||
BleField(
|
||||
label: 'UID固化标志',
|
||||
value: data[0] == 1 ? '已固化' : '未固化(${data[0]})',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 芯片UID @payload[1..45] (帧字节4-48, 45字节)
|
||||
if (len >= 46) {
|
||||
fields.add(
|
||||
BleField(label: '芯片UID', value: _readNullTermString(data, 1, 45)),
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 遥控器通道配置 @payload[46..64] (帧字节49-67, 19字节)
|
||||
if (len >= 65) {
|
||||
fields.add(
|
||||
BleField(label: '遥控器通道配置', value: _bytesToHex(data.sublist(46, 65))),
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 字节68位域 @payload[65] (帧字节68)
|
||||
if (len >= 66) {
|
||||
final b = data[65];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '割刀电机模式',
|
||||
value: (b & 0x03) == 0 ? '纯电' : '油电(${b & 0x03})',
|
||||
),
|
||||
);
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '行走电机模式',
|
||||
value: ((b >> 2) & 0x03) == 0 ? '轮式' : '履带(${(b >> 2) & 0x03})',
|
||||
),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '左轮电机极性', value: (b & 0x10) == 0 ? '高极性' : '低极性(反取)'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '右轮电机极性', value: (b & 0x20) == 0 ? '高极性' : '低极性(反取)'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '左右轮通道交换', value: (b & 0x40) == 0 ? '不交换' : '通道互换'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '联网目标', value: (b & 0x80) == 0 ? 'WiFi' : '4G'),
|
||||
);
|
||||
}
|
||||
|
||||
// 5. 前进速度限制 @payload[66..67] (帧字节69-70, uint16 LE)
|
||||
if (len >= 68) {
|
||||
fields.add(
|
||||
BleField(label: '前进速度限制', value: '${bd.getUint16(66, Endian.little)}'),
|
||||
);
|
||||
}
|
||||
|
||||
// 6. 转向速度限制 @payload[68..69] (帧字节71-72, uint16 LE)
|
||||
if (len >= 70) {
|
||||
fields.add(
|
||||
BleField(label: '转向速度限制', value: '${bd.getUint16(68, Endian.little)}'),
|
||||
);
|
||||
}
|
||||
|
||||
// 7. 字节73位域 @payload[70] (帧字节73)
|
||||
if (len >= 71) {
|
||||
final b = data[70];
|
||||
fields.add(
|
||||
BleField(label: '割刀通道极性', value: (b & 0x01) == 0 ? '高极性' : '低极性(反取)'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '风门通道极性', value: (b & 0x02) == 0 ? '高极性' : '低极性(反取)'),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '油门通道极性', value: (b & 0x04) == 0 ? '高极性' : '低极性(反取)'),
|
||||
);
|
||||
fields.add(BleField(label: '底盘升降保护时间', value: '${(b >> 3) & 0x1F} 秒'));
|
||||
fields.add(
|
||||
BleField(label: 'RTK配置', value: (b & 0x80) == 0 ? '单天线' : '双天线'),
|
||||
);
|
||||
}
|
||||
|
||||
// 8. 字节74位域 @payload[71] (帧字节74)
|
||||
if (len >= 72) {
|
||||
final b = data[71];
|
||||
fields.add(BleField(label: '割刀通道配置', value: '${b & 0x0F}'));
|
||||
fields.add(BleField(label: '风门通道配置', value: '${(b >> 4) & 0x0F}'));
|
||||
}
|
||||
|
||||
// 9. 字节75位域 @payload[72] (帧字节75)
|
||||
if (len >= 73) {
|
||||
final b = data[72];
|
||||
fields.add(BleField(label: '油门通道配置', value: '${b & 0x0F}'));
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '遥控器类型',
|
||||
value: (b >> 4) & 0x07 == 0 ? '飞控' : '自定义遥控器(${(b >> 4) & 0x07})',
|
||||
),
|
||||
);
|
||||
fields.add(
|
||||
BleField(label: '是否搭载继电器板', value: (b & 0x80) == 0 ? '未搭载' : '搭载'),
|
||||
);
|
||||
}
|
||||
|
||||
// 10. 字节76位域 @payload[73] (帧字节76)
|
||||
if (len >= 74) {
|
||||
final b = data[73];
|
||||
fields.add(BleField(label: '底盘升降通道配置', value: '${b & 0x0F}'));
|
||||
fields.add(BleField(label: '底盘通道配置', value: '${(b >> 4) & 0x0F}'));
|
||||
}
|
||||
|
||||
// 11. 字节77位域 @payload[74] (帧字节77)
|
||||
if (len >= 75) {
|
||||
final b = data[74];
|
||||
fields.add(BleField(label: '机械臂通道配置', value: '${b & 0x0F}'));
|
||||
fields.add(BleField(label: '燃油泵通道配置', value: '${(b >> 4) & 0x0F}'));
|
||||
}
|
||||
|
||||
// 12. WiFi名称 @payload[75..94] (帧字节78-97, 20字节)
|
||||
if (len >= 95) {
|
||||
fields.add(
|
||||
BleField(label: 'WiFi名称', value: _readNullTermString(data, 75, 20)),
|
||||
);
|
||||
}
|
||||
|
||||
// 13. WiFi密码 @payload[95..114] (帧字节98-117, 20字节)
|
||||
if (len >= 115) {
|
||||
fields.add(
|
||||
BleField(label: 'WiFi密码', value: _readNullTermString(data, 95, 20)),
|
||||
);
|
||||
}
|
||||
|
||||
// 14. 字节118位域 @payload[115] (帧字节118)
|
||||
if (len >= 116) {
|
||||
final b = data[115];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '电池类型',
|
||||
value: (b & 0x03) == 0 ? '铅酸' : '锂电(${b & 0x03})',
|
||||
),
|
||||
);
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '行走驱动配置',
|
||||
value: switch ((b >> 2) & 0x03) {
|
||||
0 => '风德控',
|
||||
1 => '山东神澜BLDC',
|
||||
2 => '山东神澜FOC',
|
||||
_ => '未知(${(b >> 2) & 0x03})',
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 15. 转速比 @payload[116..119] (帧字节119-122, float LE)
|
||||
if (len >= 120) {
|
||||
final v = bd.getFloat32(116, Endian.little);
|
||||
fields.add(BleField(label: '转速比', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 16. 机器人长度 @payload[120..123] (帧字节123-126, float LE)
|
||||
if (len >= 124) {
|
||||
final v = bd.getFloat32(120, Endian.little);
|
||||
fields.add(BleField(label: '机器人长度', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 17. 机器人宽度 @payload[124..127] (帧字节127-130, float LE)
|
||||
if (len >= 128) {
|
||||
final v = bd.getFloat32(124, Endian.little);
|
||||
fields.add(BleField(label: '机器人宽度', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 18. 机器人高度 @payload[128..131] (帧字节131-134, float LE)
|
||||
if (len >= 132) {
|
||||
final v = bd.getFloat32(128, Endian.little);
|
||||
fields.add(BleField(label: '机器人高度', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 19. 割刀宽度 @payload[132..135] (帧字节135-138, float LE)
|
||||
if (len >= 136) {
|
||||
final v = bd.getFloat32(132, Endian.little);
|
||||
fields.add(BleField(label: '割刀宽度', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 20. 轮胎尺寸 @payload[136..139] (帧字节139-142, float LE)
|
||||
if (len >= 140) {
|
||||
final v = bd.getFloat32(136, Endian.little);
|
||||
fields.add(BleField(label: '轮胎尺寸', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 21. 左轮前进增益 @payload[140..143] (帧字节143-146, float LE)
|
||||
if (len >= 144) {
|
||||
final v = bd.getFloat32(140, Endian.little);
|
||||
fields.add(BleField(label: '左轮前进增益', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 22. 左轮后退增益 @payload[144..147] (帧字节147-150, float LE)
|
||||
if (len >= 148) {
|
||||
final v = bd.getFloat32(144, Endian.little);
|
||||
fields.add(BleField(label: '左轮后退增益', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 23. 右轮前进增益 @payload[148..151] (帧字节151-154, float LE)
|
||||
if (len >= 152) {
|
||||
final v = bd.getFloat32(148, Endian.little);
|
||||
fields.add(BleField(label: '右轮前进增益', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 24. 右轮后退增益 @payload[152..155] (帧字节155-158, float LE)
|
||||
if (len >= 156) {
|
||||
final v = bd.getFloat32(152, Endian.little);
|
||||
fields.add(BleField(label: '右轮后退增益', value: v.toStringAsFixed(2)));
|
||||
}
|
||||
|
||||
// 25. 固件版本 @payload[156..170] (帧字节159-173, 15字节)
|
||||
if (len >= 171) {
|
||||
fields.add(
|
||||
BleField(label: '固件版本', value: _readNullTermString(data, 156, 15)),
|
||||
);
|
||||
}
|
||||
|
||||
// 构建配置实体(用于后续编辑和回写)
|
||||
Mc700DeviceConfig? configEntity;
|
||||
if (data.length >= 171) {
|
||||
try {
|
||||
configEntity = Mc700DeviceConfig.fromBytes(data);
|
||||
} catch (e) {
|
||||
developer.log('[BLE] 配置实体解析失败: $e', name: 'BleProtocolDecoder');
|
||||
}
|
||||
}
|
||||
|
||||
return BleDecodedResult(
|
||||
fields: fields,
|
||||
rawHex: hex,
|
||||
configEntity: configEntity,
|
||||
);
|
||||
}
|
||||
|
||||
/// 读取 null 终止字符串(最多读取 [maxLen] 字节)
|
||||
static String _readNullTermString(Uint8List data, int offset, int maxLen) {
|
||||
final buffer = StringBuffer();
|
||||
for (int i = 0; i < maxLen && offset + i < data.length; i++) {
|
||||
final b = data[offset + i];
|
||||
if (b == 0x00) break;
|
||||
if (b >= 0x20 && b <= 0x7E) {
|
||||
buffer.writeCharCode(b);
|
||||
} else {
|
||||
buffer.writeCharCode(0x2E);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
// ─── 0x06 写配置 ───
|
||||
static BleDecodedResult _decodeWriteConfig(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
if (data.isNotEmpty) {
|
||||
final ok = data[0];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '写入结果',
|
||||
value: ok == 0x01
|
||||
? '成功'
|
||||
: ok == 0x00
|
||||
? '失败'
|
||||
: '0x${ok.toRadixString(16)}',
|
||||
),
|
||||
);
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0xFF 心跳包 ───
|
||||
static BleDecodedResult _decodeHeartbeat(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
if (data.isEmpty) {
|
||||
fields.add(const BleField(label: '心跳', value: '正常'));
|
||||
} else if (data.length >= 2) {
|
||||
final interval = (data[1] << 8) | data[0];
|
||||
fields.add(BleField(label: '心跳间隔', value: '${interval}ms'));
|
||||
} else {
|
||||
fields.add(BleField(label: '心跳数据', value: hex));
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0x01 路径规划 ───
|
||||
static BleDecodedResult _decodePathPlanning(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
try {
|
||||
final text = utf8.decode(data, allowMalformed: true);
|
||||
if (text.contains(',')) {
|
||||
final parts = text.split(',');
|
||||
if (parts.length >= 2) {
|
||||
fields.add(BleField(label: '点编号', value: parts[0]));
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '状态',
|
||||
value: switch (parts[1]) {
|
||||
'1' => '已到达',
|
||||
'2' => '收到指令',
|
||||
_ => parts[1],
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
if (parts.length >= 4) {
|
||||
fields.add(BleField(label: '纬度', value: parts[2]));
|
||||
fields.add(BleField(label: '经度', value: parts[3]));
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
} catch (_) {}
|
||||
if (data.length >= 3) {
|
||||
fields.add(BleField(label: '点编号', value: '${data[0]}'));
|
||||
final status = data.length > 1 ? data[1] : -1;
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '状态',
|
||||
value: status == 0x01
|
||||
? '已到达'
|
||||
: status == 0x02
|
||||
? '收到指令'
|
||||
: '0x${status.toRadixString(16)}',
|
||||
),
|
||||
);
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 0x07 避障 ───
|
||||
static BleDecodedResult _decodeObstacleAvoid(Uint8List data, String hex) {
|
||||
final fields = <BleField>[];
|
||||
if (data.isNotEmpty) {
|
||||
final flag = data[0];
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '避障状态',
|
||||
value: flag == 0x01
|
||||
? '触发'
|
||||
: flag == 0x00
|
||||
? '正常'
|
||||
: '0x${flag.toRadixString(16)}',
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.length >= 3) {
|
||||
fields.add(BleField(label: '距离', value: '${(data[2] << 8) | data[1]}mm'));
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 通用/未知指令 ───
|
||||
static BleDecodedResult _decodeGeneric(
|
||||
int command,
|
||||
Uint8List data,
|
||||
String hex,
|
||||
) {
|
||||
final fields = <BleField>[];
|
||||
try {
|
||||
final text = utf8.decode(data, allowMalformed: true);
|
||||
final trimmed = text.replaceAll('\x00', '').trim();
|
||||
if (trimmed.isNotEmpty) {
|
||||
fields.add(
|
||||
BleField(
|
||||
label: '文本内容',
|
||||
value: trimmed.length > 50
|
||||
? '${trimmed.substring(0, 50)}...'
|
||||
: trimmed,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (_) {}
|
||||
if (fields.isEmpty) {
|
||||
fields.add(BleField(label: '数据长度', value: '${data.length}B'));
|
||||
}
|
||||
return BleDecodedResult(fields: fields, rawHex: hex);
|
||||
}
|
||||
|
||||
// ─── 工具方法 ───
|
||||
static String _bytesToHex(List<int> bytes) {
|
||||
if (bytes.isEmpty) return '';
|
||||
return bytes
|
||||
.map((b) => b.toRadixString(16).toUpperCase().padLeft(2, '0'))
|
||||
.join(' ');
|
||||
}
|
||||
}
|
||||
38
lib/core/bluetooth/bytes_util.dart
Normal file
38
lib/core/bluetooth/bytes_util.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
class BytesUtil {
|
||||
static String bytesToHex(List<int> bytes) {
|
||||
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join();
|
||||
}
|
||||
|
||||
static Uint8List hexToBytes(String hex) {
|
||||
hex = hex.replaceAll(' ', '').replaceAll('-', '');
|
||||
if (hex.length % 2 != 0) hex = '0' + hex;
|
||||
final bytes = Uint8List(hex.length ~/ 2);
|
||||
for (int i = 0; i < hex.length ~/ 2; i++) {
|
||||
bytes[i] = int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static String bytesToString(List<int> bytes) {
|
||||
try {
|
||||
return utf8.decode(bytes);
|
||||
} catch (_) {
|
||||
return String.fromCharCodes(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
static Uint8List stringToBytes(String str) {
|
||||
return Uint8List.fromList(utf8.encode(str));
|
||||
}
|
||||
|
||||
static List<int> toByteList(Uint8List data) {
|
||||
return List<int>.from(data);
|
||||
}
|
||||
|
||||
static String bytesToHexSpaced(List<int> bytes) {
|
||||
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join(' ');
|
||||
}
|
||||
}
|
||||
402
lib/core/bluetooth/mc700_device_config.dart
Normal file
402
lib/core/bluetooth/mc700_device_config.dart
Normal file
@@ -0,0 +1,402 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// MC700设备配置实体类(与嵌入式协议规范一一对应)
|
||||
/// 所有偏移均为 payload 内偏移(ProtocolParser 已剥离帧头/命令/校验/帧尾)
|
||||
/// payload 共 171 字节,索引 0~170
|
||||
class Mc700DeviceConfig {
|
||||
// ====== 字段定义(按嵌入式协议规范) ======
|
||||
|
||||
// --- 基础标识 ---
|
||||
late int uidSolidifiedFlag; // payload[0] UID固化标志 (0=未固化, 1=已固化)
|
||||
late String chipUid; // payload[1..45] 芯片UID (45字节)
|
||||
late List<int> remoteChannelConfig; // payload[46..64] 遥控器通道配置 (19字节)
|
||||
|
||||
// --- 字节68位域 (payload[65]) ---
|
||||
late int knifeMotorMode; // bit0-1 割刀电机模式 (0=纯电, 1=油电)
|
||||
late int walkMotorMode; // bit2-3 行走电机模式 (0=轮式, 1=履带)
|
||||
late bool leftWheelPolarity; // bit4 左轮极性 (false=高, true=低)
|
||||
late bool rightWheelPolarity; // bit5 右轮极性 (false=高, true=低)
|
||||
late bool channelSwap; // bit6 左右轮通道交换
|
||||
late bool use4g; // bit7 联网目标 (false=WiFi, true=4G)
|
||||
|
||||
// --- 速度限制 ---
|
||||
late int forwardSpeedLimit; // payload[66..67] 前进速度限制 (uint16 LE)
|
||||
late int turnSpeedLimit; // payload[68..69] 转向速度限制 (uint16 LE)
|
||||
|
||||
// --- 字节73位域 (payload[70]) ---
|
||||
late bool knifeChannelPolarity; // bit0 割刀通道极性
|
||||
late bool fanChannelPolarity; // bit1 风门通道极性
|
||||
late bool throttleChannelPolarity; // bit2 油门通道极性
|
||||
late int liftProtectTime; // bit3-6 底盘升降保护时间 (秒)
|
||||
late bool dualRtk; // bit7 RTK配置 (false=单天线, true=双天线)
|
||||
|
||||
// --- 字节74位域 (payload[71]) ---
|
||||
late int knifeChannelConfig; // bit0-3 割刀通道配置
|
||||
late int fanChannelConfig; // bit4-7 风门通道配置
|
||||
|
||||
// --- 字节75位域 (payload[72]) ---
|
||||
late int throttleChannelConfig; // bit0-3 油门通道配置
|
||||
late int remoteType; // bit4-6 遥控器类型 (0=飞控, 1=自定义1)
|
||||
late bool relayBoard; // bit7 是否搭载继电器板
|
||||
|
||||
// --- 字节76位域 (payload[73]) ---
|
||||
late int chassisLiftChannel; // bit0-3 底盘升降通道配置
|
||||
late int chassisChannel; // bit4-7 底盘通道配置
|
||||
|
||||
// --- 字节77位域 (payload[74]) ---
|
||||
late int armChannel; // bit0-3 机械臂通道配置
|
||||
late int fuelPumpChannel; // bit4-7 燃油泵通道配置
|
||||
|
||||
// --- WiFi ---
|
||||
late String wifiName; // payload[75..94] WiFi名称 (20字节)
|
||||
late String wifiPassword; // payload[95..114] WiFi密码 (20字节)
|
||||
|
||||
// --- 字节118位域 (payload[115]) ---
|
||||
late int batteryType; // bit0-1 电池类型 (0=铅酸, 1=锂电)
|
||||
late int walkDriveConfig; // bit2-3 行走驱动配置
|
||||
|
||||
// --- 尺寸参数 (float LE) ---
|
||||
late double gearRatio; // payload[116..119] 转速比
|
||||
late double robotLength; // payload[120..123] 机器人长度
|
||||
late double robotWidth; // payload[124..127] 机器人宽度
|
||||
late double robotHeight; // payload[128..131] 机器人高度
|
||||
late double knifeWidth; // payload[132..135] 割刀宽度
|
||||
late double tireSize; // payload[136..139] 轮胎尺寸
|
||||
|
||||
// --- 增益 (float LE) ---
|
||||
late double leftForwardGain; // payload[140..143] 左轮前进增益
|
||||
late double leftBackwardGain; // payload[144..147] 左轮后退增益
|
||||
late double rightForwardGain; // payload[148..151] 右轮前进增益
|
||||
late double rightBackwardGain; // payload[152..155] 右轮后退增益
|
||||
|
||||
// --- 固件版本 ---
|
||||
late String firmwareVersion; // payload[156..170] 固件版本 (15字节)
|
||||
|
||||
Mc700DeviceConfig();
|
||||
|
||||
// ====== 从二进制数据解析(171字节 payload) ======
|
||||
factory Mc700DeviceConfig.fromBytes(Uint8List data) {
|
||||
if (data.length < 171) {
|
||||
throw Exception('数据长度不足171字节,实际${data.length}字节');
|
||||
}
|
||||
final bd = ByteData.sublistView(data);
|
||||
final obj = Mc700DeviceConfig();
|
||||
|
||||
// 1. UID固化标志 @0
|
||||
obj.uidSolidifiedFlag = bd.getUint8(0);
|
||||
// 2. 芯片UID @1..45 (45字节)
|
||||
obj.chipUid = _readNullTerminatedString(data, 1, 45);
|
||||
// 3. 遥控器通道配置 @46..64 (19字节)
|
||||
obj.remoteChannelConfig = List.unmodifiable(data.sublist(46, 65));
|
||||
|
||||
// 4. 字节68位域 @65
|
||||
final b68 = bd.getUint8(65);
|
||||
obj.knifeMotorMode = b68 & 0x03;
|
||||
obj.walkMotorMode = (b68 >> 2) & 0x03;
|
||||
obj.leftWheelPolarity = (b68 & 0x10) != 0;
|
||||
obj.rightWheelPolarity = (b68 & 0x20) != 0;
|
||||
obj.channelSwap = (b68 & 0x40) != 0;
|
||||
obj.use4g = (b68 & 0x80) != 0;
|
||||
|
||||
// 5. 前进速度限制 @66..67
|
||||
obj.forwardSpeedLimit = bd.getUint16(66, Endian.little);
|
||||
// 6. 转向速度限制 @68..69
|
||||
obj.turnSpeedLimit = bd.getUint16(68, Endian.little);
|
||||
|
||||
// 7. 字节73位域 @70
|
||||
final b73 = bd.getUint8(70);
|
||||
obj.knifeChannelPolarity = (b73 & 0x01) != 0;
|
||||
obj.fanChannelPolarity = (b73 & 0x02) != 0;
|
||||
obj.throttleChannelPolarity = (b73 & 0x04) != 0;
|
||||
obj.liftProtectTime = (b73 >> 3) & 0x1F;
|
||||
obj.dualRtk = (b73 & 0x80) != 0;
|
||||
|
||||
// 8. 字节74位域 @71
|
||||
final b74 = bd.getUint8(71);
|
||||
obj.knifeChannelConfig = b74 & 0x0F;
|
||||
obj.fanChannelConfig = (b74 >> 4) & 0x0F;
|
||||
|
||||
// 9. 字节75位域 @72
|
||||
final b75 = bd.getUint8(72);
|
||||
obj.throttleChannelConfig = b75 & 0x0F;
|
||||
obj.remoteType = (b75 >> 4) & 0x07;
|
||||
obj.relayBoard = (b75 & 0x80) != 0;
|
||||
|
||||
// 10. 字节76位域 @73
|
||||
final b76 = bd.getUint8(73);
|
||||
obj.chassisLiftChannel = b76 & 0x0F;
|
||||
obj.chassisChannel = (b76 >> 4) & 0x0F;
|
||||
|
||||
// 11. 字节77位域 @74
|
||||
final b77 = bd.getUint8(74);
|
||||
obj.armChannel = b77 & 0x0F;
|
||||
obj.fuelPumpChannel = (b77 >> 4) & 0x0F;
|
||||
|
||||
// 12. WiFi名称 @75..94 (20字节)
|
||||
obj.wifiName = _readNullTerminatedString(data, 75, 20);
|
||||
// 13. WiFi密码 @95..114 (20字节)
|
||||
obj.wifiPassword = _readNullTerminatedString(data, 95, 20);
|
||||
|
||||
// 14. 字节118位域 @115
|
||||
final b118 = bd.getUint8(115);
|
||||
obj.batteryType = b118 & 0x03;
|
||||
obj.walkDriveConfig = (b118 >> 2) & 0x03;
|
||||
|
||||
// 15. 转速比 @116..119
|
||||
obj.gearRatio = bd.getFloat32(116, Endian.little);
|
||||
// 16. 机器人长度 @120..123
|
||||
obj.robotLength = bd.getFloat32(120, Endian.little);
|
||||
// 17. 机器人宽度 @124..127
|
||||
obj.robotWidth = bd.getFloat32(124, Endian.little);
|
||||
// 18. 机器人高度 @128..131
|
||||
obj.robotHeight = bd.getFloat32(128, Endian.little);
|
||||
// 19. 割刀宽度 @132..135
|
||||
obj.knifeWidth = bd.getFloat32(132, Endian.little);
|
||||
// 20. 轮胎尺寸 @136..139
|
||||
obj.tireSize = bd.getFloat32(136, Endian.little);
|
||||
|
||||
// 21. 左轮前进增益 @140..143
|
||||
obj.leftForwardGain = bd.getFloat32(140, Endian.little);
|
||||
// 22. 左轮后退增益 @144..147
|
||||
obj.leftBackwardGain = bd.getFloat32(144, Endian.little);
|
||||
// 23. 右轮前进增益 @148..151
|
||||
obj.rightForwardGain = bd.getFloat32(148, Endian.little);
|
||||
// 24. 右轮后退增益 @152..155
|
||||
obj.rightBackwardGain = bd.getFloat32(152, Endian.little);
|
||||
|
||||
// 25. 固件版本 @156..170 (15字节)
|
||||
obj.firmwareVersion = _readNullTerminatedString(data, 156, 15);
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
// ====== 转换回二进制字节(用于写配置下发) ======
|
||||
/// [originalPayload] 是上次读取的 171 字节 payload,用于保留未修改字段
|
||||
Uint8List toBytes(Uint8List originalPayload) {
|
||||
final config = Uint8List.fromList(originalPayload);
|
||||
final bd = ByteData.sublistView(config);
|
||||
|
||||
// UID固化标志 @0(独立字段,不属于字节68)
|
||||
bd.setUint8(0, uidSolidifiedFlag & 0x01);
|
||||
|
||||
// 字节68位域 @65
|
||||
int b68 = 0;
|
||||
b68 |= (knifeMotorMode & 0x03);
|
||||
b68 |= (walkMotorMode & 0x03) << 2;
|
||||
if (leftWheelPolarity) b68 |= 0x10;
|
||||
if (rightWheelPolarity) b68 |= 0x20;
|
||||
if (channelSwap) b68 |= 0x40;
|
||||
if (use4g) b68 |= 0x80;
|
||||
bd.setUint8(65, b68);
|
||||
|
||||
// 速度限制
|
||||
bd.setUint16(66, forwardSpeedLimit, Endian.little);
|
||||
bd.setUint16(68, turnSpeedLimit, Endian.little);
|
||||
|
||||
// 字节73位域 @70
|
||||
int b73 = (liftProtectTime & 0x1F) << 3;
|
||||
if (knifeChannelPolarity) b73 |= 0x01;
|
||||
if (fanChannelPolarity) b73 |= 0x02;
|
||||
if (throttleChannelPolarity) b73 |= 0x04;
|
||||
if (dualRtk) b73 |= 0x80;
|
||||
bd.setUint8(70, b73);
|
||||
|
||||
// 字节74位域 @71
|
||||
int b74 = knifeChannelConfig & 0x0F;
|
||||
b74 |= (fanChannelConfig & 0x0F) << 4;
|
||||
bd.setUint8(71, b74);
|
||||
|
||||
// 字节75位域 @72
|
||||
int b75 = throttleChannelConfig & 0x0F;
|
||||
b75 |= (remoteType & 0x07) << 4;
|
||||
if (relayBoard) b75 |= 0x80;
|
||||
bd.setUint8(72, b75);
|
||||
|
||||
// 字节76位域 @73
|
||||
int b76 = chassisLiftChannel & 0x0F;
|
||||
b76 |= (chassisChannel & 0x0F) << 4;
|
||||
bd.setUint8(73, b76);
|
||||
|
||||
// 字节77位域 @74
|
||||
int b77 = armChannel & 0x0F;
|
||||
b77 |= (fuelPumpChannel & 0x0F) << 4;
|
||||
bd.setUint8(74, b77);
|
||||
|
||||
// WiFi
|
||||
_writeNullTerminatedString(config, 75, wifiName, 20);
|
||||
_writeNullTerminatedString(config, 95, wifiPassword, 20);
|
||||
|
||||
// 字节118位域 @115
|
||||
int b118 = batteryType & 0x03;
|
||||
b118 |= (walkDriveConfig & 0x03) << 2;
|
||||
bd.setUint8(115, b118);
|
||||
|
||||
// 尺寸参数
|
||||
bd.setFloat32(116, gearRatio, Endian.little);
|
||||
bd.setFloat32(120, robotLength, Endian.little);
|
||||
bd.setFloat32(124, robotWidth, Endian.little);
|
||||
bd.setFloat32(128, robotHeight, Endian.little);
|
||||
bd.setFloat32(132, knifeWidth, Endian.little);
|
||||
bd.setFloat32(136, tireSize, Endian.little);
|
||||
|
||||
// 增益
|
||||
bd.setFloat32(140, leftForwardGain, Endian.little);
|
||||
bd.setFloat32(144, leftBackwardGain, Endian.little);
|
||||
bd.setFloat32(148, rightForwardGain, Endian.little);
|
||||
bd.setFloat32(152, rightBackwardGain, Endian.little);
|
||||
|
||||
// 固件版本
|
||||
_writeNullTerminatedString(config, 156, firmwareVersion, 15);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/// 获取所有字段的 label→value 映射
|
||||
Map<String, String> toFieldMap() {
|
||||
return {
|
||||
'UID固化标志': '$uidSolidifiedFlag',
|
||||
'芯片UID': chipUid,
|
||||
'割刀电机模式': knifeMotorMode == 0 ? '纯电' : '油电($knifeMotorMode)',
|
||||
'行走电机模式': walkMotorMode == 0 ? '轮式' : '履带($walkMotorMode)',
|
||||
'左轮极性': leftWheelPolarity ? '低' : '高',
|
||||
'右轮极性': rightWheelPolarity ? '低' : '高',
|
||||
'通道交换': channelSwap ? '是' : '否',
|
||||
'联网目标': use4g ? '4G' : 'WiFi',
|
||||
'前进速度限制': '$forwardSpeedLimit',
|
||||
'转向速度限制': '$turnSpeedLimit',
|
||||
'割刀通道极性': knifeChannelPolarity ? '低' : '高',
|
||||
'风门通道极性': fanChannelPolarity ? '低' : '高',
|
||||
'油门通道极性': throttleChannelPolarity ? '低' : '高',
|
||||
'升降保护时间': '$liftProtectTime 秒',
|
||||
'RTK配置': dualRtk ? '双天线' : '单天线',
|
||||
'割刀通道配置': '$knifeChannelConfig',
|
||||
'风门通道配置': '$fanChannelConfig',
|
||||
'油门通道配置': '$throttleChannelConfig',
|
||||
'遥控器类型': '$remoteType',
|
||||
'搭载继电器板': relayBoard ? '是' : '否',
|
||||
'底盘升降通道': '$chassisLiftChannel',
|
||||
'底盘通道': '$chassisChannel',
|
||||
'机械臂通道': '$armChannel',
|
||||
'燃油泵通道': '$fuelPumpChannel',
|
||||
'WiFi名称': wifiName,
|
||||
'WiFi密码': wifiPassword,
|
||||
'电池类型': batteryType == 0 ? '铅酸' : '锂电',
|
||||
'行走驱动': walkDriveConfig.toString(),
|
||||
'转速比': gearRatio.toStringAsFixed(2),
|
||||
'机器人长度': robotLength.toStringAsFixed(2),
|
||||
'机器人宽度': robotWidth.toStringAsFixed(2),
|
||||
'机器人高度': robotHeight.toStringAsFixed(2),
|
||||
'割刀宽度': knifeWidth.toStringAsFixed(2),
|
||||
'轮胎尺寸': tireSize.toStringAsFixed(2),
|
||||
'左轮前进增益': leftForwardGain.toStringAsFixed(2),
|
||||
'左轮后退增益': leftBackwardGain.toStringAsFixed(2),
|
||||
'右轮前进增益': rightForwardGain.toStringAsFixed(2),
|
||||
'右轮后退增益': rightBackwardGain.toStringAsFixed(2),
|
||||
'固件版本': firmwareVersion,
|
||||
};
|
||||
}
|
||||
|
||||
/// 根据字段标签设置新值(返回 null 表示成功,返回错误原因字符串)
|
||||
String? setField(String label, String value) {
|
||||
final intVal = int.tryParse(value);
|
||||
final doubleVal = double.tryParse(value);
|
||||
|
||||
switch (label) {
|
||||
case 'UID固化标志':
|
||||
if (intVal == null || intVal < 0 || intVal > 1) return '值范围: 0~1';
|
||||
uidSolidifiedFlag = intVal;
|
||||
return null;
|
||||
case '前进速度限制':
|
||||
if (intVal == null || intVal < 0 || intVal > 65535)
|
||||
return '值范围: 0~65535';
|
||||
forwardSpeedLimit = intVal;
|
||||
return null;
|
||||
case '转向速度限制':
|
||||
if (intVal == null || intVal < 0 || intVal > 65535)
|
||||
return '值范围: 0~65535';
|
||||
turnSpeedLimit = intVal;
|
||||
return null;
|
||||
case 'WiFi名称':
|
||||
if (value.length > 20) return '最多20字符';
|
||||
wifiName = value;
|
||||
return null;
|
||||
case 'WiFi密码':
|
||||
if (value.length > 20) return '最多20字符';
|
||||
wifiPassword = value;
|
||||
return null;
|
||||
case '转速比':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
gearRatio = doubleVal;
|
||||
return null;
|
||||
case '机器人长度':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
robotLength = doubleVal;
|
||||
return null;
|
||||
case '机器人宽度':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
robotWidth = doubleVal;
|
||||
return null;
|
||||
case '机器人高度':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
robotHeight = doubleVal;
|
||||
return null;
|
||||
case '割刀宽度':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
knifeWidth = doubleVal;
|
||||
return null;
|
||||
case '轮胎尺寸':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
tireSize = doubleVal;
|
||||
return null;
|
||||
case '左轮前进增益':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
leftForwardGain = doubleVal;
|
||||
return null;
|
||||
case '左轮后退增益':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
leftBackwardGain = doubleVal;
|
||||
return null;
|
||||
case '右轮前进增益':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
rightForwardGain = doubleVal;
|
||||
return null;
|
||||
case '右轮后退增益':
|
||||
if (doubleVal == null) return '请输入有效数字';
|
||||
rightBackwardGain = doubleVal;
|
||||
return null;
|
||||
case '固件版本':
|
||||
if (value.length > 15) return '最多15字符';
|
||||
firmwareVersion = value;
|
||||
return null;
|
||||
default:
|
||||
return '未知字段: $label';
|
||||
}
|
||||
}
|
||||
|
||||
// 工具:读取0结尾的ASCII字符串
|
||||
static String _readNullTerminatedString(
|
||||
Uint8List data,
|
||||
int offset,
|
||||
int maxLen,
|
||||
) {
|
||||
final end = data.indexOf(0, offset);
|
||||
final realEnd = (end == -1 || end > offset + maxLen)
|
||||
? offset + maxLen
|
||||
: end;
|
||||
return ascii.decode(data.sublist(offset, realEnd));
|
||||
}
|
||||
|
||||
// 工具:写入ASCII字符串,不足补0
|
||||
static void _writeNullTerminatedString(
|
||||
Uint8List data,
|
||||
int offset,
|
||||
String str,
|
||||
int maxLen,
|
||||
) {
|
||||
final bytes = ascii.encode(str);
|
||||
for (int i = 0; i < maxLen; i++) {
|
||||
data[offset + i] = i < bytes.length ? bytes[i] : 0x00;
|
||||
}
|
||||
}
|
||||
}
|
||||
122
lib/core/bluetooth/protocol_parser.dart
Normal file
122
lib/core/bluetooth/protocol_parser.dart
Normal file
@@ -0,0 +1,122 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
class BlePacket {
|
||||
final int command;
|
||||
final Uint8List payload;
|
||||
const BlePacket({required this.command, required this.payload});
|
||||
}
|
||||
|
||||
/// 有状态的 BLE 协议解析器
|
||||
/// 支持分片接收:多次调用 [append] 累积数据,[parse] 提取完整帧
|
||||
class ProtocolParser {
|
||||
static const int _header1 = 0xAB;
|
||||
static const int _header2 = 0xAA;
|
||||
static const int _tail1 = 0xAA;
|
||||
static const int _tail2 = 0xAB;
|
||||
|
||||
final List<int> _buffer = [];
|
||||
|
||||
/// 清空缓冲区
|
||||
void clear() {
|
||||
_buffer.clear();
|
||||
}
|
||||
|
||||
/// 获取缓冲区长度
|
||||
int get bufferLength => _buffer.length;
|
||||
|
||||
/// 打包命令为字节帧(用于发送)
|
||||
/// CRC16 覆盖 command + payload 确保整帧完整性
|
||||
static Uint8List pack(int command, List<int> payload) {
|
||||
final dataToCheck = [command, ...payload];
|
||||
final crc = _crc16(dataToCheck);
|
||||
final builder = BytesBuilder()
|
||||
..addByte(_header1)
|
||||
..addByte(_header2)
|
||||
..addByte(command)
|
||||
..add(payload)
|
||||
..addByte(crc & 0xFF)
|
||||
..addByte((crc >> 8) & 0xFF)
|
||||
..addByte(_tail1)
|
||||
..addByte(_tail2);
|
||||
return builder.takeBytes();
|
||||
}
|
||||
|
||||
/// 追加新接收的数据到缓冲区
|
||||
void append(List<int> data) {
|
||||
_buffer.addAll(data);
|
||||
}
|
||||
|
||||
/// 从缓冲区解析所有完整的数据包
|
||||
/// 未完成的帧保留在缓冲区等待后续数据
|
||||
List<BlePacket> parse() {
|
||||
final List<BlePacket> packets = [];
|
||||
|
||||
while (_buffer.length >= 6) {
|
||||
// 1. 查找帧头
|
||||
int headIdx = -1;
|
||||
for (int i = 0; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == _header1 && _buffer[i + 1] == _header2) {
|
||||
headIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (headIdx == -1) {
|
||||
// 无有效帧头,清空缓冲区
|
||||
_buffer.clear();
|
||||
break;
|
||||
}
|
||||
|
||||
// 移除帧头前的垃圾数据
|
||||
if (headIdx > 0) _buffer.removeRange(0, headIdx);
|
||||
|
||||
// 2. 查找帧尾
|
||||
int tailIdx = -1;
|
||||
for (int i = 2; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == _tail1 && _buffer[i + 1] == _tail2) {
|
||||
tailIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tailIdx == -1) {
|
||||
// 帧尾未找到,可能是分片数据,等待更多数据
|
||||
break;
|
||||
}
|
||||
|
||||
// 3. 提取数据包
|
||||
if (_buffer.length >= 5) {
|
||||
final cmd = _buffer[2];
|
||||
final payload = Uint8List.fromList(_buffer.sublist(3, tailIdx));
|
||||
packets.add(BlePacket(command: cmd, payload: payload));
|
||||
}
|
||||
|
||||
// 4. 移除已处理的帧
|
||||
_buffer.removeRange(0, tailIdx + 2);
|
||||
}
|
||||
|
||||
return packets;
|
||||
}
|
||||
|
||||
/// 便捷方法:追加数据并立即解析
|
||||
List<BlePacket> appendAndParse(List<int> data) {
|
||||
append(data);
|
||||
return parse();
|
||||
}
|
||||
|
||||
/// CRC16-Modbus: polynomial=0x8005, init=0xFFFF, refIn/refOut=true
|
||||
static int _crc16(List<int> data) {
|
||||
int crc = 0xFFFF;
|
||||
for (final b in data) {
|
||||
crc ^= b;
|
||||
for (int j = 0; j < 8; j++) {
|
||||
if ((crc & 0x0001) != 0) {
|
||||
crc = (crc >> 1) ^ 0xA001;
|
||||
} else {
|
||||
crc >>= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,14 @@ class HttpApiConsts {
|
||||
// 获取设备列表
|
||||
static const String getUserDevicesList = "$baseUrl/iot/device/list";
|
||||
// 绑定设备
|
||||
static const String bindDevice = "$baseUrl/forward/device/bind";
|
||||
static const String bindDevice = "$baseUrl/iot/device/bind";
|
||||
// 解绑设备
|
||||
static const String unbindDevice = "$baseUrl/forward/device/unbind";
|
||||
// 切换设备
|
||||
static const String switchDevice = "$baseUrl/forward/device/switchDevice";
|
||||
|
||||
// 获取光伏电站列表
|
||||
static const String getSiteList = "$baseUrl/system/site/list";
|
||||
static const String getSiteList = "$baseUrl/system/site/selectByUserId";
|
||||
|
||||
// 获取场站下的设备列表
|
||||
static const String getSiteDeviceList = "$baseUrl/iot/device/getSiteList";
|
||||
@@ -42,7 +42,8 @@ class HttpApiConsts {
|
||||
static const String getFlightTask = "$baseUrl/iot/UAV/getFlightTask";
|
||||
|
||||
// 获取飞行任务详情
|
||||
static const String getFlightTaskDetail = "$baseUrl/iot/UAV/getFlightTaskDetail";
|
||||
static const String getFlightTaskDetail =
|
||||
"$baseUrl/iot/UAV/getFlightTaskDetail";
|
||||
|
||||
// 获取航线列表
|
||||
static const String getWayline = "$baseUrl/iot/UAV/getWayline";
|
||||
@@ -51,7 +52,8 @@ class HttpApiConsts {
|
||||
static const String createFlightTask = "$baseUrl/iot/UAV/createFlightTask";
|
||||
|
||||
// 更新飞行任务状态
|
||||
static const String updateFlightTaskStatus = "$baseUrl/iot/UAV/updateFlightTaskStatus";
|
||||
static const String updateFlightTaskStatus =
|
||||
"$baseUrl/iot/UAV/updateFlightTaskStatus";
|
||||
|
||||
// 切换无人机镜头获取视频流
|
||||
static const String changeUAVLens = "$baseUrl/iot/UAV/changeLens";
|
||||
@@ -61,4 +63,56 @@ class HttpApiConsts {
|
||||
|
||||
// 飞行任务命令控制(暂停、返航等)
|
||||
static const String flightTaskCommand = "$baseUrl/iot/UAV/flightTaskCommand";
|
||||
|
||||
/// 告警相关
|
||||
static const String alarmBaseUrl = "http://1.95.137.212:8081";
|
||||
// 获取告警工单配置列表
|
||||
static const String alarmOrderConfigList =
|
||||
"$alarmBaseUrl/iot/alarmOrderConfig/list";
|
||||
// 获取告警列表
|
||||
static const String alarmList = "$baseUrl/iot/alarm/list";
|
||||
// 获取告警详情
|
||||
static const String alarmDetail = "$baseUrl/iot/alarm";
|
||||
// 处理告警(确认/关闭等)
|
||||
static const String alarmHandle = "$baseUrl/iot/alarm/handle";
|
||||
|
||||
/// 工单相关
|
||||
// 获取工单模型配置列表
|
||||
static const String orderModelList = "$baseUrl/iot/orderModel/list";
|
||||
// 添加工单(上报)
|
||||
static const String workOrderAdd = "$baseUrl/iot/ioTworkOrder/add";
|
||||
// 获取工单列表
|
||||
static const String workOrderList = "$baseUrl/iot/ioTworkOrder/list";
|
||||
// 获取工单详情
|
||||
static const String workOrderDetail = "$baseUrl/iot/ioTworkOrder";
|
||||
// 派发工单
|
||||
static const String workOrderDispat = "$baseUrl/iot/ioTworkOrder/dispatch";
|
||||
// 挂起工单
|
||||
static const String workOrderSuspend = "$baseUrl/iot/ioTworkOrder/suspend";
|
||||
// 完成工单
|
||||
static const String workOrderComplete = "$baseUrl/iot/ioTworkOrder/complete";
|
||||
// 开始执行工单
|
||||
static const String workOrderStart = "$baseUrl/iot/ioTworkOrder/start";
|
||||
// 获取工单统计
|
||||
static const String workOrderCount = "$baseUrl/iot/ioTworkOrder/count";
|
||||
// 设备运行参数查询
|
||||
static const String deviceRunParamSelect =
|
||||
"$baseUrl/iot/deviceRunParam/selectByDeviceId";
|
||||
// 设备运行参数保存
|
||||
static const String deviceRunParamSave = "$baseUrl/iot/deviceRunParam/save";
|
||||
|
||||
// 设备操作权限校验
|
||||
static const String hasPermission = "$baseUrl/iot/device/hasPermission";
|
||||
|
||||
/// 用户相关
|
||||
// 获取用户列表
|
||||
static const String systemUserList = "$baseUrl/system/user/list";
|
||||
|
||||
/// 组织与场站相关
|
||||
// 获取组织列表
|
||||
static const String orgList = "$baseUrl/system/org/list";
|
||||
// 根据组织ID获取场站列表
|
||||
static const String siteListByOrgId = "$baseUrl/system/site/selectByOrgId";
|
||||
// 根据场站ID获取用户列表
|
||||
static const String userListBySiteId = "$baseUrl/system/user/list";
|
||||
}
|
||||
|
||||
@@ -52,15 +52,12 @@ import '../../features/devices/domain/usecases/get_device_location_usecase.dart'
|
||||
import '../../features/devices/domain/usecases/get_work_record_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/get_work_records_by_site_id_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/create_device_task_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/get_work_records_by_site_id_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/route_planning_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/save_work_record_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/select_work_record_usecase.dart';
|
||||
import '../../features/devices/domain/usecases/switch_device_usecase.dart';
|
||||
import '../../features/devices/presentation/bloc/device_status_bloc.dart';
|
||||
import '../../features/remote_control/data/datasources/remote_http_datasource.dart';
|
||||
import '../../features/remote_control/data/datasources/remote_tcp_datasource.dart';
|
||||
import '../../features/remote_control/domain/usecase/remote_control_usecase.dart';
|
||||
import '../../features/remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import '../../features/v2/home/data/datasources/home_remote_datasource.dart';
|
||||
import '../../features/v2/home/data/datasources/site_datasource.dart';
|
||||
@@ -96,6 +93,12 @@ import '../../features/v2/device_list/domain/usecases/return_home_usecase.dart';
|
||||
import '../../features/v2/device_list/presentation/bloc/drone_station_bloc.dart';
|
||||
import '../../features/v2/device_list/presentation/bloc/robot_list_bloc.dart';
|
||||
import '../../features/v2/device_list/presentation/bloc/device_realtime_bloc.dart';
|
||||
import '../../features/v2/device_list/data/datasources/bind_device_datasource.dart';
|
||||
import '../../features/v2/device_list/data/datasources/impl/bind_device_datasource_impl.dart';
|
||||
import '../../features/v2/device_list/data/repositories/bind_device_repository_impl.dart';
|
||||
import '../../features/v2/device_list/domain/repositories/bind_device_repository.dart';
|
||||
import '../../features/v2/device_list/domain/usecases/bind_device_usecases.dart';
|
||||
import '../../features/v2/device_list/presentation/cubit/bind_device_cubit.dart';
|
||||
import '../../features/v2/waring_center/data/datasources/alarm_remote_datasource.dart';
|
||||
import '../../features/v2/waring_center/data/datasources/impl/alarm_remote_datasource_impl.dart';
|
||||
import '../../features/v2/waring_center/data/repositories/alarm_repository_impl.dart';
|
||||
@@ -116,6 +119,18 @@ import '../../features/v2/message_center/data/repositories/message_center_reposi
|
||||
import '../../features/v2/message_center/domain/repositories/message_center_repository.dart';
|
||||
import '../../features/v2/message_center/domain/usecases/message_center_usecase.dart';
|
||||
import '../../features/v2/message_center/presentation/bloc/message_center_cubit.dart';
|
||||
import '../../features/v2/work_order/data/datasources/work_order_remote_datasource.dart';
|
||||
import '../../features/v2/work_order/data/datasources/work_order_remote_datasource_impl.dart';
|
||||
import '../../features/v2/work_order/data/repositories/work_order_repository_impl.dart';
|
||||
import '../../features/v2/work_order/domain/repositories/work_order_repository.dart';
|
||||
import '../../features/v2/work_order/domain/usecases/work_order_usecases.dart';
|
||||
import '../../features/v2/work_order/presentation/cubit/work_order_cubit.dart';
|
||||
import '../../features/v2/device_run_param/data/datasources/device_run_param_remote_datasource.dart';
|
||||
import '../../features/v2/device_run_param/data/datasources/device_run_param_remote_datasource_impl.dart';
|
||||
import '../../features/v2/device_run_param/data/repositories/device_run_param_repository_impl.dart';
|
||||
import '../../features/v2/device_run_param/domain/repositories/device_run_param_repository.dart';
|
||||
import '../../features/v2/device_run_param/domain/usecases/device_run_param_usecases.dart';
|
||||
import '../services/device_permission_service.dart';
|
||||
import '../../features/devices/data/datasources/device_task_datasource.dart';
|
||||
import '../../features/devices/data/repositories/device_task_repository_impl.dart';
|
||||
import '../../features/devices/domain/repositories/device_task_repository.dart';
|
||||
@@ -196,7 +211,9 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<ILoggerService>(() => SentryLoggerImpl());
|
||||
|
||||
/// 1.4 --- Route Observer (路由监听器) ---
|
||||
sl.registerLazySingleton<RouteObserver>(() => RouteObserver<ModalRoute<void>>());
|
||||
sl.registerLazySingleton<RouteObserver>(
|
||||
() => RouteObserver<ModalRoute<void>>(),
|
||||
);
|
||||
|
||||
/// 1.5 --- MQTT Data Sources ---
|
||||
sl.registerFactory<DroneOsdDataSource>(
|
||||
@@ -367,9 +384,7 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<PauseFlightTaskUseCase>(
|
||||
() => PauseFlightTaskUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<ReturnHomeUseCase>(
|
||||
() => ReturnHomeUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<ReturnHomeUseCase>(() => ReturnHomeUseCase(sl()));
|
||||
sl.registerFactory<DroneStationBloc>(
|
||||
() => DroneStationBloc(sl(), sl(), sl(), sl()),
|
||||
);
|
||||
@@ -384,7 +399,7 @@ Future<void> init() async {
|
||||
|
||||
/// Alarm Center V2
|
||||
sl.registerLazySingleton<AlarmRemoteDataSource>(
|
||||
() => AlarmRemoteDataSourceImpl(),
|
||||
() => AlarmRemoteDataSourceImpl(sl<Dio>()),
|
||||
);
|
||||
sl.registerLazySingleton<AlarmRepository>(() => AlarmRepositoryImpl(sl()));
|
||||
sl.registerLazySingleton<GetAlarmListUseCase>(
|
||||
@@ -393,13 +408,11 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<GetAlarmCountUseCase>(
|
||||
() => GetAlarmCountUseCase(sl()),
|
||||
);
|
||||
sl.registerFactory<AlarmCubit>(
|
||||
() => AlarmCubit(getAlarmListUseCase: sl(), getAlarmCountUseCase: sl()),
|
||||
);
|
||||
sl.registerFactory<AlarmCubit>(() => AlarmCubit(getAlarmListUseCase: sl()));
|
||||
|
||||
/// Alarm Detail V2
|
||||
sl.registerLazySingleton<AlarmDetailRemoteDataSource>(
|
||||
() => AlarmDetailRemoteDataSourceImpl(),
|
||||
() => AlarmDetailRemoteDataSourceImpl(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<AlarmDetailRepository>(
|
||||
() => AlarmDetailRepositoryImpl(sl()),
|
||||
@@ -410,11 +423,13 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<ConfirmAlarmUseCase>(
|
||||
() => ConfirmAlarmUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<HandleAlarmUseCase>(() => HandleAlarmUseCase(sl()));
|
||||
sl.registerLazySingleton<AIDiagnosisUseCase>(() => AIDiagnosisUseCase(sl()));
|
||||
sl.registerFactory<AlarmDetailCubit>(
|
||||
() => AlarmDetailCubit(
|
||||
getAlarmDetailUseCase: sl(),
|
||||
confirmAlarmUseCase: sl(),
|
||||
handleAlarmUseCase: sl(),
|
||||
aiDiagnosisUseCase: sl(),
|
||||
),
|
||||
);
|
||||
@@ -565,5 +580,84 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton(() => CancelTaskUseCase(sl()));
|
||||
sl.registerLazySingleton(() => PauseTaskUseCase(sl()));
|
||||
sl.registerLazySingleton(() => RecoveryTaskUseCase(sl()));
|
||||
sl.registerFactory(() => DeviceTaskCubit(sl(), sl(), sl(), sl()));
|
||||
sl.registerLazySingleton(() => DeviceTaskCubit(sl(), sl(), sl(), sl()));
|
||||
|
||||
/// 11. 工单管理 (Work Order)
|
||||
sl.registerLazySingleton<WorkOrderRemoteDataSource>(
|
||||
() => WorkOrderRemoteDataSourceImpl(sl<Dio>()),
|
||||
);
|
||||
sl.registerLazySingleton<WorkOrderRepository>(
|
||||
() => WorkOrderRepositoryImpl(remoteDataSource: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<GetWorkOrderListUseCase>(
|
||||
() => GetWorkOrderListUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<GetWorkOrderDetailUseCase>(
|
||||
() => GetWorkOrderDetailUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<DispatchWorkOrderUseCase>(
|
||||
() => DispatchWorkOrderUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<SuspendWorkOrderUseCase>(
|
||||
() => SuspendWorkOrderUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<CompleteWorkOrderUseCase>(
|
||||
() => CompleteWorkOrderUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<StartWorkOrderUseCase>(
|
||||
() => StartWorkOrderUseCase(sl()),
|
||||
);
|
||||
sl.registerFactory<WorkOrderCubit>(
|
||||
() => WorkOrderCubit(
|
||||
getWorkOrderListUseCase: sl(),
|
||||
getWorkOrderDetailUseCase: sl(),
|
||||
dispatchWorkOrderUseCase: sl(),
|
||||
suspendWorkOrderUseCase: sl(),
|
||||
completeWorkOrderUseCase: sl(),
|
||||
startWorkOrderUseCase: sl(),
|
||||
),
|
||||
);
|
||||
|
||||
/// 12. 设备运行参数管理 (Device Run Param)
|
||||
sl.registerLazySingleton<DeviceRunParamRemoteDataSource>(
|
||||
() => DeviceRunParamRemoteDataSourceImpl(sl<Dio>()),
|
||||
);
|
||||
sl.registerLazySingleton<DeviceRunParamRepository>(
|
||||
() => DeviceRunParamRepositoryImpl(remoteDataSource: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<GetDeviceRunParamUseCase>(
|
||||
() => GetDeviceRunParamUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<SaveDeviceRunParamUseCase>(
|
||||
() => SaveDeviceRunParamUseCase(sl()),
|
||||
);
|
||||
|
||||
/// 13. 设备操作权限校验服务 (Device Permission Service)
|
||||
sl.registerLazySingleton<DevicePermissionService>(
|
||||
() => DevicePermissionService(sl<Dio>()),
|
||||
);
|
||||
|
||||
/// 14. 绑定智能装备 (Bind Device)
|
||||
sl.registerLazySingleton<BindDeviceDatasource>(
|
||||
() => BindDeviceDatasourceImpl(sl<Dio>()),
|
||||
);
|
||||
sl.registerLazySingleton<BindDeviceRepository>(
|
||||
() => BindDeviceRepositoryImpl(sl<BindDeviceDatasource>()),
|
||||
);
|
||||
sl.registerLazySingleton<GetOrgListUseCase>(() => GetOrgListUseCase(sl()));
|
||||
sl.registerLazySingleton<GetSitesByOrgUseCase>(
|
||||
() => GetSitesByOrgUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<GetUsersBySiteUseCase>(
|
||||
() => GetUsersBySiteUseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<BindDeviceV2UseCase>(
|
||||
() => BindDeviceV2UseCase(sl()),
|
||||
);
|
||||
sl.registerLazySingleton<IsDeviceAtSiteUseCase>(
|
||||
() => IsDeviceAtSiteUseCase(sl()),
|
||||
);
|
||||
sl.registerFactory<BindDeviceCubit>(
|
||||
() => BindDeviceCubit(sl(), sl(), sl(), sl(), sl(), sl<AppUserCubit>()),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@ class UserEntity extends Equatable {
|
||||
final String username;
|
||||
final String nickname;
|
||||
final String token;
|
||||
final int orgId; // 组织ID,用于获取场站列表
|
||||
final int orgId;
|
||||
final String? avatar;
|
||||
final String? email;
|
||||
final String? phone;
|
||||
final String? roleKey;
|
||||
final int? siteId;
|
||||
|
||||
UserEntity({
|
||||
const UserEntity({
|
||||
required this.userId,
|
||||
required this.username,
|
||||
required this.nickname,
|
||||
@@ -19,6 +21,8 @@ class UserEntity extends Equatable {
|
||||
this.avatar,
|
||||
this.email,
|
||||
this.phone,
|
||||
this.roleKey,
|
||||
this.siteId,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -31,5 +35,33 @@ class UserEntity extends Equatable {
|
||||
orgId,
|
||||
email,
|
||||
phone,
|
||||
roleKey,
|
||||
siteId,
|
||||
];
|
||||
}
|
||||
|
||||
UserEntity copyWith({
|
||||
String? userId,
|
||||
String? username,
|
||||
String? nickname,
|
||||
String? token,
|
||||
int? orgId,
|
||||
String? avatar,
|
||||
String? email,
|
||||
String? phone,
|
||||
String? roleKey,
|
||||
int? siteId,
|
||||
}) {
|
||||
return UserEntity(
|
||||
userId: userId ?? this.userId,
|
||||
username: username ?? this.username,
|
||||
nickname: nickname ?? this.nickname,
|
||||
token: token ?? this.token,
|
||||
orgId: orgId ?? this.orgId,
|
||||
avatar: avatar ?? this.avatar,
|
||||
email: email ?? this.email,
|
||||
phone: phone ?? this.phone,
|
||||
roleKey: roleKey ?? this.roleKey,
|
||||
siteId: siteId ?? this.siteId,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,24 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../features/v2/device_list/domain/entities/drone_station_entity.dart';
|
||||
|
||||
/// 无人机轨迹点(轻量级,避免在核心层引入 latlong2 依赖)
|
||||
class DroneTrajectoryPoint {
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
final double? heading;
|
||||
|
||||
const DroneTrajectoryPoint({
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
this.heading,
|
||||
});
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'DroneTrajectoryPoint(lat=$latitude, lng=$longitude, heading=$heading)';
|
||||
}
|
||||
|
||||
/// 无人机任务信息
|
||||
class DroneTaskInfo {
|
||||
final String droneSn;
|
||||
@@ -33,9 +51,33 @@ class DroneTaskStateManager {
|
||||
final ValueNotifier<DroneTaskInfo?> _currentTaskInfo =
|
||||
ValueNotifier<DroneTaskInfo?>(null);
|
||||
|
||||
/// 任务下发成功后,等待无人机 OSD 推送数据(实时信息)
|
||||
final ValueNotifier<bool> _isWaitingForOsdPush = ValueNotifier<bool>(false);
|
||||
|
||||
/// 任务下发成功后,等待无人机视频流
|
||||
final ValueNotifier<bool> _isWaitingForVideo = ValueNotifier<bool>(false);
|
||||
|
||||
/// 无人机飞行轨迹点(跨页面持久化,退出视频页后不丢失)
|
||||
final ValueNotifier<List<DroneTrajectoryPoint>> _trajectoryPoints =
|
||||
ValueNotifier<List<DroneTrajectoryPoint>>([]);
|
||||
|
||||
/// 超时定时器,避免一直转圈(推送/视频迟迟不到)
|
||||
Timer? _osdWaitTimeoutTimer;
|
||||
Timer? _videoWaitTimeoutTimer;
|
||||
|
||||
/// 监听无人机任务信息变化
|
||||
ValueListenable<DroneTaskInfo?> get currentTaskInfo => _currentTaskInfo;
|
||||
|
||||
/// 监听“等待 OSD 推送”状态
|
||||
ValueListenable<bool> get isWaitingForOsdPush => _isWaitingForOsdPush;
|
||||
|
||||
/// 监听“等待视频流”状态
|
||||
ValueListenable<bool> get isWaitingForVideo => _isWaitingForVideo;
|
||||
|
||||
/// 监听无人机轨迹点
|
||||
ValueListenable<List<DroneTrajectoryPoint>> get trajectoryPoints =>
|
||||
_trajectoryPoints;
|
||||
|
||||
/// 获取当前无人机任务信息
|
||||
DroneTaskInfo? get currentInfo => _currentTaskInfo.value;
|
||||
|
||||
@@ -50,10 +92,84 @@ class DroneTaskStateManager {
|
||||
_currentTaskInfo.value = info;
|
||||
}
|
||||
|
||||
/// 任务下发成功后调用:开始监测无人机实时推送与视频流
|
||||
/// 在接口返回成功之后调用
|
||||
void markTaskIssued() {
|
||||
debugPrint('🚀 [DroneTaskStateManager] 任务已下发,开始监测推送数据与视频流');
|
||||
_isWaitingForOsdPush.value = true;
|
||||
_isWaitingForVideo.value = true;
|
||||
|
||||
_osdWaitTimeoutTimer?.cancel();
|
||||
_videoWaitTimeoutTimer?.cancel();
|
||||
|
||||
// 超时兜底:90 秒后仍未收到 OSD 推送,自动停止转圈
|
||||
_osdWaitTimeoutTimer = Timer(const Duration(seconds: 90), () {
|
||||
if (_isWaitingForOsdPush.value) {
|
||||
debugPrint('⚠️ [DroneTaskStateManager] 等待 OSD 推送超时,自动停止');
|
||||
_isWaitingForOsdPush.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
// 超时兜底:90 秒后仍未收到视频,自动停止 toast
|
||||
_videoWaitTimeoutTimer = Timer(const Duration(seconds: 90), () {
|
||||
if (_isWaitingForVideo.value) {
|
||||
debugPrint('⚠️ [DroneTaskStateManager] 等待视频流超时,自动停止');
|
||||
_isWaitingForVideo.value = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 收到无人机 OSD 推送数据后调用:停止转圈,恢复绿点
|
||||
void markOsdPushReceived() {
|
||||
if (_isWaitingForOsdPush.value) {
|
||||
debugPrint('✅ [DroneTaskStateManager] 收到 OSD 推送数据,停止监测');
|
||||
_isWaitingForOsdPush.value = false;
|
||||
_osdWaitTimeoutTimer?.cancel();
|
||||
_osdWaitTimeoutTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 收到无人机视频流后调用:隐藏"视频获取中" toast
|
||||
void markVideoReceived() {
|
||||
if (_isWaitingForVideo.value) {
|
||||
debugPrint('✅ [DroneTaskStateManager] 收到视频流,停止监测');
|
||||
_isWaitingForVideo.value = false;
|
||||
_videoWaitTimeoutTimer?.cancel();
|
||||
_videoWaitTimeoutTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 添加无人机轨迹点
|
||||
void addTrajectoryPoint(DroneTrajectoryPoint point) {
|
||||
final list = List<DroneTrajectoryPoint>.from(_trajectoryPoints.value);
|
||||
list.add(point);
|
||||
// 性能优化:只保留最近 1000 个点
|
||||
if (list.length > 1000) {
|
||||
list.removeAt(0);
|
||||
}
|
||||
_trajectoryPoints.value = list;
|
||||
}
|
||||
|
||||
/// 批量设置轨迹点(恢复历史轨迹时使用)
|
||||
void setTrajectoryPoints(List<DroneTrajectoryPoint> points) {
|
||||
_trajectoryPoints.value = List<DroneTrajectoryPoint>.from(points);
|
||||
}
|
||||
|
||||
/// 清空轨迹
|
||||
void clearTrajectory() {
|
||||
_trajectoryPoints.value = [];
|
||||
}
|
||||
|
||||
/// 清除无人机任务信息
|
||||
void clearDroneTaskInfo() {
|
||||
debugPrint('🛸 [DroneTaskStateManager] 清除无人机任务信息');
|
||||
_currentTaskInfo.value = null;
|
||||
_osdWaitTimeoutTimer?.cancel();
|
||||
_videoWaitTimeoutTimer?.cancel();
|
||||
_osdWaitTimeoutTimer = null;
|
||||
_videoWaitTimeoutTimer = null;
|
||||
_isWaitingForOsdPush.value = false;
|
||||
_isWaitingForVideo.value = false;
|
||||
}
|
||||
|
||||
/// 检查是否有当前任务
|
||||
|
||||
@@ -15,7 +15,13 @@ class DioClient {
|
||||
),
|
||||
);
|
||||
|
||||
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
|
||||
dio.interceptors.add(
|
||||
LogInterceptor(
|
||||
requestBody: true,
|
||||
responseBody: true,
|
||||
requestHeader: true,
|
||||
),
|
||||
);
|
||||
|
||||
dio.interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
@@ -30,23 +36,29 @@ class DioClient {
|
||||
return handler.next(options);
|
||||
},
|
||||
|
||||
// ======================
|
||||
// ✅ 关键:401 自动拦截
|
||||
// ======================
|
||||
onResponse: (response, handler) {
|
||||
if (response.data is Map<String, dynamic>) {
|
||||
final code = response.data['code'];
|
||||
if (code == 401 || code == 403) {
|
||||
print(
|
||||
'>>> [DIO] 🚨🚨🚨 收到业务错误码 $code,触发 Token 过期处理!URL: ${response.requestOptions.uri},时间: ${DateTime.now()}',
|
||||
);
|
||||
try {
|
||||
sl<AuthCubit>().tokenExpired();
|
||||
} catch (ex) {}
|
||||
}
|
||||
}
|
||||
return handler.next(response);
|
||||
},
|
||||
|
||||
onError: (DioException e, handler) async {
|
||||
// 401 = token 过期 / 未授权
|
||||
if (e.response?.statusCode == 401) {
|
||||
print('>>> [DIO] 🚨🚨🚨 收到 401 响应,触发自动退出登录!URL: ${e.requestOptions.uri},时间: ${DateTime.now()}');
|
||||
if (e.response?.statusCode == 401 || e.response?.statusCode == 403) {
|
||||
print(
|
||||
'>>> [DIO] 🚨🚨🚨 收到 HTTP ${e.response?.statusCode},触发 Token 过期处理!URL: ${e.requestOptions.uri},时间: ${DateTime.now()}',
|
||||
);
|
||||
try {
|
||||
// 调用 logout 清除本地缓存 + 跳登录
|
||||
await sl<AuthCubit>().logout();
|
||||
} catch (ex) {
|
||||
// 防止报错
|
||||
}
|
||||
sl<AuthCubit>().tokenExpired();
|
||||
} catch (ex) {}
|
||||
}
|
||||
|
||||
return handler.next(e);
|
||||
|
||||
@@ -28,6 +28,8 @@ class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
StreamSubscription<MqttMessage>? _subscription;
|
||||
String? _deviceSn;
|
||||
String? _gatewaySn;
|
||||
int _listenerCount = 0;
|
||||
bool _isDisposed = false;
|
||||
|
||||
DroneOsdDataSourceImpl(this.mqttClient);
|
||||
|
||||
@@ -42,10 +44,14 @@ class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
required String deviceSn,
|
||||
required String gatewaySn,
|
||||
}) async {
|
||||
if (_deviceSn == deviceSn &&
|
||||
if (_isDisposed) return;
|
||||
|
||||
if (_listenerCount > 0 &&
|
||||
_deviceSn == deviceSn &&
|
||||
_gatewaySn == gatewaySn &&
|
||||
_subscription != null) {
|
||||
debugPrint('[DroneOsdDataSource] already listening');
|
||||
_listenerCount++;
|
||||
debugPrint('[DroneOsdDataSource] 引用计数+1: $_listenerCount');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -73,10 +79,20 @@ class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
_subscription = mqttClient.messageStream?.listen((message) {
|
||||
_handleMessage(message);
|
||||
});
|
||||
|
||||
_listenerCount = 1;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopListening() async {
|
||||
_listenerCount--;
|
||||
if (_listenerCount > 0) {
|
||||
debugPrint('[DroneOsdDataSource] 引用计数-1: $_listenerCount (保留订阅)');
|
||||
return;
|
||||
}
|
||||
|
||||
_listenerCount = 0;
|
||||
|
||||
await _subscription?.cancel();
|
||||
_subscription = null;
|
||||
|
||||
@@ -94,26 +110,19 @@ class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
}
|
||||
|
||||
void _handleMessage(MqttMessage message) {
|
||||
if (_isDisposed) return;
|
||||
try {
|
||||
final jsonData = jsonDecode(message.payload) as Map<String, dynamic>;
|
||||
final osdData = DroneOsdEntity.fromJson(jsonData);
|
||||
|
||||
// 🔥 重要修复:先判断 gatewaySn,再判断 deviceSn
|
||||
// 因为 topic 可能同时包含两者,但我们需要优先匹配机场
|
||||
if (_gatewaySn != null &&
|
||||
_gatewaySn!.isNotEmpty &&
|
||||
message.topic.contains(_gatewaySn!)) {
|
||||
debugPrint('🏢 [DroneOsdDataSource] 机场 OSD 更新');
|
||||
debugPrint('🏢 [DroneOsdDataSource] Topic: ${message.topic}');
|
||||
_stationOsdController.add(osdData);
|
||||
} else if (_deviceSn != null &&
|
||||
_deviceSn!.isNotEmpty &&
|
||||
message.topic.contains(_deviceSn!)) {
|
||||
debugPrint('🛸 [DroneOsdDataSource] 无人机 OSD 更新');
|
||||
debugPrint('🛸 [DroneOsdDataSource] Topic: ${message.topic}');
|
||||
_droneOsdController.add(osdData);
|
||||
} else {
|
||||
debugPrint('⚠️ [DroneOsdDataSource] 未知设备类型,Topic: ${message.topic}');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [DroneOsdDataSource] 解析 OSD 数据失败: $e');
|
||||
@@ -121,8 +130,9 @@ class DroneOsdDataSourceImpl implements DroneOsdDataSource {
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_isDisposed = true;
|
||||
stopListening();
|
||||
_droneOsdController.close();
|
||||
_stationOsdController.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ abstract class TaskMessageDataSource {
|
||||
Stream<TaskArriveEntity> get taskArriveStream;
|
||||
Stream<RealTimeMessageEntity> get realTimeMessageStream;
|
||||
|
||||
Future<void> startListening({required String deviceId});
|
||||
Future<void> startListening({required String deviceId, int? taskId});
|
||||
Future<void> stopListening();
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ class TaskMessageDataSourceImpl implements TaskMessageDataSource {
|
||||
|
||||
StreamSubscription<MqttMessage>? _subscription;
|
||||
String? _deviceId;
|
||||
int? _taskId;
|
||||
|
||||
TaskMessageDataSourceImpl(this.mqttClient);
|
||||
|
||||
@@ -40,9 +41,9 @@ class TaskMessageDataSourceImpl implements TaskMessageDataSource {
|
||||
_realTimeMessageController.stream;
|
||||
|
||||
@override
|
||||
Future<void> startListening({required String deviceId}) async {
|
||||
if (_deviceId == deviceId && _subscription != null) {
|
||||
debugPrint('[TaskMessageDataSource] already listening: $deviceId');
|
||||
Future<void> startListening({required String deviceId, int? taskId}) async {
|
||||
if (_deviceId == deviceId && _taskId == taskId && _subscription != null) {
|
||||
debugPrint('[TaskMessageDataSource] already listening: deviceId=$deviceId, taskId=$taskId');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -54,18 +55,20 @@ class TaskMessageDataSourceImpl implements TaskMessageDataSource {
|
||||
}
|
||||
|
||||
_deviceId = deviceId;
|
||||
_taskId = taskId;
|
||||
|
||||
final taskStatusTopic = 'task/$deviceId/status';
|
||||
final taskArriveTopic = 'task/$deviceId/arrive';
|
||||
// 🔥 status/arrive 话题使用 taskId,realTimeMessage 使用 deviceId
|
||||
final taskStatusTopic = taskId != null ? 'task/$taskId/status' : null;
|
||||
final taskArriveTopic = taskId != null ? 'task/$taskId/arrive' : null;
|
||||
final realTimeTopic = 'device/$deviceId/realTimeMessage';
|
||||
|
||||
debugPrint('📋 [TaskMessageDataSource] 开始监听:');
|
||||
debugPrint(' 任务状态: $taskStatusTopic');
|
||||
debugPrint(' 到达通知: $taskArriveTopic');
|
||||
if (taskStatusTopic != null) debugPrint(' 任务状态: $taskStatusTopic');
|
||||
if (taskArriveTopic != null) debugPrint(' 到达通知: $taskArriveTopic');
|
||||
debugPrint(' 实时消息: $realTimeTopic');
|
||||
|
||||
await mqttClient.subscribe(taskStatusTopic);
|
||||
await mqttClient.subscribe(taskArriveTopic);
|
||||
if (taskStatusTopic != null) await mqttClient.subscribe(taskStatusTopic);
|
||||
if (taskArriveTopic != null) await mqttClient.subscribe(taskArriveTopic);
|
||||
await mqttClient.subscribe(realTimeTopic);
|
||||
|
||||
_subscription = mqttClient.messageStream?.listen((message) {
|
||||
@@ -80,12 +83,16 @@ class TaskMessageDataSourceImpl implements TaskMessageDataSource {
|
||||
|
||||
if (_deviceId != null) {
|
||||
final deviceId = _deviceId!;
|
||||
await mqttClient.unsubscribe('task/$deviceId/status');
|
||||
await mqttClient.unsubscribe('task/$deviceId/arrive');
|
||||
// 🔥 status/arrive 用 taskId 取消订阅
|
||||
if (_taskId != null) {
|
||||
await mqttClient.unsubscribe('task/$_taskId/status');
|
||||
await mqttClient.unsubscribe('task/$_taskId/arrive');
|
||||
}
|
||||
await mqttClient.unsubscribe('device/$deviceId/realTimeMessage');
|
||||
}
|
||||
|
||||
_deviceId = null;
|
||||
_taskId = null;
|
||||
}
|
||||
|
||||
void _handleMessage(MqttMessage message) {
|
||||
|
||||
@@ -24,9 +24,9 @@ class TaskMessageRepositoryImpl implements TaskMessageRepository {
|
||||
Stream<TaskStatusEntity> get taskStatusStream => dataSource.taskStatusStream;
|
||||
|
||||
@override
|
||||
Future<Either<Failure, void>> startListening({required String deviceId}) async {
|
||||
Future<Either<Failure, void>> startListening({required String deviceId, int? taskId}) async {
|
||||
try {
|
||||
await dataSource.startListening(deviceId: deviceId);
|
||||
await dataSource.startListening(deviceId: deviceId, taskId: taskId);
|
||||
return right(null);
|
||||
} catch (e) {
|
||||
return left(Failure(e.toString()));
|
||||
|
||||
@@ -71,7 +71,7 @@ class MqttConfig extends Equatable {
|
||||
factory MqttConfig.taskMessage() {
|
||||
return const MqttConfig(
|
||||
host: '1.95.137.212',
|
||||
port: 59020,
|
||||
port: 1883,
|
||||
username: 'maibu',
|
||||
password: 'jsmbzn520',
|
||||
protocol: MqttProtocol.tcp,
|
||||
|
||||
@@ -11,6 +11,6 @@ abstract class TaskMessageRepository {
|
||||
Stream<TaskArriveEntity> get taskArriveStream;
|
||||
Stream<TaskStatusEntity> get taskStatusStream;
|
||||
|
||||
Future<Either<Failure, void>> startListening({required String deviceId});
|
||||
Future<Either<Failure, void>> startListening({required String deviceId, int? taskId});
|
||||
Future<void> stopListening();
|
||||
}
|
||||
|
||||
@@ -36,9 +36,15 @@ class TcpClient {
|
||||
|
||||
final ILoggerService _logger = GetIt.I<ILoggerService>();
|
||||
|
||||
// 新增:心跳定时器
|
||||
// 心跳超时定时器(收到服务端心跳后重置,超时则判定连接断开)
|
||||
Timer? _heartbeatTimer;
|
||||
Timer? _heartbeatSendTimer; // 🔥 主动发送心跳定时器:每5秒给服务端发一次,防止服务端判定客户端失效
|
||||
Timer? _reconnectTimer; // 重连定时器
|
||||
int _reconnectAttempt = 0; // 🔥 重连尝试次数,用于退避计算
|
||||
int _reconnectFailCount = 0; // 🔥 连续重连失败次数(含心跳超时),达到阈值后停止重连
|
||||
/// 🔥 重连耗尽回调:连续4次重连失败(含心跳超时)后触发,通知上层弹窗提示用户
|
||||
VoidCallback? onReconnectExhausted;
|
||||
static const Duration _heartbeatTimeout = Duration(seconds: 15); // 心跳超时时间
|
||||
|
||||
String? _lastHost;
|
||||
int? _lastPort;
|
||||
@@ -46,6 +52,7 @@ class TcpClient {
|
||||
bool _isSwitching = false;
|
||||
bool _connecting = false; // 🔥 是否正在建立连接(防止 connect() 和 connectBySwitch() 并发竞争)
|
||||
Completer<void>? _connectionCompleter; // 🔥 用于通知连接就绪
|
||||
int _connectionId = 0; // 🔥 连接代数:每次新建连接递增,旧socket回调发现ID不匹配则忽略
|
||||
|
||||
// 🔥 关键标志:记录客户端最后一次发送 0x03 认证包的时间
|
||||
// 用于区分"自身认证触发的 have_logged_in"和"真正的异地登录"
|
||||
@@ -95,6 +102,7 @@ class TcpClient {
|
||||
|
||||
bool get isConnected => _socket != null;
|
||||
void disconnects({bool forSwitch = false}) {
|
||||
_connectionId++; // 🔥 使旧socket回调失效
|
||||
if (forSwitch) {
|
||||
_isSwitching = true;
|
||||
//debugPrint('🚫 [TCP] 标记为切换断开,将禁止自动重连');
|
||||
@@ -103,7 +111,7 @@ class TcpClient {
|
||||
|
||||
// 🔥 关键:立即取消可能已经存在或即将触发的重连定时器
|
||||
_reconnectTimer?.cancel();
|
||||
_heartbeatTimer?.cancel();
|
||||
stopHeartbeat();
|
||||
|
||||
if (_socket != null) {
|
||||
//debugPrint('🔌 [TCP] 物理断开 Socket...');
|
||||
@@ -123,6 +131,7 @@ class TcpClient {
|
||||
/// 🔥 彻底断开 TCP(用于退出登录),清除所有重连能力
|
||||
void forceDisconnect() {
|
||||
_logger.logWithLevel('🛑 [TCP] 强制断开并清除重连能力', shouldLog: true);
|
||||
_connectionId++; // 🔥 使旧socket回调失效
|
||||
|
||||
// 1. 停止心跳
|
||||
stopHeartbeat();
|
||||
@@ -141,6 +150,8 @@ class TcpClient {
|
||||
_connecting = false;
|
||||
_connectionCompleter = null;
|
||||
_lastAuthPacketSentAt = null;
|
||||
_reconnectAttempt = 0; // 🔥 重置重连退避
|
||||
_reconnectFailCount = 0; // 🔥 重置重连失败计数
|
||||
|
||||
// 5. 销毁 Socket
|
||||
if (_socket != null) {
|
||||
@@ -187,7 +198,9 @@ class TcpClient {
|
||||
|
||||
_connecting = true;
|
||||
_connectionCompleter = Completer<void>();
|
||||
debugPrint('🔌 [TCP-connect] 设置 _connecting=true');
|
||||
_connectionId++; // 🔥 新一代连接,旧socket的回调将自动失效
|
||||
final myConnId = _connectionId;
|
||||
debugPrint('🔌 [TCP-connect] 设置 _connecting=true, connectionId=$myConnId');
|
||||
|
||||
_logger.logWithLevel('🔌 [TCP] 开始连接:$host:$port', shouldLog: true);
|
||||
|
||||
@@ -207,6 +220,9 @@ class TcpClient {
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
_connecting = false; // 🔥 连接成功,重置标志
|
||||
// 🔥 关键:在重置退避计数前,记住本次是否是重连(用于后续检测服务端残留session)
|
||||
final bool wasReconnecting = _reconnectAttempt > 0;
|
||||
_reconnectAttempt = 0; // 🔥 连接成功,重置重连退避
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
_connectionCompleter!.complete();
|
||||
debugPrint('✅ [TCP-connect] 连接就绪,通知等待方');
|
||||
@@ -225,6 +241,8 @@ class TcpClient {
|
||||
|
||||
// 开始认证tcp
|
||||
await _sendAuthPacket();
|
||||
// 🔥 启动心跳超时检测:等待服务端心跳,超时则触发重连
|
||||
startHeartbeat();
|
||||
_socket!.listen(
|
||||
(data) {
|
||||
//debugPrint('📥 [TCP] 收到原始数据:${data.length} 字节, 内容:$data');
|
||||
@@ -248,12 +266,23 @@ class TcpClient {
|
||||
shouldLog: false,
|
||||
);
|
||||
for (var packet in packets) {
|
||||
// 🔥 最根部日志:收到任何推送都打印
|
||||
// debugPrint('📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}');
|
||||
// _logger.logWithLevel(
|
||||
// '📥 [TCP-ROOT] 收到推送 CMD: 0x${packet.command.toRadixString(16).toUpperCase()}, Payload长度: ${packet.payload.length}',
|
||||
// shouldLog: true,
|
||||
// );
|
||||
// 🔥 关键修复:重连期间收到 have_logged_in,拦截不分发给 AuthCubit
|
||||
// 必须在 _controller.add 之前检查,否则 AuthCubit 会判定为异地登录弹出退出弹窗
|
||||
if (packet.command == 0x12 && wasReconnecting) {
|
||||
try {
|
||||
final payloadStr = utf8.decode(packet.payload.length > 2
|
||||
? packet.payload.sublist(0, packet.payload.length - 2)
|
||||
: packet.payload);
|
||||
if (payloadStr.contains('have_logged_in')) {
|
||||
debugPrint('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留!立即断开让服务端清理session');
|
||||
_logger.logWithLevel('🔄 [TCP] 重连后收到 have_logged_in,服务端session残留,强制重连', shouldLog: true);
|
||||
_handleReconnectSessionReset(myConnId);
|
||||
return; // 停止处理后续数据,不分发给任何监听器
|
||||
}
|
||||
} catch (_) {
|
||||
// 解析失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
if (!_controller.isClosed) {
|
||||
_controller.add(packet);
|
||||
@@ -264,12 +293,9 @@ class TcpClient {
|
||||
);
|
||||
}
|
||||
if (packet.command == 0xFF) {
|
||||
//debugPrint('收到服务端心跳,自动回复...');
|
||||
_logger.logWithLevel(
|
||||
'✅ [TCP] 收到服务端心跳,自动回复...',
|
||||
shouldLog: false,
|
||||
);
|
||||
debugPrint('📥 [TCP] ✅ 收到服务端心跳 0xFF,重置超时计时器');
|
||||
sendHeartbeat(); // 回复 AB AA FF AA AB
|
||||
_resetHeartbeatTimeout(); // 重置超时计时器
|
||||
}
|
||||
if (packet.command == 0x03) {
|
||||
// debugPrint('⚠️ 收到认证响应:${packet.payload}');
|
||||
@@ -289,24 +315,28 @@ class TcpClient {
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
// TODO: 断线重连
|
||||
// debugPrint('来到断线重连!');
|
||||
// 🔥 关键修复:检查 connectionId,防止旧socket的回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
//debugPrint('onDone❌ [TCP] 连接已断开!');
|
||||
_logger.logWithLevel('❌ [TCP] 连接已断开!', shouldLog: false);
|
||||
_logger.logWithLevel('❌ [TCP] 连接已断开!', shouldLog: true);
|
||||
_handleDisconnect();
|
||||
}
|
||||
_isSwitching = false; // 重置标志,以免影响下次
|
||||
_isSwitching = false;
|
||||
},
|
||||
onError: (e) {
|
||||
//debugPrint('来到断线重连!error');
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 的回调,当前 #$_connectionId,忽略');
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
if (!_isSwitching) {
|
||||
//debugPrint('❌ [TCP] 发生错误:$e');
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
_handleDisconnect();
|
||||
} // 统一走重连逻辑,保护 Controller 不被关闭
|
||||
_isSwitching = false; // 重置标志,以免影响下次
|
||||
}
|
||||
_isSwitching = false;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
@@ -318,13 +348,46 @@ class TcpClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔥 重连后服务端session残留处理:立即销毁连接,等待服务端清理session后再重连
|
||||
/// 这是解决"退出登录重连就好"问题的核心:
|
||||
/// 退出登录 → forceDisconnect → 服务端有足够时间清理session → 重新登录 → 新session → 心跳正常
|
||||
/// 自动重连 → 5秒内重连 → 服务端session还在 → have_logged_in → 不重启心跳 → 超时循环
|
||||
void _handleReconnectSessionReset(int myConnId) {
|
||||
_connectionId++; // 使旧socket回调失效
|
||||
stopHeartbeat();
|
||||
if (_socket != null) {
|
||||
_socket!.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
// 🔥 服务端session残留也算一次重连失败
|
||||
_reconnectFailCount++;
|
||||
debugPrint('📊 [TCP] session残留,重连失败计数: $_reconnectFailCount/4');
|
||||
if (_reconnectFailCount >= 4) {
|
||||
debugPrint('🛑 [TCP] 重连失败已达 4 次,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 重连失败已达 4 次,停止重连', shouldLog: true);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
// 🔥 递增重连尝试次数,让下次重连等待更长时间
|
||||
_reconnectAttempt++;
|
||||
_scheduleReconnect();
|
||||
}
|
||||
|
||||
//
|
||||
void _handleDisconnect() {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效,防止onDone/onError污染新连接
|
||||
debugPrint('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnect, connectionId→$_connectionId', shouldLog: true);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
// 注意:这里不要关闭 _controller!否则监听者会丢失数据流
|
||||
// _controller?.close();
|
||||
// 🔥 连续失败达到4次,停止重连,通知上层弹窗
|
||||
if (_reconnectFailCount >= 4) {
|
||||
debugPrint('🛑 [TCP] 重连失败已达 4 次,停止重连,通知用户退出登录');
|
||||
_logger.logWithLevel('🛑 [TCP] 重连失败已达 4 次,停止重连', shouldLog: true);
|
||||
onReconnectExhausted?.call();
|
||||
return;
|
||||
}
|
||||
_scheduleReconnect();
|
||||
}
|
||||
|
||||
@@ -333,15 +396,16 @@ class TcpClient {
|
||||
if (isUserSwitch) return;
|
||||
if (_reconnectTimer != null) return;
|
||||
|
||||
// debugPrint('⏳ 调度重连:Host=${_lastHost}, Port=${_lastPort}'); // ✅ 检查 Host/Port 是否为空
|
||||
_logger.logWithLevel('⏳ 调度重连:Host=${_lastHost}, Port=${_lastPort}');
|
||||
// 🔥 重连退避:5s → 10s → 20s → 30s(max)
|
||||
final delay = [5, 10, 20, 30][_reconnectAttempt.clamp(0, 3)];
|
||||
_reconnectAttempt++;
|
||||
_logger.logWithLevel('⏳ 调度重连:第$_reconnectAttempt次,${delay}s后重连,Host=${_lastHost}, Port=${_lastPort}');
|
||||
if (_lastHost == null || _lastPort == null) {
|
||||
//debugPrint('❌ 无法重连:Host 或 Port 为空!');
|
||||
_logger.logWithLevel('❌ 无法重连:Host 或 Port 为空!', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
|
||||
_reconnectTimer = Timer(const Duration(seconds: 5), () {
|
||||
_reconnectTimer = Timer(Duration(seconds: delay), () async {
|
||||
_reconnectTimer = null;
|
||||
// 🔥 关键修复:定时器触发时检查是否已有连接,避免重复创建
|
||||
if (_socket != null) {
|
||||
@@ -355,7 +419,29 @@ class TcpClient {
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('⏰ 定时器触发,开始执行重连...', shouldLog: true);
|
||||
connect(host: _lastHost!, port: _lastPort!);
|
||||
try {
|
||||
await connect(host: _lastHost!, port: _lastPort!);
|
||||
_reconnectAttempt = 0; // 🔥 重连成功,重置退避计数
|
||||
// 🔥 重连成功后,补调 HTTP switchDevice 告知服务端推送目标设备
|
||||
try {
|
||||
final remoteControlCubit = GetIt.I<RemoteControlCubit>();
|
||||
final targetDevice = remoteControlCubit.state.targetDevice;
|
||||
if (targetDevice != null) {
|
||||
debugPrint('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}');
|
||||
_logger.logWithLevel('🔄 [TCP-重连] 补调 HTTP switchDevice: ${targetDevice.deviceName}', shouldLog: true);
|
||||
await switchDeviceUseCase.deviceRepository.switchDevice('app', targetDevice.deviceName);
|
||||
debugPrint('✅ [TCP-重连] HTTP switchDevice 成功');
|
||||
} else {
|
||||
debugPrint('⚠️ [TCP-重连] targetDevice 为 null,跳过 switchDevice');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] HTTP switchDevice 失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-重连] HTTP switchDevice 失败: $e', shouldLog: true);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('❌ [TCP-重连] connect 失败: $e');
|
||||
_logger.logWithLevel('❌ [TCP-重连] connect 失败: $e', shouldLog: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -446,19 +532,47 @@ class TcpClient {
|
||||
..addByte(0xAA)
|
||||
..addByte(0xAB);
|
||||
_socket!.add(builder.takeBytes());
|
||||
debugPrint('💓 [TCP] 发送心跳 AB AA FF AA AB');
|
||||
}
|
||||
|
||||
// 新增:启动心跳(每 4 秒发送一次 0xFF 指令)
|
||||
/// 启动心跳:主动定时发送 + 超时检测
|
||||
/// 1. 每5秒主动给服务端发心跳,防止服务端判定客户端失效
|
||||
/// 2. 15秒内没收到服务端心跳,判定连接断开并重连
|
||||
void startHeartbeat({Duration interval = const Duration(seconds: 4)}) {
|
||||
if (_heartbeatTimer != null) return; // 防止重复启动
|
||||
debugPrint('⏰ [TCP] 启动心跳定时器,间隔: ${interval.inSeconds}秒');
|
||||
_logger.logWithLevel('✅ [TCP] 收到服务端心跳,自动回复...', shouldLog: true);
|
||||
_heartbeatTimer = Timer.periodic(interval, (_) {
|
||||
// 发送心跳帧:AB AA FF AA AB
|
||||
debugPrint('💓 [TCP] 发送心跳包 0xFF');
|
||||
sendHeartbeat();
|
||||
debugPrint('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)');
|
||||
_logger.logWithLevel('⏰ [TCP] 启动心跳:主动发送(5s) + 超时检测(${_heartbeatTimeout.inSeconds}s)', shouldLog: true);
|
||||
|
||||
// 🔥 主动定时发送心跳给服务端(每5秒)
|
||||
_heartbeatSendTimer?.cancel();
|
||||
_heartbeatSendTimer = Timer.periodic(const Duration(seconds: 5), (_) {
|
||||
if (_socket != null) {
|
||||
sendHeartbeat();
|
||||
}
|
||||
});
|
||||
|
||||
// 超时检测
|
||||
_resetHeartbeatTimeout();
|
||||
}
|
||||
|
||||
/// 重置心跳超时定时器
|
||||
/// 每次收到服务端心跳(0xFF)时调用,重新开始计时
|
||||
void _resetHeartbeatTimeout() {
|
||||
_heartbeatTimer?.cancel();
|
||||
_heartbeatTimer = Timer(_heartbeatTimeout, () {
|
||||
debugPrint('⚠️ [TCP] 心跳超时 ${_heartbeatTimeout.inSeconds}s 未收到服务端心跳,判定连接断开');
|
||||
_logger.logWithLevel('⚠️ [TCP] 心跳超时,判定连接断开', shouldLog: true);
|
||||
// 触发断开重连
|
||||
if (_socket != null) {
|
||||
_socket!.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
// 🔥 累计重连失败次数(心跳超时 = 本次连接无效 = 一次失败)
|
||||
_reconnectFailCount++;
|
||||
debugPrint('📊 [TCP] 重连失败计数: $_reconnectFailCount/4');
|
||||
// 🔥 统一走普通断开重连路径(_scheduleReconnect 已包含 HTTP switchDevice)
|
||||
_handleDisconnect();
|
||||
});
|
||||
debugPrint("✅ TCP Connected - 心跳已启动");
|
||||
}
|
||||
|
||||
/// 🔥 封装完整的TCP初始化方法:连接 + 认证 + 心跳
|
||||
@@ -478,6 +592,8 @@ class TcpClient {
|
||||
|
||||
_connecting = true;
|
||||
_connectionCompleter = Completer<void>();
|
||||
_connectionId++; // 🔥 新一代连接,旧socket回调自动失效
|
||||
final myConnId = _connectionId;
|
||||
|
||||
try {
|
||||
// 更新状态为连接中
|
||||
@@ -516,7 +632,7 @@ class TcpClient {
|
||||
_logger.logWithLevel('✅ [TCP] 心跳已启动', shouldLog: true);
|
||||
|
||||
// 设置数据监听(复用现有的监听逻辑)
|
||||
_setupDataListener();
|
||||
_setupDataListener(myConnId);
|
||||
|
||||
_connecting = false;
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
@@ -538,7 +654,7 @@ class TcpClient {
|
||||
}
|
||||
|
||||
/// 设置数据监听器
|
||||
void _setupDataListener() {
|
||||
void _setupDataListener(int myConnId) {
|
||||
if (_socket == null) return;
|
||||
|
||||
_socket!.listen(
|
||||
@@ -557,7 +673,9 @@ class TcpClient {
|
||||
_controller.add(packet);
|
||||
}
|
||||
if (packet.command == 0xFF) {
|
||||
debugPrint('📥 [TCP] ✅ 收到服务端心跳 0xFF,重置超时计时器');
|
||||
sendHeartbeat();
|
||||
_resetHeartbeatTimeout(); // 重置超时计时器
|
||||
}
|
||||
if (packet.command == 0x03) {
|
||||
_logger.logWithLevel(
|
||||
@@ -574,13 +692,23 @@ class TcpClient {
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
if (!_isSwitching) {
|
||||
_logger.logWithLevel('❌ [TCP] 连接已断开!', shouldLog: false);
|
||||
_logger.logWithLevel('❌ [TCP] 连接已断开!', shouldLog: true);
|
||||
_handleDisconnect();
|
||||
}
|
||||
_isSwitching = false;
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ [TCP] 发生错误:$e', shouldLog: true);
|
||||
if (!_isSwitching) {
|
||||
_handleDisconnect();
|
||||
@@ -590,10 +718,12 @@ class TcpClient {
|
||||
);
|
||||
}
|
||||
|
||||
// 新增:停止心跳
|
||||
// 停止心跳(主动发送 + 超时检测全部停止)
|
||||
void stopHeartbeat() {
|
||||
_heartbeatTimer?.cancel();
|
||||
_heartbeatTimer = null;
|
||||
_heartbeatSendTimer?.cancel();
|
||||
_heartbeatSendTimer = null;
|
||||
}
|
||||
|
||||
// void disconnect() {
|
||||
@@ -608,7 +738,8 @@ class TcpClient {
|
||||
//
|
||||
// }
|
||||
void disconnect() {
|
||||
debugPrint('🛑 [TCP] 主动断开连接...');
|
||||
_connectionId++; // 🔥 使旧socket回调失效
|
||||
debugPrint('🛑 [TCP] 主动断开连接... connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🛑 [TCP] 主动断开连接...');
|
||||
|
||||
// 1. 停止心跳
|
||||
@@ -629,8 +760,8 @@ class TcpClient {
|
||||
_isSwitching = false;
|
||||
_connecting = false;
|
||||
_connectionCompleter = null;
|
||||
|
||||
// 5. 销毁 Socket
|
||||
_reconnectAttempt = 0; // 🔥 重置重连退避
|
||||
_reconnectFailCount = 0; // 🔥 重置重连失败计数
|
||||
if (_socket != null) {
|
||||
_socket!.destroy();
|
||||
_socket = null;
|
||||
@@ -736,7 +867,7 @@ class TcpClient {
|
||||
|
||||
_lastAuthPacketSentAt = DateTime.now(); // 🔥 记录发送 0x03 的时间
|
||||
_socket!.add(builder.takeBytes());
|
||||
//debugPrint('🔑 [TCP] 已发送认证包 (0x03): $authString');
|
||||
await _socket!.flush(); // 🔥 关键修复:强制 flush,确保认证包立即到达服务端
|
||||
_logger.logWithLevel('🔑 [TCP] 已发送认证包 (0x03): $authString');
|
||||
|
||||
// 🔥 关键修复:移除登录时自动获取设备列表和切换设备的逻辑
|
||||
@@ -850,7 +981,9 @@ class TcpClient {
|
||||
|
||||
isUserSwitch = true;
|
||||
_connecting = true; // 🔥 防止 connect() 并发创建新连接
|
||||
debugPrint('🔌 [TCP-connectBySwitch] 无现有连接,开始新建');
|
||||
_connectionId++; // 🔥 新一代连接,旧socket回调自动失效
|
||||
final myConnId = _connectionId;
|
||||
debugPrint('🔌 [TCP-connectBySwitch] 无现有连接,开始新建, connectionId=$myConnId');
|
||||
|
||||
// debugPrint('🔌被动 [TCP] 开始连接:$host:$port'); // ✅ 必须看到这条
|
||||
_logger.logWithLevel('🔌被动 [TCP] 开始连接:$host:$port');
|
||||
@@ -908,10 +1041,9 @@ class TcpClient {
|
||||
);
|
||||
}
|
||||
if (packet.command == 0xFF) {
|
||||
//debugPrint('收到服务端心跳,自动回复...');
|
||||
_logger.logWithLevel('✅ [TCP] 收到服务端心跳,自动回复...');
|
||||
//
|
||||
debugPrint('📥 [TCP] ✅ 收到服务端心跳 0xFF,重置超时计时器');
|
||||
sendHeartbeat(); // 回复 AB AA FF AA AB
|
||||
_resetHeartbeatTimeout(); // 重置超时计时器
|
||||
}
|
||||
if (packet.command == 0x03) {
|
||||
//debugPrint('⚠️ 收到认证响应:${packet.payload}');
|
||||
@@ -925,18 +1057,28 @@ class TcpClient {
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
// 🔥 检查 connectionId,防止旧socket回调污染新连接
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
_logger.logWithLevel('⏭️ [TCP-onDone] 旧连接 #$myConnId 回调,忽略', shouldLog: true);
|
||||
return;
|
||||
}
|
||||
debugPrint('onDone [TCP] 被动连接已断开!_isSwitching=$_isSwitching');
|
||||
if (!_isSwitching) {
|
||||
_handleDisconnectBySwitch(deviceName);
|
||||
_handleDisconnect();
|
||||
} else {
|
||||
debugPrint('🚫 [TCP] 切换过程中的断开,忽略重连调度');
|
||||
_isSwitching = false;
|
||||
}
|
||||
},
|
||||
onError: (e) {
|
||||
if (myConnId != _connectionId) {
|
||||
debugPrint('⏭️ [TCP-onError] 旧连接 #$myConnId 回调,当前 #$_connectionId,忽略');
|
||||
return;
|
||||
}
|
||||
_logger.logWithLevel('❌ 被动[TCP] 发生错误:$e');
|
||||
if (!_isSwitching) {
|
||||
_handleDisconnectBySwitch(deviceName);
|
||||
_handleDisconnect();
|
||||
} else {
|
||||
debugPrint('🚫 [TCP] 切换过程中的错误,忽略重连调度');
|
||||
_isSwitching = false;
|
||||
@@ -951,8 +1093,9 @@ class TcpClient {
|
||||
rethrow; // 向上抛出连接异常
|
||||
}
|
||||
|
||||
// 🔥 关键修复:只有在所有操作成功后才重置 _connecting
|
||||
// 🔥 重置 _connecting 和 isUserSwitch
|
||||
_connecting = false;
|
||||
isUserSwitch = false; // 🔥 关键:切换完成后重置,后续超时走普通重连路径
|
||||
if (_connectionCompleter != null && !_connectionCompleter!.isCompleted) {
|
||||
_connectionCompleter!.complete();
|
||||
debugPrint('✅ [TCP-connectBySwitch] 连接就绪,通知等待方');
|
||||
@@ -1029,6 +1172,9 @@ class TcpClient {
|
||||
}
|
||||
|
||||
void _handleDisconnectBySwitch(String deviceName) {
|
||||
_connectionId++; // 🔥 使旧socket的所有回调立即失效
|
||||
debugPrint('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId');
|
||||
_logger.logWithLevel('🔌 [TCP] _handleDisconnectBySwitch, connectionId→$_connectionId', shouldLog: true);
|
||||
stopHeartbeat();
|
||||
|
||||
_socket = null;
|
||||
|
||||
@@ -9,6 +9,7 @@ import 'package:maibu_satabot_v2/features/home/presentation/routes/home_routes.d
|
||||
import 'package:maibu_satabot_v2/features/main_container/presentation/pages/tab_settings_page.dart';
|
||||
import 'package:maibu_satabot_v2/features/my/presentation/routes/my_routes.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/waring_center/presentation/routes/alarm_center_routes.dart';
|
||||
import 'package:maibu_satabot_v2/features/v2/workorder/presentation/routes/workorder_routes.dart';
|
||||
|
||||
import '../../features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_state.dart';
|
||||
@@ -20,11 +21,13 @@ import 'go_router_refresh_stream.dart';
|
||||
GoRouter createRouter(AuthCubit authCubit) {
|
||||
// 调试:打印所有路由
|
||||
debugPrint('🔍 [Router] 开始创建路由配置...');
|
||||
debugPrint('🔍 [Router] AlarmCenterRoutes.routes 数量: ${AlarmCenterRoutes.routes.length}');
|
||||
debugPrint(
|
||||
'🔍 [Router] AlarmCenterRoutes.routes 数量: ${AlarmCenterRoutes.routes.length}',
|
||||
);
|
||||
for (var route in AlarmCenterRoutes.routes) {
|
||||
debugPrint('🔍 [Router] 路由: ${route.toString()}');
|
||||
}
|
||||
|
||||
|
||||
return GoRouter(
|
||||
navigatorKey: navigatorKey, // 🔥 绑定全局 navigatorKey,使异地登录弹窗能获取 context
|
||||
initialLocation: RoutePaths.login,
|
||||
@@ -74,6 +77,7 @@ GoRouter createRouter(AuthCubit authCubit) {
|
||||
...AiRoutes.routes,
|
||||
...MyRoutes.routes,
|
||||
...AlarmCenterRoutes.routes,
|
||||
...WorkOrderRoutes.routes,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,4 +20,8 @@ class RoutePaths {
|
||||
static const settings = '/my/settings';
|
||||
|
||||
static const machineDetails = '/machine_details/machine_details';
|
||||
|
||||
/// 工单相关页面
|
||||
static const workOrder = '/workorder';
|
||||
static const workOrderDetail = '/workorder/detail/:orderId';
|
||||
}
|
||||
|
||||
69
lib/core/services/device_permission_service.dart
Normal file
69
lib/core/services/device_permission_service.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../consts/http_api_consts.dart';
|
||||
|
||||
/// 设备操作权限校验服务
|
||||
/// 接口: GET /iot/device/hasPermission?deviceId=xxx
|
||||
/// 通过条件: code==200 且 data==true,缺一不可
|
||||
/// 安全原则: 仅明确收到 code=200 && data=true 才放行,其余所有情况一律阻止
|
||||
class DevicePermissionService {
|
||||
final Dio _dio;
|
||||
|
||||
DevicePermissionService(this._dio);
|
||||
|
||||
/// 校验当前用户是否有权操作指定设备
|
||||
/// 返回 true 表示有权限,false 表示无权限或校验失败
|
||||
Future<bool> checkPermission(String deviceId) async {
|
||||
debugPrint('🔐 [权限校验] 开始校验 - deviceId: $deviceId');
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
HttpApiConsts.hasPermission,
|
||||
queryParameters: {'deviceId': deviceId},
|
||||
);
|
||||
|
||||
debugPrint('🔐 [权限校验] HTTP响应 - statusCode: ${response.statusCode}');
|
||||
|
||||
// HTTP 层面必须 200
|
||||
if (response.statusCode != 200) {
|
||||
debugPrint('🔐 [权限校验] ❌ HTTP状态码非200: ${response.statusCode}');
|
||||
return false;
|
||||
}
|
||||
|
||||
final body = response.data;
|
||||
debugPrint('🔐 [权限校验] 响应体: $body');
|
||||
|
||||
// body 必须是 Map
|
||||
if (body is! Map<String, dynamic>) {
|
||||
debugPrint('🔐 [权限校验] ❌ 响应体格式异常,非Map类型');
|
||||
return false;
|
||||
}
|
||||
|
||||
final code = body['code'];
|
||||
final data = body['data'];
|
||||
|
||||
debugPrint('🔐 [权限校验] code=$code (type: ${code.runtimeType}), data=$data (type: ${data.runtimeType})');
|
||||
|
||||
// code 必须是 200(兼容 int 和 String)
|
||||
final codeMatch = code == 200 || code.toString() == '200';
|
||||
// data 必须是 true
|
||||
final dataMatch = data == true || data.toString() == 'true';
|
||||
|
||||
if (codeMatch && dataMatch) {
|
||||
debugPrint('🔐 [权限校验] ✅ 校验通过 - code=200, data=true');
|
||||
return true;
|
||||
}
|
||||
|
||||
debugPrint('🔐 [权限校验] ❌ 校验未通过 - codeMatch=$codeMatch, dataMatch=$dataMatch');
|
||||
return false;
|
||||
} on DioException catch (e) {
|
||||
// 网络异常(断网、超时、服务器不可达等)
|
||||
debugPrint('🔐 [权限校验] ❌ DioException: ${e.type} - ${e.message}');
|
||||
return false;
|
||||
} catch (e) {
|
||||
// 任何未知异常
|
||||
debugPrint('🔐 [权限校验] ❌ 未知异常: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user