2026-09-18 16:22:20 +08:00
|
|
|
|
#include "robotclient.h"
|
2026-11-10 16:10:46 +08:00
|
|
|
|
#include "agvmaprasterizer.h"
|
|
|
|
|
|
#include "seeragvmapclient.h"
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include "videodecoder.h"
|
2026-10-14 17:15:46 +08:00
|
|
|
|
#include "tcpjogcontroller.h"
|
2026-09-18 16:22:20 +08:00
|
|
|
|
|
|
|
|
|
|
#include <QDateTime>
|
|
|
|
|
|
#include <QElapsedTimer>
|
2026-11-10 16:10:46 +08:00
|
|
|
|
#include <QFile>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include <QJsonArray>
|
|
|
|
|
|
#include <QJsonDocument>
|
|
|
|
|
|
#include <QJsonObject>
|
|
|
|
|
|
#include <QJsonParseError>
|
2026-11-10 16:10:46 +08:00
|
|
|
|
#include <QLineF>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include <QMutexLocker>
|
|
|
|
|
|
#include <QPainter>
|
2026-09-23 11:11:49 +08:00
|
|
|
|
#include <QSysInfo>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include <QTimer>
|
|
|
|
|
|
#include <QUuid>
|
|
|
|
|
|
#include <QtMath>
|
|
|
|
|
|
|
|
|
|
|
|
#include <chrono>
|
2026-10-14 17:15:46 +08:00
|
|
|
|
#include <cmath>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include <algorithm>
|
|
|
|
|
|
#include <atomic>
|
|
|
|
|
|
#include <condition_variable>
|
|
|
|
|
|
#include <cstring>
|
|
|
|
|
|
#include <deque>
|
|
|
|
|
|
#include <functional>
|
|
|
|
|
|
#include <limits>
|
|
|
|
|
|
#include <memory>
|
|
|
|
|
|
#include <mutex>
|
|
|
|
|
|
#include <thread>
|
2026-10-20 16:49:27 +08:00
|
|
|
|
#include <vector>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
#include <grpcpp/grpcpp.h>
|
|
|
|
|
|
#include <grpcpp/generic/generic_stub.h>
|
|
|
|
|
|
#include <google/protobuf/dynamic_message.h>
|
2026-11-10 16:10:46 +08:00
|
|
|
|
#include <google/protobuf/text_format.h>
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include <google/protobuf/util/json_util.h>
|
|
|
|
|
|
#include "cmvr/api/agv_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/agv_service.grpc.pb.h"
|
|
|
|
|
|
#include "cmvr/api/arm_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/arm_service.grpc.pb.h"
|
2026-10-20 16:49:27 +08:00
|
|
|
|
#include "cmvr/api/motor_service.grpc.pb.h"
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include "cmvr/api/camera_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/camera_service.grpc.pb.h"
|
2026-10-14 17:15:46 +08:00
|
|
|
|
#include "cmvr/api/dexhand_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/dexhand_service.grpc.pb.h"
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#include "cmvr/api/configuration_service.grpc.pb.h"
|
|
|
|
|
|
#include "cmvr/api/microphone_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/microphone_service.grpc.pb.h"
|
|
|
|
|
|
#include "cmvr/api/speaker_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/speaker_service.grpc.pb.h"
|
|
|
|
|
|
#include "cmvr/api/system_command.pb.h"
|
|
|
|
|
|
#include "cmvr/api/system_service.grpc.pb.h"
|
2026-11-10 16:10:46 +08:00
|
|
|
|
#include "cmvr/config/agv_config/agv_config.pb.h"
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
|
|
namespace {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QString agvStationDisplayName(QString description, const QString &id,
|
|
|
|
|
|
bool decodeJson = false)
|
|
|
|
|
|
{
|
|
|
|
|
|
// Unified properties may carry the original SMAP value as a JSON string.
|
|
|
|
|
|
if (decodeJson) {
|
|
|
|
|
|
const QJsonDocument json = QJsonDocument::fromJson(
|
|
|
|
|
|
(QLatin1Char('[') + description + QLatin1Char(']')).toUtf8());
|
|
|
|
|
|
if (json.isArray() && json.array().size() == 1 && json.array().first().isString())
|
|
|
|
|
|
description = json.array().first().toString();
|
|
|
|
|
|
}
|
|
|
|
|
|
description = description.trimmed();
|
|
|
|
|
|
return description.isEmpty() ? id : description;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
constexpr int kGrpcMaxMessageBytes = 64 * 1024 * 1024;
|
|
|
|
|
|
constexpr int kArmMotionTimeoutMs = 120000;
|
|
|
|
|
|
|
2026-10-26 17:35:27 +08:00
|
|
|
|
bool confirmedJointNames(const cmvr::api::JointState &state, QStringList &names)
|
|
|
|
|
|
{
|
|
|
|
|
|
names.clear();
|
|
|
|
|
|
if (state.position_size() == 0 || state.name_size() != state.position_size())
|
|
|
|
|
|
return false;
|
|
|
|
|
|
for (int i = 0; i < state.name_size(); ++i) {
|
|
|
|
|
|
const QString name = QString::fromStdString(state.name(i)).trimmed();
|
|
|
|
|
|
if (name.isEmpty() || names.contains(name) || !std::isfinite(state.position(i)))
|
|
|
|
|
|
return false;
|
|
|
|
|
|
names.append(name);
|
|
|
|
|
|
}
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::shared_ptr<grpc::Channel> createGrpcChannel(const std::string &endpoint)
|
|
|
|
|
|
{
|
|
|
|
|
|
grpc::ChannelArguments arguments;
|
|
|
|
|
|
arguments.SetMaxReceiveMessageSize(kGrpcMaxMessageBytes);
|
|
|
|
|
|
arguments.SetMaxSendMessageSize(kGrpcMaxMessageBytes);
|
|
|
|
|
|
return grpc::CreateCustomChannel(endpoint, grpc::InsecureChannelCredentials(), arguments);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
// The map-only configuration lookup owns a separate channel. It never changes
|
|
|
|
|
|
// the configuration editor's connection or writes a configuration file.
|
|
|
|
|
|
class DirectMapRpcCancellation
|
|
|
|
|
|
{
|
|
|
|
|
|
public:
|
|
|
|
|
|
DirectMapRpcCancellation(grpc::ClientContext &context,
|
|
|
|
|
|
const std::shared_ptr<std::atomic<bool>> &cancel)
|
|
|
|
|
|
: m_thread([this, &context, cancel]() {
|
|
|
|
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
|
|
|
|
|
while (!m_finished) {
|
|
|
|
|
|
if (cancel->load()) {
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_condition.wait_for(lock, std::chrono::milliseconds(20));
|
|
|
|
|
|
}
|
|
|
|
|
|
}) {}
|
|
|
|
|
|
~DirectMapRpcCancellation()
|
|
|
|
|
|
{
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
|
|
|
|
m_finished = true;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_condition.notify_all();
|
|
|
|
|
|
m_thread.join();
|
|
|
|
|
|
}
|
|
|
|
|
|
private:
|
|
|
|
|
|
std::mutex m_mutex;
|
|
|
|
|
|
std::condition_variable m_condition;
|
|
|
|
|
|
bool m_finished = false;
|
|
|
|
|
|
std::thread m_thread;
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
bool resolveDirectMapConnection(const QString &configHost, int configPort,
|
|
|
|
|
|
const QString &deviceId,
|
|
|
|
|
|
const std::shared_ptr<std::atomic<bool>> &cancel,
|
|
|
|
|
|
SeerAgvMapConnection &connection, QString &error)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (configHost.isEmpty() || configPort < 1 || configPort > 65535) {
|
|
|
|
|
|
error = QStringLiteral("请填写车辆 IP,或设置可用的配置服务地址以读取 AGV 配置");
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString host = configHost.contains(QLatin1Char(':'))
|
|
|
|
|
|
&& !configHost.startsWith(QLatin1Char('['))
|
|
|
|
|
|
? QLatin1Char('[') + configHost + QLatin1Char(']') : configHost;
|
|
|
|
|
|
auto stub = cmvr::api::ConfigurationService::NewStub(
|
|
|
|
|
|
createGrpcChannel(QStringLiteral("%1:%2").arg(host).arg(configPort).toStdString()));
|
|
|
|
|
|
cmvr::api::ListConfigFilesCommand::Request listRequest;
|
|
|
|
|
|
cmvr::api::ListConfigFilesCommand::Feedback listResponse;
|
|
|
|
|
|
grpc::ClientContext listContext;
|
|
|
|
|
|
listContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
|
|
|
|
|
|
grpc::Status listStatus;
|
|
|
|
|
|
{
|
|
|
|
|
|
DirectMapRpcCancellation cancellation(listContext, cancel);
|
|
|
|
|
|
listStatus = stub->ListConfigFiles(&listContext, listRequest, &listResponse);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (cancel->load()) {
|
|
|
|
|
|
error = QStringLiteral("地图直连配置读取已取消");
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!listStatus.ok() || !listResponse.header().success()) {
|
|
|
|
|
|
error = QStringLiteral("无法读取 AGV 配置列表:%1;可手动填写车辆 IP")
|
|
|
|
|
|
.arg(QString::fromStdString(listStatus.ok()
|
|
|
|
|
|
? listResponse.header().error_message() : listStatus.error_message()));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
int matches = 0;
|
|
|
|
|
|
for (const auto &file : listResponse.files()) {
|
|
|
|
|
|
if (file.message_type() != "cmvr.config.AGVRootConfig")
|
|
|
|
|
|
continue;
|
|
|
|
|
|
cmvr::api::ReadConfigFileCommand::Request readRequest;
|
|
|
|
|
|
readRequest.set_relative_path(file.relative_path());
|
|
|
|
|
|
cmvr::api::ReadConfigFileCommand::Feedback readResponse;
|
|
|
|
|
|
grpc::ClientContext readContext;
|
|
|
|
|
|
readContext.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(3));
|
|
|
|
|
|
grpc::Status readStatus;
|
|
|
|
|
|
{
|
|
|
|
|
|
DirectMapRpcCancellation cancellation(readContext, cancel);
|
|
|
|
|
|
readStatus = stub->ReadConfigFile(&readContext, readRequest, &readResponse);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (cancel->load()) {
|
|
|
|
|
|
error = QStringLiteral("地图直连配置读取已取消");
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!readStatus.ok() || !readResponse.header().success()) {
|
|
|
|
|
|
error = QStringLiteral("无法完整核查 AGV 配置 %1:%2;未连接车辆")
|
|
|
|
|
|
.arg(QString::fromStdString(file.relative_path()),
|
|
|
|
|
|
QString::fromStdString(readStatus.ok()
|
|
|
|
|
|
? readResponse.header().error_message() : readStatus.error_message()));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::config::AGVRootConfig root;
|
|
|
|
|
|
if (!google::protobuf::TextFormat::ParseFromString(readResponse.content(), &root)) {
|
|
|
|
|
|
error = QStringLiteral("AGV 配置 %1 解析失败;未连接车辆")
|
|
|
|
|
|
.arg(QString::fromStdString(file.relative_path()));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
for (const auto &device : root.agv().agvs()) {
|
|
|
|
|
|
const QString configuredId = QString::fromStdString(device.id()).trimmed();
|
|
|
|
|
|
if (configuredId != deviceId)
|
|
|
|
|
|
continue;
|
|
|
|
|
|
++matches;
|
|
|
|
|
|
if (!device.has_seer_robokit_agv()) {
|
|
|
|
|
|
error = QStringLiteral("设备 %1 不是 SEER Robokit,不能使用地图直连").arg(deviceId);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &seer = device.seer_robokit_agv();
|
|
|
|
|
|
const QString backendId = QString::fromStdString(seer.id()).trimmed();
|
|
|
|
|
|
if (!backendId.isEmpty() && backendId != deviceId) {
|
|
|
|
|
|
error = QStringLiteral("设备 %1 的内外配置 ID 不一致,未连接车辆").arg(deviceId);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
connection.host = QString::fromStdString(seer.ip()).trimmed();
|
|
|
|
|
|
const int statusPort = seer.port_status() == 0 ? 19204 : seer.port_status();
|
|
|
|
|
|
const int controlPort = seer.port_control() == 0 ? 19205 : seer.port_control();
|
|
|
|
|
|
const int mapPort = seer.port_config() == 0 ? 19207 : seer.port_config();
|
|
|
|
|
|
if (connection.host.isEmpty() || statusPort < 1 || statusPort > 65535
|
|
|
|
|
|
|| controlPort < 1 || controlPort > 65535 || mapPort < 1 || mapPort > 65535) {
|
|
|
|
|
|
error = QStringLiteral("设备 %1 的车辆地址或端口无效,未连接车辆").arg(deviceId);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
connection.statusPort = static_cast<quint16>(statusPort);
|
|
|
|
|
|
connection.controlPort = static_cast<quint16>(controlPort);
|
|
|
|
|
|
connection.configPort = static_cast<quint16>(mapPort);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if (matches != 1) {
|
|
|
|
|
|
error = matches == 0
|
|
|
|
|
|
? QStringLiteral("配置中未找到设备 %1 的 SEER 地址;可手动填写车辆 IP").arg(deviceId)
|
|
|
|
|
|
: QStringLiteral("设备 %1 在配置中有多个匹配,未连接车辆").arg(deviceId);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
return !cancel->load();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-23 11:11:49 +08:00
|
|
|
|
cmvr::api::DeviceType deviceTypeFromKind(cmvr::api::DeviceKind kind,
|
|
|
|
|
|
cmvr::api::DeviceType fallback)
|
|
|
|
|
|
{
|
|
|
|
|
|
switch (kind) {
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_AGV: return cmvr::api::AGV;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_ARM:
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_ROBOT: return cmvr::api::Robot;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_BATTERY: return cmvr::api::Battery;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_BIO_HEAD: return cmvr::api::BioHead;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_CAMERA: return cmvr::api::Camera;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_CAN_BUS: return cmvr::api::CanBus;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_DEX_HAND: return cmvr::api::DexHand;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_GRIPPER: return cmvr::api::Gripper;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_MICROPHONE: return cmvr::api::Microphone;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_MOTOR: return cmvr::api::Motor;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_MOTOR_SYSTEM: return cmvr::api::MotorSystem;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_MUJOCO_VIEWER: return cmvr::api::MujocoViewer;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_MUJOCO_WORLD: return cmvr::api::MujocoWorld;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_SPEAKER: return cmvr::api::Speaker;
|
|
|
|
|
|
case cmvr::api::DEVICE_KIND_UNKNOWN:
|
|
|
|
|
|
default: return fallback;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
QVariantList deviceListFromStatus(const cmvr::api::GetSystemStatusCommand::Feedback &response)
|
|
|
|
|
|
{
|
|
|
|
|
|
QVariantList devices;
|
|
|
|
|
|
devices.reserve(response.device_list_size());
|
|
|
|
|
|
for (const auto &device : response.device_list()) {
|
|
|
|
|
|
QVariantMap item;
|
|
|
|
|
|
const auto deviceType = deviceTypeFromKind(device.device_kind(), device.device_type());
|
|
|
|
|
|
item.insert(QStringLiteral("deviceId"), QString::fromStdString(device.device_id()));
|
|
|
|
|
|
item.insert(QStringLiteral("type"), static_cast<int>(deviceType));
|
|
|
|
|
|
item.insert(QStringLiteral("typeName"),
|
|
|
|
|
|
QString::fromStdString(cmvr::api::DeviceType_Name(deviceType)));
|
|
|
|
|
|
item.insert(QStringLiteral("deviceKind"), static_cast<int>(device.device_kind()));
|
|
|
|
|
|
item.insert(QStringLiteral("deviceKindName"),
|
|
|
|
|
|
QString::fromStdString(cmvr::api::DeviceKind_Name(device.device_kind())));
|
|
|
|
|
|
item.insert(QStringLiteral("driverType"),
|
|
|
|
|
|
QString::fromStdString(device.driver_type()));
|
|
|
|
|
|
item.insert(QStringLiteral("vendor"), QString::fromStdString(device.vendor()));
|
|
|
|
|
|
item.insert(QStringLiteral("online"), true);
|
|
|
|
|
|
devices.append(item);
|
|
|
|
|
|
}
|
|
|
|
|
|
return devices;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
|
2026-09-23 11:11:49 +08:00
|
|
|
|
QVariantList demoDeviceList()
|
|
|
|
|
|
{
|
|
|
|
|
|
QVariantList devices;
|
|
|
|
|
|
const QList<QVariantMap> definitions = {
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("right_arm")},
|
|
|
|
|
|
{QStringLiteral("type"), 6}, {QStringLiteral("deviceKind"), 2},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("AuboARM")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("AUBO")}},
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("hikvision_camera")},
|
|
|
|
|
|
{QStringLiteral("type"), 2}, {QStringLiteral("deviceKind"), 5},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("HikvisionCamera")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("HIKVISION")}},
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("src1100_agv")},
|
|
|
|
|
|
{QStringLiteral("type"), 0}, {QStringLiteral("deviceKind"), 1},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("SeerRobokitAgv")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("SEER")}},
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("dexterous_hand")},
|
|
|
|
|
|
{QStringLiteral("type"), 3}, {QStringLiteral("deviceKind"), 7},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("RH56DFTPDexhand")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("Inspire Robots")}},
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("meeting_microphone")},
|
|
|
|
|
|
{QStringLiteral("type"), 5}, {QStringLiteral("deviceKind"), 9},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("FFMpegMicroPhone")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("FFmpeg")}},
|
|
|
|
|
|
{{QStringLiteral("deviceId"), QStringLiteral("speaker")},
|
|
|
|
|
|
{QStringLiteral("type"), 7}, {QStringLiteral("deviceKind"), 15},
|
|
|
|
|
|
{QStringLiteral("driverType"), QStringLiteral("FFMpegSpeaker")},
|
|
|
|
|
|
{QStringLiteral("vendor"), QStringLiteral("FFmpeg")}},
|
|
|
|
|
|
};
|
|
|
|
|
|
for (const auto &definition : definitions) {
|
|
|
|
|
|
QVariantMap device = definition;
|
|
|
|
|
|
device.insert(QStringLiteral("online"), true);
|
|
|
|
|
|
devices.append(device);
|
|
|
|
|
|
}
|
|
|
|
|
|
return devices;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QStringList armJointNamesForDevice(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString prefix = deviceId.contains(QStringLiteral("left"), Qt::CaseInsensitive)
|
|
|
|
|
|
? QStringLiteral("L_") : QStringLiteral("R_");
|
|
|
|
|
|
return {
|
|
|
|
|
|
prefix + QStringLiteral("SHOULDER_P"), prefix + QStringLiteral("SHOULDER_R"),
|
|
|
|
|
|
prefix + QStringLiteral("SHOULDER_Y"), prefix + QStringLiteral("ELBOW_R"),
|
|
|
|
|
|
prefix + QStringLiteral("WRIST_P"), prefix + QStringLiteral("WRIST_Y"),
|
|
|
|
|
|
prefix + QStringLiteral("WRIST_R")
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
VideoFrame videoFrameFromImage(const QImage &image)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
|
|
|
|
|
|
VideoFrame frame;
|
|
|
|
|
|
frame.width = rgba.width();
|
|
|
|
|
|
frame.height = rgba.height();
|
|
|
|
|
|
frame.format = VideoPixelFormat::RGBA;
|
|
|
|
|
|
frame.stride0 = frame.width * 4;
|
|
|
|
|
|
frame.plane0.resize(frame.width * frame.height * 4);
|
|
|
|
|
|
for (int row = 0; row < frame.height; ++row) {
|
|
|
|
|
|
std::memcpy(frame.plane0.data() + row * frame.width * 4,
|
|
|
|
|
|
rgba.constScanLine(row), static_cast<size_t>(frame.width * 4));
|
|
|
|
|
|
}
|
|
|
|
|
|
return frame;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
2026-10-14 17:15:46 +08:00
|
|
|
|
QImage depthImageFromFrame(const cmvr::api::FrameData &frame)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (frame.width() <= 0 || frame.height() <= 0)
|
|
|
|
|
|
return {};
|
|
|
|
|
|
const bool uint16Depth = frame.type() == cmvr::api::FrameData::U16C1;
|
|
|
|
|
|
const bool floatDepth = frame.type() == cmvr::api::FrameData::F32C1;
|
|
|
|
|
|
const int bytesPerPixel = uint16Depth ? 2 : (floatDepth ? 4 : 0);
|
|
|
|
|
|
if (bytesPerPixel == 0
|
|
|
|
|
|
|| frame.data().size() < frame.width() * frame.height() * bytesPerPixel)
|
|
|
|
|
|
return {};
|
|
|
|
|
|
|
|
|
|
|
|
QImage image(frame.width(), frame.height(), QImage::Format_RGB888);
|
|
|
|
|
|
const char *source = frame.data().data();
|
|
|
|
|
|
for (int y = 0; y < frame.height(); ++y) {
|
|
|
|
|
|
uchar *destination = image.scanLine(y);
|
|
|
|
|
|
for (int x = 0; x < frame.width(); ++x) {
|
|
|
|
|
|
const int index = y * frame.width() + x;
|
|
|
|
|
|
double metres = 0.0;
|
|
|
|
|
|
if (uint16Depth) {
|
|
|
|
|
|
quint16 millimetres = 0;
|
|
|
|
|
|
std::memcpy(&millimetres, source + index * 2, sizeof(millimetres));
|
|
|
|
|
|
metres = millimetres / 1000.0;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
float value = 0.0f;
|
|
|
|
|
|
std::memcpy(&value, source + index * 4, sizeof(value));
|
|
|
|
|
|
metres = value;
|
|
|
|
|
|
}
|
|
|
|
|
|
QColor color(Qt::black);
|
|
|
|
|
|
if (std::isfinite(metres) && metres > 0.0) {
|
|
|
|
|
|
const double normalized = qBound(0.0, metres / 5.0, 1.0);
|
|
|
|
|
|
color = QColor::fromHsvF(normalized * 0.66, 0.9, 1.0);
|
|
|
|
|
|
}
|
|
|
|
|
|
destination[x * 3] = static_cast<uchar>(color.red());
|
|
|
|
|
|
destination[x * 3 + 1] = static_cast<uchar>(color.green());
|
|
|
|
|
|
destination[x * 3 + 2] = static_cast<uchar>(color.blue());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return image;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
VideoFrame videoFrameFromDepth(const cmvr::api::FrameData &frame)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (frame.width() <= 0 || frame.height() <= 0 ||
|
|
|
|
|
|
frame.type() != cmvr::api::FrameData::U16C1 ||
|
|
|
|
|
|
frame.data().size() < frame.width() * frame.height() * 2) {
|
|
|
|
|
|
return {};
|
|
|
|
|
|
}
|
|
|
|
|
|
QImage gray(frame.width(), frame.height(), QImage::Format_Grayscale8);
|
|
|
|
|
|
const auto *source = reinterpret_cast<const uchar *>(frame.data().data());
|
|
|
|
|
|
for (int y = 0; y < frame.height(); ++y) {
|
|
|
|
|
|
uchar *destination = gray.scanLine(y);
|
|
|
|
|
|
for (int x = 0; x < frame.width(); ++x) {
|
|
|
|
|
|
quint16 millimeters = 0;
|
|
|
|
|
|
std::memcpy(&millimeters,
|
|
|
|
|
|
source + (y * frame.width() + x) * sizeof(quint16),
|
|
|
|
|
|
sizeof(quint16));
|
|
|
|
|
|
const int clamped = std::min<int>(millimeters, 5000);
|
|
|
|
|
|
destination[x] = static_cast<uchar>(255 - (clamped * 255 / 5000));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return videoFrameFromImage(gray);
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
class BackendWorker : public QObject
|
|
|
|
|
|
{
|
|
|
|
|
|
public:
|
|
|
|
|
|
struct CameraStreamSession {
|
|
|
|
|
|
QString cameraId;
|
|
|
|
|
|
QString codec;
|
|
|
|
|
|
QString mode = QStringLiteral("rgb");
|
|
|
|
|
|
std::atomic<bool> stop{false};
|
|
|
|
|
|
std::atomic<bool> running{false};
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::atomic<bool> superseded{false};
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::thread thread;
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
grpc::ClientContext *context = nullptr;
|
|
|
|
|
|
std::mutex contextMutex;
|
|
|
|
|
|
#endif
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
struct ArmMotionSession {
|
|
|
|
|
|
std::atomic<bool> stop{false};
|
|
|
|
|
|
std::atomic<bool> running{false};
|
|
|
|
|
|
std::thread thread;
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
grpc::ClientContext *context = nullptr;
|
2026-10-20 16:49:27 +08:00
|
|
|
|
std::vector<std::shared_ptr<grpc::ClientContext>> groupContexts;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::mutex contextMutex;
|
|
|
|
|
|
#endif
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
explicit BackendWorker(QObject *parent = nullptr)
|
|
|
|
|
|
: QObject(parent)
|
|
|
|
|
|
{
|
|
|
|
|
|
m_pollTimer = new QTimer(this);
|
|
|
|
|
|
m_pollTimer->setInterval(100);
|
|
|
|
|
|
connect(m_pollTimer, &QTimer::timeout, this, &BackendWorker::poll);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
~BackendWorker() override
|
|
|
|
|
|
{
|
|
|
|
|
|
stopArmMotionInternal();
|
|
|
|
|
|
stopCameraStreamInternal();
|
|
|
|
|
|
stopSpeakerStreamInternal(true);
|
|
|
|
|
|
stopMicrophoneStreamInternal();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
stopDexHandTactileStreamInternal();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
stopAgvMapStreamInternal();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
|
void connectToServer(const QString &host, int port, bool demoMode)
|
|
|
|
|
|
{
|
2026-10-16 09:39:44 +08:00
|
|
|
|
// A failed gRPC channel can leave stubs and stream threads alive even
|
|
|
|
|
|
// though the server has disappeared. Always rebuild from a clean
|
|
|
|
|
|
// transport before accepting a new connection request.
|
|
|
|
|
|
if (m_connected
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
|| m_channel
|
|
|
|
|
|
#endif
|
|
|
|
|
|
) {
|
|
|
|
|
|
disconnectFromServer();
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_host = host.trimmed();
|
|
|
|
|
|
m_port = port;
|
|
|
|
|
|
m_demoMode = demoMode;
|
|
|
|
|
|
m_tick = 0;
|
2026-10-26 17:35:27 +08:00
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
m_jointTelemetryOnly = false;
|
|
|
|
|
|
m_legacyArmDiscovery.clear();
|
|
|
|
|
|
m_armFrameDefaults.clear();
|
|
|
|
|
|
#endif
|
2026-09-18 16:22:20 +08:00
|
|
|
|
|
|
|
|
|
|
if (m_host.isEmpty()) {
|
|
|
|
|
|
emit connectionChanged(false, 0, QStringLiteral("主机地址不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_connected = true;
|
|
|
|
|
|
m_pollTimer->start();
|
|
|
|
|
|
emit connectionChanged(true, 8, QStringLiteral("演示数据源"));
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"),
|
|
|
|
|
|
QStringLiteral("已启动演示模式,界面数据由本地模拟器生成"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const std::string endpoint = QStringLiteral("%1:%2").arg(m_host).arg(m_port).toStdString();
|
|
|
|
|
|
m_channel = createGrpcChannel(endpoint);
|
|
|
|
|
|
QElapsedTimer elapsed;
|
|
|
|
|
|
elapsed.start();
|
|
|
|
|
|
const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1200);
|
|
|
|
|
|
if (!m_channel->WaitForConnected(deadline)) {
|
|
|
|
|
|
m_connected = false;
|
|
|
|
|
|
emit connectionChanged(false, 0, QStringLiteral("连接超时,请检查地址和服务状态"));
|
|
|
|
|
|
emit logMessage(QStringLiteral("ERROR"), QStringLiteral("gRPC 通道连接超时:%1").arg(QString::fromStdString(endpoint)));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_arm = cmvr::api::ArmService::NewStub(m_channel);
|
|
|
|
|
|
m_camera = cmvr::api::CameraService::NewStub(m_channel);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
m_dexHand = cmvr::api::DexHandService::NewStub(m_channel);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_system = cmvr::api::SystemService::NewStub(m_channel);
|
|
|
|
|
|
m_agv = cmvr::api::AgvService::NewStub(m_channel);
|
|
|
|
|
|
m_microphone = cmvr::api::MicPhoneService::NewStub(m_channel);
|
|
|
|
|
|
m_generic = std::make_unique<grpc::GenericStub>(m_channel);
|
|
|
|
|
|
m_connected = true;
|
2026-10-16 09:39:44 +08:00
|
|
|
|
m_channelFailureTicks = 0;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_pollTimer->start();
|
|
|
|
|
|
emit connectionChanged(true, static_cast<int>(elapsed.elapsed()), QString::fromStdString(endpoint));
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"), QStringLiteral("gRPC 通道已连接:%1").arg(QString::fromStdString(endpoint)));
|
|
|
|
|
|
#else
|
|
|
|
|
|
m_connected = false;
|
|
|
|
|
|
emit connectionChanged(false, 0, QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
emit logMessage(QStringLiteral("ERROR"),
|
|
|
|
|
|
QStringLiteral("请使用 CMake 和 gRPC C++ 依赖重新构建,或启用演示模式"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void disconnectFromServer()
|
|
|
|
|
|
{
|
|
|
|
|
|
m_pollTimer->stop();
|
|
|
|
|
|
stopArmMotionInternal();
|
|
|
|
|
|
stopCameraStreamInternal();
|
|
|
|
|
|
stopSpeakerStreamInternal(true);
|
|
|
|
|
|
stopMicrophoneStreamInternal();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
stopDexHandTactileStreamInternal();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
stopAgvMapStreamInternal();
|
|
|
|
|
|
if (m_cameraRecording) {
|
|
|
|
|
|
m_cameraRecording = false;
|
|
|
|
|
|
emit cameraRecordingStateChanged(false, QStringLiteral("连接已断开,录像状态未知"));
|
|
|
|
|
|
}
|
|
|
|
|
|
m_connected = false;
|
2026-10-16 09:39:44 +08:00
|
|
|
|
m_channelFailureTicks = 0;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_armPollingEnabled = false;
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
m_arm.reset();
|
|
|
|
|
|
m_camera.reset();
|
2026-10-16 09:39:44 +08:00
|
|
|
|
m_dexHand.reset();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_system.reset();
|
|
|
|
|
|
m_agv.reset();
|
|
|
|
|
|
m_microphone.reset();
|
|
|
|
|
|
m_generic.reset();
|
|
|
|
|
|
m_channel.reset();
|
|
|
|
|
|
#endif
|
|
|
|
|
|
emit connectionChanged(false, 0, QStringLiteral("已断开"));
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"), QStringLiteral("连接已断开"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void connectConfigurationServer(const QString &host, int port)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString trimmedHost = host.trimmed();
|
|
|
|
|
|
if (trimmedHost.isEmpty()) {
|
|
|
|
|
|
emit configurationConnectionChanged(false, QStringLiteral("主机地址不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const std::string endpoint = QStringLiteral("%1:%2").arg(trimmedHost).arg(port).toStdString();
|
|
|
|
|
|
m_configChannel = createGrpcChannel(endpoint);
|
|
|
|
|
|
const auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(1500);
|
|
|
|
|
|
if (!m_configChannel->WaitForConnected(deadline)) {
|
|
|
|
|
|
m_configuration.reset();
|
|
|
|
|
|
m_configChannel.reset();
|
|
|
|
|
|
m_configConnected = false;
|
|
|
|
|
|
emit configurationConnectionChanged(
|
|
|
|
|
|
false, QStringLiteral("配置服务连接超时:%1").arg(QString::fromStdString(endpoint)));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_configuration = cmvr::api::ConfigurationService::NewStub(m_configChannel);
|
|
|
|
|
|
m_configConnected = true;
|
|
|
|
|
|
emit configurationConnectionChanged(
|
|
|
|
|
|
true, QStringLiteral("已连接配置服务:%1").arg(QString::fromStdString(endpoint)));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(port)
|
|
|
|
|
|
emit configurationConnectionChanged(false, QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void disconnectConfigurationServer()
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
m_configuration.reset();
|
|
|
|
|
|
m_configChannel.reset();
|
|
|
|
|
|
#endif
|
|
|
|
|
|
m_configConnected = false;
|
|
|
|
|
|
emit configurationConnectionChanged(false, QStringLiteral("配置服务已断开"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void listConfigurationFiles()
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!ensureConfigurationConnected(QStringLiteral("读取配置列表")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
cmvr::api::ListConfigFilesCommand::Request request;
|
|
|
|
|
|
cmvr::api::ListConfigFilesCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_configuration->ListConfigFiles(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
QVariantList files;
|
|
|
|
|
|
if (success) {
|
|
|
|
|
|
for (const auto &file : response.files()) {
|
|
|
|
|
|
QVariantMap item;
|
|
|
|
|
|
item.insert(QStringLiteral("relativePath"), QString::fromStdString(file.relative_path()));
|
|
|
|
|
|
item.insert(QStringLiteral("sizeBytes"), QVariant::fromValue<qulonglong>(file.size_bytes()));
|
|
|
|
|
|
item.insert(QStringLiteral("modifiedUnixMs"), QVariant::fromValue<qlonglong>(file.modified_unix_ms()));
|
|
|
|
|
|
item.insert(QStringLiteral("messageType"), QString::fromStdString(file.message_type()));
|
|
|
|
|
|
files.append(item);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
emit configurationFilesReceived(
|
|
|
|
|
|
QString::fromStdString(response.config_root()), files, success,
|
|
|
|
|
|
configurationError(status, response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void readConfigurationFile(const QString &relativePath)
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!ensureConfigurationConnected(QStringLiteral("读取配置文件")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
cmvr::api::ReadConfigFileCommand::Request request;
|
|
|
|
|
|
request.set_relative_path(relativePath.toStdString());
|
|
|
|
|
|
cmvr::api::ReadConfigFileCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_configuration->ReadConfigFile(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
emit configurationFileReceived(
|
|
|
|
|
|
relativePath,
|
|
|
|
|
|
success ? QString::fromStdString(response.content()) : QString(),
|
|
|
|
|
|
success ? QString::fromStdString(response.revision()) : QString(),
|
|
|
|
|
|
success ? QString::fromStdString(response.file().message_type()) : QString(),
|
|
|
|
|
|
success, configurationError(status, response.header().error_message()));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(relativePath)
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void validateConfigurationFile(const QString &relativePath, const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!ensureConfigurationConnected(QStringLiteral("校验配置文件")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
cmvr::api::ValidateConfigFileCommand::Request request;
|
|
|
|
|
|
request.set_relative_path(relativePath.toStdString());
|
|
|
|
|
|
request.set_content(content.toStdString());
|
|
|
|
|
|
cmvr::api::ValidateConfigFileCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_configuration->ValidateConfigFile(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
QString detail = configurationError(status, response.header().error_message());
|
|
|
|
|
|
if (success)
|
|
|
|
|
|
detail = QStringLiteral("配置有效:%1").arg(QString::fromStdString(response.message_type()));
|
|
|
|
|
|
emit configurationValidationFinished(relativePath, success, detail);
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(relativePath)
|
|
|
|
|
|
Q_UNUSED(content)
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void saveConfigurationFile(const QString &relativePath, const QString &content,
|
|
|
|
|
|
const QString &expectedRevision)
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!ensureConfigurationConnected(QStringLiteral("保存配置文件")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
cmvr::api::SaveConfigFileCommand::Request request;
|
|
|
|
|
|
request.set_relative_path(relativePath.toStdString());
|
|
|
|
|
|
request.set_content(content.toStdString());
|
|
|
|
|
|
request.set_expected_revision(expectedRevision.toStdString());
|
|
|
|
|
|
cmvr::api::SaveConfigFileCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 5000);
|
|
|
|
|
|
const grpc::Status status = m_configuration->SaveConfigFile(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
emit configurationSaveFinished(
|
|
|
|
|
|
relativePath, success ? QString::fromStdString(response.revision()) : QString(),
|
|
|
|
|
|
success, configurationError(status, response.header().error_message()));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(relativePath)
|
|
|
|
|
|
Q_UNUSED(content)
|
|
|
|
|
|
Q_UNUSED(expectedRevision)
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void setArmTelemetry(const QString &deviceId, bool enabled)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (enabled && !ensureConnected(QStringLiteral("Arm Telemetry")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (enabled && !ensureDeviceId(QStringLiteral("Arm Telemetry"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
const QString nextDeviceId = enabled ? deviceId.trimmed() : QString();
|
2026-09-23 11:11:49 +08:00
|
|
|
|
if (m_armDeviceId != nextDeviceId) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_demoTargets.clear();
|
2026-09-23 11:11:49 +08:00
|
|
|
|
m_armBaseFrame.clear();
|
|
|
|
|
|
m_armTcpFrame.clear();
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_armDeviceId = nextDeviceId;
|
|
|
|
|
|
m_armPollingEnabled = enabled;
|
|
|
|
|
|
m_consecutivePollErrors = 0;
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Arm Telemetry"), true,
|
|
|
|
|
|
enabled ? QStringLiteral("机械臂遥测已启动")
|
|
|
|
|
|
: QStringLiteral("机械臂遥测已停止"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void getArmInfo(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("GetArmInfo"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("GetArmInfo"), deviceId)) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantMap info;
|
|
|
|
|
|
info.insert(QStringLiteral("deviceId"), deviceId.trimmed());
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
const QStringList jointNames = armJointNamesForDevice(deviceId);
|
|
|
|
|
|
info.insert(QStringLiteral("manufacturer"), QStringLiteral("CMVR"));
|
|
|
|
|
|
info.insert(QStringLiteral("model"), QStringLiteral("demo_arm"));
|
|
|
|
|
|
info.insert(QStringLiteral("descriptionId"), QStringLiteral("demo_arm"));
|
|
|
|
|
|
info.insert(QStringLiteral("dof"), jointNames.size());
|
|
|
|
|
|
info.insert(QStringLiteral("jointNames"), jointNames);
|
|
|
|
|
|
info.insert(QStringLiteral("detectedFromSdk"), false);
|
|
|
|
|
|
emit armInfoReceived(deviceId.trimmed(), info);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetArmInfo::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::GetArmInfo::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1200);
|
|
|
|
|
|
const grpc::Status status = m_arm->GetArmInfo(&context, request, &response);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED) {
|
|
|
|
|
|
cmvr::api::JointRequest jointRequest;
|
|
|
|
|
|
fillHeader(jointRequest.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::JointResponse jointResponse;
|
|
|
|
|
|
grpc::ClientContext jointContext;
|
|
|
|
|
|
setDeadline(jointContext, 1200);
|
|
|
|
|
|
const auto jointStatus = m_arm->getJointState(&jointContext, jointRequest, &jointResponse);
|
|
|
|
|
|
QStringList names;
|
|
|
|
|
|
if (!jointStatus.ok() || !jointResponse.header().success()
|
|
|
|
|
|
|| !confirmedJointNames(jointResponse.state(), names)) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("GetArmInfo"), false,
|
|
|
|
|
|
QStringLiteral("服务端未提供 GetArmInfo,关节信息读取失败:%1").arg(
|
|
|
|
|
|
!jointStatus.ok() ? QString::fromStdString(jointStatus.error_message())
|
|
|
|
|
|
: QStringLiteral("关节名称或位置缺失、重复或无效")));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
info.insert(QStringLiteral("dof"), names.size());
|
|
|
|
|
|
info.insert(QStringLiteral("jointNames"), names);
|
|
|
|
|
|
info.insert(QStringLiteral("source"), QStringLiteral("getJointState"));
|
|
|
|
|
|
emit armInfoReceived(deviceId.trimmed(), info);
|
|
|
|
|
|
emit commandFinished(QStringLiteral("GetArmInfo"), true,
|
|
|
|
|
|
QStringLiteral("已从关节接口读取 %1 轴信息;型号和整体使能状态由服务端提供后显示")
|
|
|
|
|
|
.arg(names.size()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
const QString detail = status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
|
|
|
|
|
emit commandFinished(QStringLiteral("GetArmInfo"), false, detail);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QStringList jointNames;
|
|
|
|
|
|
jointNames.reserve(response.joint_names_size());
|
|
|
|
|
|
for (const auto &name : response.joint_names())
|
|
|
|
|
|
jointNames.append(QString::fromStdString(name));
|
|
|
|
|
|
info.insert(QStringLiteral("manufacturer"), QString::fromStdString(response.manufacturer()));
|
|
|
|
|
|
info.insert(QStringLiteral("model"), QString::fromStdString(response.model()));
|
|
|
|
|
|
info.insert(QStringLiteral("subtype"), QString::fromStdString(response.subtype()));
|
|
|
|
|
|
info.insert(QStringLiteral("dof"), static_cast<int>(response.dof()));
|
|
|
|
|
|
info.insert(QStringLiteral("jointNames"), jointNames);
|
|
|
|
|
|
info.insert(QStringLiteral("defaultBaseFrame"), QString::fromStdString(response.default_base_frame()));
|
|
|
|
|
|
info.insert(QStringLiteral("defaultTcpFrame"), QString::fromStdString(response.default_tcp_frame()));
|
|
|
|
|
|
info.insert(QStringLiteral("descriptionId"), QString::fromStdString(response.description_id()));
|
|
|
|
|
|
info.insert(QStringLiteral("detectedFromSdk"), response.detected_from_sdk());
|
|
|
|
|
|
info.insert(QStringLiteral("driverType"), QString::fromStdString(response.driver_type()));
|
2026-10-26 17:35:27 +08:00
|
|
|
|
m_armFrameDefaults.insert(deviceId.trimmed(),
|
|
|
|
|
|
{QString::fromStdString(response.default_base_frame()).trimmed(),
|
|
|
|
|
|
QString::fromStdString(response.default_tcp_frame()).trimmed()});
|
2026-09-23 11:11:49 +08:00
|
|
|
|
emit armInfoReceived(deviceId.trimmed(), info);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-04 15:00:14 +08:00
|
|
|
|
void userCoordinates(const QString &deviceId, const QVariantMap ¶meters, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString service = QStringLiteral("cmvr.user_coordinates");
|
|
|
|
|
|
const bool move = parameters.value("operation").toString() == "move";
|
|
|
|
|
|
const QString command = QStringLiteral("User Frame Move:%1").arg(token);
|
|
|
|
|
|
const auto fail = [&](const QString &why) {
|
|
|
|
|
|
if (move) emit commandFinished(command,false,why);
|
|
|
|
|
|
else if (rpcFinished) rpcFinished(service,QString::number(token),false,why);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (!ensureConnected(service) || !ensureDeviceId(service,deviceId)) { fail(QStringLiteral("设备未连接")); return; }
|
|
|
|
|
|
if (m_demoMode) { fail(QStringLiteral("演示模式不应用坐标系或运动")); return; }
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (move) {
|
|
|
|
|
|
cmvr::api::MoveL::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(),deviceId,kArmMotionTimeoutMs);
|
|
|
|
|
|
const auto values = parameters.value("target").toList();
|
|
|
|
|
|
const auto name=parameters.value("name").toString();
|
|
|
|
|
|
if (values.size()!=6 || name.isEmpty()) { fail(QStringLiteral("请选择服务端坐标系并提供六维目标")); return; }
|
|
|
|
|
|
request.set_coordinate_relative_translation(parameters.value("relative_translation").toBool());
|
|
|
|
|
|
request.set_user_coordinate_name(name.toStdString());
|
|
|
|
|
|
request.set_user_coordinate_revision(parameters.value("revision").toString().toULongLong());
|
|
|
|
|
|
auto *p=request.mutable_target();
|
|
|
|
|
|
p->set_x(values[0].toDouble()); p->set_y(values[1].toDouble()); p->set_z(values[2].toDouble());
|
|
|
|
|
|
p->set_rx(values[3].toDouble()); p->set_ry(values[4].toDouble()); p->set_rz(values[5].toDouble());
|
|
|
|
|
|
request.mutable_options()->set_velocity(parameters.value("velocity").toDouble());
|
|
|
|
|
|
request.mutable_options()->set_acceleration(parameters.value("acceleration").toDouble());
|
|
|
|
|
|
startArmMotion<cmvr::api::MoveL::Request,cmvr::api::MoveL::Response>(command,std::move(request),
|
|
|
|
|
|
[](cmvr::api::ArmService::Stub &stub,grpc::ClientContext *ctx,const cmvr::api::MoveL::Request &q,cmvr::api::MoveL::Response *r) {
|
|
|
|
|
|
// Old servers silently ignore unknown protobuf fields. A
|
|
|
|
|
|
// positive capability handshake is mandatory before moving.
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Request probe;
|
|
|
|
|
|
*probe.mutable_header()=q.header();
|
|
|
|
|
|
probe.set_request_json("{\"command\":\"get_active_tcp_offset\"}");
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Feedback feedback;
|
|
|
|
|
|
grpc::ClientContext probeContext;setDeadline(probeContext,3000);
|
|
|
|
|
|
const auto status=stub.ExecuteJsonCommand(&probeContext,probe,&feedback);
|
|
|
|
|
|
const auto data=QJsonDocument::fromJson(QByteArray::fromStdString(feedback.response_json())).object();
|
|
|
|
|
|
if(!status.ok() || !feedback.header().success() || data.value("coordinate_api_version").toInt()<3
|
|
|
|
|
|
|| data.value("device_id").toString()!=QString::fromStdString(q.header().device_id()))
|
|
|
|
|
|
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,"Server does not confirm explicit user-frame support; no motion sent");
|
|
|
|
|
|
return stub.moveL(ctx,q,r);
|
|
|
|
|
|
});
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString operation=parameters.value("operation").toString();
|
|
|
|
|
|
if(operation=="pose" || operation=="selected_pose") {
|
|
|
|
|
|
// The server returns and labels the requested reference. No client-side conversion.
|
|
|
|
|
|
cmvr::api::GetPose::Request q;fillHeader(q.mutable_header(),deviceId);
|
|
|
|
|
|
const QString reference=operation=="selected_pose"?parameters.value("name").toString():QStringLiteral("base");
|
|
|
|
|
|
q.set_base_link(reference.toStdString());q.set_ee_link("tcp");
|
|
|
|
|
|
const auto expected=reference=="__builtin_base__"?std::string("base"):reference.toStdString();
|
|
|
|
|
|
cmvr::api::GetPose::Response r;
|
|
|
|
|
|
grpc::ClientContext ctx;setDeadline(ctx,3000);
|
|
|
|
|
|
const auto status=m_arm->getPose(&ctx,q,&r);
|
|
|
|
|
|
if(!status.ok()||!r.header().success()) {
|
|
|
|
|
|
fail(QString::fromStdString(status.ok()?r.header().error_message():status.error_message()));return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if(!r.has_pose()||r.reference_frame()!=expected||r.end_frame()!="tcp") {
|
|
|
|
|
|
fail(QStringLiteral("GetPose返回的参考系或末端不匹配,请检查服务端版本"));return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto& p=r.pose();
|
|
|
|
|
|
QJsonArray values;
|
|
|
|
|
|
for(double v:{p.x(),p.y(),p.z(),p.rx(),p.ry(),p.rz()}) {
|
|
|
|
|
|
if(!std::isfinite(v)){fail(QStringLiteral("实际 TCP 位姿包含无效数值"));return;}
|
|
|
|
|
|
values.append(v);
|
|
|
|
|
|
}
|
|
|
|
|
|
const QJsonObject data{{"success",true},{"device_id",deviceId},{"operation","pose"},
|
|
|
|
|
|
{"pose",values},{"reference",QString::fromStdString(r.reference_frame())},
|
|
|
|
|
|
{"end_frame",QString::fromStdString(r.end_frame())},{"source","GetPose"},
|
|
|
|
|
|
{"received_at",QDateTime::currentDateTime().toString("HH:mm:ss.zzz")}};
|
|
|
|
|
|
if(rpcFinished)rpcFinished(service,QString::number(token),true,QString::fromUtf8(QJsonDocument(data).toJson(QJsonDocument::Compact)));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if(operation!="read") {
|
|
|
|
|
|
cmvr::api::UserCoordinateSystemCommand::Request q;
|
|
|
|
|
|
fillHeader(q.mutable_header(),deviceId);
|
|
|
|
|
|
q.set_name(parameters.value("name").toString().toStdString());
|
|
|
|
|
|
q.set_expected_revision(parameters.value("revision").toString().toULongLong());
|
|
|
|
|
|
if(operation=="create"||operation=="update"||operation=="calibrate") {
|
|
|
|
|
|
q.mutable_coordinate()->set_name(q.name());
|
|
|
|
|
|
q.mutable_coordinate()->set_calibration_version(2);
|
|
|
|
|
|
for(const auto& point:parameters.value("calibration_points").toList()) {
|
|
|
|
|
|
const auto a=point.toList();if(a.size()!=6){fail(QStringLiteral("每个标定点需要六维 Base TCP 位姿"));return;}
|
|
|
|
|
|
auto* p=q.mutable_coordinate()->add_calibration_points()->mutable_base_tcp_pose();
|
|
|
|
|
|
p->set_x(a[0].toDouble());p->set_y(a[1].toDouble());p->set_z(a[2].toDouble());
|
|
|
|
|
|
p->set_rx(a[3].toDouble());p->set_ry(a[4].toDouble());p->set_rz(a[5].toDouble());
|
|
|
|
|
|
}
|
|
|
|
|
|
for(const auto&v:parameters.value("user_pose").toList())q.mutable_coordinate()->add_user_pose(v.toDouble());
|
|
|
|
|
|
for(const auto&v:parameters.value("tcp_offset").toList())q.mutable_coordinate()->add_tcp_offset(v.toDouble());
|
|
|
|
|
|
}
|
|
|
|
|
|
grpc::ClientContext ctx;setDeadline(ctx,operation=="apply"?20000:5000);
|
|
|
|
|
|
cmvr::api::UserCoordinateSystemCommand::Response r;grpc::Status status;
|
|
|
|
|
|
if(operation=="calibrate")status=m_arm->CalibrateUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="create")status=m_arm->CreateUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="get")status=m_arm->GetUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="list")status=m_arm->ListUserCoordinateSystems(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="update")status=m_arm->UpdateUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="delete")status=m_arm->DeleteUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else if(operation=="apply")status=m_arm->ApplyUserCoordinateSystem(&ctx,q,&r);
|
|
|
|
|
|
else {fail(QStringLiteral("未知坐标操作"));return;}
|
|
|
|
|
|
if(!status.ok()||!r.header().success()){fail(QString::fromStdString(status.ok()?r.header().error_message():status.error_message()));return;}
|
|
|
|
|
|
const auto record=[](const cmvr::api::UserCoordinateSystem& p) {
|
|
|
|
|
|
QJsonArray user,tcp,points;for(double x:p.user_pose())user.append(x);for(double x:p.tcp_offset())tcp.append(x);
|
|
|
|
|
|
for(const auto& point:p.calibration_points()){const auto& v=point.base_tcp_pose();points.append(QJsonArray{v.x(),v.y(),v.z(),v.rx(),v.ry(),v.rz()});}
|
|
|
|
|
|
return QJsonObject{{"name",QString::fromStdString(p.name())},{"revision",QString::number(p.revision())},
|
|
|
|
|
|
{"calibration_points",points},{"calibration_version",int(p.calibration_version())},{"user_pose",user},{"tcp_offset",tcp},{"user_reference","base"},{"tcp_reference","flange"},{"units","m_rad"},{"rotation_convention","RzRyRx"}};
|
|
|
|
|
|
};
|
|
|
|
|
|
QJsonArray list,actual;for(const auto&p:r.coordinates())list.append(record(p));for(double x:r.actual_tcp_offset())actual.append(x);
|
|
|
|
|
|
const QJsonObject data{{"success",true},{"device_id",deviceId},{"operation",operation},
|
|
|
|
|
|
{"coordinate",record(r.coordinate())},{"coordinates",list},{"actual_tcp_offset",actual},
|
|
|
|
|
|
{"work_object_acknowledged",r.work_object_acknowledged()},
|
|
|
|
|
|
{"last_applied_name",QString::fromStdString(r.last_applied_name())},
|
|
|
|
|
|
{"last_applied_revision",QString::number(r.last_applied_revision())},{"application_known",r.application_known()}};
|
|
|
|
|
|
if(rpcFinished)rpcFinished(service,QString::number(token),true,QString::fromUtf8(QJsonDocument(data).toJson(QJsonDocument::Compact)));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(),deviceId);
|
|
|
|
|
|
QJsonObject payload = QJsonObject::fromVariantMap(parameters);
|
|
|
|
|
|
payload.insert("command",parameters.value("operation").toString()=="read"
|
|
|
|
|
|
? "get_active_tcp_offset" : "apply_user_coordinates");
|
|
|
|
|
|
request.set_request_json(QJsonDocument(payload).toJson(QJsonDocument::Compact).toStdString());
|
|
|
|
|
|
grpc::ClientContext context; setDeadline(context,5000);
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Feedback response;
|
|
|
|
|
|
const auto status=m_arm->ExecuteJsonCommand(&context,request,&response);
|
|
|
|
|
|
const bool ok=status.ok() && response.header().success();
|
|
|
|
|
|
const QString text=ok ? QString::fromStdString(response.response_json())
|
|
|
|
|
|
: QString::fromStdString(status.ok()?response.header().error_message():status.error_message());
|
|
|
|
|
|
if (rpcFinished) rpcFinished(service,QString::number(token),ok,text);
|
|
|
|
|
|
#else
|
|
|
|
|
|
fail(QStringLiteral("当前构建未启用 gRPC"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void getControllerTcpOffset(const QString &deviceId, quint64 requestId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString device = deviceId.trimmed();
|
|
|
|
|
|
const auto reject = [this, requestId, device](const QString &detail) {
|
|
|
|
|
|
controllerTcpOffsetReceived(requestId, device, {}, false, detail);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (m_demoMode || !m_connected || device.isEmpty()) {
|
|
|
|
|
|
reject(QStringLiteral("请连接真实机械臂后读取控制器 TCP 偏移"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!m_arm) { reject(QStringLiteral("机械臂服务不可用")); return; }
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), device);
|
|
|
|
|
|
request.set_request_json("{\"command\":\"get_active_tcp_offset\"}");
|
|
|
|
|
|
cmvr::api::JsonDeviceCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const auto status = m_arm->ExecuteJsonCommand(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
reject(QStringLiteral("读取活动 TCP 偏移失败:%1").arg(QString::fromStdString(
|
|
|
|
|
|
status.ok() ? response.header().error_message() : status.error_message())));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto json = QJsonDocument::fromJson(QByteArray::fromStdString(response.response_json())).object();
|
|
|
|
|
|
if (!json.value("success").toBool() || json.value("device_id").toString() != device
|
|
|
|
|
|
|| json.value("transform").toString() != "T_flange_tcp"
|
|
|
|
|
|
|| json.value("units").toString() != "m_rad"
|
|
|
|
|
|
|| json.value("rotation_convention").toString() != "RzRyRx") {
|
|
|
|
|
|
reject(QStringLiteral("控制器 TCP 偏移的设备身份或坐标约定不匹配"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto values = json.value("offset").toArray();
|
|
|
|
|
|
if (values.size() != 6) { reject(QStringLiteral("控制器 TCP 偏移维度错误")); return; }
|
|
|
|
|
|
const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"};
|
|
|
|
|
|
QVariantMap offset;
|
|
|
|
|
|
for (int i = 0; i < 6; ++i) {
|
|
|
|
|
|
if (!values[i].isDouble() || !std::isfinite(values[i].toDouble())) {
|
|
|
|
|
|
reject(QStringLiteral("控制器 TCP 偏移包含无效数值")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
offset.insert(QString::fromLatin1(keys[i]), values[i].toDouble());
|
|
|
|
|
|
}
|
|
|
|
|
|
controllerTcpOffsetReceived(requestId, device, offset, true, QString());
|
|
|
|
|
|
#else
|
|
|
|
|
|
reject(QStringLiteral("当前构建未启用 gRPC"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void getTcpCalibrationPose(const QString &deviceId, quint64 requestId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString selectedDevice = deviceId.trimmed();
|
|
|
|
|
|
const auto reject = [this, requestId, selectedDevice](const QString &detail) {
|
|
|
|
|
|
emit tcpCalibrationPoseReceived(requestId, selectedDevice, {}, {}, false, detail);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定不接受演示数据,请连接真实机械臂"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!m_connected || selectedDevice.isEmpty()) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:服务未连接或设备 ID 为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!m_arm) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:机械臂服务不可用"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::api::GetArmInfo::Request infoRequest;
|
|
|
|
|
|
fillHeader(infoRequest.mutable_header(), selectedDevice);
|
|
|
|
|
|
cmvr::api::GetArmInfo::Response info;
|
|
|
|
|
|
grpc::ClientContext infoContext;
|
|
|
|
|
|
setDeadline(infoContext, 1500);
|
|
|
|
|
|
const grpc::Status infoStatus = m_arm->GetArmInfo(&infoContext, infoRequest, &info);
|
|
|
|
|
|
if (!infoStatus.ok() || !info.header().success()
|
|
|
|
|
|
|| QString::fromStdString(info.device_id()).trimmed() != selectedDevice) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:无法确认机械臂驱动身份"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString driver = QString::fromStdString(info.driver_type()).trimmed().toLower();
|
|
|
|
|
|
const QString manufacturer = QString::fromStdString(info.manufacturer()).trimmed().toLower();
|
|
|
|
|
|
const bool auboDriver = driver == QStringLiteral("auboarm")
|
|
|
|
|
|
|| driver == QStringLiteral("aubo_arm");
|
|
|
|
|
|
const bool auboManufacturer = manufacturer == QStringLiteral("aubo")
|
|
|
|
|
|
|| manufacturer == QStringLiteral("auboarm");
|
|
|
|
|
|
if (!auboDriver && !(driver.isEmpty() && auboManufacturer)) {
|
|
|
|
|
|
reject(QStringLiteral("当前驱动尚未适配 TCP 标定所需的姿态及运动约定:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(info.driver_type())));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
// A fresh state request deliberately bypasses display telemetry and named
|
|
|
|
|
|
// getPose: some drivers silently ignore its requested base/flange names.
|
|
|
|
|
|
cmvr::api::GetRobotState::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), selectedDevice);
|
|
|
|
|
|
cmvr::api::GetRobotState::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1500);
|
|
|
|
|
|
const qint64 requestedAtMs = QDateTime::currentMSecsSinceEpoch();
|
|
|
|
|
|
const grpc::Status status = m_arm->getRobotState(&context, request, &response);
|
|
|
|
|
|
const qint64 receivedAtMs = QDateTime::currentMSecsSinceEpoch();
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
const QString error = status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定实时采样失败:%1").arg(error));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!response.has_state()) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:服务未返回机械臂状态"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &robotState = response.state();
|
|
|
|
|
|
if (!robotState.connected() || robotState.moving() || robotState.fault()
|
|
|
|
|
|
|| robotState.protective_stopped() || robotState.emergency_stopped()) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:机械臂未连接、正在运动或存在故障/停止状态"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if ((robotState.safety_mode() != cmvr::api::ARM_SAFETY_MODE_NORMAL
|
|
|
|
|
|
&& robotState.safety_mode() != cmvr::api::ARM_SAFETY_MODE_REDUCED)
|
|
|
|
|
|
|| (robotState.robot_mode() != cmvr::api::ARM_ROBOT_MODE_IDLE
|
|
|
|
|
|
&& robotState.robot_mode() != cmvr::api::ARM_ROBOT_MODE_PAUSED)) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:机械臂未处于可确认的静止安全状态"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!robotState.has_actual_tcp_pose() || !robotState.has_actual_joint_state()
|
|
|
|
|
|
|| !std::isfinite(robotState.timestamp()) || robotState.timestamp() < 0.0) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:缺少有效 TCP 位姿、关节状态或时间戳"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &joints = robotState.actual_joint_state();
|
|
|
|
|
|
if (info.dof() == 0 || joints.position_size() != static_cast<int>(info.dof())
|
|
|
|
|
|
|| joints.velocity_size() != joints.position_size()
|
|
|
|
|
|
|| (joints.name_size() != 0 && joints.name_size() != joints.position_size())) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:关节速度缺失或维度不一致"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
bool allJointsZero = true;
|
|
|
|
|
|
for (int i = 0; i < joints.position_size(); ++i) {
|
|
|
|
|
|
if (!std::isfinite(joints.position(i)) || !std::isfinite(joints.velocity(i))
|
|
|
|
|
|
|| std::abs(joints.velocity(i)) > 0.01) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:关节数据无效或机械臂尚未静止"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
allJointsZero = allJointsZero && joints.position(i) == 0.0 && joints.velocity(i) == 0.0;
|
|
|
|
|
|
}
|
|
|
|
|
|
// This backend also zero-fills joint arrays when an SDK read fails.
|
|
|
|
|
|
if (allJointsZero) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:关节反馈全零,无法排除 SDK 读取失败,请更换姿态后重试"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &tcp = robotState.actual_tcp_pose();
|
|
|
|
|
|
const double values[] = {tcp.x(), tcp.y(), tcp.z(), tcp.rx(), tcp.ry(), tcp.rz()};
|
|
|
|
|
|
bool allZero = true;
|
|
|
|
|
|
for (double value : values) {
|
|
|
|
|
|
if (!std::isfinite(value)) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:TCP 位姿包含非有限数值"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
allZero = allZero && value == 0.0;
|
|
|
|
|
|
}
|
|
|
|
|
|
// Existing AUBO backend returns a zero pose on SDK read failure.
|
|
|
|
|
|
if (allZero) {
|
|
|
|
|
|
reject(QStringLiteral("TCP 标定采样失败:服务返回全零位姿,无法排除 SDK 读取失败"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QVariantMap pose = {
|
|
|
|
|
|
{QStringLiteral("x"), tcp.x()}, {QStringLiteral("y"), tcp.y()},
|
|
|
|
|
|
{QStringLiteral("z"), tcp.z()}, {QStringLiteral("rx"), tcp.rx()},
|
|
|
|
|
|
{QStringLiteral("ry"), tcp.ry()}, {QStringLiteral("rz"), tcp.rz()}};
|
|
|
|
|
|
QVariantList capturedJoints; for(int i=0;i<joints.position_size();++i) capturedJoints.append(joints.position(i));
|
|
|
|
|
|
const QVariantMap state = {
|
|
|
|
|
|
{QStringLiteral("jointPositions"),capturedJoints},
|
|
|
|
|
|
{QStringLiteral("connected"), robotState.connected()},
|
|
|
|
|
|
{QStringLiteral("moving"), robotState.moving()},
|
|
|
|
|
|
{QStringLiteral("fault"), robotState.fault()},
|
|
|
|
|
|
{QStringLiteral("protectiveStopped"), robotState.protective_stopped()},
|
|
|
|
|
|
{QStringLiteral("emergencyStopped"), robotState.emergency_stopped()},
|
|
|
|
|
|
{QStringLiteral("timestamp"), robotState.timestamp()},
|
|
|
|
|
|
{QStringLiteral("serverTimestampAvailable"), robotState.timestamp() > 0.0},
|
|
|
|
|
|
{QStringLiteral("requestedAtMs"), requestedAtMs},
|
|
|
|
|
|
{QStringLiteral("receivedAtMs"), receivedAtMs},
|
|
|
|
|
|
{QStringLiteral("driverType"), QString::fromStdString(info.driver_type())},
|
|
|
|
|
|
{QStringLiteral("manufacturer"), QString::fromStdString(info.manufacturer())},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("getRobotState.actual_tcp_pose")}};
|
|
|
|
|
|
emit tcpCalibrationPoseReceived(requestId, selectedDevice, pose, state, true,
|
|
|
|
|
|
QStringLiteral("已实时读取当前 TCP 位姿;需用已确认的当前 TCP 偏置换算为法兰位姿"));
|
|
|
|
|
|
#else
|
|
|
|
|
|
reject(QStringLiteral("当前构建未启用 gRPC,无法采集真实 TCP 位姿"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-29 11:46:39 +08:00
|
|
|
|
void discoverArmFrames(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("ListBaseFrame"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("ListBaseFrame"), deviceId) || m_demoMode)
|
|
|
|
|
|
return;
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::ListFrame::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::ListFrame::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 30000);
|
|
|
|
|
|
// Manual diagnostic only: invoke the server's frame discovery without
|
|
|
|
|
|
// consuming its result or changing the UI's configured frame choices.
|
|
|
|
|
|
(void)m_arm->ListBaseFrame(&context, request, &response);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void getArmFrames(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("List Arm Frames"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("List Arm Frames"), deviceId)) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QStringList baseFrames;
|
|
|
|
|
|
QStringList tcpFrames;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
baseFrames << QStringLiteral("base0") << QStringLiteral("world");
|
|
|
|
|
|
tcpFrames << QStringLiteral("tool0") << QStringLiteral("flange");
|
|
|
|
|
|
emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
2026-10-26 17:35:27 +08:00
|
|
|
|
// No remote frame enumeration: some AUBO controllers do not implement
|
|
|
|
|
|
// SyncMove.frameGetChildren. Use only defaults returned by GetArmInfo.
|
|
|
|
|
|
const auto defaults = m_armFrameDefaults.value(deviceId.trimmed());
|
|
|
|
|
|
if (!defaults.first.isEmpty()) baseFrames.append(defaults.first);
|
|
|
|
|
|
if (!defaults.second.isEmpty()) tcpFrames.append(defaults.second);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
emit armFramesReceived(deviceId.trimmed(), baseFrames, tcpFrames);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void getCameraStatus(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Get Camera Status"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("Get Camera Status"), cameraId)) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantMap state;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
state.insert(QStringLiteral("codec"), QStringLiteral("h264"));
|
|
|
|
|
|
state.insert(QStringLiteral("fps"), 30);
|
|
|
|
|
|
state.insert(QStringLiteral("width"), 1280);
|
|
|
|
|
|
state.insert(QStringLiteral("height"), 720);
|
|
|
|
|
|
if (cameraStatusReceived)
|
|
|
|
|
|
cameraStatusReceived(cameraId.trimmed(), state);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetCameraStateCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::GetCameraStateCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1200);
|
|
|
|
|
|
const grpc::Status status = m_camera->GetStatus(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
const QString detail = status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Get Camera Status"), false, detail);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &cameraState = response.state();
|
|
|
|
|
|
state.insert(QStringLiteral("codec"), QString::fromStdString(cameraState.codec()));
|
|
|
|
|
|
state.insert(QStringLiteral("fps"), cameraState.fps());
|
|
|
|
|
|
state.insert(QStringLiteral("width"), cameraState.width());
|
|
|
|
|
|
state.insert(QStringLiteral("height"), cameraState.height());
|
|
|
|
|
|
state.insert(QStringLiteral("streaming"), cameraState.is_streaming());
|
|
|
|
|
|
if (cameraStatusReceived)
|
|
|
|
|
|
cameraStatusReceived(cameraId.trimmed(), state);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void getDexHandStatus(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Get DexHand Status"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("Get DexHand Status"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
QVariantList freedoms;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
for (int id = 0; id < 6; ++id) {
|
|
|
|
|
|
QVariantMap freedom;
|
|
|
|
|
|
freedom.insert(QStringLiteral("id"), id);
|
|
|
|
|
|
freedom.insert(QStringLiteral("angle"), id == 4 ? 280 : 120 + id * 70);
|
|
|
|
|
|
freedom.insert(QStringLiteral("position"), 240 + id * 120);
|
|
|
|
|
|
freedom.insert(QStringLiteral("speed"), 500);
|
|
|
|
|
|
freedom.insert(QStringLiteral("force"), 0);
|
|
|
|
|
|
freedom.insert(QStringLiteral("current"), 0);
|
|
|
|
|
|
freedom.insert(QStringLiteral("temperature"), 0);
|
|
|
|
|
|
freedom.insert(QStringLiteral("error"), 0);
|
|
|
|
|
|
freedoms.append(freedom);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (dexHandStatusReceived)
|
|
|
|
|
|
dexHandStatusReceived(deviceId.trimmed(), true, true,
|
|
|
|
|
|
QStringLiteral("Demo DexHand"), freedoms);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetDexHandStateCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::GetDexHandStateCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1200);
|
|
|
|
|
|
const grpc::Status status = m_dexHand->GetStatus(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Get DexHand Status"), false,
|
|
|
|
|
|
status.ok() ? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
for (const auto &item : response.state().hands()) {
|
|
|
|
|
|
QVariantMap freedom;
|
|
|
|
|
|
freedom.insert(QStringLiteral("id"), item.dof_id());
|
|
|
|
|
|
freedom.insert(QStringLiteral("angle"), item.angle());
|
|
|
|
|
|
freedom.insert(QStringLiteral("position"), item.position());
|
|
|
|
|
|
freedom.insert(QStringLiteral("speed"), item.speed());
|
|
|
|
|
|
freedom.insert(QStringLiteral("force"), item.force());
|
|
|
|
|
|
freedom.insert(QStringLiteral("current"), item.current());
|
|
|
|
|
|
freedom.insert(QStringLiteral("temperature"), item.temperature());
|
|
|
|
|
|
freedom.insert(QStringLiteral("error"), item.error());
|
|
|
|
|
|
QStringList errors;
|
|
|
|
|
|
for (const auto &message : item.error_message())
|
|
|
|
|
|
errors.append(QString::fromStdString(message));
|
|
|
|
|
|
freedom.insert(QStringLiteral("errors"), errors);
|
|
|
|
|
|
freedoms.append(freedom);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (dexHandStatusReceived)
|
|
|
|
|
|
dexHandStatusReceived(deviceId.trimmed(), response.state().is_initialized(),
|
|
|
|
|
|
response.state().has_tactile_feedback(),
|
|
|
|
|
|
QString::fromStdString(response.state().model()),
|
|
|
|
|
|
freedoms);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void setDexHandValues(const QString &deviceId, const QString &command,
|
|
|
|
|
|
const QVariantList &values)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString displayCommand = QStringLiteral("DexHand %1").arg(command);
|
|
|
|
|
|
if (!ensureConnected(displayCommand) || !ensureDeviceId(displayCommand, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (values.size() != 6) {
|
|
|
|
|
|
emit commandFinished(displayCommand, false, QStringLiteral("灵巧手命令必须包含 6 个自由度"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(displayCommand, true, QStringLiteral("演示命令已执行"));
|
|
|
|
|
|
getDexHandStatus(deviceId);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const auto fillValues = [&values](auto *request) {
|
|
|
|
|
|
for (int id = 0; id < values.size(); ++id) {
|
|
|
|
|
|
auto *value = request->add_values();
|
|
|
|
|
|
value->set_id(id);
|
|
|
|
|
|
value->set_value(static_cast<float>(values.at(id).toDouble()));
|
|
|
|
|
|
}
|
|
|
|
|
|
};
|
|
|
|
|
|
grpc::Status status;
|
|
|
|
|
|
bool success = false;
|
|
|
|
|
|
QString error;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2000);
|
|
|
|
|
|
if (command == QStringLiteral("angle")) {
|
|
|
|
|
|
cmvr::api::SetDexHandAnglesCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId); fillValues(&request);
|
|
|
|
|
|
cmvr::api::SetDexHandAnglesCommand::Feedback response;
|
|
|
|
|
|
status = m_dexHand->SetDexHandAngle(&context, request, &response);
|
|
|
|
|
|
success = status.ok() && response.header().success();
|
|
|
|
|
|
error = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
} else if (command == QStringLiteral("position")) {
|
|
|
|
|
|
cmvr::api::SetDexHandPositionsCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId); fillValues(&request);
|
|
|
|
|
|
cmvr::api::SetDexHandPositionsCommand::Feedback response;
|
|
|
|
|
|
status = m_dexHand->SetDexHandPos(&context, request, &response);
|
|
|
|
|
|
success = status.ok() && response.header().success();
|
|
|
|
|
|
error = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
} else if (command == QStringLiteral("speed")) {
|
|
|
|
|
|
cmvr::api::SetDexHandSpeedCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId); fillValues(&request);
|
|
|
|
|
|
cmvr::api::SetDexHandSpeedCommand::Feedback response;
|
|
|
|
|
|
status = m_dexHand->SetDexHandSpeed(&context, request, &response);
|
|
|
|
|
|
success = status.ok() && response.header().success();
|
|
|
|
|
|
error = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
} else if (command == QStringLiteral("force")) {
|
|
|
|
|
|
cmvr::api::SetDexHandForceCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId); fillValues(&request);
|
|
|
|
|
|
cmvr::api::SetDexHandForceCommand::Feedback response;
|
|
|
|
|
|
status = m_dexHand->SetDexHandForce(&context, request, &response);
|
|
|
|
|
|
success = status.ok() && response.header().success();
|
|
|
|
|
|
error = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
} else {
|
|
|
|
|
|
emit commandFinished(displayCommand, false, QStringLiteral("未知灵巧手命令"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!status.ok())
|
|
|
|
|
|
error = QString::fromStdString(status.error_message());
|
|
|
|
|
|
emit commandFinished(displayCommand, success,
|
|
|
|
|
|
success ? QStringLiteral("命令执行成功") : error);
|
|
|
|
|
|
if (success)
|
|
|
|
|
|
getDexHandStatus(deviceId);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame,
|
|
|
|
|
|
const QString &tcpFrame)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (deviceId.trimmed() != m_armDeviceId)
|
|
|
|
|
|
return;
|
|
|
|
|
|
m_armBaseFrame = baseFrame.trimmed();
|
|
|
|
|
|
m_armTcpFrame = tcpFrame.trimmed();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void speedJ(const QString &deviceId, const QVariantList &velocities,
|
|
|
|
|
|
double acceleration, double duration)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("SpeedJ"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("SpeedJ"), deviceId)) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (velocities.isEmpty()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("SpeedJ"), false,
|
|
|
|
|
|
QStringLiteral("关节速度不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("SpeedJ"), true,
|
|
|
|
|
|
QStringLiteral("演示点动:%1 个关节").arg(velocities.size()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::SpeedJ::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs);
|
|
|
|
|
|
for (const QVariant &value : velocities)
|
|
|
|
|
|
request.mutable_velocity()->add_velocity(value.toDouble());
|
|
|
|
|
|
request.set_acceleration(acceleration);
|
|
|
|
|
|
request.set_duration(duration);
|
|
|
|
|
|
startArmMotion<cmvr::api::SpeedJ::Request, cmvr::api::SpeedJ::Response>(
|
|
|
|
|
|
QStringLiteral("SpeedJ"), std::move(request),
|
|
|
|
|
|
[](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context,
|
|
|
|
|
|
const cmvr::api::SpeedJ::Request &motionRequest,
|
|
|
|
|
|
cmvr::api::SpeedJ::Response *response) {
|
|
|
|
|
|
return stub.speedJ(context, motionRequest, response);
|
|
|
|
|
|
});
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void speedL(const QString &deviceId, const QVariantMap &velocity,
|
|
|
|
|
|
double acceleration, double duration, bool toolFrame)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("SpeedL"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("SpeedL"), deviceId)) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("SpeedL"), true,
|
|
|
|
|
|
QStringLiteral("演示笛卡尔点动"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::SpeedL::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs);
|
|
|
|
|
|
auto *target = request.mutable_velocity();
|
|
|
|
|
|
target->set_vx(velocity.value(QStringLiteral("vx")).toDouble());
|
|
|
|
|
|
target->set_vy(velocity.value(QStringLiteral("vy")).toDouble());
|
|
|
|
|
|
target->set_vz(velocity.value(QStringLiteral("vz")).toDouble());
|
|
|
|
|
|
target->set_wx(velocity.value(QStringLiteral("wx")).toDouble());
|
|
|
|
|
|
target->set_wy(velocity.value(QStringLiteral("wy")).toDouble());
|
|
|
|
|
|
target->set_wz(velocity.value(QStringLiteral("wz")).toDouble());
|
|
|
|
|
|
request.set_acceleration(acceleration);
|
|
|
|
|
|
request.set_duration(duration);
|
|
|
|
|
|
request.set_frame(toolFrame ? cmvr::api::ARM_FRAME_TOOL
|
|
|
|
|
|
: cmvr::api::ARM_FRAME_BASE);
|
|
|
|
|
|
startArmMotion<cmvr::api::SpeedL::Request, cmvr::api::SpeedL::Response>(
|
|
|
|
|
|
QStringLiteral("SpeedL"), std::move(request),
|
|
|
|
|
|
[](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context,
|
|
|
|
|
|
const cmvr::api::SpeedL::Request &motionRequest,
|
|
|
|
|
|
cmvr::api::SpeedL::Response *response) {
|
|
|
|
|
|
return stub.speedL(context, motionRequest, response);
|
|
|
|
|
|
});
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-20 16:49:27 +08:00
|
|
|
|
void motorRpc(const QString &method,const QString &manager,int node,const QVariantMap ¶ms,quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
const auto fail=[&](const QString &error) { motorRpcFinished(token,method,false,{},error); };
|
|
|
|
|
|
if (!m_connected || manager.isEmpty()) { fail(QStringLiteral("服务未连接或电机系统为空")); return; }
|
|
|
|
|
|
if (m_demoMode) { fail(QStringLiteral("电机调试需要连接支持 MotorService 的真实服务端")); return; }
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
try {
|
|
|
|
|
|
cmvr::api::MotorRequest request;
|
|
|
|
|
|
fillHeader(request.mutable_header(),manager,method=="GetState"?500:5000);
|
|
|
|
|
|
if (node<0 || node>255) { fail(QStringLiteral("电机 ID 超出范围")); return; }
|
|
|
|
|
|
request.set_node_id(node);
|
|
|
|
|
|
request.set_mode(params.value("mode").toInt());
|
|
|
|
|
|
request.set_q(params.value("q").toDouble()); request.set_qd(params.value("qd").toDouble());
|
|
|
|
|
|
request.set_qdd(params.value("qdd").toDouble()); request.set_tau(params.value("tau").toDouble());
|
|
|
|
|
|
request.set_torque_slope(params.value("torqueSlope").toUInt());
|
|
|
|
|
|
request.set_upper(params.value("upper").toDouble()); request.set_lower(params.value("lower").toDouble());
|
|
|
|
|
|
grpc::ClientContext context; setDeadline(context,method=="GetState"?500:5000);
|
|
|
|
|
|
auto stub=cmvr::api::MotorService::NewStub(m_channel);
|
|
|
|
|
|
cmvr::api::MotorResponse response;
|
|
|
|
|
|
cmvr::api::MotorListResponse list;
|
|
|
|
|
|
grpc::Status status;
|
|
|
|
|
|
bool accepted=false;
|
|
|
|
|
|
QString applicationError;
|
|
|
|
|
|
if (method=="ListMotors") {
|
|
|
|
|
|
status=stub->ListMotors(&context,request,&list);
|
|
|
|
|
|
accepted=list.header().success(); applicationError=QString::fromStdString(list.header().error_message());
|
|
|
|
|
|
} else {
|
|
|
|
|
|
#define MOTOR_CALL(name) if (method==#name) status=stub->name(&context,request,&response); else
|
|
|
|
|
|
MOTOR_CALL(GetInfo) MOTOR_CALL(GetState) MOTOR_CALL(getMode) MOTOR_CALL(getQ) MOTOR_CALL(getQd)
|
|
|
|
|
|
MOTOR_CALL(getTau) MOTOR_CALL(reachedTargetQ) MOTOR_CALL(setMode) MOTOR_CALL(torqueOn)
|
|
|
|
|
|
MOTOR_CALL(torqueOff) MOTOR_CALL(brakeRelease) MOTOR_CALL(quickStop) MOTOR_CALL(calibrateZeroQ)
|
|
|
|
|
|
MOTOR_CALL(commandProfilePosition) MOTOR_CALL(commandProfileVelocity)
|
|
|
|
|
|
MOTOR_CALL(commandProfileTorque)
|
|
|
|
|
|
MOTOR_CALL(commandCyclicPosition) MOTOR_CALL(commandCyclicVelocity) MOTOR_CALL(commandCyclicTorque)
|
|
|
|
|
|
MOTOR_CALL(setLimitQ) MOTOR_CALL(setLimitQd) MOTOR_CALL(setLimitQdd)
|
|
|
|
|
|
{ fail(QStringLiteral("未知电机接口")); return; }
|
|
|
|
|
|
#undef MOTOR_CALL
|
|
|
|
|
|
accepted=response.header().success(); applicationError=QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!status.ok()) { fail(QStringLiteral("gRPC %1:%2").arg(status.error_code()).arg(QString::fromStdString(status.error_message()))); return; }
|
|
|
|
|
|
if (!accepted) { fail(applicationError.isEmpty()?QStringLiteral("电机接口未返回成功"):applicationError); return; }
|
|
|
|
|
|
// Preserve typed feedback directly; no JSON round trip in the sampling path.
|
|
|
|
|
|
const auto motorInfo=[](const cmvr::api::MotorInfo &i) {
|
|
|
|
|
|
return QVariantMap{{"managerId",QString::fromStdString(i.manager_id())},{"nodeId",i.node_id()},
|
|
|
|
|
|
{"jointName",QString::fromStdString(i.joint_name())},{"driver",QString::fromStdString(i.driver())},
|
|
|
|
|
|
{"limitQLb",i.limit_q_lb()},{"limitQUb",i.limit_q_ub()},{"limitQd",i.limit_qd()},{"limitQdd",i.limit_qdd()}};
|
|
|
|
|
|
};
|
|
|
|
|
|
QVariantMap payload;
|
|
|
|
|
|
if(method=="ListMotors") {
|
|
|
|
|
|
QVariantList motors;
|
|
|
|
|
|
for(const auto &i:list.motors())motors.append(motorInfo(i));
|
|
|
|
|
|
payload.insert("motors",motors);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
payload.insert("info",motorInfo(response.info()));
|
|
|
|
|
|
payload.insert("reachedTarget",response.reached_target());
|
|
|
|
|
|
payload.insert("driverAcknowledged",response.driver_acknowledged());
|
|
|
|
|
|
const auto &s=response.state();
|
|
|
|
|
|
payload.insert("state",QVariantMap{{"position",s.position()},{"velocity",s.velocity()},
|
|
|
|
|
|
{"torque",s.torque()},{"feedbackValid",s.feedback_valid()},{"torqueValid",s.torque_valid()},
|
|
|
|
|
|
{"torqueUnit",QString::fromStdString(s.torque_unit())},{"mode",s.mode()},
|
|
|
|
|
|
{"statusWord",s.status_word()},{"errorCode",s.error_code()},{"statusValid",s.status_valid()},
|
|
|
|
|
|
{"enabled",s.enabled()},{"fault",s.fault()},{"sampledAtS",s.sampled_at_s()}});
|
|
|
|
|
|
}
|
|
|
|
|
|
motorRpcFinished(token,method,true,payload,QString::fromStdString(response.detail()));
|
|
|
|
|
|
} catch (const std::exception &e) { fail(QString::fromLocal8Bit(e.what())); }
|
|
|
|
|
|
#else
|
|
|
|
|
|
fail(QStringLiteral("此构建未启用 gRPC"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void captureJointPoint(const QStringList &devices, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
QVariantList targets;
|
|
|
|
|
|
QString error;
|
|
|
|
|
|
if (!m_connected || devices.isEmpty()) error = QStringLiteral("服务未连接或未选择机械臂");
|
|
|
|
|
|
if (error.isEmpty() && m_demoMode) {
|
|
|
|
|
|
for (const auto &id : devices) {
|
|
|
|
|
|
const auto names=armJointNamesForDevice(id);
|
|
|
|
|
|
QVariantList values;
|
|
|
|
|
|
for (int i=0;i<names.size();++i) {
|
|
|
|
|
|
const double phase=m_tick*0.035+i*0.46;
|
|
|
|
|
|
values.append(i<m_demoTargets.size() ? m_demoTargets[i]+0.025*qSin(phase*1.7) : 0.36*qSin(phase));
|
|
|
|
|
|
}
|
|
|
|
|
|
targets.append(QVariantMap{{"deviceId",id},{"jointNames",names},{"positions",values}});
|
|
|
|
|
|
}
|
|
|
|
|
|
emit jointPointCaptured(token,targets,true,QStringLiteral("演示点位"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
QSet<QString> seen;
|
|
|
|
|
|
for (const auto &id : devices) {
|
|
|
|
|
|
if (!error.isEmpty()) break;
|
|
|
|
|
|
if (id.trimmed().isEmpty() || seen.contains(id)) {
|
|
|
|
|
|
error = QStringLiteral("请选择真实且不重复的机械臂"); break;
|
|
|
|
|
|
}
|
|
|
|
|
|
seen.insert(id);
|
|
|
|
|
|
cmvr::api::JointRequest request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), id);
|
|
|
|
|
|
cmvr::api::JointResponse response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2000);
|
|
|
|
|
|
const auto status = m_arm->getJointState(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
error = id + QStringLiteral(":") + QString::fromStdString(
|
|
|
|
|
|
status.ok() ? response.header().error_message() : status.error_message());
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantList names, positions;
|
|
|
|
|
|
for (const auto &name : response.state().name()) names.append(QString::fromStdString(name));
|
|
|
|
|
|
for (double value : response.state().position()) positions.append(value);
|
|
|
|
|
|
targets.append(QVariantMap{{"deviceId", id}, {"jointNames", names},
|
|
|
|
|
|
{"positions", positions}});
|
|
|
|
|
|
}
|
|
|
|
|
|
#else
|
|
|
|
|
|
error = QStringLiteral("当前构建不支持 gRPC");
|
|
|
|
|
|
#endif
|
|
|
|
|
|
emit jointPointCaptured(token, error.isEmpty() ? targets : QVariantList(), error.isEmpty(), error);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void moveJointPoint(const QVariantList &targets, double velocity, double acceleration, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
const auto reject = [this, token](const QString &error) {
|
|
|
|
|
|
emit jointPointMoveFinished(token, false, error);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (!m_connected || targets.isEmpty()) { reject(QStringLiteral("服务未连接或点位为空")); return; }
|
|
|
|
|
|
if (!std::isfinite(velocity) || velocity <= 0 || !std::isfinite(acceleration) || acceleration <= 0) {
|
|
|
|
|
|
reject(QStringLiteral("速度和加速度必须为正数")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QSet<QString> ids;
|
|
|
|
|
|
for (const auto &value : targets) {
|
|
|
|
|
|
const auto target = value.toMap();
|
|
|
|
|
|
const auto id = target.value("deviceId").toString();
|
|
|
|
|
|
const auto names = target.value("jointNames").toStringList();
|
|
|
|
|
|
const auto positions = target.value("positions").toList();
|
|
|
|
|
|
if (id.isEmpty() || ids.contains(id) || positions.isEmpty() || names.size() != positions.size()) {
|
|
|
|
|
|
reject(QStringLiteral("点位的设备或关节数据无效")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
ids.insert(id);
|
|
|
|
|
|
QSet<QString> uniqueNames;
|
|
|
|
|
|
for (const auto &name : names) {
|
|
|
|
|
|
if (name.trimmed().isEmpty() || uniqueNames.contains(name)) {
|
|
|
|
|
|
reject(QStringLiteral("关节名称为空或重复")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
uniqueNames.insert(name);
|
|
|
|
|
|
}
|
|
|
|
|
|
for (const auto &p : positions) {
|
|
|
|
|
|
bool ok = false;
|
|
|
|
|
|
const double v = p.toDouble(&ok);
|
|
|
|
|
|
if (!ok || !std::isfinite(v)) { reject(QStringLiteral("目标角度无效")); return; }
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
for (const auto &value : targets) {
|
|
|
|
|
|
const auto t=value.toMap();
|
|
|
|
|
|
if (t.value("deviceId").toString()==m_armDeviceId || targets.size()==1) {
|
|
|
|
|
|
m_demoTargets.clear();
|
|
|
|
|
|
for (const auto &p : t.value("positions").toList()) m_demoTargets.append(p.toDouble());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
emit jointPointMoveFinished(token,true,QStringLiteral("演示点位已执行(未控制真实设备)"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
// Keep the existing global motion gate; one group owns one session.
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
|
|
|
|
|
if (m_armMotionSession && m_armMotionSession->running.load()) {
|
|
|
|
|
|
reject(QStringLiteral("已有机械臂运动命令正在执行")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto session = prepareArmMotionSession(QStringLiteral("JointPoint"));
|
|
|
|
|
|
if (!session) { reject(QStringLiteral("无法创建运动会话")); return; }
|
|
|
|
|
|
const auto channel = m_channel;
|
|
|
|
|
|
session->thread = std::thread([this, channel, session, targets, velocity, acceleration, token] {
|
|
|
|
|
|
QStringList results;
|
|
|
|
|
|
std::mutex resultMutex;
|
|
|
|
|
|
const auto fail = [&](const QString &error) {
|
|
|
|
|
|
{ std::lock_guard<std::mutex> lock(resultMutex); results.append(error); }
|
|
|
|
|
|
session->stop.store(true);
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
for (const auto &c : session->groupContexts) c->TryCancel();
|
|
|
|
|
|
};
|
|
|
|
|
|
std::vector<std::thread> calls;
|
|
|
|
|
|
bool dispatched = false;
|
|
|
|
|
|
try {
|
|
|
|
|
|
// Verify every recorded joint order before any arm is commanded.
|
|
|
|
|
|
for (const auto &value : targets) {
|
|
|
|
|
|
const auto t = value.toMap();
|
|
|
|
|
|
const auto id = t.value("deviceId").toString();
|
|
|
|
|
|
auto context=std::make_shared<grpc::ClientContext>();
|
|
|
|
|
|
setDeadline(*context, 2000);
|
|
|
|
|
|
{ std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->groupContexts.push_back(context);
|
|
|
|
|
|
if (session->stop.load()) context->TryCancel(); }
|
|
|
|
|
|
cmvr::api::GetArmInfo::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), id);
|
|
|
|
|
|
cmvr::api::GetArmInfo::Response response;
|
2026-10-26 17:35:27 +08:00
|
|
|
|
auto stub = cmvr::api::ArmService::NewStub(channel);
|
|
|
|
|
|
auto status = stub->GetArmInfo(context.get(), request, &response);
|
2026-10-20 16:49:27 +08:00
|
|
|
|
{ std::lock_guard<std::mutex> lock(session->contextMutex); session->groupContexts.clear(); }
|
|
|
|
|
|
QStringList names;
|
|
|
|
|
|
for (const auto &n : response.joint_names()) names.append(QString::fromStdString(n));
|
2026-10-26 17:35:27 +08:00
|
|
|
|
bool infoSuccess = response.header().success();
|
|
|
|
|
|
QString infoError = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED && !session->stop.load()) {
|
|
|
|
|
|
context = std::make_shared<grpc::ClientContext>();
|
|
|
|
|
|
setDeadline(*context, 2000);
|
|
|
|
|
|
{ std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->groupContexts.push_back(context);
|
|
|
|
|
|
if (session->stop.load()) context->TryCancel(); }
|
|
|
|
|
|
cmvr::api::JointRequest jointRequest;
|
|
|
|
|
|
fillHeader(jointRequest.mutable_header(), id);
|
|
|
|
|
|
cmvr::api::JointResponse jointResponse;
|
|
|
|
|
|
status = stub->getJointState(context.get(), jointRequest, &jointResponse);
|
|
|
|
|
|
{ std::lock_guard<std::mutex> lock(session->contextMutex); session->groupContexts.clear(); }
|
|
|
|
|
|
infoSuccess = jointResponse.header().success()
|
|
|
|
|
|
&& confirmedJointNames(jointResponse.state(), names);
|
|
|
|
|
|
infoError = QString::fromStdString(jointResponse.header().error_message());
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!status.ok() || !infoSuccess) {
|
|
|
|
|
|
const auto error = status.ok() ? infoError : QString::fromStdString(status.error_message());
|
2026-10-20 16:49:27 +08:00
|
|
|
|
fail(id + QStringLiteral(":读取机械臂信息失败:")
|
|
|
|
|
|
+ (error.isEmpty() ? QStringLiteral("接口未返回成功") : error));
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (names != t.value("jointNames").toStringList()) {
|
|
|
|
|
|
fail(id + QStringLiteral(":无法确认点位关节顺序,请检查连接及记录的关节名称")); break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!session->stop.load()) {
|
|
|
|
|
|
dispatched = true;
|
|
|
|
|
|
for (const auto &value : targets) {
|
|
|
|
|
|
calls.emplace_back([&, value] {
|
|
|
|
|
|
const auto t = value.toMap();
|
|
|
|
|
|
const QString id = t.value("deviceId").toString();
|
|
|
|
|
|
auto context=std::make_shared<grpc::ClientContext>();
|
|
|
|
|
|
setDeadline(*context, kArmMotionTimeoutMs);
|
|
|
|
|
|
{ std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->groupContexts.push_back(context);
|
|
|
|
|
|
if (session->stop.load()) context->TryCancel(); }
|
|
|
|
|
|
try {
|
|
|
|
|
|
cmvr::api::MoveJ::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), id, kArmMotionTimeoutMs);
|
|
|
|
|
|
for (const auto &p : t.value("positions").toList()) request.mutable_target()->add_position(p.toDouble());
|
|
|
|
|
|
request.mutable_options()->set_velocity(velocity);
|
|
|
|
|
|
request.mutable_options()->set_acceleration(acceleration);
|
|
|
|
|
|
request.mutable_options()->set_asynchronous(false);
|
|
|
|
|
|
cmvr::api::MoveJ::Response response;
|
|
|
|
|
|
if (!session->stop.load()) {
|
|
|
|
|
|
const auto status = cmvr::api::ArmService::NewStub(channel)->moveJ(context.get(), request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
const auto error=QString::fromStdString(status.ok()
|
|
|
|
|
|
? response.header().error_message() : status.error_message());
|
|
|
|
|
|
fail(id + QStringLiteral(":")
|
|
|
|
|
|
+ (error.isEmpty() ? QStringLiteral("MoveJ 未返回成功") : error));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} catch (const std::exception &e) { fail(id + QStringLiteral(":") + QString::fromLocal8Bit(e.what())); }
|
|
|
|
|
|
catch (...) { fail(id + QStringLiteral(":运动调用异常")); }
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
auto &cs = session->groupContexts;
|
|
|
|
|
|
cs.erase(std::remove(cs.begin(), cs.end(), context), cs.end());
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} catch (const std::exception &e) { fail(QString::fromLocal8Bit(e.what())); }
|
|
|
|
|
|
catch (...) { fail(QStringLiteral("组合运动异常")); }
|
|
|
|
|
|
for (auto &call : calls) if (call.joinable()) call.join();
|
|
|
|
|
|
if (session->stop.load() && dispatched) {
|
|
|
|
|
|
// Cancellation alone is not a hardware stop on every driver.
|
|
|
|
|
|
for (const auto &value : targets) {
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1500);
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, value.toMap().value("deviceId").toString());
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
const auto status = cmvr::api::ArmService::NewStub(channel)->stopMotion(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.success()) results.append(
|
|
|
|
|
|
value.toMap().value("deviceId").toString()+QStringLiteral(":停止确认失败,请检查设备"));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool ok = !session->stop.load();
|
|
|
|
|
|
session->running.store(false);
|
|
|
|
|
|
emit jointPointMoveFinished(token, ok, ok ? QStringLiteral("所有机械臂已完成点位")
|
|
|
|
|
|
: (results.isEmpty() ? QStringLiteral("点位执行已取消") : results.join("\n")));
|
|
|
|
|
|
});
|
|
|
|
|
|
#else
|
|
|
|
|
|
reject(QStringLiteral("当前构建不支持 gRPC"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void moveJ(const QString &deviceId, const QVariantList &positions,
|
|
|
|
|
|
double velocity, double acceleration)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("MoveJ")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("MoveJ"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (positions.isEmpty()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("MoveJ"), false, QStringLiteral("没有可发送的目标关节"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_demoTargets.clear();
|
|
|
|
|
|
for (const QVariant &value : positions)
|
|
|
|
|
|
m_demoTargets.append(value.toDouble());
|
|
|
|
|
|
emit commandFinished(QStringLiteral("MoveJ"), true,
|
|
|
|
|
|
QStringLiteral("已发送 %1 个目标,v=%2,a=%3")
|
|
|
|
|
|
.arg(positions.size()).arg(velocity, 0, 'f', 2).arg(acceleration, 0, 'f', 2));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::MoveJ::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs);
|
|
|
|
|
|
for (const QVariant &value : positions)
|
|
|
|
|
|
request.mutable_target()->add_position(value.toDouble());
|
|
|
|
|
|
request.mutable_options()->set_velocity(velocity);
|
|
|
|
|
|
request.mutable_options()->set_acceleration(acceleration);
|
|
|
|
|
|
startArmMotion<cmvr::api::MoveJ::Request, cmvr::api::MoveJ::Response>(
|
|
|
|
|
|
QStringLiteral("MoveJ"), std::move(request),
|
|
|
|
|
|
[](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context,
|
|
|
|
|
|
const cmvr::api::MoveJ::Request &motionRequest,
|
|
|
|
|
|
cmvr::api::MoveJ::Response *response) {
|
|
|
|
|
|
return stub.moveJ(context, motionRequest, response);
|
|
|
|
|
|
});
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void moveJPose(const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
const QString &baseLink, const QString &eeLink,
|
|
|
|
|
|
double velocity, double acceleration)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
movePoseImpl(deviceId, pose, baseLink, eeLink, velocity, acceleration, QStringLiteral("MoveL"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void tcpJogMove(const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
double velocity, double acceleration, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
// The verified driver resolves "tcp" to its current active offset.
|
|
|
|
|
|
// Never pass a local profile name as a controller frame identifier.
|
|
|
|
|
|
movePoseImpl(deviceId, pose, QStringLiteral("base"), QStringLiteral("tcp"),
|
|
|
|
|
|
velocity, acceleration, TcpJogController::commandName(token));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void movePoseImpl(const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
const QString &baseLink, const QString &eeLink,
|
|
|
|
|
|
double velocity, double acceleration, const QString &command)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(command))
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!ensureDeviceId(command, deviceId))
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit commandFinished(command, true,
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QStringLiteral("已发送末端位姿 MoveL,%1 → %2,v=%3,a=%4")
|
|
|
|
|
|
.arg(baseLink, eeLink)
|
|
|
|
|
|
.arg(velocity, 0, 'f', 2)
|
|
|
|
|
|
.arg(acceleration, 0, 'f', 2));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::MoveL::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId, kArmMotionTimeoutMs);
|
|
|
|
|
|
auto *target = request.mutable_target();
|
|
|
|
|
|
target->set_x(pose.value(QStringLiteral("x")).toDouble());
|
|
|
|
|
|
target->set_y(pose.value(QStringLiteral("y")).toDouble());
|
|
|
|
|
|
target->set_z(pose.value(QStringLiteral("z")).toDouble());
|
|
|
|
|
|
target->set_rx(pose.value(QStringLiteral("rx")).toDouble());
|
|
|
|
|
|
target->set_ry(pose.value(QStringLiteral("ry")).toDouble());
|
|
|
|
|
|
target->set_rz(pose.value(QStringLiteral("rz")).toDouble());
|
|
|
|
|
|
request.mutable_options()->set_velocity(velocity);
|
|
|
|
|
|
request.mutable_options()->set_acceleration(acceleration);
|
|
|
|
|
|
request.set_frame(cmvr::api::ARM_FRAME_BASE);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
if (!baseLink.trimmed().isEmpty())
|
|
|
|
|
|
request.set_base_frame(baseLink.trimmed().toStdString());
|
|
|
|
|
|
if (!eeLink.trimmed().isEmpty())
|
|
|
|
|
|
request.set_tcp_frame(eeLink.trimmed().toStdString());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
startArmMotion<cmvr::api::MoveL::Request, cmvr::api::MoveL::Response>(
|
2026-10-14 17:15:46 +08:00
|
|
|
|
command, std::move(request),
|
2026-09-18 16:22:20 +08:00
|
|
|
|
[](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *context,
|
|
|
|
|
|
const cmvr::api::MoveL::Request &motionRequest,
|
|
|
|
|
|
cmvr::api::MoveL::Response *response) {
|
|
|
|
|
|
return stub.moveL(context, motionRequest, response);
|
|
|
|
|
|
});
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void torque(const QString &deviceId, bool enabled)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = enabled ? QStringLiteral("Torque On") : QStringLiteral("Torque Off");
|
|
|
|
|
|
if (!ensureConnected(command))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true, enabled ? QStringLiteral("关节已使能") : QStringLiteral("关节已去使能"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, deviceId);
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
2026-10-26 17:35:27 +08:00
|
|
|
|
// Vendor arms may need to wait for power-on and brake-release states.
|
|
|
|
|
|
setDeadline(context, enabled ? 35000 : 2000);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
const grpc::Status status = enabled
|
|
|
|
|
|
? m_arm->torqueOn(&context, request, &response)
|
|
|
|
|
|
: m_arm->torqueOff(&context, request, &response);
|
|
|
|
|
|
finish(command, status, response.success(), QString::fromStdString(response.error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void armStop(const QString &deviceId)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
stopArmMotionInternal();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (!ensureConnected(QStringLiteral("Stop Motion")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("Stop Motion"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_demoTargets.clear();
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Stop Motion"), true, QStringLiteral("运动已停止"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, deviceId);
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1500);
|
|
|
|
|
|
const grpc::Status status = m_arm->stopMotion(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("Stop Motion"), status, response.success(), QString::fromStdString(response.error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void armClearFault(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Clear Fault")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("Clear Fault"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Clear Fault"), true, QStringLiteral("故障状态已清除"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, deviceId);
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2000);
|
|
|
|
|
|
const grpc::Status status = m_arm->clearFault(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("Clear Fault"), status, response.success(), QString::fromStdString(response.error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void armCalibrateZero(const QString &deviceId, const QString &jointName)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("Calibrate Zero Q");
|
|
|
|
|
|
if (!ensureConnected(command))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (jointName.trimmed().isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("关节名称不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true,
|
|
|
|
|
|
QStringLiteral("已将 %1 的当前位置设置为零位(演示)")
|
|
|
|
|
|
.arg(jointName));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CalibrateZeroQ::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_joint_name(jointName.toStdString());
|
|
|
|
|
|
cmvr::api::CalibrateZeroQ::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_arm->calibrateZeroQ(&context, request, &response);
|
|
|
|
|
|
finish(command, status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-26 17:35:27 +08:00
|
|
|
|
void enterTeachingMode(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
teachingCommand(QStringLiteral("Enter Teaching Mode"), deviceId, 0);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-29 11:46:39 +08:00
|
|
|
|
void startTrajectoryRecording(const QString &deviceId, const QString &fileName, double frequencyHz)
|
2026-10-26 17:35:27 +08:00
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("Start Trajectory Recording");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (fileName.trimmed().isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("轨迹文件名不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true,
|
|
|
|
|
|
QStringLiteral("已开始记录示教轨迹:%1(演示)").arg(fileName));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::StartTrajectoryRecording::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_file_name(fileName.trimmed().toStdString());
|
2026-10-29 11:46:39 +08:00
|
|
|
|
request.set_sampling_frequency_hz(frequencyHz);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
cmvr::api::StartTrajectoryRecording::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
2026-10-29 11:46:39 +08:00
|
|
|
|
setDeadline(context, 6000);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
const grpc::Status status = m_arm->StartTrajectoryRecording(&context, request, &response);
|
|
|
|
|
|
finish(command, status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void completeTeaching(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
teachingCommand(QStringLiteral("Complete Teaching"), deviceId, 1);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-29 11:46:39 +08:00
|
|
|
|
void recordedTrajectories(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("List Recorded Trajectories")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("List Recorded Trajectories"), deviceId)) return;
|
|
|
|
|
|
QVariantList files;
|
|
|
|
|
|
QVariantMap state;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
state.insert("directory", QStringLiteral("演示模式:不读写真实轨迹"));
|
|
|
|
|
|
emit recordedTrajectoriesReceived(deviceId, files, state, true, QString());
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::ListRecordedTrajectories::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::ListRecordedTrajectories::Response response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 6000);
|
|
|
|
|
|
const auto status = m_arm->ListRecordedTrajectories(&context, request, &response);
|
|
|
|
|
|
for (const auto &file : response.trajectories()) {
|
|
|
|
|
|
QVariantMap row;
|
|
|
|
|
|
row.insert("fileName", QString::fromStdString(file.file_name()));
|
|
|
|
|
|
row.insert("samples", QVariant::fromValue<qulonglong>(file.samples()));
|
|
|
|
|
|
row.insert("duration", file.duration_s());
|
|
|
|
|
|
row.insert("frequency", file.sampling_frequency_hz());
|
|
|
|
|
|
files.append(row);
|
|
|
|
|
|
}
|
|
|
|
|
|
state.insert("directory", QString::fromStdString(response.directory()));
|
|
|
|
|
|
state.insert("recording", response.recording());
|
|
|
|
|
|
state.insert("fileName", QString::fromStdString(response.recording_file()));
|
|
|
|
|
|
state.insert("samples", QVariant::fromValue<qulonglong>(response.recorded_samples()));
|
|
|
|
|
|
state.insert("error", QString::fromStdString(response.recording_error()));
|
|
|
|
|
|
emit recordedTrajectoriesReceived(deviceId, files, state, status.ok() && response.header().success(),
|
|
|
|
|
|
status.ok() ? QString::fromStdString(response.header().error_message()) : QString::fromStdString(status.error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void replayTrajectory(const QString &deviceId, const QString &fileName, double speedRatio, bool toStart,
|
|
|
|
|
|
const QVariantMap &limits)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = toStart ? QStringLiteral("Trajectory Start") : QStringLiteral("Replay Trajectory");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId)) return;
|
|
|
|
|
|
if (fileName.trimmed().isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("请先选择已保存的 CSV 轨迹")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) { emit commandFinished(command, true, QStringLiteral("演示模式:未执行真实运动")); return; }
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::ReplayRecordedTrajectory::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_file_name(fileName.toStdString());
|
|
|
|
|
|
request.set_speed_ratio(speedRatio);
|
|
|
|
|
|
request.set_max_velocity(limits.value("velocity", 0.3).toDouble());
|
|
|
|
|
|
request.set_max_acceleration(limits.value("acceleration", 0.5).toDouble());
|
|
|
|
|
|
request.set_max_jerk(limits.value("jerk", 2.0).toDouble());
|
|
|
|
|
|
startArmMotion<cmvr::api::ReplayRecordedTrajectory::Request, cmvr::api::ReplayRecordedTrajectory::Response>(
|
|
|
|
|
|
command, std::move(request), [toStart](cmvr::api::ArmService::Stub &stub, grpc::ClientContext *ctx,
|
|
|
|
|
|
const cmvr::api::ReplayRecordedTrajectory::Request &q, cmvr::api::ReplayRecordedTrajectory::Response *r) {
|
|
|
|
|
|
return toStart ? stub.MoveToTrajectoryStart(ctx, q, r) : stub.ReplayRecordedTrajectory(ctx, q, r);
|
|
|
|
|
|
}, 6 * 60 * 60 * 1000);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-26 17:35:27 +08:00
|
|
|
|
void stopTrajectoryRecording(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
teachingCommand(QStringLiteral("Stop Trajectory Recording"), deviceId, 2);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void exitTeachingMode(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
teachingCommand(QStringLiteral("Exit Teaching Mode"), deviceId, 3);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void snapshot(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Snapshot")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("Snapshot"), cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
QImage image(1280, 720, QImage::Format_RGB32);
|
|
|
|
|
|
image.fill(QColor("#20252b"));
|
|
|
|
|
|
QPainter painter(&image);
|
|
|
|
|
|
painter.setRenderHint(QPainter::Antialiasing);
|
|
|
|
|
|
painter.setPen(QPen(QColor("#3b424b"), 1));
|
|
|
|
|
|
for (int x = 0; x < image.width(); x += 64)
|
|
|
|
|
|
painter.drawLine(x, 0, x, image.height());
|
|
|
|
|
|
for (int y = 0; y < image.height(); y += 64)
|
|
|
|
|
|
painter.drawLine(0, y, image.width(), y);
|
|
|
|
|
|
painter.setPen(QColor("#e9edf2"));
|
|
|
|
|
|
painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold));
|
|
|
|
|
|
painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter, QStringLiteral("相机预览"));
|
|
|
|
|
|
painter.setPen(QColor("#9ca4ad"));
|
|
|
|
|
|
painter.setFont(QFont("Microsoft YaHei UI", 14));
|
|
|
|
|
|
painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter,
|
|
|
|
|
|
QStringLiteral("%1 · DEMO · %2")
|
|
|
|
|
|
.arg(cameraId, QDateTime::currentDateTime().toString("HH:mm:ss")));
|
|
|
|
|
|
emit imageReceived(image, QStringLiteral("1280 x 720 · 演示帧"));
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("已获取演示图像"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetRGBImageCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::GetRGBImageCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_camera->GetRGBImage(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
finish(QStringLiteral("Snapshot"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &frame = response.color_frame();
|
|
|
|
|
|
const QByteArray bytes(frame.data().data(), static_cast<int>(frame.data().size()));
|
|
|
|
|
|
QImage image;
|
|
|
|
|
|
if (frame.type() == cmvr::api::FrameData::U8C3 &&
|
|
|
|
|
|
frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height() * 3) {
|
|
|
|
|
|
image = QImage(reinterpret_cast<const uchar *>(bytes.constData()), frame.width(), frame.height(),
|
|
|
|
|
|
frame.width() * 3, QImage::Format_RGB888).rgbSwapped();
|
|
|
|
|
|
} else if (frame.type() == cmvr::api::FrameData::U8C1 &&
|
|
|
|
|
|
frame.width() > 0 && frame.height() > 0 && bytes.size() == frame.width() * frame.height()) {
|
|
|
|
|
|
image = QImage(reinterpret_cast<const uchar *>(bytes.constData()), frame.width(), frame.height(),
|
|
|
|
|
|
frame.width(), QImage::Format_Grayscale8).copy();
|
|
|
|
|
|
} else {
|
|
|
|
|
|
image = QImage::fromData(bytes);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (image.isNull()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Snapshot"), false,
|
|
|
|
|
|
QStringLiteral("暂不支持图像编码:%1").arg(QString::fromStdString(frame.codec())));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit imageReceived(image, QStringLiteral("%1 x %2 · %3")
|
|
|
|
|
|
.arg(image.width()).arg(image.height()).arg(QString::fromStdString(frame.codec())));
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Snapshot"), true, QStringLiteral("图像获取成功"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void getHandEyeImage(const QString &cameraId, quint64 token, bool touch=false)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString selectedCamera = cameraId.trimmed();
|
|
|
|
|
|
const auto deliver = touch ? touchRgbdImageReceived : handEyeImageReceived;
|
|
|
|
|
|
const auto reject = [deliver, token, selectedCamera](const QString &detail) {
|
|
|
|
|
|
deliver(token, selectedCamera, {}, {}, {}, false, detail);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
reject(QStringLiteral("手眼标定不接受演示图像,请连接真实相机"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!m_connected || selectedCamera.isEmpty()) {
|
|
|
|
|
|
reject(QStringLiteral("手眼图像采集失败:服务未连接或相机 ID 为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!m_camera) {
|
|
|
|
|
|
reject(QStringLiteral("手眼图像采集失败:相机服务不可用"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::api::GetRGBImageCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), selectedCamera);
|
|
|
|
|
|
cmvr::api::GetRGBImageCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const qint64 requestedAtMs = QDateTime::currentMSecsSinceEpoch();
|
|
|
|
|
|
const grpc::Status status = m_camera->GetRGBImage(&context, request, &response);
|
|
|
|
|
|
const qint64 receivedAtMs = QDateTime::currentMSecsSinceEpoch();
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
reject(QStringLiteral("手眼图像采集失败:%1").arg(status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message())));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!response.has_color_frame() || !response.has_intrinsics()) {
|
|
|
|
|
|
reject(QStringLiteral("相机未返回完整的彩色图像和对应内参"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &frame = response.color_frame();
|
|
|
|
|
|
const QString codec = QString::fromStdString(frame.codec()).trimmed().toLower();
|
|
|
|
|
|
const int channels = frame.type() == cmvr::api::FrameData::U8C3 ? 3
|
|
|
|
|
|
: frame.type() == cmvr::api::FrameData::U8C1 ? 1 : 0;
|
|
|
|
|
|
// Unary GetRGBImage serializes tightly packed OpenCV BGR/gray bytes.
|
|
|
|
|
|
// Bound the multiplication before allocating or constructing a QImage.
|
|
|
|
|
|
const qint64 pixels = static_cast<qint64>(frame.width()) * frame.height();
|
|
|
|
|
|
if (frame.width() <= 0 || frame.height() <= 0 || channels == 0
|
|
|
|
|
|
|| (!codec.isEmpty() && codec != QStringLiteral("none"))
|
|
|
|
|
|
|| pixels > kGrpcMaxMessageBytes / channels
|
|
|
|
|
|
|| static_cast<quint64>(pixels * channels) != frame.data().size()) {
|
|
|
|
|
|
reject(QStringLiteral("相机图像格式、尺寸或数据长度无效;需要原始 BGR8/灰度图像"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &camera = response.intrinsics();
|
|
|
|
|
|
bool validIntrinsics = std::isfinite(camera.fx()) && camera.fx() > 0.0f
|
|
|
|
|
|
&& std::isfinite(camera.fy()) && camera.fy() > 0.0f
|
|
|
|
|
|
&& std::isfinite(camera.cx()) && std::isfinite(camera.cy())
|
|
|
|
|
|
&& camera.coeffs_size() == 5;
|
|
|
|
|
|
QVariantList coefficients;
|
|
|
|
|
|
for (const float coefficient : camera.coeffs()) {
|
|
|
|
|
|
validIntrinsics = validIntrinsics && std::isfinite(coefficient);
|
|
|
|
|
|
coefficients.append(static_cast<double>(coefficient));
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!validIntrinsics) {
|
|
|
|
|
|
reject(QStringLiteral("相机彩色内参无效:需要正焦距、有限主点和 5 个有限畸变系数"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto *data = reinterpret_cast<const uchar *>(frame.data().data());
|
|
|
|
|
|
const QImage borrowed(data, frame.width(), frame.height(), frame.width() * channels,
|
|
|
|
|
|
channels == 3 ? QImage::Format_RGB888 : QImage::Format_Grayscale8);
|
|
|
|
|
|
const QImage image = channels == 3 ? borrowed.rgbSwapped() : borrowed.copy();
|
|
|
|
|
|
if (image.isNull()) {
|
|
|
|
|
|
reject(QStringLiteral("手眼图像解码失败"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantMap capture;
|
|
|
|
|
|
const qint64 sentNs=requestedAtMs*1000000, receivedNs=receivedAtMs*1000000;
|
|
|
|
|
|
const auto stamp=response.header().timestamp();
|
|
|
|
|
|
const qint64 serverNs=qint64(stamp.seconds())*1000000000+stamp.nanos();
|
|
|
|
|
|
const qint64 latest=frame.capture_utc_ns();
|
|
|
|
|
|
const qint64 earliest=frame.capture_earliest_utc_ns()>0?frame.capture_earliest_utc_ns():latest;
|
|
|
|
|
|
const bool bounded=latest>0 && earliest>0 && earliest<=latest && stamp.seconds()>0
|
|
|
|
|
|
&& stamp.nanos()>=0 && stamp.nanos()<1000000000 && serverNs>=latest
|
|
|
|
|
|
&& serverNs-earliest<=1500000000 && receivedNs>=sentNs && receivedNs-sentNs<=1500000000;
|
|
|
|
|
|
if(touch && (!bounded || frame.camera_serial().empty() || !frame.camera_session_generation()
|
|
|
|
|
|
|| (frame.distortion_model()!="none" && frame.distortion_model()!="brown_conrady"))) {
|
|
|
|
|
|
reject(QStringLiteral("二维定位缺少真实相机身份、畸变模型或有界采集时刻")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if(bounded) capture={{"captureUtcNs",receivedNs-(serverNs-latest)},
|
|
|
|
|
|
{"captureEarliestLocalNs",sentNs-(serverNs-earliest)},{"serverCaptureUtcNs",latest},
|
|
|
|
|
|
{"captureTimeUncertaintyNs",receivedNs-sentNs+latest-earliest}};
|
|
|
|
|
|
const QVariantMap intrinsics = {
|
|
|
|
|
|
{QStringLiteral("fx"), camera.fx()}, {QStringLiteral("fy"), camera.fy()},
|
|
|
|
|
|
{QStringLiteral("cx"), camera.cx()}, {QStringLiteral("cy"), camera.cy()},
|
|
|
|
|
|
{QStringLiteral("coeffs"), coefficients},
|
|
|
|
|
|
{QStringLiteral("width"), image.width()}, {QStringLiteral("height"), image.height()},
|
|
|
|
|
|
{QStringLiteral("distortionModelAvailable"), !frame.distortion_model().empty()},
|
|
|
|
|
|
{QStringLiteral("model"),QString::fromStdString(frame.distortion_model())},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImage.intrinsics")}};
|
|
|
|
|
|
// Older/current unary servers omit these fields. Preserve zero and
|
|
|
|
|
|
// advertise the absence; receipt time is not a camera capture time.
|
|
|
|
|
|
const bool captureTimestampAvailable = frame.capture_utc_ns() > 0;
|
|
|
|
|
|
QVariantMap metadata = {
|
|
|
|
|
|
{QStringLiteral("captureUtcNs"), static_cast<qint64>(frame.capture_utc_ns())},
|
|
|
|
|
|
{QStringLiteral("cameraSerial"),QString::fromStdString(frame.camera_serial())},
|
|
|
|
|
|
{QStringLiteral("cameraSessionGeneration"),qulonglong(frame.camera_session_generation())},
|
|
|
|
|
|
{QStringLiteral("sourceSequence"), static_cast<quint64>(frame.source_sequence())},
|
|
|
|
|
|
{QStringLiteral("sourceFrameNumber"), static_cast<quint64>(frame.source_frame_number())},
|
|
|
|
|
|
{QStringLiteral("sourceTimestamp"), static_cast<quint64>(frame.source_timestamp())},
|
|
|
|
|
|
{QStringLiteral("pts"), static_cast<qint64>(frame.pts())},
|
|
|
|
|
|
{QStringLiteral("dts"), static_cast<qint64>(frame.dts())},
|
|
|
|
|
|
{QStringLiteral("sourceFps"), frame.source_fps()},
|
|
|
|
|
|
{QStringLiteral("requestedAtMs"), requestedAtMs},
|
|
|
|
|
|
{QStringLiteral("receivedAtMs"), receivedAtMs},
|
|
|
|
|
|
{QStringLiteral("captureTimestampAvailable"), captureTimestampAvailable},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImage.color_frame")}};
|
|
|
|
|
|
for(auto it=capture.cbegin();it!=capture.cend();++it) metadata.insert(it.key(),it.value());
|
|
|
|
|
|
deliver(token, selectedCamera, image, intrinsics, metadata, true,
|
|
|
|
|
|
captureTimestampAvailable
|
|
|
|
|
|
? QStringLiteral("已获取原始图像、对应内参及采集时间戳")
|
|
|
|
|
|
: QStringLiteral("已获取图像和内参;服务未提供图像采集时间戳,不能确认与机械臂位姿同步"));
|
|
|
|
|
|
#else
|
|
|
|
|
|
reject(QStringLiteral("当前构建未启用 gRPC,无法采集真实相机图像"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void getCameraCapabilities(const QString &cameraId, quint64 token) {
|
|
|
|
|
|
QVariantMap result; bool success=false; QString detail;
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if(m_connected && !m_demoMode && m_camera && !cameraId.isEmpty()) {
|
|
|
|
|
|
cmvr::api::GetCameraStateCommand::Request request; fillHeader(request.mutable_header(),cameraId);
|
|
|
|
|
|
cmvr::api::GetCameraStateCommand::Feedback response; grpc::ClientContext context; setDeadline(context,2000);
|
|
|
|
|
|
const auto status=m_camera->GetStatus(&context,request,&response);
|
|
|
|
|
|
success=status.ok() && response.header().success() && response.state().has_capabilities();
|
|
|
|
|
|
if(success) {
|
|
|
|
|
|
const auto& c=response.state().capabilities();
|
|
|
|
|
|
result={{"version",c.version()},{"driver",QString::fromStdString(c.driver())},{"model",QString::fromStdString(c.model())},
|
|
|
|
|
|
{"serial",QString::fromStdString(c.serial())},{"transport",QString::fromStdString(c.transport())},
|
|
|
|
|
|
{"rawImage",c.raw_image()},{"validIntrinsics",c.valid_intrinsics()},{"captureTimestamp",c.capture_timestamp()},
|
2026-10-16 09:39:44 +08:00
|
|
|
|
{"metricAlignedDepth",c.metric_aligned_depth()},
|
|
|
|
|
|
{"depthImage",c.depth_image()},{"depthStream",c.depth_stream()},
|
|
|
|
|
|
{"distortionModel",QString::fromStdString(c.distortion_model())},
|
2026-10-14 17:15:46 +08:00
|
|
|
|
{"sessionGeneration",qulonglong(c.session_generation())},{"unavailableReason",QString::fromStdString(c.unavailable_reason())},
|
|
|
|
|
|
{"width",response.state().width()},{"height",response.state().height()},
|
|
|
|
|
|
{"intrinsicsSignature",QString::fromStdString(c.intrinsics_signature())}};
|
|
|
|
|
|
} else detail=status.ok()?QString::fromStdString(response.header().error_message()):QString::fromStdString(status.error_message());
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
if(!success && detail.isEmpty()) detail=QStringLiteral("相机能力不可用,请更新服务端或检查连接");
|
|
|
|
|
|
cameraCapabilitiesReceived(token,cameraId,result,success,detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void getTouchRgbdImage(const QString &cameraId, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
const auto reject=[&](const QString &detail) { touchRgbdImageReceived(token,cameraId,{},{},{},false,detail); };
|
|
|
|
|
|
if(m_demoMode||!m_connected||cameraId.trimmed().isEmpty()) { reject(QStringLiteral("请连接真实相机服务")); return; }
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if(!m_camera) { reject(QStringLiteral("相机服务不可用")); return; }
|
|
|
|
|
|
cmvr::api::GetRGBDImagesCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(),cameraId); request.set_require_metric_depth(true);
|
|
|
|
|
|
cmvr::api::GetRGBDImagesCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context; setDeadline(context,3000);
|
|
|
|
|
|
const qint64 sentNs=QDateTime::currentMSecsSinceEpoch()*1000000;
|
|
|
|
|
|
const auto status=m_camera->GetRGBDImages(&context,request,&response);
|
|
|
|
|
|
const qint64 receivedNs=QDateTime::currentMSecsSinceEpoch()*1000000;
|
|
|
|
|
|
if(!status.ok()||!response.header().success()) {
|
|
|
|
|
|
reject(QStringLiteral("GetRGBDImages:%1").arg(QString::fromStdString(status.ok()?response.header().error_message():status.error_message()))); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if(!response.has_depth_geometry()) {
|
|
|
|
|
|
reject(QStringLiteral("相机服务尚未提供公制深度元数据,请安装随上位机提供的 RGBD 服务补丁。")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &rgb=response.color_frame(); const auto &d=response.depth_frame();
|
|
|
|
|
|
const auto &g=response.depth_geometry(); const auto &k=response.intrinsics();
|
|
|
|
|
|
const auto &stamp=response.header().timestamp();
|
|
|
|
|
|
if(stamp.seconds()<=0||stamp.seconds()>std::numeric_limits<qint64>::max()/1000000000-1
|
|
|
|
|
|
||stamp.nanos()<0||stamp.nanos()>=1000000000||receivedNs<sentNs||receivedNs-sentNs>1500000000) {
|
|
|
|
|
|
reject(QStringLiteral("RGBD 服务响应时间戳无效或通信时间窗过大")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const qint64 serverResponseNs=stamp.seconds()*1000000000+stamp.nanos();
|
|
|
|
|
|
const qint64 colorAgeNs=serverResponseNs-rgb.capture_utc_ns();
|
|
|
|
|
|
const qint64 depthAgeNs=serverResponseNs-d.capture_utc_ns();
|
|
|
|
|
|
if(colorAgeNs<0||depthAgeNs<0||colorAgeNs>1500000000||depthAgeNs>1500000000) {
|
|
|
|
|
|
reject(QStringLiteral("RGBD 采集时间与服务器时钟不一致或图像已过期")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
// Exposure timestamps and feedback time share the server clock. Map
|
|
|
|
|
|
// their ages to the client request/response interval; retain the full
|
|
|
|
|
|
// interval instead of assuming the two hosts have identical clocks.
|
|
|
|
|
|
const qint64 colorLatestNs=receivedNs-colorAgeNs, depthLatestNs=receivedNs-depthAgeNs;
|
|
|
|
|
|
const int bytes=d.type()==cmvr::api::FrameData::U16C1?2:d.type()==cmvr::api::FrameData::F32C1?4:0;
|
|
|
|
|
|
const qint64 pixels=qint64(rgb.width())*rgb.height();
|
|
|
|
|
|
const auto raw=[](const cmvr::api::FrameData &f) { return f.codec().empty()||f.codec()=="none"; };
|
|
|
|
|
|
if(rgb.width()<2||rgb.height()<2||rgb.width()>16384||rgb.height()>16384||pixels>kGrpcMaxMessageBytes/7
|
|
|
|
|
|
||rgb.type()!=cmvr::api::FrameData::U8C3||!bytes||!raw(rgb)||!raw(d)
|
|
|
|
|
|
||d.width()!=rgb.width()||d.height()!=rgb.height()
|
|
|
|
|
|
||rgb.data().size()!=quint64(pixels*3)||d.data().size()!=quint64(pixels*bytes)
|
|
|
|
|
|
||!g.aligned_to_color()||!g.color_axial_z()||g.byte_order()!="little"
|
|
|
|
|
|
||!std::isfinite(g.metres_per_unit())||g.metres_per_unit()<=0||g.metres_per_unit()>1
|
|
|
|
|
|
||rgb.capture_utc_ns()<=0||d.capture_utc_ns()<=0
|
|
|
|
|
|
||std::abs(rgb.capture_utc_ns()-d.capture_utc_ns())>33000000
|
|
|
|
|
|
||(g.distortion_model()!="none"&&g.distortion_model()!="brown_conrady")) {
|
|
|
|
|
|
reject(QStringLiteral("RGBD 格式、配准、时间戳或公制深度信息无效")); return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantList coeffs;
|
|
|
|
|
|
for(float value:k.coeffs()) { if(!std::isfinite(value)) { reject(QStringLiteral("RGB 内参无效")); return; } coeffs<<double(value); }
|
|
|
|
|
|
if(!std::isfinite(k.fx())||!std::isfinite(k.fy())||k.fx()<=0||k.fy()<=0
|
|
|
|
|
|
||!std::isfinite(k.cx())||!std::isfinite(k.cy())||coeffs.size()!=5) { reject(QStringLiteral("RGB 内参无效")); return; }
|
|
|
|
|
|
const QImage borrowed(reinterpret_cast<const uchar*>(rgb.data().data()),rgb.width(),rgb.height(),rgb.width()*3,QImage::Format_RGB888);
|
|
|
|
|
|
const QImage image=borrowed.rgbSwapped(); // Owning RGB image; raw transport is OpenCV BGR.
|
|
|
|
|
|
const QVariantMap intrinsics{{"fx",double(k.fx())},{"fy",double(k.fy())},{"cx",double(k.cx())},{"cy",double(k.cy())},
|
|
|
|
|
|
{"width",rgb.width()},{"height",rgb.height()},{"coeffs",coeffs},{"model",QString::fromStdString(g.distortion_model())}};
|
|
|
|
|
|
const QVariantMap metadata{{"cameraSerial",QString::fromStdString(rgb.camera_serial())},{"cameraSessionGeneration",qulonglong(rgb.camera_session_generation())},
|
|
|
|
|
|
{"captureUtcNs",colorLatestNs},{"depthCaptureUtcNs",depthLatestNs},
|
|
|
|
|
|
{"captureEarliestLocalNs",sentNs-colorAgeNs},{"depthCaptureEarliestLocalNs",sentNs-depthAgeNs},
|
|
|
|
|
|
{"serverCaptureUtcNs",qint64(rgb.capture_utc_ns())},{"serverDepthCaptureUtcNs",qint64(d.capture_utc_ns())},
|
|
|
|
|
|
{"serverResponseUtcNs",serverResponseNs},{"captureTimeUncertaintyNs",receivedNs-sentNs},
|
|
|
|
|
|
{"alignedToColor",true},{"colorAxialZ",true},{"byteOrder","little"},{"metresPerUnit",g.metres_per_unit()},
|
|
|
|
|
|
{"depthWidth",d.width()},{"depthHeight",d.height()},{"depthFloat32",bytes==4},
|
|
|
|
|
|
{"depthData",QByteArray(d.data().data(),int(d.data().size()))}};
|
|
|
|
|
|
touchRgbdImageReceived(token,cameraId,image,intrinsics,metadata,true,QStringLiteral("已获取同步公制 RGBD"));
|
|
|
|
|
|
#else
|
|
|
|
|
|
reject(QStringLiteral("当前构建未启用 gRPC"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void depthSnapshot(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Depth Snapshot"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("Depth Snapshot"), cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
QImage image(640, 480, QImage::Format_RGB888);
|
|
|
|
|
|
for (int y = 0; y < image.height(); ++y) {
|
|
|
|
|
|
uchar *line = image.scanLine(y);
|
|
|
|
|
|
for (int x = 0; x < image.width(); ++x) {
|
|
|
|
|
|
const QColor color = QColor::fromHsvF(
|
|
|
|
|
|
(static_cast<double>(x) / image.width()) * 0.66, 0.9, 1.0);
|
|
|
|
|
|
line[x * 3] = static_cast<uchar>(color.red());
|
|
|
|
|
|
line[x * 3 + 1] = static_cast<uchar>(color.green());
|
|
|
|
|
|
line[x * 3 + 2] = static_cast<uchar>(color.blue());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
emit imageReceived(image, QStringLiteral("深度 · 640 x 480 · DEMO · 0–5 m"));
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Depth Snapshot"), true,
|
|
|
|
|
|
QStringLiteral("深度图像获取成功"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetDepthImageCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::GetDepthImageCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_camera->GetDepthImage(&context, request, &response);
|
|
|
|
|
|
if (!status.ok() || !response.header().success()) {
|
|
|
|
|
|
finish(QStringLiteral("Depth Snapshot"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &frame = response.depth_frame();
|
|
|
|
|
|
const QImage image = depthImageFromFrame(frame);
|
|
|
|
|
|
if (image.isNull()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Depth Snapshot"), false,
|
|
|
|
|
|
QStringLiteral("不支持的深度图格式:type=%1, codec=%2")
|
|
|
|
|
|
.arg(frame.type()).arg(QString::fromStdString(frame.codec())));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit imageReceived(image, QStringLiteral("深度 · %1 x %2 · %3 · 0–5 m")
|
|
|
|
|
|
.arg(frame.width()).arg(frame.height())
|
|
|
|
|
|
.arg(QString::fromStdString(frame.codec())));
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Depth Snapshot"), true,
|
|
|
|
|
|
QStringLiteral("深度图像获取成功"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void startDexHandTactileStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("DexHand Tactile Stream"))
|
|
|
|
|
|
|| !ensureDeviceId(QStringLiteral("DexHand Tactile Stream"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
stopDexHandTactileStreamInternal();
|
|
|
|
|
|
m_dexHandTactileStop.store(false);
|
|
|
|
|
|
m_dexHandTactileRunning.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const auto channel = m_channel;
|
|
|
|
|
|
m_dexHandTactileThread = std::thread([this, channel, deviceId]() {
|
|
|
|
|
|
auto stub = cmvr::api::DexHandService::NewStub(channel);
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_dexHandTactileContextMutex);
|
|
|
|
|
|
m_dexHandTactileContext = &context;
|
|
|
|
|
|
}
|
|
|
|
|
|
auto stream = stub->GetSensorDataStream(&context);
|
|
|
|
|
|
cmvr::api::GetSensorDataStreamCommand::Request request;
|
|
|
|
|
|
request.mutable_header()->set_device_id(deviceId.toStdString());
|
|
|
|
|
|
bool started = stream && stream->Write(request);
|
|
|
|
|
|
if (stream) stream->WritesDone();
|
|
|
|
|
|
quint64 frameCount = 0;
|
|
|
|
|
|
cmvr::api::GetSensorDataStreamCommand::Feedback response;
|
|
|
|
|
|
while (started && !m_dexHandTactileStop.load() && stream->Read(&response)) {
|
|
|
|
|
|
for (const auto &sensor : response.sensor()) {
|
|
|
|
|
|
if (sensor.finger_type() != cmvr::api::SensorData::INDEX)
|
|
|
|
|
|
continue;
|
|
|
|
|
|
QVariantList values;
|
|
|
|
|
|
values.reserve(sensor.rows() * sensor.cols());
|
|
|
|
|
|
for (const auto &row : sensor.data())
|
|
|
|
|
|
for (const auto value : row.values()) values.append(value);
|
|
|
|
|
|
++frameCount;
|
|
|
|
|
|
emit dexHandTactileReceived(deviceId, sensor.rows(), sensor.cols(),
|
|
|
|
|
|
values, frameCount);
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
grpc::Status status = stream ? stream->Finish()
|
|
|
|
|
|
: grpc::Status(grpc::StatusCode::UNKNOWN,
|
|
|
|
|
|
"cannot create tactile stream");
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_dexHandTactileContextMutex);
|
|
|
|
|
|
m_dexHandTactileContext = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool stopped = m_dexHandTactileStop.load();
|
|
|
|
|
|
emit dexHandTactileStreamStateChanged(
|
|
|
|
|
|
false, stopped ? QStringLiteral("食指触觉流已停止")
|
|
|
|
|
|
: QStringLiteral("食指触觉流结束:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(status.error_message())));
|
|
|
|
|
|
m_dexHandTactileRunning.store(false);
|
|
|
|
|
|
});
|
|
|
|
|
|
emit dexHandTactileStreamStateChanged(true, QStringLiteral("正在接收食指触觉数据"));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(deviceId)
|
|
|
|
|
|
m_dexHandTactileRunning.store(false);
|
|
|
|
|
|
emit dexHandTactileStreamStateChanged(false, QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopDexHandTactileStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
stopDexHandTactileStreamInternal();
|
|
|
|
|
|
emit dexHandTactileStreamStateChanged(false, QStringLiteral("食指触觉流已停止"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void startCameraStream(const QString &cameraId, const QString &codec,
|
|
|
|
|
|
const QString &mode)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Camera Stream")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("Camera Stream"), cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
|
|
const QString normalizedCameraId = cameraId.trimmed();
|
|
|
|
|
|
std::shared_ptr<CameraStreamSession> existing;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_cameraSessionsMutex);
|
|
|
|
|
|
const auto it = m_cameraSessions.find(normalizedCameraId);
|
|
|
|
|
|
if (it != m_cameraSessions.end())
|
|
|
|
|
|
existing = it.value();
|
|
|
|
|
|
}
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (existing && existing->running.load() && existing->mode == mode) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("Camera Stream"), false,
|
|
|
|
|
|
QStringLiteral("摄像头 %1 的视频预览已经在运行")
|
|
|
|
|
|
.arg(normalizedCameraId));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (existing) {
|
|
|
|
|
|
existing->superseded.store(existing->mode != mode);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
stopCameraStreamInternal(normalizedCameraId);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
|
|
|
|
|
|
auto session = std::make_shared<CameraStreamSession>();
|
|
|
|
|
|
session->cameraId = normalizedCameraId;
|
|
|
|
|
|
session->codec = codec.trimmed().toLower();
|
|
|
|
|
|
session->mode = mode.trimmed().toLower();
|
|
|
|
|
|
if (session->mode != QStringLiteral("depth") &&
|
|
|
|
|
|
session->mode != QStringLiteral("rgbd"))
|
|
|
|
|
|
session->mode = QStringLiteral("rgb");
|
|
|
|
|
|
if (session->codec.isEmpty())
|
|
|
|
|
|
session->codec = m_defaultCameraCodec;
|
|
|
|
|
|
session->running.store(true);
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_cameraSessionsMutex);
|
|
|
|
|
|
m_cameraSessions[normalizedCameraId] = session;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(normalizedCameraId, true,
|
|
|
|
|
|
QStringLiteral("正在建立视频流..."));
|
|
|
|
|
|
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
session->thread = std::thread([this, session]() {
|
|
|
|
|
|
int frameNumber = 0;
|
|
|
|
|
|
QElapsedTimer elapsed;
|
|
|
|
|
|
elapsed.start();
|
|
|
|
|
|
while (!session->stop.load()) {
|
|
|
|
|
|
QImage image(1280, 720, QImage::Format_RGB32);
|
|
|
|
|
|
image.fill(QColor("#20252b"));
|
|
|
|
|
|
QPainter painter(&image);
|
|
|
|
|
|
painter.setPen(QPen(QColor("#3b424b"), 1));
|
|
|
|
|
|
const int offset = frameNumber % 64;
|
|
|
|
|
|
for (int x = offset; x < image.width(); x += 64)
|
|
|
|
|
|
painter.drawLine(x, 0, x, image.height());
|
|
|
|
|
|
for (int y = offset; y < image.height(); y += 64)
|
|
|
|
|
|
painter.drawLine(0, y, image.width(), y);
|
|
|
|
|
|
painter.setPen(QColor("#e9edf2"));
|
|
|
|
|
|
painter.setFont(QFont("Microsoft YaHei UI", 28, QFont::DemiBold));
|
|
|
|
|
|
painter.drawText(image.rect().adjusted(0, -40, 0, 0), Qt::AlignCenter,
|
|
|
|
|
|
QStringLiteral("摄像头实时预览"));
|
|
|
|
|
|
painter.setPen(QColor("#9ca4ad"));
|
|
|
|
|
|
painter.setFont(QFont("Microsoft YaHei UI", 14));
|
|
|
|
|
|
painter.drawText(image.rect().adjusted(0, 48, 0, 0), Qt::AlignCenter,
|
|
|
|
|
|
QStringLiteral("%1 | DEMO | frame %2")
|
|
|
|
|
|
.arg(session->cameraId).arg(frameNumber));
|
|
|
|
|
|
const QString decodeCodec = session->codec == QStringLiteral("h265")
|
|
|
|
|
|
? QStringLiteral("H.265") : QStringLiteral("H.264");
|
|
|
|
|
|
if (videoFrameReceivedForCamera)
|
|
|
|
|
|
videoFrameReceivedForCamera(
|
|
|
|
|
|
session->cameraId, videoFrameFromImage(image),
|
|
|
|
|
|
QStringLiteral("1280 x 720 | DEMO / %1 | 30.0 FPS | #%2")
|
|
|
|
|
|
.arg(decodeCodec).arg(frameNumber));
|
|
|
|
|
|
++frameNumber;
|
|
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(33));
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (cameraStreamStateChangedForCamera && !session->superseded.load())
|
2026-09-18 16:22:20 +08:00
|
|
|
|
cameraStreamStateChangedForCamera(
|
|
|
|
|
|
session->cameraId, false,
|
|
|
|
|
|
QStringLiteral("视频预览已停止,%1 帧,%2 秒")
|
|
|
|
|
|
.arg(frameNumber)
|
|
|
|
|
|
.arg(elapsed.elapsed() / 1000.0, 0, 'f', 1));
|
|
|
|
|
|
});
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const std::shared_ptr<grpc::Channel> channel = m_channel;
|
|
|
|
|
|
session->thread = std::thread([this, channel, session]() {
|
|
|
|
|
|
if (session->mode == QStringLiteral("depth"))
|
|
|
|
|
|
runDepthCameraStream(channel, session, false);
|
|
|
|
|
|
else if (session->mode == QStringLiteral("rgbd"))
|
|
|
|
|
|
runDepthCameraStream(channel, session, true);
|
|
|
|
|
|
else
|
|
|
|
|
|
runCameraStream(channel, session);
|
|
|
|
|
|
});
|
|
|
|
|
|
#else
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(session->cameraId, false,
|
|
|
|
|
|
QStringLiteral("当前程序未编译 gRPC 支持"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopCameraStream(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
stopCameraStreamInternal(cameraId.trimmed());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void startCameraRecording(const QString &cameraId, const QString &videoPath)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("Camera Start Recording");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
const QString path = videoPath.trimmed();
|
|
|
|
|
|
if (path.isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("服务端录像路径不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_cameraRecording) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("相机已经在录像"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_cameraRecording = true;
|
|
|
|
|
|
emit cameraRecordingStateChanged(true,
|
|
|
|
|
|
QStringLiteral("演示录像中:%1").arg(path));
|
|
|
|
|
|
emit commandFinished(command, true, QStringLiteral("录像已开始(演示)"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::StartCameraRecordingCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
request.set_video_path(path.toStdString());
|
|
|
|
|
|
cmvr::api::StartCameraRecordingCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_camera->StartRecording(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
const QString error = status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
|
|
|
|
|
if (success) {
|
|
|
|
|
|
m_cameraRecording = true;
|
|
|
|
|
|
emit cameraRecordingStateChanged(true, QStringLiteral("录像中:%1").arg(path));
|
|
|
|
|
|
}
|
|
|
|
|
|
finish(command, status, response.header().success(), error);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopCameraRecording(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("Camera Stop Recording");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!m_cameraRecording) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("当前没有正在进行的录像"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_cameraRecording = false;
|
|
|
|
|
|
emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止"));
|
|
|
|
|
|
emit commandFinished(command, true, QStringLiteral("录像已停止(演示)"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::StopCameraRecordingCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::StopCameraRecordingCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 3000);
|
|
|
|
|
|
const grpc::Status status = m_camera->StopRecording(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
const QString error = status.ok()
|
|
|
|
|
|
? QString::fromStdString(response.header().error_message())
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
|
|
|
|
|
if (success) {
|
|
|
|
|
|
m_cameraRecording = false;
|
|
|
|
|
|
emit cameraRecordingStateChanged(false, QStringLiteral("录像已停止"));
|
|
|
|
|
|
}
|
|
|
|
|
|
finish(command, status, response.header().success(), error);
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void setCameraStreamCodec(const QString &codec)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString normalized = codec.trimmed().toLower();
|
|
|
|
|
|
const bool hevc = normalized == QStringLiteral("h265") ||
|
|
|
|
|
|
normalized == QStringLiteral("hevc") ||
|
|
|
|
|
|
normalized == QStringLiteral("h.265");
|
|
|
|
|
|
m_defaultCameraCodec = hevc ? QStringLiteral("h265") : QStringLiteral("h264");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void startSpeakerAudioStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("Speaker Stream")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("Speaker Stream"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_speakerStreamRunning.load()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Speaker Stream"), false,
|
|
|
|
|
|
QStringLiteral("扬声器音频流已经在运行"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_speakerStreamThread.joinable())
|
|
|
|
|
|
m_speakerStreamThread.join();
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerQueueMutex);
|
|
|
|
|
|
m_speakerQueue.clear();
|
|
|
|
|
|
m_speakerQueueBytes = 0;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_speakerStreamStop.store(false);
|
|
|
|
|
|
m_speakerStreamRunning.store(true);
|
|
|
|
|
|
m_speakerFrames.store(0);
|
|
|
|
|
|
m_speakerBytes.store(0);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true,
|
|
|
|
|
|
QStringLiteral("正在建立扬声器客户端音频流..."));
|
|
|
|
|
|
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("SpeakerService"), true,
|
|
|
|
|
|
QStringLiteral("演示模式:音频帧将在本地计数,不发送到设备"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const std::shared_ptr<grpc::Channel> channel = m_channel;
|
|
|
|
|
|
m_speakerStreamThread = std::thread([this, channel, deviceId]() {
|
|
|
|
|
|
runSpeakerAudioStream(channel, deviceId);
|
|
|
|
|
|
});
|
|
|
|
|
|
#else
|
|
|
|
|
|
m_speakerStreamRunning.store(false);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false,
|
|
|
|
|
|
QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void enqueueSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels,
|
|
|
|
|
|
qint64 pts, int samples)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!m_speakerStreamRunning.load() || data.isEmpty() ||
|
|
|
|
|
|
sampleRate <= 0 || channels <= 0 || samples <= 0)
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
const quint64 frames = ++m_speakerFrames;
|
|
|
|
|
|
const quint64 bytes = m_speakerBytes.fetch_add(data.size()) + data.size();
|
|
|
|
|
|
emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes,
|
|
|
|
|
|
pts / 1000 + samples * 1000LL / sampleRate);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
SpeakerAudioFrame frame;
|
|
|
|
|
|
frame.data = data;
|
|
|
|
|
|
frame.sampleRate = sampleRate;
|
|
|
|
|
|
frame.channels = channels;
|
|
|
|
|
|
frame.pts = pts;
|
|
|
|
|
|
frame.samples = samples;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerQueueMutex);
|
|
|
|
|
|
static const int kMaximumQueueBytes = 2 * 1024 * 1024;
|
|
|
|
|
|
while (!m_speakerQueue.empty() &&
|
|
|
|
|
|
m_speakerQueueBytes + data.size() > kMaximumQueueBytes) {
|
|
|
|
|
|
m_speakerQueueBytes -= m_speakerQueue.front().data.size();
|
|
|
|
|
|
m_speakerQueue.pop_front();
|
|
|
|
|
|
}
|
|
|
|
|
|
m_speakerQueue.push_back(std::move(frame));
|
|
|
|
|
|
m_speakerQueueBytes += data.size();
|
|
|
|
|
|
}
|
|
|
|
|
|
m_speakerQueueCondition.notify_one();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopSpeakerAudioStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
stopSpeakerStreamInternal();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void startMicrophoneAudioStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("MicPhone Stream")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("MicPhone Stream"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_microphoneStreamRunning.load()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("MicPhone Stream"), false,
|
|
|
|
|
|
QStringLiteral("麦克风音频流已经在运行"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_microphoneStreamThread.joinable())
|
|
|
|
|
|
m_microphoneStreamThread.join();
|
|
|
|
|
|
m_microphoneStreamStop.store(false);
|
|
|
|
|
|
m_microphoneStreamRunning.store(true);
|
|
|
|
|
|
m_microphoneFrames.store(0);
|
|
|
|
|
|
m_microphoneBytes.store(0);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true,
|
|
|
|
|
|
QStringLiteral("正在建立麦克风服务端音频流..."));
|
|
|
|
|
|
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_microphoneStreamThread = std::thread([this]() {
|
|
|
|
|
|
const int sampleRate = 48000;
|
|
|
|
|
|
const int samples = sampleRate / 50;
|
|
|
|
|
|
const double pi = 3.14159265358979323846;
|
|
|
|
|
|
qint64 sampleIndex = 0;
|
|
|
|
|
|
while (!m_microphoneStreamStop.load()) {
|
|
|
|
|
|
QByteArray pcm(samples * 2, Qt::Uninitialized);
|
|
|
|
|
|
qint16 *output = reinterpret_cast<qint16 *>(pcm.data());
|
|
|
|
|
|
for (int i = 0; i < samples; ++i) {
|
|
|
|
|
|
output[i] = static_cast<qint16>(
|
|
|
|
|
|
1800.0 * qSin((sampleIndex + i) * 2.0 * pi * 440.0 / sampleRate));
|
|
|
|
|
|
}
|
|
|
|
|
|
const qint64 pts = sampleIndex * 1000000LL / sampleRate;
|
|
|
|
|
|
sampleIndex += samples;
|
|
|
|
|
|
const quint64 frames = ++m_microphoneFrames;
|
|
|
|
|
|
const quint64 bytes = m_microphoneBytes.fetch_add(pcm.size()) + pcm.size();
|
|
|
|
|
|
emit audioFrameReceived(pcm, sampleRate, 1, 0,
|
|
|
|
|
|
QStringLiteral("pcm_s16le"), pts, samples);
|
|
|
|
|
|
emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes,
|
|
|
|
|
|
sampleIndex * 1000LL / sampleRate);
|
|
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
|
|
|
|
}
|
|
|
|
|
|
m_microphoneStreamRunning.store(false);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false,
|
|
|
|
|
|
QStringLiteral("麦克风音频拉流已停止"));
|
|
|
|
|
|
});
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), true,
|
|
|
|
|
|
QStringLiteral("演示模式:正在播放本地测试音"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const std::shared_ptr<grpc::Channel> channel = m_channel;
|
|
|
|
|
|
m_microphoneStreamThread = std::thread([this, channel, deviceId]() {
|
|
|
|
|
|
runMicrophoneAudioStream(channel, deviceId);
|
|
|
|
|
|
});
|
|
|
|
|
|
#else
|
|
|
|
|
|
m_microphoneStreamRunning.store(false);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false,
|
|
|
|
|
|
QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopMicrophoneAudioStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
stopMicrophoneStreamInternal();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void systemRefresh()
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("System Refresh")))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
QVariantMap info;
|
|
|
|
|
|
info.insert(QStringLiteral("name"), QStringLiteral("CMVR Demo Controller"));
|
|
|
|
|
|
info.insert(QStringLiteral("version"), QStringLiteral("demo-1.0"));
|
2026-09-23 11:11:49 +08:00
|
|
|
|
QString platform = QSysInfo::prettyProductName();
|
|
|
|
|
|
if (platform.isEmpty())
|
|
|
|
|
|
platform = QSysInfo::productType();
|
|
|
|
|
|
info.insert(QStringLiteral("os"), platform + QStringLiteral(" / simulator"));
|
|
|
|
|
|
info.insert(QStringLiteral("architecture"), QSysInfo::currentCpuArchitecture());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit systemInfoReceived(info);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
emit systemStatusReceived(34.0, 48.0, 62.0, demoDeviceList());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("System Refresh"), true, QStringLiteral("系统信息已刷新"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::GetSystemInfoCommand::Request request;
|
|
|
|
|
|
cmvr::api::GetSystemInfoCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1200);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
const grpc::Status infoStatus = m_system->GetSystemInfo(&context, request, &response);
|
|
|
|
|
|
if (infoStatus.ok() && response.header().success()) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QVariantMap info;
|
|
|
|
|
|
info.insert(QStringLiteral("name"), QString::fromStdString(response.system_name()));
|
|
|
|
|
|
info.insert(QStringLiteral("version"), QString::fromStdString(response.version()));
|
|
|
|
|
|
info.insert(QStringLiteral("description"), QString::fromStdString(response.description()));
|
|
|
|
|
|
info.insert(QStringLiteral("os"), QString::fromStdString(response.os()));
|
|
|
|
|
|
info.insert(QStringLiteral("kernel"), QString::fromStdString(response.kernel_version()));
|
|
|
|
|
|
info.insert(QStringLiteral("architecture"), QString::fromStdString(response.architecture()));
|
|
|
|
|
|
emit systemInfoReceived(info);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
|
|
|
|
|
|
cmvr::api::GetSystemStatusCommand::Request statusRequest;
|
|
|
|
|
|
cmvr::api::GetSystemStatusCommand::Feedback statusResponse;
|
|
|
|
|
|
grpc::ClientContext statusContext;
|
|
|
|
|
|
setDeadline(statusContext, 1200);
|
|
|
|
|
|
const grpc::Status status = m_system->GetSystemStatus(
|
|
|
|
|
|
&statusContext, statusRequest, &statusResponse);
|
|
|
|
|
|
if (status.ok() && statusResponse.header().success()) {
|
|
|
|
|
|
const double memory = statusResponse.mem_total_mb() > 0
|
|
|
|
|
|
? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0;
|
|
|
|
|
|
const double disk = statusResponse.disk_total_gb() > 0
|
|
|
|
|
|
? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0;
|
|
|
|
|
|
emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk,
|
2026-10-26 17:35:27 +08:00
|
|
|
|
discoverLegacyArms(statusResponse));
|
2026-09-23 11:11:49 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (!infoStatus.ok() || !response.header().success()) {
|
|
|
|
|
|
finish(QStringLiteral("System Refresh"), infoStatus, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
} else {
|
|
|
|
|
|
finish(QStringLiteral("System Refresh"), status, statusResponse.header().success(),
|
|
|
|
|
|
QString::fromStdString(statusResponse.header().error_message()));
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void systemStopAll(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("System StopAll")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("System StopAll"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("System StopAll"), true, QStringLiteral("全局停止命令已执行"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::StopAllCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::StopAllCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1800);
|
|
|
|
|
|
const grpc::Status status = m_system->StopAll(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("System StopAll"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvRefresh(const QString &deviceId)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV Refresh"))) {
|
|
|
|
|
|
emitAgvStateUnavailable(deviceId, QStringLiteral("设备尚未连接"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
}
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("AGV Refresh"), deviceId)) {
|
|
|
|
|
|
emitAgvStateUnavailable(deviceId, QStringLiteral("请填写 AGV 设备 ID"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (m_demoMode) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap state = agvContext(deviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("connected"), true);
|
|
|
|
|
|
state.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
state.insert(QStringLiteral("mode"), 2);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("localized"), true);
|
|
|
|
|
|
state.insert(QStringLiteral("moving"), false);
|
|
|
|
|
|
state.insert(QStringLiteral("fault"), false);
|
|
|
|
|
|
state.insert(QStringLiteral("emergency"), false);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
state.insert(QStringLiteral("map"), demoAgvCurrentMap(deviceId));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("station"), QStringLiteral("HOME"));
|
|
|
|
|
|
state.insert(QStringLiteral("battery"), 0.82);
|
|
|
|
|
|
state.insert(QStringLiteral("voltage"), 49.2);
|
|
|
|
|
|
state.insert(QStringLiteral("current"), -2.9);
|
|
|
|
|
|
state.insert(QStringLiteral("temperature"), 28.0);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
state.insert(QStringLiteral("charging"), false);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("x"), 1.24);
|
|
|
|
|
|
state.insert(QStringLiteral("y"), -0.36);
|
|
|
|
|
|
state.insert(QStringLiteral("theta"), 0.12);
|
|
|
|
|
|
QVariantMap navigation;
|
|
|
|
|
|
navigation.insert(QStringLiteral("state"), 0);
|
|
|
|
|
|
navigation.insert(QStringLiteral("type"), 0);
|
|
|
|
|
|
navigation.insert(QStringLiteral("progress"), 0.0);
|
|
|
|
|
|
navigation.insert(QStringLiteral("message"), QStringLiteral("空闲"));
|
|
|
|
|
|
emit agvStateReceived(state, navigation);
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV Refresh"), true, QStringLiteral("AGV 状态已刷新"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvRuntimeStateCommand::Request stateRequest;
|
|
|
|
|
|
fillHeader(stateRequest.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::AgvRuntimeStateCommand::Feedback stateResponse;
|
|
|
|
|
|
grpc::ClientContext stateContext;
|
|
|
|
|
|
setDeadline(stateContext, 1000);
|
|
|
|
|
|
const grpc::Status stateStatus = m_agv->getRuntimeState(&stateContext, stateRequest, &stateResponse);
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::AgvNavigationStatusCommand::Request navRequest;
|
|
|
|
|
|
fillHeader(navRequest.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::AgvNavigationStatusCommand::Feedback navResponse;
|
|
|
|
|
|
grpc::ClientContext navContext;
|
|
|
|
|
|
setDeadline(navContext, 1000);
|
|
|
|
|
|
const grpc::Status navStatus = m_agv->getNavigationStatus(&navContext, navRequest, &navResponse);
|
|
|
|
|
|
|
|
|
|
|
|
if (stateStatus.ok() && stateResponse.header().success()) {
|
|
|
|
|
|
const auto &source = stateResponse.state();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap state = agvContext(deviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("connected"), source.connected());
|
|
|
|
|
|
state.insert(QStringLiteral("timestamp"), source.timestamp());
|
|
|
|
|
|
state.insert(QStringLiteral("mode"), source.mode());
|
|
|
|
|
|
state.insert(QStringLiteral("localized"), source.localized());
|
|
|
|
|
|
state.insert(QStringLiteral("moving"), source.moving());
|
|
|
|
|
|
state.insert(QStringLiteral("fault"), source.fault());
|
|
|
|
|
|
state.insert(QStringLiteral("emergency"), source.emergency_stopped());
|
|
|
|
|
|
state.insert(QStringLiteral("map"), QString::fromStdString(source.current_map()));
|
|
|
|
|
|
state.insert(QStringLiteral("station"), QString::fromStdString(source.current_station()));
|
|
|
|
|
|
state.insert(QStringLiteral("battery"), source.battery().percentage());
|
|
|
|
|
|
state.insert(QStringLiteral("voltage"), source.battery().voltage());
|
|
|
|
|
|
state.insert(QStringLiteral("current"), source.battery().current());
|
|
|
|
|
|
state.insert(QStringLiteral("temperature"), source.battery().temperature());
|
2026-10-14 17:15:46 +08:00
|
|
|
|
state.insert(QStringLiteral("charging"), source.battery().charging());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
state.insert(QStringLiteral("x"), source.pose().x());
|
|
|
|
|
|
state.insert(QStringLiteral("y"), source.pose().y());
|
|
|
|
|
|
state.insert(QStringLiteral("theta"), source.pose().theta());
|
|
|
|
|
|
state.insert(QStringLiteral("vx"), source.velocity().vx());
|
|
|
|
|
|
state.insert(QStringLiteral("vy"), source.velocity().vy());
|
|
|
|
|
|
state.insert(QStringLiteral("wz"), source.velocity().wz());
|
|
|
|
|
|
state.insert(QStringLiteral("error"), QString::fromStdString(source.last_error()));
|
|
|
|
|
|
QVariantMap navigation;
|
|
|
|
|
|
if (navStatus.ok() && navResponse.header().success()) {
|
|
|
|
|
|
navigation.insert(QStringLiteral("state"), navResponse.status().state());
|
|
|
|
|
|
navigation.insert(QStringLiteral("type"), navResponse.status().type());
|
|
|
|
|
|
navigation.insert(QStringLiteral("progress"), navResponse.status().progress());
|
|
|
|
|
|
navigation.insert(QStringLiteral("message"), QString::fromStdString(navResponse.status().message()));
|
|
|
|
|
|
}
|
|
|
|
|
|
emit agvStateReceived(state, navigation);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
const QString responseError = QString::fromStdString(stateResponse.header().error_message());
|
|
|
|
|
|
QString detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了状态查询")
|
|
|
|
|
|
: responseError;
|
|
|
|
|
|
if (!stateStatus.ok()) {
|
|
|
|
|
|
const QString message = QString::fromStdString(stateStatus.error_message());
|
|
|
|
|
|
detail = QStringLiteral("gRPC code %1:%2")
|
|
|
|
|
|
.arg(static_cast<int>(stateStatus.error_code()))
|
|
|
|
|
|
.arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情") : message);
|
|
|
|
|
|
}
|
|
|
|
|
|
emitAgvStateUnavailable(deviceId, detail);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
finish(QStringLiteral("AGV Refresh"), stateStatus, stateResponse.header().success(),
|
|
|
|
|
|
QString::fromStdString(stateResponse.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void agvRelocalize(const QString &deviceId, double x, double y, double theta)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("AGV Relocalize");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!qIsFinite(x) || !qIsFinite(y) || !qIsFinite(theta)) {
|
|
|
|
|
|
emit commandFinished(command, false,
|
|
|
|
|
|
QStringLiteral("重新定位位姿必须是有效数值"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true,
|
|
|
|
|
|
QStringLiteral("重新定位位姿已下发"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvRelocalizeCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.mutable_pose()->set_x(x);
|
|
|
|
|
|
request.mutable_pose()->set_y(y);
|
|
|
|
|
|
request.mutable_pose()->set_theta(theta);
|
|
|
|
|
|
cmvr::api::AgvRelocalizeCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_agv->relocalize(&context, request, &response);
|
|
|
|
|
|
finish(command, status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void agvNavigatePose(const QString &deviceId, double x, double y, double theta, double maxSpeed)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV NavigateToPose")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("AGV NavigateToPose"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV NavigateToPose"), true,
|
|
|
|
|
|
QStringLiteral("目标位姿 (%1, %2, %3) 已下发").arg(x).arg(y).arg(theta));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvNavigateToPoseCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.mutable_pose()->set_x(x);
|
|
|
|
|
|
request.mutable_pose()->set_y(y);
|
|
|
|
|
|
request.mutable_pose()->set_theta(theta);
|
|
|
|
|
|
request.mutable_options()->set_max_speed(maxSpeed);
|
|
|
|
|
|
request.mutable_options()->set_asynchronous(true);
|
|
|
|
|
|
cmvr::api::AgvNavigateToPoseCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_agv->navigateToPose(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("AGV NavigateToPose"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvNavigateStation(const QString &deviceId, const QString &stationId, double maxSpeed)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV NavigateToStation")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("AGV NavigateToStation"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (stationId.trimmed().isEmpty()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV NavigateToStation"), false, QStringLiteral("站点 ID 不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV NavigateToStation"), true,
|
|
|
|
|
|
QStringLiteral("目标站点 %1 已下发").arg(stationId));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvNavigateToStationCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_station_id(stationId.toStdString());
|
|
|
|
|
|
request.mutable_options()->set_max_speed(maxSpeed);
|
|
|
|
|
|
request.mutable_options()->set_asynchronous(true);
|
|
|
|
|
|
cmvr::api::AgvNavigateToStationCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_agv->navigateToStation(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("AGV NavigateToStation"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvFollowPath(const QString &deviceId, const QVariantList &path, double maxSpeed)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("AGV FollowPath");
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (path.isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("路径至少需要包含一个有效路径段"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true,
|
|
|
|
|
|
QStringLiteral("包含 %1 个路径段的导航任务已下发").arg(path.size()));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvFollowPathCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
for (const QVariant &entry : path) {
|
|
|
|
|
|
const QVariantMap segmentValue = entry.toMap();
|
|
|
|
|
|
const QString source = segmentValue.value(QStringLiteral("sourceStation")).toString().trimmed();
|
|
|
|
|
|
const QString target = segmentValue.value(QStringLiteral("targetStation")).toString().trimmed();
|
|
|
|
|
|
if (source.isEmpty() || target.isEmpty()) {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("路径段的起点和终点不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::msgs::AgvPathSegment *segment = request.add_path();
|
|
|
|
|
|
segment->set_source_station(source.toStdString());
|
|
|
|
|
|
segment->set_target_station(target.toStdString());
|
|
|
|
|
|
}
|
|
|
|
|
|
request.mutable_options()->set_max_speed(maxSpeed);
|
|
|
|
|
|
request.mutable_options()->set_asynchronous(true);
|
|
|
|
|
|
cmvr::api::AgvFollowPathCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_agv->followPath(&context, request, &response);
|
|
|
|
|
|
finish(command, status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
bool agvVelocity(const QString &deviceId, double vx, double vy, double wz,
|
|
|
|
|
|
QString *resultDetail = nullptr)
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV SetVelocity"))) {
|
|
|
|
|
|
if (resultDetail)
|
|
|
|
|
|
*resultDetail = QStringLiteral("设备尚未连接");
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!ensureDeviceId(QStringLiteral("AGV SetVelocity"), deviceId)) {
|
|
|
|
|
|
if (resultDetail)
|
|
|
|
|
|
*resultDetail = QStringLiteral("请在对应服务页填写设备 ID");
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (m_demoMode) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (resultDetail)
|
|
|
|
|
|
*resultDetail = QStringLiteral("底盘速度已下发");
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("AGV SetVelocity"), true, QStringLiteral("底盘速度已下发"));
|
2026-11-10 16:10:46 +08:00
|
|
|
|
return true;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvSetVelocityCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.mutable_velocity()->set_vx(vx);
|
|
|
|
|
|
request.mutable_velocity()->set_vy(vy);
|
|
|
|
|
|
request.mutable_velocity()->set_wz(wz);
|
|
|
|
|
|
cmvr::api::AgvSetVelocityCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1200);
|
|
|
|
|
|
const grpc::Status status = m_agv->setVelocity(&context, request, &response);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
return finishAgvVelocity(QStringLiteral("AGV SetVelocity"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()), resultDetail);
|
|
|
|
|
|
#else
|
|
|
|
|
|
if (resultDetail)
|
|
|
|
|
|
*resultDetail = QStringLiteral("当前程序未编译 gRPC 支持");
|
|
|
|
|
|
return false;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvAction(const QString &deviceId, const QString &action)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("AGV %1").arg(action);
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true, QStringLiteral("AGV 操作已执行"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, deviceId);
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 1500);
|
|
|
|
|
|
grpc::Status status;
|
|
|
|
|
|
if (action == QStringLiteral("EmergencyStop"))
|
|
|
|
|
|
status = m_agv->emergencyStop(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("ClearFault"))
|
|
|
|
|
|
status = m_agv->clearFault(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("Pause"))
|
|
|
|
|
|
status = m_agv->pauseNavigation(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("Resume"))
|
|
|
|
|
|
status = m_agv->resumeNavigation(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("Cancel"))
|
|
|
|
|
|
status = m_agv->cancelNavigation(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("StopVelocity"))
|
|
|
|
|
|
status = m_agv->stopVelocityControl(&context, request, &response);
|
|
|
|
|
|
else if (action == QStringLiteral("StopMapping"))
|
|
|
|
|
|
status = m_agv->stopMapping(&context, request, &response);
|
|
|
|
|
|
else {
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("未知 AGV 操作"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
finish(command, status, response.success(), QString::fromStdString(response.error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvInventory(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV Inventory")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("AGV Inventory"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QStringList maps = {QStringLiteral("demo_map"), QStringLiteral("warehouse")};
|
|
|
|
|
|
const QString keyPrefix = demoAgvMapKey(deviceId, QString());
|
|
|
|
|
|
for (auto it = m_demoAgvMapContents.cbegin(); it != m_demoAgvMapContents.cend(); ++it) {
|
|
|
|
|
|
if (it.key().startsWith(keyPrefix)) {
|
|
|
|
|
|
const QString name = it.key().mid(keyPrefix.size());
|
|
|
|
|
|
if (!maps.contains(name))
|
|
|
|
|
|
maps.append(name);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
const QVariantList stations = demoAgvStations(
|
|
|
|
|
|
demoAgvMapContent(deviceId, demoAgvCurrentMap(deviceId)));
|
|
|
|
|
|
emit agvInventoryReceived(agvContext(deviceId), maps, stations);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("AGV Inventory"), true, QStringLiteral("地图与站点已刷新"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvListMapsCommand::Request mapsRequest;
|
|
|
|
|
|
fillHeader(mapsRequest.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::AgvListMapsCommand::Feedback mapsResponse;
|
|
|
|
|
|
grpc::ClientContext mapsContext;
|
|
|
|
|
|
setDeadline(mapsContext, 1200);
|
|
|
|
|
|
const grpc::Status mapsStatus = m_agv->listMaps(&mapsContext, mapsRequest, &mapsResponse);
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::AgvListStationsCommand::Request stationsRequest;
|
|
|
|
|
|
fillHeader(stationsRequest.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::AgvListStationsCommand::Feedback stationsResponse;
|
|
|
|
|
|
grpc::ClientContext stationsContext;
|
|
|
|
|
|
setDeadline(stationsContext, 1200);
|
|
|
|
|
|
const grpc::Status stationsStatus = m_agv->listStations(&stationsContext, stationsRequest, &stationsResponse);
|
|
|
|
|
|
|
|
|
|
|
|
if (mapsStatus.ok() && mapsResponse.header().success()) {
|
|
|
|
|
|
QStringList maps;
|
|
|
|
|
|
for (const auto &mapName : mapsResponse.maps())
|
|
|
|
|
|
maps.append(QString::fromStdString(mapName));
|
|
|
|
|
|
QVariantList stations;
|
|
|
|
|
|
if (stationsStatus.ok() && stationsResponse.header().success()) {
|
|
|
|
|
|
for (const auto &source : stationsResponse.stations()) {
|
|
|
|
|
|
QVariantMap station;
|
|
|
|
|
|
station.insert(QStringLiteral("id"), QString::fromStdString(source.id()));
|
|
|
|
|
|
station.insert(QStringLiteral("type"), QString::fromStdString(source.type()));
|
|
|
|
|
|
station.insert(QStringLiteral("description"), QString::fromStdString(source.description()));
|
|
|
|
|
|
station.insert(QStringLiteral("x"), source.pose().x());
|
|
|
|
|
|
station.insert(QStringLiteral("y"), source.pose().y());
|
|
|
|
|
|
station.insert(QStringLiteral("theta"), source.pose().theta());
|
|
|
|
|
|
stations.append(station);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvInventoryReceived(agvContext(deviceId), maps, stations);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
finish(QStringLiteral("AGV Inventory"), mapsStatus, mapsResponse.header().success(),
|
|
|
|
|
|
QString::fromStdString(mapsResponse.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void agvSwitchMap(const QString &deviceId, const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV SwitchMap")) ||
|
|
|
|
|
|
!ensureDeviceId(QStringLiteral("AGV SwitchMap"), deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (mapName.trimmed().isEmpty()) {
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV SwitchMap"), false, QStringLiteral("地图名称不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_demoAgvCurrentMaps.insert(deviceId.trimmed(), mapName.trimmed());
|
|
|
|
|
|
demoAgvMapContent(deviceId, mapName);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("AGV SwitchMap"), true,
|
|
|
|
|
|
QStringLiteral("已切换到地图 %1").arg(mapName));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_map_name(mapName.toStdString());
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
const grpc::Status status = m_agv->switchMap(&context, request, &response);
|
|
|
|
|
|
finish(QStringLiteral("AGV SwitchMap"), status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void requestAgvMapContent(quint64 requestId, const QString &deviceId,
|
|
|
|
|
|
const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString validationError = agvMapRequestError(deviceId, mapName);
|
|
|
|
|
|
if (!validationError.isEmpty()) {
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName, QString(),
|
|
|
|
|
|
false, validationError);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName,
|
|
|
|
|
|
demoAgvMapContent(deviceId, mapName), true,
|
|
|
|
|
|
QStringLiteral("演示地图已读取"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!m_agv) {
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName, QString(),
|
|
|
|
|
|
false, QStringLiteral("AGV 服务尚未连接"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId.trimmed(), 4000);
|
|
|
|
|
|
request.set_map_name(mapName.trimmed().toStdString());
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 4000);
|
|
|
|
|
|
const grpc::Status status = m_agv->downloadMap(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
QString detail = success ? QStringLiteral("地图已读取")
|
|
|
|
|
|
: QString::fromStdString(status.ok() ? response.header().error_message()
|
|
|
|
|
|
: status.error_message());
|
|
|
|
|
|
if (detail.isEmpty())
|
|
|
|
|
|
detail = QStringLiteral("读取地图失败,服务端未返回错误详情");
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName,
|
|
|
|
|
|
success ? QString::fromStdString(response.content()) : QString(),
|
|
|
|
|
|
success, detail);
|
|
|
|
|
|
#else
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName, QString(), false,
|
|
|
|
|
|
QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void saveAgvMapContent(quint64 requestId, const QString &deviceId,
|
|
|
|
|
|
const QString &mapName, const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString validationError = agvMapRequestError(deviceId, mapName);
|
|
|
|
|
|
if (!validationError.isEmpty()) {
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, false, validationError);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
m_demoAgvMapContents.insert(demoAgvMapKey(deviceId, mapName), content);
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, true,
|
|
|
|
|
|
QStringLiteral("演示地图已保存"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!m_agv) {
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, false,
|
|
|
|
|
|
QStringLiteral("AGV 服务尚未连接"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId.trimmed(), 10000);
|
|
|
|
|
|
request.set_map_name(mapName.trimmed().toStdString());
|
|
|
|
|
|
request.set_content(content.toStdString());
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 10000);
|
|
|
|
|
|
const grpc::Status status = m_agv->uploadMap(&context, request, &response);
|
|
|
|
|
|
const bool success = status.ok() && response.header().success();
|
|
|
|
|
|
QString detail = success ? QStringLiteral("地图已保存")
|
|
|
|
|
|
: QString::fromStdString(status.ok() ? response.header().error_message()
|
|
|
|
|
|
: status.error_message());
|
|
|
|
|
|
if (detail.isEmpty())
|
|
|
|
|
|
detail = QStringLiteral("保存地图失败,服务端未返回错误详情");
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, success, detail);
|
|
|
|
|
|
#else
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, false,
|
|
|
|
|
|
QStringLiteral("当前程序未编译 gRPC 支持"));
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void startAgvMapStream(const QString &deviceId, const QString &mapName,
|
2026-11-10 16:10:46 +08:00
|
|
|
|
int dimension, bool snapshot, bool incremental,
|
|
|
|
|
|
quint64 generation, bool preview)
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap sourceContext = agvContext(deviceId);
|
|
|
|
|
|
sourceContext.insert(QStringLiteral("mapId"), mapName.trimmed());
|
|
|
|
|
|
sourceContext.insert(QStringLiteral("streamGeneration"), generation);
|
|
|
|
|
|
sourceContext.insert(QStringLiteral("preview"), preview);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (!ensureConnected(QStringLiteral("AGV StreamMap")) ||
|
2026-11-10 16:10:46 +08:00
|
|
|
|
!ensureDeviceId(QStringLiteral("AGV StreamMap"), deviceId)) {
|
|
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, false,
|
|
|
|
|
|
deviceId.trimmed().isEmpty() ? QStringLiteral("AGV 设备 ID 不能为空")
|
|
|
|
|
|
: QStringLiteral("AGV 尚未连接"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
stopAgvMapStreamInternal();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_agvMapStreamSourceContext = sourceContext;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_agvMapStreamStop.store(false);
|
|
|
|
|
|
m_agvMapStreamRunning.store(true);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, true, QStringLiteral("正在等待地图数据"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
|
|
|
|
|
|
if (m_demoMode) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
const QString demoMap = mapName.trimmed().isEmpty()
|
|
|
|
|
|
? demoAgvCurrentMap(deviceId) : mapName.trimmed();
|
|
|
|
|
|
const QJsonObject root = QJsonDocument::fromJson(
|
|
|
|
|
|
demoAgvMapContent(deviceId, demoMap).toUtf8()).object();
|
|
|
|
|
|
const QJsonObject header = root.value(QStringLiteral("header")).toObject();
|
|
|
|
|
|
const QJsonObject minimum = header.value(QStringLiteral("min_pos")).toObject();
|
|
|
|
|
|
const QJsonObject maximum = header.value(QStringLiteral("max_pos")).toObject();
|
|
|
|
|
|
const double resolution = header.value(QStringLiteral("resolution")).toDouble(0.04);
|
|
|
|
|
|
const double originX = minimum.value(QStringLiteral("x")).toDouble();
|
|
|
|
|
|
const double originY = minimum.value(QStringLiteral("y")).toDouble();
|
|
|
|
|
|
const int width = qRound((maximum.value(QStringLiteral("x")).toDouble() - originX) / resolution);
|
|
|
|
|
|
const int height = qRound((maximum.value(QStringLiteral("y")).toDouble() - originY) / resolution);
|
|
|
|
|
|
if (width <= 0 || height <= 0) {
|
|
|
|
|
|
m_agvMapStreamRunning.store(false);
|
|
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, false, QStringLiteral("演示扫描地图资源加载失败"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
// The raster and editable SMAP share the same measured scan coordinates.
|
|
|
|
|
|
QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
|
|
|
|
|
|
image.fill(Qt::transparent);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QPainter painter(&image);
|
|
|
|
|
|
painter.setRenderHint(QPainter::Antialiasing);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
painter.setPen(QPen(QColor(107, 125, 140, 210), 1.3,
|
|
|
|
|
|
Qt::SolidLine, Qt::RoundCap));
|
|
|
|
|
|
for (const QJsonValue &value : root.value(QStringLiteral("normal_pos_list")).toArray()) {
|
|
|
|
|
|
const QJsonObject point = value.toObject();
|
|
|
|
|
|
painter.drawPoint(QPointF(
|
|
|
|
|
|
(point.value(QStringLiteral("x")).toDouble() - originX) / resolution,
|
|
|
|
|
|
height - (point.value(QStringLiteral("y")).toDouble() - originY) / resolution));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
painter.end();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap metadata = sourceContext;
|
|
|
|
|
|
metadata.insert(QStringLiteral("mapId"), demoMap);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("dimension"), 2);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("originX"), originX);
|
|
|
|
|
|
metadata.insert(QStringLiteral("originY"), originY);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("originTheta"), 0.0);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("resolution"), resolution);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("sourceWidth"), image.width());
|
|
|
|
|
|
metadata.insert(QStringLiteral("sourceHeight"), image.height());
|
|
|
|
|
|
metadata.insert(QStringLiteral("renderScale"), 1.0);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("demo"), true);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("timestamp"),
|
|
|
|
|
|
QDateTime::currentMSecsSinceEpoch() / 1000.0);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvMapFrameReceived(image, metadata, QStringLiteral("演示扫描地图 · Demo"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
m_agvMapStreamThread = std::thread(
|
2026-11-10 16:10:46 +08:00
|
|
|
|
[this, deviceId, mapName, dimension, snapshot, incremental, sourceContext, preview]() {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
cmvr::api::AgvMapStreamCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
request.set_map_name(mapName.toStdString());
|
|
|
|
|
|
request.set_dimension(static_cast<cmvr::msgs::AgvMapDimension>(dimension));
|
|
|
|
|
|
request.set_snapshot(snapshot);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
request.set_incremental(preview ? false : incremental);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
request.set_max_chunk_bytes(1024 * 1024);
|
|
|
|
|
|
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_agvMapStreamContextMutex);
|
|
|
|
|
|
m_agvMapStreamContext = &context;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
// Stop may run before this thread publishes its context.
|
|
|
|
|
|
// Check under the same lock used by Stop so cancellation is
|
|
|
|
|
|
// remembered even when no RPC existed at that point.
|
|
|
|
|
|
if (m_agvMapStreamStop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
QString streamError;
|
|
|
|
|
|
QString rawMapId;
|
|
|
|
|
|
QString rawAttemptId;
|
|
|
|
|
|
QString rawAttemptError;
|
|
|
|
|
|
QImage rawMapImage;
|
|
|
|
|
|
QVariantMap rawMapMetadata;
|
|
|
|
|
|
bool frameDelivered = false;
|
|
|
|
|
|
bool incompleteReported = false;
|
|
|
|
|
|
const auto readRawMap = [&](const QString &actualMap) {
|
|
|
|
|
|
if (rawMapId == actualMap)
|
|
|
|
|
|
return true;
|
|
|
|
|
|
if (rawAttemptId == actualMap)
|
|
|
|
|
|
return false;
|
|
|
|
|
|
rawAttemptId = actualMap;
|
|
|
|
|
|
rawAttemptError.clear();
|
|
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, true,
|
|
|
|
|
|
QStringLiteral("正在读取地图 %1…").arg(actualMap));
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Request rawRequest;
|
|
|
|
|
|
fillHeader(rawRequest.mutable_header(), deviceId.trimmed(), 4000);
|
|
|
|
|
|
rawRequest.set_map_name(actualMap.toStdString());
|
|
|
|
|
|
cmvr::api::AgvMapCommand::Feedback rawResponse;
|
|
|
|
|
|
grpc::ClientContext rawContext;
|
|
|
|
|
|
setDeadline(rawContext, 4000);
|
|
|
|
|
|
const grpc::Status rawStatus = m_agv->downloadMap(
|
|
|
|
|
|
&rawContext, rawRequest, &rawResponse);
|
|
|
|
|
|
if (!rawStatus.ok() || !rawResponse.header().success()) {
|
|
|
|
|
|
rawAttemptError = QStringLiteral("读取地图 %1 失败:%2").arg(actualMap,
|
|
|
|
|
|
QString::fromStdString(rawStatus.ok()
|
|
|
|
|
|
? rawResponse.header().error_message() : rawStatus.error_message()));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
QString renderError;
|
|
|
|
|
|
if (!renderAgvSmap2d(QString::fromStdString(rawResponse.content()),
|
|
|
|
|
|
rawMapImage, rawMapMetadata, renderError)) {
|
|
|
|
|
|
rawAttemptError = QStringLiteral("地图 %1 无法显示:%2").arg(actualMap, renderError);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString returnedMap = rawMapMetadata.value(QStringLiteral("mapId")).toString();
|
|
|
|
|
|
if (!returnedMap.isEmpty() && returnedMap != actualMap) {
|
|
|
|
|
|
rawAttemptError = QStringLiteral("请求地图 %1,车端却返回了 %2").arg(actualMap, returnedMap);
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
rawMapId = actualMap;
|
|
|
|
|
|
return true;
|
|
|
|
|
|
};
|
|
|
|
|
|
// A selected saved map can be displayed even when the vehicle's
|
|
|
|
|
|
// live stream is silent or still reports its previous active map.
|
|
|
|
|
|
const QString selectedMap = mapName.trimmed();
|
|
|
|
|
|
const bool rawLoaded = dimension == 1 && !selectedMap.isEmpty() && readRawMap(selectedMap);
|
|
|
|
|
|
if (rawLoaded && !m_agvMapStreamStop.load()) {
|
|
|
|
|
|
QVariantMap previewMetadata = rawMapMetadata;
|
|
|
|
|
|
for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it)
|
|
|
|
|
|
previewMetadata.insert(it.key(), it.value());
|
|
|
|
|
|
previewMetadata.insert(QStringLiteral("mapId"), selectedMap);
|
|
|
|
|
|
previewMetadata.insert(QStringLiteral("timestamp"), QDateTime::currentMSecsSinceEpoch() / 1000.0);
|
|
|
|
|
|
previewMetadata.insert(QStringLiteral("sequence"), static_cast<qulonglong>(0));
|
|
|
|
|
|
previewMetadata.insert(QStringLiteral("updateType"),
|
|
|
|
|
|
static_cast<int>(cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT));
|
|
|
|
|
|
emit agvMapFrameReceived(rawMapImage, previewMetadata,
|
|
|
|
|
|
QStringLiteral("%1 · 2D · 扫描地图").arg(selectedMap));
|
|
|
|
|
|
frameDelivered = true;
|
|
|
|
|
|
} else if (!rawAttemptError.isEmpty() && !m_agvMapStreamStop.load()) {
|
|
|
|
|
|
// A silent stream must not hide the completed raw-read error.
|
|
|
|
|
|
// Keep reading: legacy servers may still provide a usable grid.
|
|
|
|
|
|
QVariantMap errorContext = sourceContext;
|
|
|
|
|
|
errorContext.insert(QStringLiteral("error"), rawAttemptError);
|
|
|
|
|
|
emit agvMapStreamStateChanged(errorContext, true,
|
|
|
|
|
|
rawAttemptError + QStringLiteral(";等待统一地图数据"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
std::unique_ptr<grpc::ClientReader<cmvr::api::AgvMapStreamCommand::Feedback>>
|
|
|
|
|
|
reader = m_agv->streamMap(&context, request);
|
|
|
|
|
|
cmvr::api::AgvMapStreamCommand::Feedback response;
|
|
|
|
|
|
while (!m_agvMapStreamStop.load() && reader->Read(&response)) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (!response.header().success()) {
|
|
|
|
|
|
streamError = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
if (streamError.isEmpty())
|
|
|
|
|
|
streamError = QStringLiteral("服务端拒绝了地图读取");
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
const auto &update = response.update();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (preview && rawLoaded) {
|
|
|
|
|
|
// Saved-map preview has an independent complete source.
|
|
|
|
|
|
// Live deltas, chunks and grids cannot overwrite that source.
|
|
|
|
|
|
QVariantMap values = rawMapMetadata;
|
|
|
|
|
|
for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it)
|
|
|
|
|
|
values.insert(it.key(), it.value());
|
|
|
|
|
|
values.insert(QStringLiteral("mapId"), selectedMap);
|
|
|
|
|
|
values.insert(QStringLiteral("streamMapId"), QString::fromStdString(update.map_id()));
|
|
|
|
|
|
values.insert(QStringLiteral("timestamp"), update.timestamp());
|
|
|
|
|
|
values.insert(QStringLiteral("sequence"), static_cast<qulonglong>(update.sequence()));
|
|
|
|
|
|
values.insert(QStringLiteral("updateType"), static_cast<int>(update.update_type()));
|
|
|
|
|
|
values.insert(QStringLiteral("chunkIndex"), static_cast<int>(update.chunk_index()));
|
|
|
|
|
|
values.insert(QStringLiteral("chunkCount"), static_cast<int>(update.chunk_count()));
|
|
|
|
|
|
emit agvMapFrameReceived(rawMapImage, values,
|
|
|
|
|
|
QStringLiteral("%1 · 2D · 扫描地图预览").arg(selectedMap));
|
|
|
|
|
|
frameDelivered = true;
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (preview && !rawLoaded && !selectedMap.isEmpty()
|
|
|
|
|
|
&& QString::fromStdString(update.map_id()) != selectedMap) {
|
|
|
|
|
|
// A failed named download cannot fall back to another
|
|
|
|
|
|
// map's grid or hide its error by marking it delivered.
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (preview && !update.has_map_2d()) {
|
|
|
|
|
|
if (!incompleteReported) {
|
|
|
|
|
|
incompleteReported = true;
|
|
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, true,
|
|
|
|
|
|
rawAttemptError + QStringLiteral(";等待完整的 2D 统一地图"));
|
|
|
|
|
|
}
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QImage image;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap metadata = sourceContext;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QString detail;
|
|
|
|
|
|
if (update.has_map_2d()) {
|
|
|
|
|
|
const auto &map = update.map_2d();
|
|
|
|
|
|
const int sourceWidth = static_cast<int>(map.width());
|
|
|
|
|
|
const int sourceHeight = static_cast<int>(map.height());
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (sourceWidth <= 0 || sourceHeight <= 0 || map.data_size() == 0) {
|
|
|
|
|
|
// Older services omit camelCase SMAP bounds and scan cells.
|
|
|
|
|
|
// Read the selected device's original map once per stream.
|
|
|
|
|
|
const QString actualMap = mapName.trimmed().isEmpty()
|
|
|
|
|
|
? QString::fromStdString(update.map_id()).trimmed() : mapName.trimmed();
|
|
|
|
|
|
if (actualMap.isEmpty()) {
|
|
|
|
|
|
streamError = QStringLiteral("车端返回空地图,且未提供地图名称");
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!readRawMap(actualMap)) {
|
|
|
|
|
|
streamError = rawAttemptError;
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_agvMapStreamStop.load())
|
|
|
|
|
|
break;
|
|
|
|
|
|
QVariantMap rawMetadata = rawMapMetadata;
|
|
|
|
|
|
for (auto it = sourceContext.cbegin(); it != sourceContext.cend(); ++it)
|
|
|
|
|
|
rawMetadata.insert(it.key(), it.value());
|
|
|
|
|
|
rawMetadata.insert(QStringLiteral("mapId"), actualMap);
|
|
|
|
|
|
rawMetadata.insert(QStringLiteral("timestamp"), update.timestamp());
|
|
|
|
|
|
rawMetadata.insert(QStringLiteral("sequence"),
|
|
|
|
|
|
static_cast<qulonglong>(update.sequence()));
|
|
|
|
|
|
rawMetadata.insert(QStringLiteral("updateType"),
|
|
|
|
|
|
static_cast<int>(update.update_type()));
|
|
|
|
|
|
emit agvMapFrameReceived(rawMapImage, rawMetadata,
|
|
|
|
|
|
QStringLiteral("%1 · 2D · 扫描地图").arg(actualMap));
|
|
|
|
|
|
frameDelivered = true;
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (preview && ((update.update_type() != cmvr::msgs::AGV_MAP_UPDATE_UNSPECIFIED
|
|
|
|
|
|
&& update.update_type() != cmvr::msgs::AGV_MAP_UPDATE_SNAPSHOT)
|
|
|
|
|
|
|| update.chunk_count() > 1 || update.chunk_index() > 0
|
|
|
|
|
|
|| qint64(sourceWidth) * sourceHeight != map.data_size())) {
|
|
|
|
|
|
if (!incompleteReported) {
|
|
|
|
|
|
incompleteReported = true;
|
|
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, true,
|
|
|
|
|
|
rawAttemptError + QStringLiteral(";等待完整单帧地图,已忽略增量或分片数据"));
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
continue;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
const double scale = qMin(
|
|
|
|
|
|
1.0, qMin(1600.0 / sourceWidth, 1000.0 / sourceHeight));
|
2026-11-10 16:10:46 +08:00
|
|
|
|
const int width = qMax(1, qCeil(sourceWidth * scale));
|
|
|
|
|
|
const int height = qMax(1, qCeil(sourceHeight * scale));
|
|
|
|
|
|
image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
for (int y = 0; y < height; ++y) {
|
|
|
|
|
|
QRgb *line = reinterpret_cast<QRgb *>(
|
|
|
|
|
|
image.scanLine(height - 1 - y));
|
|
|
|
|
|
const int sourceY = qMin(sourceHeight - 1,
|
|
|
|
|
|
qFloor(y / scale));
|
2026-11-10 16:10:46 +08:00
|
|
|
|
const int endY = qMin(sourceHeight, qCeil((y + 1) / scale));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
for (int x = 0; x < width; ++x) {
|
|
|
|
|
|
const int sourceX = qMin(sourceWidth - 1,
|
|
|
|
|
|
qFloor(x / scale));
|
2026-11-10 16:10:46 +08:00
|
|
|
|
const int endX = qMin(sourceWidth, qCeil((x + 1) / scale));
|
|
|
|
|
|
// Retain thin scanned walls when reducing a large map.
|
|
|
|
|
|
int value = -1;
|
|
|
|
|
|
for (int sy = sourceY; sy < endY; ++sy)
|
|
|
|
|
|
for (int sx = sourceX; sx < endX; ++sx) {
|
|
|
|
|
|
const qint64 index = qint64(sy) * sourceWidth + sx;
|
|
|
|
|
|
if (index < map.data_size())
|
|
|
|
|
|
value = qMax(value, map.data(static_cast<int>(index)));
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (value < 0)
|
2026-11-10 16:10:46 +08:00
|
|
|
|
line[x] = qPremultiply(qRgba(203, 213, 225, 35));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
else if (value == 0)
|
2026-11-10 16:10:46 +08:00
|
|
|
|
line[x] = 0;
|
|
|
|
|
|
else
|
|
|
|
|
|
line[x] = qPremultiply(qRgba(107, 125, 140,
|
|
|
|
|
|
qBound(45, 45 + value * 2, 245)));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
QPainter painter(&image);
|
|
|
|
|
|
painter.setRenderHint(QPainter::Antialiasing);
|
|
|
|
|
|
const double resolution = map.resolution() > 0.0
|
|
|
|
|
|
? map.resolution() : 1.0;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantList stations;
|
|
|
|
|
|
QVariantList routes;
|
|
|
|
|
|
const double c = qCos(map.origin().theta());
|
|
|
|
|
|
const double s = qSin(map.origin().theta());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
for (const auto &object : map.objects()) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
const QString objectId = QString::fromStdString(object.id()).trimmed();
|
|
|
|
|
|
auto classProperty = object.properties().find("class_name");
|
|
|
|
|
|
if (classProperty == object.properties().end())
|
|
|
|
|
|
classProperty = object.properties().find("className");
|
|
|
|
|
|
const QString className = classProperty != object.properties().end()
|
|
|
|
|
|
? QString::fromStdString(classProperty->second) : QString();
|
|
|
|
|
|
QVariantList worldPoints;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QPolygonF geometry;
|
|
|
|
|
|
for (const auto &point : object.points()) {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
worldPoints.append(QVariantMap{
|
|
|
|
|
|
{QStringLiteral("x"), point.x()},
|
|
|
|
|
|
{QStringLiteral("y"), point.y()}});
|
|
|
|
|
|
const double dx = point.x() - map.origin().x();
|
|
|
|
|
|
const double dy = point.y() - map.origin().y();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
geometry.append(QPointF(
|
2026-11-10 16:10:46 +08:00
|
|
|
|
(c * dx + s * dy) / resolution * scale,
|
|
|
|
|
|
height - (-s * dx + c * dy) / resolution * scale));
|
|
|
|
|
|
}
|
|
|
|
|
|
if (geometry.size() == 1
|
|
|
|
|
|
&& (object.type() == cmvr::msgs::AGV_MAP_OBJECT_STATION
|
|
|
|
|
|
|| object.type() == cmvr::msgs::AGV_MAP_OBJECT_EXTERNAL_DEVICE)) {
|
|
|
|
|
|
QVariantMap station = worldPoints.first().toMap();
|
|
|
|
|
|
station.insert(QStringLiteral("id"), objectId);
|
|
|
|
|
|
const auto description = object.properties().find("description");
|
|
|
|
|
|
station.insert(QStringLiteral("name"), agvStationDisplayName(
|
|
|
|
|
|
description != object.properties().end()
|
|
|
|
|
|
? QString::fromStdString(description->second) : QString(), objectId, true));
|
|
|
|
|
|
station.insert(QStringLiteral("theta"), object.heading());
|
|
|
|
|
|
station.insert(QStringLiteral("type"), className.isEmpty()
|
|
|
|
|
|
? QStringLiteral("LandMark") : className);
|
|
|
|
|
|
stations.append(station);
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool navigationPath = className == QStringLiteral("BezierPath")
|
|
|
|
|
|
|| className == QStringLiteral("StraightPath")
|
|
|
|
|
|
|| className == QStringLiteral("ArcPath");
|
|
|
|
|
|
if (geometry.size() > 1 && object.type() == cmvr::msgs::AGV_MAP_OBJECT_LINE
|
|
|
|
|
|
&& navigationPath) {
|
|
|
|
|
|
// SEER's unified stream carries Bezier control points.
|
|
|
|
|
|
// Sample the curve rather than displaying its control polygon.
|
|
|
|
|
|
if (className == QStringLiteral("BezierPath") && worldPoints.size() > 2) {
|
|
|
|
|
|
const QVariantList controls = worldPoints;
|
|
|
|
|
|
worldPoints.clear();
|
|
|
|
|
|
for (int sample = 0; sample <= 32; ++sample) {
|
|
|
|
|
|
QVector<QPointF> work;
|
|
|
|
|
|
for (const QVariant &value : controls) {
|
|
|
|
|
|
const QVariantMap point = value.toMap();
|
|
|
|
|
|
work.append(QPointF(point.value(QStringLiteral("x")).toDouble(),
|
|
|
|
|
|
point.value(QStringLiteral("y")).toDouble()));
|
|
|
|
|
|
}
|
|
|
|
|
|
const double t = sample / 32.0;
|
|
|
|
|
|
for (int count = work.size() - 1; count > 0; --count)
|
|
|
|
|
|
for (int i = 0; i < count; ++i)
|
|
|
|
|
|
work[i] = work.at(i) * (1.0 - t) + work.at(i + 1) * t;
|
|
|
|
|
|
worldPoints.append(QVariantMap{
|
|
|
|
|
|
{QStringLiteral("x"), work.first().x()},
|
|
|
|
|
|
{QStringLiteral("y"), work.first().y()}});
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
routes.append(QVariantMap{{QStringLiteral("id"), objectId},
|
|
|
|
|
|
{QStringLiteral("points"), worldPoints}});
|
|
|
|
|
|
continue;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
// Keep non-navigation semantic geometry such as regions and reflectors.
|
2026-09-18 16:22:20 +08:00
|
|
|
|
painter.setPen(QPen(QColor(QStringLiteral("#218c74")), 2));
|
2026-11-10 16:10:46 +08:00
|
|
|
|
painter.setBrush(QColor(33, 140, 116, 30));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (geometry.size() == 1)
|
|
|
|
|
|
painter.drawEllipse(geometry.first(), 6, 6);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
else if (geometry.size() > 2 && object.type() == cmvr::msgs::AGV_MAP_OBJECT_AREA)
|
|
|
|
|
|
painter.drawPolygon(geometry);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
else if (geometry.size() > 1)
|
|
|
|
|
|
painter.drawPolyline(geometry);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!geometry.isEmpty() && !objectId.isEmpty()
|
|
|
|
|
|
&& objectId != QStringLiteral("0")) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
painter.setPen(QColor(QStringLiteral("#145da8")));
|
|
|
|
|
|
painter.drawText(geometry.first() + QPointF(8, -6),
|
2026-10-14 17:15:46 +08:00
|
|
|
|
objectId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
painter.end();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("stations"), stations);
|
|
|
|
|
|
metadata.insert(QStringLiteral("routes"), routes);
|
|
|
|
|
|
metadata.insert(QStringLiteral("deviceId"), deviceId.trimmed());
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("mapId"),
|
|
|
|
|
|
QString::fromStdString(update.map_id()));
|
|
|
|
|
|
metadata.insert(QStringLiteral("dimension"), 2);
|
|
|
|
|
|
metadata.insert(QStringLiteral("originX"), map.origin().x());
|
|
|
|
|
|
metadata.insert(QStringLiteral("originY"), map.origin().y());
|
|
|
|
|
|
metadata.insert(QStringLiteral("originTheta"), map.origin().theta());
|
|
|
|
|
|
metadata.insert(QStringLiteral("resolution"), resolution);
|
|
|
|
|
|
metadata.insert(QStringLiteral("sourceWidth"), sourceWidth);
|
|
|
|
|
|
metadata.insert(QStringLiteral("sourceHeight"), sourceHeight);
|
|
|
|
|
|
metadata.insert(QStringLiteral("renderScale"), scale);
|
|
|
|
|
|
metadata.insert(QStringLiteral("timestamp"), map.timestamp());
|
|
|
|
|
|
metadata.insert(QStringLiteral("sequence"),
|
|
|
|
|
|
static_cast<qulonglong>(update.sequence()));
|
|
|
|
|
|
metadata.insert(QStringLiteral("updateType"),
|
|
|
|
|
|
static_cast<int>(update.update_type()));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
detail = QStringLiteral("%1 · 2D · %2×%3 · seq %4")
|
|
|
|
|
|
.arg(QString::fromStdString(update.map_id()))
|
|
|
|
|
|
.arg(sourceWidth).arg(sourceHeight)
|
|
|
|
|
|
.arg(static_cast<qulonglong>(update.sequence()));
|
|
|
|
|
|
} else if (update.has_map_3d()) {
|
|
|
|
|
|
const auto &map = update.map_3d();
|
|
|
|
|
|
image = QImage(1280, 720, QImage::Format_RGB32);
|
|
|
|
|
|
image.fill(QColor(QStringLiteral("#eef2f6")));
|
|
|
|
|
|
if (map.points_size() > 0) {
|
|
|
|
|
|
double minX = map.points(0).x(), maxX = minX;
|
|
|
|
|
|
double minY = map.points(0).y(), maxY = minY;
|
|
|
|
|
|
const int step = qMax(1, map.points_size() / 80000);
|
|
|
|
|
|
for (int i = 0; i < map.points_size(); i += step) {
|
|
|
|
|
|
minX = qMin(minX, map.points(i).x());
|
|
|
|
|
|
maxX = qMax(maxX, map.points(i).x());
|
|
|
|
|
|
minY = qMin(minY, map.points(i).y());
|
|
|
|
|
|
maxY = qMax(maxY, map.points(i).y());
|
|
|
|
|
|
}
|
|
|
|
|
|
if (qFuzzyCompare(minX, maxX)) { minX -= 1.0; maxX += 1.0; }
|
|
|
|
|
|
if (qFuzzyCompare(minY, maxY)) { minY -= 1.0; maxY += 1.0; }
|
|
|
|
|
|
QPainter painter(&image);
|
|
|
|
|
|
painter.setPen(QColor(QStringLiteral("#456b87")));
|
|
|
|
|
|
for (int i = 0; i < map.points_size(); i += step) {
|
|
|
|
|
|
const auto &point = map.points(i);
|
|
|
|
|
|
painter.drawPoint(QPointF(
|
|
|
|
|
|
30.0 + (point.x() - minX) / (maxX - minX) * 1220.0,
|
|
|
|
|
|
690.0 - (point.y() - minY) / (maxY - minY) * 660.0));
|
|
|
|
|
|
}
|
|
|
|
|
|
painter.end();
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("deviceId"), deviceId.trimmed());
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadata.insert(QStringLiteral("mapId"),
|
|
|
|
|
|
QString::fromStdString(update.map_id()));
|
|
|
|
|
|
metadata.insert(QStringLiteral("dimension"), 3);
|
|
|
|
|
|
metadata.insert(QStringLiteral("timestamp"), map.timestamp());
|
|
|
|
|
|
metadata.insert(QStringLiteral("sequence"),
|
|
|
|
|
|
static_cast<qulonglong>(update.sequence()));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
detail = QStringLiteral("%1 · 3D · %2 points · seq %3")
|
|
|
|
|
|
.arg(QString::fromStdString(update.map_id()))
|
|
|
|
|
|
.arg(map.points_size())
|
|
|
|
|
|
.arg(static_cast<qulonglong>(update.sequence()));
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (!image.isNull()) {
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit agvMapFrameReceived(image, metadata, detail);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
frameDelivered = true;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (m_agvMapStreamStop.load())
|
|
|
|
|
|
context.TryCancel();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
const grpc::Status status = reader->Finish();
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_agvMapStreamContextMutex);
|
|
|
|
|
|
m_agvMapStreamContext = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_agvMapStreamRunning.store(false);
|
|
|
|
|
|
const QString detail = m_agvMapStreamStop.load()
|
|
|
|
|
|
? QStringLiteral("地图流已停止")
|
2026-11-10 16:10:46 +08:00
|
|
|
|
: !streamError.isEmpty() ? streamError
|
|
|
|
|
|
: !frameDelivered && !rawAttemptError.isEmpty() ? rawAttemptError
|
2026-09-18 16:22:20 +08:00
|
|
|
|
: status.ok() ? QStringLiteral("地图流已结束")
|
|
|
|
|
|
: QString::fromStdString(status.error_message());
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvMapStreamStateChanged(sourceContext, false, detail);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
});
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void stopAgvMapStream(quint64 generation)
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
|
|
|
|
|
stopAgvMapStreamInternal();
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap context = m_agvMapStreamSourceContext;
|
|
|
|
|
|
context.insert(QStringLiteral("streamGeneration"), generation);
|
|
|
|
|
|
emit agvMapStreamStateChanged(context, false, QStringLiteral("地图流已停止"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void invokeRpc(const QString &serviceName, const QString &methodName,
|
|
|
|
|
|
const QString &requestJson, const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString command = QStringLiteral("%1.%2").arg(serviceName, methodName);
|
|
|
|
|
|
if (!ensureConnected(command)) {
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QStringLiteral("{\"error\":\"设备尚未连接\"}"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
QJsonObject result;
|
|
|
|
|
|
result.insert(QStringLiteral("demo"), true);
|
2026-10-19 09:18:07 +08:00
|
|
|
|
result.insert(QStringLiteral("header"), QJsonObject{{QStringLiteral("success"), true}});
|
2026-09-18 16:22:20 +08:00
|
|
|
|
result.insert(QStringLiteral("service"), serviceName);
|
|
|
|
|
|
result.insert(QStringLiteral("method"), methodName);
|
|
|
|
|
|
result.insert(QStringLiteral("deviceId"), deviceId);
|
|
|
|
|
|
result.insert(QStringLiteral("message"), QStringLiteral("演示模式调用成功"));
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, true,
|
|
|
|
|
|
QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Indented)));
|
|
|
|
|
|
emit commandFinished(command, true, QStringLiteral("演示模式 RPC 调用完成"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
const google::protobuf::ServiceDescriptor *service =
|
|
|
|
|
|
google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(
|
|
|
|
|
|
serviceName.toStdString());
|
|
|
|
|
|
const google::protobuf::MethodDescriptor *method =
|
|
|
|
|
|
service ? service->FindMethodByName(methodName.toStdString()) : nullptr;
|
|
|
|
|
|
if (!method || !m_generic) {
|
|
|
|
|
|
const QString error = QStringLiteral("找不到 RPC 描述符:%1").arg(command);
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QStringLiteral("{\"error\":\"%1\"}").arg(error));
|
|
|
|
|
|
emit commandFinished(command, false, error);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
google::protobuf::DynamicMessageFactory factory;
|
|
|
|
|
|
const google::protobuf::Message *requestPrototype =
|
|
|
|
|
|
factory.GetPrototype(method->input_type());
|
|
|
|
|
|
const google::protobuf::Message *responsePrototype =
|
|
|
|
|
|
factory.GetPrototype(method->output_type());
|
|
|
|
|
|
if (!requestPrototype || !responsePrototype) {
|
|
|
|
|
|
const QString error = QStringLiteral("无法创建 protobuf 动态消息");
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QStringLiteral("{\"error\":\"%1\"}").arg(error));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
QStringList requestDocuments;
|
|
|
|
|
|
QJsonParseError parseError;
|
|
|
|
|
|
const QJsonDocument jsonDocument = QJsonDocument::fromJson(requestJson.toUtf8(), &parseError);
|
|
|
|
|
|
if (parseError.error != QJsonParseError::NoError) {
|
|
|
|
|
|
const QString error = QStringLiteral("请求 JSON 无效:%1").arg(parseError.errorString());
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QStringLiteral("{\"error\":\"%1\"}").arg(error));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (jsonDocument.isArray()) {
|
|
|
|
|
|
for (const QJsonValue &value : jsonDocument.array())
|
|
|
|
|
|
requestDocuments.append(QString::fromUtf8(
|
|
|
|
|
|
QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)));
|
|
|
|
|
|
} else {
|
|
|
|
|
|
requestDocuments.append(QString::fromUtf8(
|
|
|
|
|
|
QJsonDocument(jsonDocument.object()).toJson(QJsonDocument::Compact)));
|
|
|
|
|
|
}
|
|
|
|
|
|
if (requestDocuments.isEmpty())
|
|
|
|
|
|
requestDocuments.append(QStringLiteral("{}"));
|
|
|
|
|
|
|
|
|
|
|
|
std::vector<std::unique_ptr<google::protobuf::Message>> requests;
|
|
|
|
|
|
std::vector<grpc::ByteBuffer> requestBuffers;
|
|
|
|
|
|
google::protobuf::util::JsonParseOptions jsonOptions;
|
|
|
|
|
|
jsonOptions.ignore_unknown_fields = false;
|
|
|
|
|
|
for (const QString &document : requestDocuments) {
|
|
|
|
|
|
std::unique_ptr<google::protobuf::Message> request(requestPrototype->New());
|
|
|
|
|
|
const auto jsonStatus = google::protobuf::util::JsonStringToMessage(
|
|
|
|
|
|
document.toStdString(), request.get(), jsonOptions);
|
|
|
|
|
|
if (!jsonStatus.ok()) {
|
|
|
|
|
|
const QString error = QStringLiteral("protobuf JSON 转换失败:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(jsonStatus.ToString()));
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QStringLiteral("{\"error\":\"%1\"}").arg(error));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setDynamicDeviceId(request.get(), deviceId);
|
|
|
|
|
|
std::string serialized;
|
|
|
|
|
|
request->SerializeToString(&serialized);
|
|
|
|
|
|
grpc::Slice slice(serialized);
|
|
|
|
|
|
requestBuffers.emplace_back(&slice, 1);
|
|
|
|
|
|
requests.emplace_back(std::move(request));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const std::string path = QStringLiteral("/%1/%2").arg(serviceName, methodName).toStdString();
|
|
|
|
|
|
grpc::Status grpcStatus;
|
|
|
|
|
|
QJsonArray streamResponses;
|
|
|
|
|
|
QString unaryResponse;
|
|
|
|
|
|
bool transportOk = false;
|
|
|
|
|
|
if (!method->client_streaming() && !method->server_streaming()) {
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 4000);
|
|
|
|
|
|
grpc::CompletionQueue queue;
|
|
|
|
|
|
grpc::ByteBuffer responseBuffer;
|
|
|
|
|
|
std::unique_ptr<grpc::GenericClientAsyncResponseReader> call =
|
|
|
|
|
|
m_generic->PrepareUnaryCall(&context, path, requestBuffers.front(), &queue);
|
|
|
|
|
|
call->StartCall();
|
|
|
|
|
|
call->Finish(&responseBuffer, &grpcStatus, reinterpret_cast<void *>(1));
|
|
|
|
|
|
void *tag = nullptr;
|
|
|
|
|
|
bool eventOk = false;
|
|
|
|
|
|
transportOk = queue.Next(&tag, &eventOk) && eventOk &&
|
|
|
|
|
|
tag == reinterpret_cast<void *>(1) && grpcStatus.ok();
|
|
|
|
|
|
if (transportOk)
|
|
|
|
|
|
unaryResponse = byteBufferToJson(responseBuffer, responsePrototype, factory);
|
|
|
|
|
|
queue.Shutdown();
|
|
|
|
|
|
} else {
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 5000);
|
|
|
|
|
|
grpc::CompletionQueue queue;
|
|
|
|
|
|
std::unique_ptr<grpc::GenericClientAsyncReaderWriter> call =
|
|
|
|
|
|
m_generic->PrepareCall(&context, path, &queue);
|
|
|
|
|
|
void *tag = nullptr;
|
|
|
|
|
|
bool eventOk = false;
|
|
|
|
|
|
call->StartCall(reinterpret_cast<void *>(1));
|
|
|
|
|
|
bool started = queue.Next(&tag, &eventOk) && eventOk;
|
|
|
|
|
|
for (int index = 0; started && index < static_cast<int>(requestBuffers.size()); ++index) {
|
|
|
|
|
|
call->Write(requestBuffers.at(index), reinterpret_cast<void *>(2));
|
|
|
|
|
|
started = queue.Next(&tag, &eventOk) && eventOk;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (started) {
|
|
|
|
|
|
call->WritesDone(reinterpret_cast<void *>(3));
|
|
|
|
|
|
queue.Next(&tag, &eventOk);
|
|
|
|
|
|
}
|
|
|
|
|
|
while (started && streamResponses.size() < 100) {
|
|
|
|
|
|
grpc::ByteBuffer responseBuffer;
|
|
|
|
|
|
call->Read(&responseBuffer, reinterpret_cast<void *>(4));
|
|
|
|
|
|
if (!queue.Next(&tag, &eventOk) || !eventOk)
|
|
|
|
|
|
break;
|
|
|
|
|
|
const QString response = byteBufferToJson(responseBuffer, responsePrototype, factory);
|
|
|
|
|
|
QJsonParseError responseError;
|
|
|
|
|
|
const QJsonDocument parsed = QJsonDocument::fromJson(response.toUtf8(), &responseError);
|
|
|
|
|
|
streamResponses.append(responseError.error == QJsonParseError::NoError
|
|
|
|
|
|
? QJsonValue(parsed.object()) : QJsonValue(response));
|
|
|
|
|
|
}
|
|
|
|
|
|
if (streamResponses.size() >= 100)
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
call->Finish(&grpcStatus, reinterpret_cast<void *>(5));
|
|
|
|
|
|
queue.Next(&tag, &eventOk);
|
|
|
|
|
|
transportOk = grpcStatus.ok() ||
|
|
|
|
|
|
(grpcStatus.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED &&
|
|
|
|
|
|
!streamResponses.isEmpty());
|
|
|
|
|
|
queue.Shutdown();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
QString result;
|
|
|
|
|
|
if (transportOk) {
|
|
|
|
|
|
result = method->client_streaming() || method->server_streaming()
|
|
|
|
|
|
? QString::fromUtf8(QJsonDocument(streamResponses).toJson(QJsonDocument::Indented))
|
|
|
|
|
|
: unaryResponse;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
QJsonObject error;
|
|
|
|
|
|
error.insert(QStringLiteral("grpcCode"), grpcStatus.error_code());
|
|
|
|
|
|
error.insert(QStringLiteral("error"), QString::fromStdString(grpcStatus.error_message()));
|
|
|
|
|
|
result = QString::fromUtf8(QJsonDocument(error).toJson(QJsonDocument::Indented));
|
|
|
|
|
|
}
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, transportOk, result);
|
|
|
|
|
|
emit commandFinished(command, transportOk,
|
|
|
|
|
|
transportOk ? QStringLiteral("RPC 调用完成")
|
|
|
|
|
|
: QString::fromStdString(grpcStatus.error_message()));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(requestJson)
|
|
|
|
|
|
Q_UNUSED(deviceId)
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
std::function<void(bool, int, const QString &)> connectionChanged;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::function<void(quint64, const QString &, const QVariantMap &, bool, const QString &)>
|
|
|
|
|
|
controllerTcpOffsetReceived;
|
2026-09-23 11:11:49 +08:00
|
|
|
|
std::function<void(const QString &, const QVariantMap &)> armInfoReceived;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::function<void(quint64, const QString &, const QVariantMap &, const QVariantMap &,
|
|
|
|
|
|
bool, const QString &)> tcpCalibrationPoseReceived;
|
2026-09-23 11:11:49 +08:00
|
|
|
|
std::function<void(const QString &, const QStringList &, const QStringList &)>
|
|
|
|
|
|
armFramesReceived;
|
|
|
|
|
|
std::function<void(const QString &, const QVariantList &, const QVariantMap &,
|
|
|
|
|
|
const QVariantMap &)> telemetryReceived;
|
2026-09-23 16:04:01 +08:00
|
|
|
|
std::function<void(const QString &, bool, const QString &)>
|
|
|
|
|
|
armTelemetryHealthChanged;
|
2026-09-23 11:11:49 +08:00
|
|
|
|
std::function<void(double, double, double, const QVariantList &)> systemStatusReceived;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::function<void(const QVariantMap &)> systemInfoReceived;
|
|
|
|
|
|
std::function<void(const QImage &, const QString &)> imageReceived;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::function<void(quint64, const QString &, const QImage &, const QVariantMap &,
|
|
|
|
|
|
const QVariantMap &, bool, const QString &)> handEyeImageReceived;
|
|
|
|
|
|
std::function<void(quint64, const QString &, const QImage &, const QVariantMap &,
|
|
|
|
|
|
const QVariantMap &, bool, const QString &)> touchRgbdImageReceived;
|
|
|
|
|
|
std::function<void(quint64,const QString&,const QVariantMap&,bool,const QString&)> cameraCapabilitiesReceived;
|
|
|
|
|
|
std::function<void(const QString &, const QVariantMap &)> cameraStatusReceived;
|
|
|
|
|
|
std::function<void(const QString &, bool, bool, const QString &,
|
|
|
|
|
|
const QVariantList &)>
|
|
|
|
|
|
dexHandStatusReceived;
|
|
|
|
|
|
std::function<void(const QString &, int, int, const QVariantList &, quint64)>
|
|
|
|
|
|
dexHandTactileReceived;
|
|
|
|
|
|
std::function<void(bool, const QString &)> dexHandTactileStreamStateChanged;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::function<void(const QString &, const VideoFrame &, const QString &)>
|
|
|
|
|
|
videoFrameReceivedForCamera;
|
|
|
|
|
|
std::function<void(const QString &, bool, const QString &)>
|
|
|
|
|
|
cameraStreamStateChangedForCamera;
|
|
|
|
|
|
std::function<void(bool, const QString &)> cameraRecordingStateChanged;
|
|
|
|
|
|
std::function<void(const QVariantMap &, const QVariantMap &)> agvStateReceived;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
std::function<void(const QVariantMap &, const QStringList &, const QVariantList &)> agvInventoryReceived;
|
|
|
|
|
|
std::function<void(quint64, const QString &, const QString &, const QString &,
|
|
|
|
|
|
bool, const QString &)> agvMapContentReceived;
|
|
|
|
|
|
std::function<void(quint64, const QString &, const QString &, bool,
|
|
|
|
|
|
const QString &)> agvMapSaveFinished;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::function<void(const QImage &, const QVariantMap &, const QString &)>
|
|
|
|
|
|
agvMapFrameReceived;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
std::function<void(const QVariantMap &, bool, const QString &)> agvMapStreamStateChanged;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::function<void(const QString &, const QString &, bool, const QString &)> rpcFinished;
|
|
|
|
|
|
std::function<void(const QString &, bool, const QString &)> audioStreamStateChanged;
|
|
|
|
|
|
std::function<void(const QString &, quint64, quint64, qint64)> audioStreamStatistics;
|
|
|
|
|
|
std::function<void(const QByteArray &, int, int, int, const QString &, qint64, int)>
|
|
|
|
|
|
audioFrameReceived;
|
|
|
|
|
|
std::function<void(bool, const QString &)> configurationConnectionChanged;
|
|
|
|
|
|
std::function<void(const QString &, const QVariantList &, bool, const QString &)>
|
|
|
|
|
|
configurationFilesReceived;
|
|
|
|
|
|
std::function<void(const QString &, const QString &, const QString &, const QString &,
|
|
|
|
|
|
bool, const QString &)> configurationFileReceived;
|
|
|
|
|
|
std::function<void(const QString &, bool, const QString &)>
|
|
|
|
|
|
configurationValidationFinished;
|
|
|
|
|
|
std::function<void(const QString &, const QString &, bool, const QString &)>
|
|
|
|
|
|
configurationSaveFinished;
|
|
|
|
|
|
std::function<void(const QString &, bool, const QString &)> commandFinished;
|
2026-10-29 11:46:39 +08:00
|
|
|
|
std::function<void(const QString &, const QVariantList &, const QVariantMap &, bool, const QString &)>
|
|
|
|
|
|
recordedTrajectoriesReceived;
|
2026-10-20 16:49:27 +08:00
|
|
|
|
std::function<void(quint64, const QVariantList &, bool, const QString &)> jointPointCaptured;
|
|
|
|
|
|
std::function<void(quint64, bool, const QString &)> jointPointMoveFinished;
|
|
|
|
|
|
std::function<void(quint64,const QString&,bool,const QVariantMap&,const QString&)> motorRpcFinished;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::function<void(const QString &, const QString &)> logMessage;
|
|
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
bool ensureConfigurationConnected(const QString &operation)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (m_configConnected && m_configuration)
|
|
|
|
|
|
return true;
|
|
|
|
|
|
emit configurationConnectionChanged(
|
|
|
|
|
|
false, QStringLiteral("%1失败:配置服务未连接").arg(operation));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static QString configurationError(const grpc::Status &status,
|
|
|
|
|
|
const std::string &applicationError)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!status.ok())
|
|
|
|
|
|
return QString::fromStdString(status.error_message());
|
|
|
|
|
|
return QString::fromStdString(applicationError);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
std::shared_ptr<ArmMotionSession> prepareArmMotionSession(const QString &command)
|
|
|
|
|
|
{
|
|
|
|
|
|
std::shared_ptr<ArmMotionSession> previous;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
|
|
|
|
|
previous = m_armMotionSession;
|
|
|
|
|
|
if (previous && previous->running.load()) {
|
|
|
|
|
|
emit commandFinished(command, false,
|
|
|
|
|
|
QStringLiteral("已有机械臂运动命令正在执行"));
|
|
|
|
|
|
return {};
|
|
|
|
|
|
}
|
|
|
|
|
|
m_armMotionSession.reset();
|
|
|
|
|
|
}
|
|
|
|
|
|
if (previous && previous->thread.joinable() &&
|
|
|
|
|
|
previous->thread.get_id() != std::this_thread::get_id()) {
|
|
|
|
|
|
previous->thread.join();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
auto session = std::make_shared<ArmMotionSession>();
|
|
|
|
|
|
session->running.store(true);
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
|
|
|
|
|
m_armMotionSession = session;
|
|
|
|
|
|
}
|
|
|
|
|
|
return session;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
template <typename Request, typename Response, typename Call>
|
2026-10-29 11:46:39 +08:00
|
|
|
|
void startArmMotion(const QString &command, Request request, Call call, int timeoutMs = kArmMotionTimeoutMs)
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
|
|
|
|
|
const auto session = prepareArmMotionSession(command);
|
|
|
|
|
|
if (!session)
|
|
|
|
|
|
return;
|
|
|
|
|
|
const auto channel = m_channel;
|
|
|
|
|
|
session->thread = std::thread(
|
2026-10-29 11:46:39 +08:00
|
|
|
|
[this, channel, session, command, request = std::move(request), call, timeoutMs]() mutable {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
grpc::ClientContext context;
|
2026-10-29 11:46:39 +08:00
|
|
|
|
setDeadline(context, timeoutMs);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->context = &context;
|
|
|
|
|
|
if (session->stop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
|
|
|
auto stub = cmvr::api::ArmService::NewStub(channel);
|
|
|
|
|
|
Response response;
|
|
|
|
|
|
const grpc::Status status = call(*stub, &context, request, &response);
|
|
|
|
|
|
finish(command, status, response.header().success(),
|
|
|
|
|
|
QString::fromStdString(response.header().error_message()));
|
|
|
|
|
|
} catch (const std::exception &error) {
|
|
|
|
|
|
emit commandFinished(command, false,
|
|
|
|
|
|
QStringLiteral("机械臂运动调用异常:%1")
|
|
|
|
|
|
.arg(QString::fromLocal8Bit(error.what())));
|
|
|
|
|
|
} catch (...) {
|
|
|
|
|
|
emit commandFinished(command, false,
|
|
|
|
|
|
QStringLiteral("机械臂运动调用发生未知异常"));
|
|
|
|
|
|
}
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->context = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void setDynamicDeviceId(google::protobuf::Message *request,
|
|
|
|
|
|
const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!request || deviceId.trimmed().isEmpty())
|
|
|
|
|
|
return;
|
|
|
|
|
|
const google::protobuf::FieldDescriptor *headerField =
|
|
|
|
|
|
request->GetDescriptor()->FindFieldByName("header");
|
|
|
|
|
|
if (!headerField || headerField->cpp_type() !=
|
|
|
|
|
|
google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE)
|
|
|
|
|
|
return;
|
|
|
|
|
|
google::protobuf::Message *header =
|
|
|
|
|
|
request->GetReflection()->MutableMessage(request, headerField);
|
|
|
|
|
|
const google::protobuf::FieldDescriptor *deviceField =
|
|
|
|
|
|
header->GetDescriptor()->FindFieldByName("device_id");
|
|
|
|
|
|
if (deviceField)
|
|
|
|
|
|
header->GetReflection()->SetString(header, deviceField, deviceId.toStdString());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static QString byteBufferToJson(const grpc::ByteBuffer &buffer,
|
|
|
|
|
|
const google::protobuf::Message *prototype,
|
|
|
|
|
|
google::protobuf::DynamicMessageFactory &factory)
|
|
|
|
|
|
{
|
|
|
|
|
|
Q_UNUSED(factory)
|
|
|
|
|
|
std::vector<grpc::Slice> slices;
|
|
|
|
|
|
buffer.Dump(&slices);
|
|
|
|
|
|
std::string serialized;
|
|
|
|
|
|
for (const grpc::Slice &slice : slices)
|
|
|
|
|
|
serialized.append(reinterpret_cast<const char *>(slice.begin()), slice.size());
|
|
|
|
|
|
std::unique_ptr<google::protobuf::Message> response(prototype->New());
|
|
|
|
|
|
if (!response->ParseFromString(serialized))
|
|
|
|
|
|
return QStringLiteral("{\"error\":\"无法解析 protobuf 反馈\"}");
|
|
|
|
|
|
std::string json;
|
|
|
|
|
|
google::protobuf::util::JsonPrintOptions options;
|
|
|
|
|
|
options.add_whitespace = true;
|
|
|
|
|
|
options.always_print_primitive_fields = true;
|
|
|
|
|
|
const auto status = google::protobuf::util::MessageToJsonString(*response, &json, options);
|
|
|
|
|
|
return status.ok() ? QString::fromStdString(json)
|
|
|
|
|
|
: QStringLiteral("{\"error\":\"%1\"}")
|
|
|
|
|
|
.arg(QString::fromStdString(status.ToString()));
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
|
|
void stopArmMotionInternal()
|
|
|
|
|
|
{
|
|
|
|
|
|
std::shared_ptr<ArmMotionSession> session;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
|
|
|
|
|
session = m_armMotionSession;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!session)
|
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
|
|
session->stop.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
if (session->context)
|
|
|
|
|
|
session->context->TryCancel();
|
2026-10-20 16:49:27 +08:00
|
|
|
|
for (const auto &context : session->groupContexts)
|
|
|
|
|
|
context->TryCancel();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
if (session->thread.joinable() &&
|
|
|
|
|
|
session->thread.get_id() != std::this_thread::get_id()) {
|
|
|
|
|
|
session->thread.join();
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_armMotionSessionMutex);
|
|
|
|
|
|
if (m_armMotionSession == session)
|
|
|
|
|
|
m_armMotionSession.reset();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void stopDexHandTactileStreamInternal()
|
|
|
|
|
|
{
|
|
|
|
|
|
m_dexHandTactileStop.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_dexHandTactileContextMutex);
|
|
|
|
|
|
if (m_dexHandTactileContext)
|
|
|
|
|
|
m_dexHandTactileContext->TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
if (m_dexHandTactileThread.joinable()
|
|
|
|
|
|
&& m_dexHandTactileThread.get_id() != std::this_thread::get_id())
|
|
|
|
|
|
m_dexHandTactileThread.join();
|
|
|
|
|
|
m_dexHandTactileRunning.store(false);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void stopAgvMapStreamInternal()
|
|
|
|
|
|
{
|
|
|
|
|
|
m_agvMapStreamStop.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_agvMapStreamContextMutex);
|
|
|
|
|
|
if (m_agvMapStreamContext)
|
|
|
|
|
|
m_agvMapStreamContext->TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
if (m_agvMapStreamThread.joinable() &&
|
|
|
|
|
|
m_agvMapStreamThread.get_id() != std::this_thread::get_id())
|
|
|
|
|
|
m_agvMapStreamThread.join();
|
|
|
|
|
|
m_agvMapStreamRunning.store(false);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopCameraStreamInternal(const QString &cameraId = QString())
|
|
|
|
|
|
{
|
|
|
|
|
|
QVector<std::shared_ptr<CameraStreamSession>> sessions;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_cameraSessionsMutex);
|
|
|
|
|
|
if (cameraId.isEmpty()) {
|
|
|
|
|
|
sessions.reserve(m_cameraSessions.size());
|
|
|
|
|
|
for (auto it = m_cameraSessions.cbegin();
|
|
|
|
|
|
it != m_cameraSessions.cend(); ++it) {
|
|
|
|
|
|
sessions.append(it.value());
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
const auto it = m_cameraSessions.find(cameraId);
|
|
|
|
|
|
if (it != m_cameraSessions.end())
|
|
|
|
|
|
sessions.append(it.value());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for (const auto &session : sessions) {
|
|
|
|
|
|
session->stop.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
if (session->context)
|
|
|
|
|
|
session->context->TryCancel();
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
for (const auto &session : sessions) {
|
|
|
|
|
|
if (session->thread.joinable() &&
|
|
|
|
|
|
session->thread.get_id() != std::this_thread::get_id()) {
|
|
|
|
|
|
session->thread.join();
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
|
|
|
|
|
}
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_cameraSessionsMutex);
|
|
|
|
|
|
for (const auto &session : sessions) {
|
|
|
|
|
|
const auto it = m_cameraSessions.find(session->cameraId);
|
|
|
|
|
|
if (it != m_cameraSessions.end() && it.value() == session)
|
|
|
|
|
|
m_cameraSessions.erase(it);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopSpeakerStreamInternal(bool cancel = false)
|
|
|
|
|
|
{
|
|
|
|
|
|
const bool wasRunning = m_speakerStreamRunning.load();
|
|
|
|
|
|
m_speakerStreamStop.store(true);
|
|
|
|
|
|
m_speakerQueueCondition.notify_all();
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerContextMutex);
|
|
|
|
|
|
if (cancel && m_speakerStreamContext)
|
|
|
|
|
|
m_speakerStreamContext->TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
const bool hadThread = m_speakerStreamThread.joinable();
|
|
|
|
|
|
if (hadThread && m_speakerStreamThread.get_id() != std::this_thread::get_id())
|
|
|
|
|
|
m_speakerStreamThread.join();
|
|
|
|
|
|
m_speakerStreamRunning.store(false);
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerQueueMutex);
|
|
|
|
|
|
m_speakerQueue.clear();
|
|
|
|
|
|
m_speakerQueueBytes = 0;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (wasRunning && !hadThread)
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false,
|
|
|
|
|
|
QStringLiteral("扬声器音频流已停止"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void stopMicrophoneStreamInternal()
|
|
|
|
|
|
{
|
|
|
|
|
|
const bool wasRunning = m_microphoneStreamRunning.load();
|
|
|
|
|
|
m_microphoneStreamStop.store(true);
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_microphoneContextMutex);
|
|
|
|
|
|
if (m_microphoneStreamContext)
|
|
|
|
|
|
m_microphoneStreamContext->TryCancel();
|
|
|
|
|
|
}
|
|
|
|
|
|
#endif
|
|
|
|
|
|
const bool hadThread = m_microphoneStreamThread.joinable();
|
|
|
|
|
|
if (hadThread && m_microphoneStreamThread.get_id() != std::this_thread::get_id())
|
|
|
|
|
|
m_microphoneStreamThread.join();
|
|
|
|
|
|
m_microphoneStreamRunning.store(false);
|
|
|
|
|
|
if (wasRunning && !hadThread)
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false,
|
|
|
|
|
|
QStringLiteral("麦克风音频拉流已停止"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void poll()
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!m_connected)
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
pollDemo();
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
2026-10-16 09:39:44 +08:00
|
|
|
|
if (m_channel) {
|
|
|
|
|
|
const grpc_connectivity_state state = m_channel->GetState(true);
|
|
|
|
|
|
if (state == GRPC_CHANNEL_READY || state == GRPC_CHANNEL_IDLE) {
|
|
|
|
|
|
m_channelFailureTicks = 0;
|
|
|
|
|
|
} else if (state == GRPC_CHANNEL_TRANSIENT_FAILURE
|
|
|
|
|
|
|| state == GRPC_CHANNEL_SHUTDOWN) {
|
|
|
|
|
|
++m_channelFailureTicks;
|
|
|
|
|
|
// Avoid treating a single Wi-Fi jitter as a disconnect. At
|
|
|
|
|
|
// 100 ms polling this reports a persistent failure in about
|
|
|
|
|
|
// one second and releases every old stream/context.
|
|
|
|
|
|
if (m_channelFailureTicks >= 10) {
|
|
|
|
|
|
handleUnexpectedDisconnect(QStringLiteral(
|
|
|
|
|
|
"gRPC 服务连接已中断,请重新连接"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
pollGrpc();
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private:
|
2026-10-26 17:35:27 +08:00
|
|
|
|
void teachingCommand(const QString &command, const QString &deviceId, int operation)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!ensureConnected(command) || !ensureDeviceId(command, deviceId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (m_demoMode) {
|
|
|
|
|
|
emit commandFinished(command, true, QStringLiteral("示教命令执行成功(演示)"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
cmvr::api::CommandHeader::Request request;
|
|
|
|
|
|
fillHeader(&request, deviceId);
|
|
|
|
|
|
cmvr::api::CommandHeader::Feedback response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 2500);
|
|
|
|
|
|
grpc::Status status;
|
|
|
|
|
|
switch (operation) {
|
|
|
|
|
|
case 0:
|
|
|
|
|
|
status = m_arm->EnterTeachingMode(&context, request, &response);
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 1:
|
|
|
|
|
|
status = m_arm->CompleteTeaching(&context, request, &response);
|
|
|
|
|
|
break;
|
|
|
|
|
|
case 2:
|
|
|
|
|
|
status = m_arm->StopTrajectoryRecording(&context, request, &response);
|
|
|
|
|
|
break;
|
|
|
|
|
|
default:
|
|
|
|
|
|
status = m_arm->ExitTeachingMode(&context, request, &response);
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
finish(command, status, response.success(),
|
|
|
|
|
|
QString::fromStdString(response.error_message()));
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(operation)
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QString agvMapRequestError(const QString &deviceId, const QString &mapName) const
|
|
|
|
|
|
{
|
|
|
|
|
|
if (deviceId.trimmed().isEmpty())
|
|
|
|
|
|
return QStringLiteral("AGV 设备 ID 不能为空");
|
|
|
|
|
|
if (mapName.trimmed().isEmpty())
|
|
|
|
|
|
return QStringLiteral("地图名称不能为空");
|
|
|
|
|
|
if (!m_connected)
|
|
|
|
|
|
return QStringLiteral("设备尚未连接");
|
|
|
|
|
|
return QString();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static QString demoAgvMapKey(const QString &deviceId, const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString device = deviceId.trimmed();
|
|
|
|
|
|
return QString::number(device.size()) + QLatin1Char(':') + device + mapName.trimmed();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
QString demoAgvCurrentMap(const QString &deviceId) const
|
|
|
|
|
|
{
|
|
|
|
|
|
return m_demoAgvCurrentMaps.value(deviceId.trimmed(), QStringLiteral("demo_map"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
QString demoAgvMapContent(const QString &deviceId, const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString key = demoAgvMapKey(deviceId, mapName);
|
|
|
|
|
|
const auto existing = m_demoAgvMapContents.constFind(key);
|
|
|
|
|
|
if (existing != m_demoAgvMapContents.cend())
|
|
|
|
|
|
return existing.value();
|
|
|
|
|
|
QFile sample(QStringLiteral(":/assets/agv/demo_scan.smap"));
|
|
|
|
|
|
if (!sample.open(QIODevice::ReadOnly))
|
|
|
|
|
|
return QString();
|
|
|
|
|
|
QJsonObject root = QJsonDocument::fromJson(sample.readAll()).object();
|
|
|
|
|
|
QJsonObject header = root.value(QStringLiteral("header")).toObject();
|
|
|
|
|
|
header.insert(QStringLiteral("map_name"), mapName.trimmed());
|
|
|
|
|
|
root.insert(QStringLiteral("header"), header);
|
|
|
|
|
|
const QString content = QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Indented));
|
|
|
|
|
|
m_demoAgvMapContents.insert(key, content);
|
|
|
|
|
|
return content;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static QVariantList demoAgvStations(const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QJsonObject root = QJsonDocument::fromJson(content.toUtf8()).object();
|
|
|
|
|
|
const QJsonArray points = root.contains(QStringLiteral("advanced_point_list"))
|
|
|
|
|
|
? root.value(QStringLiteral("advanced_point_list")).toArray()
|
|
|
|
|
|
: root.value(QStringLiteral("advancedPointList")).toArray();
|
|
|
|
|
|
QVariantList stations;
|
|
|
|
|
|
for (const auto &value : points) {
|
|
|
|
|
|
const QJsonObject point = value.toObject();
|
|
|
|
|
|
const QString className = point.value(QStringLiteral("class_name")).toString(
|
|
|
|
|
|
point.value(QStringLiteral("className")).toString());
|
|
|
|
|
|
const QString id = point.value(QStringLiteral("instance_name")).toString(
|
|
|
|
|
|
point.value(QStringLiteral("instanceName")).toString());
|
|
|
|
|
|
if (className.compare(QStringLiteral("LandMark"), Qt::CaseInsensitive) != 0
|
|
|
|
|
|
|| id.trimmed().isEmpty())
|
|
|
|
|
|
continue;
|
|
|
|
|
|
const QJsonObject position = point.value(QStringLiteral("pos")).toObject();
|
|
|
|
|
|
QVariantMap station;
|
|
|
|
|
|
station.insert(QStringLiteral("id"), id);
|
|
|
|
|
|
station.insert(QStringLiteral("name"), agvStationDisplayName(
|
|
|
|
|
|
point.value(QStringLiteral("description")).toString(), id));
|
|
|
|
|
|
station.insert(QStringLiteral("type"), className);
|
|
|
|
|
|
station.insert(QStringLiteral("description"), point.value(QStringLiteral("description")).toString());
|
|
|
|
|
|
station.insert(QStringLiteral("x"), position.value(QStringLiteral("x")).toDouble());
|
|
|
|
|
|
station.insert(QStringLiteral("y"), position.value(QStringLiteral("y")).toDouble());
|
|
|
|
|
|
station.insert(QStringLiteral("theta"), point.value(QStringLiteral("dir")).toDouble());
|
|
|
|
|
|
stations.append(station);
|
|
|
|
|
|
}
|
|
|
|
|
|
return stations;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
bool ensureConnected(const QString &command)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (m_connected)
|
|
|
|
|
|
return true;
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("设备尚未连接"));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
bool ensureDeviceId(const QString &command, const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!deviceId.trimmed().isEmpty())
|
|
|
|
|
|
return true;
|
|
|
|
|
|
emit commandFinished(command, false, QStringLiteral("请在对应服务页填写设备 ID"));
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap agvContext(const QString &deviceId) const
|
|
|
|
|
|
{
|
|
|
|
|
|
return {{QStringLiteral("deviceId"), deviceId.trimmed()},
|
|
|
|
|
|
{QStringLiteral("endpoint"), QStringLiteral("%1:%2").arg(m_host).arg(m_port)},
|
|
|
|
|
|
{QStringLiteral("demo"), m_demoMode},
|
|
|
|
|
|
{QStringLiteral("available"), true}};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void emitAgvStateUnavailable(const QString &deviceId, const QString &detail)
|
|
|
|
|
|
{
|
|
|
|
|
|
QVariantMap state = agvContext(deviceId);
|
|
|
|
|
|
state.insert(QStringLiteral("available"), false);
|
|
|
|
|
|
state.insert(QStringLiteral("error"), detail);
|
|
|
|
|
|
emit agvStateReceived(state, QVariantMap());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void pollDemo()
|
|
|
|
|
|
{
|
|
|
|
|
|
++m_tick;
|
|
|
|
|
|
if (m_armPollingEnabled) {
|
|
|
|
|
|
QVariantList joints;
|
|
|
|
|
|
const QStringList jointNames = armJointNamesForDevice(m_armDeviceId);
|
|
|
|
|
|
for (int i = 0; i < jointNames.size(); ++i) {
|
|
|
|
|
|
const double phase = m_tick * 0.035 + i * 0.46;
|
|
|
|
|
|
double position = 0.36 * qSin(phase);
|
|
|
|
|
|
if (i < m_demoTargets.size())
|
|
|
|
|
|
position = m_demoTargets.at(i) + 0.025 * qSin(phase * 1.7);
|
|
|
|
|
|
QVariantMap joint;
|
|
|
|
|
|
joint.insert(QStringLiteral("name"), jointNames.at(i));
|
|
|
|
|
|
joint.insert(QStringLiteral("position"), position);
|
|
|
|
|
|
joint.insert(QStringLiteral("velocity"), 0.22 * qCos(phase));
|
|
|
|
|
|
joint.insert(QStringLiteral("effort"), 0.4 + 0.3 * qAbs(qSin(phase * 0.7)));
|
2026-10-14 17:15:46 +08:00
|
|
|
|
joint.insert(QStringLiteral("current"), 320.0 + 180.0 * qAbs(qSin(phase * 0.9)));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
joints.append(joint);
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantMap pose;
|
|
|
|
|
|
pose.insert(QStringLiteral("x"), 0.421 + 0.004 * qSin(m_tick * 0.02));
|
|
|
|
|
|
pose.insert(QStringLiteral("y"), -0.182 + 0.003 * qCos(m_tick * 0.025));
|
|
|
|
|
|
pose.insert(QStringLiteral("z"), 0.736 + 0.002 * qSin(m_tick * 0.017));
|
|
|
|
|
|
pose.insert(QStringLiteral("rx"), 1.571);
|
|
|
|
|
|
pose.insert(QStringLiteral("ry"), 0.014);
|
|
|
|
|
|
pose.insert(QStringLiteral("rz"), -0.021);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
QVariantMap state;
|
|
|
|
|
|
state.insert(QStringLiteral("connected"), true);
|
|
|
|
|
|
state.insert(QStringLiteral("poweredOn"), true);
|
|
|
|
|
|
state.insert(QStringLiteral("fault"), false);
|
|
|
|
|
|
state.insert(QStringLiteral("moving"), !m_demoTargets.isEmpty());
|
|
|
|
|
|
emit telemetryReceived(m_armDeviceId, joints, pose, state);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
if (m_tick % 10 == 0) {
|
|
|
|
|
|
emit systemStatusReceived(31.0 + 8.0 * qSin(m_tick * 0.04),
|
2026-09-23 11:11:49 +08:00
|
|
|
|
47.0 + 3.0 * qCos(m_tick * 0.025), 62.0,
|
|
|
|
|
|
demoDeviceList());
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
2026-10-16 09:39:44 +08:00
|
|
|
|
void handleUnexpectedDisconnect(const QString &detail)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!m_connected)
|
|
|
|
|
|
return;
|
|
|
|
|
|
m_pollTimer->stop();
|
|
|
|
|
|
stopArmMotionInternal();
|
|
|
|
|
|
stopCameraStreamInternal();
|
|
|
|
|
|
stopSpeakerStreamInternal(true);
|
|
|
|
|
|
stopMicrophoneStreamInternal();
|
|
|
|
|
|
stopDexHandTactileStreamInternal();
|
|
|
|
|
|
stopAgvMapStreamInternal();
|
|
|
|
|
|
if (m_cameraRecording) {
|
|
|
|
|
|
m_cameraRecording = false;
|
|
|
|
|
|
emit cameraRecordingStateChanged(false,
|
|
|
|
|
|
QStringLiteral("连接中断,录像状态未知"));
|
|
|
|
|
|
}
|
|
|
|
|
|
m_connected = false;
|
|
|
|
|
|
m_armPollingEnabled = false;
|
|
|
|
|
|
m_channelFailureTicks = 0;
|
|
|
|
|
|
m_arm.reset();
|
|
|
|
|
|
m_camera.reset();
|
|
|
|
|
|
m_dexHand.reset();
|
|
|
|
|
|
m_system.reset();
|
|
|
|
|
|
m_agv.reset();
|
|
|
|
|
|
m_microphone.reset();
|
|
|
|
|
|
m_generic.reset();
|
|
|
|
|
|
m_channel.reset();
|
|
|
|
|
|
emit connectionChanged(false, 0, detail);
|
|
|
|
|
|
emit logMessage(QStringLiteral("ERROR"), detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
static void fillHeader(cmvr::api::CommandHeader::Request *header,
|
|
|
|
|
|
const QString &deviceId, int validForMs = 5000)
|
|
|
|
|
|
{
|
|
|
|
|
|
header->set_device_id(deviceId.toStdString());
|
|
|
|
|
|
const qint64 now = QDateTime::currentMSecsSinceEpoch();
|
|
|
|
|
|
header->mutable_timestamp()->set_seconds(now / 1000);
|
|
|
|
|
|
header->mutable_timestamp()->set_nanos(static_cast<int>((now % 1000) * 1000000));
|
|
|
|
|
|
header->set_command_id(
|
|
|
|
|
|
QUuid::createUuid().toString(QUuid::WithoutBraces).toStdString());
|
|
|
|
|
|
header->set_valid_for_ms(static_cast<quint32>(qMax(1, validForMs)));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
static void setDeadline(grpc::ClientContext &context, int milliseconds)
|
|
|
|
|
|
{
|
|
|
|
|
|
context.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(milliseconds));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void runSpeakerAudioStream(const std::shared_ptr<grpc::Channel> &channel,
|
|
|
|
|
|
const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
std::unique_ptr<cmvr::api::SpeakerService::Stub> speaker =
|
|
|
|
|
|
cmvr::api::SpeakerService::NewStub(channel);
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerContextMutex);
|
|
|
|
|
|
m_speakerStreamContext = &context;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_speakerStreamStop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::StreamSpeakerAudioCommand::Feedback feedback;
|
|
|
|
|
|
std::unique_ptr<grpc::ClientWriter<cmvr::api::StreamSpeakerAudioCommand::Request>> writer =
|
|
|
|
|
|
speaker->StreamAudio(&context, &feedback);
|
|
|
|
|
|
bool writeOk = static_cast<bool>(writer);
|
|
|
|
|
|
while (writeOk) {
|
|
|
|
|
|
SpeakerAudioFrame frame;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::unique_lock<std::mutex> lock(m_speakerQueueMutex);
|
|
|
|
|
|
m_speakerQueueCondition.wait(lock, [this]() {
|
|
|
|
|
|
return m_speakerStreamStop.load() || !m_speakerQueue.empty();
|
|
|
|
|
|
});
|
|
|
|
|
|
if (m_speakerQueue.empty()) {
|
|
|
|
|
|
if (m_speakerStreamStop.load())
|
|
|
|
|
|
break;
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
frame = std::move(m_speakerQueue.front());
|
|
|
|
|
|
m_speakerQueue.pop_front();
|
|
|
|
|
|
m_speakerQueueBytes -= frame.data.size();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::StreamSpeakerAudioCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::AudioData *audio = request.mutable_audio();
|
|
|
|
|
|
audio->set_data(frame.data.constData(), frame.data.size());
|
|
|
|
|
|
audio->set_sample_rate(frame.sampleRate);
|
|
|
|
|
|
audio->set_channels(frame.channels);
|
|
|
|
|
|
audio->set_format(cmvr::api::AudioData::PCM);
|
|
|
|
|
|
audio->set_codec("pcm_s16le");
|
|
|
|
|
|
audio->set_pts(frame.pts);
|
|
|
|
|
|
audio->set_nb_samples(frame.samples);
|
|
|
|
|
|
writeOk = writer->Write(request);
|
|
|
|
|
|
if (writeOk) {
|
|
|
|
|
|
const quint64 frames = ++m_speakerFrames;
|
|
|
|
|
|
const quint64 bytes = m_speakerBytes.fetch_add(frame.data.size()) + frame.data.size();
|
|
|
|
|
|
emit audioStreamStatistics(QStringLiteral("SpeakerService"), frames, bytes,
|
|
|
|
|
|
frame.pts / 1000 + frame.samples * 1000LL / frame.sampleRate);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (writer)
|
|
|
|
|
|
writer->WritesDone();
|
|
|
|
|
|
const grpc::Status status = writer ? writer->Finish()
|
|
|
|
|
|
: grpc::Status(grpc::StatusCode::UNKNOWN,
|
|
|
|
|
|
"failed to create client writer");
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_speakerContextMutex);
|
|
|
|
|
|
m_speakerStreamContext = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool stopped = m_speakerStreamStop.load();
|
|
|
|
|
|
const bool success = !stopped && status.ok() && feedback.header().success();
|
|
|
|
|
|
QString detail;
|
|
|
|
|
|
if (stopped)
|
|
|
|
|
|
detail = QStringLiteral("扬声器音频流已停止");
|
|
|
|
|
|
else if (!status.ok())
|
|
|
|
|
|
detail = QStringLiteral("扬声器音频流失败:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(status.error_message()));
|
|
|
|
|
|
else if (!feedback.header().success())
|
|
|
|
|
|
detail = QStringLiteral("扬声器拒绝音频流:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(feedback.header().error_message()));
|
|
|
|
|
|
else
|
|
|
|
|
|
detail = QStringLiteral("扬声器音频流发送完成");
|
|
|
|
|
|
m_speakerStreamRunning.store(false);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("SpeakerService"), false, detail);
|
|
|
|
|
|
if (!stopped)
|
|
|
|
|
|
emit commandFinished(QStringLiteral("Speaker Stream"), success, detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void runMicrophoneAudioStream(const std::shared_ptr<grpc::Channel> &channel,
|
|
|
|
|
|
const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
std::unique_ptr<cmvr::api::MicPhoneService::Stub> microphone =
|
|
|
|
|
|
cmvr::api::MicPhoneService::NewStub(channel);
|
|
|
|
|
|
cmvr::api::StreamMicAudioCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_microphoneContextMutex);
|
|
|
|
|
|
m_microphoneStreamContext = &context;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_microphoneStreamStop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
|
|
|
|
|
|
std::unique_ptr<grpc::ClientReader<cmvr::api::StreamMicAudioCommand::Feedback>> reader =
|
|
|
|
|
|
microphone->StreamAudio(&context, request);
|
|
|
|
|
|
cmvr::api::StreamMicAudioCommand::Feedback feedback;
|
|
|
|
|
|
while (reader && !m_microphoneStreamStop.load() && reader->Read(&feedback)) {
|
|
|
|
|
|
if (!feedback.header().success()) {
|
|
|
|
|
|
emit logMessage(QStringLiteral("WARN"),
|
|
|
|
|
|
QStringLiteral("麦克风音频帧反馈失败:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(feedback.header().error_message())));
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
const cmvr::api::AudioData &audio = feedback.audio();
|
|
|
|
|
|
const QByteArray data(audio.data().data(), static_cast<int>(audio.data().size()));
|
|
|
|
|
|
const quint64 frames = ++m_microphoneFrames;
|
|
|
|
|
|
const quint64 bytes = m_microphoneBytes.fetch_add(data.size()) + data.size();
|
|
|
|
|
|
emit audioFrameReceived(data, audio.sample_rate(), audio.channels(),
|
|
|
|
|
|
static_cast<int>(audio.format()),
|
|
|
|
|
|
QString::fromStdString(audio.codec()), audio.pts(),
|
|
|
|
|
|
audio.nb_samples());
|
|
|
|
|
|
const qint64 durationMs = audio.sample_rate() > 0
|
|
|
|
|
|
? audio.pts() / 1000 + audio.nb_samples() * 1000LL / audio.sample_rate()
|
|
|
|
|
|
: 0;
|
|
|
|
|
|
emit audioStreamStatistics(QStringLiteral("MicPhoneService"), frames, bytes,
|
|
|
|
|
|
durationMs);
|
|
|
|
|
|
}
|
|
|
|
|
|
const grpc::Status status = reader ? reader->Finish()
|
|
|
|
|
|
: grpc::Status(grpc::StatusCode::UNKNOWN,
|
|
|
|
|
|
"failed to create client reader");
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(m_microphoneContextMutex);
|
|
|
|
|
|
m_microphoneStreamContext = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool stopped = m_microphoneStreamStop.load();
|
|
|
|
|
|
QString detail;
|
|
|
|
|
|
if (stopped)
|
|
|
|
|
|
detail = QStringLiteral("麦克风音频拉流已停止");
|
|
|
|
|
|
else if (!status.ok())
|
|
|
|
|
|
detail = QStringLiteral("麦克风音频拉流失败:%1")
|
|
|
|
|
|
.arg(QString::fromStdString(status.error_message()));
|
|
|
|
|
|
else
|
|
|
|
|
|
detail = QStringLiteral("麦克风音频拉流已结束");
|
|
|
|
|
|
m_microphoneStreamRunning.store(false);
|
|
|
|
|
|
emit audioStreamStateChanged(QStringLiteral("MicPhoneService"), false, detail);
|
|
|
|
|
|
if (!stopped)
|
|
|
|
|
|
emit commandFinished(QStringLiteral("MicPhone Stream"), status.ok(), detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void runDepthCameraStream(const std::shared_ptr<grpc::Channel> &channel,
|
|
|
|
|
|
const std::shared_ptr<CameraStreamSession> &session,
|
|
|
|
|
|
bool rgbd)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString cameraId = session->cameraId;
|
|
|
|
|
|
auto camera = cmvr::api::CameraService::NewStub(channel);
|
|
|
|
|
|
cmvr::api::StartCameraCommand::Request startRequest;
|
|
|
|
|
|
fillHeader(startRequest.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::StartCameraCommand::Feedback startResponse;
|
|
|
|
|
|
grpc::ClientContext startContext;
|
|
|
|
|
|
setDeadline(startContext, 3000);
|
|
|
|
|
|
const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse);
|
|
|
|
|
|
if (!startStatus.ok() || !startResponse.header().success()) {
|
|
|
|
|
|
const QString error = !startStatus.ok()
|
|
|
|
|
|
? QString::fromStdString(startStatus.error_message())
|
|
|
|
|
|
: QString::fromStdString(startResponse.header().error_message());
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(cameraId, false,
|
|
|
|
|
|
QStringLiteral("鍚姩鐩告満澶辫触锛?1").arg(error));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("Camera Stream"), false, error);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->context = &context;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (session->stop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
|
|
|
|
|
|
QString terminalError;
|
|
|
|
|
|
if (rgbd) {
|
|
|
|
|
|
auto stream = camera->GetRGBDImagesStream(&context);
|
|
|
|
|
|
cmvr::api::GetRGBDImagesStreamCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
request.set_eof(false);
|
|
|
|
|
|
if (!stream || !stream->Write(request)) {
|
|
|
|
|
|
terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触");
|
|
|
|
|
|
} else {
|
|
|
|
|
|
cmvr::api::GetRGBDImagesStreamCommand::Feedback response;
|
|
|
|
|
|
while (!session->stop.load() && stream->Read(&response)) {
|
|
|
|
|
|
if (!response.header().success()) {
|
|
|
|
|
|
terminalError = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &depth = response.depth_frame();
|
|
|
|
|
|
VideoFrame frame = videoFrameFromDepth(depth);
|
|
|
|
|
|
if (!frame.isValid())
|
|
|
|
|
|
continue;
|
|
|
|
|
|
if (videoFrameReceivedForCamera)
|
|
|
|
|
|
videoFrameReceivedForCamera(cameraId, frame,
|
|
|
|
|
|
QStringLiteral("%1 x %2 | DEPTH | #%3")
|
|
|
|
|
|
.arg(depth.width()).arg(depth.height()).arg(response.seq_no()));
|
|
|
|
|
|
}
|
|
|
|
|
|
stream->WritesDone();
|
|
|
|
|
|
stream->Finish();
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
auto stream = camera->GetDepthImageStream(&context);
|
|
|
|
|
|
cmvr::api::GetDepthImageStreamCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
request.set_eof(false);
|
|
|
|
|
|
if (!stream || !stream->Write(request)) {
|
|
|
|
|
|
terminalError = QStringLiteral("鍙戦€佽棰戞祦璁㈤槄璇锋眰澶辫触");
|
|
|
|
|
|
} else {
|
|
|
|
|
|
cmvr::api::GetDepthImageStreamCommand::Feedback response;
|
|
|
|
|
|
while (!session->stop.load() && stream->Read(&response)) {
|
|
|
|
|
|
if (!response.header().success()) {
|
|
|
|
|
|
terminalError = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &depth = response.depth_frame();
|
|
|
|
|
|
VideoFrame frame = videoFrameFromDepth(depth);
|
|
|
|
|
|
if (!frame.isValid())
|
|
|
|
|
|
continue;
|
|
|
|
|
|
if (videoFrameReceivedForCamera)
|
|
|
|
|
|
videoFrameReceivedForCamera(cameraId, frame,
|
|
|
|
|
|
QStringLiteral("%1 x %2 | DEPTH | #%3")
|
|
|
|
|
|
.arg(depth.width()).arg(depth.height()).arg(response.seq_no()));
|
|
|
|
|
|
}
|
|
|
|
|
|
stream->WritesDone();
|
|
|
|
|
|
stream->Finish();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if (session->stop.load())
|
|
|
|
|
|
terminalError = QStringLiteral("瑙嗛棰勮宸插仠姝?");
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
if (session->context == &context)
|
|
|
|
|
|
session->context = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(
|
|
|
|
|
|
cameraId, false,
|
|
|
|
|
|
terminalError.isEmpty() ? QStringLiteral("Depth stream ended") : terminalError);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void runCameraStream(const std::shared_ptr<grpc::Channel> &channel,
|
|
|
|
|
|
const std::shared_ptr<CameraStreamSession> &session)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString cameraId = session->cameraId;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::CameraService::Stub> camera =
|
|
|
|
|
|
cmvr::api::CameraService::NewStub(channel);
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::StartCameraCommand::Request startRequest;
|
|
|
|
|
|
fillHeader(startRequest.mutable_header(), cameraId);
|
|
|
|
|
|
cmvr::api::StartCameraCommand::Feedback startResponse;
|
|
|
|
|
|
grpc::ClientContext startContext;
|
|
|
|
|
|
setDeadline(startContext, 3000);
|
|
|
|
|
|
const grpc::Status startStatus = camera->StartCamera(&startContext, startRequest, &startResponse);
|
|
|
|
|
|
if (!startStatus.ok() || !startResponse.header().success()) {
|
|
|
|
|
|
const QString error = !startStatus.ok()
|
|
|
|
|
|
? QString::fromStdString(startStatus.error_message())
|
|
|
|
|
|
: QString::fromStdString(startResponse.header().error_message());
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(
|
|
|
|
|
|
cameraId, false, QStringLiteral("启动相机失败:%1").arg(error));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit commandFinished(QStringLiteral("Camera Stream"), false, error);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (session->stop.load()) {
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(
|
|
|
|
|
|
cameraId, false, QStringLiteral("视频预览已停止"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->context = &context;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (session->stop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
std::unique_ptr<grpc::ClientReaderWriter<
|
|
|
|
|
|
cmvr::api::GetRGBImageStreamCommand::Request,
|
|
|
|
|
|
cmvr::api::GetRGBImageStreamCommand::Feedback>> stream =
|
|
|
|
|
|
camera->GetRGBImageStream(&context);
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::GetRGBImageStreamCommand::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), cameraId);
|
|
|
|
|
|
request.set_eof(false);
|
|
|
|
|
|
if (!stream || !stream->Write(request)) {
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
if (stream)
|
|
|
|
|
|
stream->Finish();
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
session->context = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
session->running.store(false);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(
|
|
|
|
|
|
cameraId, false, QStringLiteral("发送视频流订阅请求失败"));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (session->stop.load())
|
|
|
|
|
|
context.TryCancel();
|
|
|
|
|
|
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"),
|
|
|
|
|
|
QStringLiteral("CameraService.GetRGBImageStream 已启动:%1,解码格式=%2")
|
|
|
|
|
|
.arg(cameraId, session->codec == QStringLiteral("h265")
|
|
|
|
|
|
? QStringLiteral("H.265")
|
|
|
|
|
|
: QStringLiteral("H.264")));
|
|
|
|
|
|
struct CompressedVideoFrame {
|
|
|
|
|
|
QByteArray data;
|
|
|
|
|
|
QString codec;
|
|
|
|
|
|
qint64 pts = 0;
|
|
|
|
|
|
qint64 dts = 0;
|
|
|
|
|
|
int width = 0;
|
|
|
|
|
|
int height = 0;
|
|
|
|
|
|
int seqNo = 0;
|
|
|
|
|
|
quint32 sourceFps = 0;
|
|
|
|
|
|
quint64 generation = 0;
|
|
|
|
|
|
bool keyFrame = false;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
QVariantMap intrinsics;
|
|
|
|
|
|
QVariantMap metadata;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
};
|
|
|
|
|
|
// Frame-threaded HEVC needs several packets before its first output.
|
|
|
|
|
|
// Keep enough startup headroom so the low-latency recovery logic does
|
|
|
|
|
|
// not repeatedly reset a decoder that is still warming up.
|
|
|
|
|
|
constexpr std::size_t kMaxCompressedFrames = 45;
|
|
|
|
|
|
std::deque<CompressedVideoFrame> compressedFrames;
|
|
|
|
|
|
std::mutex compressedFramesMutex;
|
|
|
|
|
|
std::condition_variable compressedFramesReady;
|
|
|
|
|
|
bool readerFinished = false;
|
|
|
|
|
|
quint64 queueGeneration = 0;
|
|
|
|
|
|
std::atomic<quint64> decodedFrames{0};
|
|
|
|
|
|
std::atomic<quint64> displayedFrames{0};
|
|
|
|
|
|
std::atomic<quint64> receivedFrames{0};
|
|
|
|
|
|
std::atomic<quint64> receivedBytes{0};
|
|
|
|
|
|
std::atomic<quint64> droppedFrames{0};
|
|
|
|
|
|
std::atomic<quint64> sourceSequence{0};
|
|
|
|
|
|
std::atomic<quint64> sourceSequenceGaps{0};
|
|
|
|
|
|
std::atomic<std::size_t> compressedQueueDepth{0};
|
|
|
|
|
|
QElapsedTimer totalTimer;
|
|
|
|
|
|
totalTimer.start();
|
|
|
|
|
|
QString terminalError;
|
|
|
|
|
|
|
|
|
|
|
|
std::thread decoderThread([&] {
|
|
|
|
|
|
VideoDecoder decoder;
|
|
|
|
|
|
QElapsedTimer rateTimer;
|
|
|
|
|
|
rateTimer.start();
|
|
|
|
|
|
quint64 rateFrames = 0;
|
|
|
|
|
|
quint64 previousReceivedFrames = 0;
|
|
|
|
|
|
quint64 previousDecodedFrames = 0;
|
|
|
|
|
|
quint64 previousRateBytes = 0;
|
|
|
|
|
|
quint64 previousSourceSequence = 0;
|
|
|
|
|
|
qint64 decodeNanoseconds = 0;
|
|
|
|
|
|
quint64 timedDecodePackets = 0;
|
|
|
|
|
|
double receiveFps = 0.0;
|
|
|
|
|
|
double sourceSequenceFps = 0.0;
|
|
|
|
|
|
double displayFps = 0.0;
|
|
|
|
|
|
double decodeFps = 0.0;
|
|
|
|
|
|
double decodeMilliseconds = 0.0;
|
|
|
|
|
|
double bitrateKbps = 0.0;
|
|
|
|
|
|
int decodeErrors = 0;
|
|
|
|
|
|
QString activeCodec;
|
|
|
|
|
|
quint64 activeGeneration = std::numeric_limits<quint64>::max();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
struct FrameMetadata {
|
|
|
|
|
|
QVariantMap intrinsics;
|
|
|
|
|
|
QVariantMap metadata;
|
|
|
|
|
|
bool ambiguous = false;
|
|
|
|
|
|
bool delivered = false;
|
|
|
|
|
|
};
|
|
|
|
|
|
QHash<qint64, FrameMetadata> metadataByPts;
|
|
|
|
|
|
std::deque<qint64> metadataOrder;
|
|
|
|
|
|
constexpr std::size_t kMaxFrameMetadata = 256;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
while (!session->stop.load()) {
|
|
|
|
|
|
CompressedVideoFrame packet;
|
|
|
|
|
|
{
|
|
|
|
|
|
std::unique_lock<std::mutex> lock(compressedFramesMutex);
|
|
|
|
|
|
compressedFramesReady.wait(lock, [&] {
|
|
|
|
|
|
return session->stop.load() || readerFinished ||
|
|
|
|
|
|
!compressedFrames.empty();
|
|
|
|
|
|
});
|
|
|
|
|
|
if ((session->stop.load() || readerFinished) &&
|
|
|
|
|
|
compressedFrames.empty())
|
|
|
|
|
|
break;
|
|
|
|
|
|
packet = std::move(compressedFrames.front());
|
|
|
|
|
|
compressedFrames.pop_front();
|
|
|
|
|
|
compressedQueueDepth.store(compressedFrames.size());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const QString codec = packet.codec.isEmpty()
|
|
|
|
|
|
? session->codec : packet.codec;
|
|
|
|
|
|
if (codec != activeCodec ||
|
|
|
|
|
|
packet.generation != activeGeneration) {
|
|
|
|
|
|
decoder.reset();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadataByPts.clear();
|
|
|
|
|
|
metadataOrder.clear();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
activeCodec = codec;
|
|
|
|
|
|
activeGeneration = packet.generation;
|
|
|
|
|
|
decodeErrors = 0;
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"),
|
|
|
|
|
|
QStringLiteral("视频解码器已切换为 %1,等待参数集和关键帧")
|
|
|
|
|
|
.arg(codec.toUpper()));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
// FFmpeg may output an older frame after several input packets.
|
|
|
|
|
|
// Match by decoded PTS, never by the most recently read packet.
|
|
|
|
|
|
// Zero is also the protobuf missing-field default: omit it from
|
|
|
|
|
|
// calibration matching, while leaving video display unaffected.
|
|
|
|
|
|
if (packet.pts != 0 && packet.pts != std::numeric_limits<qint64>::min()) {
|
|
|
|
|
|
auto existingMetadata = metadataByPts.find(packet.pts);
|
|
|
|
|
|
if (existingMetadata != metadataByPts.end()) {
|
|
|
|
|
|
existingMetadata->ambiguous = true;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
FrameMetadata values;
|
|
|
|
|
|
values.intrinsics = packet.intrinsics;
|
|
|
|
|
|
values.metadata = packet.metadata;
|
|
|
|
|
|
metadataByPts.insert(packet.pts, values);
|
|
|
|
|
|
metadataOrder.push_back(packet.pts);
|
|
|
|
|
|
while (metadataOrder.size() > kMaxFrameMetadata) {
|
|
|
|
|
|
metadataByPts.remove(metadataOrder.front());
|
|
|
|
|
|
metadataOrder.pop_front();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QVector<VideoFrame> frames;
|
|
|
|
|
|
int decodedCount = 0;
|
|
|
|
|
|
QElapsedTimer decodeTimer;
|
|
|
|
|
|
decodeTimer.start();
|
|
|
|
|
|
if (!decoder.decode(packet.data, codec, packet.pts, packet.dts,
|
|
|
|
|
|
&frames, true, &decodedCount)) {
|
2026-10-14 17:15:46 +08:00
|
|
|
|
metadataByPts.clear();
|
|
|
|
|
|
metadataOrder.clear();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
++decodeErrors;
|
|
|
|
|
|
if (decodeErrors == 1 || decodeErrors % 60 == 0) {
|
|
|
|
|
|
emit logMessage(QStringLiteral("WARN"),
|
|
|
|
|
|
QStringLiteral("视频解码失败(%1 次):%2")
|
|
|
|
|
|
.arg(decodeErrors).arg(decoder.lastError()));
|
|
|
|
|
|
}
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
decodeNanoseconds += decodeTimer.nsecsElapsed();
|
|
|
|
|
|
++timedDecodePackets;
|
|
|
|
|
|
decodedFrames.fetch_add(static_cast<quint64>(decodedCount));
|
|
|
|
|
|
|
|
|
|
|
|
if (!frames.isEmpty()) {
|
|
|
|
|
|
if (displayedFrames.load() == 0) {
|
|
|
|
|
|
emit logMessage(QStringLiteral("INFO"),
|
|
|
|
|
|
QStringLiteral("视频预览解码后端:%1")
|
|
|
|
|
|
.arg(decoder.backendName()));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-14 17:15:46 +08:00
|
|
|
|
for (VideoFrame &frame : frames) {
|
|
|
|
|
|
frame.metadata = {{QStringLiteral("kind"), QStringLiteral("rgb")},
|
|
|
|
|
|
{QStringLiteral("ptsMatched"), false},
|
|
|
|
|
|
{QStringLiteral("captureTimestampAvailable"), false}};
|
|
|
|
|
|
auto matched = metadataByPts.find(frame.presentationTimestamp);
|
|
|
|
|
|
if (matched != metadataByPts.end() && !matched->ambiguous
|
|
|
|
|
|
&& !matched->delivered) {
|
|
|
|
|
|
frame.intrinsics = matched->intrinsics;
|
|
|
|
|
|
frame.metadata = matched->metadata;
|
|
|
|
|
|
frame.metadata.insert(QStringLiteral("ptsMatched"), true);
|
|
|
|
|
|
matched->delivered = true;
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
displayedFrames.fetch_add(1);
|
|
|
|
|
|
++rateFrames;
|
|
|
|
|
|
if (rateTimer.elapsed() >= 1000) {
|
|
|
|
|
|
const double seconds = rateTimer.elapsed() / 1000.0;
|
|
|
|
|
|
const quint64 currentBytes = receivedBytes.load();
|
|
|
|
|
|
const quint64 currentReceivedFrames = receivedFrames.load();
|
|
|
|
|
|
const quint64 currentSourceSequence = sourceSequence.load();
|
|
|
|
|
|
receiveFps = (currentReceivedFrames - previousReceivedFrames) / seconds;
|
|
|
|
|
|
sourceSequenceFps = previousSourceSequence > 0 &&
|
|
|
|
|
|
currentSourceSequence >= previousSourceSequence
|
|
|
|
|
|
? (currentSourceSequence - previousSourceSequence) / seconds : 0.0;
|
|
|
|
|
|
displayFps = rateFrames / seconds;
|
|
|
|
|
|
const quint64 currentDecodedFrames = decodedFrames.load();
|
|
|
|
|
|
decodeFps = (currentDecodedFrames - previousDecodedFrames) / seconds;
|
|
|
|
|
|
bitrateKbps = (currentBytes - previousRateBytes) * 8.0 /
|
|
|
|
|
|
seconds / 1000.0;
|
|
|
|
|
|
decodeMilliseconds = timedDecodePackets > 0
|
|
|
|
|
|
? decodeNanoseconds / 1000000.0 / timedDecodePackets : 0.0;
|
|
|
|
|
|
rateFrames = 0;
|
|
|
|
|
|
previousReceivedFrames = currentReceivedFrames;
|
|
|
|
|
|
previousSourceSequence = currentSourceSequence;
|
|
|
|
|
|
previousDecodedFrames = currentDecodedFrames;
|
|
|
|
|
|
previousRateBytes = currentBytes;
|
|
|
|
|
|
decodeNanoseconds = 0;
|
|
|
|
|
|
timedDecodePackets = 0;
|
|
|
|
|
|
rateTimer.restart();
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString sourceRate = packet.sourceFps > 0
|
|
|
|
|
|
? QStringLiteral("/%1").arg(packet.sourceFps) : QString();
|
|
|
|
|
|
const QString dropDetail = droppedFrames.load() > 0
|
|
|
|
|
|
? QStringLiteral(" | 低延迟丢帧 %1").arg(droppedFrames.load())
|
|
|
|
|
|
: QString();
|
|
|
|
|
|
const QString detail = QStringLiteral("%1 x %2 | %3 | FPS 源/收/解/显 %4/%5/%6/%7%8 | %9 %10 ms | Q%11 缺%12 | %13 kbps | #%14%15")
|
|
|
|
|
|
.arg(packet.width).arg(packet.height).arg(codec.toUpper())
|
|
|
|
|
|
.arg(sourceSequenceFps, 0, 'f', 1).arg(receiveFps, 0, 'f', 1)
|
|
|
|
|
|
.arg(decodeFps, 0, 'f', 1).arg(displayFps, 0, 'f', 1)
|
|
|
|
|
|
.arg(sourceRate).arg(decoder.backendName())
|
|
|
|
|
|
.arg(decodeMilliseconds, 0, 'f', 1).arg(compressedQueueDepth.load())
|
|
|
|
|
|
.arg(sourceSequenceGaps.load()).arg(bitrateKbps, 0, 'f', 0)
|
|
|
|
|
|
.arg(packet.seqNo).arg(dropDetail);
|
|
|
|
|
|
if (videoFrameReceivedForCamera)
|
|
|
|
|
|
videoFrameReceivedForCamera(cameraId, frame, detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
cmvr::api::GetRGBImageStreamCommand::Feedback response;
|
|
|
|
|
|
while (!session->stop.load() && stream->Read(&response)) {
|
|
|
|
|
|
if (!response.header().success()) {
|
|
|
|
|
|
terminalError = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
const auto &frame = response.color_frame();
|
|
|
|
|
|
if (frame.data().empty())
|
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
|
|
receivedBytes.fetch_add(static_cast<quint64>(frame.data().size()));
|
|
|
|
|
|
receivedFrames.fetch_add(1);
|
|
|
|
|
|
const quint64 currentSourceSequence = frame.source_sequence();
|
|
|
|
|
|
const quint64 previousSequence = sourceSequence.exchange(currentSourceSequence);
|
|
|
|
|
|
if (previousSequence > 0 && currentSourceSequence > previousSequence + 1)
|
|
|
|
|
|
sourceSequenceGaps.fetch_add(currentSourceSequence - previousSequence - 1);
|
|
|
|
|
|
CompressedVideoFrame packet;
|
|
|
|
|
|
packet.data = QByteArray(frame.data().data(), static_cast<int>(frame.data().size()));
|
|
|
|
|
|
packet.codec = QString::fromStdString(frame.codec()).trimmed().toLower();
|
|
|
|
|
|
packet.pts = frame.pts();
|
|
|
|
|
|
packet.dts = frame.dts();
|
|
|
|
|
|
packet.width = frame.width();
|
|
|
|
|
|
packet.height = frame.height();
|
|
|
|
|
|
packet.seqNo = response.seq_no();
|
|
|
|
|
|
packet.sourceFps = frame.source_fps();
|
|
|
|
|
|
packet.keyFrame = frame.is_key_frame();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
const auto &intrinsics = response.intrinsics();
|
|
|
|
|
|
QVariantList coefficients;
|
|
|
|
|
|
for (const float coefficient : intrinsics.coeffs())
|
|
|
|
|
|
coefficients.append(static_cast<double>(coefficient));
|
|
|
|
|
|
// Preserve the server values. Some drivers resize their encoded
|
|
|
|
|
|
// output without scaling K; consumers must confirm native dimensions.
|
|
|
|
|
|
packet.intrinsics = {
|
|
|
|
|
|
{QStringLiteral("fx"), intrinsics.fx()}, {QStringLiteral("fy"), intrinsics.fy()},
|
|
|
|
|
|
{QStringLiteral("cx"), intrinsics.cx()}, {QStringLiteral("cy"), intrinsics.cy()},
|
|
|
|
|
|
{QStringLiteral("coeffs"), coefficients},
|
|
|
|
|
|
{QStringLiteral("width"), frame.width()},
|
|
|
|
|
|
{QStringLiteral("height"), frame.height()},
|
|
|
|
|
|
{QStringLiteral("distortionModelAvailable"), false},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImageStream.intrinsics")}};
|
|
|
|
|
|
packet.metadata = {
|
|
|
|
|
|
{QStringLiteral("cameraSerial"),QString::fromStdString(frame.camera_serial())},
|
|
|
|
|
|
{QStringLiteral("cameraSessionGeneration"),qulonglong(frame.camera_session_generation())},
|
|
|
|
|
|
{QStringLiteral("kind"), QStringLiteral("rgb")},
|
|
|
|
|
|
{QStringLiteral("captureUtcNs"), static_cast<qint64>(frame.capture_utc_ns())},
|
|
|
|
|
|
{QStringLiteral("sourceSequence"), static_cast<quint64>(frame.source_sequence())},
|
|
|
|
|
|
{QStringLiteral("sourceFrameNumber"), static_cast<quint64>(frame.source_frame_number())},
|
|
|
|
|
|
{QStringLiteral("sourceTimestamp"), static_cast<quint64>(frame.source_timestamp())},
|
|
|
|
|
|
{QStringLiteral("pts"), static_cast<qint64>(frame.pts())},
|
|
|
|
|
|
{QStringLiteral("dts"), static_cast<qint64>(frame.dts())},
|
|
|
|
|
|
{QStringLiteral("sourceFps"), frame.source_fps()},
|
|
|
|
|
|
{QStringLiteral("receivedAtMs"), QDateTime::currentMSecsSinceEpoch()},
|
|
|
|
|
|
{QStringLiteral("captureTimestampAvailable"), frame.capture_utc_ns() > 0},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("CameraService.GetRGBImageStream.color_frame")}};
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(compressedFramesMutex);
|
|
|
|
|
|
// Resynchronize only at a keyframe already in hand. Clearing a
|
|
|
|
|
|
// full queue at an arbitrary P-frame makes the decoder wait for
|
|
|
|
|
|
// a future keyframe and can cause a reset loop during startup.
|
|
|
|
|
|
if (compressedFrames.size() >= kMaxCompressedFrames) {
|
|
|
|
|
|
if (packet.keyFrame) {
|
|
|
|
|
|
droppedFrames.fetch_add(
|
|
|
|
|
|
static_cast<quint64>(compressedFrames.size()));
|
|
|
|
|
|
compressedFrames.clear();
|
|
|
|
|
|
compressedQueueDepth.store(0);
|
|
|
|
|
|
++queueGeneration;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
droppedFrames.fetch_add(1);
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
packet.generation = queueGeneration;
|
|
|
|
|
|
compressedFrames.push_back(std::move(packet));
|
|
|
|
|
|
compressedQueueDepth.store(compressedFrames.size());
|
|
|
|
|
|
}
|
|
|
|
|
|
compressedFramesReady.notify_one();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(compressedFramesMutex);
|
|
|
|
|
|
readerFinished = true;
|
|
|
|
|
|
}
|
|
|
|
|
|
compressedFramesReady.notify_all();
|
|
|
|
|
|
|
|
|
|
|
|
stream->WritesDone();
|
|
|
|
|
|
const grpc::Status status = stream->Finish();
|
|
|
|
|
|
if (decoderThread.joinable())
|
|
|
|
|
|
decoderThread.join();
|
|
|
|
|
|
{
|
|
|
|
|
|
std::lock_guard<std::mutex> lock(session->contextMutex);
|
|
|
|
|
|
if (session->context == &context)
|
|
|
|
|
|
session->context = nullptr;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const bool stoppedByUser = session->stop.load();
|
|
|
|
|
|
if (terminalError.isEmpty() && !status.ok() && !stoppedByUser)
|
|
|
|
|
|
terminalError = QString::fromStdString(status.error_message());
|
|
|
|
|
|
session->running.store(false);
|
|
|
|
|
|
const QString summary = terminalError.isEmpty()
|
|
|
|
|
|
? QStringLiteral("视频预览已停止,解码 %1 帧,显示 %2 帧,%3 MB,%4 秒")
|
|
|
|
|
|
.arg(decodedFrames.load()).arg(displayedFrames.load())
|
|
|
|
|
|
.arg(receivedBytes.load() / 1048576.0, 0, 'f', 1)
|
|
|
|
|
|
.arg(totalTimer.elapsed() / 1000.0, 0, 'f', 1)
|
|
|
|
|
|
: QStringLiteral("视频流失败:%1").arg(terminalError);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (!session->superseded.load())
|
|
|
|
|
|
emit cameraStreamStateChangedForCamera(cameraId, false, summary);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit logMessage(terminalError.isEmpty() ? QStringLiteral("INFO") : QStringLiteral("ERROR"), summary);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
bool finishAgvVelocity(const QString &command, const grpc::Status &status, bool responseSuccess,
|
|
|
|
|
|
const QString &responseError, QString *resultDetail = nullptr)
|
|
|
|
|
|
{
|
|
|
|
|
|
const bool success = status.ok() && responseSuccess;
|
|
|
|
|
|
QString detail;
|
|
|
|
|
|
if (!status.ok()) {
|
|
|
|
|
|
const QString message = QString::fromStdString(status.error_message());
|
|
|
|
|
|
detail = QStringLiteral("gRPC code %1:%2")
|
|
|
|
|
|
.arg(static_cast<int>(status.error_code()))
|
|
|
|
|
|
.arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情")
|
|
|
|
|
|
: message);
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (!responseSuccess)
|
|
|
|
|
|
detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了命令") : responseError;
|
|
|
|
|
|
else
|
|
|
|
|
|
detail = QStringLiteral("命令执行成功");
|
|
|
|
|
|
if (resultDetail)
|
|
|
|
|
|
*resultDetail = detail;
|
|
|
|
|
|
emit commandFinished(command, success, detail);
|
|
|
|
|
|
return success;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void finish(const QString &command, const grpc::Status &status, bool responseSuccess,
|
|
|
|
|
|
const QString &responseError)
|
|
|
|
|
|
{
|
|
|
|
|
|
const bool success = status.ok() && responseSuccess;
|
|
|
|
|
|
QString detail;
|
|
|
|
|
|
if (!status.ok()) {
|
|
|
|
|
|
const QString message = QString::fromStdString(status.error_message());
|
|
|
|
|
|
detail = QStringLiteral("gRPC code %1:%2")
|
|
|
|
|
|
.arg(static_cast<int>(status.error_code()))
|
|
|
|
|
|
.arg(message.isEmpty() ? QStringLiteral("服务端未返回错误详情")
|
|
|
|
|
|
: message);
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (!responseSuccess)
|
|
|
|
|
|
detail = responseError.isEmpty() ? QStringLiteral("设备拒绝了命令") : responseError;
|
|
|
|
|
|
else
|
|
|
|
|
|
detail = QStringLiteral("命令执行成功");
|
|
|
|
|
|
emit commandFinished(command, success, detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void pollGrpc()
|
|
|
|
|
|
{
|
|
|
|
|
|
++m_tick;
|
2026-09-23 16:04:01 +08:00
|
|
|
|
const bool armPollDue = m_consecutivePollErrors < 3 || m_tick % 10 == 0;
|
|
|
|
|
|
if (m_armPollingEnabled && !m_armDeviceId.isEmpty() && armPollDue) {
|
2026-09-23 11:11:49 +08:00
|
|
|
|
const QString polledDeviceId = m_armDeviceId;
|
2026-10-26 17:35:27 +08:00
|
|
|
|
if (m_jointTelemetryOnly) {
|
|
|
|
|
|
pollLegacyArmTelemetry(polledDeviceId);
|
|
|
|
|
|
} else {
|
2026-09-23 11:11:49 +08:00
|
|
|
|
cmvr::api::GetRobotState::Request request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), polledDeviceId);
|
|
|
|
|
|
cmvr::api::GetRobotState::Response response;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 350);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
const grpc::Status status = m_arm->getRobotState(&context, request, &response);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (status.ok() && response.header().success()) {
|
2026-09-23 16:04:01 +08:00
|
|
|
|
const bool recovered = m_consecutivePollErrors >= 3;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_consecutivePollErrors = 0;
|
|
|
|
|
|
QVariantList joints;
|
2026-09-23 11:11:49 +08:00
|
|
|
|
const auto &robotState = response.state();
|
|
|
|
|
|
const auto &jointState = robotState.actual_joint_state();
|
2026-10-14 17:15:46 +08:00
|
|
|
|
// Position order is the controller's joint command order. Some
|
|
|
|
|
|
// services omit names; retain the real array and use ordinal
|
|
|
|
|
|
// display labels instead of silently returning zero joints.
|
|
|
|
|
|
QStringList reportedNames;
|
|
|
|
|
|
bool completeNames = jointState.name_size() == jointState.position_size();
|
|
|
|
|
|
for (const auto &name : jointState.name()) {
|
|
|
|
|
|
const QString label = QString::fromStdString(name).trimmed();
|
|
|
|
|
|
if (label.isEmpty() || reportedNames.contains(label)) completeNames = false;
|
|
|
|
|
|
reportedNames.append(label);
|
|
|
|
|
|
}
|
|
|
|
|
|
for (int i = 0; i < jointState.position_size(); ++i) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QVariantMap joint;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
joint.insert(QStringLiteral("name"), completeNames
|
|
|
|
|
|
? reportedNames.at(i) : QStringLiteral("J%1").arg(i + 1));
|
|
|
|
|
|
joint.insert(QStringLiteral("position"), jointState.position(i));
|
2026-09-23 11:11:49 +08:00
|
|
|
|
joint.insert(QStringLiteral("velocity"), i < jointState.velocity_size() ? jointState.velocity(i) : 0.0);
|
|
|
|
|
|
joint.insert(QStringLiteral("effort"), i < jointState.effort_size() ? jointState.effort(i) : 0.0);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
if (i < jointState.current_size())
|
|
|
|
|
|
joint.insert(QStringLiteral("current"), jointState.current(i));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
joints.append(joint);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
const auto &tcp = robotState.actual_tcp_pose();
|
|
|
|
|
|
QVariantMap pose;
|
|
|
|
|
|
pose.insert(QStringLiteral("x"), tcp.x());
|
|
|
|
|
|
pose.insert(QStringLiteral("y"), tcp.y());
|
|
|
|
|
|
pose.insert(QStringLiteral("z"), tcp.z());
|
|
|
|
|
|
pose.insert(QStringLiteral("rx"), tcp.rx());
|
|
|
|
|
|
pose.insert(QStringLiteral("ry"), tcp.ry());
|
|
|
|
|
|
pose.insert(QStringLiteral("rz"), tcp.rz());
|
2026-10-14 17:15:46 +08:00
|
|
|
|
const QVariantMap activeTcpPose = pose;
|
2026-09-23 16:04:01 +08:00
|
|
|
|
if (robotState.connected()
|
|
|
|
|
|
&& !m_armBaseFrame.isEmpty() && !m_armTcpFrame.isEmpty()) {
|
2026-09-23 11:11:49 +08:00
|
|
|
|
cmvr::api::GetPose::Request poseRequest;
|
|
|
|
|
|
fillHeader(poseRequest.mutable_header(), polledDeviceId);
|
|
|
|
|
|
poseRequest.set_base_link(m_armBaseFrame.toStdString());
|
|
|
|
|
|
poseRequest.set_ee_link(m_armTcpFrame.toStdString());
|
|
|
|
|
|
cmvr::api::GetPose::Response poseResponse;
|
|
|
|
|
|
grpc::ClientContext poseContext;
|
|
|
|
|
|
setDeadline(poseContext, 250);
|
|
|
|
|
|
const grpc::Status poseStatus =
|
|
|
|
|
|
m_arm->getPose(&poseContext, poseRequest, &poseResponse);
|
|
|
|
|
|
if (poseStatus.ok() && poseResponse.header().success()) {
|
|
|
|
|
|
const auto &selectedPose = poseResponse.pose();
|
|
|
|
|
|
pose.insert(QStringLiteral("x"), selectedPose.x());
|
|
|
|
|
|
pose.insert(QStringLiteral("y"), selectedPose.y());
|
|
|
|
|
|
pose.insert(QStringLiteral("z"), selectedPose.z());
|
|
|
|
|
|
pose.insert(QStringLiteral("rx"), selectedPose.rx());
|
|
|
|
|
|
pose.insert(QStringLiteral("ry"), selectedPose.ry());
|
|
|
|
|
|
pose.insert(QStringLiteral("rz"), selectedPose.rz());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
QVariantMap state;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
state.insert(QStringLiteral("activeTcpPose"), activeTcpPose);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
state.insert(QStringLiteral("robotMode"), static_cast<int>(robotState.robot_mode()));
|
|
|
|
|
|
state.insert(QStringLiteral("safetyMode"), static_cast<int>(robotState.safety_mode()));
|
|
|
|
|
|
state.insert(QStringLiteral("controlMode"), static_cast<int>(robotState.control_mode()));
|
2026-09-23 16:04:01 +08:00
|
|
|
|
state.insert(QStringLiteral("freedrive"),
|
|
|
|
|
|
robotState.control_mode()
|
|
|
|
|
|
== cmvr::api::ARM_CONTROL_MODE_FREEDRIVE);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
state.insert(QStringLiteral("connected"), robotState.connected());
|
|
|
|
|
|
state.insert(QStringLiteral("poweredOn"), robotState.powered_on());
|
|
|
|
|
|
state.insert(QStringLiteral("brakeReleased"), robotState.brake_released());
|
|
|
|
|
|
state.insert(QStringLiteral("moving"), robotState.moving());
|
|
|
|
|
|
state.insert(QStringLiteral("fault"), robotState.fault());
|
|
|
|
|
|
state.insert(QStringLiteral("protectiveStopped"), robotState.protective_stopped());
|
|
|
|
|
|
state.insert(QStringLiteral("emergencyStopped"), robotState.emergency_stopped());
|
|
|
|
|
|
state.insert(QStringLiteral("speedScaling"), robotState.speed_scaling());
|
|
|
|
|
|
emit telemetryReceived(polledDeviceId, joints, pose, state);
|
2026-09-23 16:04:01 +08:00
|
|
|
|
if (recovered) {
|
|
|
|
|
|
emit armTelemetryHealthChanged(
|
|
|
|
|
|
polledDeviceId, true, QStringLiteral("机械臂遥测通信已恢复"));
|
|
|
|
|
|
}
|
2026-10-26 17:35:27 +08:00
|
|
|
|
} else if (status.error_code() == grpc::StatusCode::UNIMPLEMENTED) {
|
|
|
|
|
|
m_jointTelemetryOnly = true;
|
|
|
|
|
|
pollLegacyArmTelemetry(polledDeviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
++m_consecutivePollErrors;
|
2026-09-23 16:04:01 +08:00
|
|
|
|
QString detail;
|
|
|
|
|
|
if (!status.ok()) {
|
|
|
|
|
|
const QString message = QString::fromStdString(status.error_message());
|
|
|
|
|
|
detail = QStringLiteral("gRPC code %1:%2")
|
|
|
|
|
|
.arg(static_cast<int>(status.error_code()))
|
|
|
|
|
|
.arg(message.isEmpty()
|
|
|
|
|
|
? QStringLiteral("服务端未返回错误详情")
|
|
|
|
|
|
: message);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
detail = QString::fromStdString(response.header().error_message());
|
|
|
|
|
|
if (detail.isEmpty())
|
|
|
|
|
|
detail = QStringLiteral("边缘端未返回机械臂状态");
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_consecutivePollErrors == 3)
|
|
|
|
|
|
emit armTelemetryHealthChanged(polledDeviceId, false, detail);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
2026-10-26 17:35:27 +08:00
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (m_tick % 10 != 0)
|
|
|
|
|
|
return;
|
|
|
|
|
|
cmvr::api::GetSystemStatusCommand::Request statusRequest;
|
|
|
|
|
|
cmvr::api::GetSystemStatusCommand::Feedback statusResponse;
|
|
|
|
|
|
grpc::ClientContext statusContext;
|
|
|
|
|
|
setDeadline(statusContext, 500);
|
|
|
|
|
|
const grpc::Status rpcStatus = m_system->GetSystemStatus(&statusContext, statusRequest, &statusResponse);
|
|
|
|
|
|
if (rpcStatus.ok() && statusResponse.header().success()) {
|
|
|
|
|
|
const double memory = statusResponse.mem_total_mb() > 0
|
|
|
|
|
|
? statusResponse.mem_used_mb() * 100.0 / statusResponse.mem_total_mb() : 0.0;
|
|
|
|
|
|
const double disk = statusResponse.disk_total_gb() > 0
|
|
|
|
|
|
? statusResponse.disk_used_gb() * 100.0 / statusResponse.disk_total_gb() : 0.0;
|
|
|
|
|
|
emit systemStatusReceived(statusResponse.cpu_usage(), memory, disk,
|
2026-10-26 17:35:27 +08:00
|
|
|
|
discoverLegacyArms(statusResponse));
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-26 17:35:27 +08:00
|
|
|
|
QVariantList discoverLegacyArms(const cmvr::api::GetSystemStatusCommand::Feedback &response)
|
|
|
|
|
|
{
|
|
|
|
|
|
auto devices = deviceListFromStatus(response);
|
|
|
|
|
|
QSet<QString> present;
|
|
|
|
|
|
for (auto &value : devices) {
|
|
|
|
|
|
auto device = value.toMap();
|
|
|
|
|
|
const QString id = device.value(QStringLiteral("deviceId")).toString();
|
|
|
|
|
|
present.insert(id);
|
|
|
|
|
|
// Older servers default unknown drivers to enum zero (AGV). Probe
|
|
|
|
|
|
// only ambiguous entries, never override explicit device metadata.
|
|
|
|
|
|
if (device.value(QStringLiteral("type")).toInt() != cmvr::api::AGV
|
|
|
|
|
|
|| device.value(QStringLiteral("deviceKind")).toInt() != cmvr::api::DEVICE_KIND_UNKNOWN
|
|
|
|
|
|
|| !device.value(QStringLiteral("driverType")).toString().isEmpty())
|
|
|
|
|
|
continue;
|
|
|
|
|
|
if (!m_legacyArmDiscovery.contains(id)) {
|
|
|
|
|
|
cmvr::api::JointRequest request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), id);
|
|
|
|
|
|
cmvr::api::JointResponse joints;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 350);
|
|
|
|
|
|
const auto status = m_arm->getJointState(&context, request, &joints);
|
|
|
|
|
|
QStringList names;
|
|
|
|
|
|
if (status.ok() && joints.header().success()
|
|
|
|
|
|
&& confirmedJointNames(joints.state(), names))
|
|
|
|
|
|
m_legacyArmDiscovery.insert(id, true);
|
|
|
|
|
|
else if (status.error_code() == grpc::StatusCode::NOT_FOUND
|
|
|
|
|
|
|| status.error_code() == grpc::StatusCode::UNIMPLEMENTED)
|
|
|
|
|
|
m_legacyArmDiscovery.insert(id, false);
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_legacyArmDiscovery.value(id, false)) {
|
|
|
|
|
|
device.insert(QStringLiteral("type"), int(cmvr::api::Robot));
|
|
|
|
|
|
device.insert(QStringLiteral("typeName"), QStringLiteral("Robot"));
|
|
|
|
|
|
device.insert(QStringLiteral("deviceKind"), int(cmvr::api::DEVICE_KIND_ARM));
|
|
|
|
|
|
device.insert(QStringLiteral("deviceKindName"), QStringLiteral("DEVICE_KIND_ARM"));
|
|
|
|
|
|
device.insert(QStringLiteral("identitySource"), QStringLiteral("ArmService.getJointState"));
|
|
|
|
|
|
value = device;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
for (auto it = m_legacyArmDiscovery.begin(); it != m_legacyArmDiscovery.end(); ) {
|
|
|
|
|
|
if (!present.contains(it.key())) it = m_legacyArmDiscovery.erase(it);
|
|
|
|
|
|
else ++it;
|
|
|
|
|
|
}
|
|
|
|
|
|
return devices;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void pollLegacyArmTelemetry(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
cmvr::api::JointRequest request;
|
|
|
|
|
|
fillHeader(request.mutable_header(), deviceId);
|
|
|
|
|
|
cmvr::api::JointResponse response;
|
|
|
|
|
|
grpc::ClientContext context;
|
|
|
|
|
|
setDeadline(context, 350);
|
|
|
|
|
|
const auto status = m_arm->getJointState(&context, request, &response);
|
|
|
|
|
|
QStringList names;
|
|
|
|
|
|
if (!status.ok() || !response.header().success()
|
|
|
|
|
|
|| !confirmedJointNames(response.state(), names)) {
|
|
|
|
|
|
if (++m_consecutivePollErrors == 3)
|
|
|
|
|
|
emit armTelemetryHealthChanged(deviceId, false,
|
|
|
|
|
|
!status.ok() ? QString::fromStdString(status.error_message())
|
|
|
|
|
|
: QStringLiteral("服务端未返回有效关节数据"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const bool recovered = m_consecutivePollErrors >= 3;
|
|
|
|
|
|
m_consecutivePollErrors = 0;
|
|
|
|
|
|
QVariantList joints;
|
|
|
|
|
|
const auto &values = response.state();
|
|
|
|
|
|
for (int i = 0; i < names.size(); ++i) {
|
|
|
|
|
|
QVariantMap joint{{QStringLiteral("name"), names.at(i)},
|
|
|
|
|
|
{QStringLiteral("position"), values.position(i)}};
|
|
|
|
|
|
if (i < values.velocity_size()) joint.insert(QStringLiteral("velocity"), values.velocity(i));
|
|
|
|
|
|
if (i < values.effort_size()) joint.insert(QStringLiteral("effort"), values.effort(i));
|
|
|
|
|
|
if (i < values.current_size()) joint.insert(QStringLiteral("current"), values.current(i));
|
|
|
|
|
|
joints.append(joint);
|
|
|
|
|
|
}
|
|
|
|
|
|
emit telemetryReceived(deviceId, joints, {},
|
|
|
|
|
|
{{QStringLiteral("robotStateAvailable"), false},
|
|
|
|
|
|
{QStringLiteral("source"), QStringLiteral("getJointState")}});
|
|
|
|
|
|
if (recovered) emit armTelemetryHealthChanged(deviceId, true, QStringLiteral("关节遥测通信已恢复"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::shared_ptr<grpc::Channel> m_channel;
|
|
|
|
|
|
std::shared_ptr<grpc::Channel> m_configChannel;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::ArmService::Stub> m_arm;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::CameraService::Stub> m_camera;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::unique_ptr<cmvr::api::DexHandService::Stub> m_dexHand;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::unique_ptr<cmvr::api::SystemService::Stub> m_system;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::AgvService::Stub> m_agv;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::MicPhoneService::Stub> m_microphone;
|
|
|
|
|
|
std::unique_ptr<grpc::GenericStub> m_generic;
|
|
|
|
|
|
std::unique_ptr<cmvr::api::ConfigurationService::Stub> m_configuration;
|
2026-10-26 17:35:27 +08:00
|
|
|
|
bool m_jointTelemetryOnly = false;
|
|
|
|
|
|
QHash<QString, bool> m_legacyArmDiscovery;
|
|
|
|
|
|
QHash<QString, QPair<QString, QString>> m_armFrameDefaults;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
grpc::ClientContext *m_speakerStreamContext = nullptr;
|
|
|
|
|
|
std::mutex m_speakerContextMutex;
|
|
|
|
|
|
grpc::ClientContext *m_microphoneStreamContext = nullptr;
|
|
|
|
|
|
std::mutex m_microphoneContextMutex;
|
|
|
|
|
|
grpc::ClientContext *m_agvMapStreamContext = nullptr;
|
|
|
|
|
|
std::mutex m_agvMapStreamContextMutex;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
grpc::ClientContext *m_dexHandTactileContext = nullptr;
|
|
|
|
|
|
std::mutex m_dexHandTactileContextMutex;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
|
|
struct SpeakerAudioFrame {
|
|
|
|
|
|
QByteArray data;
|
|
|
|
|
|
int sampleRate = 0;
|
|
|
|
|
|
int channels = 0;
|
|
|
|
|
|
qint64 pts = 0;
|
|
|
|
|
|
int samples = 0;
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
QTimer *m_pollTimer = nullptr;
|
|
|
|
|
|
QString m_host;
|
|
|
|
|
|
QString m_armDeviceId;
|
2026-09-23 11:11:49 +08:00
|
|
|
|
QString m_armBaseFrame;
|
|
|
|
|
|
QString m_armTcpFrame;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
int m_port = 50052;
|
|
|
|
|
|
int m_tick = 0;
|
|
|
|
|
|
int m_consecutivePollErrors = 0;
|
2026-10-16 09:39:44 +08:00
|
|
|
|
int m_channelFailureTicks = 0;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
bool m_connected = false;
|
|
|
|
|
|
bool m_configConnected = false;
|
|
|
|
|
|
bool m_demoMode = true;
|
|
|
|
|
|
bool m_armPollingEnabled = false;
|
|
|
|
|
|
std::shared_ptr<ArmMotionSession> m_armMotionSession;
|
|
|
|
|
|
std::mutex m_armMotionSessionMutex;
|
|
|
|
|
|
QHash<QString, std::shared_ptr<CameraStreamSession>> m_cameraSessions;
|
|
|
|
|
|
std::mutex m_cameraSessionsMutex;
|
|
|
|
|
|
QString m_defaultCameraCodec = QStringLiteral("h264");
|
|
|
|
|
|
bool m_cameraRecording = false;
|
|
|
|
|
|
std::atomic<bool> m_speakerStreamRunning{false};
|
|
|
|
|
|
std::atomic<bool> m_speakerStreamStop{false};
|
|
|
|
|
|
std::atomic<quint64> m_speakerFrames{0};
|
|
|
|
|
|
std::atomic<quint64> m_speakerBytes{0};
|
|
|
|
|
|
std::thread m_speakerStreamThread;
|
|
|
|
|
|
std::deque<SpeakerAudioFrame> m_speakerQueue;
|
|
|
|
|
|
int m_speakerQueueBytes = 0;
|
|
|
|
|
|
std::mutex m_speakerQueueMutex;
|
|
|
|
|
|
std::condition_variable m_speakerQueueCondition;
|
|
|
|
|
|
std::atomic<bool> m_microphoneStreamRunning{false};
|
|
|
|
|
|
std::atomic<bool> m_microphoneStreamStop{false};
|
|
|
|
|
|
std::atomic<quint64> m_microphoneFrames{0};
|
|
|
|
|
|
std::atomic<quint64> m_microphoneBytes{0};
|
|
|
|
|
|
std::thread m_microphoneStreamThread;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
std::atomic<bool> m_dexHandTactileRunning{false};
|
|
|
|
|
|
std::atomic<bool> m_dexHandTactileStop{false};
|
|
|
|
|
|
std::thread m_dexHandTactileThread;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
std::atomic<bool> m_agvMapStreamRunning{false};
|
|
|
|
|
|
std::atomic<bool> m_agvMapStreamStop{false};
|
|
|
|
|
|
std::thread m_agvMapStreamThread;
|
2026-11-10 16:10:46 +08:00
|
|
|
|
QVariantMap m_agvMapStreamSourceContext;
|
|
|
|
|
|
QHash<QString, QString> m_demoAgvMapContents;
|
|
|
|
|
|
QHash<QString, QString> m_demoAgvCurrentMaps;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QVector<double> m_demoTargets;
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
RobotClient::RobotClient(QObject *parent)
|
|
|
|
|
|
: QObject(parent), m_worker(new BackendWorker)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_agvMapDirectWorker = new QObject;
|
|
|
|
|
|
m_agvMapDirectWorker->moveToThread(&m_agvMapDirectThread);
|
|
|
|
|
|
connect(&m_agvMapDirectThread, &QThread::finished,
|
|
|
|
|
|
m_agvMapDirectWorker, &QObject::deleteLater);
|
|
|
|
|
|
m_agvMapDirectThread.start();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
qRegisterMetaType<QImage>("QImage");
|
|
|
|
|
|
qRegisterMetaType<VideoFrame>("VideoFrame");
|
|
|
|
|
|
|
|
|
|
|
|
m_worker->connectionChanged = [this](bool connected, int latencyMs, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, connected, latencyMs, detail]() {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (!connected)
|
|
|
|
|
|
interruptAgvManualVelocity();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit connectionChanged(connected, latencyMs, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-23 11:11:49 +08:00
|
|
|
|
m_worker->armInfoReceived = [this](const QString &deviceId, const QVariantMap &info) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, deviceId, info]() {
|
|
|
|
|
|
emit armInfoReceived(deviceId, info);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-23 11:11:49 +08:00
|
|
|
|
m_worker->armFramesReceived =
|
|
|
|
|
|
[this](const QString &deviceId, const QStringList &baseFrames,
|
|
|
|
|
|
const QStringList &tcpFrames) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, deviceId, baseFrames, tcpFrames]() {
|
|
|
|
|
|
emit armFramesReceived(deviceId, baseFrames, tcpFrames);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-14 17:15:46 +08:00
|
|
|
|
m_worker->controllerTcpOffsetReceived =
|
|
|
|
|
|
[this](quint64 requestId, const QString &deviceId, const QVariantMap &offset,
|
|
|
|
|
|
bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, requestId, deviceId, offset, success, detail] {
|
|
|
|
|
|
emit controllerTcpOffsetReceived(requestId, deviceId, offset, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->tcpCalibrationPoseReceived =
|
|
|
|
|
|
[this](quint64 requestId, const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
const QVariantMap &state, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, requestId, deviceId, pose, state, success, detail]() {
|
|
|
|
|
|
emit tcpCalibrationPoseReceived(requestId, deviceId, pose, state,
|
|
|
|
|
|
success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-23 11:11:49 +08:00
|
|
|
|
m_worker->telemetryReceived = [this](const QString &deviceId,
|
|
|
|
|
|
const QVariantList &joints,
|
|
|
|
|
|
const QVariantMap &pose,
|
|
|
|
|
|
const QVariantMap &state) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, deviceId, joints, pose, state]() {
|
|
|
|
|
|
emit telemetryReceived(deviceId, joints, pose, state);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-23 16:04:01 +08:00
|
|
|
|
m_worker->armTelemetryHealthChanged =
|
|
|
|
|
|
[this](const QString &deviceId, bool available, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, deviceId, available, detail]() {
|
|
|
|
|
|
emit armTelemetryHealthChanged(deviceId, available, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-23 11:11:49 +08:00
|
|
|
|
m_worker->systemStatusReceived = [this](double cpu, double memory, double disk,
|
|
|
|
|
|
const QVariantList &devices) {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
QMetaObject::invokeMethod(this, [this, cpu, memory, disk, devices]() {
|
|
|
|
|
|
emit systemStatusReceived(cpu, memory, disk, devices);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->systemInfoReceived = [this](const QVariantMap &info) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, info]() {
|
|
|
|
|
|
emit systemInfoReceived(info);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->imageReceived = [this](const QImage &image, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, image, detail]() {
|
|
|
|
|
|
emit imageReceived(image, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-14 17:15:46 +08:00
|
|
|
|
m_worker->cameraCapabilitiesReceived=[this](quint64 token,const QString& camera,const QVariantMap& c,bool ok,const QString& detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,[this,token,camera,c,ok,detail] { emit cameraCapabilitiesReceived(token,camera,c,ok,detail); },Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->handEyeImageReceived =
|
|
|
|
|
|
[this](quint64 token, const QString &cameraId, const QImage &image,
|
|
|
|
|
|
const QVariantMap &intrinsics, const QVariantMap &metadata,
|
|
|
|
|
|
bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, token, cameraId, image, intrinsics, metadata, success, detail]() {
|
|
|
|
|
|
emit handEyeImageReceived(token, cameraId, image, intrinsics,
|
|
|
|
|
|
metadata, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->touchRgbdImageReceived =
|
|
|
|
|
|
[this](quint64 token,const QString &camera,const QImage &image,const QVariantMap &intrinsics,
|
|
|
|
|
|
const QVariantMap &metadata,bool success,const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,[this,token,camera,image,intrinsics,metadata,success,detail] {
|
|
|
|
|
|
emit touchRgbdImageReceived(token,camera,image,intrinsics,metadata,success,detail);
|
|
|
|
|
|
},Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->cameraStatusReceived = [this](const QString &cameraId,
|
|
|
|
|
|
const QVariantMap &state) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, cameraId, state]() {
|
|
|
|
|
|
emit cameraStatusReceived(cameraId, state);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->dexHandStatusReceived =
|
|
|
|
|
|
[this](const QString &deviceId, bool initialized, bool hasTactileFeedback,
|
|
|
|
|
|
const QString &model,
|
|
|
|
|
|
const QVariantList &freedoms) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, deviceId, initialized,
|
|
|
|
|
|
hasTactileFeedback, model, freedoms]() {
|
|
|
|
|
|
emit dexHandStatusReceived(deviceId, initialized,
|
|
|
|
|
|
hasTactileFeedback, model, freedoms);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->dexHandTactileReceived =
|
|
|
|
|
|
[this](const QString &deviceId, int rows, int cols,
|
|
|
|
|
|
const QVariantList &values, quint64 frameCount) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, deviceId, rows, cols, values, frameCount]() {
|
|
|
|
|
|
emit dexHandTactileReceived(deviceId, rows, cols, values, frameCount);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->dexHandTactileStreamStateChanged =
|
|
|
|
|
|
[this](bool running, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, running, detail]() {
|
|
|
|
|
|
emit dexHandTactileStreamStateChanged(running, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-18 16:22:20 +08:00
|
|
|
|
const auto queueVideoFrame = [this](const QString &cameraId,
|
|
|
|
|
|
const VideoFrame &frame,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
{
|
|
|
|
|
|
QMutexLocker locker(&m_videoFrameMutex);
|
|
|
|
|
|
PendingVideoFrame &pending = m_pendingVideoFrames[cameraId];
|
|
|
|
|
|
pending.frame = frame;
|
|
|
|
|
|
pending.detail = detail;
|
|
|
|
|
|
if (m_videoFrameDeliveryScheduled.contains(cameraId))
|
|
|
|
|
|
return;
|
|
|
|
|
|
m_videoFrameDeliveryScheduled.insert(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, cameraId]() {
|
|
|
|
|
|
PendingVideoFrame pending;
|
|
|
|
|
|
{
|
|
|
|
|
|
QMutexLocker locker(&m_videoFrameMutex);
|
|
|
|
|
|
pending = m_pendingVideoFrames.take(cameraId);
|
|
|
|
|
|
m_videoFrameDeliveryScheduled.remove(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
emit videoFrameReceived(cameraId, pending.frame, pending.detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->videoFrameReceivedForCamera = queueVideoFrame;
|
|
|
|
|
|
const auto queueCameraState = [this](const QString &cameraId, bool running,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, cameraId, running, detail]() {
|
|
|
|
|
|
emit cameraStreamStateChanged(cameraId, running, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->cameraStreamStateChangedForCamera = queueCameraState;
|
|
|
|
|
|
m_worker->cameraRecordingStateChanged = [this](bool recording, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, recording, detail]() {
|
|
|
|
|
|
emit cameraRecordingStateChanged(recording, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->agvStateReceived = [this](const QVariantMap &state, const QVariantMap &navigation) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, state, navigation]() {
|
|
|
|
|
|
emit agvStateReceived(state, navigation);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_worker->agvInventoryReceived = [this](const QVariantMap &context,
|
|
|
|
|
|
const QStringList &maps, const QVariantList &stations) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, context, maps, stations]() {
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvInventoryReceived(maps, stations);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvInventoryReceivedForContext(context, maps, stations);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_worker->agvMapContentReceived =
|
|
|
|
|
|
[this](quint64 requestId, const QString &deviceId, const QString &mapName,
|
|
|
|
|
|
const QString &content, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(
|
|
|
|
|
|
this, [this, requestId, deviceId, mapName, content, success, detail]() {
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName, content, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->agvMapSaveFinished =
|
|
|
|
|
|
[this](quint64 requestId, const QString &deviceId, const QString &mapName,
|
|
|
|
|
|
bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(
|
|
|
|
|
|
this, [this, requestId, deviceId, mapName, success, detail]() {
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-14 17:15:46 +08:00
|
|
|
|
m_worker->agvMapFrameReceived = [this](const QImage &image,
|
|
|
|
|
|
const QVariantMap &metadata,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, image, metadata, detail]() {
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if (metadata.value(QStringLiteral("streamGeneration")).toULongLong()
|
|
|
|
|
|
!= agvMapStreamGeneration())
|
|
|
|
|
|
return;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit agvMapFrameReceived(image, metadata, detail);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-11-10 16:10:46 +08:00
|
|
|
|
m_worker->agvMapStreamStateChanged = [this](const QVariantMap &context, bool running, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, context, running, detail]() {
|
|
|
|
|
|
if (context.value(QStringLiteral("streamGeneration")).toULongLong()
|
|
|
|
|
|
!= agvMapStreamGeneration())
|
|
|
|
|
|
return;
|
|
|
|
|
|
emit agvMapStreamStateChangedForContext(context, running, detail);
|
|
|
|
|
|
// A contextual receiver may restart the stream synchronously.
|
|
|
|
|
|
if (context.value(QStringLiteral("streamGeneration")).toULongLong()
|
|
|
|
|
|
!= agvMapStreamGeneration())
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvMapStreamStateChanged(running, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->rpcFinished = [this](const QString &serviceName, const QString &methodName,
|
|
|
|
|
|
bool success, const QString &responseJson) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, serviceName, methodName, success, responseJson]() {
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, success, responseJson);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->audioStreamStateChanged = [this](const QString &serviceName, bool running,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, serviceName, running, detail]() {
|
|
|
|
|
|
emit audioStreamStateChanged(serviceName, running, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->audioStreamStatistics = [this](const QString &serviceName, quint64 frames,
|
|
|
|
|
|
quint64 bytes, qint64 durationMs) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, serviceName, frames, bytes, durationMs]() {
|
|
|
|
|
|
emit audioStreamStatistics(serviceName, frames, bytes, durationMs);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->audioFrameReceived = [this](const QByteArray &data, int sampleRate, int channels,
|
|
|
|
|
|
int format, const QString &codec,
|
|
|
|
|
|
qint64 pts, int samples) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, data, sampleRate, channels, format, codec, pts, samples]() {
|
|
|
|
|
|
emit audioFrameReceived(data, sampleRate, channels, format, codec, pts, samples);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->configurationConnectionChanged = [this](bool connected, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, connected, detail]() {
|
|
|
|
|
|
emit configurationConnectionChanged(connected, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->configurationFilesReceived =
|
|
|
|
|
|
[this](const QString &root, const QVariantList &files, bool success,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, root, files, success, detail]() {
|
|
|
|
|
|
emit configurationFilesReceived(root, files, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->configurationFileReceived =
|
|
|
|
|
|
[this](const QString &path, const QString &content, const QString &revision,
|
|
|
|
|
|
const QString &messageType, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(
|
|
|
|
|
|
this, [this, path, content, revision, messageType, success, detail]() {
|
|
|
|
|
|
emit configurationFileReceived(path, content, revision, messageType,
|
|
|
|
|
|
success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->configurationValidationFinished =
|
|
|
|
|
|
[this](const QString &path, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, path, success, detail]() {
|
|
|
|
|
|
emit configurationValidationFinished(path, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->configurationSaveFinished =
|
|
|
|
|
|
[this](const QString &path, const QString &revision, bool success,
|
|
|
|
|
|
const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, path, revision, success, detail]() {
|
|
|
|
|
|
emit configurationSaveFinished(path, revision, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->commandFinished = [this](const QString &command, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, command, success, detail]() {
|
|
|
|
|
|
emit commandFinished(command, success, detail);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-20 16:49:27 +08:00
|
|
|
|
m_worker->jointPointCaptured = [this](quint64 token, const QVariantList &targets, bool ok, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [=] { emit jointPointCaptured(token, targets, ok, detail); }, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
m_worker->jointPointMoveFinished = [this](quint64 token, bool ok, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [=] { emit jointPointMoveFinished(token, ok, detail); }, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-29 11:46:39 +08:00
|
|
|
|
m_worker->recordedTrajectoriesReceived = [this](const QString &id, const QVariantList &files,
|
|
|
|
|
|
const QVariantMap &state, bool success, const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [=] { emit recordedTrajectoriesReceived(id, files, state, success, detail); },
|
|
|
|
|
|
Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-10-20 16:49:27 +08:00
|
|
|
|
m_worker->motorRpcFinished=[this](quint64 token,const QString &method,bool ok,const QVariantMap &response,const QString &detail) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this,[=] { emit motorRpcFinished(token,method,ok,response,detail); },Qt::QueuedConnection);
|
|
|
|
|
|
};
|
2026-09-18 16:22:20 +08:00
|
|
|
|
m_worker->logMessage = [this](const QString &level, const QString &message) {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, level, message]() {
|
|
|
|
|
|
emit logMessage(level, message);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
m_worker->moveToThread(&m_thread);
|
|
|
|
|
|
|
|
|
|
|
|
connect(this, &RobotClient::connectRequested, m_worker, &BackendWorker::connectToServer);
|
|
|
|
|
|
connect(this, &RobotClient::disconnectRequested, m_worker, &BackendWorker::disconnectFromServer);
|
|
|
|
|
|
connect(this, &RobotClient::armTelemetryRequested, m_worker, &BackendWorker::setArmTelemetry);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
connect(this, &RobotClient::armInfoRequested, m_worker, &BackendWorker::getArmInfo);
|
2026-11-04 15:00:14 +08:00
|
|
|
|
connect(this, &RobotClient::userCoordinatesRequested, m_worker, &BackendWorker::userCoordinates);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
connect(this, &RobotClient::tcpCalibrationPoseRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::getTcpCalibrationPose);
|
|
|
|
|
|
connect(this, &RobotClient::controllerTcpOffsetRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::getControllerTcpOffset);
|
|
|
|
|
|
connect(this, &RobotClient::tcpJogMoveRequested, m_worker, &BackendWorker::tcpJogMove);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
connect(this, &RobotClient::armFramesRequested, m_worker, &BackendWorker::getArmFrames);
|
2026-10-29 11:46:39 +08:00
|
|
|
|
connect(this, &RobotClient::armFrameDiscoveryRequested, m_worker, &BackendWorker::discoverArmFrames);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
connect(this, &RobotClient::armTelemetryFramesRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::setArmTelemetryFrames);
|
|
|
|
|
|
connect(this, &RobotClient::speedJRequested, m_worker, &BackendWorker::speedJ);
|
|
|
|
|
|
connect(this, &RobotClient::speedLRequested, m_worker, &BackendWorker::speedL);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::moveJRequested, m_worker, &BackendWorker::moveJ);
|
2026-10-20 16:49:27 +08:00
|
|
|
|
connect(this,&RobotClient::motorRpcRequested,m_worker,&BackendWorker::motorRpc);
|
|
|
|
|
|
connect(this, &RobotClient::jointPointCaptureRequested, m_worker, &BackendWorker::captureJointPoint);
|
|
|
|
|
|
connect(this, &RobotClient::jointPointMoveRequested, m_worker, &BackendWorker::moveJointPoint);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::moveJPoseRequested, m_worker, &BackendWorker::moveJPose);
|
|
|
|
|
|
connect(this, &RobotClient::torqueRequested, m_worker, &BackendWorker::torque);
|
|
|
|
|
|
connect(this, &RobotClient::armStopRequested, m_worker, &BackendWorker::armStop);
|
|
|
|
|
|
connect(this, &RobotClient::armClearFaultRequested, m_worker, &BackendWorker::armClearFault);
|
|
|
|
|
|
connect(this, &RobotClient::armCalibrateZeroRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::armCalibrateZero);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
connect(this, &RobotClient::enterTeachingModeRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::enterTeachingMode);
|
|
|
|
|
|
connect(this, &RobotClient::startTrajectoryRecordingRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startTrajectoryRecording);
|
2026-10-29 11:46:39 +08:00
|
|
|
|
connect(this, &RobotClient::recordedTrajectoriesRequested, m_worker, &BackendWorker::recordedTrajectories);
|
|
|
|
|
|
connect(this, &RobotClient::replayTrajectoryRequested, m_worker, &BackendWorker::replayTrajectory);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
connect(this, &RobotClient::completeTeachingRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::completeTeaching);
|
|
|
|
|
|
connect(this, &RobotClient::stopTrajectoryRecordingRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopTrajectoryRecording);
|
|
|
|
|
|
connect(this, &RobotClient::exitTeachingModeRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::exitTeachingMode);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::snapshotRequested, m_worker, &BackendWorker::snapshot);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
connect(this, &RobotClient::handEyeImageRequested, m_worker, [this](const QString& camera,quint64 token) { m_worker->getHandEyeImage(camera,token); });
|
|
|
|
|
|
connect(this,&RobotClient::cameraCapabilitiesRequested,m_worker,&BackendWorker::getCameraCapabilities);
|
|
|
|
|
|
connect(this,&RobotClient::touchImageRequested,m_worker,[this](const QString& camera,quint64 token) { m_worker->getHandEyeImage(camera,token,true); });
|
|
|
|
|
|
connect(this, &RobotClient::touchRgbdImageRequested, m_worker, &BackendWorker::getTouchRgbdImage);
|
|
|
|
|
|
connect(this, &RobotClient::depthSnapshotRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::depthSnapshot);
|
|
|
|
|
|
connect(this, &RobotClient::cameraStatusRequested, m_worker, &BackendWorker::getCameraStatus);
|
|
|
|
|
|
connect(this, &RobotClient::dexHandStatusRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::getDexHandStatus);
|
|
|
|
|
|
connect(this, &RobotClient::dexHandCommandRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::setDexHandValues);
|
|
|
|
|
|
connect(this, &RobotClient::dexHandTactileStreamStartRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startDexHandTactileStream);
|
|
|
|
|
|
connect(this, &RobotClient::dexHandTactileStreamStopRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopDexHandTactileStream);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::cameraStreamStartRequested, m_worker, &BackendWorker::startCameraStream);
|
|
|
|
|
|
connect(this, &RobotClient::cameraStreamCodecRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::setCameraStreamCodec);
|
|
|
|
|
|
connect(this, &RobotClient::cameraStreamStopRequested, m_worker, &BackendWorker::stopCameraStream);
|
|
|
|
|
|
connect(this, &RobotClient::cameraRecordingStartRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startCameraRecording);
|
|
|
|
|
|
connect(this, &RobotClient::cameraRecordingStopRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopCameraRecording);
|
|
|
|
|
|
connect(this, &RobotClient::systemRefreshRequested, m_worker, &BackendWorker::systemRefresh);
|
|
|
|
|
|
connect(this, &RobotClient::systemStopAllRequested, m_worker, &BackendWorker::systemStopAll);
|
|
|
|
|
|
connect(this, &RobotClient::agvRefreshRequested, m_worker, &BackendWorker::agvRefresh);
|
2026-10-14 17:15:46 +08:00
|
|
|
|
connect(this, &RobotClient::agvRelocalizeRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::agvRelocalize);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::agvNavigatePoseRequested, m_worker, &BackendWorker::agvNavigatePose);
|
|
|
|
|
|
connect(this, &RobotClient::agvNavigateStationRequested, m_worker, &BackendWorker::agvNavigateStation);
|
|
|
|
|
|
connect(this, &RobotClient::agvFollowPathRequested, m_worker, &BackendWorker::agvFollowPath);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
connect(this, &RobotClient::agvVelocityRequested, m_worker,
|
|
|
|
|
|
[this](const QString &deviceId, double vx, double vy, double wz) {
|
|
|
|
|
|
m_worker->agvVelocity(deviceId, vx, vy, wz);
|
|
|
|
|
|
});
|
|
|
|
|
|
connect(this, &RobotClient::agvManualVelocityRequested, this,
|
|
|
|
|
|
[this](quint64 requestId, const QString &deviceId, double vx, double vy, double wz) {
|
|
|
|
|
|
if (m_agvManualBusy) {
|
|
|
|
|
|
emit agvManualVelocityFinished(requestId, false,
|
|
|
|
|
|
QStringLiteral("上一条手动速度尚未完成,本次请求未排队"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
m_agvManualBusy = true;
|
|
|
|
|
|
const auto generationState = m_agvManualGeneration;
|
|
|
|
|
|
const quint64 generation = generationState->load();
|
|
|
|
|
|
QElapsedTimer queuedAt;
|
|
|
|
|
|
queuedAt.start();
|
|
|
|
|
|
QMetaObject::invokeMethod(m_worker,
|
|
|
|
|
|
[this, requestId, deviceId, vx, vy, wz, generationState, generation, queuedAt]() {
|
|
|
|
|
|
bool success = false;
|
|
|
|
|
|
QString detail;
|
|
|
|
|
|
// Never read GUI-owned state from this worker. Cancellation
|
|
|
|
|
|
// invalidates a queued packet before its RPC may begin.
|
|
|
|
|
|
if (generationState->load() != generation)
|
|
|
|
|
|
detail = QStringLiteral("手动速度已取消,未下发");
|
|
|
|
|
|
else if (queuedAt.elapsed() > 300)
|
|
|
|
|
|
detail = QStringLiteral("手动速度排队超过 300 ms,已丢弃");
|
|
|
|
|
|
else
|
|
|
|
|
|
success = m_worker->agvVelocity(deviceId, vx, vy, wz, &detail);
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, requestId, generationState, generation, success, detail]() {
|
|
|
|
|
|
// Keep physical single-flight admission locked even
|
|
|
|
|
|
// after cancel until this worker has actually left.
|
|
|
|
|
|
m_agvManualBusy = false;
|
|
|
|
|
|
const bool current = generationState->load() == generation;
|
|
|
|
|
|
emit agvManualVelocityFinished(requestId, current && success,
|
|
|
|
|
|
current ? detail : QStringLiteral(
|
|
|
|
|
|
"手动速度上下文已取消;若已发出,结果不再用于推进速度"));
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
}, Qt::DirectConnection);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::agvActionRequested, m_worker, &BackendWorker::agvAction);
|
|
|
|
|
|
connect(this, &RobotClient::agvInventoryRequested, m_worker, &BackendWorker::agvInventory);
|
|
|
|
|
|
connect(this, &RobotClient::agvSwitchMapRequested, m_worker, &BackendWorker::agvSwitchMap);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
connect(this, &RobotClient::agvMapContentRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::requestAgvMapContent, Qt::QueuedConnection);
|
|
|
|
|
|
connect(this, &RobotClient::agvMapSaveRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::saveAgvMapContent, Qt::QueuedConnection);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
connect(this, &RobotClient::agvMapStreamStartRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startAgvMapStream);
|
|
|
|
|
|
connect(this, &RobotClient::agvMapStreamStopRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopAgvMapStream);
|
|
|
|
|
|
connect(this, &RobotClient::rpcRequested, m_worker, &BackendWorker::invokeRpc);
|
|
|
|
|
|
connect(this, &RobotClient::speakerAudioStreamStartRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startSpeakerAudioStream);
|
|
|
|
|
|
connect(this, &RobotClient::speakerAudioFrameRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::enqueueSpeakerAudioFrame);
|
|
|
|
|
|
connect(this, &RobotClient::speakerAudioStreamStopRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopSpeakerAudioStream);
|
|
|
|
|
|
connect(this, &RobotClient::microphoneAudioStreamStartRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::startMicrophoneAudioStream);
|
|
|
|
|
|
connect(this, &RobotClient::microphoneAudioStreamStopRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::stopMicrophoneAudioStream);
|
|
|
|
|
|
connect(this, &RobotClient::configurationConnectRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::connectConfigurationServer);
|
|
|
|
|
|
connect(this, &RobotClient::configurationDisconnectRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::disconnectConfigurationServer);
|
|
|
|
|
|
connect(this, &RobotClient::configurationFilesRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::listConfigurationFiles);
|
|
|
|
|
|
connect(this, &RobotClient::configurationFileReadRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::readConfigurationFile);
|
|
|
|
|
|
connect(this, &RobotClient::configurationFileValidateRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::validateConfigurationFile);
|
|
|
|
|
|
connect(this, &RobotClient::configurationFileSaveRequested,
|
|
|
|
|
|
m_worker, &BackendWorker::saveConfigurationFile);
|
|
|
|
|
|
|
|
|
|
|
|
connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
|
|
|
|
|
|
m_thread.start();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
RobotClient::~RobotClient()
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
cancelAgvManualVelocity();
|
|
|
|
|
|
cancelAgvMapDirect(false);
|
|
|
|
|
|
m_agvMapDirectThread.quit();
|
|
|
|
|
|
// All network waits are bounded and observe the cancellation token. Join
|
|
|
|
|
|
// before destroying callbacks which still refer to this client.
|
|
|
|
|
|
m_agvMapDirectThread.wait();
|
2026-09-18 16:22:20 +08:00
|
|
|
|
if (m_thread.isRunning()) {
|
|
|
|
|
|
QMetaObject::invokeMethod(m_worker, [this]() {
|
|
|
|
|
|
m_worker->disconnectConfigurationServer();
|
|
|
|
|
|
m_worker->disconnectFromServer();
|
|
|
|
|
|
}, Qt::BlockingQueuedConnection);
|
|
|
|
|
|
}
|
|
|
|
|
|
m_thread.quit();
|
|
|
|
|
|
m_thread.wait(2500);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
bool RobotClient::grpcAvailable() const
|
|
|
|
|
|
{
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
return true;
|
|
|
|
|
|
#else
|
|
|
|
|
|
return false;
|
|
|
|
|
|
#endif
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
quint64 RobotClient::agvMapStreamGeneration() const
|
|
|
|
|
|
{
|
|
|
|
|
|
return m_agvMapStreamGeneration.load();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::connectToServer(const QString &host, int port, bool demoMode)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
m_agvMapDirectDemo = demoMode;
|
|
|
|
|
|
++m_agvMapStreamGeneration;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit connectRequested(host, port, demoMode);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void RobotClient::disconnectFromServer()
|
|
|
|
|
|
{
|
|
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
++m_agvMapStreamGeneration;
|
|
|
|
|
|
emit disconnectRequested();
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::setArmTelemetry(const QString &deviceId, bool enabled)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armTelemetryRequested(deviceId, enabled);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void RobotClient::requestArmInfo(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armInfoRequested(deviceId);
|
|
|
|
|
|
}
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void RobotClient::requestTcpCalibrationPose(const QString &deviceId, quint64 requestId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit tcpCalibrationPoseRequested(deviceId, requestId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestControllerTcpOffset(const QString &deviceId, quint64 requestId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit controllerTcpOffsetRequested(deviceId, requestId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestTcpJogMove(const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
double velocity, double acceleration, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit tcpJogMoveRequested(deviceId, pose, velocity, acceleration, token);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void RobotClient::requestArmFrames(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armFramesRequested(deviceId);
|
|
|
|
|
|
}
|
2026-10-29 11:46:39 +08:00
|
|
|
|
void RobotClient::requestArmFrameDiscovery(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armFrameDiscoveryRequested(deviceId);
|
|
|
|
|
|
}
|
2026-09-23 11:11:49 +08:00
|
|
|
|
void RobotClient::setArmTelemetryFrames(const QString &deviceId, const QString &baseFrame,
|
|
|
|
|
|
const QString &tcpFrame)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armTelemetryFramesRequested(deviceId, baseFrame, tcpFrame);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestSpeedJ(const QString &deviceId, const QVariantList &velocities,
|
|
|
|
|
|
double acceleration, double duration)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit armCommandStarting(deviceId);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
emit speedJRequested(deviceId, velocities, acceleration, duration);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestSpeedL(const QString &deviceId, const QVariantMap &velocity,
|
|
|
|
|
|
double acceleration, double duration, bool toolFrame)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit armCommandStarting(deviceId);
|
2026-09-23 11:11:49 +08:00
|
|
|
|
emit speedLRequested(deviceId, velocity, acceleration, duration, toolFrame);
|
|
|
|
|
|
}
|
2026-10-20 16:49:27 +08:00
|
|
|
|
void RobotClient::requestMotorRpc(const QString &method,const QString &manager,int node,const QVariantMap ¶meters,quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit motorRpcRequested(method,manager,node,parameters,token);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestJointPointCapture(const QStringList &devices, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit jointPointCaptureRequested(devices, token);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestJointPointMove(const QVariantList &targets, double velocity,
|
|
|
|
|
|
double acceleration, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
for (const auto &target : targets) emit armCommandStarting(target.toMap().value("deviceId").toString());
|
|
|
|
|
|
emit jointPointMoveRequested(targets, velocity, acceleration, token);
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestMoveJ(const QString &deviceId, const QVariantList &positions,
|
|
|
|
|
|
double velocity, double acceleration)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit armCommandStarting(deviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit moveJRequested(deviceId, positions, velocity, acceleration);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestMoveJPose(const QString &deviceId, const QVariantMap &pose,
|
|
|
|
|
|
const QString &baseLink, const QString &eeLink,
|
|
|
|
|
|
double velocity, double acceleration)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit tcpReferenceInvalidated(deviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit moveJPoseRequested(deviceId, pose, baseLink, eeLink, velocity, acceleration);
|
|
|
|
|
|
}
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void RobotClient::requestTorque(const QString &deviceId, bool enabled) { emit armCommandStarting(deviceId); emit torqueRequested(deviceId, enabled); }
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestArmStop(const QString &deviceId) { emit armStopRequested(deviceId); }
|
|
|
|
|
|
void RobotClient::requestArmClearFault(const QString &deviceId) { emit armClearFaultRequested(deviceId); }
|
|
|
|
|
|
void RobotClient::requestArmCalibrateZero(const QString &deviceId, const QString &jointName)
|
|
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit armCommandStarting(deviceId);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit armCalibrateZeroRequested(deviceId, jointName);
|
|
|
|
|
|
}
|
2026-10-26 17:35:27 +08:00
|
|
|
|
void RobotClient::requestEnterTeachingMode(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armCommandStarting(deviceId);
|
|
|
|
|
|
emit enterTeachingModeRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestStartTrajectoryRecording(const QString &deviceId,
|
2026-10-29 11:46:39 +08:00
|
|
|
|
const QString &fileName, double frequencyHz)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit armCommandStarting(deviceId);
|
|
|
|
|
|
emit startTrajectoryRecordingRequested(deviceId, fileName, frequencyHz);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestRecordedTrajectories(const QString &deviceId) { emit recordedTrajectoriesRequested(deviceId); }
|
|
|
|
|
|
void RobotClient::requestReplayTrajectory(const QString &deviceId, const QString &fileName, double ratio, bool toStart,
|
|
|
|
|
|
const QVariantMap &limits)
|
2026-10-26 17:35:27 +08:00
|
|
|
|
{
|
|
|
|
|
|
emit armCommandStarting(deviceId);
|
2026-10-29 11:46:39 +08:00
|
|
|
|
emit replayTrajectoryRequested(deviceId, fileName, ratio, toStart, limits);
|
2026-10-26 17:35:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestCompleteTeaching(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit completeTeachingRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestStopTrajectoryRecording(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit stopTrajectoryRecordingRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestExitTeachingMode(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit exitTeachingModeRequested(deviceId);
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestSnapshot(const QString &cameraId) { emit snapshotRequested(cameraId); }
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void RobotClient::requestTouchRgbdImage(const QString &cameraId, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit touchRgbdImageRequested(cameraId, token);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestCameraCapabilities(const QString& camera,quint64 token) { emit cameraCapabilitiesRequested(camera.trimmed(),token); }
|
|
|
|
|
|
void RobotClient::requestTouchImage(const QString& camera,quint64 token) { emit touchImageRequested(camera.trimmed(),token); }
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestHandEyeImage(const QString &cameraId, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit handEyeImageRequested(cameraId, token);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestDepthSnapshot(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit depthSnapshotRequested(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestCameraStatus(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraStatusRequested(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestDexHandStatus(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit dexHandStatusRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestDexHandCommand(const QString &deviceId, const QString &command,
|
|
|
|
|
|
const QVariantList &values)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit dexHandCommandRequested(deviceId, command, values);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::startDexHandTactileStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit dexHandTactileStreamStartRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::stopDexHandTactileStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
emit dexHandTactileStreamStopRequested();
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::startCameraStream(const QString &cameraId, const QString &codec,
|
|
|
|
|
|
const QString &mode)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraStreamStartRequested(cameraId, codec, mode);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::setCameraStreamCodec(const QString &codec)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraStreamCodecRequested(codec);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::stopCameraStream(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraStreamStopRequested(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::startCameraRecording(const QString &cameraId, const QString &videoPath)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraRecordingStartRequested(cameraId, videoPath);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::stopCameraRecording(const QString &cameraId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit cameraRecordingStopRequested(cameraId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestSystemRefresh() { emit systemRefreshRequested(); }
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void RobotClient::requestSystemStopAll(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
interruptAgvManualVelocity(false);
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
emit systemStopAllRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestAgvRefresh(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
emit agvRefreshRequested(deviceId);
|
|
|
|
|
|
}
|
2026-10-14 17:15:46 +08:00
|
|
|
|
void RobotClient::requestAgvRelocalize(const QString &deviceId, double x, double y,
|
|
|
|
|
|
double theta)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV Relocalize")))
|
|
|
|
|
|
return;
|
2026-10-14 17:15:46 +08:00
|
|
|
|
emit agvRelocalizeRequested(deviceId, x, y, theta);
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestAgvNavigatePose(const QString &deviceId, double x, double y,
|
|
|
|
|
|
double theta, double maxSpeed)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV NavigateToPose")))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvNavigatePoseRequested(deviceId, x, y, theta, maxSpeed);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestAgvNavigateStation(const QString &deviceId, const QString &stationId,
|
|
|
|
|
|
double maxSpeed)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV NavigateToStation")))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvNavigateStationRequested(deviceId, stationId, maxSpeed);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestAgvFollowPath(const QString &deviceId, const QVariantList &path,
|
|
|
|
|
|
double maxSpeed)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV FollowPath")))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvFollowPathRequested(deviceId, path, maxSpeed);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::requestAgvVelocity(const QString &deviceId, double vx, double vy, double wz)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (vx == 0.0 && vy == 0.0 && wz == 0.0)
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
else if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV SetVelocity")))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvVelocityRequested(deviceId, vx, vy, wz);
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
|
|
|
|
|
|
void RobotClient::beginAgvManualControl(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
// Synchronize device context before the UI marks a fresh hold active.
|
|
|
|
|
|
// This is local bookkeeping only; it never sends a robot command.
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestAgvManualVelocity(quint64 requestId, const QString &deviceId,
|
|
|
|
|
|
double vx, double vy, double wz)
|
|
|
|
|
|
{
|
|
|
|
|
|
const quint64 contextGeneration = m_agvManualGeneration->load();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
// A device-change observer may synchronously end the held UI control.
|
|
|
|
|
|
// Do not admit the remainder of that canceled call in the new generation.
|
|
|
|
|
|
if (m_agvManualGeneration->load() != contextGeneration) {
|
|
|
|
|
|
emit agvManualVelocityFinished(requestId, false,
|
|
|
|
|
|
QStringLiteral("手动控制上下文已变更,本次速度未下发"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (deviceId.trimmed().isEmpty() || !qIsFinite(vx) || !qIsFinite(vy) || !qIsFinite(wz)) {
|
|
|
|
|
|
emit agvManualVelocityFinished(requestId, false,
|
|
|
|
|
|
QStringLiteral("手动速度需要有效设备 ID 和有限数值"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_agvMapDirectBusy || m_agvManualBusy || !m_thread.isRunning()) {
|
|
|
|
|
|
emit agvManualVelocityFinished(requestId, false,
|
|
|
|
|
|
m_agvMapDirectBusy ? QStringLiteral("地图直连操作进行中,手动速度未下发")
|
|
|
|
|
|
: QStringLiteral("速度通道忙或已停止,本次请求未排队"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit agvManualVelocityRequested(requestId, deviceId, vx, vy, wz);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::cancelAgvManualVelocity()
|
|
|
|
|
|
{
|
|
|
|
|
|
m_agvManualGeneration->fetch_add(1);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::interruptAgvManualVelocity(bool requestStop)
|
|
|
|
|
|
{
|
|
|
|
|
|
cancelAgvManualVelocity();
|
|
|
|
|
|
emit agvManualControlInterrupted(requestStop);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestAgvAction(const QString &deviceId, const QString &action)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity(action != QStringLiteral("EmergencyStop")
|
|
|
|
|
|
&& action != QStringLiteral("StopVelocity"));
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
const bool stopAction = action == QStringLiteral("EmergencyStop")
|
|
|
|
|
|
|| action == QStringLiteral("StopVelocity") || action == QStringLiteral("Pause")
|
|
|
|
|
|
|| action == QStringLiteral("Cancel") || action == QStringLiteral("StopMapping");
|
|
|
|
|
|
if (stopAction)
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
else if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV %1").arg(action)))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvActionRequested(deviceId, action);
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void RobotClient::requestAgvInventory(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
emit agvInventoryRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::configureAgvMapDirect(bool enabled, const QString &vehicleHost,
|
|
|
|
|
|
const QString &configHost, int configPort)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString host = vehicleHost.trimmed();
|
|
|
|
|
|
const QString configurationHost = configHost.trimmed();
|
|
|
|
|
|
if (m_agvMapDirectEnabled == enabled && m_agvMapDirectHost == host
|
|
|
|
|
|
&& m_agvMapDirectConfigHost == configurationHost
|
|
|
|
|
|
&& m_agvMapDirectConfigPort == configPort)
|
|
|
|
|
|
return;
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
m_agvMapDirectEnabled = enabled;
|
|
|
|
|
|
m_agvMapDirectHost = host;
|
|
|
|
|
|
m_agvMapDirectConfigHost = configurationHost;
|
|
|
|
|
|
m_agvMapDirectConfigPort = configPort;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::cancelAgvMapDirectRequests()
|
|
|
|
|
|
{
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::observeAgvMapDirectDevice(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
const QString id = deviceId.trimmed();
|
|
|
|
|
|
if (m_agvMapDirectDevice == id)
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!m_agvMapDirectDevice.isEmpty() || m_agvManualBusy)
|
|
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
m_agvMapDirectDevice = id;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::cancelAgvMapDirect(bool reportCancellation)
|
|
|
|
|
|
{
|
|
|
|
|
|
++m_agvMapDirectGeneration;
|
|
|
|
|
|
if (!m_agvMapDirectCancel || m_agvMapDirectCancel->exchange(true))
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (!reportCancellation)
|
|
|
|
|
|
return;
|
|
|
|
|
|
const QString detail = QStringLiteral("地图直连操作已取消;若命令已发送,车端结果待核查,未自动重试");
|
|
|
|
|
|
if (m_agvMapDirectOperation == DirectMapOperation::Read)
|
|
|
|
|
|
emit agvMapContentReceived(m_agvMapDirectRequestId, m_agvMapDirectRequestDevice,
|
|
|
|
|
|
m_agvMapDirectRequestMap, QString(), false, detail);
|
|
|
|
|
|
else if (m_agvMapDirectOperation == DirectMapOperation::Save)
|
|
|
|
|
|
emit agvMapSaveFinished(m_agvMapDirectRequestId, m_agvMapDirectRequestDevice,
|
|
|
|
|
|
m_agvMapDirectRequestMap, false, detail);
|
|
|
|
|
|
else
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV SwitchMap"), false, detail);
|
|
|
|
|
|
// Keep the physical worker busy until it has left the socket operation.
|
|
|
|
|
|
// Changing context must never queue another write behind a cancelled one.
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
bool RobotClient::rejectAgvWhileMapDirectBusy(const QString &command)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (!m_agvMapDirectBusy)
|
|
|
|
|
|
return false;
|
|
|
|
|
|
emit commandFinished(command, false,
|
|
|
|
|
|
QStringLiteral("地图直连操作进行中,请结束后再执行;停止和急停仍可使用"));
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestAgvMapDirect(DirectMapOperation operation, quint64 requestId,
|
|
|
|
|
|
const QString &deviceId, const QString &mapName,
|
|
|
|
|
|
const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
const auto reportFailure = [this, operation, requestId, deviceId, mapName](const QString &detail) {
|
|
|
|
|
|
if (operation == DirectMapOperation::Read)
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName, QString(), false, detail);
|
|
|
|
|
|
else if (operation == DirectMapOperation::Save)
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, false, detail);
|
|
|
|
|
|
else
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV SwitchMap"), false, detail);
|
|
|
|
|
|
};
|
|
|
|
|
|
if (deviceId.trimmed().isEmpty() || mapName.trimmed().isEmpty()) {
|
|
|
|
|
|
reportFailure(QStringLiteral("AGV 设备 ID 和地图名称不能为空"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_agvMapDirectBusy) {
|
|
|
|
|
|
reportFailure(QStringLiteral("已有地图直连操作进行中,本次请求未发送,请稍后重试"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const QString vehicleHost = m_agvMapDirectHost;
|
|
|
|
|
|
const QString configHost = m_agvMapDirectConfigHost;
|
|
|
|
|
|
const int configPort = m_agvMapDirectConfigPort;
|
|
|
|
|
|
const QString id = deviceId.trimmed();
|
|
|
|
|
|
const QString map = mapName.trimmed();
|
|
|
|
|
|
m_agvMapDirectBusy = true;
|
|
|
|
|
|
// The UI stops any held manual-motion timer synchronously here. Its stop
|
|
|
|
|
|
// command joins the backend queue before the barrier below. Do not create
|
|
|
|
|
|
// this operation's cancellation token until that preparatory stop returns.
|
|
|
|
|
|
emit agvMapDirectBusyChanged(true);
|
|
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
if (!m_agvMapDirectEnabled || m_agvMapDirectDemo || m_agvMapDirectDevice != id
|
|
|
|
|
|
|| m_agvMapDirectHost != vehicleHost || m_agvMapDirectConfigHost != configHost
|
|
|
|
|
|
|| m_agvMapDirectConfigPort != configPort) {
|
|
|
|
|
|
m_agvMapDirectBusy = false;
|
|
|
|
|
|
emit agvMapDirectBusyChanged(false);
|
|
|
|
|
|
reportFailure(QStringLiteral("地图直连上下文已变更,本次请求未发送"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const quint64 generation = m_agvMapDirectGeneration;
|
|
|
|
|
|
const auto cancel = std::make_shared<std::atomic<bool>>(false);
|
|
|
|
|
|
m_agvMapDirectCancel = cancel;
|
|
|
|
|
|
m_agvMapDirectOperation = operation;
|
|
|
|
|
|
m_agvMapDirectRequestId = requestId;
|
|
|
|
|
|
m_agvMapDirectRequestDevice = deviceId;
|
|
|
|
|
|
m_agvMapDirectRequestMap = mapName;
|
|
|
|
|
|
const auto runDirect =
|
|
|
|
|
|
[this, operation, requestId, deviceId, mapName, content, generation, cancel,
|
|
|
|
|
|
vehicleHost, configHost, configPort, id, map]() {
|
|
|
|
|
|
SeerAgvMapConnection connection;
|
|
|
|
|
|
connection.host = vehicleHost;
|
|
|
|
|
|
connection.nickName = QStringLiteral("CMVRControlStation-map-%1").arg(id);
|
|
|
|
|
|
QString lookupError;
|
|
|
|
|
|
bool resolved = !connection.host.isEmpty();
|
|
|
|
|
|
#ifdef CMVR_WITH_GRPC
|
|
|
|
|
|
if (!resolved && !cancel->load())
|
|
|
|
|
|
resolved = resolveDirectMapConnection(configHost, configPort, id,
|
|
|
|
|
|
cancel, connection, lookupError);
|
|
|
|
|
|
#else
|
|
|
|
|
|
Q_UNUSED(configHost)
|
|
|
|
|
|
Q_UNUSED(configPort)
|
|
|
|
|
|
if (!resolved)
|
|
|
|
|
|
lookupError = QStringLiteral("当前程序未编译 gRPC 支持,请手动填写车辆 IP");
|
|
|
|
|
|
#endif
|
|
|
|
|
|
SeerAgvMapResult result;
|
|
|
|
|
|
if (cancel->load())
|
|
|
|
|
|
result.detail = QStringLiteral("地图直连操作已取消");
|
|
|
|
|
|
else if (!resolved)
|
|
|
|
|
|
result.detail = lookupError;
|
|
|
|
|
|
else {
|
|
|
|
|
|
const auto cancelled = [cancel]() { return cancel->load(); };
|
|
|
|
|
|
if (operation == DirectMapOperation::Read)
|
|
|
|
|
|
result = SeerAgvMapClient::readMap(connection, map, cancelled);
|
|
|
|
|
|
else if (operation == DirectMapOperation::Save)
|
|
|
|
|
|
result = SeerAgvMapClient::saveMap(connection, map, content, cancelled);
|
|
|
|
|
|
else
|
|
|
|
|
|
result = SeerAgvMapClient::switchMap(connection, map, cancelled);
|
|
|
|
|
|
}
|
|
|
|
|
|
QMetaObject::invokeMethod(this,
|
|
|
|
|
|
[this, operation, requestId, deviceId, mapName, map, generation, cancel, result]() {
|
|
|
|
|
|
if (m_agvMapDirectCancel != cancel)
|
|
|
|
|
|
return;
|
|
|
|
|
|
m_agvMapDirectCancel.reset();
|
|
|
|
|
|
m_agvMapDirectBusy = false;
|
|
|
|
|
|
emit agvMapDirectBusyChanged(false);
|
|
|
|
|
|
if (cancel->load() || generation != m_agvMapDirectGeneration)
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (operation == DirectMapOperation::Read)
|
|
|
|
|
|
emit agvMapContentReceived(requestId, deviceId, mapName,
|
|
|
|
|
|
result.success ? result.content : QString(), result.success, result.detail);
|
|
|
|
|
|
else if (operation == DirectMapOperation::Save)
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName,
|
|
|
|
|
|
result.success, result.detail);
|
|
|
|
|
|
else {
|
|
|
|
|
|
const bool confirmed = result.success && result.currentMap == map;
|
|
|
|
|
|
QString detail = result.detail;
|
|
|
|
|
|
if (!confirmed && result.accepted && result.uncertain
|
|
|
|
|
|
&& !detail.contains(QStringLiteral("待确认")))
|
|
|
|
|
|
detail += QStringLiteral(";切图请求已接受,车辆当前地图待确认");
|
|
|
|
|
|
emit commandFinished(QStringLiteral("AGV SwitchMap"),
|
|
|
|
|
|
result.success || (result.accepted && result.uncertain), detail);
|
|
|
|
|
|
if (confirmed && !cancel->load()
|
|
|
|
|
|
&& generation == m_agvMapDirectGeneration)
|
|
|
|
|
|
emit agvDirectMapSwitchConfirmed(deviceId, mapName, detail);
|
|
|
|
|
|
}
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
};
|
|
|
|
|
|
// Drain all already-admitted backend commands before opening a direct
|
|
|
|
|
|
// socket. The backend thread only posts back to this QObject; it never
|
|
|
|
|
|
// reads GUI-owned state or retains the direct worker's lifetime.
|
|
|
|
|
|
QMetaObject::invokeMethod(m_worker, [this, generation, cancel, runDirect]() {
|
|
|
|
|
|
QMetaObject::invokeMethod(this, [this, generation, cancel, runDirect]() {
|
|
|
|
|
|
if (m_agvMapDirectCancel != cancel)
|
|
|
|
|
|
return;
|
|
|
|
|
|
if (cancel->load() || generation != m_agvMapDirectGeneration) {
|
|
|
|
|
|
m_agvMapDirectCancel.reset();
|
|
|
|
|
|
m_agvMapDirectBusy = false;
|
|
|
|
|
|
emit agvMapDirectBusyChanged(false);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
QMetaObject::invokeMethod(m_agvMapDirectWorker, runDirect, Qt::QueuedConnection);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
}, Qt::QueuedConnection);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestAgvSwitchMap(const QString &deviceId, const QString &mapName)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
interruptAgvManualVelocity();
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) {
|
|
|
|
|
|
requestAgvMapDirect(DirectMapOperation::Switch, 0, deviceId, mapName);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (rejectAgvWhileMapDirectBusy(QStringLiteral("AGV SwitchMap")))
|
|
|
|
|
|
return;
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit agvSwitchMapRequested(deviceId, mapName);
|
|
|
|
|
|
}
|
2026-11-10 16:10:46 +08:00
|
|
|
|
void RobotClient::requestAgvMapContent(quint64 requestId, const QString &deviceId,
|
|
|
|
|
|
const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) {
|
|
|
|
|
|
requestAgvMapDirect(DirectMapOperation::Read, requestId, deviceId, mapName);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit agvMapContentRequested(requestId, deviceId, mapName);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::saveAgvMapContent(quint64 requestId, const QString &deviceId,
|
|
|
|
|
|
const QString &mapName, const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
if (m_agvMapDirectEnabled && !m_agvMapDirectDemo) {
|
|
|
|
|
|
requestAgvMapDirect(DirectMapOperation::Save, requestId, deviceId, mapName, content);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (m_agvMapDirectBusy) {
|
|
|
|
|
|
emit agvMapSaveFinished(requestId, deviceId, mapName, false,
|
|
|
|
|
|
QStringLiteral("上一项地图直连操作仍在结束,未发送保存请求"));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
emit agvMapSaveRequested(requestId, deviceId, mapName, content);
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::startAgvMapStream(const QString &deviceId, const QString &mapName,
|
|
|
|
|
|
int dimension, bool snapshot, bool incremental)
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
emit agvMapStreamStartRequested(deviceId, mapName, dimension, snapshot, incremental,
|
|
|
|
|
|
++m_agvMapStreamGeneration, false);
|
|
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::startAgvMapPreview(const QString &deviceId, const QString &mapName)
|
|
|
|
|
|
{
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
emit agvMapStreamStartRequested(deviceId, mapName, 1, true, false,
|
|
|
|
|
|
++m_agvMapStreamGeneration, true);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
|
|
|
|
|
void RobotClient::stopAgvMapStream()
|
|
|
|
|
|
{
|
2026-11-10 16:10:46 +08:00
|
|
|
|
emit agvMapStreamStopRequested(++m_agvMapStreamGeneration);
|
2026-09-18 16:22:20 +08:00
|
|
|
|
}
|
2026-11-04 15:00:14 +08:00
|
|
|
|
void RobotClient::requestUserCoordinates(const QString &deviceId, const QVariantMap ¶meters, quint64 token)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (parameters.value("operation").toString() == "apply" || parameters.value("operation").toString() == "move") {
|
|
|
|
|
|
emit armCommandStarting(deviceId);
|
|
|
|
|
|
emit tcpReferenceInvalidated(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
emit userCoordinatesRequested(deviceId,parameters,token);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-18 16:22:20 +08:00
|
|
|
|
void RobotClient::requestRpc(const QString &serviceName, const QString &methodName,
|
2026-10-14 17:15:46 +08:00
|
|
|
|
const QString &requestJson, const QString &deviceId)
|
2026-09-18 16:22:20 +08:00
|
|
|
|
{
|
2026-10-14 17:15:46 +08:00
|
|
|
|
const QString method = methodName.toLower();
|
|
|
|
|
|
if (serviceName.contains(QStringLiteral("ArmService"), Qt::CaseInsensitive)
|
|
|
|
|
|
&& !method.startsWith(QStringLiteral("get")) && !method.startsWith(QStringLiteral("list")))
|
|
|
|
|
|
emit tcpReferenceInvalidated(deviceId);
|
2026-11-10 16:10:46 +08:00
|
|
|
|
if ((serviceName == QStringLiteral("cmvr.api.SystemService")
|
|
|
|
|
|
|| serviceName == QStringLiteral("SystemService"))
|
|
|
|
|
|
&& (methodName == QStringLiteral("StopAll") || methodName == QStringLiteral("stopAll"))) {
|
|
|
|
|
|
interruptAgvManualVelocity(false);
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
}
|
|
|
|
|
|
if (serviceName == QStringLiteral("cmvr.api.AgvService")
|
|
|
|
|
|
|| serviceName == QStringLiteral("AgvService")) {
|
|
|
|
|
|
observeAgvMapDirectDevice(deviceId);
|
|
|
|
|
|
const bool stop = methodName == QStringLiteral("emergencyStop")
|
|
|
|
|
|
|| methodName == QStringLiteral("stopVelocityControl")
|
|
|
|
|
|
|| methodName == QStringLiteral("cancelNavigation")
|
|
|
|
|
|
|| methodName == QStringLiteral("pauseNavigation")
|
|
|
|
|
|
|| methodName == QStringLiteral("stopMapping");
|
|
|
|
|
|
const bool read = methodName == QStringLiteral("getRuntimeState")
|
|
|
|
|
|
|| methodName == QStringLiteral("getNavigationStatus")
|
|
|
|
|
|
|| methodName == QStringLiteral("listMaps")
|
|
|
|
|
|
|| methodName == QStringLiteral("listStations")
|
|
|
|
|
|
|| methodName == QStringLiteral("downloadMap")
|
|
|
|
|
|
|| methodName == QStringLiteral("streamMap");
|
|
|
|
|
|
if (!read)
|
|
|
|
|
|
interruptAgvManualVelocity(methodName != QStringLiteral("emergencyStop")
|
|
|
|
|
|
&& methodName != QStringLiteral("stopVelocityControl"));
|
|
|
|
|
|
bool zeroVelocity = false;
|
|
|
|
|
|
if (methodName == QStringLiteral("setVelocity")) {
|
|
|
|
|
|
const QJsonObject velocity = QJsonDocument::fromJson(requestJson.toUtf8())
|
|
|
|
|
|
.object().value(QStringLiteral("velocity")).toObject();
|
|
|
|
|
|
zeroVelocity = !velocity.isEmpty()
|
|
|
|
|
|
&& velocity.value(QStringLiteral("vx")).toDouble() == 0.0
|
|
|
|
|
|
&& velocity.value(QStringLiteral("vy")).toDouble() == 0.0
|
|
|
|
|
|
&& velocity.value(QStringLiteral("wz")).toDouble() == 0.0;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (stop || zeroVelocity)
|
|
|
|
|
|
cancelAgvMapDirect();
|
|
|
|
|
|
else if (!read && m_agvMapDirectBusy) {
|
|
|
|
|
|
const QString error = QStringLiteral("地图直连操作进行中,该 AGV 命令未发送;停止和急停仍可使用");
|
|
|
|
|
|
emit rpcFinished(serviceName, methodName, false,
|
|
|
|
|
|
QString::fromUtf8(QJsonDocument(QJsonObject{{QStringLiteral("error"), error}})
|
|
|
|
|
|
.toJson(QJsonDocument::Compact)));
|
|
|
|
|
|
emit commandFinished(QStringLiteral("%1.%2").arg(serviceName, methodName), false, error);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-09-18 16:22:20 +08:00
|
|
|
|
emit rpcRequested(serviceName, methodName, requestJson, deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::startSpeakerAudioStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit speakerAudioStreamStartRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::sendSpeakerAudioFrame(const QByteArray &data, int sampleRate, int channels,
|
|
|
|
|
|
qint64 pts, int samples)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit speakerAudioFrameRequested(data, sampleRate, channels, pts, samples);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::stopSpeakerAudioStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
emit speakerAudioStreamStopRequested();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::startMicrophoneAudioStream(const QString &deviceId)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit microphoneAudioStreamStartRequested(deviceId);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::stopMicrophoneAudioStream()
|
|
|
|
|
|
{
|
|
|
|
|
|
emit microphoneAudioStreamStopRequested();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::connectConfigurationServer(const QString &host, int port)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationConnectRequested(host, port);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::disconnectConfigurationServer()
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationDisconnectRequested();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::requestConfigurationFiles()
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationFilesRequested();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::readConfigurationFile(const QString &relativePath)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationFileReadRequested(relativePath);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::validateConfigurationFile(const QString &relativePath,
|
|
|
|
|
|
const QString &content)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationFileValidateRequested(relativePath, content);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void RobotClient::saveConfigurationFile(const QString &relativePath, const QString &content,
|
|
|
|
|
|
const QString &expectedRevision)
|
|
|
|
|
|
{
|
|
|
|
|
|
emit configurationFileSaveRequested(relativePath, content, expectedRevision);
|
|
|
|
|
|
}
|