feat(aubo): add three-point work frames and reliable service startup
This commit is contained in:
parent
3b14ca97e6
commit
048cea580d
@ -17,7 +17,7 @@ arm {
|
||||
tool_frame: "tool0"
|
||||
username: "aubo"
|
||||
password: "123456"
|
||||
auto_enable: true
|
||||
auto_enable: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,7 +133,7 @@ device_manager {
|
||||
id: "aubo_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/aubo_arm.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -154,7 +154,7 @@ device_manager {
|
||||
id: "src1100"
|
||||
type: DEVICE_TYPE_AGV
|
||||
config_file: "devices/agv/agv.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -237,7 +237,7 @@ device_manager {
|
||||
id: "lingkong_can_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/lingkong_motors.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "tchl_joint_motors"
|
||||
|
||||
@ -27,6 +27,6 @@ task_manager {
|
||||
type: TASK_TYPE_QUIC_EDGE
|
||||
run_mode: TASK_RUN_MODE_BLOCKING_SERVICE
|
||||
config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ quic_edge {
|
||||
server_port: 4433
|
||||
alpn: "cmvr-quic-edge/1"
|
||||
node_id: "cmvr-edge"
|
||||
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-002"
|
||||
robot_id: "AIMA-20261026-003"
|
||||
software_version: "0.1"
|
||||
|
||||
# The existing cmvr-es gRPC server remains the robot-control endpoint. "auto"
|
||||
|
||||
@ -17,7 +17,9 @@ set(AUBO_SDK_INCLUDE_DIR ${AUBO_SDK_ROOT}/include)
|
||||
set(AUBO_SDK_LIB_DIR ${AUBO_SDK_ROOT}/lib)
|
||||
|
||||
if (EXISTS "${AUBO_SDK_INCLUDE_DIR}/aubo_sdk/rpc.h")
|
||||
target_compile_definitions(aubo_arm PRIVATE CMVR_HAS_AUBO_SDK)
|
||||
# The public AuboArm header uses this macro in its object layout.
|
||||
# Consumers must compile with the same layout as the shared library.
|
||||
target_compile_definitions(aubo_arm PUBLIC CMVR_HAS_AUBO_SDK)
|
||||
target_include_directories(aubo_arm PRIVATE ${AUBO_SDK_INCLUDE_DIR})
|
||||
if (EXISTS "${AUBO_SDK_LIB_DIR}")
|
||||
target_link_directories(aubo_arm PRIVATE ${AUBO_SDK_LIB_DIR})
|
||||
@ -41,6 +43,14 @@ add_library(cmvr_es::device::aubo_arm ALIAS aubo_arm)
|
||||
install(TARGETS aubo_arm LIBRARY DESTINATION lib)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_executable(aubo_user_coordinate_store_test tests/aubo_user_coordinate_store_test.cpp)
|
||||
target_include_directories(aubo_user_coordinate_store_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
target_link_libraries(aubo_user_coordinate_store_test PRIVATE jsoncpp Threads::Threads)
|
||||
add_test(NAME aubo_user_coordinate_store_test COMMAND aubo_user_coordinate_store_test)
|
||||
add_executable(aubo_user_frame_validation_test tests/aubo_user_frame_validation_test.cpp)
|
||||
target_include_directories(aubo_user_frame_validation_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
target_link_libraries(aubo_user_frame_validation_test PRIVATE aubo_arm cmvr_es::proto)
|
||||
add_test(NAME aubo_user_frame_validation_test COMMAND aubo_user_frame_validation_test)
|
||||
add_executable(joint_trajectory_csv_test tests/joint_trajectory_csv_test.cpp)
|
||||
target_include_directories(joint_trajectory_csv_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es)
|
||||
add_test(NAME joint_trajectory_csv_test COMMAND joint_trajectory_csv_test)
|
||||
|
||||
@ -18,6 +18,16 @@ namespace cmvr::device {
|
||||
|
||||
class AuboArm final : public RobotArm {
|
||||
public:
|
||||
Result calibrateUserCoordinate(const std::vector<std::vector<double>>& points, std::vector<double>& pose);
|
||||
Result moveLRelativeInCoordinate(const CartesianPose& delta,const MotionOptions& options);
|
||||
Result applyBuiltinCoordinate(const std::string& name,
|
||||
std::vector<double>& actual_tcp_offset);
|
||||
Result applyUserCoordinates(const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset,
|
||||
std::vector<double>& actual_tcp_offset,
|
||||
const std::string& name = {}, std::uint64_t revision = 0);
|
||||
bool currentUserCoordinateMatches(const std::string& name, std::uint64_t revision) const;
|
||||
bool lastAppliedUserCoordinate(std::string& name,std::uint64_t& revision) const;
|
||||
explicit AuboArm(const config::RobotArmConfig& cfg);
|
||||
~AuboArm() override;
|
||||
|
||||
@ -62,6 +72,9 @@ public:
|
||||
Result moveJ(const JointPositionCommand& target, const MotionOptions& options) override;
|
||||
Result speedJ(const JointVelocityCommand& velocity, double acceleration, double duration) override;
|
||||
Result stopJ(double acceleration) override;
|
||||
Result moveLInUserFrame(const CartesianPose& target,
|
||||
const MotionOptions& options, const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset);
|
||||
Result moveL(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
FrameType frame = FrameType::Base) override;
|
||||
@ -114,6 +127,11 @@ public:
|
||||
bool busy() const override { return busy_.load(); }
|
||||
|
||||
private:
|
||||
Result configureWorkObject_(const std::vector<double>& base_user_pose, bool invalidate = true);
|
||||
Result moveLConfigured_(const CartesianPose& target, const MotionOptions& options,
|
||||
const std::string& base_frame, const std::string& tcp_frame,
|
||||
const std::vector<double>* user_pose,
|
||||
const std::vector<double>* tcp_offset, bool relative_translation = false);
|
||||
enum class ActiveMotion {
|
||||
None,
|
||||
Joint,
|
||||
@ -155,6 +173,14 @@ private:
|
||||
std::atomic<bool> hardware_estop_latched_{false};
|
||||
std::atomic<bool> auto_recovery_suppressed_{false};
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::mutex user_coordinate_mutex_;
|
||||
std::atomic<bool> user_coordinates_active_{false};
|
||||
// Tool reference is sampled at the start of each MoveL, never at Apply.
|
||||
std::atomic<bool> builtin_tool_reference_{false};
|
||||
std::string applied_user_coordinate_name_;
|
||||
std::uint64_t applied_user_coordinate_revision_{};
|
||||
std::vector<double> applied_base_user_pose_;
|
||||
std::vector<double> applied_tcp_offset_;
|
||||
struct CsvRecording;
|
||||
std::shared_ptr<CsvRecording> csv_recording_;
|
||||
mutable std::mutex trajectory_mutex_;
|
||||
|
||||
50
cmvr-es/devices/arm/aubo_arm/include/three_point_frame.h
Normal file
50
cmvr-es/devices/arm/aubo_arm/include/three_point_frame.h
Normal file
@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
namespace cmvr::device {
|
||||
template<class Compose>
|
||||
inline std::vector<double> coordinateTranslationTarget(const std::vector<double>& current,
|
||||
const std::vector<double>& reference,const std::vector<double>& delta,Compose compose) {
|
||||
const auto valid=[](const std::vector<double>& p){return p.size()==6&&std::all_of(p.begin(),p.end(),[](double x){return std::isfinite(x);});};
|
||||
if(!valid(current)||!valid(reference)||!valid(delta)||delta[3]!=0||delta[4]!=0||delta[5]!=0)
|
||||
throw std::invalid_argument("axis translation requires finite poses and zero rotation increment");
|
||||
const auto origin=compose(reference,std::vector<double>(6,0.0));
|
||||
const auto tip=compose(reference,delta);
|
||||
if(!valid(origin)||!valid(tip))throw std::runtime_error("SDK Math returned invalid translation");
|
||||
auto target=current;for(int i=0;i<3;++i)target[i]+=tip[i]-origin[i];
|
||||
if(!valid(target))throw std::runtime_error("invalid translated target");
|
||||
return target;
|
||||
}
|
||||
// Geometry validation for SDK Math::calibrateCoordinate(poses, 0): O, +X, +Y half-plane.
|
||||
inline std::vector<double> threePointFrame(const std::vector<std::vector<double>>& points) {
|
||||
if(points.size()!=3)throw std::invalid_argument("exactly three base TCP poses required: origin, +X, XY plane");
|
||||
for(const auto& p:points)if(p.size()!=6)throw std::invalid_argument("each point must contain six values (m/rad)");
|
||||
for(const auto& p:points)for(double x:p)if(!std::isfinite(x))throw std::invalid_argument("non-finite calibration point");
|
||||
std::array<double,3> x{},y{},z{};
|
||||
double nx=0,ny=0,projection=0;
|
||||
for(int i=0;i<3;++i){x[i]=points[1][i]-points[0][i];y[i]=points[2][i]-points[0][i];nx+=x[i]*x[i];}
|
||||
nx=std::sqrt(nx);if(nx<1e-5)throw std::invalid_argument("origin and +X point are coincident or too close (<0.01 mm)");
|
||||
for(int i=0;i<3;++i){x[i]/=nx;projection+=x[i]*y[i];}
|
||||
for(int i=0;i<3;++i){y[i]-=projection*x[i];ny+=y[i]*y[i];}
|
||||
ny=std::sqrt(ny);if(ny<1e-5)throw std::invalid_argument("three points are collinear or XY plane height is too small (<0.01 mm)");
|
||||
for(double& v:y)v/=ny;
|
||||
z={x[1]*y[2]-x[2]*y[1],x[2]*y[0]-x[0]*y[2],x[0]*y[1]-x[1]*y[0]};
|
||||
const double ry=std::atan2(-x[2],std::hypot(x[0],x[1]));
|
||||
const bool singular=std::hypot(x[0],x[1])<1e-10;
|
||||
const double rx=singular?0:std::atan2(y[2],z[2]);
|
||||
const double rz=singular?std::atan2(-y[0],y[1]):std::atan2(x[1],x[0]);
|
||||
return {points[0][0],points[0][1],points[0][2],rx,ry,rz};
|
||||
}
|
||||
inline bool sameCoordinateFrame(const std::vector<double>& a,const std::vector<double>& b,double tolerance=1e-6){
|
||||
if(a.size()!=6||b.size()!=6)return false;
|
||||
for(int i=0;i<3;++i)if(!std::isfinite(a[i])||!std::isfinite(b[i])||std::abs(a[i]-b[i])>tolerance)return false;
|
||||
const auto rotation=[](const std::vector<double>& p){
|
||||
const double x=p[3],y=p[4],z=p[5],cx=std::cos(x),sx=std::sin(x),cy=std::cos(y),sy=std::sin(y),cz=std::cos(z),sz=std::sin(z);
|
||||
return std::array<double,9>{cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx,sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx,-sy,cy*sx,cy*cx};
|
||||
};
|
||||
const auto ra=rotation(a),rb=rotation(b);for(int i=0;i<9;++i)if(!std::isfinite(ra[i])||!std::isfinite(rb[i])||std::abs(ra[i]-rb[i])>tolerance)return false;return true;
|
||||
}
|
||||
}
|
||||
153
cmvr-es/devices/arm/aubo_arm/include/user_coordinate_store.h
Normal file
153
cmvr-es/devices/arm/aubo_arm/include/user_coordinate_store.h
Normal file
@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
#include <json/json.h>
|
||||
#include "three_point_frame.h"
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace cmvr::device {
|
||||
struct UserCoordinateProfile {
|
||||
std::string name;
|
||||
std::vector<double> user_pose, tcp_offset; // T_base_user and T_flange_tcp, m/rad.
|
||||
std::uint64_t revision{};
|
||||
std::vector<std::vector<double>> calibration_points;
|
||||
};
|
||||
struct CoordinateStoreError : std::runtime_error {
|
||||
enum Kind { Invalid, Missing, Exists, Conflict, Storage } kind;
|
||||
CoordinateStoreError(Kind k,const std::string& text):std::runtime_error(text),kind(k){}
|
||||
};
|
||||
class UserCoordinateStore {
|
||||
std::filesystem::path directory_;
|
||||
static Json::Value& field(Json::Value& value,const char* key) { return *value.demand(key,key+std::strlen(key)); }
|
||||
static const Json::Value& field(const Json::Value& value,const char* key) {
|
||||
const auto* found=value.find(key,key+std::strlen(key));static const Json::Value empty;
|
||||
return found?*found:empty;
|
||||
}
|
||||
static void require(bool ok,CoordinateStoreError::Kind kind,const std::string& text) {
|
||||
if(!ok)throw CoordinateStoreError(kind,text);
|
||||
}
|
||||
struct Lock {
|
||||
int fd{-1};
|
||||
explicit Lock(const std::filesystem::path& path) {
|
||||
fd=::open(path.c_str(),O_RDWR|O_CREAT|O_CLOEXEC|O_NOFOLLOW,0600);
|
||||
if(fd<0 || ::flock(fd,LOCK_EX)!=0){if(fd>=0)::close(fd);throw CoordinateStoreError(CoordinateStoreError::Storage,"cannot lock coordinate store");}
|
||||
}
|
||||
~Lock(){if(fd>=0){::flock(fd,LOCK_UN);::close(fd);}}
|
||||
};
|
||||
Json::Value read() const {
|
||||
const auto path=directory_/"coordinates.json";
|
||||
require(!std::filesystem::is_symlink(path),CoordinateStoreError::Storage,"coordinate file must not be a symbolic link");
|
||||
Json::Value root(Json::objectValue);
|
||||
if(!std::filesystem::exists(path)) {
|
||||
field(root,"version")=2;field(root,"next_revision")=Json::UInt64(1);field(root,"coordinates")=Json::Value(Json::arrayValue);return root;
|
||||
}
|
||||
int fd=::open(path.c_str(),O_RDONLY|O_CLOEXEC|O_NOFOLLOW);
|
||||
require(fd>=0,CoordinateStoreError::Storage,"cannot open coordinate store");
|
||||
std::string bytes;char buffer[4096];ssize_t count;
|
||||
while((count=::read(fd,buffer,sizeof(buffer)))>0){bytes.append(buffer,count);if(bytes.size()>2*1024*1024){::close(fd);throw CoordinateStoreError(CoordinateStoreError::Storage,"coordinate store too large");}}
|
||||
::close(fd);require(count==0,CoordinateStoreError::Storage,"coordinate store read failed");
|
||||
Json::CharReaderBuilder builder;builder[std::string("rejectDupKeys")]=true;builder[std::string("failIfExtra")]=true;
|
||||
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());std::string error;
|
||||
require(reader->parse(bytes.data(),bytes.data()+bytes.size(),&root,&error),CoordinateStoreError::Storage,"invalid coordinate JSON; original file preserved");
|
||||
// Explicitly discard the retired manual-pose schema. Preserve revision monotonicity.
|
||||
if(root.isObject() && field(root,"version").isInt() && field(root,"version").asInt()==1
|
||||
&& field(root,"coordinates").isArray() && field(root,"next_revision").isUInt64()) {
|
||||
field(root,"version")=2;field(root,"coordinates")=Json::Value(Json::arrayValue);write(root);
|
||||
}
|
||||
require(root.isObject()&&field(root,"version").isInt()&&field(root,"version").asInt()==2&&field(root,"next_revision").isUInt64()&&field(root,"coordinates").isArray(),CoordinateStoreError::Storage,"invalid coordinate schema; original file preserved");
|
||||
require(field(root,"coordinates").size()<=1000,CoordinateStoreError::Storage,"too many stored coordinates");
|
||||
std::set<std::string> names;
|
||||
for(const auto& value:field(root,"coordinates")){auto p=decode(value);validate(p);require(p.revision>0&&names.insert(p.name).second,CoordinateStoreError::Storage,"duplicate or invalid stored coordinate revision");}
|
||||
return root;
|
||||
}
|
||||
void write(const Json::Value& root) const {
|
||||
Json::StreamWriterBuilder builder;builder[std::string("indentation")]=" ";
|
||||
const auto bytes=Json::writeString(builder,root);
|
||||
std::string temp=(directory_/"coordinates.tmp.XXXXXX").string();
|
||||
std::vector<char> name(temp.begin(),temp.end());name.push_back(0);
|
||||
int fd=::mkstemp(name.data());require(fd>=0,CoordinateStoreError::Storage,"cannot create coordinate temporary file");
|
||||
bool ok=true;std::size_t offset=0;
|
||||
while(offset<bytes.size()){auto n=::write(fd,bytes.data()+offset,bytes.size()-offset);if(n<=0){ok=false;break;}offset+=n;}
|
||||
ok=(::fsync(fd)==0)&&ok;::close(fd);
|
||||
if(!ok || ::rename(name.data(),(directory_/"coordinates.json").c_str())!=0){::unlink(name.data());throw CoordinateStoreError(CoordinateStoreError::Storage,"cannot commit coordinate store; previous data retained");}
|
||||
int dir=::open(directory_.c_str(),O_RDONLY|O_DIRECTORY|O_CLOEXEC);if(dir>=0){::fsync(dir);::close(dir);}
|
||||
}
|
||||
public:
|
||||
explicit UserCoordinateStore(std::filesystem::path directory):directory_(std::move(directory)){}
|
||||
static UserCoordinateStore forArm(const std::string& id) {
|
||||
require(!id.empty()&&id!="."&&id!=".."&&id.find_first_of("/\\")==std::string::npos&&id.find('\0')==std::string::npos,CoordinateStoreError::Invalid,"invalid device ID");
|
||||
return UserCoordinateStore(std::filesystem::read_symlink("/proc/self/exe").parent_path()/"data"/"user_coordinates"/id);
|
||||
}
|
||||
static bool poseValid(const std::vector<double>& pose) {return pose.size()==6&&std::all_of(pose.begin(),pose.end(),[](double x){return std::isfinite(x);});}
|
||||
static void validate(const UserCoordinateProfile& p) {
|
||||
require(!p.name.empty()&&p.name.size()<=240&&p.name.front()!=' '&&p.name.back()!=' ',CoordinateStoreError::Invalid,"coordinate name is required (max 240 UTF-8 bytes)");
|
||||
for(unsigned char c:p.name)require(c>=32&&c!=127,CoordinateStoreError::Invalid,"coordinate name contains control characters");
|
||||
if(!isBuiltin(p.name)) { try {require(sameCoordinateFrame(threePointFrame(p.calibration_points),p.user_pose),CoordinateStoreError::Invalid,"calibrated frame does not match its three source points");} catch(const std::exception& e){throw CoordinateStoreError(CoordinateStoreError::Invalid,e.what());} }
|
||||
require(poseValid(p.user_pose)&&poseValid(p.tcp_offset),CoordinateStoreError::Invalid,"user_pose and tcp_offset must contain six finite values (m, rad)");
|
||||
}
|
||||
static Json::Value encode(const UserCoordinateProfile& p) {
|
||||
Json::Value v(Json::objectValue);field(v,"name")=p.name;field(v,"revision")=Json::UInt64(p.revision);
|
||||
field(v,"user_reference")="base";field(v,"tcp_reference")="flange";field(v,"units")="m_rad";
|
||||
field(v,"user_pose")=Json::Value(Json::arrayValue);field(v,"tcp_offset")=Json::Value(Json::arrayValue);
|
||||
field(v,"calibration_version")=2;field(v,"calibration_points")=Json::Value(Json::arrayValue);
|
||||
for(const auto& point:p.calibration_points){Json::Value a(Json::arrayValue);for(double x:point)a.append(x);field(v,"calibration_points").append(a);}
|
||||
for(double x:p.user_pose)field(v,"user_pose").append(x);for(double x:p.tcp_offset)field(v,"tcp_offset").append(x);return v;
|
||||
}
|
||||
static UserCoordinateProfile decode(const Json::Value& v) {
|
||||
require(v.isObject()&&field(v,"name").isString()&&field(v,"revision").isUInt64()&&field(v,"user_pose").isArray()&&field(v,"tcp_offset").isArray(),CoordinateStoreError::Storage,"invalid stored coordinate record");
|
||||
require(field(v,"user_reference").asString()=="base"&&field(v,"tcp_reference").asString()=="flange"&&field(v,"units").asString()=="m_rad",CoordinateStoreError::Storage,"unsupported stored coordinate convention");
|
||||
UserCoordinateProfile p;p.name=field(v,"name").asString();p.revision=field(v,"revision").asUInt64();
|
||||
require(field(v,"calibration_version").asInt()==2 && field(v,"calibration_points").isArray(),CoordinateStoreError::Storage,"retired or missing calibration data");
|
||||
for(const auto& point:field(v,"calibration_points")){std::vector<double> a;for(const auto& x:point){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid calibration point");a.push_back(x.asDouble());}p.calibration_points.push_back(a);}
|
||||
for(const auto& x:field(v,"user_pose")){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid pose number");p.user_pose.push_back(x.asDouble());}
|
||||
for(const auto& x:field(v,"tcp_offset")){require(x.isNumeric(),CoordinateStoreError::Storage,"invalid TCP number");p.tcp_offset.push_back(x.asDouble());}return p;
|
||||
}
|
||||
std::vector<UserCoordinateProfile> list() const {
|
||||
std::filesystem::create_directories(directory_);Lock lock(directory_/"coordinates.lock");const auto root=read();
|
||||
std::vector<UserCoordinateProfile> result;for(const auto& v:field(root,"coordinates"))result.push_back(decode(v));return result;
|
||||
}
|
||||
UserCoordinateProfile get(const std::string& name,std::uint64_t expected=0) const {
|
||||
if(isBuiltin(name)) {
|
||||
require(!expected||expected==1,CoordinateStoreError::Conflict,"invalid built-in coordinate revision");
|
||||
return builtin(name);
|
||||
}
|
||||
for(const auto& p:list())if(p.name==name){require(!expected||p.revision==expected,CoordinateStoreError::Conflict,"coordinate revision changed; refresh before applying or moving");return p;}
|
||||
throw CoordinateStoreError(CoordinateStoreError::Missing,"coordinate not found");
|
||||
}
|
||||
UserCoordinateProfile mutate(const std::string& operation,UserCoordinateProfile profile,std::uint64_t expected=0) const {
|
||||
require(!isBuiltin(profile.name),CoordinateStoreError::Invalid,"built-in coordinates cannot be created, edited or deleted");
|
||||
if(operation!="delete")validate(profile);
|
||||
std::filesystem::create_directories(directory_);Lock lock(directory_/"coordinates.lock");auto root=read();auto& records=field(root,"coordinates");
|
||||
int found=-1;for(unsigned i=0;i<records.size();++i)if(field(records[i],"name").asString()==profile.name)found=int(i);
|
||||
if(operation=="create")require(found<0,CoordinateStoreError::Exists,"coordinate already exists; use update");
|
||||
else {require(found>=0,CoordinateStoreError::Missing,"coordinate not found");require(expected>0&&decode(records[found]).revision==expected,CoordinateStoreError::Conflict,"coordinate revision changed or missing; refresh first");}
|
||||
if(operation=="delete"){Json::Value removed;records.removeIndex(found,&removed);profile=decode(removed);}
|
||||
else {
|
||||
const auto revision=field(root,"next_revision").asUInt64();require(revision>0&&revision<std::numeric_limits<std::uint64_t>::max(),CoordinateStoreError::Storage,"invalid revision counter");
|
||||
profile.revision=revision;field(root,"next_revision")=Json::UInt64(revision+1);
|
||||
if(found<0){require(records.size()<1000,CoordinateStoreError::Invalid,"coordinate limit reached");records.append(encode(profile));}else records[found]=encode(profile);
|
||||
}
|
||||
write(root);return profile;
|
||||
}
|
||||
static bool isBuiltin(const std::string& name) {
|
||||
return name=="__builtin_base__"||name=="__builtin_tool__";
|
||||
}
|
||||
static UserCoordinateProfile builtin(const std::string& name) {
|
||||
require(isBuiltin(name),CoordinateStoreError::Invalid,"unknown built-in coordinate");
|
||||
// These zeros are schema placeholders, NOT a TCP readback or saved tool.
|
||||
return {name,std::vector<double>(6,0.0),std::vector<double>(6,0.0),1};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/include/three_point_frame.h"
|
||||
#include "devices/arm/aubo_arm/include/aubo_motion_result.h"
|
||||
|
||||
#include <algorithm>
|
||||
@ -290,26 +291,6 @@ SafetyMode toPublicSafetyMode(
|
||||
return SafetyMode::Unknown;
|
||||
}
|
||||
|
||||
std::vector<std::string> listAuboWorldFrames(
|
||||
const arcs::common_interface::SyncMovePtr& sync_move)
|
||||
{
|
||||
if (!sync_move) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::set<std::string> frame_names{"world", "base", "flange", "tcp"};
|
||||
std::vector<std::string> pending(frame_names.begin(), frame_names.end());
|
||||
for (std::size_t index = 0; index < pending.size(); ++index) {
|
||||
for (const auto& child : sync_move->frameGetChildren(pending[index])) {
|
||||
if (!child.empty() && sync_move->frameExist(child) &&
|
||||
frame_names.insert(child).second) {
|
||||
pending.push_back(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {frame_names.begin(), frame_names.end()};
|
||||
}
|
||||
|
||||
CartesianPose auboPoseFromVector(const std::vector<double>& values,
|
||||
const std::string& context)
|
||||
{
|
||||
@ -324,14 +305,6 @@ CartesianPose auboPoseFromVector(const std::vector<double>& values,
|
||||
};
|
||||
}
|
||||
|
||||
void insertFrameName(std::set<std::string>& frame_names,
|
||||
const std::string& frame_name)
|
||||
{
|
||||
if (!frame_name.empty()) {
|
||||
frame_names.insert(frame_name);
|
||||
}
|
||||
}
|
||||
|
||||
bool isAuboTcpFrame(const arcs::common_interface::SyncMovePtr& sync_move,
|
||||
const std::string& frame_name)
|
||||
{
|
||||
@ -454,6 +427,123 @@ bool AuboArm::stop()
|
||||
return stopMotion().ok();
|
||||
}
|
||||
|
||||
Result AuboArm::calibrateUserCoordinate(const std::vector<std::vector<double>>& points, std::vector<double>& pose)
|
||||
{
|
||||
try {threePointFrame(points);} catch(const std::exception& e){return Result::failure(ArmErrorCode::InvalidArgument,e.what());}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
const auto ready=ensureConnected_("three-point calibration");if(!ready.ok())return ready;
|
||||
try {
|
||||
const auto result=sdk_->rpc_client->getMath()->calibrateCoordinate(points,0);
|
||||
if(std::get<1>(result)!=0)return Result::failure(ArmErrorCode::InvalidArgument,"SDK three-point calibration failed: "+std::to_string(std::get<1>(result)));
|
||||
pose=std::get<0>(result);
|
||||
if(pose.size()!=6 || !std::all_of(pose.begin(),pose.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"SDK returned invalid calibrated frame");
|
||||
if(!sameCoordinateFrame(threePointFrame(points),pose))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"SDK calibration does not match origin/+X/XY convention");
|
||||
return Result::success();
|
||||
} catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,e.what());}
|
||||
#else
|
||||
return unsupported_("three-point calibration");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::moveLRelativeInCoordinate(const CartesianPose& delta,const MotionOptions& options)
|
||||
{
|
||||
if(delta.rx!=0 || delta.ry!=0 || delta.rz!=0)
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"axis translation must not include rotation");
|
||||
if(!user_coordinates_active_.load())return Result::failure(ArmErrorCode::CommandRejected,"apply a coordinate before axis translation");
|
||||
return moveLConfigured_(delta,options,{},{},nullptr,nullptr,true);
|
||||
}
|
||||
|
||||
Result AuboArm::configureWorkObject_(const std::vector<double>& base_user_pose, bool invalidate)
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto names=sdk_->rpc_client->getRobotNames();
|
||||
if(names.empty())return Result::failure(ArmErrorCode::RobotNotReady,"robot name unavailable");
|
||||
auto robot=sdk_->rpc_client->getRobotInterface(names.front());
|
||||
if(!robot || !robot->getRobotConfig())return Result::failure(ArmErrorCode::RobotNotReady,"robot config unavailable");
|
||||
auto config=robot->getRobotConfig();
|
||||
const auto mounting=config->getMountingPose();
|
||||
if(mounting.size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"world-to-base mounting pose unavailable");
|
||||
// The saved pose is T_base_user, while remote_tool=false requires
|
||||
// WObjectData.user_coord in world. Convert the FRAME once, not targets.
|
||||
const auto world_user=sdk_->rpc_client->getMath()->poseTrans(mounting,base_user_pose);
|
||||
if(world_user.size()!=6 || !std::all_of(world_user.begin(),world_user.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid world-to-user pose");
|
||||
arcs::common_interface::WObjectData work_object;
|
||||
work_object.remote_tool=false;
|
||||
work_object.attach_frame=""; // Not a display name or pendant-library key.
|
||||
work_object.user_coord=world_user;
|
||||
work_object.obj_coord.assign(6,0.0);
|
||||
// A timeout can leave controller state uncertain. Invalidate the old
|
||||
// application identity BEFORE the write so it cannot authorize motion.
|
||||
if(invalidate){std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;user_coordinates_active_.store(false);builtin_tool_reference_.store(false);}
|
||||
const int ret=config->setWorkObjectData(work_object);
|
||||
if(ret!=arcs::common_interface::AUBO_OK)
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"setWorkObjectData rejected: sdk ret="+std::to_string(ret));
|
||||
if(invalidate)user_coordinates_active_.store(true);
|
||||
return Result::success();
|
||||
}catch(const std::exception& e){return Result::failure(ArmErrorCode::CommandFailed,std::string("setWorkObjectData failed: ")+e.what());}
|
||||
#else
|
||||
return unsupported_("setWorkObjectData");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::applyBuiltinCoordinate(const std::string& name,
|
||||
std::vector<double>& actual_tcp_offset)
|
||||
{
|
||||
if(name!="__builtin_base__" && name!="__builtin_tool__")
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"unknown built-in coordinate");
|
||||
// Keep the actual configured tool; choosing a reference must not zero TCP.
|
||||
std::string response;
|
||||
if(!executeJsonCommand("{\"command\":\"get_active_tcp_offset\"}",response))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,response);
|
||||
Json::Value data;std::string error;
|
||||
if(!parseJsonCommand(response,data,error))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"invalid TCP readback");
|
||||
const auto* offset=findJsonMember(data,"offset");
|
||||
if(!offset || !offset->isArray() || offset->size()!=6)
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"missing TCP readback");
|
||||
std::vector<double> tcp;for(const auto& x:*offset)tcp.push_back(x.asDouble());
|
||||
const auto result=applyUserCoordinates(std::vector<double>(6,0.0),tcp,actual_tcp_offset,name,1);
|
||||
if(result.ok())builtin_tool_reference_.store(name=="__builtin_tool__");
|
||||
return result;
|
||||
}
|
||||
|
||||
Result AuboArm::applyUserCoordinates(const std::vector<double>& user_pose,
|
||||
const std::vector<double>& tcp_offset,
|
||||
std::vector<double>& actual_tcp_offset,
|
||||
const std::string& name, std::uint64_t revision)
|
||||
{
|
||||
Json::Value q(Json::objectValue);jsonMember(q,"command")="apply_user_coordinates";
|
||||
Json::Value user(Json::arrayValue),tcp(Json::arrayValue);
|
||||
for(double x:user_pose)user.append(x);for(double x:tcp_offset)tcp.append(x);
|
||||
jsonMember(q,"user_pose")=user;jsonMember(q,"tcp_offset")=tcp;
|
||||
std::string response;
|
||||
if(!executeJsonCommand(compactJson(q),response))return Result::failure(ArmErrorCode::CommandFailed,response);
|
||||
Json::Value r;std::string error;
|
||||
if(!parseJsonCommand(response,r,error))return Result::failure(ArmErrorCode::CommandFailed,"invalid apply response");
|
||||
actual_tcp_offset.clear();const auto* offset=findJsonMember(r,"offset");
|
||||
if(!offset || !offset->isArray() || offset->size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"missing TCP readback");
|
||||
for(const auto& x:*offset)actual_tcp_offset.push_back(x.asDouble());
|
||||
{std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_=name;applied_user_coordinate_revision_=revision;applied_base_user_pose_=user_pose;applied_tcp_offset_=actual_tcp_offset;}
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
bool AuboArm::currentUserCoordinateMatches(const std::string& name,std::uint64_t revision) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
return user_coordinates_active_.load() && !name.empty() && applied_user_coordinate_name_==name && applied_user_coordinate_revision_==revision;
|
||||
}
|
||||
|
||||
bool AuboArm::lastAppliedUserCoordinate(std::string& name,std::uint64_t& revision) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
name=applied_user_coordinate_name_;revision=applied_user_coordinate_revision_;
|
||||
return user_coordinates_active_.load()&&!name.empty();
|
||||
}
|
||||
|
||||
bool AuboArm::executeJsonCommand(const std::string& request_json,
|
||||
std::string& response_json)
|
||||
{
|
||||
@ -484,6 +574,75 @@ bool AuboArm::executeJsonCommand(const std::string& request_json,
|
||||
"field 'command' is required and must be a non-empty string");
|
||||
}
|
||||
command = lowerString(command);
|
||||
if (command == "apply_user_coordinates" || command == "get_active_tcp_offset") {
|
||||
const auto read_pose = [&](const char* key, std::vector<double>& pose) {
|
||||
const auto* value = findJsonMember(root, key);
|
||||
if (!value || !value->isArray() || value->size() != 6) return false;
|
||||
for (unsigned i = 0; i < 6; ++i) {
|
||||
if (!(*value)[i].isNumeric() || !std::isfinite((*value)[i].asDouble())) return false;
|
||||
pose.push_back((*value)[i].asDouble());
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const bool read_only = command == "get_active_tcp_offset";
|
||||
std::vector<double> user_pose, tcp_offset;
|
||||
if (!read_only && (!read_pose("user_pose", user_pose) || !read_pose("tcp_offset", tcp_offset)))
|
||||
return fail("invalid_argument", "user_pose and tcp_offset must each contain six finite values (m, rad)");
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
const auto ready = ensureConnected_(command);
|
||||
if (!ready.ok()) return fail("not_connected", ready.message);
|
||||
std::uint64_t token{};
|
||||
if (!read_only && !tryBeginMotion_(ActiveMotion::Joint, token))
|
||||
return fail("busy", "cannot change TCP while arm motion is active");
|
||||
ScopeExit owner([this, token, read_only]() {
|
||||
if (!read_only) releaseMotion_(ActiveMotion::Joint, token);
|
||||
});
|
||||
try {
|
||||
const auto names = sdk_->rpc_client->getRobotNames();
|
||||
if (names.empty()) return fail("not_ready", "robot name unavailable");
|
||||
auto config = sdk_->rpc_client->getRobotInterface(names.front())->getRobotConfig();
|
||||
if (!read_only) {
|
||||
// Any subsequent failure must not leave the old record labelled
|
||||
// as applied after a possibly successful TCP/frame write.
|
||||
{std::lock_guard<std::mutex> lock(user_coordinate_mutex_);applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;user_coordinates_active_.store(false);builtin_tool_reference_.store(false);}
|
||||
const auto previous=config->getTcpOffset();
|
||||
bool unchanged=previous.size()==6;
|
||||
if(unchanged)for(std::size_t i=0;i<6;++i)unchanged=unchanged&&std::isfinite(previous[i])&&std::abs(previous[i]-tcp_offset[i])<=1e-9;
|
||||
if(!unchanged && config->setTcpOffset(tcp_offset)!=arcs::common_interface::AUBO_OK)
|
||||
return fail("apply_failed","setTcpOffset rejected");
|
||||
}
|
||||
const auto actual = config->getTcpOffset();
|
||||
if (actual.size() != 6) return fail("readback_failed", "invalid TCP readback size");
|
||||
Json::Value offset(Json::arrayValue);
|
||||
for (std::size_t i=0; i<6; ++i) {
|
||||
if (!std::isfinite(actual[i])) return fail("readback_failed", "non-finite TCP readback");
|
||||
if (!read_only && std::abs(actual[i]-tcp_offset[i]) > 1e-6)
|
||||
return fail("readback_failed", "TCP readback differs from requested offset");
|
||||
offset.append(actual[i]);
|
||||
}
|
||||
if(!read_only){
|
||||
// Configure WorkObject LAST: no TCP setter may follow it before
|
||||
// the caller submits a Cartesian instruction.
|
||||
const auto result=configureWorkObject_(user_pose);
|
||||
if(!result.ok())return fail("work_object_failed",result.message);
|
||||
}
|
||||
jsonMember(response,"success") = true;
|
||||
jsonMember(response,"device_id") = id_;
|
||||
jsonMember(response,"transform") = "T_flange_tcp";
|
||||
jsonMember(response,"units") = "m_rad";
|
||||
jsonMember(response,"rotation_convention") = "RzRyRx";
|
||||
jsonMember(response,"coordinate_api_version") = 3;
|
||||
jsonMember(response,"work_object_acknowledged") = !read_only;
|
||||
jsonMember(response,"offset") = offset;
|
||||
jsonMember(response,"user_frame_reference") = "base";
|
||||
jsonMember(response,"persistent_in_controller") = false;
|
||||
response_json = compactJson(response);
|
||||
return true;
|
||||
} catch (const std::exception& e) { return fail("sdk_error",e.what()); }
|
||||
#else
|
||||
return fail("unsupported", "Aubo SDK unavailable");
|
||||
#endif
|
||||
}
|
||||
if (command != "cabinet_io") {
|
||||
return fail("unsupported_command",
|
||||
"unsupported json command: " + command);
|
||||
@ -871,110 +1030,15 @@ bool AuboArm::isFault() const
|
||||
Result AuboArm::listBaseFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
const auto ready = ensureConnected_("ListBaseFrame");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
// Frame discovery can be slow on older controllers. Keep its longer
|
||||
// timeout and possible disconnect isolated from state/control RPCs.
|
||||
arcs::aubo_sdk::RpcClient frame_client;
|
||||
frame_client.setRequestTimeout(10000);
|
||||
frame_client.connect(ip_, port_);
|
||||
frame_client.login(username_, password_);
|
||||
const auto robot_names = frame_client.getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
frame_client.getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getSyncMove()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] world-frame interface is unavailable");
|
||||
}
|
||||
std::set<std::string> available_frames{"world", "base"};
|
||||
insertFrameName(available_frames, vendor_cfg_.base_frame());
|
||||
try {
|
||||
const auto discovered_frames =
|
||||
listAuboWorldFrames(robot_interface->getSyncMove());
|
||||
available_frames.insert(
|
||||
discovered_frames.begin(), discovered_frames.end());
|
||||
} catch (const std::exception& e) {
|
||||
// Older Aubo controller releases do not expose
|
||||
// SyncMove.frameGetChildren even though SDK 0.27.1 declares it.
|
||||
// Keep the built-in/configured frames usable instead of failing
|
||||
// the whole gRPC request with JSON-RPC -32601.
|
||||
CMVR_LOG(WARNING)
|
||||
<< "[AuboArm] ListBaseFrame dynamic discovery unavailable; "
|
||||
"using built-in/configured frames: "
|
||||
<< e.what();
|
||||
}
|
||||
frame_names.assign(available_frames.begin(), available_frames.end());
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] ListBaseFrame failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("ListBaseFrame");
|
||||
#endif
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListBaseFrame/frameGetChildren is not supported for AUBO");
|
||||
}
|
||||
|
||||
Result AuboArm::listTCPFrame(std::vector<std::string>& frame_names) const
|
||||
{
|
||||
frame_names.clear();
|
||||
const auto ready = ensureConnected_("ListTCPFrame");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] robot name list is empty");
|
||||
}
|
||||
const auto robot_interface =
|
||||
sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface || !robot_interface->getSyncMove()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"[AuboArm] world-frame interface is unavailable");
|
||||
}
|
||||
const auto sync_move = robot_interface->getSyncMove();
|
||||
std::set<std::string> available_frames{"tool0", "flange", "tcp"};
|
||||
insertFrameName(available_frames, vendor_cfg_.tool_frame());
|
||||
try {
|
||||
for (const auto& frame_name : listAuboWorldFrames(sync_move)) {
|
||||
if (frame_name != "flange" && frame_name != "tcp" &&
|
||||
isAuboTcpFrame(sync_move, frame_name)) {
|
||||
available_frames.insert(frame_name);
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(WARNING)
|
||||
<< "[AuboArm] ListTCPFrame dynamic discovery unavailable; "
|
||||
"using built-in/configured frames: "
|
||||
<< e.what();
|
||||
}
|
||||
frame_names.assign(available_frames.begin(), available_frames.end());
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
std::string("[AuboArm] ListTCPFrame failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("ListTCPFrame");
|
||||
#endif
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"ListTCPFrame/frameGetChildren is not supported for AUBO");
|
||||
}
|
||||
|
||||
Result AuboArm::torqueOn()
|
||||
@ -1311,6 +1375,29 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
const std::string& base_frame,
|
||||
const std::string& tcp_frame)
|
||||
{
|
||||
return moveLConfigured_(target, options, base_frame, tcp_frame, nullptr, nullptr);
|
||||
}
|
||||
|
||||
Result AuboArm::moveLInUserFrame(const CartesianPose& target, const MotionOptions& options,
|
||||
const std::vector<double>& user_pose, const std::vector<double>& tcp_offset)
|
||||
{
|
||||
const auto valid = [](const std::vector<double>& p) {
|
||||
return p.size() == 6 && std::all_of(p.begin(),p.end(),[](double v){return std::isfinite(v);});
|
||||
};
|
||||
const std::vector<double> p{target.x,target.y,target.z,target.rx,target.ry,target.rz};
|
||||
if (!valid(user_pose) || !valid(tcp_offset) || !valid(p) ||
|
||||
!std::isfinite(options.velocity) || options.velocity <= 0 ||
|
||||
!std::isfinite(options.acceleration) || options.acceleration <= 0)
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid explicit user frame, TCP or motion limits");
|
||||
return moveLConfigured_(target, options, "base", "tcp", &user_pose, &tcp_offset);
|
||||
}
|
||||
|
||||
Result AuboArm::moveLConfigured_(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
const std::string& base_frame, const std::string& tcp_frame,
|
||||
const std::vector<double>* user_pose,
|
||||
const std::vector<double>* explicit_tcp_offset, bool relative_translation)
|
||||
{
|
||||
if (options.cancellation_requested && options.cancellation_requested()) {
|
||||
return Result::failure(ArmErrorCode::CommandRejected,
|
||||
@ -1341,7 +1428,7 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
auto motion_control = robot_interface->getMotionControl();
|
||||
motion_control->setSpeedFraction(speed_scaling_);
|
||||
|
||||
const std::string selected_base_frame = base_frame.empty()
|
||||
const std::string selected_base_frame = (user_pose || user_coordinates_active_.load()) ? std::string{"base"} : base_frame.empty()
|
||||
? (vendor_cfg_.base_frame().empty()
|
||||
? std::string{"base"}
|
||||
: vendor_cfg_.base_frame())
|
||||
@ -1353,6 +1440,8 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
: tcp_frame;
|
||||
auto robot_config = robot_interface->getRobotConfig();
|
||||
auto sync_move = robot_interface->getSyncMove();
|
||||
if(user_coordinates_active_.load() && !user_pose && (!base_frame.empty() || !tcp_frame.empty()))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"controller work-object coordinates are active; omit legacy named base/TCP fields to follow the applied coordinate system");
|
||||
if (selected_base_frame != "base" &&
|
||||
(!sync_move || !sync_move->frameExist(selected_base_frame))) {
|
||||
return Result::failure(
|
||||
@ -1362,7 +1451,11 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
}
|
||||
|
||||
std::vector<double> tcp_offset;
|
||||
if (selected_tcp_frame == "tool0" ||
|
||||
if (explicit_tcp_offset) {
|
||||
tcp_offset = *explicit_tcp_offset;
|
||||
} else if (tcp_frame.empty()) {
|
||||
tcp_offset = robot_config->getTcpOffset();
|
||||
} else if (selected_tcp_frame == "tool0" ||
|
||||
selected_tcp_frame == "flange") {
|
||||
tcp_offset.assign(6, 0.0);
|
||||
} else if (selected_tcp_frame == "tcp") {
|
||||
@ -1384,7 +1477,10 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
"[AuboArm] moveL failed: invalid tcp_frame pose: " +
|
||||
selected_tcp_frame);
|
||||
}
|
||||
const int tcp_ret = robot_config->setTcpOffset(tcp_offset);
|
||||
const auto actual_tcp=robot_config->getTcpOffset();
|
||||
bool same_tcp=actual_tcp.size()==6;
|
||||
if(same_tcp)for(std::size_t i=0;i<6;++i)same_tcp=same_tcp&&std::isfinite(actual_tcp[i])&&std::abs(actual_tcp[i]-tcp_offset[i])<=1e-9;
|
||||
const int tcp_ret = same_tcp ? arcs::common_interface::AUBO_OK : robot_config->setTcpOffset(tcp_offset);
|
||||
if (tcp_ret != arcs::common_interface::AUBO_OK) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
@ -1394,6 +1490,37 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
}
|
||||
|
||||
std::vector<double> pose{target.x, target.y, target.z, target.rx, target.ry, target.rz};
|
||||
std::vector<double> selected_user;std::vector<double> selected_tcp;
|
||||
const bool selected=user_coordinates_active_.load();
|
||||
if(selected){std::lock_guard<std::mutex> lock(user_coordinate_mutex_);selected_user=applied_base_user_pose_;selected_tcp=applied_tcp_offset_;}
|
||||
if(selected && (selected_user.size()!=6 || selected_tcp.size()!=6))return Result::failure(ArmErrorCode::CommandRejected,"coordinate application is incomplete");
|
||||
if(selected && actual_tcp.size()!=6)return Result::failure(ArmErrorCode::CommandFailed,"TCP readback unavailable");
|
||||
if(selected)for(int i=0;i<6;++i)if(!std::isfinite(actual_tcp[i]) || std::abs(actual_tcp[i]-selected_tcp[i])>1e-8)
|
||||
return Result::failure(ArmErrorCode::CommandRejected,"TCP changed after Apply; reapply coordinate");
|
||||
auto math=sdk_->rpc_client->getMath();
|
||||
if(relative_translation) {
|
||||
const auto current=robot_interface->getRobotState()->getTcpPose();
|
||||
if(current.size()!=6 || !std::all_of(current.begin(),current.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"actual TCP unavailable");
|
||||
const auto reference=builtin_tool_reference_.load()?current:selected_user;
|
||||
pose=coordinateTranslationTarget(current,reference,pose,
|
||||
[&math](const auto& a,const auto& b){return math->poseTrans(a,b);});
|
||||
} else if (builtin_tool_reference_.load() && !user_pose) {
|
||||
// A tool-relative MoveL is an increment from the CURRENT TCP.
|
||||
// WorkObject is base for this mode; compose once at command start.
|
||||
if(!robot_interface->getRobotState() || !sdk_->rpc_client->getMath())
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,"tool-relative MoveL requires robot state and math interfaces");
|
||||
const auto current=robot_interface->getRobotState()->getTcpPose();
|
||||
if(current.size()!=6 || !std::all_of(current.begin(),current.end(),[](double x){return std::isfinite(x);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"invalid current TCP pose for tool-relative MoveL");
|
||||
pose=sdk_->rpc_client->getMath()->poseTrans(current,pose);
|
||||
if(pose.size()!=6 || !std::all_of(pose.begin(),pose.end(),[](double x){return std::isfinite(x);}))
|
||||
return Result::failure(ArmErrorCode::CommandFailed,"invalid tool-relative MoveL target");
|
||||
}
|
||||
if(!relative_translation && !builtin_tool_reference_.load() && (user_pose || selected))
|
||||
pose=math->poseTrans(user_pose?*user_pose:selected_user,pose);
|
||||
if(pose.size()!=6 || !std::all_of(pose.begin(),pose.end(),[](double v){return std::isfinite(v);}))
|
||||
return Result::failure(ArmErrorCode::InvalidArgument,"invalid SDK-transformed MoveL target");
|
||||
if (selected_base_frame != "base") {
|
||||
pose = sync_move->frameConvertPose(
|
||||
pose, selected_base_frame, "base");
|
||||
@ -1414,6 +1541,14 @@ Result AuboArm::moveL(const CartesianPose& target,
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[AuboArm] moveL canceled before submission");
|
||||
}
|
||||
// Targets are now explicitly in Base. Neutralize the native WorkObject
|
||||
// to prevent a second transformation on controllers which consume it.
|
||||
if(selected || user_pose) {
|
||||
const auto base_result=configureWorkObject_(std::vector<double>(6,0.0),false);
|
||||
if(!base_result.ok()){user_coordinates_active_.store(false);return base_result;}
|
||||
}
|
||||
if(canceled())return Result::failure(ArmErrorCode::CommandRejected,"[AuboArm] moveL cancelled after native coordinate setup");
|
||||
CMVR_LOG(DEBUG)<<"[AuboArm] SDK Math Base MoveL target=["<<pose[0]<<","<<pose[1]<<","<<pose[2]<<","<<pose[3]<<","<<pose[4]<<","<<pose[5]<<"], work_object_active="<<user_coordinates_active_.load();
|
||||
const int ret = motion_control->moveLine(
|
||||
pose,
|
||||
options.acceleration > 0.0 ? options.acceleration : 0.5,
|
||||
@ -1498,7 +1633,7 @@ Result AuboArm::speedL(const CartesianVelocity& velocity, double acceleration, d
|
||||
velocity.vx, velocity.vy, velocity.vz, 0.0, 0.0, 0.0};
|
||||
std::vector<double> angular_velocity{
|
||||
velocity.wx, velocity.wy, velocity.wz, 0.0, 0.0, 0.0};
|
||||
if (frame == FrameType::Tool) {
|
||||
if (frame == FrameType::Tool || builtin_tool_reference_.load()) {
|
||||
if (!robot_interface->getRobotState()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
@ -1783,6 +1918,12 @@ Result AuboArm::connect(const std::string& ip, const int port)
|
||||
|
||||
Result AuboArm::disconnect()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(user_coordinate_mutex_);
|
||||
user_coordinates_active_.store(false);builtin_tool_reference_.store(false);
|
||||
applied_user_coordinate_name_.clear();applied_user_coordinate_revision_=0;
|
||||
applied_base_user_pose_.clear();applied_tcp_offset_.clear();
|
||||
}
|
||||
(void)stopTrajectoryRecording();
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (sdk_) {
|
||||
@ -2235,9 +2376,18 @@ std::vector<double> AuboArm::ik(const std::string& base_link,
|
||||
|
||||
CartesianPose AuboArm::fk(const std::string& base_link, const std::string& ee_link)
|
||||
{
|
||||
(void)base_link;
|
||||
(void)ee_link;
|
||||
return fk(true);
|
||||
// Never silently label a base-frame result as a requested user/world frame.
|
||||
// The SDK RobotState getters below always report poses relative to base.
|
||||
const bool base = base_link.empty() || base_link=="base" ||
|
||||
base_link=="__builtin_base__" ||
|
||||
(!vendor_cfg_.base_frame().empty() && base_link==vendor_cfg_.base_frame());
|
||||
if(!base)throw std::invalid_argument(
|
||||
"GetPose: this reference is not supported by the native SDK pose query: "+base_link+
|
||||
"; request base explicitly; no coordinate conversion has been performed");
|
||||
if(ee_link=="flange" || ee_link=="tool0")return fk(false);
|
||||
if(ee_link.empty() || ee_link=="tcp" ||
|
||||
(!vendor_cfg_.tool_frame().empty() && ee_link==vendor_cfg_.tool_frame()))return fk(true);
|
||||
throw std::invalid_argument("GetPose: unsupported end frame: "+ee_link);
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(bool is_tcp)
|
||||
|
||||
@ -235,6 +235,17 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
safety == arcs::common_interface::SafetyModeType::ReducedMode, "robot safety state does not allow replay");
|
||||
};
|
||||
check();
|
||||
if (to_start) {
|
||||
// Plan a new rest-to-rest transfer from real feedback to the CSV
|
||||
// start. Recording duration and replay percentage do not govern it.
|
||||
const auto current = robot->getRobotState()->getJointPositions();
|
||||
require(current.size() == model_.dof, "current joint positions unavailable");
|
||||
const auto target = source.points.front();
|
||||
source.points = {current, target};
|
||||
source.times = {0.0, 0.02};
|
||||
source.frequency = 100;
|
||||
trajectory = source;
|
||||
}
|
||||
const auto lower = robot->getRobotConfig()->getJointMinPositions();
|
||||
const auto upper = robot->getRobotConfig()->getJointMaxPositions();
|
||||
require(lower.size() == model_.dof && upper.size() == model_.dof, "joint limits unavailable");
|
||||
@ -242,7 +253,7 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
require(std::isfinite(lower[j]) && std::isfinite(upper[j]) && lower[j] < upper[j] &&
|
||||
q[j] >= lower[j] && q[j] <= upper[j], "trajectory exceeds controller joint limits");
|
||||
auto motion = robot->getMotionControl();
|
||||
if (!to_start) {
|
||||
{
|
||||
MotionOptions limits = options;
|
||||
const auto vmax = robot->getRobotConfig()->getJointMaxSpeeds();
|
||||
const auto amax = robot->getRobotConfig()->getJointMaxAccelerations();
|
||||
@ -279,10 +290,11 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
timed.times = {0.0, 0.01, 0.02};
|
||||
timed.points = {timed.points.front(), last, last};
|
||||
}
|
||||
const double stretch = std::max(1.0, source.times.back() / timed.times.back());
|
||||
const double stretch = to_start ? 1.0 : std::max(1.0, source.times.back() / timed.times.back());
|
||||
const double time_scale = stretch / (to_start ? 1.0 : ratio);
|
||||
trajectory = aubo_csv::resample(timed, 1.0);
|
||||
trajectory.frequency /= stretch / ratio;
|
||||
for (auto& t : trajectory.times) t *= stretch / ratio;
|
||||
trajectory.frequency /= time_scale;
|
||||
for (auto& t : trajectory.times) t *= time_scale;
|
||||
// The B-spline may round corners: recheck generated positions, not
|
||||
// merely the source samples. SDK evaluates the final path too.
|
||||
for (const auto& q : trajectory.points) for (std::size_t j = 0; j < q.size(); ++j)
|
||||
@ -295,13 +307,11 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
if (!std::isfinite(q[j]) || std::abs(q[j] - target[j]) > 0.01) return false;
|
||||
return true;
|
||||
};
|
||||
double expected_duration = 120;
|
||||
if (to_start) {
|
||||
check();
|
||||
submitted = true;
|
||||
require(motion->moveJoint(trajectory.points.front(), 0.1, 0.1, 0, 0) == 0, "move to start rejected");
|
||||
} else {
|
||||
require(near(trajectory.points.front()), "not at trajectory start; use MoveToTrajectoryStart first");
|
||||
const double expected_duration = trajectory.times.back() + 30;
|
||||
{
|
||||
require(near(trajectory.points.front()), to_start
|
||||
? "robot moved while planning move to start; retry from standstill"
|
||||
: "not at trajectory start; use MoveToTrajectoryStart first");
|
||||
// A unique, service-owned buffer never overwrites a user SDK buffer.
|
||||
buffer = "cmvr_csv_" + std::to_string(::getpid()) + "_" + std::to_string(token);
|
||||
require(motion->pathBufferAlloc(buffer, 2, static_cast<int>(trajectory.points.size())) == 0,
|
||||
@ -323,7 +333,6 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
require(near(trajectory.points.front()), "robot moved away from trajectory start");
|
||||
submitted = true;
|
||||
require(motion->movePathBuffer(buffer) == 0, "movePathBuffer rejected");
|
||||
expected_duration = trajectory.times.back() + 30;
|
||||
}
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
bool observed_motion = false;
|
||||
@ -332,8 +341,8 @@ Result AuboArm::replayRecordedTrajectory(const std::string& name, double ratio,
|
||||
const int exec = motion->getExecId();
|
||||
observed_motion = observed_motion || exec >= 0;
|
||||
const double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - started).count();
|
||||
const auto& target = to_start ? trajectory.points.front() : trajectory.points.back();
|
||||
if (exec < 0 && (observed_motion || elapsed >= (to_start ? 1.0 : trajectory.times.back())) && near(target)) break;
|
||||
const auto& target = trajectory.points.back();
|
||||
if (exec < 0 && (observed_motion || elapsed >= trajectory.times.back()) && near(target)) break;
|
||||
require(elapsed < expected_duration, "trajectory motion did not complete within deadline");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
#include "devices/arm/aubo_arm/include/user_coordinate_store.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
using namespace cmvr::device;
|
||||
#define CHECK(x) do{if(!(x)){std::cerr<<"FAIL line "<<__LINE__<<": "<<#x<<'\n';return 1;}}while(false)
|
||||
template<class F>bool rejects(F f,CoordinateStoreError::Kind kind){try{f();}catch(const CoordinateStoreError& e){return e.kind==kind;}return false;}
|
||||
int main(){
|
||||
char pattern[]="/tmp/cmvr-user-coordinates-test.XXXXXX";const char* directory=::mkdtemp(pattern);CHECK(directory);
|
||||
const std::filesystem::path path(directory);UserCoordinateStore store(path);
|
||||
CHECK(store.list().empty());
|
||||
UserCoordinateProfile p;p.name=u8"正方形";p.user_pose.assign(6,0);p.tcp_offset.assign(6,0);p.calibration_points={{0,0,0,0,0,0},{.1,0,0,0,0,0},{0,.1,0,0,0,0}};
|
||||
p=store.mutate("create",p);CHECK(p.revision>0&&store.list().size()==1);
|
||||
CHECK(rejects([&]{store.mutate("create",p);},CoordinateStoreError::Exists));
|
||||
auto changed=p;changed.user_pose[0]=.1;for(auto& point:changed.calibration_points)point[0]+=.1;changed=store.mutate("update",changed,p.revision);
|
||||
CHECK(changed.revision>p.revision&&store.get(p.name).user_pose[0]==.1);
|
||||
CHECK(rejects([&]{store.mutate("update",p,p.revision);},CoordinateStoreError::Conflict));
|
||||
CHECK(rejects([&]{store.mutate("delete",p,p.revision);},CoordinateStoreError::Conflict));
|
||||
CHECK(rejects([&]{store.get(p.name,p.revision);},CoordinateStoreError::Conflict));
|
||||
auto invalid=p;invalid.user_pose[0]=std::numeric_limits<double>::quiet_NaN();
|
||||
CHECK(rejects([&]{store.mutate("create",invalid);},CoordinateStoreError::Invalid));
|
||||
CHECK(rejects([&]{UserCoordinateStore::forArm("../../etc");},CoordinateStoreError::Invalid));
|
||||
std::atomic<bool> good{true};
|
||||
const auto create=[&](int id){try{auto other=p;other.name="parallel_"+std::to_string(id);store.mutate("create",other);}catch(...){good=false;}};
|
||||
std::thread one(create,1),two(create,2);one.join();two.join();CHECK(good&&store.list().size()==3);
|
||||
CHECK(UserCoordinateStore(path/"other_arm").list().empty());
|
||||
store.mutate("delete",changed,changed.revision);CHECK(store.list().size()==2);
|
||||
CHECK(rejects([&]{store.get(p.name);},CoordinateStoreError::Missing));
|
||||
{std::ofstream file(path/"coordinates.json");file<<"{\"version\":1,\"next_revision\":100,\"coordinates\":[]}";}
|
||||
CHECK(store.list().empty());const auto fresh=store.mutate("create",p);CHECK(fresh.revision==100);
|
||||
{std::ofstream file(path/"coordinates.json");file<<"{broken";}
|
||||
CHECK(rejects([&]{store.mutate("create",p);},CoordinateStoreError::Storage));
|
||||
std::ifstream file(path/"coordinates.json");std::string content((std::istreambuf_iterator<char>(file)),{});CHECK(content=="{broken");
|
||||
std::cout<<"PASS: CRUD, revisions, concurrency, isolation, invalid input and corrupted-file preservation\n";
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#define CHECK(x) do {if(!(x)){std::cerr<<"FAIL line "<<__LINE__<<": "<<#x<<'\n';return 1;}}while(false)
|
||||
int main() {
|
||||
cmvr::config::RobotArmConfig config;config.set_id("offline_test");
|
||||
cmvr::device::AuboArm arm(config); // Never init/connect or send hardware commands.
|
||||
cmvr::device::MotionOptions limits;limits.velocity=.05;limits.acceleration=.1;
|
||||
cmvr::device::CartesianPose target{};std::vector<double> zero(6,0);
|
||||
CHECK(!arm.isConnected());
|
||||
std::vector<std::string> frames{"stale"};
|
||||
auto unsupported=arm.listBaseFrame(frames);
|
||||
CHECK(!unsupported.ok()&&unsupported.code==cmvr::device::ArmErrorCode::UnsupportedCommand&&frames.empty());
|
||||
frames={"stale"};unsupported=arm.listTCPFrame(frames);
|
||||
CHECK(!unsupported.ok()&&unsupported.code==cmvr::device::ArmErrorCode::UnsupportedCommand&&frames.empty());
|
||||
auto r=arm.moveLInUserFrame(target,limits,{0},zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
r=arm.moveLInUserFrame(target,limits,zero,{0});
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
auto nan=zero;nan[3]=std::numeric_limits<double>::quiet_NaN();
|
||||
r=arm.moveLInUserFrame(target,limits,nan,zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
limits.velocity=-1;r=arm.moveLInUserFrame(target,limits,zero,zero);
|
||||
CHECK(!r.ok()&&r.code==cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
limits.velocity=.05;r=arm.moveLInUserFrame(target,limits,zero,zero);
|
||||
CHECK(!r.ok()&&r.code!=cmvr::device::ArmErrorCode::InvalidArgument);
|
||||
std::string response;
|
||||
CHECK(!arm.executeJsonCommand("{\"command\":\"apply_user_coordinates\",\"user_pose\":[0],\"tcp_offset\":[0,0,0,0,0,0]}",response));
|
||||
CHECK(response.find("invalid_argument")!=std::string::npos);
|
||||
CHECK(!arm.isConnected());
|
||||
std::cout<<"PASS: explicit-frame validation and disconnected rejection, no SDK initialization\n";
|
||||
}
|
||||
@ -91,6 +91,14 @@ public:
|
||||
api::CommandHeader_Feedback* response) override;
|
||||
|
||||
private:
|
||||
grpc::Status CalibrateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status CreateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status GetUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status ListUserCoordinateSystems(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status UpdateUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status DeleteUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status ApplyUserCoordinateSystem(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*) override;
|
||||
grpc::Status coordinateCommand(grpc::ServerContext*, const api::UserCoordinateSystemCommand_Request*, api::UserCoordinateSystemCommand_Response*, const std::string& operation);
|
||||
grpc::Status ListRecordedTrajectories(grpc::ServerContext*,
|
||||
const api::ListRecordedTrajectories_Request*, api::ListRecordedTrajectories_Response*) override;
|
||||
grpc::Status MoveToTrajectoryStart(grpc::ServerContext*,
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
#include "service/grpc/include/grpc_arm_service.h"
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/include/user_coordinate_store.h"
|
||||
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
|
||||
@ -350,7 +352,30 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
<< ", velocity=" << options.velocity
|
||||
<< ", acceleration=" << options.acceleration
|
||||
<< ", frame=" << request->frame();
|
||||
const auto result = has_named_frame
|
||||
const bool explicit_user_frame = request->user_frame_pose_size() || request->tcp_offset_size();
|
||||
device::Result result;
|
||||
if(request->coordinate_relative_translation() && request->user_coordinate_name().empty())return setResponseResult(response,device::Result::failure(device::ArmErrorCode::InvalidArgument,"relative translation requires named applied coordinate"));
|
||||
if (!request->user_coordinate_name().empty()) {
|
||||
auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if(!aubo || has_named_frame || explicit_user_frame)
|
||||
return setResponseResult(response,device::Result::failure(device::ArmErrorCode::InvalidArgument,"saved user coordinates cannot combine with explicit frame parameters and require AUBO"));
|
||||
const auto profile=device::UserCoordinateStore::forArm(device_id).get(request->user_coordinate_name(),request->user_coordinate_revision());
|
||||
if(!aubo->currentUserCoordinateMatches(profile.name,profile.revision))
|
||||
return setResponseResult(response,device::Result::failure(device::ArmErrorCode::CommandRejected,"requested coordinate is not currently applied; call ApplyUserCoordinateSystem first"));
|
||||
result=request->coordinate_relative_translation()
|
||||
? aubo->moveLRelativeInCoordinate(toCartesianPose(request->target()),options)
|
||||
: arm->moveL(toCartesianPose(request->target()),options,device::FrameType::Base);
|
||||
} else if (explicit_user_frame) {
|
||||
auto aubo = std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if (!aubo || has_named_frame) {
|
||||
result = device::Result::failure(device::ArmErrorCode::InvalidArgument,
|
||||
"explicit user frames require AUBO and cannot combine with named frames");
|
||||
} else {
|
||||
result = aubo->moveLInUserFrame(toCartesianPose(request->target()), options,
|
||||
std::vector<double>(request->user_frame_pose().begin(),request->user_frame_pose().end()),
|
||||
std::vector<double>(request->tcp_offset().begin(),request->tcp_offset().end()));
|
||||
}
|
||||
} else result = has_named_frame
|
||||
? arm->moveL(toCartesianPose(request->target()),
|
||||
options,
|
||||
request->has_base_frame()
|
||||
@ -378,6 +403,10 @@ grpc::Status gRPCArmServiceImpl::moveL(grpc::ServerContext* context,
|
||||
<< device_id << ", error=" << result.message;
|
||||
}
|
||||
return setResponseResult(response, result);
|
||||
} catch (const device::CoordinateStoreError& e) {
|
||||
fillFeedback(response->mutable_header(),false,e.what());
|
||||
return grpc::Status(e.kind==device::CoordinateStoreError::Missing?grpc::StatusCode::NOT_FOUND:
|
||||
e.kind==device::CoordinateStoreError::Conflict?grpc::StatusCode::ABORTED:grpc::StatusCode::INVALID_ARGUMENT,e.what());
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
@ -647,15 +676,24 @@ grpc::Status gRPCArmServiceImpl::getPose(grpc::ServerContext*,
|
||||
if (!arm) {
|
||||
return setDeviceNotFound(response, device_id);
|
||||
}
|
||||
const auto pose = request->base_link().empty() || request->ee_link().empty()
|
||||
const auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
const auto pose = aubo ? aubo->fk(request->base_link(),request->ee_link())
|
||||
: request->base_link().empty() || request->ee_link().empty()
|
||||
? arm->fk(true)
|
||||
: arm->fk(request->base_link(), request->ee_link());
|
||||
*response->mutable_pose() = toApiCartesianPose(pose);
|
||||
if(aubo){
|
||||
response->set_reference_frame("base");
|
||||
response->set_end_frame(request->ee_link()=="flange"||request->ee_link()=="tool0"?"flange":"tcp");
|
||||
}
|
||||
fillFeedback(response->mutable_header(), true);
|
||||
CMVR_LOG(DEBUG) << "[gRPCArmServiceImpl] (getPose): success, id=" << device_id
|
||||
<< ", pose=(" << pose.x << ", " << pose.y << ", " << pose.z
|
||||
<< ", " << pose.rx << ", " << pose.ry << ", " << pose.rz << ")";
|
||||
return grpc::Status::OK;
|
||||
} catch (const std::invalid_argument& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
|
||||
} catch (const std::exception& e) {
|
||||
fillFeedback(response->mutable_header(), false, e.what());
|
||||
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
||||
@ -908,4 +946,83 @@ grpc::Status gRPCArmServiceImpl::replayTrajectory(grpc::ServerContext* context,
|
||||
}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::coordinateCommand(grpc::ServerContext* context,
|
||||
const api::UserCoordinateSystemCommand_Request* request,
|
||||
api::UserCoordinateSystemCommand_Response* response,const std::string& operation)
|
||||
{
|
||||
try {
|
||||
if(context && context->IsCancelled())return grpc::Status(grpc::StatusCode::CANCELLED,"request cancelled");
|
||||
const auto id=request->header().device_id();
|
||||
auto arm=dmgr_.getDevice<device::RobotArm>(id);
|
||||
if(!arm)return setDeviceNotFound(response,id);
|
||||
auto aubo=std::dynamic_pointer_cast<device::AuboArm>(arm);
|
||||
if(!aubo)return setResponseResult(response,device::Result::failure(device::ArmErrorCode::UnsupportedCommand,"user coordinate management requires AUBO"));
|
||||
auto store=device::UserCoordinateStore::forArm(id);
|
||||
const auto output=[](const device::UserCoordinateProfile& p,api::UserCoordinateSystem* value) {
|
||||
value->set_name(p.name);value->set_revision(p.revision);
|
||||
for(double x:p.user_pose)value->add_user_pose(x);
|
||||
for(double x:p.tcp_offset)value->add_tcp_offset(x);
|
||||
value->set_calibration_version(2);
|
||||
for(const auto& point:p.calibration_points){auto* v=value->add_calibration_points()->mutable_base_tcp_pose();v->set_x(point[0]);v->set_y(point[1]);v->set_z(point[2]);v->set_rx(point[3]);v->set_ry(point[4]);v->set_rz(point[5]);}
|
||||
};
|
||||
if(operation=="list") {
|
||||
output(device::UserCoordinateStore::builtin("__builtin_base__"),response->add_coordinates());
|
||||
output(device::UserCoordinateStore::builtin("__builtin_tool__"),response->add_coordinates());
|
||||
for(const auto& p:store.list())output(p,response->add_coordinates());
|
||||
}
|
||||
else {
|
||||
device::UserCoordinateProfile p;
|
||||
if(operation=="create"||operation=="update"||operation=="calibrate") {
|
||||
p.name=request->coordinate().name();
|
||||
p.user_pose.assign(request->coordinate().user_pose().begin(),request->coordinate().user_pose().end());
|
||||
p.tcp_offset.assign(request->coordinate().tcp_offset().begin(),request->coordinate().tcp_offset().end());
|
||||
for(const auto& v:request->coordinate().calibration_points()){
|
||||
if(!v.has_base_tcp_pose())return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,"calibration point is missing base_tcp_pose");
|
||||
const auto& x=v.base_tcp_pose();p.calibration_points.push_back({x.x(),x.y(),x.z(),x.rx(),x.ry(),x.rz()});
|
||||
}
|
||||
if(request->coordinate().calibration_version()!=2)return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,"three-point coordinate API version 2 required; retired manual records are not accepted");
|
||||
const auto calibrated=aubo->calibrateUserCoordinate(p.calibration_points,p.user_pose);
|
||||
if(!calibrated.ok())return setResponseResult(response,calibrated);
|
||||
if(operation!="calibrate")p=store.mutate(operation,p,request->expected_revision());
|
||||
} else if(operation=="delete") {
|
||||
p.name=request->name();p=store.mutate(operation,p,request->expected_revision());
|
||||
} else {
|
||||
p=store.get(request->name(),request->expected_revision());
|
||||
if(operation=="apply") {
|
||||
auto lease=ControlCommandArbiter::instance().tryAcquireControl();
|
||||
if(!lease)return setControlBusy(response);
|
||||
std::vector<double> actual;
|
||||
const auto result=device::UserCoordinateStore::isBuiltin(p.name)
|
||||
? aubo->applyBuiltinCoordinate(p.name,actual)
|
||||
: aubo->applyUserCoordinates(p.user_pose,p.tcp_offset,actual,p.name,p.revision);
|
||||
if(!result.ok())return setResponseResult(response,result);
|
||||
for(double x:actual)response->add_actual_tcp_offset(x);
|
||||
response->set_work_object_acknowledged(true);
|
||||
}
|
||||
}
|
||||
output(p,response->mutable_coordinate());
|
||||
}
|
||||
std::string applied;std::uint64_t revision{};
|
||||
response->set_application_known(aubo->lastAppliedUserCoordinate(applied,revision));
|
||||
response->set_last_applied_name(applied);response->set_last_applied_revision(revision);
|
||||
CMVR_LOG(DEBUG)<<"[gRPCArmServiceImpl] ("<<operation<<"UserCoordinateSystem): success, id="<<id;
|
||||
fillFeedback(response->mutable_header(),true);return grpc::Status::OK;
|
||||
}catch(const device::CoordinateStoreError& e){
|
||||
fillFeedback(response->mutable_header(),false,e.what());
|
||||
const auto code=e.kind==device::CoordinateStoreError::Missing?grpc::StatusCode::NOT_FOUND:
|
||||
e.kind==device::CoordinateStoreError::Exists?grpc::StatusCode::ALREADY_EXISTS:
|
||||
e.kind==device::CoordinateStoreError::Conflict?grpc::StatusCode::ABORTED:
|
||||
e.kind==device::CoordinateStoreError::Invalid?grpc::StatusCode::INVALID_ARGUMENT:grpc::StatusCode::INTERNAL;
|
||||
return grpc::Status(code,e.what());
|
||||
}catch(const std::exception& e){fillFeedback(response->mutable_header(),false,e.what());return grpc::Status(grpc::StatusCode::INTERNAL,e.what());}
|
||||
}
|
||||
|
||||
grpc::Status gRPCArmServiceImpl::CalibrateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"calibrate");}
|
||||
grpc::Status gRPCArmServiceImpl::CreateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"create");}
|
||||
grpc::Status gRPCArmServiceImpl::GetUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"get");}
|
||||
grpc::Status gRPCArmServiceImpl::ListUserCoordinateSystems(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"list");}
|
||||
grpc::Status gRPCArmServiceImpl::UpdateUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"update");}
|
||||
grpc::Status gRPCArmServiceImpl::DeleteUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"delete");}
|
||||
grpc::Status gRPCArmServiceImpl::ApplyUserCoordinateSystem(grpc::ServerContext* c,const api::UserCoordinateSystemCommand_Request* q,api::UserCoordinateSystemCommand_Response* r){return coordinateCommand(c,q,r,"apply");}
|
||||
|
||||
} // namespace cmvr::service
|
||||
|
||||
@ -149,6 +149,54 @@ message MoveJ {
|
||||
}
|
||||
|
||||
// TCP 笛卡尔直线运动命令。
|
||||
// 服务端持久化记录。名称仅用于服务端查找,不是示教器命名坐标系。
|
||||
message CoordinateCalibrationPoint {
|
||||
// Actual TCP pose in Base, m/rad. Three points: origin, +X, XY plane (+Y).
|
||||
CartesianPose base_tcp_pose = 1;
|
||||
}
|
||||
message UserCoordinateSystem {
|
||||
// 内置记录标识:__builtin_base__(基座)、__builtin_tool__(工具)。
|
||||
// List/Get 默认提供,revision 固定为 1;禁止 Create/Update/Delete。
|
||||
// 内置记录的 user_pose/tcp_offset 全零仅作协议占位,不是实际 TCP 回读。
|
||||
// Apply 保留当前 TCP 偏移,恢复基座 WorkObject;工具模式每次 MoveL
|
||||
// 将 target 解释为相对下发时当前 TCP 的位姿增量,基座模式为绝对位姿。
|
||||
string name = 1;
|
||||
// 服务端 SDK 三点标定结果 T_base_user,[x,y,z,rx,ry,rz],m/rad,RzRyRx。
|
||||
// Create/Update 不采用客户端提供的该字段,只采用 calibration_points 重新计算。
|
||||
repeated double user_pose = 2;
|
||||
// T_flange_tcp,维度、单位及姿态约定同上。
|
||||
repeated double tcp_offset = 3;
|
||||
// 由服务端分配,创建后单调递增;客户端不能自行设置版本。
|
||||
uint64 revision = 4;
|
||||
// Required for custom Create/Update; user_pose is computed by server, never trusted as input.
|
||||
repeated CoordinateCalibrationPoint calibration_points = 5;
|
||||
uint32 calibration_version = 6;
|
||||
}
|
||||
message UserCoordinateSystemCommand {
|
||||
message Request {
|
||||
CommandHeader.Request header = 1;
|
||||
// Create/Update 使用 coordinate;名称不变,修改名称请新建后删除原记录。
|
||||
UserCoordinateSystem coordinate = 2;
|
||||
// Get/Delete/Apply 使用 name;List 不需要名称。
|
||||
string name = 3;
|
||||
// Update/Delete 必须等于当前版本;Apply 为 0 时使用最新版本。
|
||||
uint64 expected_revision = 4;
|
||||
}
|
||||
message Response {
|
||||
CommandHeader.Feedback header = 1;
|
||||
// Create/Get/Update/Delete/Apply 返回处理的记录。
|
||||
UserCoordinateSystem coordinate = 2;
|
||||
// List 返回所有记录;查询和 CRUD 不设置控制器、不运动。
|
||||
repeated UserCoordinateSystem coordinates = 3;
|
||||
// Apply 成功后实际回读的 TCP。工件坐标没有完整回读接口,SDK成功码并非持久化证明。
|
||||
repeated double actual_tcp_offset = 4;
|
||||
bool work_object_acknowledged = 5;
|
||||
// 本服务本次运行中最后成功应用的记录;不是 SDK 工件坐标实时回读。
|
||||
string last_applied_name = 6;
|
||||
uint64 last_applied_revision = 7;
|
||||
bool application_known = 8;
|
||||
}
|
||||
}
|
||||
message MoveL {
|
||||
// MoveL 请求。
|
||||
message Request {
|
||||
@ -164,6 +212,21 @@ message MoveL {
|
||||
optional string base_frame = 5;
|
||||
// 可选 TCP 坐标系名称,无单位;不传或为空时使用驱动配置的默认 TCP 坐标系。
|
||||
optional string tcp_frame = 6;
|
||||
// AUBO explicit host-managed user frame T_base_user, [x,y,z,rx,ry,rz], m/rad.
|
||||
// Both vectors must contain six finite values; cannot combine with named frames.
|
||||
// Compatibility path: configures SDK setWorkObjectData, not pendant persistence.
|
||||
// Prefer server CRUD + ApplyUserCoordinateSystem for named managed records.
|
||||
repeated double user_frame_pose = 7;
|
||||
// T_flange_tcp, [x,y,z,rx,ry,rz], m/rad. Required together with user_frame_pose.
|
||||
repeated double tcp_offset = 8;
|
||||
// 校验当前已应用的服务端坐标系名称,不自动切换;请先调用 ApplyUserCoordinateSystem。
|
||||
// 不传时沿用 SDK 当前工件系;不能与显式位姿或命名世界坐标系同时传入。
|
||||
string user_coordinate_name = 9;
|
||||
// 所选记录的版本号,非零时拒绝执行已被修改的记录。
|
||||
uint64 user_coordinate_revision = 10;
|
||||
// Translate from current actual TCP along selected frame axes; target.rx/ry/rz must be zero.
|
||||
// Target xyz is a displacement in metres, orientation is held unchanged.
|
||||
bool coordinate_relative_translation = 11;
|
||||
}
|
||||
|
||||
// MoveL 执行结果。
|
||||
@ -404,6 +467,11 @@ message GetPose {
|
||||
CommandHeader.Feedback header = 1;
|
||||
// TCP 位姿;位置单位为 m,姿态单位为 rad。
|
||||
CartesianPose pose = 2;
|
||||
// 实际返回值的参考坐标系。遨博原生 RobotState 反馈固定为 base,
|
||||
// 不会仅因 setWorkObjectData 被调用就变成用户坐标系。
|
||||
string reference_frame = 3;
|
||||
// 实际返回的末端:tcp 为当前工具中心点,flange 为法兰。
|
||||
string end_frame = 4;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -57,8 +57,20 @@ service ArmService {
|
||||
rpc ExitTeachingMode(CommandHeader.Request) returns (CommandHeader.Feedback);
|
||||
// 查询 CSV 轨迹及当前录制状态,不启动采样或运动。
|
||||
rpc ListRecordedTrajectories(ListRecordedTrajectories.Request) returns (ListRecordedTrajectories.Response);
|
||||
// 低速到所选轨迹起点(0.1 rad/s,0.1 rad/s²);必须退出示教且已使能。
|
||||
// 按请求的速度、加速度、加加速度限值平滑运动到轨迹起点;必须退出示教且已使能。
|
||||
rpc MoveToTrajectoryStart(ReplayRecordedTrajectory.Request) returns (ReplayRecordedTrajectory.Response);
|
||||
// 同步回放;必须先到达起点,结束后返回。取消请求会停止运动。
|
||||
rpc ReplayRecordedTrajectory(ReplayRecordedTrajectory.Request) returns (ReplayRecordedTrajectory.Response);
|
||||
// 以下记录保存在服务端程序目录 data/user_coordinates/<device_id>/coordinates.json。
|
||||
// Three-point SDK calibration only; no persistence, TCP write or movement.
|
||||
rpc CalibrateUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
rpc CreateUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
rpc GetUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
rpc ListUserCoordinateSystems(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
rpc UpdateUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
rpc DeleteUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
// 实际调用 setWorkObjectData + setTcpOffset,并在服务端记住当前选择。
|
||||
// MoveL 通过 SDK Math 将所选工件系目标转换至 Base;提交前中和原生 WorkObject,避免重复变换。
|
||||
// 不运动、不写示教器命名配置库;SDK 工件系无完整回读,重连/服务重启后应重新应用。
|
||||
rpc ApplyUserCoordinateSystem(UserCoordinateSystemCommand.Request) returns (UserCoordinateSystemCommand.Response);
|
||||
}
|
||||
|
||||
12
scripts/systemd/cmvr-es.service.d/10-device-readiness.conf
Normal file
12
scripts/systemd/cmvr-es.service.d/10-device-readiness.conf
Normal file
@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
# Devices may be powered later than this PC. Do not exhaust startup retries.
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
[Service]
|
||||
# network-online alone does not guarantee that device services accept TCP.
|
||||
ExecStartPre=/usr/bin/python3 /home/cmvr/project/cmvr-es/scripts/wait_network_devices.py --config-dir /home/cmvr/project/cmvr-es/output/bin/config --timeout 180 --stable-seconds 10
|
||||
# Check sockets owned by this process, not just a running PID or open gRPC port.
|
||||
ExecStartPost=/usr/bin/python3 /home/cmvr/project/cmvr-es/scripts/wait_network_devices.py --config-dir /home/cmvr/project/cmvr-es/output/bin/config --mode connected --pid $MAINPID --timeout 60 --stable-seconds 3
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=260
|
||||
93
scripts/test_wait_network_devices.py
Normal file
93
scripts/test_wait_network_devices.py
Normal file
@ -0,0 +1,93 @@
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import wait_network_devices as readiness
|
||||
|
||||
|
||||
class ReadinessTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / "manager").mkdir()
|
||||
(self.root / "devices").mkdir()
|
||||
(self.root / "manager/device_manager.pb.txt").write_text('''device_manager {
|
||||
devices { id: "aubo_arm" type: DEVICE_TYPE_ROBOT_ARM config_file: "devices/arm.pb.txt" enable: true }
|
||||
devices { id: "src1100" type: DEVICE_TYPE_AGV config_file: "devices/agv.pb.txt" enable: true }
|
||||
devices { id: "disabled" type: DEVICE_TYPE_AGV config_file: "not-present" enable: false }
|
||||
}''')
|
||||
(self.root / "devices/arm.pb.txt").write_text('''arm { robot_arms {
|
||||
id: "aubo_arm" vendor { brand: VENDOR_ROBOT_ARM_BRAND_AUBO_ARM ip: "192.168.192.18" port: 30004 }
|
||||
}}''')
|
||||
(self.root / "devices/agv.pb.txt").write_text('''agv {
|
||||
agvs { id: "unused" my_agv { ip: "127.0.0.1" port: 8080 } }
|
||||
agvs { id: "src1100" seer_robokit_agv {
|
||||
ip: "192.168.192.5" port_status: 19204 port_control: 19205
|
||||
port_nav: 19206 port_config: 19207 port_other: 19210 port_push: 19301 enable_state_push: true
|
||||
}}
|
||||
}''')
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def test_configured_devices_and_real_connections_only(self):
|
||||
values = readiness.endpoints(self.root)
|
||||
self.assertEqual([p.port for p in values], [30004, 19204, 19205, 19206, 19207, 19301])
|
||||
self.assertEqual(values[1].host, "192.168.192.5")
|
||||
|
||||
def test_disabled_devices_do_not_block(self):
|
||||
manager = self.root / "manager/device_manager.pb.txt"
|
||||
manager.write_text(manager.read_text().replace("enable: true", "enable: false"))
|
||||
self.assertEqual(readiness.endpoints(self.root), [])
|
||||
|
||||
def test_disabled_push_not_required(self):
|
||||
path = self.root / "devices/agv.pb.txt"
|
||||
path.write_text(path.read_text().replace("enable_state_push: true", "enable_state_push: false"))
|
||||
self.assertNotIn(19301, [e.port for e in readiness.endpoints(self.root)])
|
||||
|
||||
def test_missing_port_rejected(self):
|
||||
path = self.root / "devices/agv.pb.txt"
|
||||
path.write_text(path.read_text().replace("port_nav: 19206", ""))
|
||||
with self.assertRaises(ValueError):
|
||||
readiness.endpoints(self.root)
|
||||
|
||||
def test_quoted_braces_and_comments(self):
|
||||
text = '# devices { wrong }\nname: "devices { ignored }"\ndevices { id: "x}#//{" enable: true }'
|
||||
values = list(readiness.blocks(text, "devices"))
|
||||
self.assertEqual(len(values), 1)
|
||||
self.assertEqual(readiness.scalar(values[0], "id"), "x}#//{")
|
||||
|
||||
def test_path_escape_rejected(self):
|
||||
path = self.root / "manager/device_manager.pb.txt"
|
||||
path.write_text(path.read_text().replace("devices/arm.pb.txt", "../elsewhere"))
|
||||
with self.assertRaises(ValueError):
|
||||
readiness.endpoints(self.root)
|
||||
|
||||
def test_unavailable_times_out(self):
|
||||
with mock.patch.object(readiness, "reachable", return_value=False):
|
||||
self.assertFalse(readiness.wait_ready([readiness.Endpoint("x", "127.0.0.1", 1)], .03, .01, interval=.005))
|
||||
|
||||
def test_retries_then_stable(self):
|
||||
attempts = iter([False, False, True, True, True, True, True])
|
||||
with mock.patch.object(readiness, "reachable", side_effect=lambda _: next(attempts)):
|
||||
self.assertTrue(readiness.wait_ready([readiness.Endpoint("x", "127.0.0.1", 1)], .3, .01, interval=.01))
|
||||
|
||||
def test_only_connections_owned_by_main_process(self):
|
||||
with socket.socket() as server:
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.listen()
|
||||
port = server.getsockname()[1]
|
||||
with socket.create_connection(("127.0.0.1", port)) as client:
|
||||
accepted, _ = server.accept()
|
||||
with accepted:
|
||||
self.assertIn(("127.0.0.1", port), readiness.process_connections(os.getpid()))
|
||||
with mock.patch.object(readiness, "reachable", side_effect=AssertionError("must not probe devices")):
|
||||
self.assertTrue(readiness.wait_ready([readiness.Endpoint("x", "127.0.0.1", port)], .2, 0, "connected", os.getpid()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
197
scripts/wait_network_devices.py
Executable file
197
scripts/wait_network_devices.py
Executable file
@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Startup readiness only. Never sends device commands or restarts a running service."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Endpoint:
|
||||
device: str
|
||||
host: str
|
||||
port: int
|
||||
|
||||
def label(self):
|
||||
return f"{self.device} {self.host}:{self.port}"
|
||||
|
||||
|
||||
def uncomment(text):
|
||||
pattern = r'"(?:\\.|[^"\\])*"|\#[^\n]*|//[^\n]*'
|
||||
return re.sub(pattern, lambda m: m[0] if m[0].startswith('"') else "", text)
|
||||
|
||||
|
||||
def blocks(text, name):
|
||||
"""Read balanced named textproto blocks, preserving quoted braces."""
|
||||
text = uncomment(text)
|
||||
masked = re.sub(r'"(?:\\.|[^"\\])*"', lambda m: " " * len(m[0]), text)
|
||||
for match in re.finditer(r'\b' + re.escape(name) + r'\s*:?\s*\{', masked):
|
||||
start = match.end()
|
||||
depth, quoted, escape = 1, False, False
|
||||
for i in range(start, len(text)):
|
||||
c = text[i]
|
||||
if quoted:
|
||||
if escape:
|
||||
escape = False
|
||||
elif c == "\\":
|
||||
escape = True
|
||||
elif c == '"':
|
||||
quoted = False
|
||||
elif c == '"':
|
||||
quoted = True
|
||||
elif c == "{":
|
||||
depth += 1
|
||||
elif c == "}":
|
||||
depth -= 1
|
||||
if not depth:
|
||||
yield text[start:i]
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"unterminated {name} configuration block")
|
||||
|
||||
|
||||
def scalar(text, key, default=None):
|
||||
match = re.search(r'\b' + re.escape(key) + r'\s*:\s*("(?:\\.|[^"\\])*"|[^\s{};,]+)', uncomment(text))
|
||||
if not match:
|
||||
return default
|
||||
value = match[1]
|
||||
return json.loads(value) if value.startswith('"') else value
|
||||
|
||||
|
||||
def endpoints(config_dir):
|
||||
root = Path(config_dir).resolve()
|
||||
manager = (root / "manager/device_manager.pb.txt").read_text(encoding="utf-8")
|
||||
result = []
|
||||
for device in blocks(manager, "devices"):
|
||||
if scalar(device, "enable", "false") != "true":
|
||||
continue
|
||||
kind, identifier = scalar(device, "type"), scalar(device, "id")
|
||||
if kind not in ("DEVICE_TYPE_ROBOT_ARM", "DEVICE_TYPE_AGV"):
|
||||
continue
|
||||
relative = scalar(device, "config_file")
|
||||
if not relative:
|
||||
raise ValueError(f"missing config_file for {identifier}")
|
||||
path = (root / relative).resolve()
|
||||
if root not in path.parents:
|
||||
raise ValueError(f"config path outside runtime config: {identifier}")
|
||||
content = path.read_text(encoding="utf-8")
|
||||
candidates = [b for b in blocks(content, "robot_arms" if kind == "DEVICE_TYPE_ROBOT_ARM" else "agvs")
|
||||
if scalar(b, "id") == identifier]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f"expected one matching configuration for {identifier}")
|
||||
entry = candidates[0]
|
||||
if kind == "DEVICE_TYPE_ROBOT_ARM":
|
||||
vendor = next(blocks(entry, "vendor"), None)
|
||||
if not vendor or scalar(vendor, "brand") != "VENDOR_ROBOT_ARM_BRAND_AUBO_ARM":
|
||||
continue
|
||||
pairs = [(scalar(vendor, "ip"), scalar(vendor, "port", "30004"))]
|
||||
else:
|
||||
vendor = next(blocks(entry, "seer_robokit_agv"), None)
|
||||
if vendor is None:
|
||||
continue
|
||||
host = scalar(vendor, "ip")
|
||||
keys = ["port_status", "port_control", "port_nav", "port_config"]
|
||||
if scalar(vendor, "enable_state_push", "false") == "true":
|
||||
keys.append("port_push")
|
||||
pairs = [(host, scalar(vendor, key)) for key in keys]
|
||||
for host, port in pairs:
|
||||
if not host or not port or not 1 <= int(port) <= 65535:
|
||||
raise ValueError(f"missing or invalid network endpoint for {identifier}")
|
||||
ipaddress.IPv4Address(host)
|
||||
item = Endpoint(identifier, host, int(port))
|
||||
if item not in result:
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def reachable(endpoint):
|
||||
try:
|
||||
with socket.create_connection((endpoint.host, endpoint.port), timeout=1.5):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def process_connections(pid):
|
||||
directory = Path(f"/proc/{pid}")
|
||||
if not directory.exists():
|
||||
raise RuntimeError(f"main process {pid} exited during startup")
|
||||
inodes = set()
|
||||
for fd in (directory / "fd").iterdir():
|
||||
try:
|
||||
target = os.readlink(fd)
|
||||
except OSError:
|
||||
continue
|
||||
if target.startswith("socket:["):
|
||||
inodes.add(target[8:-1])
|
||||
result = set()
|
||||
for line in (directory / "net/tcp").read_text().splitlines()[1:]:
|
||||
fields = line.split()
|
||||
if fields[3] == "01" and fields[9] in inodes:
|
||||
host, port = fields[2].split(":")
|
||||
result.add((socket.inet_ntoa(bytes.fromhex(host)[::-1]), int(port, 16)))
|
||||
return result
|
||||
|
||||
|
||||
def wait_ready(expected, timeout, stable, mode="ports", pid=None, interval=2.0):
|
||||
print(f"[cmvr-startup] checking {mode}: " + (", ".join(e.label() for e in expected) or "no enabled AUBO/SEER network devices"), flush=True)
|
||||
if not expected:
|
||||
return True
|
||||
deadline = time.monotonic() + timeout
|
||||
since, previous, last_report = None, None, 0.0
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(expected))) as pool:
|
||||
while time.monotonic() < deadline:
|
||||
if mode == "connected":
|
||||
connections = process_connections(pid)
|
||||
ready = [(e.host, e.port) in connections for e in expected]
|
||||
else:
|
||||
ready = list(pool.map(reachable, expected))
|
||||
now = time.monotonic()
|
||||
missing = tuple(e.label() for e, ok in zip(expected, ready) if not ok)
|
||||
if not missing:
|
||||
since = now if since is None else since
|
||||
if now - since >= stable:
|
||||
print(f"[cmvr-startup] ready, stable for {stable:g}s", flush=True)
|
||||
return True
|
||||
else:
|
||||
since = None
|
||||
if missing != previous or now - last_report >= 15:
|
||||
print("[cmvr-startup] " + ("waiting: " + ", ".join(missing) if missing else "all available; waiting for stable readiness"), flush=True)
|
||||
previous, last_report = missing, now
|
||||
time.sleep(min(interval, max(0.0, deadline - time.monotonic())))
|
||||
print("[cmvr-startup] readiness timed out; systemd will retry startup", flush=True)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config-dir", required=True)
|
||||
parser.add_argument("--mode", choices=["ports", "connected"], default="ports")
|
||||
parser.add_argument("--pid", type=int)
|
||||
parser.add_argument("--timeout", type=float, default=180)
|
||||
parser.add_argument("--stable-seconds", type=float, default=10)
|
||||
parser.add_argument("--list", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
expected = endpoints(args.config_dir)
|
||||
if args.list:
|
||||
for item in expected:
|
||||
print(item.label())
|
||||
return 0
|
||||
if args.mode == "connected" and (args.pid is None or args.pid <= 0):
|
||||
raise ValueError("connected check requires the service MAINPID")
|
||||
return 0 if wait_ready(expected, args.timeout, args.stable_seconds, args.mode, args.pid) else 1
|
||||
except (OSError, ValueError, RuntimeError) as error:
|
||||
print(f"[cmvr-startup] configuration/check error: {error}", file=sys.stderr, flush=True)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in New Issue
Block a user