diff --git a/lib/features/device/services/device_message.dart b/lib/features/device/services/device_message.dart index a1115c4..fa82e58 100644 --- a/lib/features/device/services/device_message.dart +++ b/lib/features/device/services/device_message.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'package:uuid/uuid.dart'; + /// 下位机消息类型 /// /// 对应《下位机交互数据模型.md》中定义的四种 type 字段。 @@ -147,18 +149,11 @@ class DeviceMessage { /// 消息 ID 生成器 /// -/// 使用时间戳 + 随机数生成全局唯一 ID(避免引入 uuid 依赖)。 -/// 格式:`-`,例如 `1717500000000-1a2b3c` +/// 基于 [Uuid.v4] 生成全局唯一 ID(128 位随机,标准 36 字符 hex-with-dashes 形式)。 +/// 例如 `550e8400-e29b-41d4-a716-446655440000`。 class MessageIdGenerator { - int _counter = 0; + static const Uuid _uuid = Uuid(); /// 生成下一个唯一 ID - String next() { - _counter = (_counter + 1) & 0xFFFFFF; - final ts = DateTime.now().millisecondsSinceEpoch.toRadixString(36); - final rand = (_counter.toRadixString(36) + - (DateTime.now().microsecondsSinceEpoch & 0xFFFF).toRadixString(36)) - .padLeft(4, '0'); - return '$ts-$rand'; - } + String next() => _uuid.v4(); } diff --git a/lib/features/device/services/json_protocol.dart b/lib/features/device/services/json_protocol.dart index a2f2bd9..3bffa7d 100644 --- a/lib/features/device/services/json_protocol.dart +++ b/lib/features/device/services/json_protocol.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'device_log.dart'; import 'device_message.dart'; /// JSON 协议层帧编解码器 @@ -67,7 +68,7 @@ class JsonProtocolService { (_buffer[2] << 8) | _buffer[3]; if (len <= 0 || len > _maxFrameBytes) { - // 长度异常,丢弃首字节重新对齐 + DeviceLog.warn('tryDecode: 异常长度=$len 丢弃首字节 0x${_buffer[0].toRadixString(16).padLeft(2, '0')}'); _buffer.removeAt(0); return (null, 0); } diff --git a/pubspec.lock b/pubspec.lock index 5e89e28..b3ac7eb 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -763,7 +763,7 @@ packages: source: hosted version: "0.5.2" uuid: - dependency: transitive + dependency: "direct main" description: name: uuid sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" diff --git a/pubspec.yaml b/pubspec.yaml index 1bfb76f..24575a8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -43,6 +43,9 @@ dependencies: # USB 串口通信(Android USB Host 模式下的 CH340/FTDI/CP210x/PL2303 等芯片) usb_serial: ^0.5.0 + # 串口消息 ID 生成(UUID v4) + uuid: ^4.5.1 + dev_dependencies: flutter_test: sdk: flutter