From ee733021ad8210d0e45bd8ced33002e275d9a5bd Mon Sep 17 00:00:00 2001 From: tankaitao <1767759995@qq.com> Date: Wed, 11 Nov 2026 14:53:40 +0800 Subject: [PATCH] feat(biohead): add USB servo controls and local expression library Add per-servo USB-head tuning and separate local expression CRUD with atomic JSON storage. Execute local poses through the existing SetHeadExpression RPC while preserving server presets and legacy task actions. Use scoped asynchronous requests, independent cancellation and held gRPC channels. Preserve local drafts on state-read failures and clear stale errors after recovery. Validate storage, transport, UI and application-shell compatibility with loopback tests. --- CMakeLists.txt | 2 + CmvrControlStation.pro | 5 + docs/biohead_usb.md | 66 ++ protos/cmvr/api/biohead_service.proto | 9 +- protos/cmvr/api/head_joint_command.proto | 198 ++++ src/bioheadexpressionstore.cpp | 327 ++++++ src/bioheadexpressionstore.h | 25 + src/bioheadjointclient.cpp | 911 +++++++++++++++++ src/bioheadjointclient.h | 42 + src/bioheadwidget.cpp | 1194 +++++++++++++++++++--- src/bioheadwidget.h | 98 +- tests/application_shell_test.cpp | 56 +- tests/bioheadexpressionstore_test.cpp | 194 ++++ tests/bioheadjointclient_test.cpp | 675 ++++++++++++ tests/bioheadlocalexpressions_test.cpp | 330 ++++++ tests/bioheadwidget_test.cpp | 318 ++++++ 16 files changed, 4279 insertions(+), 171 deletions(-) create mode 100644 docs/biohead_usb.md create mode 100644 protos/cmvr/api/head_joint_command.proto create mode 100644 src/bioheadexpressionstore.cpp create mode 100644 src/bioheadexpressionstore.h create mode 100644 src/bioheadjointclient.cpp create mode 100644 src/bioheadjointclient.h create mode 100644 tests/bioheadexpressionstore_test.cpp create mode 100644 tests/bioheadjointclient_test.cpp create mode 100644 tests/bioheadlocalexpressions_test.cpp create mode 100644 tests/bioheadwidget_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ac9a0bb..8e52d73 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -225,6 +225,8 @@ list(APPEND CMVR_SOURCES src/touchvideowidget.cpp src/touchvideowidget.h src/touchplanestore.cpp src/touchplanestore.h src/cameracapabilities.h src/bioheadoperations.h src/bioheadwidget.cpp src/bioheadwidget.h + src/bioheadjointclient.cpp src/bioheadjointclient.h + src/bioheadexpressionstore.cpp src/bioheadexpressionstore.h src/touchoperationwidget.cpp src/touchoperationwidget.h src/handeyemotionwidget.cpp src/handeyemotionwidget.h src/tcpcalibration.cpp src/tcpcalibration.h diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 6a13967..04901c9 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -39,6 +39,7 @@ PROTO_FILES = \ $$PROTO_ROOT/cmvr/api/arm_command.proto \ $$PROTO_ROOT/cmvr/api/arm_service.proto \ $$PROTO_ROOT/cmvr/api/biohead_command.proto \ + $$PROTO_ROOT/cmvr/api/head_joint_command.proto \ $$PROTO_ROOT/cmvr/api/biohead_service.proto \ $$PROTO_ROOT/cmvr/api/camera_command.proto \ $$PROTO_ROOT/cmvr/api/camera_service.proto \ @@ -239,6 +240,8 @@ CONFIG(debug, debug|release) { !exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.") SOURCES += \ + src/bioheadexpressionstore.cpp \ + src/bioheadjointclient.cpp \ src/seeragvmapclient.cpp \ src/agvmapdocument.cpp \ src/agvmaprasterizer.cpp \ @@ -276,6 +279,8 @@ SOURCES += \ ui/handeyecalibrationwidget.cpp HEADERS += \ + src/bioheadexpressionstore.h \ + src/bioheadjointclient.h \ src/agvvelocityramp.h \ src/seeragvmapclient.h \ src/agvmapdocument.h \ diff --git a/docs/biohead_usb.md b/docs/biohead_usb.md new file mode 100644 index 0000000..437c18a --- /dev/null +++ b/docs/biohead_usb.md @@ -0,0 +1,66 @@ +# USB 仿生头调试 + +在上位机连接 `192.168.0.234:50053`,打开 **仿生头 → 常用操作**,选择 `usb_head`。 +该页面使用服务端已有的关节 gRPC 接口,不需要部署后端。 + +## 单路舵机 + +1. 点击 **刷新配置与目标**,读取当前设备的通道、弧度范围和已确认目标。 +2. 点击 **启用拖动调试**,显式设置直接位置模式;此操作不发送位置目标。 +3. 拖动对应滑块或输入弧度值。每条位置请求只包含该路舵机,不修改其他通道。 + +当前服务配置了 `eye_l_up`、`eye_l_lower`、`eye_l_v`、`eye_l_h`、`pwm8_local` 五路。 +实际显示和限制以服务端配置为准。拖动请求以 100 ms 节流,每路仅保留最新待发送值;松开后保留最终目标。 + +## 预设表情 + +页面从服务读取预设,目前包含中立、微笑、疲倦、惊讶、生气、当前姿态。 +选择表情只查看预设,点击 **执行所选表情** 才按其 ID 调用 gRPC;过渡时间支持 0.2~5 秒。 +“当前姿态”是服务端固定预设的名称,不是实时姿态采集。 + +服务要求已确认的完整起点。页面提示起点未就绪时,可显式点击 **归位并准备预设**, +它会把所有配置通道移动到各自的初始目标,成功读回后才可执行预设。页面不会自动归位。 + +**取消表情** 会取消当前 RPC 并请求停止后续主机表情帧。设备没有硬件急停接口, +这个按钮不能保证舵机立即停止,也不能撤回已经发给设备的命令。 + +## 本地自定义表情 + +右侧切换到 **本地表情**。本地库保存在上位机 `data/biohead_expressions.json`, +按服务地址(区分演示和真实连接)及设备 ID 隔离,不会上传或覆盖设备预设。 + +1. 点击 **编辑输入(不发送)**,用左侧滑块和弧度输入编辑目标;此模式不向设备发送动作。 +2. 输入名称和 0.2~5 秒过渡时长,点击 **保存当前目标为新表情**。保存的是完整输入目标, + 不是实测姿态。名称重复会报错,不会悄悄覆盖已有记录。 +3. 选择本地表情只预览。点击 **载入目标** 才会填入左侧输入,仍然不会移动设备;修改后可 + 点击 **更新所选**。**删除所选** 只删除本机记录,并需要确认。 +4. 点击 **执行本地表情** 才将完整目标通过现有 `SetHeadExpression` gRPC 接口执行。 + 起点未就绪时需要显式归位准备;页面不会自动归位或重发失败动作。 + +若要从本地编辑恢复实际逐舵机调试,需重新点击 **启用拖动调试**,这一步只切换模式, +不会自动发送编辑后的输入。配置缺失、通道不一致或目标超出当前设备范围时,禁用保存或执行。 +断线不会删除本地记录,重新连接同一服务及设备后可继续使用。文件损坏或写入失败会明确报错, +不会显示保存成功。 + +## 状态和边界 + +- 服务提供的是已确认目标缓存,没有实际位置测量;确认成功不代表机械已经到位。 +- 打开页面、刷新状态、选择表情均不会发送位置命令。 +- 切换设备、切换“常用操作/全部接口”、离开仿生头页面或断线时,清除待发目标并取消当前请求;再次调试需要重新启用。 +- 切换“设备预设/本地表情”会清除待发目标并停用拖动调试;已经开始的表情需点击“取消表情”来取消。 +- 操作失败或超时后不自动重发,不自动重连或归位。先刷新状态,再明确选择下一步操作。 +- 只读状态查询使用独立的 6 秒预算。读取失败时暂停真实控制,保留同一设备的本地输入草稿和上次配置;可继续本地编辑或保存,手动刷新成功后再恢复控制。状态读取失败不会被描述为动作执行失败。 +- 页面移除了说话类快捷动作。原有任务编排和“全部接口”中的旧接口仍保留兼容。 + +## 编译 + +在 CMD 中执行(已安装本机项目依赖的情况下): + +```bat +cd /d C:\Users\LattePanda\Documents\CmvrControlStation-main +set "PATH=E:\qt\qt5.12.4\5.12.4\mingw73_64\bin;E:\qt\qt5.12.4\Tools\mingw730_64\bin;%PATH%" +qmake CmvrControlStation.pro +mingw32-make -f Makefile.Release -j4 +``` + +关闭旧程序后重新编译,运行 `bin\release\CmvrControlStation.exe`。 diff --git a/protos/cmvr/api/biohead_service.proto b/protos/cmvr/api/biohead_service.proto index f2dda32..59b8c39 100644 --- a/protos/cmvr/api/biohead_service.proto +++ b/protos/cmvr/api/biohead_service.proto @@ -2,9 +2,16 @@ syntax = "proto3"; package cmvr.api; import "cmvr/api/biohead_command.proto"; +import "cmvr/api/head_joint_command.proto"; // 生物头部机器人服务接口 service BioHeadService { + // USB-head joint state, direct joint control and configured expressions. + rpc ControlHeadJoints(HeadJointCommand.Request) returns (HeadJointCommand.Feedback){}; + rpc GetHeadJointState(GetHeadJointStateCommand.Request) returns (GetHeadJointStateCommand.Feedback){}; + rpc SetHeadExpression(SetHeadExpressionCommand.Request) returns (SetHeadExpressionCommand.Feedback){}; + rpc PlayHeadExpression(PlayHeadExpressionCommand.Request) returns (PlayHeadExpressionCommand.Feedback){}; + // 设置面部表情 rpc SetExpression(SetFacialExpression.Request) returns (SetFacialExpression.Feedback){}; @@ -44,4 +51,4 @@ service BioHeadService { -} \ No newline at end of file +} diff --git a/protos/cmvr/api/head_joint_command.proto b/protos/cmvr/api/head_joint_command.proto new file mode 100644 index 0000000..6e8d392 --- /dev/null +++ b/protos/cmvr/api/head_joint_command.proto @@ -0,0 +1,198 @@ +syntax = "proto3"; + +package cmvr.api; + +import "cmvr/api/common.proto"; + +// 头部关节运动模式。 +enum HeadJointMotionMode { + HEAD_JOINT_MOTION_IMMEDIATE = 0; + HEAD_JOINT_MOTION_S_CURVE = 1; + HEAD_JOINT_MOTION_FOLLOW = 2; +} + +// 最近一次设备命令的处理结果。 +enum HeadJointCommandOutcome { + HEAD_JOINT_COMMAND_NONE = 0; + HEAD_JOINT_COMMAND_ACKNOWLEDGED = 1; + HEAD_JOINT_COMMAND_REJECTED = 2; + HEAD_JOINT_COMMAND_UNKNOWN = 3; +} + +// 一个关节的目标位置。 +message HeadJointTarget { + string id = 1; + + // 单位:rad。 + // 区分“没有填写目标”和“明确要求移动到 0 rad”。 + oneof target { + double position_rad = 2; + } +} + +// 从设备配置中取得的关节信息。 +message HeadJointInfo { + string id = 1; + double min_position_rad = 2; + double max_position_rad = 3; + double home_position_rad = 4; +} + +// 最近一次获得固件 ACK 的目标缓存。 +// 这里保存的是命令目标,不是机械位置测量值。 +message HeadJointTargetState { + string id = 1; + double target_position_rad = 2; + bool target_valid = 3; +} + +// 头部关节控制命令。 +message HeadJointCommand { + // 单路或多路目标控制。 + message Move { + // 本次未列出的通道不参与目标下发。 + // 驱动会拒绝重复的通道 ID。 + repeated HeadJointTarget targets = 1; + } + + // 显式移动到配置中的 home 位置。 + message Home {} + + // Reopen and probe service 1 without sending any position target. + message Reconnect {} + + // Cancel later host-side expression frames; this is not a hardware stop. + message CancelExpression {} + + // 设置设备运动模式。 + message Mode { + // 区分未填写和明确选择 IMMEDIATE。 + oneof value { + HeadJointMotionMode mode = 1; + } + } + + // 设置指定关节的运动约束。 + message Constraints { + string id = 1; + double max_velocity_rad_s = 2; + double max_acceleration_rad_s2 = 3; + double max_jerk_rad_s3 = 4; + } + + // 设置指定关节的位置增益。 + message PositionGain { + string id = 1; + + // 0 是合法增益,需要与未填写区分。 + oneof value { + double gain = 2; + } + } + + // 设置设备更新周期,单位:ms。 + message UpdatePeriod { + uint32 period_ms = 1; + } + + message Request { + CommandHeader.Request header = 1; + + // 一条请求明确执行一项操作。 + oneof operation { + Move move = 2; + Home home = 3; + Mode mode = 4; + Constraints constraints = 5; + PositionGain position_gain = 6; + UpdatePeriod update_period = 7; + Reconnect reconnect = 8; + CancelExpression cancel_expression = 9; + } + } + + message Feedback { + // Move/configuration: success means firmware ACK, not mechanical arrival. + // Reconnect: success means open + service-1 probe, without automatic motion. + // CancelExpression: success means cancellation was requested for later host + // frames, not that firmware trajectory/PWM or the mechanism was stopped. + // A timed-out write may already have taken effect; do not blindly retry. + CommandHeader.Feedback header = 1; + } +} + +// 查询头部驱动的配置和缓存状态。 +message GetHeadJointStateCommand { + message Request { + CommandHeader.Request header = 1; + } + + message Feedback { + // success=true 表示成功取得驱动状态。 + // 设备连接和命令结果仍需检查下面的对应字段。 + CommandHeader.Feedback header = 1; + + // 表示串口传输连接状态,不是持续的硬件健康检测。 + bool connected = 2; + + // 配置中的关节信息,不是从控制板读取的标定。 + repeated HeadJointInfo joint_info = 3; + + // 最近一次获得 ACK 的目标及其有效性。 + repeated HeadJointTargetState targets = 4; + + HeadJointCommandOutcome last_command_outcome = 5; + string last_error = 6; + + // 当前 eRPC 服务 1 不提供真实关节位置测量反馈。 + bool position_feedback_available = 7; + + // Presets come from configuration, not measured hardware poses. + repeated HeadExpressionInfo expressions = 8; + bool expression_baseline_ready = 9; + bool hardware_emergency_stop_available = 10; + } +} +// One configured expression, with a stable ID and an exact display name. +message HeadExpressionInfo { + string expression_id = 1; + string expression_name = 2; + repeated HeadJointTarget targets = 3; +} + +// Synchronously send a complete five-joint expression through a bounded host +// transition. Omitted joints and partial expressions are rejected. +message SetHeadExpressionCommand { + message Request { + CommandHeader.Request header = 1; + repeated HeadJointTarget targets = 2; + // Finite duration in [0.2, 5.0] seconds; 0 or omission is rejected. + double transition_duration_s = 3; + } + message Feedback { + // Every transmitted frame, including the final target, was acknowledged. + // This is not proof of mechanical arrival; late intermediate frames may be skipped. + CommandHeader.Feedback header = 1; + } +} + +// Select one configured expression by exact stable ID or exact name. +// Unknown selectors and ambiguous names are rejected without fallback. +message PlayHeadExpressionCommand { + message Request { + CommandHeader.Request header = 1; + oneof expression { + string expression_id = 2; + string expression_name = 3; + } + // Finite duration in [0.2, 5.0] seconds; 0 or omission is rejected. + double transition_duration_s = 4; + } + message Feedback { + // Every transmitted frame, including the final target, was acknowledged. + // This is not proof of mechanical arrival; late intermediate frames may be skipped. + CommandHeader.Feedback header = 1; + string expression_id = 2; + string expression_name = 3; + } +} diff --git a/src/bioheadexpressionstore.cpp b/src/bioheadexpressionstore.cpp new file mode 100644 index 0000000..54f7ea3 --- /dev/null +++ b/src/bioheadexpressionstore.cpp @@ -0,0 +1,327 @@ +#include "bioheadexpressionstore.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace BioHeadExpressionStore { +namespace { +constexpr qint64 MaximumBytes = 8 * 1024 * 1024; +constexpr int MaximumScopes = 256; +constexpr int MaximumPerScope = 256; +constexpr int MaximumTotal = 4096; + +struct Scope { + QString endpointKey; + QString deviceId; + QList expressions; +}; +using Database = QList; + +bool fail(QString *error, const QString &detail) +{ + if (error) *error = detail; + return false; +} + +bool text(const QString &value, int maximum) +{ + if (value.isEmpty() || value.size() > maximum || value != value.trimmed()) return false; + for (const QChar character : value) + if (character.category() == QChar::Other_Control) return false; + return true; +} + +bool scopeValid(const QString &endpointKey, const QString &deviceId, QString *error) +{ + if (!text(endpointKey, 512) || !text(deviceId, 128)) + return fail(error, QStringLiteral("表情库连接标识或设备 ID 无效")); + return true; +} + +bool localId(const QString &id) +{ + const QUuid uuid(id); + return !uuid.isNull() && uuid.toString(QUuid::WithoutBraces) == id; +} + +bool exactKeys(const QJsonObject &object, const QStringList &keys) +{ + if (object.size() != keys.size()) return false; + for (const QString &key : keys) if (!object.contains(key)) return false; + return true; +} + +bool numberVariant(const QVariant &value, double *out) +{ + switch (value.type()) { + case QVariant::Double: case QVariant::Int: case QVariant::UInt: + case QVariant::LongLong: case QVariant::ULongLong: break; + default: return false; + } + *out = value.toDouble(); + return std::isfinite(*out); +} + +bool expressionValid(const Expression &expression, QString *error) +{ + if (!localId(expression.id)) + return fail(error, QStringLiteral("本地表情 ID 必须是独立的 UUID,不能使用服务端预设 ID")); + if (!text(expression.name, 80)) + return fail(error, QStringLiteral("表情名称需为 1~80 个字符,且不能带首尾空白或控制字符")); + if (!std::isfinite(expression.transitionDurationS) + || expression.transitionDurationS < .2 || expression.transitionDurationS > 5.) + return fail(error, QStringLiteral("表情过渡时间必须为 0.2~5.0 秒")); + if (expression.targets.isEmpty() || expression.targets.size() > 64) + return fail(error, QStringLiteral("表情必须包含 1~64 路关节目标")); + QSet ids; + for (const QVariant &entry : expression.targets) { + if (entry.type() != QVariant::Map) + return fail(error, QStringLiteral("表情关节目标格式无效")); + const QVariantMap target = entry.toMap(); + double position = 0; + if (target.size() != 2 || !target.contains(QStringLiteral("id")) + || !target.contains(QStringLiteral("positionRad")) + || target.value(QStringLiteral("id")).type() != QVariant::String + || !text(target.value(QStringLiteral("id")).toString(), 128) + || !numberVariant(target.value(QStringLiteral("positionRad")), &position)) + return fail(error, QStringLiteral("关节 ID 或弧度目标无效,目标必须是有限数值")); + const QString id = target.value(QStringLiteral("id")).toString(); + if (ids.contains(id)) return fail(error, QStringLiteral("表情包含重复的关节 ID")); + ids.insert(id); + } + return true; +} + +QJsonObject expressionJson(const Expression &expression) +{ + QJsonArray targets; + for (const QVariant &entry : expression.targets) { + const QVariantMap target = entry.toMap(); + targets.append(QJsonObject{{QStringLiteral("id"), target.value(QStringLiteral("id")).toString()}, + {QStringLiteral("positionRad"), target.value(QStringLiteral("positionRad")).toDouble()}}); + } + return {{QStringLiteral("id"), expression.id}, {QStringLiteral("name"), expression.name}, + {QStringLiteral("targets"), targets}, {QStringLiteral("transitionDurationS"), expression.transitionDurationS}}; +} + +bool parseExpression(const QJsonValue &value, Expression *expression, QString *error) +{ + if (!value.isObject()) return fail(error, QStringLiteral("表情记录格式损坏,原文件未修改")); + const QJsonObject object = value.toObject(); + if (!exactKeys(object, {QStringLiteral("id"), QStringLiteral("name"), QStringLiteral("targets"), + QStringLiteral("transitionDurationS")}) + || !object.value(QStringLiteral("id")).isString() || !object.value(QStringLiteral("name")).isString() + || !object.value(QStringLiteral("targets")).isArray() + || !object.value(QStringLiteral("transitionDurationS")).isDouble()) + return fail(error, QStringLiteral("表情记录字段无效,原文件未修改")); + expression->id = object.value(QStringLiteral("id")).toString(); + expression->name = object.value(QStringLiteral("name")).toString(); + expression->transitionDurationS = object.value(QStringLiteral("transitionDurationS")).toDouble(); + expression->targets.clear(); + for (const QJsonValue &entry : object.value(QStringLiteral("targets")).toArray()) { + if (!entry.isObject()) return fail(error, QStringLiteral("表情关节目标格式损坏")); + const QJsonObject target = entry.toObject(); + if (!exactKeys(target, {QStringLiteral("id"), QStringLiteral("positionRad")}) + || !target.value(QStringLiteral("id")).isString() + || !target.value(QStringLiteral("positionRad")).isDouble()) + return fail(error, QStringLiteral("表情关节目标字段无效")); + expression->targets.append(QVariantMap{{QStringLiteral("id"), target.value(QStringLiteral("id")).toString()}, + {QStringLiteral("positionRad"), target.value(QStringLiteral("positionRad")).toDouble()}}); + } + return expressionValid(*expression, error); +} + +bool read(const QString &path, Database *database, QString *error) +{ + database->clear(); + const QFileInfo info(path); + if (!info.exists()) return true; + if (!info.isFile() || info.size() > MaximumBytes) + return fail(error, QStringLiteral("表情库不是普通文件或超过 8 MiB,原文件未修改")); + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) + return fail(error, QStringLiteral("无法读取表情库:%1").arg(file.errorString())); + const QByteArray bytes = file.read(MaximumBytes + 1); + if (file.error() != QFileDevice::NoError || bytes.size() > MaximumBytes) + return fail(error, QStringLiteral("读取表情库失败或文件过大,原文件未修改")); + QJsonParseError parseError; + const QJsonDocument document = QJsonDocument::fromJson(bytes, &parseError); + if (parseError.error != QJsonParseError::NoError || !document.isObject()) + return fail(error, QStringLiteral("表情库 JSON 损坏,已保留原文件,请先备份并修复")); + const QJsonObject root = document.object(); + if (!root.value(QStringLiteral("version")).isDouble() + || root.value(QStringLiteral("version")).toDouble() != 1.) + return fail(error, QStringLiteral("表情库版本不受支持,已保留原文件,禁止覆盖")); + if (!exactKeys(root, {QStringLiteral("version"), QStringLiteral("scopes")}) + || !root.value(QStringLiteral("scopes")).isArray()) + return fail(error, QStringLiteral("表情库结构无效,原文件未修改")); + const QJsonArray scopes = root.value(QStringLiteral("scopes")).toArray(); + if (scopes.size() > MaximumScopes) return fail(error, QStringLiteral("表情库连接分组过多")); + int total = 0; + QSet scopeIds; + for (const QJsonValue &value : scopes) { + if (!value.isObject()) return fail(error, QStringLiteral("表情库分组格式无效")); + const QJsonObject object = value.toObject(); + if (!exactKeys(object, {QStringLiteral("endpointKey"), QStringLiteral("deviceId"), QStringLiteral("expressions")}) + || !object.value(QStringLiteral("endpointKey")).isString() + || !object.value(QStringLiteral("deviceId")).isString() + || !object.value(QStringLiteral("expressions")).isArray()) + return fail(error, QStringLiteral("表情库分组字段无效")); + Scope scope{object.value(QStringLiteral("endpointKey")).toString(), + object.value(QStringLiteral("deviceId")).toString(), {}}; + if (!scopeValid(scope.endpointKey, scope.deviceId, error)) return false; + // JSON-encode the pair, avoiding ambiguous separator concatenations. + const QString key = QString::fromUtf8(QJsonDocument(QJsonArray{scope.endpointKey, scope.deviceId}).toJson(QJsonDocument::Compact)); + if (scopeIds.contains(key)) return fail(error, QStringLiteral("表情库包含重复连接分组")); + scopeIds.insert(key); + const QJsonArray expressions = object.value(QStringLiteral("expressions")).toArray(); + total += expressions.size(); + if (expressions.size() > MaximumPerScope || total > MaximumTotal) + return fail(error, QStringLiteral("表情库记录数量超出限制")); + QSet ids, names; + for (const QJsonValue &entry : expressions) { + Expression expression; + if (!parseExpression(entry, &expression, error)) return false; + if (ids.contains(expression.id) || names.contains(expression.name)) + return fail(error, QStringLiteral("表情库包含重复的表情 ID 或名称")); + ids.insert(expression.id); names.insert(expression.name); + scope.expressions.append(expression); + } + database->append(scope); + } + return true; +} + +bool write(const QString &path, const Database &database, QString *error) +{ + QJsonArray scopes; + int total = 0; + for (const Scope &scope : database) { + QJsonArray expressions; + for (const Expression &expression : scope.expressions) expressions.append(expressionJson(expression)); + total += expressions.size(); + if (expressions.size() > MaximumPerScope || total > MaximumTotal) + return fail(error, QStringLiteral("表情库记录数量超出限制,未保存")); + scopes.append(QJsonObject{{QStringLiteral("endpointKey"), scope.endpointKey}, + {QStringLiteral("deviceId"), scope.deviceId}, {QStringLiteral("expressions"), expressions}}); + } + if (scopes.size() > MaximumScopes) return fail(error, QStringLiteral("表情库连接分组过多,未保存")); + const QByteArray bytes = QJsonDocument(QJsonObject{{QStringLiteral("version"), 1}, + {QStringLiteral("scopes"), scopes}}).toJson(QJsonDocument::Indented); + if (bytes.size() > MaximumBytes) return fail(error, QStringLiteral("表情库超过 8 MiB,未保存")); + QSaveFile file(path); + file.setDirectWriteFallback(false); + if (!file.open(QIODevice::WriteOnly)) + return fail(error, QStringLiteral("无法写入表情库,原文件未修改:%1").arg(file.errorString())); + if (file.write(bytes) != bytes.size()) { + file.cancelWriting(); + return fail(error, QStringLiteral("表情库写入不完整,原文件未修改:%1").arg(file.errorString())); + } + if (!file.commit()) return fail(error, QStringLiteral("表情库提交失败,原文件未修改:%1").arg(file.errorString())); + return true; +} + +bool lock(QLockFile *file, QString *error) +{ + file->setStaleLockTime(30000); + if (file->tryLock(150)) return true; + return fail(error, file->error() == QLockFile::LockFailedError + ? QStringLiteral("表情库正在被其他窗口使用,请稍后重试") + : QStringLiteral("无法锁定表情库,请检查目录写入权限")); +} + +int findScope(const Database &database, const QString &endpointKey, const QString &deviceId) +{ + for (int i = 0; i < database.size(); ++i) + if (database[i].endpointKey == endpointKey && database[i].deviceId == deviceId) return i; + return -1; +} +} // namespace + +QString defaultPath() +{ + return QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("data/biohead_expressions.json")); +} + +bool load(const QString &path, const QString &endpointKey, const QString &deviceId, + QList *out, QString *error) +{ + if (error) error->clear(); + if (!out || path.isEmpty()) return fail(error, QStringLiteral("表情库路径或输出参数无效")); + if (!scopeValid(endpointKey, deviceId, error)) return false; + if (!QFileInfo(QFileInfo(path).absolutePath()).exists()) { out->clear(); return true; } + QLockFile guard(path + QStringLiteral(".lock")); + if (!lock(&guard, error)) return false; + Database database; + if (!read(path, &database, error)) return false; + const int index = findScope(database, endpointKey, deviceId); + *out = index < 0 ? QList() : database[index].expressions; + return true; +} + +bool save(const QString &path, const QString &endpointKey, const QString &deviceId, + const Expression &expression, bool replace, QString *error) +{ + if (error) error->clear(); + if (path.isEmpty()) return fail(error, QStringLiteral("表情库路径无效")); + if (!scopeValid(endpointKey, deviceId, error) || !expressionValid(expression, error)) return false; + if (!QDir().mkpath(QFileInfo(path).absolutePath())) + return fail(error, QStringLiteral("无法创建表情库目录,请检查写入权限")); + QLockFile guard(path + QStringLiteral(".lock")); + if (!lock(&guard, error)) return false; + Database database; + if (!read(path, &database, error)) return false; + int index = findScope(database, endpointKey, deviceId); + if (index < 0) { + if (replace) return fail(error, QStringLiteral("要覆盖的本地表情不存在,请先重新读取")); + database.append({endpointKey, deviceId, {}}); index = database.size() - 1; + } + QList &expressions = database[index].expressions; + int found = -1; + for (int i = 0; i < expressions.size(); ++i) { + if (expressions[i].id == expression.id) found = i; + if (expressions[i].name == expression.name && expressions[i].id != expression.id) + return fail(error, QStringLiteral("当前连接和设备下已有同名表情,请更换名称")); + } + if (replace && found < 0) return fail(error, QStringLiteral("要覆盖的本地表情不存在,请先重新读取")); + if (!replace && found >= 0) return fail(error, QStringLiteral("本地表情 ID 已存在,不能重复新增")); + if (replace) expressions[found] = expression; + else expressions.append(expression); + return write(path, database, error); +} + +bool remove(const QString &path, const QString &endpointKey, const QString &deviceId, + const QString &id, QString *error) +{ + if (error) error->clear(); + if (path.isEmpty() || !localId(id)) return fail(error, QStringLiteral("表情库路径或本地表情 ID 无效")); + if (!scopeValid(endpointKey, deviceId, error)) return false; + if (!QFileInfo(path).exists()) return fail(error, QStringLiteral("要删除的本地表情不存在")); + QLockFile guard(path + QStringLiteral(".lock")); + if (!lock(&guard, error)) return false; + Database database; + if (!read(path, &database, error)) return false; + const int index = findScope(database, endpointKey, deviceId); + if (index >= 0) { + auto &expressions = database[index].expressions; + for (int i = 0; i < expressions.size(); ++i) { + if (expressions[i].id != id) continue; + expressions.removeAt(i); + if (expressions.isEmpty()) database.removeAt(index); + return write(path, database, error); + } + } + return fail(error, QStringLiteral("要删除的本地表情不存在,请先重新读取")); +} +} // namespace BioHeadExpressionStore diff --git a/src/bioheadexpressionstore.h b/src/bioheadexpressionstore.h new file mode 100644 index 0000000..360ac00 --- /dev/null +++ b/src/bioheadexpressionstore.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include + +namespace BioHeadExpressionStore { + +// IDs are local, canonical QUuid::WithoutBraces values, never server preset IDs. +struct Expression { + QString id; + QString name; + QVariantList targets; + double transitionDurationS = 1.0; +}; + +QString defaultPath(); +bool load(const QString &path, const QString &endpointKey, const QString &deviceId, + QList *out, QString *error = nullptr); +bool save(const QString &path, const QString &endpointKey, const QString &deviceId, + const Expression &expression, bool replace, QString *error = nullptr); +bool remove(const QString &path, const QString &endpointKey, const QString &deviceId, + const QString &id, QString *error = nullptr); + +} // namespace BioHeadExpressionStore diff --git a/src/bioheadjointclient.cpp b/src/bioheadjointclient.cpp new file mode 100644 index 0000000..06ce50b --- /dev/null +++ b/src/bioheadjointclient.cpp @@ -0,0 +1,911 @@ +#include "bioheadjointclient.h" +#include "robotclient.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef CMVR_WITH_GRPC +#include +#include "cmvr/api/biohead_service.grpc.pb.h" +#include "cmvr/api/head_joint_command.pb.h" +#endif + +namespace { + +bool finiteNumber(const QVariant &value, double *number) +{ + bool ok = false; + const double converted = value.toDouble(&ok); + if (!ok || !std::isfinite(converted)) return false; + *number = converted; + return true; +} + +bool exactKeys(const QVariantMap ¶meters, const QStringList &keys) +{ + if (parameters.size() != keys.size()) return false; + for (const QString &key : keys) if (!parameters.contains(key)) return false; + return true; +} + +QString endpointAddress(QString host, int port) +{ + host = host.trimmed().toLower(); + if (host.startsWith(QLatin1Char('[')) && host.endsWith(QLatin1Char(']'))) + host = host.mid(1, host.size() - 2); + QHostAddress address; + if (address.setAddress(host)) host = address.toString().toLower(); + if (host.contains(QLatin1Char(':'))) host = QLatin1Char('[') + host + QLatin1Char(']'); + return QStringLiteral("%1:%2").arg(host).arg(port); +} + +QString validateStateMetadata(const QVariantMap &state) +{ + const QVariantList info = state.value(QStringLiteral("jointInfo")).toList(); + if (info.isEmpty() || info.size() > 64) + return QStringLiteral("服务没有返回有效的关节配置"); + QMap> limits; + for (const QVariant &entry : info) { + const QVariantMap joint = entry.toMap(); + const QString id = joint.value(QStringLiteral("id")).toString(); + double minimum = 0, maximum = 0, home = 0; + if (id.isEmpty() || id.trimmed() != id || limits.contains(id) + || !finiteNumber(joint.value(QStringLiteral("minPositionRad")), &minimum) + || !finiteNumber(joint.value(QStringLiteral("maxPositionRad")), &maximum) + || !finiteNumber(joint.value(QStringLiteral("homePositionRad")), &home) + || maximum <= minimum || home < minimum || home > maximum) + return QStringLiteral("服务返回的关节 ID、范围或初始姿态无效,请检查设备配置"); + limits.insert(id, qMakePair(minimum, maximum)); + } + QSet targetIds; + for (const QVariant &entry : state.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = entry.toMap(); + const QString id = target.value(QStringLiteral("id")).toString(); + if (!limits.contains(id) || targetIds.contains(id)) + return QStringLiteral("服务返回了未知或重复的目标关节 ID"); + targetIds.insert(id); + double position = 0; + if (target.value(QStringLiteral("targetValid")).toBool() + && (!finiteNumber(target.value(QStringLiteral("targetPositionRad")), &position) + || position < limits.value(id).first || position > limits.value(id).second)) + return QStringLiteral("服务返回的有效目标缓存超出关节范围"); + } + QSet expressionIds; + for (const QVariant &entry : state.value(QStringLiteral("expressions")).toList()) { + const QVariantMap expression = entry.toMap(); + const QString expressionId = expression.value(QStringLiteral("expressionId")).toString(); + if (expressionId.isEmpty() || expressionIds.contains(expressionId)) + return QStringLiteral("服务返回的表情预设 ID 为空或重复"); + expressionIds.insert(expressionId); + QSet presetIds; + for (const QVariant &targetEntry : expression.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = targetEntry.toMap(); + const QString id = target.value(QStringLiteral("id")).toString(); + double position = 0; + if (!limits.contains(id) || presetIds.contains(id) + || !finiteNumber(target.value(QStringLiteral("positionRad")), &position) + || position < limits.value(id).first || position > limits.value(id).second) + return QStringLiteral("服务返回的表情关节目标无效"); + presetIds.insert(id); + } + if (presetIds.size() != limits.size()) + return QStringLiteral("服务返回的表情没有包含全部配置关节"); + } + return {}; +} + +QVariantMap demoInitialState() +{ + const QStringList ids{QStringLiteral("eye_l_up"), QStringLiteral("eye_l_lower"), + QStringLiteral("eye_l_v"), QStringLiteral("eye_l_h"), + QStringLiteral("pwm8_local")}; + const double minimum[]{-1.0, -0.35, -1.5, -0.65, -1.5}; + const double maximum[]{1.0, 0.55, 1.0, 0.70, 0.393}; + const double home[]{0.0, 0.0, 0.0, 0.0, -1.0}; + QVariantList info, targets, expressions; + for (int i = 0; i < ids.size(); ++i) { + info.append(QVariantMap{{QStringLiteral("id"), ids[i]}, + {QStringLiteral("minPositionRad"), minimum[i]}, + {QStringLiteral("maxPositionRad"), maximum[i]}, + {QStringLiteral("homePositionRad"), home[i]}}); + targets.append(QVariantMap{{QStringLiteral("id"), ids[i]}, + {QStringLiteral("targetPositionRad"), 0.0}, + {QStringLiteral("targetValid"), false}}); + } + const char *presetIds[]{"0de8a527543e423abab593484926dd1c", + "ad8f669a78d54d30a2356512b0802c1d", "516bc0f0e76647109411cbf92e5c86fc", + "5e68f9b26f4d4f8580dead7777c6501b", "44821d9fa6df4fc78558666db32656e1", + "8f97ed10b5b44012b004183ba61c839c"}; + const QStringList names{QStringLiteral("中立"), QStringLiteral("微笑"), + QStringLiteral("疲倦"), QStringLiteral("惊讶"), QStringLiteral("生气"), + QStringLiteral("当前姿态")}; + const double positions[][5]{ + {0, 0, 0, 0, -1}, + {0.2329999953508377, -0.00041940261144191027, -0.00041940261144191027, + -0.00041940261144191027, -1.121000051498413}, + {-0.991, 0.322, -1.015, 0.004, -0.537}, + {-1, -0.0004194026121000505, 0.999890384765, + -0.0004194026121000505, -0.0004194026121000505}, + {-1, 0.5497252979258, 0.999890384765, 0.6999468312800001, -1.400129282005}, + {-0.0004194026121000505, -0.0004194026121000505, + -0.0004194026121000505, -0.65, -1}}; + for (int i = 0; i < 6; ++i) { + QVariantList presetTargets; + for (int j = 0; j < ids.size(); ++j) + presetTargets.append(QVariantMap{{QStringLiteral("id"), ids[j]}, + {QStringLiteral("positionRad"), positions[i][j]}}); + expressions.append(QVariantMap{{QStringLiteral("expressionId"), + QString::fromLatin1(presetIds[i])}, + {QStringLiteral("expressionName"), names[i]}, + {QStringLiteral("targets"), presetTargets}}); + } + return {{QStringLiteral("connected"), true}, + {QStringLiteral("jointInfo"), info}, {QStringLiteral("targets"), targets}, + {QStringLiteral("expressions"), expressions}, + {QStringLiteral("lastCommandOutcome"), QStringLiteral("HEAD_JOINT_COMMAND_NONE")}, + {QStringLiteral("lastError"), QString()}, + {QStringLiteral("positionFeedbackAvailable"), false}, + {QStringLiteral("expressionBaselineReady"), false}, + {QStringLiteral("hardwareEmergencyStopAvailable"), false}}; +} + +void invalidateTargets(QVariantMap &state) +{ + QVariantList targets = state.value(QStringLiteral("targets")).toList(); + for (QVariant &entry : targets) { + QVariantMap target = entry.toMap(); + target.insert(QStringLiteral("targetValid"), false); + entry = target; + } + state.insert(QStringLiteral("targets"), targets); + state.insert(QStringLiteral("expressionBaselineReady"), false); +} + +#ifdef CMVR_WITH_GRPC +QString channelStateName(grpc_connectivity_state state) +{ + switch (state) { + case GRPC_CHANNEL_IDLE: return QStringLiteral("IDLE"); + case GRPC_CHANNEL_CONNECTING: return QStringLiteral("CONNECTING"); + case GRPC_CHANNEL_READY: return QStringLiteral("READY"); + case GRPC_CHANNEL_TRANSIENT_FAILURE: return QStringLiteral("TRANSIENT_FAILURE"); + case GRPC_CHANNEL_SHUTDOWN: return QStringLiteral("SHUTDOWN"); + } + return QStringLiteral("UNKNOWN"); +} + +void fillHeader(cmvr::api::CommandHeader_Request *header, const QString &deviceId, + int timeoutMs) +{ + header->set_device_id(deviceId.toStdString()); + header->set_command_id(QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString()); + const qint64 milliseconds = QDateTime::currentMSecsSinceEpoch(); + header->mutable_timestamp()->set_seconds(milliseconds / 1000); + header->mutable_timestamp()->set_nanos(static_cast((milliseconds % 1000) * 1000000)); + header->set_valid_for_ms(static_cast(timeoutMs)); +} + +QVariantMap headerMap(const cmvr::api::CommandHeader_Feedback &header) +{ + // Use typed numeric getters. The bundled protobuf JSON formatter on this + // station corrupts double literals; no text round-trip is needed here. + return {{QStringLiteral("success"), header.success()}, + {QStringLiteral("errorMessage"), QString::fromStdString(header.error_message())}, + {QStringLiteral("timestamp"), QDateTime::fromMSecsSinceEpoch( + header.timestamp().seconds() * 1000 + header.timestamp().nanos() / 1000000, + Qt::UTC).toString(Qt::ISODateWithMs)}, + {QStringLiteral("reasonCode"), QString::fromStdString(cmvr::api::CommandReasonCode_Name(header.reason_code()))}, + {QStringLiteral("commandId"), QString::fromStdString(header.command_id())}, + {QStringLiteral("serviceInstanceId"), QString::fromStdString(header.service_instance_id())}, + {QStringLiteral("safetyEpoch"), QString::number(header.safety_epoch())}, + {QStringLiteral("deviceGeneration"), QString::number(header.device_generation())}, + {QStringLiteral("executionState"), QString::fromStdString(cmvr::api::CommandExecutionState_Name(header.execution_state()))}}; +} + +QVariantMap feedbackMap(const cmvr::api::HeadJointCommand_Feedback &feedback) +{ + QVariantMap result; + if (feedback.has_header()) result.insert(QStringLiteral("header"), headerMap(feedback.header())); + return result; +} + +QVariantMap feedbackMap(const cmvr::api::SetHeadExpressionCommand_Feedback &feedback) +{ + QVariantMap result; + if (feedback.has_header()) result.insert(QStringLiteral("header"), headerMap(feedback.header())); + return result; +} + +QVariantMap feedbackMap(const cmvr::api::PlayHeadExpressionCommand_Feedback &feedback) +{ + QVariantMap result{{QStringLiteral("expressionId"), QString::fromStdString(feedback.expression_id())}, + {QStringLiteral("expressionName"), QString::fromStdString(feedback.expression_name())}}; + if (feedback.has_header()) result.insert(QStringLiteral("header"), headerMap(feedback.header())); + return result; +} + +QVariantMap feedbackMap(const cmvr::api::GetHeadJointStateCommand_Feedback &feedback) +{ + QVariantList info, targets, expressions; + for (const auto &joint : feedback.joint_info()) { + info.append(QVariantMap{{QStringLiteral("id"), QString::fromStdString(joint.id())}, + {QStringLiteral("minPositionRad"), joint.min_position_rad()}, + {QStringLiteral("maxPositionRad"), joint.max_position_rad()}, + {QStringLiteral("homePositionRad"), joint.home_position_rad()}}); + } + for (const auto &target : feedback.targets()) { + targets.append(QVariantMap{{QStringLiteral("id"), QString::fromStdString(target.id())}, + {QStringLiteral("targetPositionRad"), target.target_position_rad()}, + {QStringLiteral("targetValid"), target.target_valid()}}); + } + for (const auto &expression : feedback.expressions()) { + QVariantList presetTargets; + for (const auto &target : expression.targets()) { + QVariantMap entry{{QStringLiteral("id"), QString::fromStdString(target.id())}}; + if (target.has_position_rad()) entry.insert(QStringLiteral("positionRad"), target.position_rad()); + presetTargets.append(entry); + } + expressions.append(QVariantMap{ + {QStringLiteral("expressionId"), QString::fromStdString(expression.expression_id())}, + {QStringLiteral("expressionName"), QString::fromStdString(expression.expression_name())}, + {QStringLiteral("targets"), presetTargets}}); + } + QVariantMap result{{QStringLiteral("connected"), feedback.connected()}, + {QStringLiteral("jointInfo"), info}, {QStringLiteral("targets"), targets}, + {QStringLiteral("expressions"), expressions}, + {QStringLiteral("lastCommandOutcome"), QString::fromStdString(cmvr::api::HeadJointCommandOutcome_Name(feedback.last_command_outcome()))}, + {QStringLiteral("lastError"), QString::fromStdString(feedback.last_error())}, + {QStringLiteral("positionFeedbackAvailable"), feedback.position_feedback_available()}, + {QStringLiteral("expressionBaselineReady"), feedback.expression_baseline_ready()}, + {QStringLiteral("hardwareEmergencyStopAvailable"), feedback.hardware_emergency_stop_available()}}; + if (feedback.has_header()) result.insert(QStringLiteral("header"), headerMap(feedback.header())); + return result; +} +#endif + +} // namespace + +struct BioHeadJointClient::Impl +{ + struct Result { + bool success = false; + QVariantMap data; + QString detail; + bool demoChanged = false; + QVariantMap demoState; + int demoMode = -1; + }; + + struct Session { + quint64 token = 0; + quint64 generation = 0; + QString deviceId; + QString operation; + QVariantMap parameters; + QString endpoint; + bool demo = false; + QVariantMap demoState; + int demoMode = -1; + std::atomic canceled{false}; + std::thread thread; +#ifdef CMVR_WITH_GRPC + std::shared_ptr channel; + quint64 channelInstance = 0; + std::mutex contextMutex; + std::shared_ptr context; +#endif + + void cancel() + { + canceled.store(true); +#ifdef CMVR_WITH_GRPC + std::lock_guard lock(contextMutex); + if (context) context->TryCancel(); +#endif + } + }; + + explicit Impl(BioHeadJointClient *owner) : q(owner), demoState(demoInitialState()) {} + + ~Impl() + { + { + std::lock_guard lock(dispatchMutex); + shuttingDown.store(true); + epoch.fetch_add(1); + if (active) active->cancel(); + if (cancellation) cancellation->cancel(); + } + if (active && active->thread.joinable()) active->thread.join(); + if (cancellation && cancellation->thread.joinable()) cancellation->thread.join(); + } + + BioHeadJointClient *q; + QString deviceId; + QString host; + int port = 0; + bool demo = false; + bool wantConnected = false; + bool connected = false; + std::atomic epoch{1}; + std::atomic shuttingDown{false}; + // Serializes cancellation/context changes with the worker's pre-dispatch check. + std::mutex dispatchMutex; + std::shared_ptr active; + std::shared_ptr cancellation; + QVariantMap state; + QVariantMap demoState; + int demoMode = -1; +#ifdef CMVR_WITH_GRPC + // The head owns its connection independently of the other device workers. + // Each admitted session keeps this channel alive even if the profile changes. + std::shared_ptr channel; + QString channelEndpoint; + quint64 nextChannelInstance = 0; +#endif + + void clearTransport() + { +#ifdef CMVR_WITH_GRPC + channel.reset(); + channelEndpoint.clear(); +#endif + } + + void invalidate(bool resetDemo = false, const std::function &changeContext = {}) + { + { + std::lock_guard lock(dispatchMutex); + epoch.fetch_add(1); + if (active) active->cancel(); + if (cancellation) cancellation->cancel(); + if (changeContext) changeContext(); + } + state.clear(); + if (resetDemo) { + demoState = demoInitialState(); + demoMode = -1; + } else { + invalidateTargets(demoState); + } + emit q->availabilityChanged(); + } + + void reject(quint64 token, const QString &operation, const QString &detail) + { + emit q->requestFinished(token, deviceId, operation, epoch.load(), false, {}, detail); + } + + QString validate(const QString &operation, const QVariantMap ¶meters) const + { + if (!connected || !wantConnected) + return QStringLiteral("请先连接服务,再操作仿生头"); + if (deviceId.isEmpty()) return QStringLiteral("请选择仿生头设备"); + if (operation == QLatin1String("move")) { + double position = 0; + if (!exactKeys(parameters, {QStringLiteral("id"), QStringLiteral("positionRad")}) + || parameters.value(QStringLiteral("id")).toString().isEmpty() + || !finiteNumber(parameters.value(QStringLiteral("positionRad")), &position)) + return QStringLiteral("单路调试需要关节 ID 和有限的弧度目标"); + if (!state.value(QStringLiteral("connected")).toBool()) + return QStringLiteral("请先成功读取当前设备的关节状态"); + const QString id = parameters.value(QStringLiteral("id")).toString(); + bool found = false; + for (const QVariant &value : state.value(QStringLiteral("jointInfo")).toList()) { + const QVariantMap joint = value.toMap(); + if (joint.value(QStringLiteral("id")).toString() != id) continue; + if (found) return QStringLiteral("服务返回了重复的关节 ID"); + found = true; + double minimum = 0, maximum = 0; + if (!finiteNumber(joint.value(QStringLiteral("minPositionRad")), &minimum) + || !finiteNumber(joint.value(QStringLiteral("maxPositionRad")), &maximum) + || maximum <= minimum || position < minimum || position > maximum) + return QStringLiteral("关节目标超出当前设备的配置范围"); + } + if (!found) return QStringLiteral("当前设备没有此关节"); + } else if (operation == QLatin1String("mode")) { + double mode = -1; + if (!exactKeys(parameters, {QStringLiteral("mode")}) + || !finiteNumber(parameters.value(QStringLiteral("mode")), &mode) + || mode != std::floor(mode) || mode < 0 || mode > 2) + return QStringLiteral("请选择有效的关节运动模式"); + } else if (operation == QLatin1String("expression")) { + double duration = 0; + if (!exactKeys(parameters, {QStringLiteral("targets"), QStringLiteral("transitionDurationS")}) + || parameters.value(QStringLiteral("targets")).type() != QVariant::List + || !finiteNumber(parameters.value(QStringLiteral("transitionDurationS")), &duration) + || duration < 0.2 || duration > 5.0) + return QStringLiteral("自定义表情需要完整目标和 0.2 到 5.0 秒的过渡时间"); + if (!state.value(QStringLiteral("connected")).toBool()) + return QStringLiteral("请先成功读取当前设备的关节配置"); + if (!state.value(QStringLiteral("expressionBaselineReady")).toBool()) + return QStringLiteral("表情起点未就绪,请先显式归位,不会自动移动舵机"); + const QVariantList configured = state.value(QStringLiteral("jointInfo")).toList(); + const QVariantList targets = parameters.value(QStringLiteral("targets")).toList(); + if (configured.size() != 5 || targets.size() != 5) + return QStringLiteral("自定义表情必须包含当前设备全部五路关节"); + QMap> limits; + for (const QVariant &entry : configured) { + const QVariantMap info = entry.toMap(); + limits.insert(info.value(QStringLiteral("id")).toString(), + qMakePair(info.value(QStringLiteral("minPositionRad")).toDouble(), + info.value(QStringLiteral("maxPositionRad")).toDouble())); + } + QSet seen; + for (const QVariant &entry : targets) { + if (entry.type() != QVariant::Map) + return QStringLiteral("自定义表情关节目标格式无效"); + const QVariantMap target = entry.toMap(); + const QString id = target.value(QStringLiteral("id")).toString(); + double position = 0; + if (!exactKeys(target, {QStringLiteral("id"), QStringLiteral("positionRad")}) + || !limits.contains(id) || seen.contains(id) + || !finiteNumber(target.value(QStringLiteral("positionRad")), &position) + || position < limits.value(id).first || position > limits.value(id).second) + return QStringLiteral("自定义表情含未知、重复、缺失或越界的关节目标"); + seen.insert(id); + } + } else if (operation == QLatin1String("play")) { + double duration = 0; + if (!exactKeys(parameters, {QStringLiteral("expressionId"), + QStringLiteral("transitionDurationS")}) + || !finiteNumber(parameters.value(QStringLiteral("transitionDurationS")), &duration) + || duration < 0.2 || duration > 5.0) + return QStringLiteral("表情过渡时间必须为 0.2 到 5.0 秒"); + if (!state.value(QStringLiteral("connected")).toBool()) + return QStringLiteral("请先成功读取当前设备的表情预设"); + const QString id = parameters.value(QStringLiteral("expressionId")).toString(); + int matches = 0; + for (const QVariant &value : state.value(QStringLiteral("expressions")).toList()) + if (value.toMap().value(QStringLiteral("expressionId")).toString() == id) ++matches; + if (id.isEmpty() || matches != 1) + return QStringLiteral("预设 ID 不属于当前设备或不唯一,请重新读取"); + } else if (operation == QLatin1String("state") || operation == QLatin1String("home") + || operation == QLatin1String("cancel") || operation == QLatin1String("reconnect")) { + if (!parameters.isEmpty()) return QStringLiteral("此操作不接受附加参数"); + } else { + return QStringLiteral("不支持的仿生头关节操作"); + } + return {}; + } + + Result runDemo(const std::shared_ptr &session) + { + Result result; + QVariantMap next = session->demoState; + int mode = session->demoMode; + const QString &operation = session->operation; + const QVariantMap ¶meters = session->parameters; + if (operation == QLatin1String("play") || operation == QLatin1String("expression")) { + if (!next.value(QStringLiteral("expressionBaselineReady")).toBool()) { + result.detail = QStringLiteral("请先显式回到初始姿态,建立表情起点(不会自动回位)"); + return result; + } + const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds( + static_cast(parameters.value(QStringLiteral("transitionDurationS")).toDouble() * 1000)); + while (std::chrono::steady_clock::now() < until) { + if (session->canceled.load()) { + result.detail = QStringLiteral("表情请求已取消;取消后续帧不等于硬件急停"); + return result; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + if (session->canceled.load()) { + result.detail = QStringLiteral("请求已取消"); + return result; + } + QVariantMap feedbackHeader{{QStringLiteral("success"), true}, + {QStringLiteral("errorMessage"), QString()}, + {QStringLiteral("commandId"), QUuid::createUuid().toString(QUuid::WithoutBraces)}, + {QStringLiteral("timestamp"), QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)}}; + result.data.insert(QStringLiteral("header"), feedbackHeader); + result.success = true; + if (operation == QLatin1String("state")) { + result.data = next; + result.data.insert(QStringLiteral("header"), feedbackHeader); + result.detail = QStringLiteral("演示:已读取五路配置和六个表情预设;目标缓存不是实测位置"); + return result; + } + QVariantList targets = next.value(QStringLiteral("targets")).toList(); + if (operation == QLatin1String("home")) { + mode = 0; + const QVariantList info = next.value(QStringLiteral("jointInfo")).toList(); + for (int i = 0; i < targets.size(); ++i) { + QVariantMap target = targets[i].toMap(); + target.insert(QStringLiteral("targetPositionRad"), info[i].toMap().value(QStringLiteral("homePositionRad"))); + target.insert(QStringLiteral("targetValid"), true); + targets[i] = target; + } + next.insert(QStringLiteral("expressionBaselineReady"), true); + } else if (operation == QLatin1String("move")) { + for (QVariant &entry : targets) { + QVariantMap target = entry.toMap(); + if (target.value(QStringLiteral("id")) != parameters.value(QStringLiteral("id"))) continue; + target.insert(QStringLiteral("targetPositionRad"), parameters.value(QStringLiteral("positionRad"))); + target.insert(QStringLiteral("targetValid"), mode == 0); + entry = target; + } + bool baseline = mode == 0 && targets.size() == 5; + for (const QVariant &entry : targets) + baseline = baseline && entry.toMap().value(QStringLiteral("targetValid")).toBool(); + next.insert(QStringLiteral("expressionBaselineReady"), baseline); + } else if (operation == QLatin1String("play")) { + for (const QVariant &entry : next.value(QStringLiteral("expressions")).toList()) { + const QVariantMap expression = entry.toMap(); + if (expression.value(QStringLiteral("expressionId")) != parameters.value(QStringLiteral("expressionId"))) continue; + targets.clear(); + for (const QVariant &targetEntry : expression.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = targetEntry.toMap(); + targets.append(QVariantMap{{QStringLiteral("id"), target.value(QStringLiteral("id"))}, + {QStringLiteral("targetPositionRad"), target.value(QStringLiteral("positionRad"))}, + {QStringLiteral("targetValid"), true}}); + } + result.data.insert(QStringLiteral("expressionId"), expression.value(QStringLiteral("expressionId"))); + result.data.insert(QStringLiteral("expressionName"), expression.value(QStringLiteral("expressionName"))); + } + } else if (operation == QLatin1String("expression")) { + targets.clear(); + for (const QVariant &entry : parameters.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = entry.toMap(); + targets.append(QVariantMap{{QStringLiteral("id"), target.value(QStringLiteral("id"))}, + {QStringLiteral("targetPositionRad"), target.value(QStringLiteral("positionRad"))}, + {QStringLiteral("targetValid"), true}}); + } + next.insert(QStringLiteral("expressionBaselineReady"), true); + } else if (operation == QLatin1String("mode")) { + mode = parameters.value(QStringLiteral("mode")).toInt(); + if (mode != 0) { + for (QVariant &entry : targets) { + QVariantMap target = entry.toMap(); + target.insert(QStringLiteral("targetValid"), false); + entry = target; + } + next.insert(QStringLiteral("expressionBaselineReady"), false); + } + } else if (operation == QLatin1String("reconnect") || operation == QLatin1String("cancel")) { + // A reconnect does not send a position; cancellation cannot prove where a mechanism stopped. + for (QVariant &entry : targets) { + QVariantMap target = entry.toMap(); + target.insert(QStringLiteral("targetValid"), false); + entry = target; + } + next.insert(QStringLiteral("expressionBaselineReady"), false); + } + next.insert(QStringLiteral("targets"), targets); + next.insert(QStringLiteral("lastCommandOutcome"), QStringLiteral("HEAD_JOINT_COMMAND_ACKNOWLEDGED")); + result.demoChanged = true; + result.demoState = next; + result.demoMode = mode; + result.detail = operation == QLatin1String("cancel") + ? QStringLiteral("演示:已取消后续表情帧;不代表硬件停止") + : QStringLiteral("演示:命令已确认;目标缓存不是实测位置"); + return result; + } + +#ifdef CMVR_WITH_GRPC + template + static Result rpcResult(const grpc::Status &status, const Feedback &feedback, + bool readOnlyState = false) + { + Result result; + result.data = feedbackMap(feedback); + result.success = status.ok() && feedback.has_header() && feedback.header().success(); + if (!status.ok()) { + result.data.insert(QStringLiteral("grpcCode"), static_cast(status.error_code())); + result.detail = readOnlyState + ? (status.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED + ? QStringLiteral("状态读取超时(gRPC %1):%2") + : QStringLiteral("状态读取失败(gRPC %1):%2")) + : QStringLiteral("gRPC %1:%2"); + result.detail = result.detail.arg(static_cast(status.error_code())) + .arg(QString::fromStdString(status.error_message())); + if (!readOnlyState && (status.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED + || status.error_code() == grpc::StatusCode::UNKNOWN)) + result.detail += QStringLiteral(";执行结果未确认,请先读取状态,不会自动重发"); + } else if (!result.success) { + result.detail = feedback.has_header() + ? QString::fromStdString(feedback.header().error_message()) + : QStringLiteral("服务反馈缺少命令结果"); + if (result.detail.isEmpty()) result.detail = QStringLiteral("服务拒绝了关节命令"); + if (readOnlyState) result.detail.prepend(QStringLiteral("状态读取失败:")); + } else { + result.detail = QStringLiteral("固件已确认;目标缓存不是实测位置,也不表示机械到位"); + } + return result; + } + + Result runRpc(const std::shared_ptr &session, + const std::shared_ptr &context) + { + auto stub = cmvr::api::BioHeadService::NewStub(session->channel); + const int timeoutMs = (session->operation == QLatin1String("play") + || session->operation == QLatin1String("expression")) + ? static_cast(std::ceil(session->parameters.value(QStringLiteral("transitionDurationS")).toDouble() * 1000)) + 2000 + : (session->operation == QLatin1String("state") ? 6000 : 3000); + context->set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(timeoutMs)); + if (session->operation == QLatin1String("state")) { + cmvr::api::GetHeadJointStateCommand_Request request; + cmvr::api::GetHeadJointStateCommand_Feedback response; + fillHeader(request.mutable_header(), session->deviceId, timeoutMs); + const auto status = stub->GetHeadJointState(context.get(), request, &response); + Result result = rpcResult(status, response, true); + if (result.success) result.detail = QStringLiteral("已读取关节配置、ACK 目标缓存和表情预设"); + return result; + } + if (session->operation == QLatin1String("play")) { + cmvr::api::PlayHeadExpressionCommand_Request request; + cmvr::api::PlayHeadExpressionCommand_Feedback response; + fillHeader(request.mutable_header(), session->deviceId, timeoutMs); + request.set_expression_id(session->parameters.value(QStringLiteral("expressionId")).toString().toStdString()); + request.set_transition_duration_s(session->parameters.value(QStringLiteral("transitionDurationS")).toDouble()); + const auto status = stub->PlayHeadExpression(context.get(), request, &response); + return rpcResult(status, response); + } + if (session->operation == QLatin1String("expression")) { + cmvr::api::SetHeadExpressionCommand_Request request; + cmvr::api::SetHeadExpressionCommand_Feedback response; + fillHeader(request.mutable_header(), session->deviceId, timeoutMs); + for (const QVariant &entry : session->parameters.value(QStringLiteral("targets")).toList()) { + const QVariantMap value = entry.toMap(); + auto *target = request.add_targets(); + target->set_id(value.value(QStringLiteral("id")).toString().toStdString()); + target->set_position_rad(value.value(QStringLiteral("positionRad")).toDouble()); + } + request.set_transition_duration_s(session->parameters.value(QStringLiteral("transitionDurationS")).toDouble()); + const auto status = stub->SetHeadExpression(context.get(), request, &response); + return rpcResult(status, response); + } + cmvr::api::HeadJointCommand_Request request; + cmvr::api::HeadJointCommand_Feedback response; + fillHeader(request.mutable_header(), session->deviceId, timeoutMs); + if (session->operation == QLatin1String("move")) { + auto *target = request.mutable_move()->add_targets(); + target->set_id(session->parameters.value(QStringLiteral("id")).toString().toStdString()); + // Explicitly select the oneof even when the requested position is zero. + target->set_position_rad(session->parameters.value(QStringLiteral("positionRad")).toDouble()); + } else if (session->operation == QLatin1String("home")) { + request.mutable_home(); + } else if (session->operation == QLatin1String("mode")) { + request.mutable_mode()->set_mode(static_cast( + session->parameters.value(QStringLiteral("mode")).toInt())); + } else if (session->operation == QLatin1String("cancel")) { + request.mutable_cancel_expression(); + } else if (session->operation == QLatin1String("reconnect")) { + request.mutable_reconnect(); + } + const auto status = stub->ControlHeadJoints(context.get(), request, &response); + Result result = rpcResult(status, response); + if (result.success && session->operation == QLatin1String("cancel")) + result.detail = QStringLiteral("已请求取消后续表情帧;不代表固件轨迹或机械停止"); + if (result.success && session->operation == QLatin1String("reconnect")) + result.detail = QStringLiteral("串口已打开并完成探测;没有发送位置目标"); + return result; + } +#endif + + void complete(const std::shared_ptr &session, Result result) + { + if (session->thread.joinable()) session->thread.join(); + if (active == session) active.reset(); + if (cancellation == session) cancellation.reset(); + if (session->generation != epoch.load() || shuttingDown.load()) { + emit q->availabilityChanged(); + return; + } + if (session->canceled.load()) { + result.success = false; + result.detail = session->operation == QLatin1String("state") + ? QStringLiteral("状态读取已取消") + : QStringLiteral("请求已取消;已发送到设备的命令无法由本地撤回"); + } + if (result.success && session->operation == QLatin1String("state")) { + const QString metadataError = validateStateMetadata(result.data); + if (metadataError.isEmpty()) { + state = result.data; + } else { + state.clear(); + result.success = false; + result.detail = metadataError; + } + } else if (session->operation != QLatin1String("state")) { + // Require another explicit state read before using cached targets as confirmation. + if (!result.success || session->operation == QLatin1String("cancel") + || session->operation == QLatin1String("reconnect") + || (session->operation == QLatin1String("mode") + && session->parameters.value(QStringLiteral("mode")).toInt() != 0)) { + invalidateTargets(state); + invalidateTargets(demoState); + } + if (result.demoChanged && result.success) { + demoState = result.demoState; + demoMode = result.demoMode; + } + } else if (!result.success) { + state.clear(); + } + emit q->requestFinished(session->token, session->deviceId, session->operation, + session->generation, result.success, result.data, result.detail); + emit q->availabilityChanged(); + } + + void start(quint64 token, const QString &operation, const QVariantMap ¶meters) + { + const QString error = validate(operation, parameters); + if (!error.isEmpty()) { reject(token, operation, error); return; } + const bool cancel = operation == QLatin1String("cancel"); + if ((cancel && cancellation) || (!cancel && (active || cancellation))) { + reject(token, operation, QStringLiteral("上一条关节请求尚未结束;没有排队或重发旧目标")); + return; + } + auto session = std::make_shared(); + session->token = token; + session->generation = epoch.load(); + session->deviceId = deviceId; + session->operation = operation; + session->parameters = parameters; + session->demo = demo; + session->endpoint = endpointAddress(host, port); +#ifdef CMVR_WITH_GRPC + if (!demo) { + if (!channel || channelEndpoint != session->endpoint) { + channel = grpc::CreateChannel(session->endpoint.toStdString(), grpc::InsecureChannelCredentials()); + channelEndpoint = session->endpoint; + ++nextChannelInstance; + } + session->channel = channel; + session->channelInstance = nextChannelInstance; + } +#endif + session->demoState = demoState; + session->demoMode = demoMode; + if (cancel) { + // Independent lane: a blocking Play must not delay its own cancellation. + if (active) active->cancel(); + cancellation = session; + } else { + active = session; + } + emit q->requestStarted(token, deviceId, operation, parameters, session->generation); + emit q->availabilityChanged(); + session->thread = std::thread([this, session] { + Result result; + QElapsedTimer elapsed; + elapsed.start(); + QString channelBefore = session->demo ? QStringLiteral("DEMO") : QStringLiteral("UNAVAILABLE"); +#ifdef CMVR_WITH_GRPC + auto context = std::make_shared(); + if (session->channel) channelBefore = channelStateName(session->channel->GetState(false)); +#endif + bool dispatch = false; + { + std::lock_guard lock(dispatchMutex); + dispatch = !shuttingDown.load() && !session->canceled.load() + && session->generation == epoch.load(); +#ifdef CMVR_WITH_GRPC + if (dispatch) { + std::lock_guard contextLock(session->contextMutex); + session->context = context; + if (session->canceled.load()) context->TryCancel(); + } +#endif + } + try { + if (!dispatch) { + result.detail = QStringLiteral("连接或设备已变化,请求未发送"); + } else if (session->demo) { + result = runDemo(session); + } else { +#ifdef CMVR_WITH_GRPC + result = runRpc(session, context); +#else + result.detail = QStringLiteral("此构建未启用 gRPC,请重新构建后连接真实设备"); +#endif + } + } catch (const std::exception &error) { + result.detail = (session->operation == QLatin1String("state") + ? QStringLiteral("状态读取失败:%1") : QStringLiteral("仿生头请求失败:%1")) + .arg(QString::fromUtf8(error.what())); + } catch (...) { + result.detail = session->operation == QLatin1String("state") + ? QStringLiteral("状态读取失败") : QStringLiteral("仿生头请求失败,不会自动重发"); + } + result.data.insert(QStringLiteral("endpoint"), + (session->demo ? QStringLiteral("demo://") : QStringLiteral("grpc://")) + session->endpoint); + result.data.insert(QStringLiteral("elapsedMs"), elapsed.elapsed()); + result.data.insert(QStringLiteral("channelStateBefore"), channelBefore); + QString channelAfter = channelBefore; +#ifdef CMVR_WITH_GRPC + if (session->channel) channelAfter = channelStateName(session->channel->GetState(false)); + result.data.insert(QStringLiteral("channelInstance"), QString::number(session->channelInstance)); +#endif + result.data.insert(QStringLiteral("channelStateAfter"), channelAfter); + if (!shuttingDown.load()) { + QMetaObject::invokeMethod(q, [this, session, result] { complete(session, result); }, + Qt::QueuedConnection); + } + }); + } +}; + +BioHeadJointClient::BioHeadJointClient(RobotClient *client, QObject *parent) + : QObject(parent), m_impl(new Impl(this)) +{ + if (!client) return; + connect(client, &RobotClient::connectRequested, this, + [this](const QString &host, int port, bool demo) { + m_impl->invalidate(true, [this, host, port, demo] { + m_impl->clearTransport(); + m_impl->connected = false; + m_impl->wantConnected = true; + m_impl->host = host.trimmed(); + m_impl->port = port; + m_impl->demo = demo; + }); + }); + connect(client, &RobotClient::disconnectRequested, this, [this] { + m_impl->invalidate(false, [this] { + m_impl->clearTransport(); + m_impl->connected = false; + m_impl->wantConnected = false; + }); + }); + connect(client, &RobotClient::connectionChanged, this, + [this](bool connected, int, const QString &) { + const bool usable = connected && m_impl->wantConnected + && (m_impl->demo || (!m_impl->host.isEmpty() && m_impl->port > 0 && m_impl->port <= 65535)); + if (m_impl->connected == usable) return; + m_impl->invalidate(false, [this, usable] { m_impl->connected = usable; }); + }); + connect(client, &RobotClient::systemStopAllRequested, this, + [this](const QString &) { cancelPending(); }); + connect(client, &RobotClient::rpcRequested, this, + [this](const QString &service, const QString &method, const QString &, const QString &) { + if (service == QLatin1String("cmvr.api.SystemService") && method == QLatin1String("StopAll")) + cancelPending(); + }); + connect(client, &QObject::destroyed, this, [this] { + m_impl->invalidate(false, [this] { + m_impl->clearTransport(); + m_impl->connected = false; + m_impl->wantConnected = false; + }); + }); +} + +BioHeadJointClient::~BioHeadJointClient() = default; + +void BioHeadJointClient::setDeviceId(const QString &deviceId) +{ + const QString next = deviceId.trimmed(); + if (m_impl->deviceId == next) return; + m_impl->invalidate(true, [this, next] { m_impl->deviceId = next; }); +} + +quint64 BioHeadJointClient::generation() const { return m_impl->epoch.load(); } +QString BioHeadJointClient::endpointKey() const +{ + return (m_impl->demo ? QStringLiteral("demo://") : QStringLiteral("grpc://")) + + endpointAddress(m_impl->host, m_impl->port); +} +bool BioHeadJointClient::isConnected() const { return m_impl->connected; } +bool BioHeadJointClient::isBusy() const { return bool(m_impl->active || m_impl->cancellation); } + +void BioHeadJointClient::request(quint64 token, const QString &operation, + const QVariantMap ¶meters) +{ + m_impl->start(token, operation, parameters); +} + +void BioHeadJointClient::cancelPending() { m_impl->invalidate(); } diff --git a/src/bioheadjointclient.h b/src/bioheadjointclient.h new file mode 100644 index 0000000..98e6969 --- /dev/null +++ b/src/bioheadjointclient.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include + +#include + +class RobotClient; + +// Dedicated USB-head RPC sessions. Position feedback is not supplied by this +// protocol; a successful command reports firmware ACK, not physical arrival. +class BioHeadJointClient final : public QObject +{ + Q_OBJECT +public: + explicit BioHeadJointClient(RobotClient *client, QObject *parent = nullptr); + ~BioHeadJointClient() override; + + void setDeviceId(const QString &deviceId); + QString endpointKey() const; + quint64 generation() const; + bool isConnected() const; + bool isBusy() const; + void request(quint64 token, const QString &operation, + const QVariantMap ¶meters = {}); + void cancelPending(); + +signals: + void requestStarted(quint64 token, const QString &deviceId, + const QString &operation, const QVariantMap ¶meters, + quint64 generation); + void requestFinished(quint64 token, const QString &deviceId, + const QString &operation, quint64 generation, + bool success, const QVariantMap &data, + const QString &detail); + void availabilityChanged(); + +private: + struct Impl; + std::unique_ptr m_impl; +}; diff --git a/src/bioheadwidget.cpp b/src/bioheadwidget.cpp index c15d982..57a2b5f 100644 --- a/src/bioheadwidget.cpp +++ b/src/bioheadwidget.cpp @@ -1,225 +1,1157 @@ #include "bioheadwidget.h" -#include "bioheadoperations.h" +#include "bioheadjointclient.h" +#include "bioheadexpressionstore.h" +#include "appmessagebox.h" #include "applicationstyle.h" #include "robotclient.h" #include "rpcservicewidget.h" #include #include +#include #include #include #include +#include #include #include #include +#include #include +#include +#include +#include #include +#include #include -#include +#include #include +#include +#include +#include -BioHeadWidget::BioHeadWidget(RobotClient *client, QWidget *parent) - : QWidget(parent), m_client(client) +namespace { +constexpr double sliderScale = 10000.; +QString jointName(const QString &id) +{ + if (id == QStringLiteral("eye_l_up")) return QStringLiteral("左眼上眼睑"); + if (id == QStringLiteral("eye_l_lower")) return QStringLiteral("左眼下眼睑"); + if (id == QStringLiteral("eye_l_v")) return QStringLiteral("左眼垂直"); + if (id == QStringLiteral("eye_l_h")) return QStringLiteral("左眼水平"); + if (id == QStringLiteral("pwm8_local")) return QStringLiteral("本地 PWM8"); + return QStringLiteral("舵机"); +} +bool finiteNumber(const QVariantMap &map, const QString &key, double *number) +{ + if (!map.contains(key)) return false; + const QVariant v = map.value(key); + if (v.type() != QVariant::Double && v.type() != QVariant::Int + && v.type() != QVariant::UInt && v.type() != QVariant::LongLong + && v.type() != QVariant::ULongLong) return false; + *number = v.toDouble(); + return std::isfinite(*number); +} +QString operationName(const QString &operation) +{ + if (operation == QStringLiteral("state")) return QStringLiteral("读取配置和目标"); + if (operation == QStringLiteral("mode")) return QStringLiteral("启用拖动调试"); + if (operation == QStringLiteral("move")) return QStringLiteral("单舵机调试"); + if (operation == QStringLiteral("home")) return QStringLiteral("归位并准备预设"); + if (operation == QStringLiteral("play")) return QStringLiteral("执行预设表情"); + if (operation == QStringLiteral("expression")) return QStringLiteral("执行本地表情"); + if (operation == QStringLiteral("cancel")) return QStringLiteral("取消表情帧"); + return QStringLiteral("重新连接头部"); +} +} + +BioHeadWidget::BioHeadWidget(RobotClient *client, QWidget *parent, const QString &storagePath) + : QWidget(parent), m_client(client), m_jointClient(new BioHeadJointClient(client, this)), + m_storagePath(storagePath.isEmpty() ? BioHeadExpressionStore::defaultPath() : storagePath) { setObjectName(QStringLiteral("bioheadPage")); + m_jointClient->setObjectName(QStringLiteral("bioheadJointClient")); auto *layout = new QVBoxLayout(this); layout->setContentsMargins(16, 12, 16, 14); - auto *tabs = new QTabWidget(this); - tabs->setObjectName(QStringLiteral("serviceTabs")); - auto *controls = new QWidget(tabs); + m_tabs = new QTabWidget(this); + m_tabs->setObjectName(QStringLiteral("serviceTabs")); + auto *controls = new QWidget(m_tabs); auto *content = new QVBoxLayout(controls); content->setContentsMargins(0, 12, 0, 0); - content->setSpacing(12); + content->setSpacing(10); auto *header = new QFrame(controls); header->setObjectName(QStringLiteral("panel")); auto *headerLayout = new QHBoxLayout(header); - auto *title = new QLabel(QStringLiteral("仿生头控制"), header); + auto *title = new QLabel(QStringLiteral("仿生头 · 舵机调试"), header); title->setObjectName(QStringLiteral("sectionTitle")); headerLayout->addWidget(title); headerLayout->addStretch(); headerLayout->addWidget(new QLabel(QStringLiteral("设备"), header)); m_device = new QComboBox(header); m_device->setObjectName(QStringLiteral("bioheadDeviceCombo")); - m_device->setMinimumWidth(220); + m_device->setMinimumWidth(180); ApplicationStyle::styleComboBox(m_device); headerLayout->addWidget(m_device); + auto makeButton = [](const QString &text, const QString &name, QWidget *parent) { + auto *b = new QPushButton(text, parent); + b->setObjectName(name); + b->setMinimumHeight(34); + return b; + }; + m_refresh = makeButton(QStringLiteral("刷新配置与目标"), QStringLiteral("bioheadRefreshButton"), header); + m_reconnect = makeButton(QStringLiteral("重新连接头部"), QStringLiteral("bioheadReconnectButton"), header); + headerLayout->addWidget(m_refresh); + headerLayout->addWidget(m_reconnect); content->addWidget(header); - auto *actionPanels = new QHBoxLayout; - actionPanels->setSpacing(12); - auto addPanel = [&](const QString &heading, const QString &description, - const QStringList &actions, int columns) { - auto *panel = new QFrame(controls); - panel->setObjectName(QStringLiteral("panel")); - auto *box = new QVBoxLayout(panel); - box->setContentsMargins(18, 16, 18, 18); - box->setSpacing(16); - auto *headingRow = new QHBoxLayout; - auto *label = new QLabel(heading, panel); - label->setObjectName(QStringLiteral("sectionTitle")); - headingRow->addWidget(label); - headingRow->addStretch(); - auto *help = new QToolButton(panel); - help->setObjectName(QStringLiteral("bioheadHelp")); - help->setText(QStringLiteral("?")); - help->setAccessibleName(heading + QStringLiteral("使用说明")); - help->setToolTip(description); - headingRow->addWidget(help); - box->addLayout(headingRow); - auto *grid = new QGridLayout; - grid->setSpacing(12); - for (int i = 0; i < actions.size(); ++i) { - const QString action = actions.at(i); - auto *button = new QPushButton(action, panel); - button->setObjectName(action == QStringLiteral("紧急停止") - ? QStringLiteral("dangerButton") : action == QStringLiteral("开始说话") - ? QStringLiteral("primaryButton") : QStringLiteral("secondaryButton")); - button->setProperty("bioheadAction", action); - button->setProperty("bioheadPreset", actions.size() == 6); - button->setMinimumHeight(56); - button->setToolTip(BioHeadOperations::hint(action)); - connect(button, &QPushButton::clicked, this, [this, action]() { invoke(action); }); - grid->addWidget(button, i / columns, i % columns); - m_buttons.append(button); - } - box->addLayout(grid); - actionPanels->addWidget(panel, actions.size() == 6 ? 3 : 2); - }; - addPanel(QStringLiteral("预设表情"), - QStringLiteral("直接调用服务端预设动作。接口确认不代表舵机已到位,当前不提供实际姿态遥测。"), - BioHeadOperations::actions().mid(0, 6), 3); - addPanel(QStringLiteral("动作控制"), - QStringLiteral("开始说话会持续执行嘴部动作,不播放音频。请使用“停止说话”结束;急停保持姿态,但服务端未保证终止说话线程。"), - {QStringLiteral("开始说话"), QStringLiteral("停止说话"), - QStringLiteral("紧急停止"), QStringLiteral("检查设备")}, 2); - content->addLayout(actionPanels); + auto *body = new QHBoxLayout; + body->setSpacing(12); + auto *servoPanel = new QFrame(controls); + servoPanel->setObjectName(QStringLiteral("panel")); + auto *servoLayout = new QVBoxLayout(servoPanel); + servoLayout->setContentsMargins(16, 14, 16, 14); + auto *servoHeader = new QHBoxLayout; + auto *servoTitle = new QLabel(QStringLiteral("逐个舵机调试"), servoPanel); + servoTitle->setObjectName(QStringLiteral("sectionTitle")); + servoHeader->addWidget(servoTitle); + servoHeader->addStretch(); + m_enableDebug = makeButton(QStringLiteral("启用拖动调试"), QStringLiteral("bioheadEnableDebugButton"), servoPanel); + servoHeader->addWidget(m_enableDebug); + servoLayout->addLayout(servoHeader); + m_profileStatus = new QLabel(QStringLiteral("连接后读取设备实际配置,不会自动移动舵机。"), servoPanel); + m_profileStatus->setObjectName(QStringLiteral("bioheadProfileStatus")); + m_profileStatus->setWordWrap(true); + servoLayout->addWidget(m_profileStatus); + auto *scroll = new QScrollArea(servoPanel); + scroll->setObjectName(QStringLiteral("bioheadServoScroll")); + scroll->setWidgetResizable(true); + scroll->setFrameShape(QFrame::NoFrame); + auto *rows = new QWidget(scroll); + m_rows = new QVBoxLayout(rows); + m_rows->setContentsMargins(0, 4, 4, 0); + m_rows->setSpacing(10); + m_rows->addStretch(); + scroll->setWidget(rows); + servoLayout->addWidget(scroll, 1); + auto *servoHint = new QLabel(QStringLiteral("拖动调试当前舵机,单位 rad。\n确认目标来自接口 ACK,设备不提供实际位置反馈。"), servoPanel); + servoHint->setWordWrap(true); + servoHint->setObjectName(QStringLiteral("mutedLabel")); + servoLayout->addWidget(servoHint); + body->addWidget(servoPanel, 3); + + auto *presetPanel = new QFrame(controls); + presetPanel->setObjectName(QStringLiteral("panel")); + auto *presetLayout = new QVBoxLayout(presetPanel); + presetLayout->setContentsMargins(16, 14, 16, 14); + m_expressionTabs = new QTabWidget(presetPanel); + m_expressionTabs->setObjectName(QStringLiteral("bioheadExpressionTabs")); + auto *serverPage = new QWidget(m_expressionTabs); + auto *serverLayout = new QVBoxLayout(serverPage); + serverLayout->setContentsMargins(4, 8, 4, 4); + m_presets = new QComboBox(presetPanel); + m_presets->setObjectName(QStringLiteral("bioheadPresetCombo")); + ApplicationStyle::styleComboBox(m_presets); + serverLayout->addWidget(m_presets); + auto *durationRow = new QHBoxLayout; + durationRow->addWidget(new QLabel(QStringLiteral("过渡时长"), presetPanel)); + m_transition = new QDoubleSpinBox(presetPanel); + m_transition->setObjectName(QStringLiteral("bioheadTransitionSeconds")); + m_transition->setRange(.2, 5.); + m_transition->setDecimals(1); + m_transition->setSingleStep(.1); + m_transition->setValue(1.); + m_transition->setSuffix(QStringLiteral(" s")); + durationRow->addWidget(m_transition, 1); + serverLayout->addLayout(durationRow); + m_presetPreview = new QLabel(QStringLiteral("等待设备预设"), presetPanel); + m_presetPreview->setObjectName(QStringLiteral("bioheadPresetPreview")); + m_presetPreview->setWordWrap(true); + m_presetPreview->setTextInteractionFlags(Qt::TextSelectableByMouse); + serverLayout->addWidget(m_presetPreview); + auto *selectionHint = new QLabel(QStringLiteral("选择仅预览,点击执行后开始过渡。"), presetPanel); + selectionHint->setObjectName(QStringLiteral("mutedLabel")); + selectionHint->setWordWrap(true); + serverLayout->addWidget(selectionHint); + m_play = makeButton(QStringLiteral("执行所选表情"), QStringLiteral("bioheadPlayPresetButton"), serverPage); + serverLayout->addWidget(m_play); + serverLayout->addStretch(); + m_expressionTabs->addTab(serverPage, QStringLiteral("设备预设")); + + auto *localScroll = new QScrollArea(m_expressionTabs); + localScroll->setObjectName(QStringLiteral("bioheadLocalExpressionScroll")); + localScroll->setWidgetResizable(true); + localScroll->setFrameShape(QFrame::NoFrame); + auto *localPage = new QWidget(localScroll); + auto *localLayout = new QVBoxLayout(localPage); + localLayout->setContentsMargins(4, 8, 4, 4); + localLayout->setSpacing(6); + m_localList = new QComboBox(localPage); + m_localList->setObjectName(QStringLiteral("bioheadLocalExpressionCombo")); + ApplicationStyle::styleComboBox(m_localList); + localLayout->addWidget(m_localList); + auto *localFields = new QHBoxLayout; + m_localName = new QLineEdit(localPage); + m_localName->setObjectName(QStringLiteral("bioheadLocalExpressionName")); + m_localName->setPlaceholderText(QStringLiteral("新表情名称")); + m_localName->setMaxLength(80); + localFields->addWidget(m_localName, 2); + m_localTransition = new QDoubleSpinBox(localPage); + m_localTransition->setObjectName(QStringLiteral("bioheadLocalTransitionSeconds")); + m_localTransition->setRange(.2, 5.); + m_localTransition->setDecimals(1); + m_localTransition->setSingleStep(.1); + m_localTransition->setValue(1.); + m_localTransition->setSuffix(QStringLiteral(" s")); + m_localTransition->setToolTip(QStringLiteral("本地表情过渡时长(0.2~5 秒)")); + localFields->addWidget(m_localTransition, 1); + localLayout->addLayout(localFields); + m_localPreview = new QLabel(QStringLiteral("当前设备尚无本地表情"), localPage); + m_localPreview->setObjectName(QStringLiteral("bioheadLocalExpressionPreview")); + m_localPreview->setWordWrap(true); + m_localPreview->setTextInteractionFlags(Qt::TextSelectableByMouse); + localLayout->addWidget(m_localPreview); + auto *localButtons = new QGridLayout; + localButtons->setSpacing(6); + m_localEdit = makeButton(QStringLiteral("编辑输入(不发送)"), QStringLiteral("bioheadLocalEditButton"), localPage); + m_localLoad = makeButton(QStringLiteral("载入目标"), QStringLiteral("bioheadLocalLoadButton"), localPage); + m_localCapture = makeButton(QStringLiteral("保存当前目标为新表情"), QStringLiteral("bioheadLocalCaptureButton"), localPage); + m_localUpdate = makeButton(QStringLiteral("更新所选"), QStringLiteral("bioheadLocalUpdateButton"), localPage); + m_localDelete = makeButton(QStringLiteral("删除所选"), QStringLiteral("bioheadLocalDeleteButton"), localPage); + m_localPlay = makeButton(QStringLiteral("执行本地表情"), QStringLiteral("bioheadLocalPlayButton"), localPage); + localButtons->addWidget(m_localEdit, 0, 0); + localButtons->addWidget(m_localLoad, 0, 1); + localButtons->addWidget(m_localCapture, 1, 0); + localButtons->addWidget(m_localUpdate, 1, 1); + localButtons->addWidget(m_localDelete, 2, 0); + localButtons->addWidget(m_localPlay, 2, 1); + localLayout->addLayout(localButtons); + auto *localHint = new QLabel(QStringLiteral("保存当前输入目标,不会发送动作。选择仅预览,载入后可编辑;执行才会移动舵机。"), localPage); + localHint->setObjectName(QStringLiteral("mutedLabel")); + localHint->setWordWrap(true); + localLayout->addWidget(localHint); + m_localLibraryStatus = new QLabel(localPage); + m_localLibraryStatus->setObjectName(QStringLiteral("bioheadLocalLibraryStatus")); + m_localLibraryStatus->setWordWrap(true); + localLayout->addWidget(m_localLibraryStatus); + localLayout->addStretch(); + localScroll->setWidget(localPage); + m_expressionTabs->addTab(localScroll, QStringLiteral("本地表情")); + presetLayout->addWidget(m_expressionTabs, 1); + m_baselineStatus = new QLabel(QStringLiteral("预设基线未知"), presetPanel); + m_baselineStatus->setObjectName(QStringLiteral("bioheadBaselineStatus")); + m_baselineStatus->setWordWrap(true); + presetLayout->addWidget(m_baselineStatus); + m_home = makeButton(QStringLiteral("归位并准备预设"), QStringLiteral("bioheadHomeButton"), presetPanel); + presetLayout->addWidget(m_home); + auto *homeHint = new QLabel(QStringLiteral("归位会移动全部配置舵机到各自初始目标,并设置调试模式。"), presetPanel); + homeHint->setWordWrap(true); + homeHint->setObjectName(QStringLiteral("mutedLabel")); + presetLayout->addWidget(homeHint); + m_cancel = makeButton(QStringLiteral("取消表情"), QStringLiteral("bioheadCancelExpressionButton"), presetPanel); + presetLayout->addWidget(m_cancel); + auto *cancelHint = new QLabel(QStringLiteral("取消仅停止后续表情帧,不能撤回已发送动作,也不是硬件急停。"), presetPanel); + cancelHint->setWordWrap(true); + cancelHint->setObjectName(QStringLiteral("mutedLabel")); + presetLayout->addWidget(cancelHint); + body->addWidget(presetPanel, 2); + content->addLayout(body, 1); auto *feedback = new QFrame(controls); feedback->setObjectName(QStringLiteral("panel")); auto *feedbackLayout = new QVBoxLayout(feedback); + feedbackLayout->setContentsMargins(14, 10, 14, 10); auto *feedbackHeader = new QHBoxLayout; - auto *feedbackTitle = new QLabel(QStringLiteral("操作记录"), feedback); - feedbackTitle->setObjectName(QStringLiteral("sectionTitle")); - feedbackHeader->addWidget(feedbackTitle); - feedbackHeader->addStretch(); - auto *clear = new QPushButton(QStringLiteral("清空记录"), feedback); - clear->setObjectName(QStringLiteral("secondaryButton")); - feedbackHeader->addWidget(clear); - feedbackLayout->addLayout(feedbackHeader); m_status = new QLabel(QStringLiteral("未连接"), feedback); - m_status->setToolTip(QStringLiteral("请连接服务并刷新设备列表。调用反馈仅代表接口结果,不代表实际运动状态。")); m_status->setObjectName(QStringLiteral("bioheadStatus")); m_status->setWordWrap(true); m_status->setTextInteractionFlags(Qt::TextSelectableByMouse); - feedbackLayout->addWidget(m_status); + feedbackHeader->addWidget(m_status, 1); + auto *clear = makeButton(QStringLiteral("清空记录"), QStringLiteral("bioheadClearHistoryButton"), feedback); + feedbackHeader->addWidget(clear); + feedbackLayout->addLayout(feedbackHeader); m_history = new QListWidget(feedback); m_history->setObjectName(QStringLiteral("bioheadHistory")); + m_history->setMaximumHeight(100); m_history->setSelectionMode(QAbstractItemView::ExtendedSelection); - feedbackLayout->addWidget(m_history, 1); + feedbackLayout->addWidget(m_history); + content->addWidget(feedback); connect(clear, &QPushButton::clicked, m_history, &QListWidget::clear); - content->addWidget(feedback, 1); + m_tabs->addTab(controls, QStringLiteral("常用操作")); + m_rpc = new RpcServiceWidget(QStringLiteral("cmvr.api.BioHeadService"), client, m_tabs); + m_tabs->addTab(m_rpc, QStringLiteral("全部接口")); + layout->addWidget(m_tabs); - tabs->addTab(controls, QStringLiteral("常用操作")); - m_rpc = new RpcServiceWidget(QStringLiteral("cmvr.api.BioHeadService"), client, tabs); - tabs->addTab(m_rpc, QStringLiteral("全部接口")); - layout->addWidget(tabs); - connect(m_device, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { - m_rpc->setDeviceId(m_device->currentData().toString()); + m_dispatchTimer = new QTimer(this); + m_dispatchTimer->setInterval(100); + connect(m_dispatchTimer, &QTimer::timeout, this, &BioHeadWidget::advanceRequests); + connect(m_device, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { changeDeviceContext(); }); + connect(m_presets, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { updatePresetPreview(); refreshControls(); }); + connect(m_localList, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { + clearPendingTargets(); + m_debugReady = false; + m_profileStatus->setText(m_localEditing + ? QStringLiteral("本地编辑输入:滑块和数值只修改输入,不发送动作。") + : QStringLiteral("已选择本地表情,仅预览目标;可载入编辑或显式执行。")); + updateLocalPreview(); refreshControls(); }); + connect(m_localEdit, &QPushButton::clicked, this, &BioHeadWidget::enterLocalEditing); + connect(m_localLoad, &QPushButton::clicked, this, &BioHeadWidget::loadLocalTargets); + connect(m_localCapture, &QPushButton::clicked, this, [this] { saveLocalExpression(false); }); + connect(m_localUpdate, &QPushButton::clicked, this, [this] { saveLocalExpression(true); }); + connect(m_localDelete, &QPushButton::clicked, this, &BioHeadWidget::deleteLocalExpression); + connect(m_localPlay, &QPushButton::clicked, this, &BioHeadWidget::executeLocalExpression); + connect(m_expressionTabs, &QTabWidget::currentChanged, this, [this](int) { + clearPendingTargets(); + m_debugReady = false; + m_modeMayEnable = false; + m_localEditing = false; + m_profileStatus->setText(QStringLiteral("拖动调试已停用;可显式启用调试,或在本地表情中编辑输入。")); + refreshControls(); + }); + connect(m_refresh, &QPushButton::clicked, this, &BioHeadWidget::requestState); + connect(m_enableDebug, &QPushButton::clicked, this, [this] { + clearPendingTargets(); + m_localEditing = false; + beginRequest(QStringLiteral("mode"), {{QStringLiteral("mode"), 0}}); + }); + connect(m_reconnect, &QPushButton::clicked, this, [this] { + clearPendingTargets(); m_debugReady = false; m_baselineReady = false; m_localEditing = false; + beginRequest(QStringLiteral("reconnect")); + }); + connect(m_home, &QPushButton::clicked, this, [this] { + clearPendingTargets(); m_debugReady = false; m_baselineReady = false; m_localEditing = false; + beginRequest(QStringLiteral("home")); + }); + connect(m_play, &QPushButton::clicked, this, [this] { + if (!m_metadataValid || !m_baselineReady || !m_expressions.contains(m_presets->currentData().toString())) return; + clearPendingTargets(); m_debugReady = false; m_localEditing = false; + beginRequest(QStringLiteral("play"), {{QStringLiteral("expressionId"), m_presets->currentData()}, + {QStringLiteral("transitionDurationS"), m_transition->value()}}); + }); + connect(m_cancel, &QPushButton::clicked, this, [this] { + resetInteraction(QStringLiteral("正在取消后续表情帧;已发送动作不能撤回。"), false, true); + m_cancelToken = ++m_nextToken; + m_cancelGeneration = m_jointClient->generation(); + refreshControls(); + m_jointClient->request(m_cancelToken, QStringLiteral("cancel")); + }); + connect(m_jointClient, &BioHeadJointClient::requestFinished, this, &BioHeadWidget::finishRequest); + connect(m_jointClient, &BioHeadJointClient::availabilityChanged, this, [this] { + if (m_resetting) return; + if (m_observedGeneration != m_jointClient->generation()) { + resetInteraction(QStringLiteral("连接上下文已变化,旧操作已作废。"), true, false); + reloadLocalExpressions(); + if (m_connected) requestState(); + } + refreshControls(); + }); + connect(m_tabs, &QTabWidget::currentChanged, this, [this](int) { + resetInteraction(QStringLiteral("已清除待发送目标;返回调试页后需重新启用。"), false, true); + if (onControlPage()) requestState(); + }); connect(client, &RobotClient::systemStatusReceived, this, [this](double, double, double, const QVariantList &devices) { setAvailableDevices(devices); }); connect(client, &RobotClient::connectionChanged, this, [this](bool connected, int, const QString &) { + const bool changed = m_connected != connected; m_connected = connected; if (!connected) { - m_pendingMethod.clear(); - m_pendingDevice.clear(); + resetInteraction(QStringLiteral("连接已断开,目标状态未知。"), true, true); setAvailableDevices({}); - m_status->setText(QStringLiteral("连接已断开")); - } - refreshControls(); - }); - connect(client, &RobotClient::rpcFinished, this, - [this](const QString &service, const QString &method, bool success, const QString &json) { - if (service != QStringLiteral("cmvr.api.BioHeadService") - || m_pendingMethod.isEmpty() || method != m_pendingMethod) return; - QString detail; - const bool accepted = BioHeadOperations::responseSucceeded(success, json, &detail); - const QString message = QStringLiteral("%1 · %2:%3") - .arg(m_pendingDevice, m_pendingAction, detail); - m_pendingMethod.clear(); - m_pendingDevice.clear(); - m_status->setText(message); - addFeedback(accepted, message); + } else if (changed) requestState(); refreshControls(); }); + m_observedGeneration = m_jointClient->generation(); + reloadLocalExpressions(); refreshControls(); } +bool BioHeadWidget::onControlPage() const +{ + return isVisible() && m_tabs->currentIndex() == 0; +} + +bool BioHeadWidget::canAdjust() const +{ + return onControlPage() && m_connected && m_jointClient->isConnected() + && m_headConnected && m_metadataValid && !m_stateReadFailed + && m_debugReady && !m_localEditing && !m_cancelToken + && (!m_activeToken || m_activeOperation == QStringLiteral("move")) + && (!m_jointClient->isBusy() || (m_activeToken && m_activeOperation == QStringLiteral("move"))); +} + +bool BioHeadWidget::dragging() const +{ + for (const JointRow &row : m_joints) if (row.slider->isSliderDown()) return true; + return false; +} + void BioHeadWidget::setAvailableDevices(const QVariantList &devices) { QStringList ids; - for (const auto &value : devices) { + for (const QVariant &value : devices) { const QVariantMap device = value.toMap(); const QString id = device.value(QStringLiteral("deviceId")).toString(); - if (device.value(QStringLiteral("type"), -1).toInt() == 8 && !id.isEmpty() - && !ids.contains(id)) ids.append(id); + if (device.value(QStringLiteral("type"), -1).toInt() == 8 && !id.isEmpty() && !ids.contains(id)) ids.append(id); } QStringList existing; - for (int i = 0; i < m_device->count(); ++i) - existing.append(m_device->itemData(i).toString()); - // Periodic system refreshes must not erase the most recent action result. + for (int i = 0; i < m_device->count(); ++i) existing.append(m_device->itemData(i).toString()); if (ids == existing) return; const QString previous = m_device->currentData().toString(); - QSignalBlocker blocker(m_device); - m_device->clear(); - for (const auto &id : ids) m_device->addItem(id, id); - const int index = m_device->findData(previous); - if (index >= 0) m_device->setCurrentIndex(index); - m_rpc->setDeviceId(m_device->currentData().toString()); - if (m_pendingMethod.isEmpty()) - m_status->setText(m_device->count() ? QStringLiteral("待操作") - : QStringLiteral("未发现仿生头设备")); + { + QSignalBlocker blocker(m_device); + m_device->clear(); + for (const QString &id : ids) m_device->addItem(id, id); + const int index = m_device->findData(previous); + if (index >= 0) m_device->setCurrentIndex(index); + } + if (previous != m_device->currentData().toString()) changeDeviceContext(); refreshControls(); } void BioHeadWidget::setDeviceId(const QString &deviceId) { - m_device->setCurrentIndex(m_device->findData(deviceId)); - m_rpc->setDeviceId(deviceId); + const int index = m_device->findData(deviceId); + if (index >= 0 || deviceId.isEmpty()) m_device->setCurrentIndex(index); +} + +void BioHeadWidget::changeDeviceContext() +{ + resetInteraction(QStringLiteral("读取当前设备的配置与预设…"), true, true); + m_resetting = true; + m_jointClient->setDeviceId(m_device->currentData().toString()); + m_resetting = false; + m_observedGeneration = m_jointClient->generation(); + m_rpc->setDeviceId(m_device->currentData().toString()); + reloadLocalExpressions(); + if (m_device->currentData().toString().isEmpty()) m_status->setText(QStringLiteral("未发现仿生头设备")); + else requestState(); + refreshControls(); +} + +void BioHeadWidget::clearPendingTargets() +{ + m_pendingTargets.clear(); + m_pendingOrder.clear(); + m_editedSliders.clear(); +} + +void BioHeadWidget::clearMetadata() +{ + m_metadataValid = false; + m_profileSignature.clear(); + m_joints.clear(); + while (m_rows->count()) { + QLayoutItem *item = m_rows->takeAt(0); + if (item->widget()) delete item->widget(); + delete item; + } + m_rows->addStretch(); + m_expressions.clear(); + { + QSignalBlocker blocker(m_presets); + m_presets->clear(); + } + m_profileStatus->setText(QStringLiteral("尚无有效舵机配置;请读取配置或重新连接头部。")); + updatePresetPreview(); +} + +void BioHeadWidget::resetInteraction(const QString &message, bool removeMetadata, bool cancelTransport) +{ + clearPendingTargets(); + m_needState = false; + m_dispatchTimer->stop(); + m_activeToken = 0; + m_cancelToken = 0; + m_activeOperation.clear(); + m_activeDevice.clear(); + m_activeJoint.clear(); + m_debugReady = false; + m_modeMayEnable = false; + m_localEditing = false; + m_stateReadFailed = false; + m_headConnected = false; + m_baselineReady = false; + m_confirmedTargets.clear(); + if (cancelTransport) { + m_resetting = true; + m_jointClient->cancelPending(); + m_resetting = false; + } + m_observedGeneration = m_jointClient->generation(); + if (removeMetadata) clearMetadata(); + else { + for (const JointRow &row : m_joints) row.confirmed->setText(QStringLiteral("确认目标:未知")); + m_profileStatus->setText(QStringLiteral("拖动调试已停用;请重新读取配置并显式启用。目标状态未知。")); + } + if (!message.isEmpty()) m_status->setText(message); + refreshControls(); +} + +void BioHeadWidget::requestState() +{ + if (!onControlPage() || !m_connected || !m_jointClient->isConnected() + || m_device->currentData().toString().isEmpty()) return; + m_needState = true; + if (!m_dispatchTimer->isActive()) m_dispatchTimer->start(); + refreshControls(); +} + +void BioHeadWidget::beginRequest(const QString &operation, const QVariantMap ¶meters) +{ + if (!onControlPage() || !m_connected || !m_jointClient->isConnected() + || m_device->currentData().toString().isEmpty() || m_activeToken || m_cancelToken + || m_jointClient->isBusy()) return; + m_activeToken = ++m_nextToken; + m_activeGeneration = m_jointClient->generation(); + m_activeDevice = m_device->currentData().toString(); + m_activeOperation = operation; + if (operation == QStringLiteral("mode")) m_modeMayEnable = true; + if (operation == QStringLiteral("move")) { + m_activeJoint = parameters.value(QStringLiteral("id")).toString(); + m_activeTarget = parameters.value(QStringLiteral("positionRad")).toDouble(); + } else m_activeJoint.clear(); + m_status->setText(QStringLiteral("%1 · 正在%2…").arg(m_activeDevice, operationName(operation))); + refreshControls(); + m_jointClient->request(m_activeToken, operation, parameters); +} + +void BioHeadWidget::queueTarget(const QString &id, double value) +{ + if (!canAdjust() || !m_joints.contains(id)) return; + const JointRow row = m_joints.value(id); + if (!std::isfinite(value) || value < row.minimum || value > row.maximum) return; + if (m_activeToken && m_activeOperation == QStringLiteral("move") && m_activeJoint == id + && std::abs(m_activeTarget - value) < 0.0000001) { + m_pendingTargets.remove(id); + m_pendingOrder.removeAll(id); + return; + } + if (!m_activeToken && m_confirmedTargets.contains(id) + && std::abs(m_confirmedTargets.value(id) - value) < 0.0000001) { + m_pendingTargets.remove(id); + m_pendingOrder.removeAll(id); + return; + } + if (!m_pendingTargets.contains(id)) m_pendingOrder.append(id); + m_pendingTargets[id] = value; + if (!m_dispatchTimer->isActive()) m_dispatchTimer->start(); + refreshControls(); +} + +void BioHeadWidget::advanceRequests() +{ + if (!onControlPage() || !m_connected || !m_jointClient->isConnected()) { + clearPendingTargets(); m_needState = false; m_dispatchTimer->stop(); return; + } + if (m_activeToken || m_cancelToken || m_jointClient->isBusy()) return; + if (!m_pendingOrder.isEmpty()) { + if (!canAdjust()) { clearPendingTargets(); } + else { + const QString id = m_pendingOrder.takeFirst(); + const double value = m_pendingTargets.take(id); + beginRequest(QStringLiteral("move"), {{QStringLiteral("id"), id}, {QStringLiteral("positionRad"), value}}); + return; + } + } + if (m_needState && !dragging()) { + m_needState = false; + beginRequest(QStringLiteral("state")); + return; + } + if (!m_needState && m_pendingOrder.isEmpty()) m_dispatchTimer->stop(); + refreshControls(); +} + +void BioHeadWidget::finishRequest(quint64 token, const QString &device, const QString &operation, + quint64 generation, bool success, const QVariantMap &data, + const QString &detail) +{ + if (generation != m_jointClient->generation() || device != m_device->currentData().toString()) return; + const bool cancellation = token == m_cancelToken && generation == m_cancelGeneration + && operation == QStringLiteral("cancel"); + if (!cancellation && (token != m_activeToken || generation != m_activeGeneration + || operation != m_activeOperation || device != m_activeDevice)) return; + const QString joint = m_activeJoint; + const double target = m_activeTarget; + if (cancellation) m_cancelToken = 0; + else { m_activeToken = 0; m_activeOperation.clear(); m_activeDevice.clear(); m_activeJoint.clear(); } + if (!success) { + if (operation == QStringLiteral("state")) { + // A read failure says nothing about whether a preceding motion ran. + // Keep this scope's validated configuration and local input draft, + // while requiring a fresh state before any further live control. + clearPendingTargets(); + m_needState = false; + m_dispatchTimer->stop(); + m_debugReady = false; + m_modeMayEnable = false; + m_headConnected = false; + m_baselineReady = false; + m_stateReadFailed = true; + if (!m_metadataValid || !localScopeMatches()) m_localEditing = false; + for (const JointRow &row : m_joints) { + row.confirmed->setText(m_confirmedTargets.contains(row.id) + ? QStringLiteral("上次确认:%1 rad(待刷新)").arg(m_confirmedTargets.value(row.id), 0, 'f', 4) + : QStringLiteral("目标待刷新")); + } + const QString failure = data.value(QStringLiteral("grpcCode")).toInt() == 4 + ? QStringLiteral("超时") : QStringLiteral("失败"); + const QString message = QStringLiteral("%1 · 状态读取%2:%3;此次为只读请求,真实控制已暂停,请手动刷新。") + .arg(device, failure, detail); + m_status->setText(message); + addFeedback(false, message, false); + refreshControls(); + return; + } + const QString message = QStringLiteral("%1 · %2失败:%3;目标状态未知,请刷新或重新连接头部。") + .arg(device, operationName(operation), detail); + resetInteraction(message, false, true); + addFeedback(false, message); + return; + } + if (operation == QStringLiteral("state")) { + const bool wasReadFailed = m_stateReadFailed; + const QByteArray previousProfile = m_profileSignature; + QString error; + if (!installState(data, &error)) { + const QString message = QStringLiteral("%1 · 配置不可用:%2;已禁用动作。旧设备需支持头部关节接口。") + .arg(device, error); + resetInteraction(message, true, true); + addFeedback(false, message); + return; + } + m_status->setText(QStringLiteral("%1 · 已读取 %2 路舵机、%3 个表情;显示确认目标,无实际位置反馈。") + .arg(device).arg(m_joints.size()).arg(m_expressions.size())); + if (wasReadFailed && (previousProfile.isEmpty() || previousProfile == m_profileSignature)) { + emit statusMessage(QStringLiteral("OK"), + QStringLiteral("%1 · 状态读取已恢复:已读取 %2 路舵机、%3 个表情;本次仅刷新状态。") + .arg(device).arg(m_joints.size()).arg(m_expressions.size())); + } + } else { + if (operation == QStringLiteral("mode")) { + m_debugReady = m_modeMayEnable; + m_modeMayEnable = false; + } + if (operation == QStringLiteral("move") && m_joints.contains(joint)) { + m_confirmedTargets[joint] = target; + m_joints[joint].confirmed->setText(QStringLiteral("确认目标:%1 rad").arg(target, 0, 'f', 4)); + } + const QString message = QStringLiteral("%1 · %2 ACK:%3(不代表舵机已到位)") + .arg(device, operationName(operation), detail); + m_status->setText(message); + addFeedback(true, message); + m_needState = true; + } + if (!m_pendingOrder.isEmpty() || m_needState) m_dispatchTimer->start(); + refreshControls(); +} + +bool BioHeadWidget::installState(const QVariantMap &state, QString *error) +{ + auto fail = [&](const QString &message) { *error = message; return false; }; + const QVariantList info = state.value(QStringLiteral("jointInfo")).toList(); + if (info.isEmpty() || info.size() > 64) return fail(QStringLiteral("缺少有效 jointInfo,或通道数量超出接口能力")); + QMap config; + for (const QVariant &value : info) { + const QVariantMap item = value.toMap(); + const QString id = item.value(QStringLiteral("id")).toString(); + double low, high, home; + if (id.isEmpty() || config.contains(id) + || !finiteNumber(item, QStringLiteral("minPositionRad"), &low) + || !finiteNumber(item, QStringLiteral("maxPositionRad"), &high) + || !finiteNumber(item, QStringLiteral("homePositionRad"), &home) + || low >= high || home < low || home > high + || low * sliderScale < std::numeric_limits::min() + || high * sliderScale > std::numeric_limits::max() + || std::ceil(low * sliderScale) >= std::floor(high * sliderScale)) + return fail(QStringLiteral("舵机 %1 的编号、范围或初始目标非法/缺失").arg(id)); + config[id] = item; + } + const QVariantList expressions = state.value(QStringLiteral("expressions")).toList(); + QMap expressionMap; + for (const QVariant &value : expressions) { + const QVariantMap item = value.toMap(); + const QString id = item.value(QStringLiteral("expressionId")).toString(); + const QVariantList targets = item.value(QStringLiteral("targets")).toList(); + if (id.isEmpty() || expressionMap.contains(id) || targets.size() != config.size()) + return fail(QStringLiteral("预设表情编号重复或目标不完整")); + QSet seen; + for (const QVariant &targetValue : targets) { + const QVariantMap target = targetValue.toMap(); + const QString joint = target.value(QStringLiteral("id")).toString(); + double position; + if (!config.contains(joint) || seen.contains(joint) + || !finiteNumber(target, QStringLiteral("positionRad"), &position) + || position < config.value(joint).value(QStringLiteral("minPositionRad")).toDouble() + || position > config.value(joint).value(QStringLiteral("maxPositionRad")).toDouble()) + return fail(QStringLiteral("预设 %1 含未知、重复或越界舵机目标").arg(id)); + seen.insert(joint); + } + expressionMap[id] = item; + } + QMap confirmed; + QSet seen; + for (const QVariant &value : state.value(QStringLiteral("targets")).toList()) { + const QVariantMap item = value.toMap(); + const QString id = item.value(QStringLiteral("id")).toString(); + if (!config.contains(id) || seen.contains(id)) return fail(QStringLiteral("返回目标的舵机编号无效")); + seen.insert(id); + if (!item.value(QStringLiteral("targetValid"), false).toBool()) continue; + double position; + if (!finiteNumber(item, QStringLiteral("targetPositionRad"), &position) + || position < config.value(id).value(QStringLiteral("minPositionRad")).toDouble() - 0.000001 + || position > config.value(id).value(QStringLiteral("maxPositionRad")).toDouble() + 0.000001) + return fail(QStringLiteral("确认目标缺失或越界")); + confirmed[id] = position; + } + const QByteArray signature = QJsonDocument::fromVariant(info).toJson(QJsonDocument::Compact); + if (signature != m_profileSignature) { + clearPendingTargets(); + m_debugReady = false; + m_localEditing = false; + rebuildRows(info); + m_profileSignature = signature; + } + m_metadataValid = true; + m_stateReadFailed = false; + m_headConnected = state.value(QStringLiteral("connected"), false).toBool(); + m_baselineReady = state.value(QStringLiteral("expressionBaselineReady"), false).toBool(); + const QString outcome = state.value(QStringLiteral("lastCommandOutcome")).toString(); + if (outcome.contains(QStringLiteral("UNKNOWN"), Qt::CaseInsensitive) + || outcome.contains(QStringLiteral("REJECT"), Qt::CaseInsensitive) + || state.value(QStringLiteral("lastCommandOutcome")).toInt() == 2 + || state.value(QStringLiteral("lastCommandOutcome")).toInt() == 3) m_debugReady = false; + m_confirmedTargets = confirmed; + for (const JointRow &row : m_joints) { + const bool known = confirmed.contains(row.id); + row.confirmed->setText(known + ? QStringLiteral("确认目标:%1 rad").arg(confirmed.value(row.id), 0, 'f', 4) + : QStringLiteral("确认目标:未知")); + row.confirmed->setToolTip(known + ? QStringLiteral("接口已确认的目标,不是实测位置。") + : QStringLiteral("输入显示初始参考值,尚未发送。请先启用拖动调试。")); + if (!m_localEditing && !m_pendingTargets.contains(row.id) && !row.slider->isSliderDown()) { + const double position = known ? confirmed.value(row.id) : row.home; + QSignalBlocker sliderBlock(row.slider), valueBlock(row.value); + row.slider->setValue(qRound(position * sliderScale)); + row.value->setValue(position); + } + } + const QString previous = m_presets->currentData().toString(); + m_expressions = expressionMap; + { + QSignalBlocker blocker(m_presets); + m_presets->clear(); + for (const QVariant &value : expressions) { + const QVariantMap item = value.toMap(); + const QString id = item.value(QStringLiteral("expressionId")).toString(); + const QString name = item.value(QStringLiteral("expressionName")).toString(); + m_presets->addItem(name.isEmpty() ? id : name, id); + } + const int index = m_presets->findData(previous); + if (index >= 0) m_presets->setCurrentIndex(index); + } + m_profileStatus->setText(m_headConnected + ? QStringLiteral("已读取设备实际 %1 路配置 · %2。无实际位置反馈。") + .arg(m_joints.size()).arg(m_localEditing ? QStringLiteral("本地编辑输入,不发送动作") + : m_debugReady ? QStringLiteral("拖动调试已启用") : QStringLiteral("请先启用拖动调试")) + : QStringLiteral("头部连接未就绪,请显式重新连接头部。")); + updatePresetPreview(); + return true; +} + +void BioHeadWidget::rebuildRows(const QVariantList &jointInfo) +{ + m_joints.clear(); + while (m_rows->count()) { + QLayoutItem *item = m_rows->takeAt(0); + if (item->widget()) delete item->widget(); + delete item; + } + for (const QVariant &value : jointInfo) { + const QVariantMap info = value.toMap(); + JointRow row; + row.id = info.value(QStringLiteral("id")).toString(); + row.minimum = info.value(QStringLiteral("minPositionRad")).toDouble(); + row.maximum = info.value(QStringLiteral("maxPositionRad")).toDouble(); + row.home = info.value(QStringLiteral("homePositionRad")).toDouble(); + auto *panel = new QFrame; + panel->setObjectName(QStringLiteral("bioheadServoRow_") + row.id); + panel->setProperty("jointId", row.id); + auto *box = new QVBoxLayout(panel); + box->setContentsMargins(8, 2, 8, 4); + box->setSpacing(2); + auto *titleRow = new QHBoxLayout; + auto *label = new QLabel(jointName(row.id) + QStringLiteral(" · ") + row.id, panel); + titleRow->addWidget(label, 1); + row.value = new QDoubleSpinBox(panel); + row.value->setObjectName(QStringLiteral("bioheadServoValue_") + row.id); + row.value->setProperty("jointId", row.id); + row.value->setDecimals(4); + row.value->setRange(row.minimum, row.maximum); + row.value->setSingleStep(.01); + row.value->setSuffix(QStringLiteral(" rad")); + row.value->setMinimumWidth(140); + row.value->setKeyboardTracking(false); + row.value->setValue(row.home); + titleRow->addWidget(row.value); + box->addLayout(titleRow); + row.slider = new QSlider(Qt::Horizontal, panel); + row.slider->setObjectName(QStringLiteral("bioheadServoSlider_") + row.id); + row.slider->setProperty("jointId", row.id); + row.slider->setRange(static_cast(std::ceil(row.minimum * sliderScale)), + static_cast(std::floor(row.maximum * sliderScale))); + row.slider->setSingleStep(1); + row.slider->setPageStep(100); + row.slider->setValue(qRound(row.home * sliderScale)); + box->addWidget(row.slider); + auto *rangeRow = new QHBoxLayout; + auto *range = new QLabel(QStringLiteral("%1 … %2 rad").arg(row.minimum, 0, 'f', 3).arg(row.maximum, 0, 'f', 3), panel); + range->setObjectName(QStringLiteral("mutedLabel")); + rangeRow->addWidget(range); + rangeRow->addStretch(); + row.confirmed = new QLabel(QStringLiteral("确认目标:未知"), panel); + row.confirmed->setObjectName(QStringLiteral("bioheadServoConfirmed_") + row.id); + row.confirmed->setWordWrap(false); + rangeRow->addWidget(row.confirmed); + box->addLayout(rangeRow); + m_rows->addWidget(panel); + m_joints[row.id] = row; + const QString id = row.id; + connect(row.slider, &QSlider::valueChanged, this, [this, id](int raw) { + if (!m_joints.contains(id)) return; + const JointRow row = m_joints.value(id); + const double position = raw / sliderScale; + { QSignalBlocker blocker(row.value); row.value->setValue(position); } + if (row.slider->isSliderDown() && !m_editedSliders.contains(id)) m_editedSliders.append(id); + queueTarget(id, position); + }); + connect(row.slider, &QSlider::sliderReleased, this, [this, id] { + if (!m_joints.contains(id) || !m_editedSliders.removeOne(id)) return; + queueTarget(id, m_joints.value(id).slider->value() / sliderScale); + }); + connect(row.value, QOverload::of(&QDoubleSpinBox::valueChanged), this, [this, id](double position) { + if (!m_joints.contains(id)) return; + { QSignalBlocker blocker(m_joints.value(id).slider); + m_joints.value(id).slider->setValue(qRound(position * sliderScale)); } + queueTarget(id, position); + }); + } + m_rows->addStretch(); +} + +void BioHeadWidget::updatePresetPreview() +{ + const QString id = m_presets->currentData().toString(); + if (!m_expressions.contains(id)) { + m_presetPreview->setText(QStringLiteral("等待设备预设")); + m_presetPreview->setToolTip(QString()); + return; + } + const QVariantMap preset = m_expressions.value(id); + QStringList lines; + lines.append(QStringLiteral("预设目标(仅预览)")); + m_presetPreview->setToolTip(QStringLiteral("预设 ID:%1").arg(id)); + for (const QVariant &value : preset.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = value.toMap(); + lines.append(QStringLiteral("%1 %2 rad").arg(jointName(target.value(QStringLiteral("id")).toString())) + .arg(target.value(QStringLiteral("positionRad")).toDouble(), 0, 'f', 4)); + } + m_presetPreview->setText(lines.join(QLatin1Char('\n'))); } void BioHeadWidget::refreshControls() { - const bool enabled = m_connected && !m_device->currentData().toString().isEmpty() - && m_pendingMethod.isEmpty(); - for (auto *button : m_buttons) button->setEnabled(enabled); - m_device->setEnabled(m_pendingMethod.isEmpty()); + const bool ready = onControlPage() && m_connected && m_jointClient->isConnected() + && !m_device->currentData().toString().isEmpty(); + const bool idle = ready && !m_activeToken && !m_cancelToken && !m_jointClient->isBusy() + && !m_needState && m_pendingOrder.isEmpty(); + m_device->setEnabled(m_connected); + m_refresh->setEnabled(ready && !m_activeToken && !m_cancelToken && !m_jointClient->isBusy()); + m_reconnect->setEnabled(idle); + m_enableDebug->setEnabled(idle && m_metadataValid && m_headConnected && !m_stateReadFailed); + m_home->setEnabled(idle && m_metadataValid && m_headConnected && !m_stateReadFailed); + m_presets->setEnabled(idle && m_metadataValid); + m_transition->setEnabled(idle && m_metadataValid); + m_play->setEnabled(idle && m_metadataValid && m_headConnected && m_baselineReady && !m_stateReadFailed + && m_expressions.contains(m_presets->currentData().toString())); + m_cancel->setEnabled(ready && !m_cancelToken && m_metadataValid + && (m_headConnected || m_activeOperation == QStringLiteral("play") + || m_activeOperation == QStringLiteral("expression") || m_activeOperation == QStringLiteral("home"))); + for (const JointRow &row : m_joints) { + row.slider->setEnabled(canAdjust() || canEditLocalInputs()); + row.value->setEnabled(canAdjust() || canEditLocalInputs()); + } + const bool localIdle = onControlPage() && !m_activeToken && !m_cancelToken + && !m_jointClient->isBusy() && !m_needState; + const bool profileReady = localIdle && m_metadataValid && localScopeMatches(); + const bool selected = m_localExpressions.contains(m_localList->currentData().toString()); + QString localError; + const bool targetsValid = selected && validateLocalTargets( + m_localExpressions.value(m_localList->currentData().toString()).value(QStringLiteral("targets")).toList(), &localError); + m_localList->setEnabled(localIdle && m_libraryValid); + m_localName->setEnabled(localIdle); + m_localTransition->setEnabled(localIdle); + m_localEdit->setEnabled(profileReady); + m_localLoad->setEnabled(profileReady && targetsValid); + m_localCapture->setEnabled(profileReady && m_libraryValid); + m_localUpdate->setEnabled(profileReady && selected && m_libraryValid); + m_localDelete->setEnabled(localIdle && selected && m_libraryValid); + m_localPlay->setEnabled(idle && m_metadataValid && localScopeMatches() && m_headConnected && !m_stateReadFailed + && m_baselineReady && targetsValid && m_libraryValid); + m_localPlay->setToolTip(targetsValid ? QStringLiteral("执行所选本地表情;不会上传或覆盖设备预设。") : localError); + if (m_stateReadFailed) { + m_profileStatus->setText(m_metadataValid + ? QStringLiteral("状态未刷新:沿用上次配置供本地编辑和保存;设备目标待刷新,真实控制已暂停。") + : QStringLiteral("状态读取未成功,尚无已验证配置;本地表情库仍可浏览和删除。")); + } + m_baselineStatus->setText(m_stateReadFailed + ? QStringLiteral("状态读取未成功;请先手动刷新,再决定是否执行。") + : m_baselineReady + ? QStringLiteral("预设基线已就绪,可执行所选表情。") + : QStringLiteral("预设基线未就绪:请显式点击“归位并准备预设”。不会自动归位。")); } -void BioHeadWidget::invoke(const QString &action) +void BioHeadWidget::hideEvent(QHideEvent *event) { - if (!m_connected || !m_pendingMethod.isEmpty()) return; - const QString device = m_device->currentData().toString(); - const QString method = BioHeadOperations::method(action); - if (device.isEmpty() || method.isEmpty()) return; - m_pendingMethod = method; - m_pendingAction = action; - m_pendingDevice = device; - m_status->setText(QStringLiteral("正在请求 %1 · %2…").arg(device, action)); - refreshControls(); - const QJsonObject request{{QStringLiteral("header"), - QJsonObject{{QStringLiteral("deviceId"), device}}}}; - m_client->requestRpc(QStringLiteral("cmvr.api.BioHeadService"), method, - QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)), device); + resetInteraction(QStringLiteral("已离开调试页,待发送目标已清除。"), false, true); + QWidget::hideEvent(event); } -void BioHeadWidget::addFeedback(bool success, const QString &message) +void BioHeadWidget::showEvent(QShowEvent *event) +{ + QWidget::showEvent(event); + requestState(); + refreshControls(); +} + +void BioHeadWidget::addFeedback(bool success, const QString &message, bool acknowledged) { m_history->addItem(QStringLiteral("%1 %2 %3") .arg(QDateTime::currentDateTime().toString(QStringLiteral("HH:mm:ss")), - success ? QStringLiteral("✓") : QStringLiteral("✕"), message)); + success ? (acknowledged ? QStringLiteral("ACK") : QStringLiteral("本地")) + : (acknowledged ? QStringLiteral("失败 / 未知") : QStringLiteral("失败")), message)); while (m_history->count() > 200) delete m_history->takeItem(0); m_history->scrollToBottom(); emit statusMessage(success ? QStringLiteral("OK") : QStringLiteral("ERROR"), message); } + +bool BioHeadWidget::localScopeMatches() const +{ + return !m_libraryEndpoint.isEmpty() && !m_libraryDevice.isEmpty() + && m_libraryEndpoint == m_jointClient->endpointKey() + && m_libraryDevice == m_device->currentData().toString(); +} + +bool BioHeadWidget::canEditLocalInputs() const +{ + return onControlPage() && m_expressionTabs->currentIndex() == 1 && m_localEditing + && m_metadataValid && localScopeMatches() && !m_activeToken && !m_cancelToken + && !m_jointClient->isBusy(); +} + +QVariantList BioHeadWidget::inputTargets() const +{ + QVariantList targets; + for (const JointRow &row : m_joints) + targets.append(QVariantMap{{QStringLiteral("id"), row.id}, + {QStringLiteral("positionRad"), row.value->value()}}); + return targets; +} + +bool BioHeadWidget::validateLocalTargets(const QVariantList &targets, QString *error) const +{ + auto fail = [&](const QString &message) { if (error) *error = message; return false; }; + if (!m_metadataValid || m_joints.isEmpty()) return fail(QStringLiteral("请先读取当前设备有效配置。")); + if (!localScopeMatches()) return fail(QStringLiteral("本地表情不属于当前服务和设备。")); + if (targets.size() != m_joints.size()) return fail(QStringLiteral("表情通道与当前设备配置不一致,不能执行或载入。")); + QSet seen; + for (const QVariant &value : targets) { + const QVariantMap target = value.toMap(); + const QString id = target.value(QStringLiteral("id")).toString(); + double position; + if (!m_joints.contains(id) || seen.contains(id) + || !finiteNumber(target, QStringLiteral("positionRad"), &position)) + return fail(QStringLiteral("本地表情含未知、重复或无效通道目标。")); + const JointRow row = m_joints.value(id); + if (position < row.minimum || position > row.maximum) + return fail(QStringLiteral("%1 目标超出当前设备范围,不能执行或载入。").arg(jointName(id))); + seen.insert(id); + } + return true; +} + +void BioHeadWidget::reloadLocalExpressions(const QString &selectedId) +{ + const QString endpoint = m_jointClient->endpointKey(); + const QString device = m_device->currentData().toString(); + // Retain the last visible local scope when the service/device disappears. + if (!endpoint.isEmpty() && !device.isEmpty()) { + m_libraryEndpoint = endpoint; + m_libraryDevice = device; + } + const QString previous = selectedId.isEmpty() ? m_localList->currentData().toString() : selectedId; + m_localExpressions.clear(); + QSignalBlocker blocker(m_localList); + m_localList->clear(); + if (m_libraryEndpoint.isEmpty() || m_libraryDevice.isEmpty()) { + m_libraryValid = true; + m_localLibraryStatus->setText(QStringLiteral("连接并选择设备后显示对应本地表情库。")); + updateLocalPreview(); + return; + } + QList expressions; + QString error; + m_libraryValid = BioHeadExpressionStore::load(m_storagePath, m_libraryEndpoint, + m_libraryDevice, &expressions, &error); + if (!m_libraryValid) { + m_localLibraryStatus->setText(QStringLiteral("本地表情库读取失败:%1").arg(error)); + m_status->setText(m_localLibraryStatus->text()); + addFeedback(false, m_localLibraryStatus->text(), false); + } else { + for (const auto &entry : expressions) { + m_localExpressions[entry.id] = QVariantMap{{QStringLiteral("id"), entry.id}, + {QStringLiteral("name"), entry.name}, {QStringLiteral("targets"), entry.targets}, + {QStringLiteral("transitionDurationS"), entry.transitionDurationS}}; + m_localList->addItem(entry.name, entry.id); + } + const int index = m_localList->findData(previous); + if (index >= 0) m_localList->setCurrentIndex(index); + m_localLibraryStatus->setText(QStringLiteral("本机库 · %1 · %2 条").arg(m_libraryDevice).arg(expressions.size())); + } + m_localLibraryStatus->setToolTip(QStringLiteral("服务:%1\n设备:%2\n文件:%3") + .arg(m_libraryEndpoint, m_libraryDevice, m_storagePath)); + updateLocalPreview(); +} + +void BioHeadWidget::updateLocalPreview() +{ + const QVariantMap entry = m_localExpressions.value(m_localList->currentData().toString()); + if (entry.isEmpty()) { + m_localPreview->setText(QStringLiteral("当前设备尚无本地表情;可编辑输入后保存新表情。")); + return; + } + { QSignalBlocker nameBlock(m_localName), durationBlock(m_localTransition); + m_localName->setText(entry.value(QStringLiteral("name")).toString()); + m_localTransition->setValue(entry.value(QStringLiteral("transitionDurationS")).toDouble()); } + QStringList targets; + for (const QVariant &value : entry.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = value.toMap(); + targets.append(QStringLiteral("%1 %2 rad").arg(jointName(target.value(QStringLiteral("id")).toString())) + .arg(target.value(QStringLiteral("positionRad")).toDouble(), 0, 'f', 4)); + } + m_localPreview->setText(QStringLiteral("已保存目标(仅预览)\n") + targets.join(QStringLiteral(" · "))); + m_localPreview->setToolTip(QStringLiteral("本地 ID:%1;不发送到设备预设接口。").arg(entry.value(QStringLiteral("id")).toString())); +} + +void BioHeadWidget::enterLocalEditing() +{ + if (!onControlPage() || !m_metadataValid || !localScopeMatches() + || m_activeToken || m_cancelToken || m_jointClient->isBusy()) return; + clearPendingTargets(); + m_needState = false; + m_dispatchTimer->stop(); + m_debugReady = false; + m_localEditing = true; + m_profileStatus->setText(QStringLiteral("本地编辑输入:滑块和数值只修改输入,不发送动作。")); + m_status->setText(QStringLiteral("正在编辑本地输入目标;保存不会发送动作,执行表情才会移动。")); + refreshControls(); +} + +void BioHeadWidget::loadLocalTargets() +{ + const QVariantMap entry = m_localExpressions.value(m_localList->currentData().toString()); + QString error; + if (entry.isEmpty() || !validateLocalTargets(entry.value(QStringLiteral("targets")).toList(), &error)) { + if (error.isEmpty()) error = QStringLiteral("请先选择本地表情。"); + m_status->setText(error); addFeedback(false, error, false); return; + } + enterLocalEditing(); + if (!m_localEditing) return; + for (const QVariant &value : entry.value(QStringLiteral("targets")).toList()) { + const QVariantMap target = value.toMap(); + const JointRow row = m_joints.value(target.value(QStringLiteral("id")).toString()); + const double position = target.value(QStringLiteral("positionRad")).toDouble(); + QSignalBlocker sliderBlock(row.slider), valueBlock(row.value); + row.slider->setValue(qRound(position * sliderScale)); + row.value->setValue(position); + } + const QString message = QStringLiteral("已载入“%1”的输入目标,仅供本地编辑,未发送动作。") + .arg(entry.value(QStringLiteral("name")).toString()); + m_status->setText(message); addFeedback(true, message, false); +} + +void BioHeadWidget::saveLocalExpression(bool replace) +{ + QString error; + const QVariantList targets = inputTargets(); + const QString name = m_localName->text().trimmed(); + const QString selected = m_localList->currentData().toString(); + if (m_activeToken || m_cancelToken || m_jointClient->isBusy()) return; + clearPendingTargets(); + m_debugReady = false; + m_profileStatus->setText(m_localEditing + ? QStringLiteral("本地编辑输入:滑块和数值只修改输入,不发送动作。") + : QStringLiteral("拖动调试已停用;保存只记录当前输入目标。")); + refreshControls(); + if (name.isEmpty() || name.size() > 80) error = QStringLiteral("请输入 1~80 字的表情名称。"); + else if (!validateLocalTargets(targets, &error)) {} + else if (replace && !m_localExpressions.contains(selected)) error = QStringLiteral("请先选择要更新的本地表情。"); + if (!error.isEmpty()) { m_status->setText(error); addFeedback(false, error, false); return; } + BioHeadExpressionStore::Expression entry; + entry.id = replace ? selected : QUuid::createUuid().toString(QUuid::WithoutBraces); + entry.name = name; + entry.targets = targets; + entry.transitionDurationS = m_localTransition->value(); + if (!BioHeadExpressionStore::save(m_storagePath, m_libraryEndpoint, m_libraryDevice, entry, replace, &error)) { + const QString message = QStringLiteral("本地表情%1失败:%2").arg(replace ? QStringLiteral("更新") : QStringLiteral("保存"), error); + m_status->setText(message); addFeedback(false, message, false); return; + } + reloadLocalExpressions(entry.id); + const QString message = QStringLiteral("已%1本地表情“%2”:保存当前输入目标,未发送动作。") + .arg(replace ? QStringLiteral("更新") : QStringLiteral("保存"), name); + m_status->setText(message); addFeedback(true, message, false); refreshControls(); +} + +void BioHeadWidget::deleteLocalExpression() +{ + const QString id = m_localList->currentData().toString(); + if (!m_localExpressions.contains(id) || !m_libraryValid || m_activeToken + || m_cancelToken || m_jointClient->isBusy()) return; + clearPendingTargets(); + m_debugReady = false; + m_profileStatus->setText(m_localEditing + ? QStringLiteral("本地编辑输入:滑块和数值只修改输入,不发送动作。") + : QStringLiteral("拖动调试已停用;删除只修改本地表情库。")); + refreshControls(); + const QString endpoint = m_libraryEndpoint, device = m_libraryDevice; + const QString name = m_localExpressions.value(id).value(QStringLiteral("name")).toString(); + if (AppMessageBox::question(this, QStringLiteral("删除本地表情"), + QStringLiteral("删除本机表情“%1”?此操作不修改设备预设。").arg(name), + AppMessageBox::Yes | AppMessageBox::No, AppMessageBox::No) != AppMessageBox::Yes) return; + if (endpoint != m_libraryEndpoint || device != m_libraryDevice || !m_localExpressions.contains(id)) return; + QString error; + if (!BioHeadExpressionStore::remove(m_storagePath, endpoint, device, id, &error)) { + m_status->setText(QStringLiteral("删除本地表情失败:%1").arg(error)); + addFeedback(false, m_status->text(), false); return; + } + reloadLocalExpressions(); + m_status->setText(QStringLiteral("已删除本机表情“%1”,未向设备发送请求。").arg(name)); + addFeedback(true, m_status->text(), false); refreshControls(); +} + +void BioHeadWidget::executeLocalExpression() +{ + const QVariantMap entry = m_localExpressions.value(m_localList->currentData().toString()); + QString error; + const QVariantList targets = entry.value(QStringLiteral("targets")).toList(); + if (entry.isEmpty() || !validateLocalTargets(targets, &error) || !m_baselineReady) { + if (error.isEmpty()) error = QStringLiteral("预设基线未就绪,请显式归位准备后再执行。"); + m_status->setText(error); addFeedback(false, error, false); return; + } + clearPendingTargets(); + m_debugReady = false; + m_localEditing = false; + beginRequest(QStringLiteral("expression"), {{QStringLiteral("targets"), targets}, + {QStringLiteral("transitionDurationS"), m_localTransition->value()}}); +} diff --git a/src/bioheadwidget.h b/src/bioheadwidget.h index d4e5096..0c14d9e 100644 --- a/src/bioheadwidget.h +++ b/src/bioheadwidget.h @@ -1,40 +1,114 @@ #pragma once -#include +#include +#include +#include #include -#include +#include +#include class RobotClient; +class BioHeadJointClient; class RpcServiceWidget; class QComboBox; +class QDoubleSpinBox; +class QHideEvent; class QLabel; class QListWidget; +class QLineEdit; class QPushButton; +class QShowEvent; +class QSlider; +class QTabWidget; +class QTimer; +class QVBoxLayout; class BioHeadWidget final : public QWidget { Q_OBJECT public: - explicit BioHeadWidget(RobotClient *client, QWidget *parent = nullptr); + explicit BioHeadWidget(RobotClient *client, QWidget *parent = nullptr, + const QString &storagePath = QString()); void setDeviceId(const QString &deviceId); void setAvailableDevices(const QVariantList &devices); signals: void statusMessage(const QString &level, const QString &message); +protected: + void hideEvent(QHideEvent *event) override; + void showEvent(QShowEvent *event) override; + private: - void invoke(const QString &action); + struct JointRow { + QString id; + double minimum = 0, maximum = 0, home = 0; + QSlider *slider = nullptr; + QDoubleSpinBox *value = nullptr; + QLabel *confirmed = nullptr; + }; + bool onControlPage() const; + bool canAdjust() const; + bool dragging() const; + void changeDeviceContext(); + void resetInteraction(const QString &message, bool clearMetadata, bool cancelTransport); + void clearPendingTargets(); + void clearMetadata(); + void requestState(); + void beginRequest(const QString &operation, const QVariantMap ¶meters = {}); + void finishRequest(quint64 token, const QString &device, const QString &operation, + quint64 generation, bool success, const QVariantMap &data, + const QString &detail); + bool installState(const QVariantMap &state, QString *error); + void rebuildRows(const QVariantList &jointInfo); + void queueTarget(const QString &id, double value); + void advanceRequests(); + void updatePresetPreview(); + void reloadLocalExpressions(const QString &selectedId = QString()); + void updateLocalPreview(); + bool validateLocalTargets(const QVariantList &targets, QString *error) const; + QVariantList inputTargets() const; + bool localScopeMatches() const; + bool canEditLocalInputs() const; + void enterLocalEditing(); + void loadLocalTargets(); + void saveLocalExpression(bool replace); + void deleteLocalExpression(); + void executeLocalExpression(); void refreshControls(); - void addFeedback(bool success, const QString &message); + void addFeedback(bool success, const QString &message, bool acknowledged = true); RobotClient *m_client; + BioHeadJointClient *m_jointClient; RpcServiceWidget *m_rpc; - QComboBox *m_device; - QLabel *m_status; + QTabWidget *m_tabs; + QTabWidget *m_expressionTabs; + QComboBox *m_device, *m_presets; + QComboBox *m_localList; + QLineEdit *m_localName; + QDoubleSpinBox *m_transition; + QDoubleSpinBox *m_localTransition; + QLabel *m_status, *m_profileStatus, *m_baselineStatus, *m_presetPreview; + QLabel *m_localPreview, *m_localLibraryStatus; QListWidget *m_history; - QList m_buttons; - bool m_connected = false; - QString m_pendingMethod; - QString m_pendingAction; - QString m_pendingDevice; + QPushButton *m_refresh, *m_reconnect, *m_enableDebug, *m_home, *m_play, *m_cancel; + QPushButton *m_localEdit, *m_localCapture, *m_localUpdate, *m_localDelete, *m_localLoad, *m_localPlay; + QVBoxLayout *m_rows; + QTimer *m_dispatchTimer; + QMap m_joints; + QMap m_expressions; + QMap m_localExpressions; + QMap m_pendingTargets, m_confirmedTargets; + QStringList m_pendingOrder, m_editedSliders; + QByteArray m_profileSignature; + QString m_storagePath, m_libraryEndpoint, m_libraryDevice; + bool m_libraryValid = true, m_localEditing = false, m_modeMayEnable = false; + bool m_connected = false, m_headConnected = false, m_metadataValid = false; + bool m_stateReadFailed = false; + bool m_debugReady = false, m_baselineReady = false, m_needState = false; + bool m_resetting = false; + quint64 m_nextToken = 0, m_activeToken = 0, m_activeGeneration = 0; + quint64 m_cancelToken = 0, m_cancelGeneration = 0, m_observedGeneration = 0; + QString m_activeDevice, m_activeOperation, m_activeJoint; + double m_activeTarget = 0; }; diff --git a/tests/application_shell_test.cpp b/tests/application_shell_test.cpp index 813a936..85877bf 100644 --- a/tests/application_shell_test.cpp +++ b/tests/application_shell_test.cpp @@ -4,6 +4,7 @@ #include "taskorchestrationwidget.h" #include "bioheadoperations.h" #include "bioheadwidget.h" +#include "bioheadjointclient.h" #include "robotclient.h" #include "motordebugwidget.h" #include "motorplot.h" @@ -42,6 +43,7 @@ #include #include #include +#include #ifdef CMVR_WITH_GRPC #include #include "cmvr/api/arm_service.grpc.pb.h" @@ -562,8 +564,9 @@ struct TaskFlowTestAccess static bool verifyBioheadPage() { RobotClient client; - // Prevent any dispatch to the real worker; inspect requests and inject replies. - QObject::disconnect(&client, &RobotClient::rpcRequested, nullptr, nullptr); + // Exercise the dedicated USB-head demo session without any hardware connection. + QObject::disconnect(&client, &RobotClient::connectRequested, nullptr, nullptr); + QObject::disconnect(&client, &RobotClient::disconnectRequested, nullptr, nullptr); BioHeadWidget page(&client); page.resize(1250, 850); page.show(); @@ -571,38 +574,37 @@ static bool verifyBioheadPage() auto *status = page.findChild(QStringLiteral("bioheadStatus")); auto *tabs = page.findChild(); if (!devices || !status || !tabs || tabs->count() != 2) return false; - QPushButton *happy = nullptr; - int count = 0; + auto *session = page.findChild(); + auto *enable = page.findChild(QStringLiteral("bioheadEnableDebugButton")); + auto *presets = page.findChild(QStringLiteral("bioheadPresetCombo")); + if (!session || !enable || !presets || enable->isEnabled()) return false; for (auto *button : page.findChildren()) { - if (button->property("bioheadAction").isValid()) { - ++count; - if (button->isEnabled()) return false; - if (button->property("bioheadAction") == QStringLiteral("高兴")) happy = button; - } + if (button->text().contains(QStringLiteral("说话")) || + button->text().contains(QStringLiteral("紧急停止"))) return false; } - if (count != 10 || !happy) return false; - const QVariantList list{QVariantMap{{"deviceId", "bio_head"}, {"type", 8}}, + int mutations = 0; + QObject::connect(session, &BioHeadJointClient::requestStarted, &page, + [&](quint64, const QString &, const QString &operation, const QVariantMap &, quint64) { + if (operation != QStringLiteral("state")) ++mutations; + }); + const QVariantList list{QVariantMap{{"deviceId", "usb_head"}, {"type", 8}}, QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}}}; - page.setAvailableDevices(list); + emit client.connectRequested(QStringLiteral("demo"), 50053, true); emit client.connectionChanged(true, 0, QString()); - if (devices->count() != 1 || !happy->isEnabled()) return false; - bool dispatched = false; - QObject::connect(&client, &RobotClient::rpcRequested, &page, - [&](const QString &service, const QString &method, const QString &json, const QString &id) { - dispatched = service == QStringLiteral("cmvr.api.BioHeadService") && method == QStringLiteral("Happy") - && id == QStringLiteral("bio_head") && QJsonDocument::fromJson(json.toUtf8()).object() - .value(QStringLiteral("header")).toObject().value(QStringLiteral("deviceId")).toString() == id; - }); - happy->click(); - if (!dispatched || happy->isEnabled()) return false; - emit client.rpcFinished(QStringLiteral("cmvr.api.BioHeadService"), QStringLiteral("Happy"), true, - QStringLiteral("{\"header\":{\"errorMessage\":\"device rejected\"}}")); - if (!happy->isEnabled() || !status->text().contains(QStringLiteral("device rejected"))) return false; page.setAvailableDevices(list); - if (!status->text().contains(QStringLiteral("device rejected"))) return false; + if (!waitFor([&] { return enable->isEnabled() && presets->count() == 6; }) || + devices->count() != 1 || mutations) return false; + enable->click(); + if (!waitFor([&] { + auto *slider = page.findChild(QStringLiteral("bioheadServoSlider_eye_l_up")); + return slider && slider->isEnabled(); + }) || mutations != 1) return false; + const QString feedback = status->text(); + page.setAvailableDevices(list); + if (status->text() != feedback || mutations != 1) return false; page.grab().save(QStringLiteral("biohead-page.png")); emit client.connectionChanged(false, 0, QString()); - if (happy->isEnabled()) return false; + if (enable->isEnabled()) return false; return true; } diff --git a/tests/bioheadexpressionstore_test.cpp b/tests/bioheadexpressionstore_test.cpp new file mode 100644 index 0000000..a057861 --- /dev/null +++ b/tests/bioheadexpressionstore_test.cpp @@ -0,0 +1,194 @@ +#include "bioheadexpressionstore.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace BioHeadExpressionStore; +const QString real = QStringLiteral("real|192.168.0.234:50051"); +const QString demo = QStringLiteral("demo|192.168.0.234:50051"); +const QString device = QStringLiteral("usb_head"); + +void check(bool value, const char *message) +{ + if (!value) throw std::runtime_error(message); +} + +QByteArray contents(const QString &path) +{ + QFile file(path); check(file.open(QIODevice::ReadOnly), "fixture file can be read"); + return file.readAll(); +} + +void fixture(const QString &path, const QByteArray &bytes) +{ + QFile file(path); check(file.open(QIODevice::WriteOnly | QIODevice::Truncate), "fixture file can be written"); + check(file.write(bytes) == bytes.size(), "fixture write is complete"); +} + +Expression expression(const QString &name = QStringLiteral("微笑")) +{ + return {QUuid::createUuid().toString(QUuid::WithoutBraces), name, + {QVariantMap{{QStringLiteral("id"), QStringLiteral("eye_l_up")}, {QStringLiteral("positionRad"), 0.0}}, + QVariantMap{{QStringLiteral("id"), QStringLiteral("pwm8_local")}, {QStringLiteral("positionRad"), -.123456789012345}}}, .7}; +} + +QList list(const QString &path, const QString &endpoint = real, const QString &id = device) +{ + QList result; QString error; + check(load(path, endpoint, id, &result, &error), "stored expressions reload successfully"); + check(error.isEmpty(), "successful operations clear previous error text"); + return result; +} + +void lifecycleAndIsolation(const QString &path) +{ + QString error; + check(list(path).isEmpty() && !QFile::exists(path), "a missing file is an empty library without creating a file"); + Expression first = expression(); + check(save(path, real, device, first, false, &error), "new local expression is persisted"); + auto reloaded = list(path); + check(reloaded.size() == 1 && reloaded[0].id == first.id && reloaded[0].name == first.name, + "fresh loads retain IDs and Chinese names without process memory state"); + check(reloaded[0].targets[0].toMap().value("positionRad").toDouble() == 0. + && reloaded[0].targets[1].toMap().value("positionRad").toDouble() == -.123456789012345 + && reloaded[0].transitionDurationS == .7, "explicit zero and double precision survive JSON round trips"); + QByteArray original = contents(path); + Expression sameName = expression(); + check(!save(path, real, device, sameName, false, &error) && !error.isEmpty() + && contents(path) == original, "same-scope duplicate names cannot overwrite the library"); + check(!save(path, real, device, first, false, &error) && contents(path) == original, + "create cannot silently replace an existing UUID"); + check(!save(path, real, device, expression(QStringLiteral("不存在")), true, &error) + && contents(path) == original, "replace requires an existing local UUID"); + first.name = QStringLiteral("眨眼"); first.transitionDurationS = 1.25; + first.targets[0] = QVariantMap{{"id", "eye_l_up"}, {"positionRad", .21}}; + check(save(path, real, device, first, true, &error) && list(path)[0].name == first.name + && list(path)[0].transitionDurationS == 1.25, "replace persists new name, targets and duration"); + const Expression alternate = expression(first.name); + check(save(path, QStringLiteral("real|192.168.0.235:50051"), device, alternate, false, &error) + && save(path, real, QStringLiteral("other_head"), alternate, false, &error) + && save(path, demo, device, alternate, false, &error), "endpoint, device and demo scopes are independent"); + check(list(path).size() == 1 && list(path, demo)[0].id == alternate.id + && list(path, real, "other_head")[0].id == alternate.id, "scope lookups never mix expression records"); + check(remove(path, real, device, first.id, &error) && list(path).isEmpty() + && list(path, demo).size() == 1 && list(path, real, "other_head").size() == 1, + "deleting one local expression preserves all other scopes"); + check(!remove(path, real, device, first.id, &error), "delete requires an existing record"); + std::puts("PASS local add/replace/delete/reload, exact numeric values and endpoint/device/demo isolation"); +} + +void invalidInputs(const QString &path) +{ + QString error; + const Expression valid = expression(); + check(save(path, real, device, valid, false, &error), "validation fixture is saved"); + const QByteArray original = contents(path); + QList bad; + Expression value = expression(); value.id = QStringLiteral("ad8f669a78d54d30a2356512b0802c1d"); bad.append(value); + value = expression(); value.name = QStringLiteral(" 前导空格"); bad.append(value); + value = expression(); value.name = QString(81, 'x'); bad.append(value); + value = expression(); value.transitionDurationS = std::numeric_limits::infinity(); bad.append(value); + value = expression(); value.transitionDurationS = .1; bad.append(value); + value = expression(); value.targets.clear(); bad.append(value); + value = expression(); value.targets.append(value.targets[0]); bad.append(value); + value = expression(); value.targets[0] = QVariantMap{{"id", "eye_l_up"}, {"positionRad", true}}; bad.append(value); + value = expression(); value.targets[0] = QVariantMap{{"id", "eye_l_up"}, {"positionRad", "0.0"}}; bad.append(value); + value = expression(); value.targets[0] = QVariantMap{{"id", "eye_l_up"}, {"positionRad", std::numeric_limits::quiet_NaN()}}; bad.append(value); + value = expression(); value.targets.clear(); + for (int i = 0; i < 65; ++i) value.targets.append(QVariantMap{{"id", QString::number(i)}, {"positionRad", 0.}}); + bad.append(value); + for (const Expression &invalid : bad) + check(!save(path, real, device, invalid, false, &error) && !error.isEmpty() && contents(path) == original, + "malformed input must fail clearly and preserve the original file"); + check(!save(path, "", device, expression(), false, &error) && contents(path) == original, + "missing routing scope never creates a shared fallback profile"); + std::puts("PASS local UUID/name/count/duplicate/finite-number/duration validation preserves existing data"); +} + +void corruptFilesAndFailedWrites(const QString &path, const QString &directory) +{ + QString error; + const Expression valid = expression(); + check(save(path, real, device, valid, false, &error), "corruption fixture is saved"); + const QJsonObject good = QJsonDocument::fromJson(contents(path)).object(); + QList damaged{QByteArray("{broken json")}; + QJsonObject object = good; object.insert("version", 2); + damaged.append(QJsonDocument(object).toJson()); + object = good; QJsonArray scopes = object.value("scopes").toArray(); scopes.append(scopes[0]); + object.insert("scopes", scopes); damaged.append(QJsonDocument(object).toJson()); + for (int fault = 0; fault < 3; ++fault) { + object = good; scopes = object.value("scopes").toArray(); QJsonObject scope = scopes[0].toObject(); + QJsonArray records = scope.value("expressions").toArray(); QJsonObject record = records[0].toObject(); + if (fault == 0) records.append(records[0]); + else if (fault == 1) { + QJsonArray targets = record.value("targets").toArray(); targets.append(targets[0]); + record.insert("targets", targets); records[0] = record; + } else { + QJsonArray targets = record.value("targets").toArray(); QJsonObject target = targets[0].toObject(); + target.insert("positionRad", "0"); targets[0] = target; record.insert("targets", targets); records[0] = record; + } + scope.insert("expressions", records); scopes[0] = scope; object.insert("scopes", scopes); + damaged.append(QJsonDocument(object).toJson()); + } + damaged.append(QByteArray(8 * 1024 * 1024 + 1, ' ')); + for (const QByteArray &bytes : damaged) { + fixture(path, bytes); QList unchanged{valid}; + check(!load(path, real, device, &unchanged, &error) && !error.isEmpty() + && unchanged.size() == 1 && unchanged[0].id == valid.id, "failed load leaves caller data intact"); + check(!save(path, real, device, expression(), false, &error) && contents(path) == bytes, + "corrupt, duplicate, unsupported-version and oversized files are never replaced"); + check(!remove(path, real, device, valid.id, &error) && contents(path) == bytes, + "delete cannot rewrite a damaged library either"); + } + fixture(path, QJsonDocument(good).toJson()); + const QByteArray original = contents(path); + { + QLockFile competing(path + ".lock"); check(competing.tryLock(0), "fixture holds a competing instance lock"); + QElapsedTimer elapsed; elapsed.start(); + check(!save(path, real, device, expression("忙碌"), false, &error) && elapsed.elapsed() < 1500 + && contents(path) == original, "competing writes fail promptly and preserve the valid library"); + } + const QString blocker = QDir(directory).filePath("file_not_directory"); fixture(blocker, "do not replace"); + check(!save(QDir(blocker).filePath("expressions.json"), real, device, expression(), false, &error) + && !error.isEmpty() && contents(blocker) == "do not replace", "unwritable destination never reports success or destroys an existing file"); +#ifdef Q_OS_WIN + const QFile::Permissions permissions = QFile::permissions(path); + check(QFile::setPermissions(path, QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup | QFile::ReadOther), + "existing library can be made read-only for an actual atomic-write failure"); + const bool written = save(path, real, device, expression(QStringLiteral("只读失败")), false, &error); + const QByteArray afterWrite = contents(path); + check(QFile::setPermissions(path, permissions), "test restores original library permissions"); + check(!written && !error.isEmpty() && afterWrite == original, + "QSaveFile failure on a read-only destination is reported without changing the original library"); +#endif + std::puts("PASS corruption/schema/duplicate/size refusal, bounded instance lock and failed-write preservation"); +} +} // namespace + +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + try { + QTemporaryDir temporary; check(temporary.isValid(), "temporary test directory exists"); + check(defaultPath().endsWith("/data/biohead_expressions.json"), "default path is explicit executable-relative data file"); + lifecycleAndIsolation(temporary.filePath("lifecycle.json")); + invalidInputs(temporary.filePath("validation.json")); + corruptFilesAndFailedWrites(temporary.filePath("damaged.json"), temporary.path()); + std::puts("PASS BioHead local expression store; QtCore temporary files only, no RPC or hardware"); + return 0; + } catch (const std::exception &error) { + std::fprintf(stderr, "FAIL BioHead expression store: %s\n", error.what()); return 1; + } +} diff --git a/tests/bioheadjointclient_test.cpp b/tests/bioheadjointclient_test.cpp new file mode 100644 index 0000000..a8fd9b5 --- /dev/null +++ b/tests/bioheadjointclient_test.cpp @@ -0,0 +1,675 @@ +// Actual gRPC transport against a loopback-only fake. No robot connection exists. +#include "bioheadjointclient.h" +#include "robotclient.h" +#include "cmvr/api/biohead_service.grpc.pb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void check(bool value, const char *message) +{ + if (!value) throw std::runtime_error(message); +} +bool waitFor(const std::function &ready, int timeout = 6000) +{ + QElapsedTimer elapsed; elapsed.start(); + while (!ready() && elapsed.elapsed() < timeout) { + QCoreApplication::processEvents(); QThread::msleep(2); + } + return ready(); +} +void pump(int milliseconds = 80) +{ + QElapsedTimer elapsed; elapsed.start(); + while (elapsed.elapsed() < milliseconds) { + QCoreApplication::processEvents(); QThread::msleep(2); + } +} + +const char *jointIds[] = {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}; +const double minima[] = {-1., -.35, -1.5, -.65, -1.5}; +const double maxima[] = {1., .55, 1., .70, .393}; +const char *neutralId = "0de8a527543e423abab593484926dd1c"; +const char *smileId = "ad8f669a78d54d30a2356512b0802c1d"; + +class FakeHead final : public cmvr::api::BioHeadService::Service +{ +public: + enum Result { Acknowledge, Reject, MissingSuccess, Timeout }; + std::atomic states{0}, controls{0}, plays{0}, expressions{0}, cancels{0}; + std::atomic holdState{false}, holdControl{false}, holdPlay{false}, holdExpression{false}; + std::atomic playEntered{false}, playCanceled{false}; + std::atomic expressionEntered{false}, expressionCanceled{false}, baseline{true}; + std::atomic expressionDeadlineMs{0}; + std::atomic nextControl{Acknowledge}, nextExpression{Acknowledge}; + std::atomic nextStateOutcome{Acknowledge}; + std::atomic nextStateDelayMs{0}, stateDeadlineMs{0}, stateValidityMs{0}; + // Malformed metadata must invalidate a previously usable configuration. + std::atomic nextStateFault{0}; + + grpc::Status GetHeadJointState(grpc::ServerContext *context, + const cmvr::api::GetHeadJointStateCommand::Request *request, + cmvr::api::GetHeadJointStateCommand::Feedback *response) override + { + ++states; + { std::lock_guard guard(mutex); stateDevices.push_back(request->header().device_id()); + statePeers.push_back(context->peer()); } + stateValidityMs.store(static_cast(request->header().valid_for_ms())); + stateDeadlineMs.store(static_cast(std::chrono::duration_cast( + context->deadline() - std::chrono::system_clock::now()).count())); + const auto ready = std::chrono::steady_clock::now() + + std::chrono::milliseconds(nextStateDelayMs.exchange(0)); + while (std::chrono::steady_clock::now() < ready && !context->IsCancelled()) + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + while (holdState.load() && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + if (context->IsCancelled()) return {grpc::StatusCode::CANCELLED, "fake state canceled"}; + const Result outcome = nextStateOutcome.exchange(Acknowledge); + if (outcome == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake state read deadline"}; + if (outcome == Reject) { + response->mutable_header()->set_success(false); + response->mutable_header()->set_error_message("fixture state unavailable"); + return grpc::Status::OK; + } + if (outcome == MissingSuccess) return grpc::Status::OK; + response->mutable_header()->set_success(true); + response->set_connected(true); + response->set_position_feedback_available(false); + response->set_hardware_emergency_stop_available(false); + response->set_expression_baseline_ready(baseline.load()); + response->set_last_command_outcome(cmvr::api::HEAD_JOINT_COMMAND_ACKNOWLEDGED); + for (int index = 0; index < 5; ++index) { + auto *info = response->add_joint_info(); + info->set_id(jointIds[index]); info->set_min_position_rad(minima[index]); + info->set_max_position_rad(maxima[index]); info->set_home_position_rad(index == 4 ? -1. : 0.); + auto *target = response->add_targets(); target->set_id(jointIds[index]); + target->set_target_position_rad(index == 4 ? -1. : 0.); target->set_target_valid(true); + } + for (int preset = 0; preset < 2; ++preset) { + auto *expression = response->add_expressions(); + expression->set_expression_id(preset ? smileId : neutralId); + expression->set_expression_name(preset ? "微笑" : "中立"); + for (int index = 0; index < 5; ++index) { + auto *target = expression->add_targets(); target->set_id(jointIds[index]); + target->set_position_rad(index == 4 ? -1. : (preset ? .2 : 0.)); + } + } + switch (nextStateFault.exchange(0)) { + case 1: response->mutable_joint_info(1)->set_id(jointIds[0]); break; + case 2: response->mutable_joint_info(0)->set_max_position_rad(minima[0]); break; + case 3: response->mutable_expressions(0)->mutable_targets()->RemoveLast(); break; + default: break; + } + return grpc::Status::OK; + } + + grpc::Status ControlHeadJoints(grpc::ServerContext *context, + const cmvr::api::HeadJointCommand::Request *request, + cmvr::api::HeadJointCommand::Feedback *response) override + { + ++controls; + { std::lock_guard guard(mutex); controlRequests.push_back(*request); } + if (request->has_cancel_expression()) { + ++cancels; response->mutable_header()->set_success(true); return grpc::Status::OK; + } + const Result result = nextControl.exchange(Acknowledge); + while (holdControl.load() && !context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + if (context->IsCancelled()) return {grpc::StatusCode::CANCELLED, "fake control canceled"}; + if (result == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake write outcome unknown"}; + if (result == Reject) { + response->mutable_header()->set_success(false); + response->mutable_header()->set_error_message("fixture firmware rejected command"); + } else if (result == Acknowledge) response->mutable_header()->set_success(true); + return grpc::Status::OK; + } + + grpc::Status PlayHeadExpression(grpc::ServerContext *context, + const cmvr::api::PlayHeadExpressionCommand::Request *request, + cmvr::api::PlayHeadExpressionCommand::Feedback *response) override + { + ++plays; + { std::lock_guard guard(mutex); playRequests.push_back(*request); } + playEntered.store(true); + while (holdPlay.load() && !context->IsCancelled() && cancels.load() == 0) + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + if (context->IsCancelled()) { + playCanceled.store(true); return {grpc::StatusCode::CANCELLED, "fake expression canceled"}; + } + response->mutable_header()->set_success(true); + response->set_expression_id(request->expression_id()); + response->set_expression_name("微笑"); + return grpc::Status::OK; + } + + grpc::Status SetHeadExpression(grpc::ServerContext *context, + const cmvr::api::SetHeadExpressionCommand::Request *request, + cmvr::api::SetHeadExpressionCommand::Feedback *response) override + { + ++expressions; + { std::lock_guard guard(mutex); expressionRequests.push_back(*request); } + expressionDeadlineMs.store(static_cast(std::chrono::duration_cast( + context->deadline() - std::chrono::system_clock::now()).count())); + expressionEntered.store(true); + const Result result = nextExpression.exchange(Acknowledge); + while (holdExpression.load() && !context->IsCancelled()) + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + if (context->IsCancelled()) { + expressionCanceled.store(true); + return {grpc::StatusCode::CANCELLED, "fake custom expression canceled"}; + } + if (result == Timeout) return {grpc::StatusCode::DEADLINE_EXCEEDED, "fake custom expression outcome unknown"}; + if (result == Reject) { + response->mutable_header()->set_success(false); + response->mutable_header()->set_error_message("fixture rejected custom expression"); + } else if (result == Acknowledge) response->mutable_header()->set_success(true); + return grpc::Status::OK; + } + + cmvr::api::HeadJointCommand::Request control(int index = -1) + { + std::lock_guard guard(mutex); + check(!controlRequests.empty(), "a control request was actually received"); + return controlRequests.at(index < 0 ? controlRequests.size() - 1 : size_t(index)); + } + cmvr::api::PlayHeadExpressionCommand::Request play() + { + std::lock_guard guard(mutex); + check(!playRequests.empty(), "a preset request was actually received"); return playRequests.back(); + } + cmvr::api::SetHeadExpressionCommand::Request expression() + { + std::lock_guard guard(mutex); + check(!expressionRequests.empty(), "a custom expression request was actually received"); + return expressionRequests.back(); + } + bool oneStatePeer() + { + std::lock_guard guard(mutex); + if (statePeers.empty() || statePeers.front().empty()) return false; + for (const auto &peer : statePeers) if (peer != statePeers.front()) return false; + return true; + } +private: + std::mutex mutex; + std::vector stateDevices; + std::vector statePeers; + std::vector controlRequests; + std::vector playRequests; + std::vector expressionRequests; +}; + +struct Reply { + quint64 token; QString device, operation; quint64 generation; + bool success; QVariantMap data; QString detail; +}; + +class Harness +{ +public: + FakeHead fake; + std::unique_ptr server; + RobotClient robot; + std::unique_ptr client; + std::vector replies; + int started = 0, port = 0; + quint64 token = 0; + + Harness() + { + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(&fake); server = builder.BuildAndStart(); + check(server && port > 0, "only an ephemeral loopback fake can be used"); + // Detach the normal backend worker. These endpoint/lifecycle signals are + // consumed only by the dedicated head client constructed afterwards. + QObject::disconnect(&robot, nullptr, nullptr, nullptr); + client.reset(new BioHeadJointClient(&robot)); + QObject::connect(client.get(), &BioHeadJointClient::requestStarted, + [&](quint64, const QString &, const QString &, const QVariantMap &, quint64) { ++started; }); + QObject::connect(client.get(), &BioHeadJointClient::requestFinished, + [&](quint64 id, const QString &device, const QString &operation, quint64 generation, + bool success, const QVariantMap &data, const QString &detail) { + replies.push_back({id, device, operation, generation, success, data, detail}); + }); + client->setDeviceId("usb_head"); + robot.connectRequested("127.0.0.1", port, false); + robot.connectionChanged(true, 0, {}); + check(client->isConnected(), "head transport observes the current endpoint and connection"); + } + ~Harness() + { + client.reset(); server->Shutdown(); server->Wait(); + } + quint64 send(const QString &operation, const QVariantMap ¶meters = {}) + { + client->request(++token, operation, parameters); return token; + } + Reply await(quint64 id) + { + check(waitFor([&] { for (const auto &reply : replies) if (reply.token == id) return true; return false; }, 8000), + "head RPC produced a bounded completion callback"); + for (const auto &reply : replies) if (reply.token == id) return reply; + throw std::runtime_error("unreachable callback lookup"); + } + Reply call(const QString &operation, const QVariantMap ¶meters = {}) { return await(send(operation, parameters)); } + void state() + { + const Reply reply = call("state"); check(reply.success, "configured metadata read succeeds"); + check(reply.data.value("jointInfo").toList().size() == 5 && reply.data.value("expressions").toList().size() == 2, + "five real channel IDs and server-defined presets reach the UI data contract"); + check(!reply.data.value("positionFeedbackAvailable").toBool() + && !reply.data.value("hardwareEmergencyStopAvailable").toBool(), + "cached targets must not be advertised as physical feedback or hardware emergency stop"); + } +}; + +void metadataAndExactWireValues() +{ + Harness h; pump(); + check(h.fake.controls == 0 && h.fake.plays == 0, "constructing/connecting never homes or moves the head"); + h.state(); check(h.fake.controls == 0 && h.fake.plays == 0, "metadata reads never send positions"); + const auto moved = h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.0}}); + check(moved.success, "one explicit servo write is acknowledged"); + const auto wire = h.fake.control(); + check(wire.has_move() && wire.move().targets_size() == 1, "one slider sends exactly one target"); + check(wire.move().targets(0).id() == "eye_l_up" && wire.move().targets(0).has_position_rad() + && wire.move().targets(0).position_rad() == 0., "explicit zero survives the protobuf target oneof"); + check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty(), + "device routing and a unique command ID reach the actual gRPC server"); + check(h.call("mode", {{"mode", 0}}).success, "explicit IMMEDIATE mode is accepted"); + const auto mode = h.fake.control(); + check(mode.has_mode() && mode.mode().has_mode() && mode.mode().mode() == cmvr::api::HEAD_JOINT_MOTION_IMMEDIATE, + "explicit enum zero survives the protobuf mode oneof"); + check(h.call("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}).success, + "a configured preset is acknowledged"); + const auto preset = h.fake.play(); + check(preset.has_expression_id() && preset.expression_id() == smileId + && std::abs(preset.transition_duration_s() - .7) < 1e-12, + "the exact configured preset ID and transition duration reach the wire"); + std::puts("PASS metadata/no automatic motion, single-target and explicit zero/mode/preset protobuf fields"); +} + +void validationAndNegativeFeedback() +{ + Harness h; + check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success + && h.fake.controls == 0, "motion is blocked until channel metadata is known"); + h.state(); const int before = h.fake.controls; + for (const auto ¶meters : {QVariantMap{{"id", "unknown_joint"}, {"positionRad", 0.}}, + QVariantMap{{"id", "eye_l_up"}, {"positionRad", 1.1}}, + QVariantMap{{"id", "eye_l_up"}, {"positionRad", std::numeric_limits::quiet_NaN()}}}) + check(!h.call("move", parameters).success, "unknown/out-of-range/nonfinite local servo input is rejected"); + check(h.fake.controls == before, "invalid inputs never reach the server"); + check(!h.call("play", {{"expressionId", "not_configured"}, {"transitionDurationS", .7}}).success + && !h.call("play", {{"expressionId", smileId}, {"transitionDurationS", 0.}}).success + && h.fake.plays == 0, "unknown presets and invalid durations never reach the server"); + for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { + h.fake.nextControl.store(result); + const auto reply = h.call("move", {{"id", "eye_l_up"}, {"positionRad", .2}}); + check(!reply.success && !reply.detail.isEmpty(), "rejection/missing success/transport timeout cannot become an ACK"); + } + std::puts("PASS local limits and preset validation; business rejection, missing success and timeout are not ACKs"); +} + +void busyCancellationAndGenerations() +{ + Harness h; h.state(); + h.fake.holdPlay.store(true); + const quint64 playing = h.send("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}); + check(waitFor([&] { return h.fake.playEntered.load() && h.client->isBusy(); }), "expression is active on the normal RPC lane"); + const int started = h.started, controls = h.fake.controls; + const auto busy = h.call("move", {{"id", "eye_l_up"}, {"positionRad", .2}}); + check(!busy.success && h.fake.controls == controls && h.started == started, "busy normal lane rejects another write without enqueueing it"); + const auto canceled = h.call("cancel"); + check(canceled.success && h.fake.cancels == 1 && h.fake.control().has_cancel_expression(), + "cancellation reaches the server through its own lane while a preset RPC is active"); + h.fake.holdPlay.store(false); + check(waitFor([&] { return !h.client->isBusy(); }), "cancellation releases normal admission"); + for (const auto &reply : h.replies) + check(reply.token != playing || !reply.success, "a canceled active expression cannot later report successful completion"); + + h.state(); h.fake.holdControl.store(true); + const int controlCount = h.fake.controls; + const quint64 old = h.send("move", {{"id", "eye_l_up"}, {"positionRad", .1}}); + check(waitFor([&] { return h.fake.controls > controlCount; }), "old-device write entered the fake server"); + const quint64 previousGeneration = h.client->generation(); + h.client->setDeviceId("other_head"); h.fake.holdControl.store(false); + check(h.client->generation() > previousGeneration, "changing device invalidates the old generation"); + pump(); + for (const auto &reply : h.replies) check(reply.token != old, "old-device reply is discarded after a generation change"); + const int beforeNew = h.fake.controls; + check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", .1}}).success && h.fake.controls == beforeNew, + "changing device clears the previous device's metadata"); + h.state(); check(h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success, + "a fresh metadata read enables the newly selected device"); + check(h.fake.control().header().device_id() == "other_head", "new writes route to the selected device only"); + h.robot.connectionChanged(false, 0, {}); + check(!h.client->isConnected() && !h.call("state").success, "disconnect prevents further RPC admission"); + std::puts("PASS one normal in-flight RPC, independent cancellation lane, stale generations and disconnect"); +} + +void malformedMetadataClearsAdmission() +{ + Harness h; h.state(); + for (int fault : {1, 2, 3}) { + h.fake.nextStateFault.store(fault); + const auto invalid = h.call("state"); + check(!invalid.success && !invalid.detail.isEmpty(), + "duplicate IDs, invalid limits and incomplete presets cannot be accepted as metadata"); + const int before = h.fake.controls; + check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success + && h.fake.controls == before, + "malformed metadata clears the previously admitted configuration before another servo write"); + h.state(); + } + std::puts("PASS malformed joint IDs/limits/preset targets reject state and clear cached motion admission"); +} + +QVariantList customTargets() +{ + const double positions[]{0., .2, -.5, .1, -1.}; + QVariantList targets; + for (int i = 0; i < 5; ++i) + targets.append(QVariantMap{{"id", jointIds[i]}, {"positionRad", positions[i]}}); + return targets; +} + +QVariantMap customParameters(double duration = .7) +{ + return {{"targets", customTargets()}, {"transitionDurationS", duration}}; +} + +void customExpressionWireAndValidation() +{ + Harness h; + check(!h.call("expression", customParameters()).success && h.fake.expressions == 0, + "a custom expression requires a state read in this generation"); + h.state(); + check(h.call("expression", customParameters()).success, "a complete local custom expression receives an ACK"); + const auto wire = h.fake.expression(); + check(wire.targets_size() == 5 && std::abs(wire.transition_duration_s() - .7) < 1e-12, + "custom expression transmits all five configured channels and exact duration"); + const QVariantList expected = customTargets(); + for (int i = 0; i < 5; ++i) + check(wire.targets(i).id() == jointIds[i] && wire.targets(i).has_position_rad() + && wire.targets(i).position_rad() == expected[i].toMap().value("positionRad").toDouble(), + "each custom target, including explicit zero, survives the actual protobuf wire"); + check(wire.header().device_id() == "usb_head" && !wire.header().command_id().empty() + && wire.header().timestamp().seconds() > 0 && wire.header().valid_for_ms() == 2700, + "custom execution preserves UUID, timestamp, device and duration-plus-two-seconds validity"); + check(h.fake.expressionDeadlineMs > 1700 && h.fake.expressionDeadlineMs <= 2800, + "custom expression deadline is bounded by its transition duration plus two seconds"); + check(h.fake.plays == 0 && h.fake.controls == 0, + "custom execution never substitutes a server preset or inserts automatic mode/home commands"); + check(!h.call("play", {{"expressionId", "local-library-uuid"}, {"transitionDurationS", .7}}).success + && h.fake.plays == 0, "a local library ID is never forwarded as a configured PlayHeadExpression selector"); + + const int before = h.fake.expressions; + std::vector invalid; + for (double duration : {.1, 5.1, std::numeric_limits::quiet_NaN()}) + invalid.push_back(customParameters(duration)); + QVariantList targets = customTargets(); targets.removeLast(); + invalid.push_back({{"targets", targets}, {"transitionDurationS", .7}}); + for (const QVariantMap &replacement : { + QVariantMap{{"id", jointIds[0]}, {"positionRad", 0.}}, + QVariantMap{{"id", "unknown_joint"}, {"positionRad", 0.}}, + QVariantMap{{"id", jointIds[1]}, {"positionRad", 1.}}, + QVariantMap{{"id", jointIds[1]}, {"positionRad", std::numeric_limits::infinity()}}, + QVariantMap{{"id", jointIds[1]}}}) { + targets = customTargets(); targets[1] = replacement; + invalid.push_back({{"targets", targets}, {"transitionDurationS", .7}}); + } + QVariantMap withLocalId = customParameters(); withLocalId.insert("expressionId", "local-library-uuid"); + invalid.push_back(withLocalId); + for (const QVariantMap ¶meters : invalid) + check(!h.call("expression", parameters).success, "invalid/incomplete/duplicate/nonfinite custom targets are rejected locally"); + check(h.fake.expressions == before && h.fake.plays == 0, "invalid custom input never dispatches either expression RPC"); + h.fake.baseline.store(false); h.state(); + check(!h.call("expression", customParameters()).success && h.fake.expressions == before, + "missing expression baseline blocks custom execution without automatic home"); + h.fake.baseline.store(true); h.state(); + for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { + h.fake.nextExpression.store(result); + const int count = h.fake.expressions; + const auto reply = h.call("expression", customParameters()); + check(!reply.success, "custom business rejection, missing success and unknown transport outcome cannot become ACK"); + pump(); check(h.fake.expressions == count + 1, "a rejected or uncertain custom expression is never retried"); + check(!h.call("expression", customParameters()).success && h.fake.expressions == count + 1, + "an uncertain custom result invalidates its baseline until another explicit state read"); + h.state(); + } + std::puts("PASS local custom expression uses SetHeadExpression: exact five targets/zero/header/deadline, validation and no retries"); +} + +void customExpressionCancellationDeadlineAndGeneration() +{ + Harness h; h.state(); h.fake.holdExpression.store(true); + const quint64 active = h.send("expression", customParameters(5.)); + check(waitFor([&] { return h.fake.expressionEntered.load(); }), "custom expression entered its independent transport worker"); + const int controls = h.fake.controls; + check(!h.call("home").success && h.fake.controls == controls, + "another mutation cannot overlap the active custom expression"); + check(h.call("cancel").success && h.fake.cancels == 1, + "CancelExpression reaches its separate lane during a long custom expression"); + check(waitFor([&] { return h.fake.expressionCanceled.load() && !h.client->isBusy(); }), + "TryCancel interrupts the active custom-expression context"); + for (const auto &reply : h.replies) + check(reply.token != active || !reply.success, "an interrupted custom expression cannot report ACK later"); + const int canceledCount = h.fake.expressions; + check(!h.call("expression", customParameters()).success && h.fake.expressions == canceledCount, + "successful cancellation invalidates the cached baseline before another custom expression"); + + h.fake.holdExpression.store(false); h.state(); + h.fake.expressionEntered.store(false); h.fake.holdExpression.store(true); + const quint64 stale = h.send("expression", customParameters(5.)); + check(waitFor([&] { return h.fake.expressionEntered.load(); }), "another custom expression reached the fake"); + h.client->setDeviceId("replacement_head"); + check(waitFor([&] { return !h.client->isBusy(); }), "device change cancels and drains old custom transport"); + for (const auto &reply : h.replies) check(reply.token != stale, "an old-device custom-expression callback is discarded"); + const int before = h.fake.expressions; + check(!h.call("expression", customParameters()).success && h.fake.expressions == before, + "a new device cannot inherit custom-expression metadata or baseline"); + h.state(); + QElapsedTimer elapsed; elapsed.start(); + const auto timedOut = h.call("expression", customParameters(.2)); + check(!timedOut.success && elapsed.elapsed() >= 1800 && elapsed.elapsed() < 4500, + "a hung custom-expression RPC obeys its actual duration-plus-two-seconds client deadline"); + pump(); check(h.fake.expressions == before + 1, "actual client deadline expiry does not replay a custom expression"); + h.fake.holdExpression.store(false); + std::puts("PASS custom expression busy admission, independent cancel, stale generation and actual bounded deadline"); +} + +void endpointIsolationAndDemoCustomTargets() +{ + Harness h; + const QString endpoint = QStringLiteral("grpc://127.0.0.1:%1").arg(h.port); + check(h.client->endpointKey() == endpoint, "endpoint key includes the normalized real service endpoint"); + h.client->setDeviceId("other_head"); + check(h.client->endpointKey() == endpoint, "device identity is separate from the stable endpoint key"); + h.robot.connectRequested("[0:0:0:0:0:0:0:1]", h.port, false); + check(h.client->endpointKey() == QStringLiteral("grpc://[::1]:%1").arg(h.port), + "IPv6 endpoint variants normalize to one bracketed key"); + h.robot.connectRequested(" Demo.EXAMPLE ", h.port, true); h.robot.connectionChanged(true, 0, {}); + check(h.client->endpointKey() == QStringLiteral("demo://demo.example:%1").arg(h.port), + "demo and real endpoints have distinct normalized persistence keys"); + const int states = h.fake.states, controls = h.fake.controls, expressions = h.fake.expressions; + check(h.call("state").success && !h.call("expression", customParameters(.2)).success, + "demo starts without a confirmed baseline and never homes automatically"); + check(h.call("home").success && h.call("state").success, "explicit demo home establishes the baseline"); + check(h.call("expression", customParameters(.2)).success, "demo custom expression acknowledges its bounded transition"); + const auto state = h.call("state"); + for (const QVariant &entry : state.data.value("targets").toList()) { + const QVariantMap target = entry.toMap(); bool matched = false; + for (const QVariant &expected : customTargets()) { + const QVariantMap value = expected.toMap(); + if (value.value("id") != target.value("id")) continue; + matched = true; + check(target.value("targetValid").toBool() + && target.value("targetPositionRad") == value.value("positionRad"), + "demo retains only acknowledged custom targets, never measured positions"); + } + check(matched, "demo state contains configured channels only"); + } + const quint64 playing = h.send("expression", customParameters(5.)); + check(h.call("cancel").success, "demo long custom transition is locally cancelable"); + check(waitFor([&] { return !h.client->isBusy(); }), "demo canceled transition drains promptly"); + for (const auto &reply : h.replies) + check(reply.token != playing || !reply.success, "canceled demo custom targets cannot overwrite the ACK cache"); + check(h.fake.states == states && h.fake.controls == controls && h.fake.expressions == expressions, + "all demo queries and explicit custom actions make zero network calls"); + std::puts("PASS endpoint namespace isolation/normalization and cancelable demo custom-expression ACK cache"); +} + +void sharedChannelSlowStateAndDiagnostics() +{ + Harness h; + const auto initial = h.call("state"); + check(initial.success, "initial state read succeeds"); + const QString channelId = initial.data.value("channelInstance").toString(); + const QString endpoint = h.client->endpointKey(); + check(!channelId.isEmpty() && initial.data.value("endpoint").toString() == endpoint + && initial.data.contains("elapsedMs") && initial.data.value("elapsedMs").toLongLong() >= 0 + && !initial.data.value("channelStateBefore").toString().isEmpty() + && initial.data.value("channelStateAfter").toString() == "READY", + "state reports its endpoint, bounded elapsed time and real channel connectivity diagnostics"); + check(h.call("state").data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(), + "sequential state reads keep the same explicit channel and HTTP2 peer alive"); + + int ticks = 0; + QTimer heartbeat; heartbeat.setInterval(10); + QObject::connect(&heartbeat, &QTimer::timeout, [&] { ++ticks; }); heartbeat.start(); + h.fake.nextStateDelayMs.store(3200); + const auto slow = h.call("state"); + check(slow.success && slow.data.value("elapsedMs").toLongLong() >= 3100 + && slow.data.value("elapsedMs").toLongLong() < 5800 && ticks > 100, + "a 3.2-second read succeeds within the six-second budget while GUI events remain responsive"); + check(h.fake.stateValidityMs == 6000 && h.fake.stateDeadlineMs > 5000 && h.fake.stateDeadlineMs <= 6100, + "only the state read has a six-second header validity and RPC deadline"); + check(slow.data.value("channelInstance").toString() == channelId && h.fake.oneStatePeer(), + "the delayed read preserves the held channel instead of reconnecting"); + + const auto moved = h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}); + check(moved.success && h.fake.control().header().valid_for_ms() == 3000 + && moved.data.value("channelInstance").toString() == channelId, + "a mutation still has its original three-second budget on the shared channel"); + h.fake.holdPlay.store(true); + h.send("play", {{"expressionId", smileId}, {"transitionDurationS", .7}}); + check(waitFor([&] { return h.fake.playEntered.load(); }), "preset begins on the shared channel"); + const auto canceled = h.call("cancel"); + check(canceled.success && canceled.data.value("channelInstance").toString() == channelId, + "the independent cancel context can preempt an active preset on the same channel"); + h.fake.holdPlay.store(false); + check(waitFor([&] { return !h.client->isBusy(); }), "shared-channel cancellation drains both sessions"); + std::puts("PASS held shared channel, readable diagnostics, slow state recovery/UI heartbeat and independent cancellation"); +} + +void stateFailureBudgetAndRecovery() +{ + Harness h; + const auto initial = h.call("state"); check(initial.success, "initial state is known"); + const QString channelId = initial.data.value("channelInstance").toString(); + for (const auto result : {FakeHead::Reject, FakeHead::MissingSuccess, FakeHead::Timeout}) { + h.fake.nextStateOutcome.store(result); + const auto reply = h.call("state"); + check(!reply.success && reply.detail.contains(QStringLiteral("状态读取")) + && !reply.detail.contains(QStringLiteral("执行结果")) + && reply.data.value("channelInstance").toString() == channelId, + "read rejection/missing header/deadline never becomes ACK or implies an unknown motion"); + h.state(); + } + const int before = h.fake.states; + h.fake.holdState.store(true); + int ticks = 0; + QTimer heartbeat; heartbeat.setInterval(10); + QObject::connect(&heartbeat, &QTimer::timeout, [&] { ++ticks; }); heartbeat.start(); + const auto timeout = h.call("state"); + check(!timeout.success && timeout.data.value("grpcCode").toInt() == grpc::StatusCode::DEADLINE_EXCEEDED + && timeout.data.value("elapsedMs").toLongLong() >= 5500 + && timeout.data.value("elapsedMs").toLongLong() < 7800 && ticks > 300, + "a hung read has a bounded six-second deadline without blocking the GUI"); + check(timeout.detail.contains(QStringLiteral("状态读取超时")) + && !timeout.detail.contains(QStringLiteral("执行结果")), + "a true read timeout is described as a read timeout, not uncertain execution"); + h.fake.holdState.store(false); pump(); + check(h.fake.states == before + 1 && h.fake.controls == 0 && h.fake.plays == 0 && h.fake.expressions == 0, + "state failure performs no automatic read retries, reconnects or motion"); + check(!h.call("move", {{"id", "eye_l_up"}, {"positionRad", 0.}}).success && h.fake.controls == 0, + "failed state invalidates cached motion admission until the next explicit successful read"); + const auto recovered = h.call("state"); + check(recovered.success && recovered.data.value("channelInstance").toString() == channelId + && h.fake.oneStatePeer(), + "explicit recovery reads succeed on the retained channel after a transient timeout"); + std::puts("PASS read-only failure wording/business ACK checks, actual six-second timeout, no retry and explicit recovery"); +} + +void sharedChannelProfileIsolation() +{ + Harness h; + const auto first = h.call("state"); check(first.success, "first endpoint state succeeds"); + const QString oldChannel = first.data.value("channelInstance").toString(); + FakeHead replacement; + int replacementPort = 0; + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &replacementPort); + builder.RegisterService(&replacement); + auto server = builder.BuildAndStart(); + check(server && replacementPort > 0, "replacement endpoint is another ephemeral loopback server"); + h.fake.holdState.store(true); + const int oldCount = h.fake.states; + const quint64 stale = h.send("state"); + check(waitFor([&] { return h.fake.states > oldCount; }), "old endpoint owns an in-flight state context"); + const quint64 oldGeneration = h.client->generation(); + h.robot.connectRequested("127.0.0.1", replacementPort, false); + h.robot.connectionChanged(true, 0, {}); + check(h.client->generation() > oldGeneration && waitFor([&] { return !h.client->isBusy(); }), + "profile switch cancels the old session while its captured old channel remains lifetime-safe"); + h.fake.holdState.store(false); + for (const auto &reply : h.replies) check(reply.token != stale, "old-profile state cannot update the new context"); + const auto current = h.call("state"); + const QString newChannel = current.data.value("channelInstance").toString(); + check(current.success && current.data.value("endpoint").toString() == h.client->endpointKey() + && newChannel != oldChannel && replacement.states == 1 && h.fake.states == oldCount + 1, + "a profile switch builds a new held channel and routes reads only to its endpoint"); + h.client->setDeviceId("second_head"); + check(h.call("state").data.value("channelInstance").toString() == newChannel, + "device generation changes retain the same connection-profile channel"); + h.client->cancelPending(); + check(h.call("state").data.value("channelInstance").toString() == newChannel, + "local cancellation generation does not discard a healthy connection"); + h.robot.disconnectRequested(); + h.robot.connectRequested("127.0.0.1", replacementPort, false); h.robot.connectionChanged(true, 0, {}); + check(h.call("state").data.value("channelInstance").toString() != newChannel, + "a new explicit connection lifetime replaces the profile's previous channel"); + server->Shutdown(); server->Wait(); + std::puts("PASS shared-channel endpoint/profile lifetime isolation, canceled old session and device generation reuse"); +} +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + app.setOrganizationName("CMVR-BioHead-Tests"); app.setApplicationName("Joint Transport Loopback"); + try { + metadataAndExactWireValues(); validationAndNegativeFeedback(); busyCancellationAndGenerations(); + malformedMetadataClearsAdmission(); + customExpressionWireAndValidation(); customExpressionCancellationDeadlineAndGeneration(); + endpointIsolationAndDemoCustomTargets(); + sharedChannelSlowStateAndDiagnostics(); stateFailureBudgetAndRecovery(); sharedChannelProfileIsolation(); + std::puts("PASS BioHead joint transport regression; loopback only, no physical head operations"); return 0; + } catch (const std::exception &error) { + std::fprintf(stderr, "FAIL BioHead joint transport: %s\n", error.what()); return 1; + } +} diff --git a/tests/bioheadlocalexpressions_test.cpp b/tests/bioheadlocalexpressions_test.cpp new file mode 100644 index 0000000..adbf0ec --- /dev/null +++ b/tests/bioheadlocalexpressions_test.cpp @@ -0,0 +1,330 @@ +// Full local-library workflow against a loopback-only fake, never a physical head. +#include "applicationstyle.h" +#include "bioheadexpressionstore.h" +#include "bioheadjointclient.h" +#include "bioheadwidget.h" +#include "robotclient.h" +#include "cmvr/api/biohead_service.grpc.pb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +void check(bool ok, const char *message) { if (!ok) throw std::runtime_error(message); } +void pump(int milliseconds = 180) +{ + QElapsedTimer timer; timer.start(); + do { + QCoreApplication::processEvents(QEventLoop::AllEvents, 10); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } while (timer.elapsed() < milliseconds); +} +bool waitFor(const std::function &ready, int timeout = 5000) +{ + QElapsedTimer timer; timer.start(); + while (!ready() && timer.elapsed() < timeout) pump(5); + return ready(); +} +void clickDialogAction(QPushButton *button) +{ + check(button && button->isEnabled(), "local-library action is enabled"); + QTimer answer; answer.setInterval(5); + QObject::connect(&answer, &QTimer::timeout, [] { + for (QWidget *widget : QApplication::topLevelWidgets()) + if (widget->isVisible() && widget->objectName() == "applicationMessageBox") + if (auto *dialog = qobject_cast(widget)) dialog->done(QMessageBox::Yes); + }); + answer.start(); button->click(); answer.stop(); pump(30); +} +const char *ids[]{"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}; +const double minima[]{-1., -.35, -1.5, -.65, -1.5}; +const double maxima[]{1., .55, 1., .7, .393}; +const double homes[]{0., 0., 0., 0., -1.}; + +class HeadService final : public cmvr::api::BioHeadService::Service +{ +public: + std::atomic reads{0}, controls{0}, presetPlays{0}, expressions{0}, cancellations{0}; + std::atomic holdExpression{false}, expressionActive{false}, expressionCancelled{false}; + std::atomic holdMode{false}, modeActive{false}; + std::atomic failNextState{false}; + std::mutex mutex; + cmvr::api::SetHeadExpressionCommand_Request lastExpression; + double acknowledged[5]{0., 0., 0., 0., -1.}; + grpc::Status GetHeadJointState(grpc::ServerContext *, + const cmvr::api::GetHeadJointStateCommand_Request *, + cmvr::api::GetHeadJointStateCommand_Feedback *response) override + { + ++reads; + if (failNextState.exchange(false)) + return {grpc::StatusCode::DEADLINE_EXCEEDED, "state query fixture timed out"}; + std::lock_guard lock(mutex); + response->mutable_header()->set_success(true); + response->set_connected(true); response->set_expression_baseline_ready(true); + for (int i = 0; i < 5; ++i) { + auto *joint = response->add_joint_info(); joint->set_id(ids[i]); + joint->set_min_position_rad(minima[i]); joint->set_max_position_rad(maxima[i]); + joint->set_home_position_rad(homes[i]); + auto *target = response->add_targets(); target->set_id(ids[i]); + target->set_target_position_rad(acknowledged[i]); target->set_target_valid(true); + } + const QStringList names{QStringLiteral("中立"), QStringLiteral("微笑"), QStringLiteral("疲倦"), + QStringLiteral("惊讶"), QStringLiteral("生气"), QStringLiteral("当前姿态")}; + for (int e = 0; e < names.size(); ++e) { + auto *preset = response->add_expressions(); preset->set_expression_id("server-" + std::to_string(e)); + preset->set_expression_name(names[e].toStdString()); + for (int j = 0; j < 5; ++j) { + auto *target = preset->add_targets(); target->set_id(ids[j]); target->set_position_rad(homes[j]); + } + } + return grpc::Status::OK; + } + grpc::Status ControlHeadJoints(grpc::ServerContext *context, + const cmvr::api::HeadJointCommand_Request *request, + cmvr::api::HeadJointCommand_Feedback *response) override + { + ++controls; + if (request->has_mode()) { + modeActive = true; + while (holdMode && !context->IsCancelled()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + modeActive = false; + } + if (request->has_cancel_expression()) ++cancellations; + response->mutable_header()->set_success(true); return grpc::Status::OK; + } + grpc::Status PlayHeadExpression(grpc::ServerContext *, + const cmvr::api::PlayHeadExpressionCommand_Request *, + cmvr::api::PlayHeadExpressionCommand_Feedback *response) override + { + ++presetPlays; response->mutable_header()->set_success(true); return grpc::Status::OK; + } + grpc::Status SetHeadExpression(grpc::ServerContext *context, + const cmvr::api::SetHeadExpressionCommand_Request *request, + cmvr::api::SetHeadExpressionCommand_Feedback *response) override + { + { + std::lock_guard lock(mutex); lastExpression = *request; + } + ++expressions; expressionActive = true; + while (holdExpression && !context->IsCancelled()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + expressionActive = false; + if (context->IsCancelled()) { + expressionCancelled = true; + return {grpc::StatusCode::CANCELLED, "cancelled local expression"}; + } + { + std::lock_guard lock(mutex); + for (const auto &target : request->targets()) + for (int i = 0; i < 5; ++i) if (target.id() == ids[i]) acknowledged[i] = target.position_rad(); + } + response->mutable_header()->set_success(true); return grpc::Status::OK; + } +}; + +struct Page { + std::unique_ptr robot; + std::unique_ptr widget; + explicit Page(int port, const QString &path) + { + robot.reset(new RobotClient); + QObject::disconnect(robot.get(), &RobotClient::connectRequested, nullptr, nullptr); + QObject::disconnect(robot.get(), &RobotClient::disconnectRequested, nullptr, nullptr); + widget.reset(new BioHeadWidget(robot.get(), nullptr, path)); + widget->resize(1660, 850); widget->show(); + robot->connectRequested("127.0.0.1", port, false); robot->connectionChanged(true, 1, "loopback"); + widget->setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 8}}, + QVariantMap{{"deviceId", "other_head"}, {"type", 8}}}); + check(waitFor([&] { return spin(ids[4]) && button("bioheadEnableDebugButton")->isEnabled(); }), + "page receives current-device metadata"); + tabs()->setCurrentIndex(1); pump(); + check(waitFor([&] { return button("bioheadEnableDebugButton")->isEnabled(); }), "local library page is idle"); + } + QPushButton *button(const char *name) { return widget->findChild(name); } + QDoubleSpinBox *spin(const char *id) { return widget->findChild(QString("bioheadServoValue_") + id); } + QTabWidget *tabs() { return widget->findChild("bioheadExpressionTabs"); } + QComboBox *list() { return widget->findChild("bioheadLocalExpressionCombo"); } + QLineEdit *name() { return widget->findChild("bioheadLocalExpressionName"); } + QDoubleSpinBox *duration() { return widget->findChild("bioheadLocalTransitionSeconds"); } + BioHeadJointClient *client() { return widget->findChild(); } +}; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); app.setOrganizationName("CMVR Local BioHead Tests"); + app.setApplicationName("Local Expressions Loopback"); ApplicationStyle::install(app); + QTemporaryDir temporary; if (!temporary.isValid()) return 1; + const QString path = temporary.filePath("biohead_expressions.json"); + HeadService service; int port = 0; grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(&service); auto server = builder.BuildAndStart(); + if (!server || !port) return 1; + int code = 0; + try { + QString savedId, endpoint; + { + Page page(port, path); + check(page.list()->count() == 0, "new local library starts empty"); + page.button("bioheadLocalEditButton")->click(); + check(page.spin(ids[0])->isEnabled(), "explicit local editing enables inputs"); + const double desired[]{.2, 0., -.5, .15, -1.2}; + for (int i = 0; i < 5; ++i) page.spin(ids[i])->setValue(desired[i]); + page.name()->setText(QStringLiteral("自定义微笑")); page.duration()->setValue(.7); + clickDialogAction(page.button("bioheadLocalCaptureButton")); + check(page.list()->count() == 1 && QFile::exists(path), "save creates a durable local record"); + savedId = page.list()->currentData().toString(); endpoint = page.client()->endpointKey(); + check(!QUuid(savedId).isNull(), "local IDs are UUIDs independent of server presets"); + QList records; QString error; + check(BioHeadExpressionStore::load(path, endpoint, "usb_head", &records, &error) && records.size() == 1, + "saved expression is readable from disk"); + check(records[0].name == QStringLiteral("自定义微笑") && std::abs(records[0].transitionDurationS - .7) < 1e-9, + "name and transition persist"); + page.spin(ids[0])->setValue(.3); page.name()->setText(QStringLiteral("自定义微笑更新")); + clickDialogAction(page.button("bioheadLocalUpdateButton")); + check(page.list()->count() == 1 && page.list()->currentData().toString() == savedId, + "update preserves the local identity"); + clickDialogAction(page.button("bioheadLocalCaptureButton")); + check(page.list()->count() == 1 && + page.widget->findChild("bioheadStatus")->text().contains(QStringLiteral("同名")), + "duplicate save reports a failure without replacing a saved expression"); + page.spin(ids[0])->setValue(.1); page.name()->setText(QStringLiteral("待删除表情")); + clickDialogAction(page.button("bioheadLocalCaptureButton")); + check(page.list()->count() == 2, "adding another expression does not overwrite the first"); + const QString secondId = page.list()->currentData().toString(); + page.list()->setCurrentIndex(page.list()->findData(savedId)); + check(std::abs(page.spin(ids[0])->value() - .1) < 1e-8, "selection only previews, never changes inputs"); + clickDialogAction(page.button("bioheadLocalLoadButton")); + check(std::abs(page.spin(ids[0])->value() - .3) < 1e-8, "explicit load restores editable targets"); + page.name()->setText(QStringLiteral("尚未保存的名称")); page.duration()->setValue(1.2); + page.spin(ids[0])->setValue(.28); + const int beforeRefresh = service.reads; + clickDialogAction(page.button("bioheadRefreshButton")); + check(waitFor([&] { return service.reads > beforeRefresh && !page.client()->isBusy(); }), + "refresh reads only current metadata"); + check(page.name()->text() == QStringLiteral("尚未保存的名称") && + std::abs(page.duration()->value() - 1.2) < 1e-9 && std::abs(page.spin(ids[0])->value() - .28) < 1e-9, + "same-profile refresh preserves all unsaved local draft fields"); + const quint64 generationBeforeReadFailure = page.client()->generation(); + QString recoveryLevel, recoveryMessage; + const auto recoveryConnection = QObject::connect(page.widget.get(), &BioHeadWidget::statusMessage, + page.widget.get(), [&](const QString &level, const QString &message) { + recoveryLevel = level; recoveryMessage = message; + }); + service.failNextState = true; + clickDialogAction(page.button("bioheadRefreshButton")); + auto *status = page.widget->findChild("bioheadStatus"); + check(waitFor([&] { return status->text().contains(QStringLiteral("状态读取超时")); }), + "read deadline has a distinct state-only error"); + check(page.client()->generation() == generationBeforeReadFailure, + "completed read failure does not fabricate a new connection context"); + check(page.name()->text() == QStringLiteral("尚未保存的名称") && + std::abs(page.duration()->value() - 1.2) < 1e-9 && std::abs(page.spin(ids[0])->value() - .28) < 1e-9 && + page.spin(ids[0])->isEnabled(), "state timeout preserves editable local draft fields"); + check(!status->text().contains(QStringLiteral("执行结果")) && !page.button("bioheadLocalPlayButton")->isEnabled(), + "a read timeout does not claim an unknown action result or allow execution"); + const int readsBeforeRecovery = service.reads; + clickDialogAction(page.button("bioheadRefreshButton")); + check(waitFor([&] { return service.reads > readsBeforeRecovery && page.button("bioheadLocalPlayButton")->isEnabled(); }), + "explicit successful read restores expression admission"); + check(page.name()->text() == QStringLiteral("尚未保存的名称") && + std::abs(page.duration()->value() - 1.2) < 1e-9 && std::abs(page.spin(ids[0])->value() - .28) < 1e-9, + "successful recovery also preserves the unsaved local draft"); + check(recoveryLevel == "OK" && recoveryMessage.contains(QStringLiteral("读取")), + "read recovery replaces the stale error in the application status bar"); + QObject::disconnect(recoveryConnection); + page.list()->setCurrentIndex(page.list()->findData(secondId)); + clickDialogAction(page.button("bioheadLocalDeleteButton")); + check(page.list()->count() == 1 && page.list()->currentData().toString() == savedId, + "delete removes only the selected local expression"); + check(page.widget->findChild("bioheadPresetCombo")->count() == 6, + "local CRUD preserves all server presets"); + pump(); check(service.controls == 0 && service.presetPlays == 0 && service.expressions == 0, + "edit/save/update/select/load/delete send no motion RPCs"); + page.widget->grab().save("biohead-local-editing.png"); + } + { + Page page(port, path); + check(page.list()->count() == 1 && page.list()->currentData().toString() == savedId, + "new widget session restores the persisted expression"); + check(page.name()->text() == QStringLiteral("自定义微笑更新"), "updated name survives restart"); + check(waitFor([&] { return page.button("bioheadLocalPlayButton")->isEnabled(); }), + "valid local expression can execute when the device baseline is ready"); + page.button("bioheadLocalPlayButton")->click(); + check(waitFor([&] { return service.expressions == 1 && !page.client()->isBusy(); }), + "explicit local play calls SetHeadExpression once"); + { + std::lock_guard lock(service.mutex); + check(service.lastExpression.header().device_id() == "usb_head" && service.lastExpression.targets_size() == 5, + "custom expression routes the complete five-channel target"); + check(std::abs(service.lastExpression.transition_duration_s() - .7) < 1e-9, + "saved transition reaches the real protobuf wire"); + bool found = false, zero = false; + for (const auto &target : service.lastExpression.targets()) { + found |= target.id() == ids[0] && std::abs(target.position_rad() - .3) < 1e-9; + zero |= target.id() == ids[1] && target.has_position_rad() && target.position_rad() == 0.; + } + check(found && zero, "saved position and explicit zero survive on the wire"); + } + check(service.presetPlays == 0 && service.controls == 0, "custom play never uses a preset ID or hidden mode/home"); + check(waitFor([&] { return page.button("bioheadLocalPlayButton")->isEnabled(); }), "local play becomes idle after readback"); + service.holdExpression = true; page.button("bioheadLocalPlayButton")->click(); + check(waitFor([&] { return service.expressionActive.load(); }), "custom transition is active"); + clickDialogAction(page.button("bioheadCancelExpressionButton")); + check(waitFor([&] { return service.expressionCancelled && service.cancellations == 1 && !page.client()->isBusy(); }), + "cancel interrupts a local expression independently"); + service.holdExpression = false; + page.widget->setDeviceId("other_head"); + check(waitFor([&] { return page.button("bioheadLocalEditButton")->isEnabled(); }), "second device metadata loads"); + check(page.list()->count() == 0, "local records are isolated by device"); + page.widget->setDeviceId("usb_head"); + check(waitFor([&] { return page.list()->count() == 1; }), "returning to the first device restores its local library"); + page.widget->grab().save("biohead-local-library.png"); + check(waitFor([&] { return page.button("bioheadEnableDebugButton")->isEnabled(); }), "ready for mode-boundary check"); + service.holdMode = true; + page.button("bioheadEnableDebugButton")->click(); + check(waitFor([&] { return service.modeActive.load(); }), "explicit mode request is in flight"); + page.tabs()->setCurrentIndex(0); + service.holdMode = false; + check(waitFor([&] { return !page.client()->isBusy() && page.button("bioheadEnableDebugButton")->isEnabled(); }), + "mode completes after a local/server tab change"); + check(!page.spin(ids[0])->isEnabled(), "late mode ACK cannot re-enable live dragging after leaving the local view"); + } + { + QFile file(path); check(file.open(QIODevice::WriteOnly), "prepare corrupt isolated fixture"); + file.write("{broken"); file.close(); + Page page(port, path); + check(!page.button("bioheadLocalCaptureButton")->isEnabled() && + !page.button("bioheadLocalPlayButton")->isEnabled(), "corrupt library cannot be overwritten or executed"); + check(file.open(QIODevice::ReadOnly) && file.readAll() == "{broken", "corrupt source file remains untouched"); + } + std::puts("PASS local BioHead UI: no-motion edit/CRUD/load, restart persistence, scope isolation, exact SetHeadExpression wire, cancellation and corrupt-file preservation"); + } catch (const std::exception &error) { + std::fprintf(stderr, "FAIL local BioHead UI: %s\n", error.what()); code = 2; + } + service.holdExpression = false; server->Shutdown(); server->Wait(); return code; +} diff --git a/tests/bioheadwidget_test.cpp b/tests/bioheadwidget_test.cpp new file mode 100644 index 0000000..71e44c7 --- /dev/null +++ b/tests/bioheadwidget_test.cpp @@ -0,0 +1,318 @@ +#include "applicationstyle.h" +#include "bioheadwidget.h" +#include "bioheadjointclient.h" +#include "robotclient.h" +#include "cmvr/api/biohead_service.grpc.pb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +bool waitFor(const std::function &ready, int timeout = 5000) +{ + QElapsedTimer clock; + clock.start(); + while (!ready() && clock.elapsed() < timeout) { + QCoreApplication::processEvents(QEventLoop::AllEvents, 10); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + return ready(); +} +void settle(int milliseconds) +{ + QElapsedTimer clock; + clock.start(); + while (clock.elapsed() < milliseconds) { + QCoreApplication::processEvents(QEventLoop::AllEvents, 10); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } +} +const char *ids[] = {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}; +const double minima[] = {-1., -.35, -1.5, -.65, -1.5}; +const double maxima[] = {1., .55, 1., .70, .393}; +const double homes[] = {0., 0., 0., 0., -1.}; + +class FakeHead final : public cmvr::api::BioHeadService::Service +{ +public: + std::atomic reads{0}, modes{0}, homesSent{0}, plays{0}, cancels{0}; + std::atomic holdPlay{false}, playActive{false}, cancelledPlay{false}; + std::atomic rejectMove{false}, badMetadata{false}; + std::atomic baselineReady{false}; + std::mutex mutex; + std::vector moves; + std::vector targets{0., 0., 0., 0., -1.}; + std::string presetId; + double duration = 0; + bool validWire = true; + + grpc::Status GetHeadJointState(grpc::ServerContext *, + const cmvr::api::GetHeadJointStateCommand_Request *request, + cmvr::api::GetHeadJointStateCommand_Feedback *reply) override + { + ++reads; + std::lock_guard lock(mutex); + validWire &= request->has_header() && !request->header().device_id().empty(); + reply->mutable_header()->set_success(true); + reply->set_connected(true); + reply->set_expression_baseline_ready(baselineReady); + for (int i = 0; i < 5; ++i) { + auto *info = reply->add_joint_info(); + info->set_id(ids[i]); + info->set_min_position_rad(minima[i]); + info->set_max_position_rad(badMetadata ? minima[i] - 1. : maxima[i]); + info->set_home_position_rad(homes[i]); + auto *target = reply->add_targets(); + target->set_id(ids[i]); + target->set_target_position_rad(targets[i]); + target->set_target_valid(true); + } + const QStringList names{QStringLiteral("中立"), QStringLiteral("微笑"), + QStringLiteral("疲倦"), QStringLiteral("惊讶"), QStringLiteral("生气"), + QStringLiteral("当前姿态")}; + for (int p = 0; p < names.size(); ++p) { + auto *expression = reply->add_expressions(); + expression->set_expression_id("preset-" + std::to_string(p)); + expression->set_expression_name(names[p].toStdString()); + for (int i = 0; i < 5; ++i) { + auto *target = expression->add_targets(); + target->set_id(ids[i]); + target->set_position_rad(homes[i]); + } + } + return grpc::Status::OK; + } + grpc::Status ControlHeadJoints(grpc::ServerContext *, + const cmvr::api::HeadJointCommand_Request *request, + cmvr::api::HeadJointCommand_Feedback *reply) override + { + reply->mutable_header()->set_success(true); + std::lock_guard lock(mutex); + validWire &= request->has_header() && !request->header().device_id().empty(); + if (request->has_mode()) { + ++modes; + validWire &= request->mode().has_mode() && request->mode().mode() == 0; + } else if (request->has_move()) { + moves.push_back(*request); + validWire &= request->move().targets_size() == 1; + for (const auto &target : request->move().targets()) { + validWire &= target.has_position_rad(); + if (!rejectMove) for (int i = 0; i < 5; ++i) + if (target.id() == ids[i]) targets[i] = target.position_rad(); + } + if (rejectMove) { + reply->mutable_header()->set_success(false); + reply->mutable_header()->set_error_message("fixture rejected target"); + } + } else if (request->has_home()) { + ++homesSent; + baselineReady = true; + for (int i = 0; i < 5; ++i) targets[i] = homes[i]; + } else if (request->has_cancel_expression()) { + ++cancels; + } + return grpc::Status::OK; + } + grpc::Status PlayHeadExpression(grpc::ServerContext *context, + const cmvr::api::PlayHeadExpressionCommand_Request *request, + cmvr::api::PlayHeadExpressionCommand_Feedback *reply) override + { + { + std::lock_guard lock(mutex); + presetId = request->expression_id(); + duration = request->transition_duration_s(); + validWire &= request->has_expression_id(); + } + ++plays; + playActive = true; + while (holdPlay && !context->IsCancelled()) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + playActive = false; + if (context->IsCancelled()) { + cancelledPlay = true; + return {grpc::StatusCode::CANCELLED, "fixture expression cancelled"}; + } + reply->mutable_header()->set_success(true); + reply->set_expression_id(request->expression_id()); + reply->set_expression_name("fixture"); + return grpc::Status::OK; + } + size_t moveCount() + { + std::lock_guard lock(mutex); + return moves.size(); + } + double lastPosition() + { + std::lock_guard lock(mutex); + return moves.empty() ? -999. : moves.back().move().targets(0).position_rad(); + } +}; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + app.setOrganizationName("CMVR Isolated BioHead Tests"); + app.setApplicationName("BioHead USB UI"); + ApplicationStyle::install(app); + FakeHead service; + int port = 0; + grpc::ServerBuilder builder; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(&service); + auto server = builder.BuildAndStart(); + if (!server || !port) return 1; + bool passed = [&]() { + auto check = [](bool ok, const char *what) { + if (!ok) qCritical() << "FAIL" << what; + return ok; + }; + RobotClient client; + QObject::disconnect(&client, &RobotClient::connectRequested, nullptr, nullptr); + QObject::disconnect(&client, &RobotClient::disconnectRequested, nullptr, nullptr); + BioHeadWidget page(&client); + page.resize(1660, 850); + page.show(); + auto button = [&](const char *name) { return page.findChild(name); }; + auto slider = [&](const char *id) { return page.findChild( + QStringLiteral("bioheadServoSlider_") + id); }; + auto spin = [&](const char *id) { return page.findChild( + QStringLiteral("bioheadServoValue_") + id); }; + auto *status = page.findChild("bioheadStatus"); + auto *preset = page.findChild("bioheadPresetCombo"); + auto *duration = page.findChild("bioheadTransitionSeconds"); + auto *tabs = page.findChild("serviceTabs"); + if (!check(status && preset && duration && tabs && tabs->count() == 2, + "required USB head controls")) return false; + for (auto *b : page.findChildren()) + if (!check(!b->text().contains(QStringLiteral("说话")) && + !b->text().contains(QStringLiteral("紧急停止")), + "no speaking or fake hardware stop button")) return false; + emit client.connectRequested("127.0.0.1", port, false); + emit client.connectionChanged(true, 1, "fixture"); + page.setAvailableDevices({QVariantMap{{"deviceId", "usb_head"}, {"type", 8}}, + QVariantMap{{"deviceId", "usb_head_2"}, {"type", 8}}}); + if (!check(waitFor([&] { return spin(ids[4]) && preset->count() == 6; }), + "dynamic metadata and presets loaded")) return false; + for (int i = 0; i < 5; ++i) { + if (!check(spin(ids[i]) && slider(ids[i]) && + std::abs(spin(ids[i])->minimum() - minima[i]) < .0001 && + std::abs(spin(ids[i])->maximum() - maxima[i]) < .0001, + "exact server joint range")) return false; + } + settle(150); + if (!check(service.modes == 0 && service.moveCount() == 0 && + service.homesSent == 0 && service.plays == 0, + "initialization never moves")) return false; + auto *enable = button("bioheadEnableDebugButton"); + auto *play = button("bioheadPlayPresetButton"); + auto *cancel = button("bioheadCancelExpressionButton"); + if (!check(enable && play && cancel && enable->isEnabled(), "explicit debug enable")) return false; + enable->click(); + if (!check(waitFor([&] { return slider(ids[0]) && slider(ids[0])->isEnabled(); }) && + service.modes == 1 && service.moveCount() == 0, "enable uses mode only")) return false; + auto *eye = slider(ids[0]); + eye->setSliderDown(true); + for (int n = 0; n < 30; ++n) + eye->setValue(eye->minimum() + (eye->maximum() - eye->minimum()) * (n + 1) / 40); + const double final = spin(ids[0])->value(); + eye->setSliderDown(false); + if (!check(waitFor([&] { return std::abs(service.lastPosition() - final) < .001; }), + "final slider target acknowledged")) return false; + settle(180); + if (!check(service.moveCount() <= 2 && service.validWire, + "throttled single-target protobuf")) return false; + if (!check(waitFor([&] { return slider(ids[0])->isEnabled(); }), + "dragging remains available after readback")) return false; + const size_t beforeRevert = service.moveCount(); + eye = slider(ids[0]); + const int acknowledgedSlider = eye->value(); + eye->setValue(eye->maximum()); + eye->setValue(acknowledgedSlider); + settle(180); + if (!check(service.moveCount() == beforeRevert, + "returning to ACK target clears an obsolete queued value")) return false; + page.grab().save(QStringLiteral("biohead-usb-debug.png")); + const size_t before = service.moveCount(); + preset->setCurrentIndex(1); + settle(130); + if (!check(service.plays == 0 && service.moveCount() == before, + "preset selection never executes")) return false; + auto *home = button("bioheadHomeButton"); + if (!check(!play->isEnabled() && service.homesSent == 0 && home && home->isEnabled(), + "unknown preset baseline requires explicit preparation")) return false; + home->click(); + if (!check(waitFor([&] { return play->isEnabled(); }) && service.homesSent == 1, + "explicit home prepares the preset baseline")) return false; + duration->setValue(.6); + play->click(); + if (!check(waitFor([&] { return service.plays == 1 && play->isEnabled(); }), + "preset executes exactly once")) return false; + { + std::lock_guard lock(service.mutex); + if (!check(service.presetId == "preset-1" && std::abs(service.duration - .6) < .001, + "stable preset ID and duration")) return false; + } + page.grab().save(QStringLiteral("biohead-usb-page.png")); + service.holdPlay = true; + play->click(); + if (!check(waitFor([&] { return service.playActive.load(); }), "expression starts")) return false; + if (!check(cancel->isEnabled(), "cancel available during expression")) return false; + cancel->click(); + if (!check(waitFor([&] { return service.cancelledPlay && service.cancels == 1; }), + "cancel interrupts active RPC and invokes typed cancellation")) return false; + service.holdPlay = false; + settle(180); + page.setDeviceId("usb_head_2"); + if (!check(waitFor([&] { return spin(ids[0]) && enable->isEnabled(); }), + "device switch reloads metadata")) return false; + if (!check(!slider(ids[0])->isEnabled(), "device switch disarms dragging")) return false; + enable->click(); + if (!check(waitFor([&] { return slider(ids[0])->isEnabled(); }), "second device debug")) return false; + const size_t movesBeforeHide = service.moveCount(); + slider(ids[0])->setValue(slider(ids[0])->maximum()); + tabs->setCurrentIndex(1); + settle(220); + if (!check(service.moveCount() == movesBeforeHide, "tab switch drops unsent slider targets")) return false; + tabs->setCurrentIndex(0); + if (!check(waitFor([&] { return enable->isEnabled(); }), "return reloads state")) return false; + enable->click(); + if (!check(waitFor([&] { return slider(ids[0])->isEnabled(); }), "explicit re-enable on return")) return false; + service.rejectMove = true; + spin(ids[0])->setValue(.1234); + if (!check(waitFor([&] { return status->text().contains("fixture rejected target"); }), + "rejection is visible on the page")) return false; + if (!check(!slider(ids[0])->isEnabled(), "rejection disarms queued dragging")) return false; + const size_t afterFailure = service.moveCount(); + settle(220); + if (!check(service.moveCount() == afterFailure, "rejected movement is never retried")) return false; + emit client.connectionChanged(false, 0, "fixture disconnected"); + settle(30); + if (!check(!enable->isEnabled() && !play->isEnabled(), "disconnect disables mutation")) return false; + qInfo() << "PASS USB head UI: dynamic ranges, no startup movement, explicit mode," + " throttled drag, stable presets, active cancellation, device/tab/disconnect boundaries"; + return true; + }(); + server->Shutdown(); + server->Wait(); + return passed ? 0 : 2; +}