// Real RobotClient + controller against an ephemeral loopback gRPC service. // This executable never uses the main application's endpoint or settings. #include #include #include #include #include "cmvr/api/arm_service.grpc.pb.h" #include "cmvr/api/camera_service.grpc.pb.h" #include "../src/robotclient.h" #include "../src/touchsequencecontroller.h" #include #include #include #include #include #include #include using Pose = TcpCalibration::Pose; class TouchFakeCamera : public cmvr::api::CameraService::Service { public: std::atomic mode{0}; std::atomic depthStreams{0}, rgbStreams{0}, endedDepth{0}, endedRgb{0}; grpc::Status StartCamera(grpc::ServerContext*,const cmvr::api::StartCameraCommand::Request*,cmvr::api::StartCameraCommand::Feedback* r) override { r->mutable_header()->set_success(true); return grpc::Status::OK; } grpc::Status GetDepthImageStream(grpc::ServerContext* context,grpc::ServerReaderWriter* stream) override { cmvr::api::GetDepthImageStreamCommand::Request request; if(stream->Read(&request)) { ++depthStreams; while(!context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(5)); } ++endedDepth; return grpc::Status::OK; } grpc::Status GetRGBImageStream(grpc::ServerContext* context,grpc::ServerReaderWriter* stream) override { cmvr::api::GetRGBImageStreamCommand::Request request; if(stream->Read(&request)) { ++rgbStreams; while(!context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(5)); } ++endedRgb; return grpc::Status::OK; } grpc::Status GetStatus(grpc::ServerContext*,const cmvr::api::GetCameraStateCommand::Request*,cmvr::api::GetCameraStateCommand::Feedback* r) override { r->mutable_header()->set_success(true); if(mode.load()==1) return grpc::Status::OK; auto *c=r->mutable_state()->mutable_capabilities(); c->set_version(1); c->set_serial("mvs-raw"); c->set_model("MV-CS050-10UM"); c->set_session_generation(3); c->set_raw_image(true); c->set_valid_intrinsics(true); c->set_capture_timestamp(true); return grpc::Status::OK; } grpc::Status GetRGBImage(grpc::ServerContext*,const cmvr::api::GetRGBImageCommand::Request*,cmvr::api::GetRGBImageCommand::Feedback* r) override { r->mutable_header()->set_success(true); auto *f=r->mutable_color_frame(); f->set_width(8); f->set_height(6); f->set_type(cmvr::api::FrameData::U8C1); f->set_data(std::string(48,char(100))); f->set_codec("none"); const qint64 now=(QDateTime::currentMSecsSinceEpoch()+2000)*1000000; r->mutable_header()->mutable_timestamp()->set_seconds(now/1000000000); r->mutable_header()->mutable_timestamp()->set_nanos(int(now%1000000000)); f->set_capture_utc_ns(now); f->set_capture_earliest_utc_ns(now-10000000); f->set_camera_serial("mvs-raw"); f->set_camera_session_generation(3); f->set_distortion_model("brown_conrady"); auto *k=r->mutable_intrinsics(); k->set_fx(500); k->set_fy(500); k->set_cx(4); k->set_cy(3); for(int i=0;i<5;++i) k->add_coeffs(0); if(mode.load()==1) f->clear_camera_serial(); return grpc::Status::OK; } grpc::Status GetRGBDImages(grpc::ServerContext *,const cmvr::api::GetRGBDImagesCommand::Request *request, cmvr::api::GetRGBDImagesCommand::Feedback *response) override { if(!request->require_metric_depth()||request->header().device_id()!="depth-camera") return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,"wrong metric snapshot request"); response->mutable_header()->set_success(true); auto *rgb=response->mutable_color_frame(); auto *depth=response->mutable_depth_frame(); rgb->set_width(8); rgb->set_height(6); rgb->set_type(cmvr::api::FrameData::U8C3); rgb->set_codec("none"); std::string bgr(8*6*3,'\0'); for(int i=0;i<48;++i) { bgr[i*3]=char(7); bgr[i*3+2]=char(99); } rgb->set_data(bgr); depth->set_width(8); depth->set_height(6); depth->set_type(cmvr::api::FrameData::U16C1); depth->set_codec("none"); std::string raw(8*6*2,'\0'); for(int i=0;i<48;++i) { raw[i*2]=char(0xf4); raw[i*2+1]=char(1); } depth->set_data(raw); auto *k=response->mutable_intrinsics(); k->set_fx(500); k->set_fy(500); k->set_cx(4); k->set_cy(3); for(int i=0;i<5;++i) k->add_coeffs(0); const qint64 now=(QDateTime::currentMSecsSinceEpoch()+(mode.load()==5?2000:0))*1000000; response->mutable_header()->mutable_timestamp()->set_seconds(now/1000000000); response->mutable_header()->mutable_timestamp()->set_nanos(int(now%1000000000)); rgb->set_capture_utc_ns(now); depth->set_capture_utc_ns(now); if(mode.load()==1) return grpc::Status::OK; // Legacy service omits geometry. auto *g=response->mutable_depth_geometry(); g->set_metres_per_unit(.001); g->set_aligned_to_color(mode.load()!=2); g->set_color_axial_z(true); g->set_byte_order("little"); g->set_distortion_model("none"); if(mode.load()==3) depth->set_data("truncated"); if(mode.load()==4) depth->set_capture_utc_ns(now-100000000); return grpc::Status::OK; } }; class TouchFakeArm : public cmvr::api::ArmService::Service { public: enum Mode { Arrive, AcknowledgeOnly, BlockUntilCancelled }; std::atomic mode{Arrive}, reads{0}, moves{0}, stops{0}, cancelled{0}, manualMoves{0}; std::atomic moving{false}; std::mutex mutex; Pose current{{.4, .2, .5, 0, 0, 0}}; std::vector requests; std::string lastStopDevice; grpc::Status GetArmInfo(grpc::ServerContext *, const cmvr::api::GetArmInfo::Request *request, cmvr::api::GetArmInfo::Response *response) override { response->mutable_header()->set_success(true); response->set_device_id(request->header().device_id()); response->set_driver_type("AuboARM"); response->set_manufacturer("Aubo"); response->set_dof(6); response->set_default_base_frame("base"); response->set_default_tcp_frame("tcp"); for (int i = 0; i < 6; ++i) response->add_joint_names("joint" + std::to_string(i)); return grpc::Status::OK; } grpc::Status getRobotState(grpc::ServerContext *, const cmvr::api::GetRobotState::Request *, cmvr::api::GetRobotState::Response *response) override { std::lock_guard lock(mutex); ++reads; response->mutable_header()->set_success(true); auto *state = response->mutable_state(); state->set_connected(true); state->set_powered_on(true); state->set_moving(moving.load()); state->set_robot_mode(cmvr::api::ARM_ROBOT_MODE_IDLE); state->set_safety_mode(cmvr::api::ARM_SAFETY_MODE_NORMAL); state->set_timestamp(QDateTime::currentMSecsSinceEpoch() / 1000.0); auto *p = state->mutable_actual_tcp_pose(); p->set_x(current[0]); p->set_y(current[1]); p->set_z(current[2]); p->set_rx(current[3]); p->set_ry(current[4]); p->set_rz(current[5]); auto *joints = state->mutable_actual_joint_state(); for (int i = 0; i < 6; ++i) { joints->add_position(.1 + .01 * i); joints->add_velocity(moving.load() ? .02 : 0); } return grpc::Status::OK; } grpc::Status moveL(grpc::ServerContext *context, const cmvr::api::MoveL::Request *request, cmvr::api::MoveL::Response *response) override { { std::lock_guard lock(mutex); requests.push_back(*request); } ++moves; const int behavior = mode.load(); if (behavior == BlockUntilCancelled) { moving.store(true); while (!context->IsCancelled()) std::this_thread::sleep_for(std::chrono::milliseconds(5)); moving.store(false); ++cancelled; return grpc::Status(grpc::StatusCode::CANCELLED, "loopback motion cancelled"); } if (behavior == Arrive) { std::lock_guard lock(mutex); const auto &p = request->target(); current = {{p.x(), p.y(), p.z(), p.rx(), p.ry(), p.rz()}}; } response->mutable_header()->set_success(true); return grpc::Status::OK; } grpc::Status stopMotion(grpc::ServerContext *, const cmvr::api::CommandHeader::Request *request, cmvr::api::CommandHeader::Feedback *response) override { { std::lock_guard lock(mutex); lastStopDevice = request->device_id(); } moving.store(false); ++stops; response->set_success(true); return grpc::Status::OK; } grpc::Status speedJ(grpc::ServerContext *, const cmvr::api::SpeedJ::Request *, cmvr::api::SpeedJ::Response *response) override { ++manualMoves; response->mutable_header()->set_success(true); return grpc::Status::OK; } }; static void require(bool condition, const char *detail) { if (!condition) throw std::runtime_error(detail); } static bool until(const std::function &predicate, int timeout = 5000) { QElapsedTimer timer; timer.start(); while (!predicate() && timer.elapsed() < timeout) QTest::qWait(10); return predicate(); } int main(int argc, char **argv) { QCoreApplication application(argc, argv); TouchFakeArm fake; grpc::ServerBuilder builder; int port = 0; builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(&fake); TouchFakeCamera camera; builder.RegisterService(&camera); auto server = builder.BuildAndStart(); if (!server || port <= 0) { std::fprintf(stderr, "FAIL: unable to start loopback service\n"); return 1; } int result = 0; { RobotClient client; TouchSequenceController sequence; bool connected = false; QObject::connect(&client, &RobotClient::connectionChanged, &application, [&](bool value, int, const QString &) { connected = value; }); QObject::connect(&sequence, &TouchSequenceController::captureRequested, &client, &RobotClient::requestTcpCalibrationPose); QObject::connect(&sequence, &TouchSequenceController::moveRequested, &client, &RobotClient::requestTcpJogMove); QObject::connect(&sequence, &TouchSequenceController::stopRequested, &client, &RobotClient::requestArmStop); QObject::connect(&client, &RobotClient::tcpCalibrationPoseReceived, &sequence, &TouchSequenceController::acceptPose); QObject::connect(&client, &RobotClient::commandFinished, &sequence, &TouchSequenceController::acceptCommand); QSignalSpy finished(&sequence, &TouchSequenceController::finished); try { require(client.grpcAvailable(), "gRPC backend not available"); client.connectToServer("127.0.0.1", port, false); require(until([&] { return connected; }), "loopback client failed to connect"); QSignalSpy rgbd(&client,&RobotClient::touchRgbdImageReceived); for(int mode=0;mode<6;++mode) { camera.mode.store(mode); rgbd.clear(); client.requestTouchRgbdImage("depth-camera",quint64(100+mode)); require(until([&] { return !rgbd.isEmpty(); }),"RGBD request did not return"); const auto reply=rgbd.last(); require(reply[0].toULongLong()==quint64(100+mode),"RGBD token was lost"); require(reply[5].toBool()==(mode==0||mode==5),"invalid RGBD contract was accepted"); if(mode==0||mode==5) { const auto image=qvariant_cast(reply[2]); require(image.pixelColor(0,0).red()==99&&image.pixelColor(0,0).blue()==7,"BGR to RGB conversion incorrect"); const auto metadata=reply[4].toMap(); require(metadata.value("depthData").toByteArray().size()==96,"raw depth not retained"); require(metadata.value("metresPerUnit").toDouble()==.001,"sensor scale lost"); if(mode==5) { const qint64 server=metadata.value("serverCaptureUtcNs").toLongLong(); const qint64 local=metadata.value("captureUtcNs").toLongLong(); require(server-local>1000000000,"server clock offset was not converted"); require(local<=QDateTime::currentMSecsSinceEpoch()*1000000,"future local capture accepted"); } } } const QString endpoint = QStringLiteral("127.0.0.1:%1").arg(port); QSignalSpy capabilities(&client,&RobotClient::cameraCapabilitiesReceived); camera.mode.store(0); client.requestCameraCapabilities("depth-camera",500); require(until([&] { return !capabilities.isEmpty(); }),"capability query did not return"); require(capabilities.last()[3].toBool() && capabilities.last()[2].toMap().value("serial")=="mvs-raw","actual camera identity not returned"); for(int mode=0;mode<2;++mode) { camera.mode.store(mode); rgbd.clear(); client.requestTouchImage("depth-camera",quint64(600+mode)); require(until([&] { return !rgbd.isEmpty(); }),"raw image query did not return"); require(rgbd.last()[5].toBool()==(mode==0),"raw positioning accepted missing hardware identity"); if(mode==0) { require(qvariant_cast(rgbd.last()[2]).pixelColor(0,0).red()==100,"Mono8 image lifetime/format invalid"); const auto data=rgbd.last()[4].toMap(); require(data.value("captureUtcNs").toLongLong()<=QDateTime::currentMSecsSinceEpoch()*1000000,"raw capture clock not mapped"); require(data.value("captureEarliestLocalNs").toLongLong()<=data.value("captureUtcNs").toLongLong(),"raw capture interval invalid"); } } camera.mode.store(1); capabilities.clear(); client.requestCameraCapabilities("depth-camera",501); require(until([&] { return !capabilities.isEmpty(); }),"legacy capability query did not return"); require(!capabilities.last()[3].toBool(),"legacy camera guessed to have capabilities"); require(fake.moves.load()==0,"camera discovery issued a movement command"); QSignalSpy streamStates(&client,&RobotClient::cameraStreamStateChanged); client.startCameraStream("stream-camera","h264","depth"); require(until([&] { return camera.depthStreams.load()==1; }),"depth stream did not subscribe"); client.startCameraStream("stream-camera","h264","rgb"); require(until([&] { return camera.rgbStreams.load()==1 && camera.endedDepth.load()==1; }),"same-camera mode switch did not retire depth and start RGB"); QTest::qWait(50); // Deliver queued UI state callbacks, not only SDK/RPC counters. for(const auto &state:streamStates) require(state[1].toBool(),"old mode end notification would stop the replacement RGB preview"); client.stopCameraStream("stream-camera"); require(until([&] { return camera.endedRgb.load()==1; }),"replacement RGB stream was not released"); sequence.setContext(endpoint, "arm-a", true, {}); const Pose observation{{.4, .2, .5, 0, 0, 0}}, contact{{.4, .2, .48, 0, 0, 0}}; const QVector path{ {contact, .01, .1, 40, "contact"}, {observation, .02, .2, 0, "return"}}; require(sequence.start(path, observation), "valid sequence did not start"); require(until([&] { return !finished.isEmpty(); }), "successful sequence did not finish"); require(finished.last().at(0).toBool(), "valid MoveL path failed verification"); require(fake.moves.load() == 2, "success did not dispatch exactly contact and return"); require(fake.reads.load() >= 4, "real initial/arrival/dwell/final state reads missing"); require(fake.stops.load() == 0, "normal completion unexpectedly requested a stop"); { std::lock_guard lock(fake.mutex); require(fake.requests[0].header().device_id() == "arm-a", "wrong MoveL device"); require(fake.requests[0].base_frame() == "base" && fake.requests[0].tcp_frame() == "tcp", "MoveL did not target the driver's active TCP in base frame"); require(fake.requests[0].target().z() == .48 && fake.requests[1].target().z() == .5, "contact/return target order changed"); require(fake.requests[0].options().velocity() == .01 && fake.requests[1].options().acceleration() == .2, "MoveL parameters not forwarded"); } fake.mode.store(TouchFakeArm::AcknowledgeOnly); finished.clear(); require(sequence.start(path, observation), "ack-only sequence did not start"); require(until([&] { return !finished.isEmpty() && fake.stops.load() >= 1; }), "ack-only motion was not stopped after pose mismatch"); require(!finished.last().at(0).toBool(), "acknowledgement was mistaken for arrival"); require(fake.moves.load() == 3, "failed contact incorrectly dispatched return"); fake.mode.store(TouchFakeArm::BlockUntilCancelled); finished.clear(); require(sequence.start(path, observation), "cancellable sequence did not start"); require(until([&] { return fake.moves.load() == 4 && fake.moving.load(); }), "blocking MoveL did not reach loopback backend"); sequence.stop(); require(until([&] { return fake.stops.load() >= 2 && fake.cancelled.load() >= 1; }), "stop did not cancel active RPC and dispatch stopMotion"); require(!finished.isEmpty() && !finished.last().at(0).toBool(), "cancel reported success"); QTest::qWait(180); require(fake.moves.load() == 4, "cancelled sequence dispatched a return or resumed"); finished.clear(); require(sequence.start(path, observation), "context-switch sequence did not start"); require(until([&] { return fake.moves.load() == 5 && fake.moving.load(); }), "context-switch MoveL did not start"); sequence.setContext(endpoint, "arm-b", false, {}); require(until([&] { return fake.stops.load() >= 3 && fake.cancelled.load() >= 2; }), "context switch did not cancel old active motion"); { std::lock_guard lock(fake.mutex); require(fake.lastStopDevice == "arm-a", "context switch stopped new device instead of old device"); } sequence.setContext(endpoint, "arm-b", true, {}); QTest::qWait(180); require(fake.moves.load() == 5 && !sequence.running(), "context restoration resumed motion"); // Mirror MainWindow's manual-command interlock using the public // signal: cancellation must run synchronously before the request // is queued to RobotClient's worker. QObject::connect(&client, &RobotClient::armCommandStarting, &sequence, [&](const QString &id) { if (id == "arm-a") sequence.stop(); }); bool stoppedBeforeManualDispatch = false; QObject::connect(&client, &RobotClient::speedJRequested, &application, [&](const QString &, const QVariantList &, double, double) { stoppedBeforeManualDispatch = !sequence.running(); }); sequence.setContext(endpoint, "arm-a", true, {}); require(sequence.start(path, observation), "manual-interlock sequence did not start"); require(until([&] { return fake.moves.load() == 6 && fake.moving.load(); }), "manual-interlock MoveL did not start"); client.requestSpeedJ("arm-a", {0., 0., 0., 0., 0., 0.}, .1, .1); require(stoppedBeforeManualDispatch, "manual command was queued before touch cancellation"); require(until([&] { return fake.stops.load() >= 4 && fake.cancelled.load() >= 3 && fake.manualMoves.load() == 1; }), "manual command did not stop existing RPC before proceeding"); QTest::qWait(180); require(fake.moves.load() == 6, "manual command allowed touch sequence to resume"); std::puts("PASS: real RobotClient fresh pose, active-TCP MoveL order/parameters, verified completion, acknowledgement-only failure, active RPC cancellation, stopMotion, context/manual-command interlocks, no automatic return/resume"); } catch (const std::exception &error) { sequence.stop(); std::fprintf(stderr, "FAIL: %s\n", error.what()); result = 1; } client.disconnectFromServer(); until([&] { return !connected; }); } server->Shutdown(); return result; }