refactor(device): 替换消息ID生成器为UUID实现

- 移除自定义时间戳+随机数ID生成逻辑
- 集成uuid包依赖并配置版本
- 使用Uuid.v4()替换原有next()方法实现
- 更新MessageIdGenerator类文档注释
- 在JSON协议层添加设备日志警告输出
- 修改pubspec.yaml添加uuid依赖声明
This commit is contained in:
Developer
2026-06-04 16:45:06 +08:00
parent 55bdaa9211
commit 3ab2232845
4 changed files with 12 additions and 13 deletions

View File

@@ -1,5 +1,7 @@
import 'dart:convert';
import 'package:uuid/uuid.dart';
/// 下位机消息类型
///
/// 对应《下位机交互数据模型.md》中定义的四种 type 字段。
@@ -147,18 +149,11 @@ class DeviceMessage {
/// 消息 ID 生成器
///
/// 使用时间戳 + 随机数生成全局唯一 ID避免引入 uuid 依赖)。
/// 格式:`<millis>-<rand>`,例如 `1717500000000-1a2b3c`
/// 基于 [Uuid.v4] 生成全局唯一 ID128 位随机,标准 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();
}

View File

@@ -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);
}

View File

@@ -763,7 +763,7 @@ packages:
source: hosted
version: "0.5.2"
uuid:
dependency: transitive
dependency: "direct main"
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"

View File

@@ -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