一次大的提交
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user