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.
1158 lines
58 KiB
C++
1158 lines
58 KiB
C++
#include "bioheadwidget.h"
|
||
#include "bioheadjointclient.h"
|
||
#include "bioheadexpressionstore.h"
|
||
#include "appmessagebox.h"
|
||
#include "applicationstyle.h"
|
||
#include "robotclient.h"
|
||
#include "rpcservicewidget.h"
|
||
|
||
#include <QComboBox>
|
||
#include <QDateTime>
|
||
#include <QDoubleSpinBox>
|
||
#include <QFrame>
|
||
#include <QGridLayout>
|
||
#include <QHBoxLayout>
|
||
#include <QHideEvent>
|
||
#include <QJsonDocument>
|
||
#include <QLabel>
|
||
#include <QListWidget>
|
||
#include <QLineEdit>
|
||
#include <QPushButton>
|
||
#include <QScrollArea>
|
||
#include <QSet>
|
||
#include <QShowEvent>
|
||
#include <QSignalBlocker>
|
||
#include <QSlider>
|
||
#include <QTabWidget>
|
||
#include <QTimer>
|
||
#include <QVBoxLayout>
|
||
#include <QUuid>
|
||
#include <cmath>
|
||
#include <limits>
|
||
|
||
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);
|
||
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(10);
|
||
auto *header = new QFrame(controls);
|
||
header->setObjectName(QStringLiteral("panel"));
|
||
auto *headerLayout = new QHBoxLayout(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(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 *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;
|
||
m_status = new QLabel(QStringLiteral("未连接"), feedback);
|
||
m_status->setObjectName(QStringLiteral("bioheadStatus"));
|
||
m_status->setWordWrap(true);
|
||
m_status->setTextInteractionFlags(Qt::TextSelectableByMouse);
|
||
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);
|
||
content->addWidget(feedback);
|
||
connect(clear, &QPushButton::clicked, m_history, &QListWidget::clear);
|
||
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);
|
||
|
||
m_dispatchTimer = new QTimer(this);
|
||
m_dispatchTimer->setInterval(100);
|
||
connect(m_dispatchTimer, &QTimer::timeout, this, &BioHeadWidget::advanceRequests);
|
||
connect(m_device, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int) { changeDeviceContext(); });
|
||
connect(m_presets, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int) { updatePresetPreview(); refreshControls(); });
|
||
connect(m_localList, QOverload<int>::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) {
|
||
resetInteraction(QStringLiteral("连接已断开,目标状态未知。"), true, true);
|
||
setAvailableDevices({});
|
||
} 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 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);
|
||
}
|
||
QStringList existing;
|
||
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 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)
|
||
{
|
||
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<QString, QVariantMap> 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<int>::min()
|
||
|| high * sliderScale > std::numeric_limits<int>::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<QString, QVariantMap> 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<QString> 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<QString, double> confirmed;
|
||
QSet<QString> 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<int>(std::ceil(row.minimum * sliderScale)),
|
||
static_cast<int>(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<double>::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 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::hideEvent(QHideEvent *event)
|
||
{
|
||
resetInteraction(QStringLiteral("已离开调试页,待发送目标已清除。"), false, true);
|
||
QWidget::hideEvent(event);
|
||
}
|
||
|
||
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 ? (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<QString> 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<BioHeadExpressionStore::Expression> 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()}});
|
||
}
|