CmvrControlStation/tests/bioheadlocalexpressions_test.cpp

331 lines
20 KiB
C++
Raw Permalink Normal View History

// 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 <QApplication>
#include <QComboBox>
#include <QDialog>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QTabWidget>
#include <QTemporaryDir>
#include <QTimer>
#include <QUuid>
#include <grpcpp/grpcpp.h>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <functional>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <thread>
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<bool()> &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<QDialog *>(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<int> reads{0}, controls{0}, presetPlays{0}, expressions{0}, cancellations{0};
std::atomic<bool> holdExpression{false}, expressionActive{false}, expressionCancelled{false};
std::atomic<bool> holdMode{false}, modeActive{false};
std::atomic<bool> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<RobotClient> robot;
std::unique_ptr<BioHeadWidget> 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", 9}},
QVariantMap{{"deviceId", "other_head"}, {"type", 9}}});
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<QPushButton *>(name); }
QDoubleSpinBox *spin(const char *id) { return widget->findChild<QDoubleSpinBox *>(QString("bioheadServoValue_") + id); }
QTabWidget *tabs() { return widget->findChild<QTabWidget *>("bioheadExpressionTabs"); }
QComboBox *list() { return widget->findChild<QComboBox *>("bioheadLocalExpressionCombo"); }
QLineEdit *name() { return widget->findChild<QLineEdit *>("bioheadLocalExpressionName"); }
QDoubleSpinBox *duration() { return widget->findChild<QDoubleSpinBox *>("bioheadLocalTransitionSeconds"); }
BioHeadJointClient *client() { return widget->findChild<BioHeadJointClient *>(); }
};
}
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<BioHeadExpressionStore::Expression> 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<QLabel *>("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<QLabel *>("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<QComboBox *>("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<std::mutex> 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;
}