Compare commits
71 Commits
dev
...
xtkuang_de
| Author | SHA1 | Date | |
|---|---|---|---|
| 67566e8aea | |||
| fad8e0e87c | |||
| c66e25ec92 | |||
| abe6486e43 | |||
| 9c9b412d91 | |||
| aac719a932 | |||
| f611ad1db8 | |||
| 8ac1bff099 | |||
| 1dfe23641d | |||
| e28a0a4381 | |||
| d6997b03b1 | |||
| 1b3cd55505 | |||
| cb5f46c598 | |||
| f4be2ffaaa | |||
| b2b0b63fe0 | |||
| 4f36cf4957 | |||
| 55912abad0 | |||
| de764de607 | |||
| 4c8b320b4b | |||
| 912d8689f7 | |||
| 9095fbf68c | |||
| 3b87f681cf | |||
| e3726e5a98 | |||
| e77c2cfea8 | |||
| ab4bbfac50 | |||
| 459b76db1d | |||
| 08d58b2ccf | |||
| 60098ee01e | |||
| b4ec07c851 | |||
| 490c141ca8 | |||
| 52d30ee412 | |||
| 26a7ad5d4b | |||
| b5c6d50022 | |||
| f092e2539d | |||
| 31b2d98625 | |||
| edb01463ff | |||
| b54c2936be | |||
| af67751937 | |||
| 28f1dd1bf8 | |||
| f443a7ce53 | |||
| 7c9a37f808 | |||
| ed231ace2b | |||
| eb188111b7 | |||
| 428ee328de | |||
| 1181b2d541 | |||
| d40c92b9bf | |||
| f8961c4e7a | |||
| b585cb6601 | |||
| a0fbeccc19 | |||
| 53f71bb720 | |||
| 1fc5179344 | |||
| 0ac04290e4 | |||
| d956e538bc | |||
| a6f00ceb6c | |||
| 2eefd845f9 | |||
| 89b1e1f8f6 | |||
| 2cda7be4d4 | |||
| d84f84b5ee | |||
| 5b94d5c85a | |||
| dc0831eb71 | |||
| c9c7e43a70 | |||
| d292360a8d | |||
| 5c8847d334 | |||
| 2fa161f1cc | |||
| 6664d181cb | |||
| 1c70819993 | |||
| 5015077cb5 | |||
| d04b1920d1 | |||
| f217ce96c4 | |||
| 5a6b75938d | |||
| 27445c00f5 |
13
.gitignore
vendored
13
.gitignore
vendored
@ -2,7 +2,20 @@
|
||||
/cmake-build-debug
|
||||
/cmake-build-sigma-debuggit
|
||||
/build
|
||||
/build-*
|
||||
/log
|
||||
/third_party/osqp/
|
||||
/third_party/OsqpEigen/
|
||||
/output
|
||||
|
||||
# Generated development artifacts
|
||||
compile_commands.json
|
||||
MUJOCO_LOG.TXT
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.log
|
||||
|
||||
# Generated plots and vision debug output
|
||||
/data/*.png
|
||||
/data/*.svg
|
||||
/python/vision_servo/red_point.png
|
||||
|
||||
6
.vscode/extensions.json
vendored
6
.vscode/extensions.json
vendored
@ -1,6 +0,0 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.cmake-tools"
|
||||
]
|
||||
}
|
||||
30
.vscode/launch.json
vendored
30
.vscode/launch.json
vendored
@ -1,32 +1,30 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
{
|
||||
"name": "C/C++: g++ 构建和调试活动文件",
|
||||
"name": "Debug cmvr_es (installed output)",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${fileDirname}/${fileBasenameNoExtension}",
|
||||
"program": "${workspaceFolder}/output/bin/cmvr_es",
|
||||
"args": [],
|
||||
"stopAtEntry": false,
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [],
|
||||
"cwd": "${workspaceFolder}/output/bin",
|
||||
"environment": [
|
||||
{
|
||||
"name": "LD_LIBRARY_PATH",
|
||||
"value": "${workspaceFolder}/output/lib:${env:LD_LIBRARY_PATH}"
|
||||
}
|
||||
],
|
||||
"externalConsole": false,
|
||||
"MIMode": "gdb",
|
||||
"preLaunchTask": "cmake: install",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "为 gdb 启用整齐打印",
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "将反汇编风格设置为 Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
],
|
||||
"preLaunchTask": "C/C++: g++ 生成活动文件",
|
||||
"miDebuggerPath": "/usr/bin/gdb"
|
||||
]
|
||||
}
|
||||
],
|
||||
"version": "2.0.0"
|
||||
]
|
||||
}
|
||||
9
.vscode/settings.json
vendored
9
.vscode/settings.json
vendored
@ -1,12 +1,11 @@
|
||||
{
|
||||
"cmake.configureOnOpen": true,
|
||||
"cmake.buildDirectory": "${workspaceFolder}/cmake-build-debug",
|
||||
"cmake.copyCompileCommands": "${workspaceFolder}/compile_commands.json",
|
||||
"cmake.sourceDirectory": "${workspaceFolder}",
|
||||
"cmake.buildDirectory": "${workspaceFolder}/build/vscode-debug",
|
||||
"cmake.configureSettings": {
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
|
||||
},
|
||||
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
|
||||
"C_Cpp.default.compileCommands": "${workspaceFolder}/compile_commands.json",
|
||||
"C_Cpp.default.compileCommands": "${workspaceFolder}/build/vscode-debug/compile_commands.json",
|
||||
"C_Cpp.default.cppStandard": "c++17",
|
||||
"C_Cpp.default.intelliSenseMode": "linux-gcc-x64"
|
||||
}
|
||||
|
||||
70
.vscode/tasks.json
vendored
70
.vscode/tasks.json
vendored
@ -1,25 +1,71 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "cppbuild",
|
||||
"label": "C/C++: g++ 生成活动文件",
|
||||
"command": "/usr/bin/g++",
|
||||
"label": "cmake: configure",
|
||||
"type": "shell",
|
||||
"command": "cmake",
|
||||
"args": [
|
||||
"-fdiagnostics-color=always",
|
||||
"-g",
|
||||
"${file}",
|
||||
"-o",
|
||||
"${fileDirname}/${fileBasenameNoExtension}"
|
||||
"-S",
|
||||
"${workspaceFolder}",
|
||||
"-B",
|
||||
"${workspaceFolder}/build/vscode-debug",
|
||||
"-DCMAKE_BUILD_TYPE=Debug",
|
||||
"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${fileDirname}"
|
||||
"group": "build",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "cmake: build",
|
||||
"type": "shell",
|
||||
"command": "cmake",
|
||||
"args": [
|
||||
"--build",
|
||||
"${workspaceFolder}/build/vscode-debug",
|
||||
"-j",
|
||||
"8"
|
||||
],
|
||||
"dependsOn": [
|
||||
"cmake: configure"
|
||||
],
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
},
|
||||
"problemMatcher": [
|
||||
"$gcc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "cmake: install",
|
||||
"type": "shell",
|
||||
"command": "cmake",
|
||||
"args": [
|
||||
"--install",
|
||||
"${workspaceFolder}/build/vscode-debug",
|
||||
"--verbose"
|
||||
],
|
||||
"dependsOn": [
|
||||
"cmake: build"
|
||||
],
|
||||
"group": "build",
|
||||
"detail": "调试器生成的任务。"
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "cmvr_es: run installed",
|
||||
"type": "shell",
|
||||
"command": "${workspaceFolder}/output/bin/cmvr_es",
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/output/bin",
|
||||
"env": {
|
||||
"LD_LIBRARY_PATH": "${workspaceFolder}/output/lib:${env:LD_LIBRARY_PATH}"
|
||||
}
|
||||
},
|
||||
"dependsOn": [
|
||||
"cmake: install"
|
||||
],
|
||||
"version": "2.0.0"
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -9,7 +9,29 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
#set(CMAKE_CXX_STANDARD_REQUIRED True)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Preserve the project's production-build behavior: tests are opt-in via
|
||||
# -DBUILD_TESTING=ON, while still registering them with CTest when requested.
|
||||
option(BUILD_TESTING "Build the test targets" OFF)
|
||||
include(CTest)
|
||||
|
||||
if(BUILD_TESTING AND UNIX AND NOT APPLE)
|
||||
# Test executables can still inherit the AUBO imported target's build-tree
|
||||
# RUNPATH. Keep the active toolchain runtime ahead of that vendor path.
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_CXX_COMPILER} -print-file-name=libstdc++.so.6
|
||||
OUTPUT_VARIABLE CMVR_TEST_SYSTEM_LIBSTDCXX
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
if(EXISTS "${CMVR_TEST_SYSTEM_LIBSTDCXX}")
|
||||
get_filename_component(
|
||||
CMVR_TEST_SYSTEM_LIBSTDCXX
|
||||
"${CMVR_TEST_SYSTEM_LIBSTDCXX}"
|
||||
REALPATH
|
||||
)
|
||||
else()
|
||||
unset(CMVR_TEST_SYSTEM_LIBSTDCXX)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Install to <source>/output
|
||||
set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/output" CACHE PATH "" FORCE)
|
||||
@ -18,7 +40,6 @@ set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/output" CACHE PATH "" FORCE)
|
||||
set(CMAKE_BUILD_RPATH "\$ORIGIN:\$ORIGIN/../lib")
|
||||
set(CMAKE_INSTALL_RPATH "\$ORIGIN:\$ORIGIN/../lib")
|
||||
|
||||
# Use RUNPATH (new dtags) generally preferable
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH OFF)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
|
||||
@ -29,6 +50,9 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
|
||||
include(FindExternalLib)
|
||||
set(ARCH "x86")
|
||||
setup_external_libs(${ARCH})
|
||||
if(BUILD_TESTING AND CMVR_EXTERNAL_LIBRARY_DIRS)
|
||||
list(JOIN CMVR_EXTERNAL_LIBRARY_DIRS ":" CMVR_TEST_EXTERNAL_LIBRARY_PATH)
|
||||
endif()
|
||||
# 在调用 setup_external_libs 之后
|
||||
message(STATUS "CMAKE_EXE_LINKER_FLAGS: ${CMAKE_EXE_LINKER_FLAGS}")
|
||||
message(STATUS "CMAKE_SHARED_LINKER_FLAGS: ${CMAKE_SHARED_LINKER_FLAGS}")
|
||||
@ -46,8 +70,9 @@ file(GLOB_RECURSE PROTO_FILES ${PROTO_IMPORT_DIR}/*.proto)
|
||||
|
||||
|
||||
set(Protobuf_PROTOC_EXECUTABLE "${CMAKE_INSTALL_PREFIX}/bin/protoc" CACHE FILEPATH "" FORCE)
|
||||
set_property(TARGET gRPC::grpc_cpp_plugin
|
||||
PROPERTY IMPORTED_LOCATION "${CMAKE_INSTALL_PREFIX}/bin/grpc_cpp_plugin"
|
||||
set_target_properties(gRPC::grpc_cpp_plugin PROPERTIES
|
||||
IMPORTED_LOCATION "${CMAKE_INSTALL_PREFIX}/bin/grpc_cpp_plugin"
|
||||
IMPORTED_LOCATION_RELEASE "${CMAKE_INSTALL_PREFIX}/bin/grpc_cpp_plugin"
|
||||
)
|
||||
|
||||
# 1) 先做 OBJECT:只负责生成/编译 pb.cc
|
||||
@ -108,7 +133,7 @@ target_link_libraries(cmvr_es PRIVATE
|
||||
cmvr_es::runtime
|
||||
cmvr_es::proto
|
||||
cmvr_es::logging
|
||||
service
|
||||
cmvr_es::quic_edge_task
|
||||
${GLOG_LIBRARIES}
|
||||
jsoncpp
|
||||
cmvr_es::service
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
Fri Jul 24 15:39:05 2026
|
||||
ERROR: could not create window
|
||||
|
||||
Fri Jul 24 15:40:37 2026
|
||||
ERROR: could not create window
|
||||
|
||||
114
README.md
114
README.md
@ -1,23 +1,25 @@
|
||||
# CMVR-ES
|
||||
|
||||
## Overview
|
||||
## 简介
|
||||
|
||||
## Installation
|
||||
CMVR-ES 工程。
|
||||
|
||||
### 1. Git submodules install
|
||||
## 安装
|
||||
|
||||
### 1. 拉取 Git 子模块
|
||||
|
||||
```
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
### 2. Dependency install
|
||||
### 2. 安装系统依赖
|
||||
|
||||
```shell
|
||||
# basic
|
||||
# 基础工具
|
||||
sudo apt-get update
|
||||
sudo apt install -y build-essential cmake git pkg-config patchelf libboost-all-dev libssl-dev
|
||||
|
||||
# opencv
|
||||
# OpenCV
|
||||
sudo apt install -y \
|
||||
libjpeg-dev libpng-dev libtiff-dev \
|
||||
libavcodec-dev libavformat-dev libswscale-dev \
|
||||
@ -39,7 +41,7 @@ sudo apt-get install libassimp-dev
|
||||
# visp
|
||||
sudo apt-get install -y libx11-dev liblapack-dev libzbar-dev libpthread-stubs0-dev libdc1394-dev nlohmann-json3-dev
|
||||
|
||||
# realsense
|
||||
# RealSense
|
||||
sudo apt-get install -y \
|
||||
libusb-1.0-0-dev libudev-dev \
|
||||
libglu1-mesa-dev
|
||||
@ -48,4 +50,102 @@ sudo apt-get install -y \
|
||||
sudo apt install gnuplot-qt
|
||||
```
|
||||
|
||||
### 3. 配置 IgH EtherCAT
|
||||
|
||||
工程已内置 IgH EtherCAT 1.7.0 的 userspace 文件:
|
||||
|
||||
```text
|
||||
dependency/x86/third_party/ethercat/v1.7.0
|
||||
```
|
||||
|
||||
先设置本机路径:
|
||||
|
||||
```shell
|
||||
export CMVR_ES_ROOT=/path/to/cmvr-es
|
||||
export IGH_ETHERCAT_ROOT=$CMVR_ES_ROOT/dependency/x86/third_party/ethercat/v1.7.0
|
||||
```
|
||||
|
||||
安装当前内核的 header:
|
||||
|
||||
```shell
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y linux-headers-$(uname -r)
|
||||
```
|
||||
|
||||
如果内置目录里已经有当前内核版本的 EtherCAT 内核模块,直接安装到系统:
|
||||
|
||||
```shell
|
||||
sudo mkdir -p /lib/modules/$(uname -r)/ethercat
|
||||
sudo cp -r $IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)/ethercat/* /lib/modules/$(uname -r)/ethercat/
|
||||
sudo depmod
|
||||
```
|
||||
|
||||
内置内核模块只适用于相同内核版本。如果 `$IGH_ETHERCAT_ROOT/lib/modules/$(uname -r)` 不存在,说明这台机器的内核版本不匹配,需要在这台机器上重新编译安装 IgH EtherCAT:
|
||||
|
||||
```shell
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
build-essential autoconf automake libtool pkg-config git \
|
||||
linux-headers-$(uname -r)
|
||||
|
||||
cd /tmp
|
||||
git clone --branch stable-1.7 --depth 1 https://gitlab.com/etherlab.org/ethercat.git ethercat-stable-1.7
|
||||
cd ethercat-stable-1.7
|
||||
|
||||
./bootstrap
|
||||
./configure \
|
||||
--prefix=$IGH_ETHERCAT_ROOT \
|
||||
--libdir=$IGH_ETHERCAT_ROOT/lib \
|
||||
--includedir=$IGH_ETHERCAT_ROOT/include \
|
||||
--sysconfdir=$IGH_ETHERCAT_ROOT/etc \
|
||||
--with-systemdsystemunitdir=$IGH_ETHERCAT_ROOT/lib/systemd/system \
|
||||
--enable-generic \
|
||||
--with-linux-dir=/lib/modules/$(uname -r)/build
|
||||
|
||||
make -j$(nproc) all modules
|
||||
make install
|
||||
sudo make modules_install
|
||||
sudo depmod
|
||||
```
|
||||
|
||||
启动 EtherCAT。`eno1` 换成实际连接 EtherCAT 从站的网卡:
|
||||
|
||||
```shell
|
||||
sudo script/ethercat/start_ethercat.sh eno1
|
||||
```
|
||||
|
||||
脚本会写入内置 IgH 配置文件:
|
||||
|
||||
```text
|
||||
$IGH_ETHERCAT_ROOT/etc/ethercat.conf
|
||||
```
|
||||
|
||||
脚本会把该网卡的 MAC 写到 `MASTER0_DEVICE`,使用 `DEVICE_MODULES="generic"`,把网卡从 NetworkManager 断开,并通过 `ethercatctl -c` 启动 IgH master。
|
||||
|
||||
查看状态:
|
||||
|
||||
```shell
|
||||
script/ethercat/status_ethercat.sh
|
||||
|
||||
$IGH_ETHERCAT_ROOT/bin/ethercat master
|
||||
$IGH_ETHERCAT_ROOT/bin/ethercat slaves
|
||||
$IGH_ETHERCAT_ROOT/bin/ethercat pdos
|
||||
```
|
||||
|
||||
停止 EtherCAT:
|
||||
|
||||
```shell
|
||||
sudo script/ethercat/stop_ethercat.sh eno1
|
||||
sudo script/ethercat/stop_ethercat.sh eno1 --restore-network
|
||||
```
|
||||
|
||||
## 组件文档
|
||||
|
||||
具体能力、配置、协议和安全边界由对应代码目录下的 README 维护:
|
||||
|
||||
- [MotorService gRPC 接口](cmvr-es/service/README.md#motorservice)
|
||||
- [电机设备模块](cmvr-es/devices/motor/README.md)
|
||||
- [AUBO 控制柜 Standard 数字 IO](cmvr-es/devices/arm/aubo_arm/README.md)
|
||||
- [配置与部署规则](cmvr-es/config/README.md)
|
||||
|
||||
AUBO JSON 接口只访问控制柜 Standard 数字 IO,不访问安全 IO。
|
||||
|
||||
@ -1 +0,0 @@
|
||||
Subproject commit 3089c7897a5711aceb39d25919aca8c57b5c5948
|
||||
@ -55,7 +55,17 @@ function(setup_external_libs ARCH)
|
||||
|
||||
# ---- library dirs ----
|
||||
if(EXISTS "${FULL_PATH}/lib")
|
||||
file(GLOB _BUNDLED_LIBSTDCXX_FILES
|
||||
"${FULL_PATH}/lib/libstdc++.so"
|
||||
"${FULL_PATH}/lib/libstdc++.so.*"
|
||||
)
|
||||
if(_BUNDLED_LIBSTDCXX_FILES)
|
||||
message(STATUS
|
||||
"${LIB_NAME}: excluding vendor lib directory from global "
|
||||
"link paths because it contains a private libstdc++")
|
||||
else()
|
||||
list(APPEND LIBRARY_DIRS "${FULL_PATH}/lib")
|
||||
endif()
|
||||
set(HAS_LIB TRUE)
|
||||
|
||||
# Collect shared libs for install: *.so and *.so.*
|
||||
@ -63,6 +73,7 @@ function(setup_external_libs ARCH)
|
||||
"${FULL_PATH}/lib/*.so"
|
||||
"${FULL_PATH}/lib/*.so.*"
|
||||
)
|
||||
list(FILTER _SO_FILES EXCLUDE REGEX "/libstdc\\+\\+\\.so(\\..*)?$")
|
||||
if(_SO_FILES)
|
||||
list(APPEND INSTALL_SO_FILES ${_SO_FILES})
|
||||
endif()
|
||||
@ -85,6 +96,7 @@ function(setup_external_libs ARCH)
|
||||
"${FULL_PATH}/*.so"
|
||||
"${FULL_PATH}/*.so.*"
|
||||
)
|
||||
list(FILTER _SO_FILES2 EXCLUDE REGEX "/libstdc\\+\\+\\.so(\\..*)?$")
|
||||
if(_SO_FILES2)
|
||||
list(APPEND INSTALL_SO_FILES ${_SO_FILES2})
|
||||
endif()
|
||||
@ -127,6 +139,7 @@ function(setup_external_libs ARCH)
|
||||
list(REMOVE_DUPLICATES LIBRARY_DIRS)
|
||||
link_directories(${LIBRARY_DIRS})
|
||||
endif()
|
||||
set(CMVR_EXTERNAL_LIBRARY_DIRS "${LIBRARY_DIRS}" PARENT_SCOPE)
|
||||
|
||||
# ---- install third-party shared libs into <prefix>/lib ----
|
||||
if(INSTALL_SO_FILES)
|
||||
@ -138,6 +151,14 @@ function(setup_external_libs ARCH)
|
||||
)
|
||||
|
||||
install(FILES ${INSTALL_SO_FILES} DESTINATION lib)
|
||||
install(CODE [[
|
||||
file(GLOB _bundled_stdlib_files
|
||||
"${CMAKE_INSTALL_PREFIX}/lib/libstdc++.so"
|
||||
"${CMAKE_INSTALL_PREFIX}/lib/libstdc++.so.*")
|
||||
if(_bundled_stdlib_files)
|
||||
file(REMOVE ${_bundled_stdlib_files})
|
||||
endif()
|
||||
]])
|
||||
|
||||
# After installing, patch RPATH of installed shared libs to $ORIGIN
|
||||
install(CODE [[
|
||||
|
||||
16
cmake/msquic/ProcessorCount.cmake
Normal file
16
cmake/msquic/ProcessorCount.cmake
Normal file
@ -0,0 +1,16 @@
|
||||
# MsQuic's QuicTLS custom build asks CMake's ProcessorCount module for a
|
||||
# nested `make -jN` value. Route that query through the build script's
|
||||
# --jobs setting so the dependency build cannot silently oversubscribe the
|
||||
# host.
|
||||
|
||||
if(NOT DEFINED CMVR_MSQUIC_PROCESSOR_COUNT OR
|
||||
NOT CMVR_MSQUIC_PROCESSOR_COUNT MATCHES "^[1-9][0-9]*$")
|
||||
message(FATAL_ERROR
|
||||
"CMVR_MSQUIC_PROCESSOR_COUNT must be a positive integer")
|
||||
endif()
|
||||
|
||||
function(ProcessorCount result_variable)
|
||||
set("${result_variable}"
|
||||
"${CMVR_MSQUIC_PROCESSOR_COUNT}"
|
||||
PARENT_SCOPE)
|
||||
endfunction()
|
||||
@ -6,8 +6,16 @@ add_subdirectory(hardware)
|
||||
add_subdirectory(algorithms)
|
||||
add_subdirectory(simulate)
|
||||
add_subdirectory(devices)
|
||||
add_subdirectory(manager/control_authority_manager)
|
||||
add_subdirectory(manager/safety_manager)
|
||||
add_subdirectory(manager/device_manager)
|
||||
add_subdirectory(service/grpc/stop_all)
|
||||
add_subdirectory(manager/media_source_manager)
|
||||
add_subdirectory(service/quic_edge)
|
||||
add_subdirectory(task)
|
||||
add_subdirectory(task/quic_edge_task)
|
||||
add_subdirectory(service/grpc/client)
|
||||
add_subdirectory(task/ume_teleop_task)
|
||||
add_subdirectory(manager/task_manager)
|
||||
add_subdirectory(service)
|
||||
add_subdirectory(runtime)
|
||||
|
||||
125
cmvr-es/algorithms/README.md
Normal file
125
cmvr-es/algorithms/README.md
Normal file
@ -0,0 +1,125 @@
|
||||
# Algorithms 模块开发指南
|
||||
|
||||
`algorithms/` 保存与具体厂商协议无关的运动学、规划、控制和感知算法。算法接受通用类型或显式接口输入,不应直接解析设备报文,也不应承担 gRPC/QUIC 传输职责。
|
||||
|
||||
返回[项目总览](../../README.md)。
|
||||
|
||||
## 当前结构
|
||||
|
||||
| 目录 | 主要能力 | 主要 CMake target |
|
||||
| --- | --- | --- |
|
||||
| `kinematics/ik_solver/` | Pinocchio DLS/QP、SRS、LAWBA 逆运动学 | `cmvr_es::ik_solver` |
|
||||
| `motion_planner/base_motion/` | TOPPRA、S 曲线、笛卡尔速度限制 | `cmvr_es::base_motion` |
|
||||
| `motion_planner/arm_motion/` | MoveJ、MoveL、SpeedL 机械臂规划 | `cmvr_es::algorithms::arm_motion` |
|
||||
| `controllers/` | PID、IBVS、笛卡尔速度控制 | `cmvr_es::algorithms::controller`、`cmvr_es::algorithms::arm_control` |
|
||||
| `perception/` | AprilTag 和视觉定位 | `cmvr_es::perception` |
|
||||
|
||||
顶层入口是 [`CMakeLists.txt`](CMakeLists.txt)。
|
||||
|
||||
## 依赖边界
|
||||
|
||||
- 算法层可以依赖 `common/`、Eigen、Pinocchio、OSQP、TOPPRA、OpenCV、ViSP 等;
|
||||
- 不包含串口、CAN、HTTP 或厂商 SDK 协议处理;
|
||||
- 不启动 gRPC/QUIC 服务或管理设备生命周期;
|
||||
- 不从算法内部读取全局配置文件,构造或 `configure` 时显式传入配置;
|
||||
- 可复用算法不应主动取得 `DeviceManager` 单例。
|
||||
|
||||
当前部分 controller target 仍链接 `device_manager`,这是现有耦合。新增算法应优先通过参数、回调或窄接口注入设备状态,避免继续扩大该依赖。
|
||||
|
||||
## 扩展已有算法类别
|
||||
|
||||
### 1. 定义或复用抽象接口
|
||||
|
||||
常用接口:
|
||||
|
||||
- [`IKSolver`](kinematics/ik_solver/common/include/ik_solver.h)
|
||||
- [`JointMotionPlanner`](motion_planner/arm_motion/joint_motion/joint_motion_planner.h)
|
||||
- [`CartesianMotionPlanner`](motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h)
|
||||
|
||||
接口应明确:
|
||||
|
||||
- 输入输出单位和坐标系;
|
||||
- 是否修改内部状态;
|
||||
- 是否线程安全;
|
||||
- 失败时输出是否保持不变;
|
||||
- 是否支持实时循环,以及最大允许耗时。
|
||||
|
||||
### 2. 增加配置
|
||||
|
||||
在 [`../../protos/README.md`](../../protos/README.md) 指导下:
|
||||
|
||||
1. 为算法增加独立配置 message;
|
||||
2. 在所属 `oneof algorithm` 中增加新字段和新 tag;
|
||||
3. 不复用已发布 tag;
|
||||
4. 为迭代次数、容差、速度和加速度设置有效范围;
|
||||
5. 在默认设备配置中给出显式参数。
|
||||
|
||||
### 3. 实现与工厂注册
|
||||
|
||||
将实现放在对应类别子目录,并修改实际工厂:
|
||||
|
||||
- IK:[`ik_solver_factory.h`](kinematics/ik_solver/ik_solver_factory.h)
|
||||
- MoveJ:[`joint_motion_planner_factory.h`](motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h)
|
||||
- MoveL / SpeedL:[`cartesian_motion_planner_factory.h`](motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h)
|
||||
|
||||
工厂失败应返回 `nullptr` 并记录清晰原因,不能静默回退到另一个算法。MoveL 和 SpeedL 的实现必须保持配置组合一致。
|
||||
|
||||
### 4. 更新 CMake
|
||||
|
||||
- 将实现 `.cpp` 加入对应 library;
|
||||
- 使用项目已有 alias target;
|
||||
- 通过 `target_include_directories` 暴露公共头;
|
||||
- 将依赖放入使用它的最小 target;
|
||||
- 测试源文件不能加入生产共享库;
|
||||
- 新增三方依赖时同步根依赖发现逻辑和 `request.txt`。
|
||||
|
||||
## 数值与机器人语义
|
||||
|
||||
算法扩展至少需要明确:
|
||||
|
||||
- 关节位置单位为 rad,速度为 rad/s;
|
||||
- 笛卡尔平移为 m,旋转和角速度为 rad;
|
||||
- base、tool、world、user frame 的转换方向;
|
||||
- URDF base frame、tip frame 和关节顺序;
|
||||
- 位置、速度、加速度和 jerk 限制;
|
||||
- 奇异点、不可达目标和求解超时行为;
|
||||
- measured state 与算法内部 seed 的更新时机。
|
||||
|
||||
IK 在求解前应使用真实关节角更新 seed。MoveL 连续求解时,应使用上一步解更新下一步状态,不能一直使用初始状态。
|
||||
|
||||
## 测试要求
|
||||
|
||||
每个新算法至少覆盖:
|
||||
|
||||
1. 正常输入;
|
||||
2. 空输入、自由度不匹配和 NaN/Inf;
|
||||
3. 关节限位与速度限制;
|
||||
4. 不可达目标和不收敛;
|
||||
5. 坐标系转换;
|
||||
6. 确定性和重复调用;
|
||||
7. 若用于实时控制,统计最坏执行时间;
|
||||
8. 与一个已知模型或离线参考结果对比。
|
||||
|
||||
当前不少算法测试只通过 `add_executable()` 构建,没有登记到 CTest。新增无设备测试应放在 `BUILD_TESTING` 条件内,并使用 `add_test()`;需要图形界面、RealSense 或 MuJoCo 的测试应明确标为集成测试,不得阻塞默认无设备测试。
|
||||
|
||||
## 新增算法类别
|
||||
|
||||
如果现有类别无法承载:
|
||||
|
||||
1. 在 `algorithms/<category>/` 新建目录;
|
||||
2. 定义协议无关抽象接口;
|
||||
3. 定义配置 Proto 和工厂;
|
||||
4. 提供单独 CMake library 与 `cmvr_es::...` alias;
|
||||
5. 在 [`algorithms/CMakeLists.txt`](CMakeLists.txt) 添加子目录;
|
||||
6. 由设备或任务层注入使用,不让算法反向控制服务层;
|
||||
7. 添加无设备单元测试和真实设备/仿真集成测试。
|
||||
|
||||
## 提交检查
|
||||
|
||||
- [ ] 厂商协议没有进入算法接口
|
||||
- [ ] 单位、坐标系和关节顺序明确
|
||||
- [ ] 工厂已注册且配置组合经过校验
|
||||
- [ ] 不可达、超时和数值异常可观测
|
||||
- [ ] 测试没有被编入生产共享库
|
||||
- [ ] 无设备测试已登记到 CTest
|
||||
- [ ] 实时路径没有日志洪泛和无界内存分配
|
||||
@ -1,5 +1,6 @@
|
||||
|
||||
add_subdirectory(arm_control)
|
||||
add_subdirectory(ume_legacy)
|
||||
|
||||
#find_package(VISP REQUIRED)
|
||||
|
||||
|
||||
@ -52,8 +52,16 @@ public:
|
||||
|
||||
private:
|
||||
void ensureWorkerStarted_();
|
||||
void workerLoop_();
|
||||
void sendZero_();
|
||||
void workerLoop_(std::uint64_t worker_generation);
|
||||
bool workerGenerationCurrent_(std::uint64_t worker_generation) const;
|
||||
std::optional<Result> sendVelocityIfCurrent_(
|
||||
const JointVelocityCommand& velocity,
|
||||
double acceleration,
|
||||
std::uint64_t worker_generation);
|
||||
void finishCommandIfCurrent_(std::uint64_t command_version,
|
||||
std::uint64_t worker_generation);
|
||||
void sendZeroIfCurrent_(std::uint64_t worker_generation);
|
||||
void sendZeroNow_();
|
||||
|
||||
static double velocityNorm_(const std::vector<double>& velocity);
|
||||
static double twistNorm_(const CartesianVelocity& velocity);
|
||||
@ -65,15 +73,25 @@ private:
|
||||
ReadStateCallback read_state_;
|
||||
SendVelocityCallback send_velocity_;
|
||||
|
||||
// lifecycle_mutex_ serializes worker creation, join, and reset. It is held
|
||||
// across join so a new command cannot start until the retired worker exits.
|
||||
mutable std::mutex lifecycle_mutex_;
|
||||
std::unique_ptr<std::thread> worker_;
|
||||
std::atomic<bool> worker_running_{false};
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::atomic<bool> stop_requested_{false};
|
||||
bool stop_requested_{false};
|
||||
bool command_active_{false};
|
||||
CartesianVelocity target_twist_{};
|
||||
FrameType target_frame_{FrameType::Base};
|
||||
double target_acceleration_{0.25};
|
||||
std::uint64_t command_version_{0};
|
||||
|
||||
// Every worker output is checked while holding output_mutex_. shutdown()
|
||||
// advances the generation before sending zero, fencing stale worker writes.
|
||||
mutable std::mutex output_mutex_;
|
||||
std::atomic<std::uint64_t> worker_generation_{0};
|
||||
std::atomic<bool> busy_{false};
|
||||
};
|
||||
|
||||
|
||||
@ -61,13 +61,14 @@ Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
|
||||
if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 || acceleration <= 0.0) {
|
||||
return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input");
|
||||
}
|
||||
if ((!worker_ || !worker_->joinable()) && busy_.exchange(true)) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy");
|
||||
}
|
||||
|
||||
ensureWorkerStarted_();
|
||||
|
||||
std::uint64_t command_version = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
if (worker_ && worker_->joinable() && !worker_running_.load()) {
|
||||
worker_->join();
|
||||
worker_.reset();
|
||||
}
|
||||
ensureWorkerStarted_();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
target_twist_ = velocity;
|
||||
@ -76,6 +77,8 @@ Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
|
||||
command_active_ = true;
|
||||
command_version = ++command_version_;
|
||||
}
|
||||
busy_.store(true);
|
||||
}
|
||||
cv_.notify_all();
|
||||
|
||||
if (duration > 0.0) {
|
||||
@ -100,39 +103,57 @@ Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
|
||||
|
||||
Result CartesianVelocityController::stop(const std::optional<double> acceleration)
|
||||
{
|
||||
if (!worker_ || !worker_->joinable()) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
if (!worker_ || !worker_->joinable() || !worker_running_.load()) {
|
||||
return Result::success();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
target_acceleration_ = acceleration.has_value() ? *acceleration : config_.stop_acceleration;
|
||||
target_acceleration_ =
|
||||
acceleration.has_value() ? *acceleration
|
||||
: config_.stop_acceleration;
|
||||
command_active_ = true;
|
||||
++command_version_;
|
||||
}
|
||||
}
|
||||
cv_.notify_all();
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
void CartesianVelocityController::shutdown()
|
||||
{
|
||||
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mutex_);
|
||||
if (!worker_ || !worker_->joinable()) {
|
||||
busy_.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Revoke the worker before issuing zero. All worker outputs perform their
|
||||
// final generation check under output_mutex_, so none can follow this zero.
|
||||
worker_generation_.fetch_add(1, std::memory_order_acq_rel);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stop_requested_.store(true);
|
||||
stop_requested_ = true;
|
||||
command_active_ = false;
|
||||
target_twist_ = {};
|
||||
target_frame_ = FrameType::Base;
|
||||
++command_version_;
|
||||
}
|
||||
cv_.notify_all();
|
||||
|
||||
sendZeroNow_();
|
||||
busy_.store(false);
|
||||
|
||||
worker_->join();
|
||||
worker_.reset();
|
||||
stop_requested_.store(false);
|
||||
busy_.store(false);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stop_requested_ = false;
|
||||
command_active_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
CartesianVelocity CartesianVelocityController::getCommandTwistBase() const
|
||||
@ -148,12 +169,26 @@ void CartesianVelocityController::ensureWorkerStarted_()
|
||||
if (worker_ && worker_->joinable()) {
|
||||
return;
|
||||
}
|
||||
stop_requested_.store(false);
|
||||
worker_ = std::make_unique<std::thread>(&CartesianVelocityController::workerLoop_, this);
|
||||
const auto worker_generation =
|
||||
worker_generation_.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stop_requested_ = false;
|
||||
command_active_ = false;
|
||||
}
|
||||
worker_running_.store(true);
|
||||
worker_ = std::make_unique<std::thread>(
|
||||
&CartesianVelocityController::workerLoop_, this, worker_generation);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::workerLoop_()
|
||||
void CartesianVelocityController::workerLoop_(
|
||||
const std::uint64_t worker_generation)
|
||||
{
|
||||
struct RunningGuard {
|
||||
std::atomic<bool>& running;
|
||||
~RunningGuard() { running.store(false); }
|
||||
} running_guard{worker_running_};
|
||||
|
||||
const double dt = config_.control_period_s;
|
||||
auto next_tick = std::chrono::steady_clock::now();
|
||||
|
||||
@ -164,9 +199,10 @@ void CartesianVelocityController::workerLoop_()
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
cv_.wait(lock, [&]() {
|
||||
return stop_requested_.load() || command_active_;
|
||||
return stop_requested_ || command_active_;
|
||||
});
|
||||
if (stop_requested_.load()) {
|
||||
if (stop_requested_ ||
|
||||
!workerGenerationCurrent_(worker_generation)) {
|
||||
break;
|
||||
}
|
||||
target_twist = target_twist_;
|
||||
@ -176,43 +212,44 @@ void CartesianVelocityController::workerLoop_()
|
||||
|
||||
next_tick = std::chrono::steady_clock::now();
|
||||
while (true) {
|
||||
bool stopping = false;
|
||||
std::uint64_t active_command_version = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (stop_requested_.load()) {
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
return;
|
||||
}
|
||||
stopping = stop_requested_;
|
||||
if (!command_active_) {
|
||||
break;
|
||||
}
|
||||
target_twist = target_twist_;
|
||||
acceleration = target_acceleration_;
|
||||
target_frame = target_frame_;
|
||||
active_command_version = command_version_;
|
||||
}
|
||||
if (stopping ||
|
||||
!workerGenerationCurrent_(worker_generation)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!planner_->updateSpeedLAcceleration(acceleration)) {
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm && acceleration <= 0.0) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
command_active_ = false;
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] updateSpeedLAcceleration failed, acceleration="
|
||||
<< acceleration;
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
return;
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
|
||||
std::vector<double> q_now;
|
||||
std::vector<double> qd_now;
|
||||
if (!read_state_(q_now, qd_now)) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] read_state failed";
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
return;
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
|
||||
std::vector<double> qd_cmd;
|
||||
@ -222,31 +259,31 @@ void CartesianVelocityController::workerLoop_()
|
||||
<< target_twist.vz << ", " << target_twist.wx << ", "
|
||||
<< target_twist.wy << ", " << target_twist.wz
|
||||
<< "], frame=" << (target_frame == FrameType::Tool ? "Tool" : "Base");
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
return;
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
|
||||
JointVelocityCommand velocity_command;
|
||||
velocity_command.velocity = qd_cmd;
|
||||
const auto send_result = send_velocity_(velocity_command, acceleration);
|
||||
if (!send_result.ok()) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: "
|
||||
<< send_result.message;
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
const auto send_result = sendVelocityIfCurrent_(
|
||||
velocity_command, acceleration, worker_generation);
|
||||
if (!send_result.has_value()) {
|
||||
return;
|
||||
}
|
||||
if (!send_result->ok()) {
|
||||
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: "
|
||||
<< send_result->message;
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
|
||||
if (twistNorm_(target_twist) < config_.stop_twist_norm &&
|
||||
velocityNorm_(qd_cmd) < config_.stop_command_velocity_norm &&
|
||||
velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
command_active_ = false;
|
||||
}
|
||||
sendZero_();
|
||||
busy_.store(false);
|
||||
finishCommandIfCurrent_(
|
||||
active_command_version, worker_generation);
|
||||
break;
|
||||
}
|
||||
|
||||
@ -256,12 +293,67 @@ void CartesianVelocityController::workerLoop_()
|
||||
}
|
||||
}
|
||||
|
||||
sendZero_();
|
||||
sendZeroIfCurrent_(worker_generation);
|
||||
if (workerGenerationCurrent_(worker_generation)) {
|
||||
busy_.store(false);
|
||||
}
|
||||
}
|
||||
|
||||
void CartesianVelocityController::sendZero_()
|
||||
bool CartesianVelocityController::workerGenerationCurrent_(
|
||||
const std::uint64_t worker_generation) const
|
||||
{
|
||||
return worker_generation_.load(std::memory_order_acquire) ==
|
||||
worker_generation;
|
||||
}
|
||||
|
||||
std::optional<Result> CartesianVelocityController::sendVelocityIfCurrent_(
|
||||
const JointVelocityCommand& velocity,
|
||||
const double acceleration,
|
||||
const std::uint64_t worker_generation)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(output_mutex_);
|
||||
if (!workerGenerationCurrent_(worker_generation)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return send_velocity_(velocity, acceleration);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::finishCommandIfCurrent_(
|
||||
const std::uint64_t command_version,
|
||||
const std::uint64_t worker_generation)
|
||||
{
|
||||
std::lock_guard<std::mutex> output_lock(output_mutex_);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (command_version_ != command_version) {
|
||||
return;
|
||||
}
|
||||
command_active_ = false;
|
||||
busy_.store(false);
|
||||
}
|
||||
if (!workerGenerationCurrent_(worker_generation)) {
|
||||
return;
|
||||
}
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(dof_, 0.0);
|
||||
(void)send_velocity_(zero, 0.0);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::sendZeroIfCurrent_(
|
||||
const std::uint64_t worker_generation)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(output_mutex_);
|
||||
if (!workerGenerationCurrent_(worker_generation) || !send_velocity_) {
|
||||
return;
|
||||
}
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(dof_, 0.0);
|
||||
(void)send_velocity_(zero, 0.0);
|
||||
}
|
||||
|
||||
void CartesianVelocityController::sendZeroNow_()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(output_mutex_);
|
||||
if (!send_velocity_) {
|
||||
return;
|
||||
}
|
||||
|
||||
22
cmvr-es/algorithms/controllers/ume_legacy/CMakeLists.txt
Normal file
22
cmvr-es/algorithms/controllers/ume_legacy/CMakeLists.txt
Normal file
@ -0,0 +1,22 @@
|
||||
add_library(ume_legacy_controller SHARED
|
||||
src/ume_legacy_controller.cpp
|
||||
src/pinocchio_ume_legacy_model_adapter.cpp
|
||||
)
|
||||
|
||||
target_include_directories(ume_legacy_controller
|
||||
PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_link_libraries(ume_legacy_controller
|
||||
PRIVATE
|
||||
pinocchio_default
|
||||
pinocchio_parsers
|
||||
)
|
||||
|
||||
add_library(
|
||||
cmvr_es::algorithms::ume_legacy
|
||||
ALIAS ume_legacy_controller
|
||||
)
|
||||
|
||||
install(TARGETS ume_legacy_controller LIBRARY DESTINATION lib)
|
||||
@ -0,0 +1,72 @@
|
||||
#ifndef CMVR_ES_PINOCCHIO_UME_LEGACY_MODEL_ADAPTER_H
|
||||
#define CMVR_ES_PINOCCHIO_UME_LEGACY_MODEL_ADAPTER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "ume_legacy_model_adapter.h"
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
|
||||
struct UmeLegacyModelContract {
|
||||
std::size_t fixed_nq{0};
|
||||
std::size_t fixed_nv{0};
|
||||
std::size_t floating_nq{0};
|
||||
std::size_t floating_nv{0};
|
||||
Transform4x4RowMajor base_from_imu{};
|
||||
};
|
||||
|
||||
// Concrete adapter for the two original UME MJCF models.
|
||||
//
|
||||
// Construction parses both models and throws std::runtime_error if their
|
||||
// dimensions, joint ordering, joint coordinate indices, or required frame
|
||||
// topology differ from the frozen structural legacy contract.
|
||||
//
|
||||
// The floating model evaluates the original rnea(q, measured_arm_velocity, 0)
|
||||
// path: base twist and all accelerations are zero. Consequently its result
|
||||
// preserves the legacy velocity-dependent terms as well as gravity.
|
||||
//
|
||||
// Pinocchio Data objects are mutable workspaces. One adapter instance must be
|
||||
// used by one controller thread at a time. All Eigen workspaces are allocated
|
||||
// at construction and reused on the control path.
|
||||
class PinocchioUmeLegacyModelAdapter final
|
||||
: public UmeLegacyModelAdapter {
|
||||
public:
|
||||
PinocchioUmeLegacyModelAdapter(
|
||||
std::string fixed_model_path,
|
||||
std::string floating_model_path);
|
||||
~PinocchioUmeLegacyModelAdapter() override;
|
||||
|
||||
PinocchioUmeLegacyModelAdapter(
|
||||
const PinocchioUmeLegacyModelAdapter&) = delete;
|
||||
PinocchioUmeLegacyModelAdapter& operator=(
|
||||
const PinocchioUmeLegacyModelAdapter&) = delete;
|
||||
PinocchioUmeLegacyModelAdapter(
|
||||
PinocchioUmeLegacyModelAdapter&&) noexcept;
|
||||
PinocchioUmeLegacyModelAdapter& operator=(
|
||||
PinocchioUmeLegacyModelAdapter&&) noexcept;
|
||||
|
||||
bool computeGravityCompensation(
|
||||
const BimanualModelState& state,
|
||||
JointVector& right_gravity_nm,
|
||||
JointVector& left_gravity_nm) const override;
|
||||
|
||||
bool projectHapticFeedback(
|
||||
const BimanualModelState& state,
|
||||
ArmSide side,
|
||||
const RawHapticFeedback& feedback,
|
||||
ProjectedHapticEffort& projected) const override;
|
||||
|
||||
const UmeLegacyModelContract& contract() const noexcept;
|
||||
const std::string& fixedModelPath() const noexcept;
|
||||
const std::string& floatingModelPath() const noexcept;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
|
||||
#endif // CMVR_ES_PINOCCHIO_UME_LEGACY_MODEL_ADAPTER_H
|
||||
@ -0,0 +1,34 @@
|
||||
#ifndef CMVR_ES_UME_LEGACY_CONTROLLER_H
|
||||
#define CMVR_ES_UME_LEGACY_CONTROLLER_H
|
||||
|
||||
#include "ume_legacy_types.h"
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
|
||||
// Constants from UME commit e087df5cd3b281418722e155d9975695f163698e:
|
||||
// ume/robot/ume/v6_imu/ume_leader/controller.py
|
||||
// ume/robot/openarm1/teleop_leader_tuning.py
|
||||
LegacyUmeTuning originalTuning() noexcept;
|
||||
|
||||
JointVector frictionCompensation(
|
||||
const JointVector& velocity_rad_s,
|
||||
const LegacyUmeTuning& tuning) noexcept;
|
||||
|
||||
JointVector stictionCompensation(
|
||||
const JointVector& velocity_rad_s,
|
||||
const LegacyUmeTuning& tuning) noexcept;
|
||||
|
||||
// error_norm is non-negative in the legacy path because it is produced by
|
||||
// np.linalg.norm. std::abs is retained here to match the subsequent Python
|
||||
// expression exactly for direct unit-level use.
|
||||
double feedbackScale(
|
||||
double error_norm,
|
||||
const LegacyUmeTuning& tuning) noexcept;
|
||||
|
||||
SideControlOutput computeSideCommand(
|
||||
const SideControlInput& input,
|
||||
const LegacyUmeTuning& tuning = originalTuning()) noexcept;
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
|
||||
#endif // CMVR_ES_UME_LEGACY_CONTROLLER_H
|
||||
@ -0,0 +1,32 @@
|
||||
#ifndef CMVR_ES_UME_LEGACY_MODEL_ADAPTER_H
|
||||
#define CMVR_ES_UME_LEGACY_MODEL_ADAPTER_H
|
||||
|
||||
#include "ume_legacy_types.h"
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
|
||||
// Boundary for the two model operations used by the original IMU controller:
|
||||
// 1. floating-base RNEA gravity compensation;
|
||||
// 2. fixed-base J_rot^T projection of shoulder/wrist moments.
|
||||
//
|
||||
// Concrete implementations must load and validate their model contract so the
|
||||
// pure controller cannot silently substitute guessed kinematics or dynamics.
|
||||
class UmeLegacyModelAdapter {
|
||||
public:
|
||||
virtual ~UmeLegacyModelAdapter() = default;
|
||||
|
||||
virtual bool computeGravityCompensation(
|
||||
const BimanualModelState& state,
|
||||
JointVector& right_gravity_nm,
|
||||
JointVector& left_gravity_nm) const = 0;
|
||||
|
||||
virtual bool projectHapticFeedback(
|
||||
const BimanualModelState& state,
|
||||
ArmSide side,
|
||||
const RawHapticFeedback& feedback,
|
||||
ProjectedHapticEffort& projected) const = 0;
|
||||
};
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
|
||||
#endif // CMVR_ES_UME_LEGACY_MODEL_ADAPTER_H
|
||||
@ -0,0 +1,110 @@
|
||||
#ifndef CMVR_ES_UME_LEGACY_TYPES_H
|
||||
#define CMVR_ES_UME_LEGACY_TYPES_H
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
|
||||
inline constexpr std::size_t kArmDof = 8;
|
||||
inline constexpr std::size_t kTransformElementCount = 16;
|
||||
|
||||
using JointVector = std::array<double, kArmDof>;
|
||||
using Vector3 = std::array<double, 3>;
|
||||
using Transform4x4RowMajor =
|
||||
std::array<double, kTransformElementCount>;
|
||||
|
||||
enum class ArmSide {
|
||||
Right,
|
||||
Left
|
||||
};
|
||||
|
||||
// Shoulder and wrist entries have already been projected by J_rot^T. The
|
||||
// elbow and gripper entries are the scalar follower efforts received by the
|
||||
// original UME controller. Keeping this type separate prevents a 3-D moment
|
||||
// from being mislabeled as a 6-D Cartesian wrench.
|
||||
struct ProjectedHapticEffort {
|
||||
Vector3 shoulder_joint_torque{};
|
||||
double elbow_effort{0.0};
|
||||
Vector3 wrist_joint_torque{};
|
||||
double gripper_effort{0.0};
|
||||
};
|
||||
|
||||
struct TrackingError {
|
||||
Vector3 shoulder_rotation{};
|
||||
double elbow{0.0};
|
||||
Vector3 wrist_rotation{};
|
||||
double gripper{0.0};
|
||||
};
|
||||
|
||||
struct FeedbackScales {
|
||||
double shoulder{0.0};
|
||||
double elbow{0.0};
|
||||
double wrist{0.0};
|
||||
double gripper{0.0};
|
||||
};
|
||||
|
||||
struct LegacyUmeTuning {
|
||||
JointVector friction_coefficient{};
|
||||
JointVector friction_max_compensation{};
|
||||
JointVector stiction_threshold_min_rad_s{};
|
||||
JointVector stiction_threshold_max_rad_s{};
|
||||
JointVector stiction_compensation{};
|
||||
|
||||
double feedback_error_tolerance_rad{0.0};
|
||||
double feedback_tanh_sharpness{0.0};
|
||||
double feedback_scale{0.0};
|
||||
double feedback_limit_dm4340_nm{0.0};
|
||||
double feedback_limit_dm4310_nm{0.0};
|
||||
};
|
||||
|
||||
struct SideControlInput {
|
||||
ArmSide side{ArmSide::Right};
|
||||
JointVector joint_velocity_rad_s{};
|
||||
JointVector gravity_compensation_nm{};
|
||||
ProjectedHapticEffort projected_haptic{};
|
||||
TrackingError tracking_error{};
|
||||
};
|
||||
|
||||
struct SideControlOutput {
|
||||
JointVector friction_compensation_nm{};
|
||||
JointVector stiction_compensation_nm{};
|
||||
JointVector feedforward_without_haptic_nm{};
|
||||
|
||||
// This is the interaction effort after the legacy left/right scalar sign
|
||||
// conventions, but before scaling and clipping.
|
||||
JointVector signed_interaction_nm{};
|
||||
FeedbackScales feedback_scales{};
|
||||
|
||||
// The legacy algorithm clips only this feedback contribution. It does not
|
||||
// apply a final clamp to gravity, friction, stiction, or command_torque.
|
||||
JointVector limited_feedback_nm{};
|
||||
JointVector command_torque_nm{};
|
||||
};
|
||||
|
||||
// Pure model inputs/outputs shared by the legacy controller and its
|
||||
// Pinocchio/MJCF model adapter.
|
||||
struct BimanualModelState {
|
||||
// Joint arrays follow the frozen RJ1..RJ8 / LJ1..LJ8 MJCF order.
|
||||
JointVector right_position_rad{};
|
||||
JointVector right_velocity_rad_s{};
|
||||
JointVector left_position_rad{};
|
||||
JointVector left_velocity_rad_s{};
|
||||
|
||||
// Homogeneous rigid transform from the IMU frame to the gravity/world
|
||||
// frame. The adapter rejects non-finite and non-rigid matrices.
|
||||
Transform4x4RowMajor world_from_imu{};
|
||||
};
|
||||
|
||||
struct RawHapticFeedback {
|
||||
// Moments use the LOCAL_WORLD_ALIGNED frame expected by the original
|
||||
// Pinocchio J_rot^T mapping.
|
||||
Vector3 shoulder_moment{};
|
||||
double elbow_effort{0.0};
|
||||
Vector3 wrist_moment{};
|
||||
double gripper_effort{0.0};
|
||||
};
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
|
||||
#endif // CMVR_ES_UME_LEGACY_TYPES_H
|
||||
@ -0,0 +1,585 @@
|
||||
#include "pinocchio_ume_legacy_model_adapter.h"
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include <Eigen/Core>
|
||||
#include <Eigen/Geometry>
|
||||
|
||||
#include <pinocchio/algorithm/frames.hpp>
|
||||
#include <pinocchio/algorithm/jacobian.hpp>
|
||||
#include <pinocchio/algorithm/joint-configuration.hpp>
|
||||
#include <pinocchio/algorithm/rnea.hpp>
|
||||
#include <pinocchio/multibody/data.hpp>
|
||||
#include <pinocchio/multibody/model.hpp>
|
||||
#include <pinocchio/parsers/mjcf.hpp>
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
namespace {
|
||||
|
||||
using ExpectedArmJointNames = std::array<std::string, 16>;
|
||||
|
||||
const ExpectedArmJointNames& expectedArmJointNames()
|
||||
{
|
||||
static const ExpectedArmJointNames names{
|
||||
"RJ1", "RJ2", "RJ3", "RJ4",
|
||||
"RJ5", "RJ6", "RJ7", "RJ8",
|
||||
"LJ1", "LJ2", "LJ3", "LJ4",
|
||||
"LJ5", "LJ6", "LJ7", "LJ8"};
|
||||
return names;
|
||||
}
|
||||
|
||||
std::runtime_error contractError(
|
||||
const std::string& model_kind,
|
||||
const std::string& detail)
|
||||
{
|
||||
return std::runtime_error(
|
||||
"UME " + model_kind + " MJCF contract violation: " + detail);
|
||||
}
|
||||
|
||||
void requireDimensions(
|
||||
const pinocchio::Model& model,
|
||||
const std::string& model_kind,
|
||||
int nq,
|
||||
int nv,
|
||||
pinocchio::JointIndex njoints)
|
||||
{
|
||||
if (model.nq != nq ||
|
||||
model.nv != nv ||
|
||||
model.njoints != njoints) {
|
||||
std::ostringstream detail;
|
||||
detail << "expected nq/nv/njoints "
|
||||
<< nq << "/" << nv << "/" << njoints
|
||||
<< ", got " << model.nq << "/" << model.nv
|
||||
<< "/" << model.njoints;
|
||||
throw contractError(model_kind, detail.str());
|
||||
}
|
||||
}
|
||||
|
||||
void requireJoint(
|
||||
const pinocchio::Model& model,
|
||||
const std::string& model_kind,
|
||||
pinocchio::JointIndex joint_index,
|
||||
const std::string& expected_name,
|
||||
int expected_idx_q,
|
||||
int expected_nq,
|
||||
int expected_idx_v,
|
||||
int expected_nv)
|
||||
{
|
||||
if (joint_index >= model.njoints) {
|
||||
throw contractError(
|
||||
model_kind,
|
||||
"missing joint " + expected_name);
|
||||
}
|
||||
|
||||
if (model.names[joint_index] != expected_name ||
|
||||
model.idx_qs[joint_index] != expected_idx_q ||
|
||||
model.nqs[joint_index] != expected_nq ||
|
||||
model.idx_vs[joint_index] != expected_idx_v ||
|
||||
model.nvs[joint_index] != expected_nv) {
|
||||
std::ostringstream detail;
|
||||
detail << "joint[" << joint_index << "] expected "
|
||||
<< expected_name << " q(" << expected_idx_q
|
||||
<< "," << expected_nq << ") v(" << expected_idx_v
|
||||
<< "," << expected_nv << "), got "
|
||||
<< model.names[joint_index] << " q("
|
||||
<< model.idx_qs[joint_index] << ","
|
||||
<< model.nqs[joint_index] << ") v("
|
||||
<< model.idx_vs[joint_index] << ","
|
||||
<< model.nvs[joint_index] << ")";
|
||||
throw contractError(model_kind, detail.str());
|
||||
}
|
||||
}
|
||||
|
||||
pinocchio::FrameIndex requireUniqueFrame(
|
||||
const pinocchio::Model& model,
|
||||
const std::string& model_kind,
|
||||
const std::string& frame_name,
|
||||
const std::string& expected_parent_joint_name)
|
||||
{
|
||||
pinocchio::FrameIndex found = model.nframes;
|
||||
std::size_t count = 0;
|
||||
for (pinocchio::FrameIndex index = 0;
|
||||
index < model.nframes;
|
||||
++index) {
|
||||
if (model.frames[index].name == frame_name) {
|
||||
found = index;
|
||||
++count;
|
||||
}
|
||||
}
|
||||
if (count != 1) {
|
||||
std::ostringstream detail;
|
||||
detail << "expected exactly one frame " << frame_name
|
||||
<< ", got " << count;
|
||||
throw contractError(model_kind, detail.str());
|
||||
}
|
||||
|
||||
const auto parent_joint = model.frames[found].parentJoint;
|
||||
if (parent_joint >= model.njoints ||
|
||||
model.names[parent_joint] != expected_parent_joint_name) {
|
||||
std::ostringstream detail;
|
||||
detail << "frame " << frame_name
|
||||
<< " expected parent joint "
|
||||
<< expected_parent_joint_name;
|
||||
if (parent_joint < model.njoints) {
|
||||
detail << ", got " << model.names[parent_joint];
|
||||
} else {
|
||||
detail << ", got invalid index " << parent_joint;
|
||||
}
|
||||
throw contractError(model_kind, detail.str());
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
void validateFixedModel(
|
||||
const pinocchio::Model& model,
|
||||
std::array<pinocchio::FrameIndex, 4>& frame_ids)
|
||||
{
|
||||
requireDimensions(model, "fixed", 16, 16, 17);
|
||||
const auto& names = expectedArmJointNames();
|
||||
for (std::size_t index = 0; index < names.size(); ++index) {
|
||||
requireJoint(
|
||||
model,
|
||||
"fixed",
|
||||
static_cast<pinocchio::JointIndex>(index + 1),
|
||||
names[index],
|
||||
static_cast<int>(index),
|
||||
1,
|
||||
static_cast<int>(index),
|
||||
1);
|
||||
}
|
||||
|
||||
frame_ids[0] =
|
||||
requireUniqueFrame(model, "fixed", "R_shoulder", "RJ3");
|
||||
frame_ids[1] =
|
||||
requireUniqueFrame(model, "fixed", "R_wrist", "RJ7");
|
||||
frame_ids[2] =
|
||||
requireUniqueFrame(model, "fixed", "L_shoulder", "LJ3");
|
||||
frame_ids[3] =
|
||||
requireUniqueFrame(model, "fixed", "L_wrist", "LJ7");
|
||||
}
|
||||
|
||||
pinocchio::FrameIndex validateFloatingModel(
|
||||
const pinocchio::Model& model)
|
||||
{
|
||||
requireDimensions(model, "floating", 23, 22, 18);
|
||||
requireJoint(
|
||||
model,
|
||||
"floating",
|
||||
1,
|
||||
"dm_j4340_2ec_freejoint",
|
||||
0,
|
||||
7,
|
||||
0,
|
||||
6);
|
||||
|
||||
const auto& names = expectedArmJointNames();
|
||||
for (std::size_t index = 0; index < names.size(); ++index) {
|
||||
requireJoint(
|
||||
model,
|
||||
"floating",
|
||||
static_cast<pinocchio::JointIndex>(index + 2),
|
||||
names[index],
|
||||
static_cast<int>(index + 7),
|
||||
1,
|
||||
static_cast<int>(index + 6),
|
||||
1);
|
||||
}
|
||||
|
||||
requireUniqueFrame(
|
||||
model, "floating", "R_shoulder", "RJ3");
|
||||
requireUniqueFrame(
|
||||
model, "floating", "R_wrist", "RJ7");
|
||||
requireUniqueFrame(
|
||||
model, "floating", "L_shoulder", "LJ3");
|
||||
requireUniqueFrame(
|
||||
model, "floating", "L_wrist", "LJ7");
|
||||
return requireUniqueFrame(
|
||||
model,
|
||||
"floating",
|
||||
"imu",
|
||||
"dm_j4340_2ec_freejoint");
|
||||
}
|
||||
|
||||
bool finite(const JointVector& values) noexcept
|
||||
{
|
||||
for (const double value : values) {
|
||||
if (!std::isfinite(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool finite(const Vector3& values) noexcept
|
||||
{
|
||||
for (const double value : values) {
|
||||
if (!std::isfinite(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool toIsometry(
|
||||
const Transform4x4RowMajor& source,
|
||||
Eigen::Isometry3d& destination) noexcept
|
||||
{
|
||||
Eigen::Matrix4d matrix;
|
||||
for (Eigen::Index row = 0; row < 4; ++row) {
|
||||
for (Eigen::Index column = 0; column < 4; ++column) {
|
||||
matrix(row, column) =
|
||||
source[static_cast<std::size_t>(row * 4 + column)];
|
||||
}
|
||||
}
|
||||
if (!matrix.allFinite()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr double kTransformTolerance = 1e-6;
|
||||
if (std::abs(matrix(3, 0)) > kTransformTolerance ||
|
||||
std::abs(matrix(3, 1)) > kTransformTolerance ||
|
||||
std::abs(matrix(3, 2)) > kTransformTolerance ||
|
||||
std::abs(matrix(3, 3) - 1.0) > kTransformTolerance) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const Eigen::Matrix3d rotation =
|
||||
matrix.template block<3, 3>(0, 0);
|
||||
if (!(rotation.transpose() * rotation)
|
||||
.isApprox(Eigen::Matrix3d::Identity(),
|
||||
kTransformTolerance) ||
|
||||
std::abs(rotation.determinant() - 1.0) >
|
||||
kTransformTolerance) {
|
||||
return false;
|
||||
}
|
||||
|
||||
destination = Eigen::Isometry3d::Identity();
|
||||
destination.linear() = rotation;
|
||||
destination.translation() =
|
||||
matrix.template block<3, 1>(0, 3);
|
||||
return true;
|
||||
}
|
||||
|
||||
Transform4x4RowMajor toRowMajor(
|
||||
const Eigen::Matrix4d& matrix) noexcept
|
||||
{
|
||||
Transform4x4RowMajor result{};
|
||||
for (Eigen::Index row = 0; row < 4; ++row) {
|
||||
for (Eigen::Index column = 0; column < 4; ++column) {
|
||||
result[static_cast<std::size_t>(row * 4 + column)] =
|
||||
matrix(row, column);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Eigen::Vector3d toEigen(const Vector3& value) noexcept
|
||||
{
|
||||
return {value[0], value[1], value[2]};
|
||||
}
|
||||
|
||||
Vector3 fromEigen(const Eigen::Vector3d& value) noexcept
|
||||
{
|
||||
return {value.x(), value.y(), value.z()};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
class PinocchioUmeLegacyModelAdapter::Impl {
|
||||
public:
|
||||
Impl(std::string fixed_path, std::string floating_path)
|
||||
: fixed_model_path(std::move(fixed_path)),
|
||||
floating_model_path(std::move(floating_path))
|
||||
{
|
||||
try {
|
||||
pinocchio::mjcf::buildModel(
|
||||
fixed_model_path, fixed_model, false);
|
||||
} catch (const std::exception& error) {
|
||||
throw std::runtime_error(
|
||||
"Failed to load fixed UME MJCF '" +
|
||||
fixed_model_path + "': " + error.what());
|
||||
}
|
||||
try {
|
||||
pinocchio::mjcf::buildModel(
|
||||
floating_model_path, floating_model, false);
|
||||
} catch (const std::exception& error) {
|
||||
throw std::runtime_error(
|
||||
"Failed to load floating UME MJCF '" +
|
||||
floating_model_path + "': " + error.what());
|
||||
}
|
||||
|
||||
validateFixedModel(fixed_model, fixed_frame_ids);
|
||||
const auto imu_frame_id =
|
||||
validateFloatingModel(floating_model);
|
||||
|
||||
fixed_data =
|
||||
std::make_unique<pinocchio::Data>(fixed_model);
|
||||
floating_data =
|
||||
std::make_unique<pinocchio::Data>(floating_model);
|
||||
fixed_q =
|
||||
Eigen::VectorXd::Zero(fixed_model.nq);
|
||||
floating_q =
|
||||
Eigen::VectorXd::Zero(floating_model.nq);
|
||||
floating_velocity =
|
||||
Eigen::VectorXd::Zero(floating_model.nv);
|
||||
floating_acceleration =
|
||||
Eigen::VectorXd::Zero(floating_model.nv);
|
||||
shoulder_jacobian =
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic>::Zero(
|
||||
6, fixed_model.nv);
|
||||
wrist_jacobian =
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic>::Zero(
|
||||
6, fixed_model.nv);
|
||||
|
||||
Eigen::VectorXd neutral =
|
||||
pinocchio::neutral(floating_model);
|
||||
pinocchio::framesForwardKinematics(
|
||||
floating_model, *floating_data, neutral);
|
||||
base_from_imu =
|
||||
floating_data->oMf[imu_frame_id];
|
||||
|
||||
const Eigen::Matrix4d base_from_imu_matrix =
|
||||
base_from_imu.toHomogeneousMatrix();
|
||||
if (!base_from_imu_matrix.allFinite()) {
|
||||
throw contractError(
|
||||
"floating", "non-finite base_from_imu transform");
|
||||
}
|
||||
|
||||
contract_info.fixed_nq =
|
||||
static_cast<std::size_t>(fixed_model.nq);
|
||||
contract_info.fixed_nv =
|
||||
static_cast<std::size_t>(fixed_model.nv);
|
||||
contract_info.floating_nq =
|
||||
static_cast<std::size_t>(floating_model.nq);
|
||||
contract_info.floating_nv =
|
||||
static_cast<std::size_t>(floating_model.nv);
|
||||
contract_info.base_from_imu =
|
||||
toRowMajor(base_from_imu_matrix);
|
||||
}
|
||||
|
||||
std::string fixed_model_path;
|
||||
std::string floating_model_path;
|
||||
pinocchio::Model fixed_model;
|
||||
pinocchio::Model floating_model;
|
||||
std::unique_ptr<pinocchio::Data> fixed_data;
|
||||
std::unique_ptr<pinocchio::Data> floating_data;
|
||||
std::array<pinocchio::FrameIndex, 4> fixed_frame_ids{};
|
||||
pinocchio::SE3 base_from_imu{pinocchio::SE3::Identity()};
|
||||
UmeLegacyModelContract contract_info;
|
||||
|
||||
// Reused by the single controller thread. This keeps the 2 kHz legacy
|
||||
// model path free of avoidable Eigen heap allocation after construction.
|
||||
Eigen::VectorXd fixed_q;
|
||||
Eigen::VectorXd floating_q;
|
||||
Eigen::VectorXd floating_velocity;
|
||||
Eigen::VectorXd floating_acceleration;
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> shoulder_jacobian;
|
||||
Eigen::Matrix<double, 6, Eigen::Dynamic> wrist_jacobian;
|
||||
};
|
||||
|
||||
PinocchioUmeLegacyModelAdapter::PinocchioUmeLegacyModelAdapter(
|
||||
std::string fixed_model_path,
|
||||
std::string floating_model_path)
|
||||
: impl_(std::make_unique<Impl>(
|
||||
std::move(fixed_model_path),
|
||||
std::move(floating_model_path)))
|
||||
{
|
||||
}
|
||||
|
||||
PinocchioUmeLegacyModelAdapter::
|
||||
~PinocchioUmeLegacyModelAdapter() = default;
|
||||
|
||||
PinocchioUmeLegacyModelAdapter::PinocchioUmeLegacyModelAdapter(
|
||||
PinocchioUmeLegacyModelAdapter&&) noexcept = default;
|
||||
|
||||
PinocchioUmeLegacyModelAdapter&
|
||||
PinocchioUmeLegacyModelAdapter::operator=(
|
||||
PinocchioUmeLegacyModelAdapter&&) noexcept = default;
|
||||
|
||||
bool PinocchioUmeLegacyModelAdapter::computeGravityCompensation(
|
||||
const BimanualModelState& state,
|
||||
JointVector& right_gravity_nm,
|
||||
JointVector& left_gravity_nm) const
|
||||
{
|
||||
right_gravity_nm = {};
|
||||
left_gravity_nm = {};
|
||||
|
||||
if (!impl_ ||
|
||||
!finite(state.right_position_rad) ||
|
||||
!finite(state.right_velocity_rad_s) ||
|
||||
!finite(state.left_position_rad) ||
|
||||
!finite(state.left_velocity_rad_s)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Isometry3d world_from_imu;
|
||||
if (!toIsometry(state.world_from_imu, world_from_imu)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Isometry3d base_from_imu =
|
||||
Eigen::Isometry3d::Identity();
|
||||
base_from_imu.linear() =
|
||||
impl_->base_from_imu.rotation();
|
||||
base_from_imu.translation() =
|
||||
impl_->base_from_imu.translation();
|
||||
const Eigen::Isometry3d world_from_base =
|
||||
world_from_imu * base_from_imu.inverse();
|
||||
|
||||
Eigen::Quaterniond world_q_base(
|
||||
world_from_base.rotation());
|
||||
if (!world_q_base.coeffs().allFinite() ||
|
||||
world_q_base.norm() <= 0.0) {
|
||||
return false;
|
||||
}
|
||||
world_q_base.normalize();
|
||||
|
||||
auto& q = impl_->floating_q;
|
||||
auto& velocity = impl_->floating_velocity;
|
||||
auto& acceleration = impl_->floating_acceleration;
|
||||
q.setZero();
|
||||
velocity.setZero();
|
||||
acceleration.setZero();
|
||||
|
||||
q.segment<3>(0) = world_from_base.translation();
|
||||
q.segment<4>(3) = world_q_base.coeffs();
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
q[static_cast<Eigen::Index>(7 + index)] =
|
||||
state.right_position_rad[index];
|
||||
q[static_cast<Eigen::Index>(15 + index)] =
|
||||
state.left_position_rad[index];
|
||||
velocity[static_cast<Eigen::Index>(6 + index)] =
|
||||
state.right_velocity_rad_s[index];
|
||||
velocity[static_cast<Eigen::Index>(14 + index)] =
|
||||
state.left_velocity_rad_s[index];
|
||||
}
|
||||
|
||||
const auto& torque = pinocchio::rnea(
|
||||
impl_->floating_model,
|
||||
*impl_->floating_data,
|
||||
q,
|
||||
velocity,
|
||||
acceleration);
|
||||
if (!torque.allFinite() || torque.size() != 22) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
right_gravity_nm[index] =
|
||||
torque[static_cast<Eigen::Index>(6 + index)];
|
||||
left_gravity_nm[index] =
|
||||
torque[static_cast<Eigen::Index>(14 + index)];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PinocchioUmeLegacyModelAdapter::projectHapticFeedback(
|
||||
const BimanualModelState& state,
|
||||
ArmSide side,
|
||||
const RawHapticFeedback& feedback,
|
||||
ProjectedHapticEffort& projected) const
|
||||
{
|
||||
projected = {};
|
||||
if (!impl_ ||
|
||||
(side != ArmSide::Right &&
|
||||
side != ArmSide::Left) ||
|
||||
!finite(state.right_position_rad) ||
|
||||
!finite(state.left_position_rad) ||
|
||||
!finite(feedback.shoulder_moment) ||
|
||||
!finite(feedback.wrist_moment) ||
|
||||
!std::isfinite(feedback.elbow_effort) ||
|
||||
!std::isfinite(feedback.gripper_effort)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto& q = impl_->fixed_q;
|
||||
q.setZero();
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
q[static_cast<Eigen::Index>(index)] =
|
||||
state.right_position_rad[index];
|
||||
q[static_cast<Eigen::Index>(8 + index)] =
|
||||
state.left_position_rad[index];
|
||||
}
|
||||
|
||||
pinocchio::framesForwardKinematics(
|
||||
impl_->fixed_model, *impl_->fixed_data, q);
|
||||
|
||||
const std::size_t frame_offset =
|
||||
side == ArmSide::Right ? 0 : 2;
|
||||
const Eigen::Index shoulder_column =
|
||||
side == ArmSide::Right ? 0 : 8;
|
||||
const Eigen::Index wrist_column =
|
||||
side == ArmSide::Right ? 4 : 12;
|
||||
|
||||
auto& shoulder_jacobian = impl_->shoulder_jacobian;
|
||||
shoulder_jacobian.setZero();
|
||||
pinocchio::computeFrameJacobian(
|
||||
impl_->fixed_model,
|
||||
*impl_->fixed_data,
|
||||
q,
|
||||
impl_->fixed_frame_ids[frame_offset],
|
||||
pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED,
|
||||
shoulder_jacobian);
|
||||
|
||||
auto& wrist_jacobian = impl_->wrist_jacobian;
|
||||
wrist_jacobian.setZero();
|
||||
pinocchio::computeFrameJacobian(
|
||||
impl_->fixed_model,
|
||||
*impl_->fixed_data,
|
||||
q,
|
||||
impl_->fixed_frame_ids[frame_offset + 1],
|
||||
pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED,
|
||||
wrist_jacobian);
|
||||
|
||||
if (!shoulder_jacobian.allFinite() ||
|
||||
!wrist_jacobian.allFinite()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const Eigen::Vector3d shoulder_torque =
|
||||
shoulder_jacobian
|
||||
.block<3, 3>(3, shoulder_column)
|
||||
.transpose() *
|
||||
toEigen(feedback.shoulder_moment);
|
||||
const Eigen::Vector3d wrist_torque =
|
||||
wrist_jacobian
|
||||
.block<3, 3>(3, wrist_column)
|
||||
.transpose() *
|
||||
toEigen(feedback.wrist_moment);
|
||||
if (!shoulder_torque.allFinite() ||
|
||||
!wrist_torque.allFinite()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
projected.shoulder_joint_torque =
|
||||
fromEigen(shoulder_torque);
|
||||
projected.elbow_effort = feedback.elbow_effort;
|
||||
projected.wrist_joint_torque =
|
||||
fromEigen(wrist_torque);
|
||||
projected.gripper_effort = feedback.gripper_effort;
|
||||
return true;
|
||||
}
|
||||
|
||||
const UmeLegacyModelContract&
|
||||
PinocchioUmeLegacyModelAdapter::contract() const noexcept
|
||||
{
|
||||
return impl_->contract_info;
|
||||
}
|
||||
|
||||
const std::string&
|
||||
PinocchioUmeLegacyModelAdapter::fixedModelPath() const noexcept
|
||||
{
|
||||
return impl_->fixed_model_path;
|
||||
}
|
||||
|
||||
const std::string&
|
||||
PinocchioUmeLegacyModelAdapter::floatingModelPath() const noexcept
|
||||
{
|
||||
return impl_->floating_model_path;
|
||||
}
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
@ -0,0 +1,193 @@
|
||||
#include "ume_legacy_controller.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace cmvr::ume_legacy {
|
||||
namespace {
|
||||
|
||||
constexpr double kPi =
|
||||
3.141592653589793238462643383279502884;
|
||||
|
||||
double legacyClip(double value, double minimum, double maximum) noexcept
|
||||
{
|
||||
// Explicit comparisons preserve NaN propagation: both comparisons are
|
||||
// false and value is returned, matching np.clip for a NaN input.
|
||||
if (value < minimum) {
|
||||
return minimum;
|
||||
}
|
||||
if (value > maximum) {
|
||||
return maximum;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
double norm(const Vector3& value) noexcept
|
||||
{
|
||||
return std::sqrt(value[0] * value[0] +
|
||||
value[1] * value[1] +
|
||||
value[2] * value[2]);
|
||||
}
|
||||
|
||||
JointVector flattenInteraction(
|
||||
ArmSide side,
|
||||
const ProjectedHapticEffort& projected) noexcept
|
||||
{
|
||||
JointVector interaction{
|
||||
projected.shoulder_joint_torque[0],
|
||||
projected.shoulder_joint_torque[1],
|
||||
projected.shoulder_joint_torque[2],
|
||||
projected.elbow_effort,
|
||||
projected.wrist_joint_torque[0],
|
||||
projected.wrist_joint_torque[1],
|
||||
projected.wrist_joint_torque[2],
|
||||
projected.gripper_effort};
|
||||
|
||||
// Exact scalar sign conventions from the legacy controller:
|
||||
// right elbow +, right gripper -
|
||||
// left elbow -, left gripper +
|
||||
if (side == ArmSide::Right) {
|
||||
interaction[7] = -interaction[7];
|
||||
} else {
|
||||
interaction[3] = -interaction[3];
|
||||
}
|
||||
return interaction;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
LegacyUmeTuning originalTuning() noexcept
|
||||
{
|
||||
LegacyUmeTuning tuning;
|
||||
tuning.friction_coefficient =
|
||||
{1.6, 1.6, 1.6, 1.6, 0.032, 0.032, 0.032, 0.032};
|
||||
tuning.friction_max_compensation =
|
||||
{0.4, 0.4, 0.4, 0.4, 0.1, 0.1, 0.1, 0.1};
|
||||
|
||||
const double one_degree = kPi / 180.0;
|
||||
const double ten_degrees = 10.0 * one_degree;
|
||||
tuning.stiction_threshold_min_rad_s =
|
||||
{one_degree, one_degree, one_degree, one_degree,
|
||||
one_degree, one_degree, one_degree, one_degree};
|
||||
tuning.stiction_threshold_max_rad_s =
|
||||
{ten_degrees, ten_degrees, ten_degrees, ten_degrees,
|
||||
ten_degrees, ten_degrees, ten_degrees, ten_degrees};
|
||||
tuning.stiction_compensation =
|
||||
{0.5, 0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0};
|
||||
|
||||
tuning.feedback_error_tolerance_rad = one_degree;
|
||||
tuning.feedback_tanh_sharpness = 10.0;
|
||||
tuning.feedback_scale = 0.5;
|
||||
tuning.feedback_limit_dm4340_nm = 4.0;
|
||||
tuning.feedback_limit_dm4310_nm = 1.0;
|
||||
return tuning;
|
||||
}
|
||||
|
||||
JointVector frictionCompensation(
|
||||
const JointVector& velocity_rad_s,
|
||||
const LegacyUmeTuning& tuning) noexcept
|
||||
{
|
||||
JointVector result{};
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
const double maximum =
|
||||
tuning.friction_max_compensation[index];
|
||||
result[index] = legacyClip(
|
||||
tuning.friction_coefficient[index] *
|
||||
velocity_rad_s[index],
|
||||
-maximum,
|
||||
maximum);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
JointVector stictionCompensation(
|
||||
const JointVector& velocity_rad_s,
|
||||
const LegacyUmeTuning& tuning) noexcept
|
||||
{
|
||||
JointVector result{};
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
const double velocity = velocity_rad_s[index];
|
||||
const double speed = std::abs(velocity);
|
||||
|
||||
// Both inequalities are intentionally strict, matching:
|
||||
// min < abs(qvel) < max.
|
||||
if (tuning.stiction_threshold_min_rad_s[index] < speed &&
|
||||
speed < tuning.stiction_threshold_max_rad_s[index]) {
|
||||
if (velocity > 0.0) {
|
||||
result[index] =
|
||||
tuning.stiction_compensation[index];
|
||||
} else if (velocity < 0.0) {
|
||||
result[index] =
|
||||
-tuning.stiction_compensation[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
double feedbackScale(
|
||||
double error_norm,
|
||||
const LegacyUmeTuning& tuning) noexcept
|
||||
{
|
||||
return tuning.feedback_scale *
|
||||
(std::tanh(
|
||||
tuning.feedback_tanh_sharpness *
|
||||
(std::abs(error_norm) -
|
||||
tuning.feedback_error_tolerance_rad)) +
|
||||
1.0) /
|
||||
2.0;
|
||||
}
|
||||
|
||||
SideControlOutput computeSideCommand(
|
||||
const SideControlInput& input,
|
||||
const LegacyUmeTuning& tuning) noexcept
|
||||
{
|
||||
SideControlOutput output;
|
||||
output.friction_compensation_nm =
|
||||
frictionCompensation(input.joint_velocity_rad_s, tuning);
|
||||
output.stiction_compensation_nm =
|
||||
stictionCompensation(input.joint_velocity_rad_s, tuning);
|
||||
output.signed_interaction_nm =
|
||||
flattenInteraction(input.side, input.projected_haptic);
|
||||
|
||||
output.feedback_scales.shoulder =
|
||||
feedbackScale(norm(input.tracking_error.shoulder_rotation),
|
||||
tuning);
|
||||
output.feedback_scales.elbow =
|
||||
feedbackScale(std::abs(input.tracking_error.elbow), tuning);
|
||||
output.feedback_scales.wrist =
|
||||
feedbackScale(norm(input.tracking_error.wrist_rotation),
|
||||
tuning);
|
||||
output.feedback_scales.gripper =
|
||||
feedbackScale(std::abs(input.tracking_error.gripper), tuning);
|
||||
|
||||
for (std::size_t index = 0; index < kArmDof; ++index) {
|
||||
output.feedforward_without_haptic_nm[index] =
|
||||
input.gravity_compensation_nm[index] +
|
||||
output.friction_compensation_nm[index] +
|
||||
output.stiction_compensation_nm[index];
|
||||
|
||||
double scale = output.feedback_scales.gripper;
|
||||
double limit = tuning.feedback_limit_dm4310_nm;
|
||||
if (index < 3) {
|
||||
scale = output.feedback_scales.shoulder;
|
||||
limit = tuning.feedback_limit_dm4340_nm;
|
||||
} else if (index == 3) {
|
||||
scale = output.feedback_scales.elbow;
|
||||
limit = tuning.feedback_limit_dm4340_nm;
|
||||
} else if (index < 7) {
|
||||
scale = output.feedback_scales.wrist;
|
||||
}
|
||||
|
||||
output.limited_feedback_nm[index] = legacyClip(
|
||||
scale * output.signed_interaction_nm[index],
|
||||
-limit,
|
||||
limit);
|
||||
output.command_torque_nm[index] =
|
||||
output.feedforward_without_haptic_nm[index] -
|
||||
output.limited_feedback_nm[index];
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace cmvr::ume_legacy
|
||||
@ -28,20 +28,3 @@ target_link_libraries(common PUBLIC
|
||||
|
||||
add_library(cmvr_es::common ALIAS common)
|
||||
install(TARGETS common LIBRARY DESTINATION lib)
|
||||
|
||||
#add_executable(image_display_test
|
||||
# utils/visualization/image_display_test.cpp
|
||||
#)
|
||||
#
|
||||
#target_link_libraries(image_display_test
|
||||
# PRIVATE
|
||||
# cmvr_es::common
|
||||
# cmvr_es::perception
|
||||
# cmvr_es::device::realsense_camera
|
||||
# cmvr_es::proto
|
||||
# glog
|
||||
# gtest
|
||||
# gtest_main
|
||||
# pthread
|
||||
#)
|
||||
#
|
||||
|
||||
111
cmvr-es/common/README.md
Normal file
111
cmvr-es/common/README.md
Normal file
@ -0,0 +1,111 @@
|
||||
# Common 模块开发指南
|
||||
|
||||
`common/` 保存可被设备、算法、管理器和协议层复用的基础能力。这里适合放稳定、协议无关、厂商无关的类型与工具,不适合放设备连接、业务服务或任务调度逻辑。
|
||||
|
||||
返回[项目总览](../../README.md)。
|
||||
|
||||
## 目录职责
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
| `base/` | 日志、基础常量、gRPC 辅助函数和线程安全缓冲区 |
|
||||
| `config/` | 配置根目录解析和 Proto Text 配置加载 |
|
||||
| `io/` | Protobuf 二进制与 TextFormat 文件读写 |
|
||||
| `math/` | 坐标变换、关节限制、QP 和运动数学 |
|
||||
| `media/` | 协议无关媒体模型以及 FFmpeg 采集、编码、写文件能力 |
|
||||
| `types/` | 跨后端共享的领域类型,例如 AGV、机械臂和几何类型 |
|
||||
| `vision/` | 图像显示、投影等视觉辅助代码 |
|
||||
|
||||
## 依赖边界
|
||||
|
||||
新增公共组件时应遵守:
|
||||
|
||||
- 不依赖 `service/`、`task/` 或具体厂商设备实现;
|
||||
- 不保存 gRPC/QUIC 连接、session 或客户端状态;
|
||||
- 通用类型不包含厂商报文字段、端口号和私有错误码;
|
||||
- 需要调用设备的逻辑应放在 manager adapter、service 或 task;
|
||||
- 需要第三方库的 `.cpp` 组件应通过明确的 CMake target 暴露依赖;
|
||||
- 避免在公共头文件中使用全局 `using namespace` 或引入大体量实现头。
|
||||
|
||||
当前 `common` 共享库目标是 `cmvr_es::common`,日志是独立目标 `cmvr_es::logging`。新增 `.cpp` 文件时,需要更新 [`CMakeLists.txt`](CMakeLists.txt) 或对应子目录 CMake;纯头文件不需要加入 `add_library` 源文件列表。
|
||||
|
||||
## 新增共享类型
|
||||
|
||||
1. 选择 `types/<domain>/` 或已有领域文件;
|
||||
2. 类型使用明确单位,例如米、弧度、秒、纳秒;
|
||||
3. 为容器长度、自由度和数值范围提供校验函数;
|
||||
4. 保持控制器无关,将厂商字段转换为通用枚举或结果;
|
||||
5. 确认不会迫使所有调用方引入设备 SDK;
|
||||
6. 增加边界值和错误输入测试。
|
||||
|
||||
AGV 通用类型应参考 [`types/agv/agv_types.h`](types/agv/agv_types.h),机械臂通用类型应参考 [`types/arm/arm_types.h`](types/arm/arm_types.h)。不要为了一个具体控制器把协议结构塞回 `abstract_*.h`。
|
||||
|
||||
## 媒体模型
|
||||
|
||||
[`media/media_frame.h`](media/media_frame.h) 中的 `TrackDescriptor`、`MediaFrame` 及 payload 在构造后不可变,可被多个协议消费者共享。
|
||||
|
||||
扩展媒体字段时需要保持:
|
||||
|
||||
- `TrackDescriptor::generation` 非零,编码参数变化时创建新 descriptor;
|
||||
- PTS、DTS 和 duration 使用 descriptor 的 `time_base`;
|
||||
- `capture_time_ns` 使用单调时钟,供节奏控制和延迟统计;
|
||||
- `capture_utc_ns` 只作为可选墙上时间,不能用于计算持续时间;
|
||||
- H.264/H.265 明确 `ANNEX_B` 或 `AVCC`;
|
||||
- AAC、Opus、PCM 明确 payload format、采样率和声道数;
|
||||
- 不把 QUIC、gRPC 或浏览器专有字段加入通用帧。
|
||||
|
||||
设备媒体接入流程见 [`../manager/README.md`](../manager/README.md) 的 MediaSourceManager 章节。
|
||||
|
||||
## 环形队列选择
|
||||
|
||||
[`base/ring_buffer.h`](base/ring_buffer.h) 当前包含三类缓冲区:
|
||||
|
||||
| 类型 | 使用场景 | 重要约束 |
|
||||
| --- | --- | --- |
|
||||
| `RingBuffer<T>` | 只需要保存最近 N 项并批量读取 | 覆盖最旧项,没有阻塞读取 |
|
||||
| `SPMCRingBuffer<T>` | 历史单生产者场景 | 独立 `reader_tail` 只能由一个线程拥有 |
|
||||
| `BroadcastFrameRing<T>` | 新的媒体或广播式多消费者场景 | 每个消费者使用独立 Cursor,保存不可变共享对象 |
|
||||
|
||||
新的实时多消费者模块优先使用 `BroadcastFrameRing<T>`:
|
||||
|
||||
- capacity 必须大于零;
|
||||
- 同一 Cursor 不得被多个线程同时读取或移动;
|
||||
- 慢消费者落后时会跳到最旧保留项,并得到精确 dropped count;
|
||||
- `reset()` 开启新 generation,旧 Cursor 在下一次成功读取时看到变化;
|
||||
- `close()` 唤醒等待者,关闭后不能继续发布;
|
||||
- 不要先读取 head 再无锁读取槽位,应使用队列提供的原子读取接口。
|
||||
|
||||
## 配置和文件路径
|
||||
|
||||
[`config/config_files.h`](config/config_files.h) 提供:
|
||||
|
||||
- `resolveConfigFile()`:相对根配置目录解析业务配置;
|
||||
- `resolveResourceFile()`:在配置根及其父目录中查找模型等资源;
|
||||
- `loadConfigFile()` / `saveConfigFile()`:读写 Proto Text 配置。
|
||||
|
||||
进程启动后配置根由 `main.cpp` 设置。公共组件不应自行使用当前工作目录拼接配置路径。
|
||||
|
||||
[`io/proto_file_io.h`](io/proto_file_io.h) 写出的 TextFormat 文件权限为 `0600`。保存运行时配置前,应确认目标目录存在,并避免把生产密钥写入仓库。
|
||||
|
||||
## 新增公共组件
|
||||
|
||||
1. 确认能力确实会被两个及以上模块复用;
|
||||
2. 定义最小 API 和所有权、线程安全、错误语义;
|
||||
3. 将头文件放入合适子目录,将实现放入相邻 `.cpp`;
|
||||
4. 更新 CMake target 和 `target_link_libraries`;
|
||||
5. 不使用未声明的传递依赖;
|
||||
6. 增加无设备单元测试;
|
||||
7. 对并发组件增加关闭、超时、覆盖、取消和析构测试;
|
||||
8. 使用 ASan/TSan 时检查生命周期和数据竞争。
|
||||
|
||||
推荐测试目标放在组件相邻的 `tests/`,并在 `BUILD_TESTING` 下通过 `add_test()` 登记。仅创建 `_test` 可执行文件不会自动进入 CTest。
|
||||
|
||||
## 提交检查
|
||||
|
||||
- [ ] API 不依赖具体设备或传输协议
|
||||
- [ ] 公共类型有明确单位和有效性规则
|
||||
- [ ] 所有权及线程安全写入注释
|
||||
- [ ] 新增 `.cpp` 和依赖已经加入 CMake
|
||||
- [ ] 缓冲区关闭能够唤醒等待线程
|
||||
- [ ] 不记录密码、私钥或大块媒体 payload
|
||||
- [ ] 无设备测试可以在开发主机运行
|
||||
@ -167,6 +167,15 @@ void Logger::shutdown()
|
||||
initialized_ = false;
|
||||
}
|
||||
|
||||
void Logger::flush()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (log_file_.is_open()) {
|
||||
log_file_.flush();
|
||||
last_flush_ = std::chrono::steady_clock::now();
|
||||
}
|
||||
}
|
||||
|
||||
bool Logger::enabled(const Level level) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@ -200,7 +209,8 @@ void Logger::write(const Level level,
|
||||
rotateIfNeeded_();
|
||||
log_file_ << line << '\n';
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (level == Level::ERROR || level == Level::FATAL || now - last_flush_ >= flush_interval_) {
|
||||
if (level == Level::ERROR || level == Level::FATAL ||
|
||||
now - last_flush_ >= flush_interval_) {
|
||||
log_file_.flush();
|
||||
last_flush_ = now;
|
||||
}
|
||||
|
||||
@ -43,6 +43,7 @@ public:
|
||||
const std::string& application_name,
|
||||
const std::filesystem::path& executable_directory);
|
||||
void shutdown();
|
||||
void flush();
|
||||
bool enabled(Level level) const;
|
||||
void write(Level level, const char* source_file, int source_line, const std::string& message);
|
||||
|
||||
|
||||
@ -6,16 +6,25 @@
|
||||
#define CMVR_ES_RING_BUFFER_H
|
||||
|
||||
#pragma once
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
template<typename T>
|
||||
class RingBuffer {
|
||||
public:
|
||||
explicit RingBuffer(size_t capacity) : capacity_(capacity) {}
|
||||
explicit RingBuffer(size_t capacity) : capacity_(capacity) {
|
||||
if (capacity_ == 0) {
|
||||
throw std::invalid_argument("RingBuffer capacity must be greater than zero");
|
||||
}
|
||||
}
|
||||
|
||||
void push(const T& item) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@ -50,47 +59,49 @@ template<typename T>
|
||||
class SPMCRingBuffer {
|
||||
public:
|
||||
explicit SPMCRingBuffer(size_t capacity)
|
||||
: buffer_(capacity), capacity_(capacity),
|
||||
head_(0), tail_(0) {}
|
||||
: buffer_(capacity), capacity_(capacity) {
|
||||
if (capacity_ == 0) {
|
||||
throw std::invalid_argument("SPMCRingBuffer capacity must be greater than zero");
|
||||
}
|
||||
}
|
||||
|
||||
// 写入操作(仅支持单个生产者)
|
||||
void push(const T& item) {
|
||||
size_t head = head_.load(std::memory_order_relaxed);
|
||||
size_t tail = tail_.load(std::memory_order_acquire);
|
||||
buffer_[head % capacity_] = item;
|
||||
head = head + 1;
|
||||
head_.store(head, std::memory_order_release);
|
||||
if (head - tail >= capacity_) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
buffer_[head_ % capacity_] = item;
|
||||
++head_;
|
||||
if (head_ - tail_ > capacity_) {
|
||||
// 队列满,覆盖最旧的数据
|
||||
tail_.store(tail + 1, std::memory_order_release);
|
||||
tail_ = head_ - capacity_;
|
||||
}
|
||||
}
|
||||
condition_.notify_all();
|
||||
}
|
||||
|
||||
// 单消费者使用(内部 tail_)
|
||||
std::optional<T> pop() {
|
||||
size_t tail = tail_.load(std::memory_order_relaxed);
|
||||
size_t head = head_.load(std::memory_order_acquire);
|
||||
if (tail >= head) return std::nullopt;
|
||||
T value = buffer_[tail % capacity_];
|
||||
tail_.store(tail + 1, std::memory_order_release);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (tail_ >= head_) return std::nullopt;
|
||||
T value = buffer_[tail_ % capacity_];
|
||||
++tail_;
|
||||
return value;
|
||||
}
|
||||
|
||||
std::optional<T> getLast() {
|
||||
size_t tail = tail_.load(std::memory_order_relaxed);
|
||||
size_t head = head_.load(std::memory_order_acquire);
|
||||
if (tail >= head) return std::nullopt;
|
||||
T value = buffer_[head_ % capacity_];
|
||||
return value;
|
||||
std::optional<T> getLast() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (tail_ >= head_) return std::nullopt;
|
||||
return buffer_[(head_ - 1) % capacity_];
|
||||
}
|
||||
|
||||
// 多消费者使用(每个读者独立维护 reader_tail)
|
||||
// 多消费者使用(每个读者独立维护 reader_tail)。同一个 reader_tail 只能由
|
||||
// 一个消费线程拥有,且不要把该游标与无参 pop() 的共享 tail_ 混合作为同一路读取。
|
||||
std::optional<T> pop(size_t& reader_tail) const {
|
||||
size_t head = head_.load(std::memory_order_acquire);
|
||||
if (reader_tail >= head) return std::nullopt;
|
||||
if (head > reader_tail + capacity_) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (reader_tail >= head_) return std::nullopt;
|
||||
if (reader_tail < tail_) {
|
||||
// 数据已被覆盖,跳过无效读取区间
|
||||
reader_tail = head - capacity_;
|
||||
reader_tail = tail_;
|
||||
return std::nullopt;
|
||||
}
|
||||
T value = buffer_[reader_tail % capacity_];
|
||||
@ -98,16 +109,52 @@ public:
|
||||
return value;
|
||||
}
|
||||
|
||||
// 在同一次加锁中把独立读游标跳到当前最新元素并读取,避免先 getHead()
|
||||
// 再 pop() 时被高速覆盖造成的检查/读取竞态。
|
||||
std::optional<T> getLatest(size_t& reader_tail) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (tail_ >= head_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
reader_tail = head_ - 1;
|
||||
T value = buffer_[reader_tail % capacity_];
|
||||
++reader_tail;
|
||||
return value;
|
||||
}
|
||||
|
||||
template<class Rep, class Period>
|
||||
std::optional<T> waitPop(
|
||||
size_t& reader_tail,
|
||||
const std::chrono::duration<Rep, Period>& timeout) const {
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
condition_.wait_for(lock, timeout, [&] { return reader_tail < head_; });
|
||||
if (reader_tail >= head_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (reader_tail < tail_) {
|
||||
reader_tail = tail_;
|
||||
}
|
||||
if (reader_tail >= head_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
T value = buffer_[reader_tail % capacity_];
|
||||
++reader_tail;
|
||||
return value;
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return head_.load(std::memory_order_acquire) - tail_.load(std::memory_order_acquire);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return head_ - tail_;
|
||||
}
|
||||
|
||||
size_t getHead() const {
|
||||
return head_.load(std::memory_order_acquire);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return head_;
|
||||
}
|
||||
|
||||
size_t getTail() const {
|
||||
return tail_.load(std::memory_order_acquire);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return tail_;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
@ -119,16 +166,278 @@ public:
|
||||
}
|
||||
|
||||
void clear() {
|
||||
head_.store(0, std::memory_order_release);
|
||||
tail_.store(0, std::memory_order_release);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Keep sequence numbers monotonic so cursors created before clear()
|
||||
// cannot alias newly published slots after the reset.
|
||||
tail_ = head_;
|
||||
}
|
||||
condition_.notify_all();
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<T> buffer_;
|
||||
mutable std::vector<T> buffer_;
|
||||
const size_t capacity_;
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::condition_variable condition_;
|
||||
size_t head_{0}; // 单调写序号;clear() 仅推进 tail_,避免旧游标 ABA。
|
||||
size_t tail_{0}; // 当前仍保留的最旧序号,同时也是 pop() 的共享读指针。
|
||||
};
|
||||
|
||||
std::atomic<size_t> head_; // 共享写指针
|
||||
std::atomic<size_t> tail_; // 共享读指针(仅用于 SPSC 模式)
|
||||
// 线程安全的多消费者广播缓冲区。缓冲区只保存不可变共享对象,消费者通过各自
|
||||
// 的 Cursor 独立前进;慢消费者被覆盖的数据会累计到 Cursor::dropped_count。
|
||||
// Cursor 是单线程所有权对象,不可由多个线程同时读写;每个消费者应创建自己的 Cursor。
|
||||
template<typename T>
|
||||
class BroadcastFrameRing {
|
||||
public:
|
||||
using ValuePtr = std::shared_ptr<const T>;
|
||||
|
||||
enum class StartPosition {
|
||||
NEXT_PUBLISHED,
|
||||
OLDEST_AVAILABLE,
|
||||
LATEST_AVAILABLE
|
||||
};
|
||||
|
||||
struct Cursor {
|
||||
uint64_t generation{0};
|
||||
uint64_t next_sequence{0};
|
||||
uint64_t dropped_count{0};
|
||||
StartPosition start_position{StartPosition::NEXT_PUBLISHED};
|
||||
|
||||
private:
|
||||
bool generation_changed{false};
|
||||
uint64_t reported_dropped_count{0};
|
||||
friend class BroadcastFrameRing<T>;
|
||||
};
|
||||
|
||||
struct ReadResult {
|
||||
ValuePtr value;
|
||||
uint64_t generation{0};
|
||||
uint64_t sequence{0};
|
||||
uint64_t dropped_count{0};
|
||||
uint64_t dropped_since_last_read{0};
|
||||
bool generation_changed{false};
|
||||
};
|
||||
|
||||
struct Stats {
|
||||
size_t capacity{0};
|
||||
size_t size{0};
|
||||
uint64_t generation{0};
|
||||
uint64_t next_sequence{0};
|
||||
uint64_t dropped_count{0};
|
||||
bool closed{false};
|
||||
};
|
||||
|
||||
explicit BroadcastFrameRing(const size_t capacity)
|
||||
: capacity_(capacity) {
|
||||
if (capacity_ == 0) {
|
||||
throw std::invalid_argument("BroadcastFrameRing capacity must be greater than zero");
|
||||
}
|
||||
}
|
||||
|
||||
BroadcastFrameRing(const BroadcastFrameRing&) = delete;
|
||||
BroadcastFrameRing& operator=(const BroadcastFrameRing&) = delete;
|
||||
|
||||
Cursor makeCursor(const StartPosition start_position = StartPosition::NEXT_PUBLISHED) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
Cursor cursor;
|
||||
cursor.generation = generation_;
|
||||
cursor.start_position = start_position;
|
||||
cursor.next_sequence = startSequenceLocked_(start_position);
|
||||
return cursor;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> publish(ValuePtr value) {
|
||||
if (!value) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> published_sequence;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (closed_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const uint64_t sequence = next_sequence_++;
|
||||
if (entries_.size() == capacity_) {
|
||||
entries_.pop_front();
|
||||
++dropped_count_;
|
||||
}
|
||||
entries_.push_back(Entry{generation_, sequence, std::move(value)});
|
||||
published_sequence = sequence;
|
||||
}
|
||||
condition_.notify_all();
|
||||
return published_sequence;
|
||||
}
|
||||
|
||||
std::optional<ReadResult> tryRead(Cursor& cursor) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return tryReadLocked_(cursor);
|
||||
}
|
||||
|
||||
// Low-latency consumers can use this before reading to abandon an excessive
|
||||
// backlog atomically. When the number of currently readable entries exceeds
|
||||
// maximum_pending_frames, every pending entry is discarded and the cursor is
|
||||
// advanced to the next sequence that will be published. Frames already
|
||||
// overwritten by the ring and frames actively discarded here are both
|
||||
// reflected in Cursor::dropped_count; the next successful read reports their
|
||||
// sum through ReadResult::dropped_since_last_read.
|
||||
uint64_t discardPendingIfExceeds(
|
||||
Cursor& cursor,
|
||||
const size_t maximum_pending_frames) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
synchronizeCursorGenerationLocked_(cursor);
|
||||
|
||||
if (!entries_.empty()) {
|
||||
const uint64_t oldest_sequence = entries_.front().sequence;
|
||||
if (cursor.next_sequence < oldest_sequence) {
|
||||
cursor.dropped_count += oldest_sequence - cursor.next_sequence;
|
||||
cursor.next_sequence = oldest_sequence;
|
||||
}
|
||||
}
|
||||
|
||||
const uint64_t pending =
|
||||
cursor.next_sequence < next_sequence_
|
||||
? next_sequence_ - cursor.next_sequence
|
||||
: 0;
|
||||
if (pending <= static_cast<uint64_t>(maximum_pending_frames)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
cursor.next_sequence = next_sequence_;
|
||||
cursor.dropped_count += pending;
|
||||
return pending;
|
||||
}
|
||||
|
||||
template<class Rep, class Period>
|
||||
std::optional<ReadResult> waitRead(
|
||||
Cursor& cursor,
|
||||
const std::chrono::duration<Rep, Period>& timeout) const {
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
while (true) {
|
||||
if (auto result = tryReadLocked_(cursor)) {
|
||||
return result;
|
||||
}
|
||||
if (closed_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (condition_.wait_until(lock, deadline) == std::cv_status::timeout) {
|
||||
return tryReadLocked_(cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 开始一个新的发布代次。旧 Cursor 会在下一次成功读取时收到
|
||||
// generation_changed=true,序号从 0 重新开始。
|
||||
uint64_t reset() {
|
||||
uint64_t generation = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
entries_.clear();
|
||||
++generation_;
|
||||
next_sequence_ = 0;
|
||||
closed_ = false;
|
||||
generation = generation_;
|
||||
}
|
||||
condition_.notify_all();
|
||||
return generation;
|
||||
}
|
||||
|
||||
void close() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closed_ = true;
|
||||
}
|
||||
condition_.notify_all();
|
||||
}
|
||||
|
||||
bool closed() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return closed_;
|
||||
}
|
||||
|
||||
Stats stats() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return Stats{capacity_, entries_.size(), generation_, next_sequence_, dropped_count_, closed_};
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
uint64_t generation;
|
||||
uint64_t sequence;
|
||||
ValuePtr value;
|
||||
};
|
||||
|
||||
uint64_t startSequenceLocked_(const StartPosition start_position) const {
|
||||
if (entries_.empty()) {
|
||||
return next_sequence_;
|
||||
}
|
||||
switch (start_position) {
|
||||
case StartPosition::OLDEST_AVAILABLE:
|
||||
return entries_.front().sequence;
|
||||
case StartPosition::LATEST_AVAILABLE:
|
||||
return entries_.back().sequence;
|
||||
case StartPosition::NEXT_PUBLISHED:
|
||||
default:
|
||||
return next_sequence_;
|
||||
}
|
||||
}
|
||||
|
||||
void synchronizeCursorGenerationLocked_(Cursor& cursor) const {
|
||||
if (cursor.generation == generation_) {
|
||||
return;
|
||||
}
|
||||
cursor.generation = generation_;
|
||||
cursor.next_sequence = startSequenceLocked_(cursor.start_position);
|
||||
cursor.generation_changed = true;
|
||||
}
|
||||
|
||||
std::optional<ReadResult> tryReadLocked_(Cursor& cursor) const {
|
||||
synchronizeCursorGenerationLocked_(cursor);
|
||||
if (entries_.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const uint64_t oldest_sequence = entries_.front().sequence;
|
||||
if (cursor.next_sequence < oldest_sequence) {
|
||||
cursor.dropped_count += oldest_sequence - cursor.next_sequence;
|
||||
cursor.next_sequence = oldest_sequence;
|
||||
}
|
||||
if (cursor.next_sequence >= next_sequence_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const size_t index = static_cast<size_t>(cursor.next_sequence - oldest_sequence);
|
||||
if (index >= entries_.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const Entry& entry = entries_[index];
|
||||
++cursor.next_sequence;
|
||||
const uint64_t dropped_since_last = cursor.dropped_count - cursor.reported_dropped_count;
|
||||
cursor.reported_dropped_count = cursor.dropped_count;
|
||||
|
||||
ReadResult result;
|
||||
result.value = entry.value;
|
||||
result.generation = entry.generation;
|
||||
result.sequence = entry.sequence;
|
||||
result.dropped_count = cursor.dropped_count;
|
||||
result.dropped_since_last_read = dropped_since_last;
|
||||
result.generation_changed = cursor.generation_changed;
|
||||
cursor.generation_changed = false;
|
||||
return result;
|
||||
}
|
||||
|
||||
const size_t capacity_;
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::condition_variable condition_;
|
||||
std::deque<Entry> entries_;
|
||||
uint64_t generation_{1};
|
||||
uint64_t next_sequence_{0};
|
||||
uint64_t dropped_count_{0};
|
||||
bool closed_{false};
|
||||
};
|
||||
|
||||
|
||||
|
||||
244
cmvr-es/common/media/media_frame.h
Normal file
244
cmvr-es/common/media/media_frame.h
Normal file
@ -0,0 +1,244 @@
|
||||
#ifndef CMVR_ES_COMMON_MEDIA_MEDIA_FRAME_H
|
||||
#define CMVR_ES_COMMON_MEDIA_MEDIA_FRAME_H
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr::media {
|
||||
|
||||
enum class MediaKind : uint8_t {
|
||||
UNKNOWN = 0,
|
||||
VIDEO = 1,
|
||||
AUDIO = 2
|
||||
};
|
||||
|
||||
enum class Codec : uint8_t {
|
||||
UNKNOWN = 0,
|
||||
H264 = 1,
|
||||
H265 = 2,
|
||||
OPUS = 3,
|
||||
PCM_S16LE = 4,
|
||||
AAC = 5
|
||||
};
|
||||
|
||||
enum class PayloadFormat : uint8_t {
|
||||
UNKNOWN = 0,
|
||||
ANNEX_B = 1,
|
||||
AVCC = 2,
|
||||
RAW = 3,
|
||||
OPUS_PACKET = 4,
|
||||
AAC_ADTS = 5
|
||||
};
|
||||
|
||||
struct Rational {
|
||||
int32_t numerator{0};
|
||||
int32_t denominator{1};
|
||||
|
||||
constexpr bool valid() const noexcept {
|
||||
return numerator > 0 && denominator > 0;
|
||||
}
|
||||
};
|
||||
|
||||
constexpr bool operator==(const Rational lhs, const Rational rhs) noexcept {
|
||||
return lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator;
|
||||
}
|
||||
|
||||
constexpr bool operator!=(const Rational lhs, const Rational rhs) noexcept {
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
// A TrackDescriptor is immutable after construction. Reconfiguration is represented by
|
||||
// publishing a new descriptor with a larger generation and attaching it to later frames.
|
||||
class TrackDescriptor final {
|
||||
public:
|
||||
struct Config {
|
||||
std::string id;
|
||||
std::string source_id;
|
||||
MediaKind kind{MediaKind::UNKNOWN};
|
||||
Codec codec{Codec::UNKNOWN};
|
||||
PayloadFormat payload_format{PayloadFormat::UNKNOWN};
|
||||
Rational time_base{};
|
||||
uint32_t width{0};
|
||||
uint32_t height{0};
|
||||
uint32_t sample_rate{0};
|
||||
uint32_t channels{0};
|
||||
uint32_t nominal_rate{0};
|
||||
float fx{0.0F};
|
||||
float fy{0.0F};
|
||||
float cx{0.0F};
|
||||
float cy{0.0F};
|
||||
std::vector<float> distortion;
|
||||
uint64_t generation{1};
|
||||
std::vector<uint8_t> codec_config;
|
||||
};
|
||||
|
||||
explicit TrackDescriptor(Config config)
|
||||
: id(std::move(config.id)),
|
||||
source_id(std::move(config.source_id)),
|
||||
kind(config.kind),
|
||||
codec(config.codec),
|
||||
payload_format(config.payload_format),
|
||||
time_base(config.time_base),
|
||||
width(config.width),
|
||||
height(config.height),
|
||||
sample_rate(config.sample_rate),
|
||||
channels(config.channels),
|
||||
nominal_rate(config.nominal_rate),
|
||||
fx(config.fx),
|
||||
fy(config.fy),
|
||||
cx(config.cx),
|
||||
cy(config.cy),
|
||||
distortion(std::move(config.distortion)),
|
||||
generation(config.generation),
|
||||
codec_config(std::move(config.codec_config)) {
|
||||
if (id.empty()) {
|
||||
throw std::invalid_argument("TrackDescriptor id must not be empty");
|
||||
}
|
||||
if (source_id.empty()) {
|
||||
throw std::invalid_argument("TrackDescriptor source_id must not be empty");
|
||||
}
|
||||
if (kind == MediaKind::UNKNOWN) {
|
||||
throw std::invalid_argument("TrackDescriptor kind must not be UNKNOWN");
|
||||
}
|
||||
if (!time_base.valid()) {
|
||||
throw std::invalid_argument("TrackDescriptor time_base is invalid");
|
||||
}
|
||||
if (generation == 0) {
|
||||
throw std::invalid_argument("TrackDescriptor generation must be greater than zero");
|
||||
}
|
||||
}
|
||||
|
||||
const std::string id;
|
||||
const std::string source_id;
|
||||
const MediaKind kind;
|
||||
const Codec codec;
|
||||
const PayloadFormat payload_format;
|
||||
const Rational time_base;
|
||||
const uint32_t width;
|
||||
const uint32_t height;
|
||||
const uint32_t sample_rate;
|
||||
const uint32_t channels;
|
||||
const uint32_t nominal_rate;
|
||||
const float fx;
|
||||
const float fy;
|
||||
const float cx;
|
||||
const float cy;
|
||||
const std::vector<float> distortion;
|
||||
const uint64_t generation;
|
||||
const std::vector<uint8_t> codec_config;
|
||||
};
|
||||
|
||||
using TrackDescriptorPtr = std::shared_ptr<const TrackDescriptor>;
|
||||
|
||||
inline bool equivalentTrackDescriptor(
|
||||
const TrackDescriptor& lhs,
|
||||
const TrackDescriptor& rhs) noexcept {
|
||||
return lhs.id == rhs.id &&
|
||||
lhs.source_id == rhs.source_id &&
|
||||
lhs.kind == rhs.kind &&
|
||||
lhs.codec == rhs.codec &&
|
||||
lhs.payload_format == rhs.payload_format &&
|
||||
lhs.time_base == rhs.time_base &&
|
||||
lhs.width == rhs.width &&
|
||||
lhs.height == rhs.height &&
|
||||
lhs.sample_rate == rhs.sample_rate &&
|
||||
lhs.channels == rhs.channels &&
|
||||
lhs.nominal_rate == rhs.nominal_rate &&
|
||||
lhs.fx == rhs.fx &&
|
||||
lhs.fy == rhs.fy &&
|
||||
lhs.cx == rhs.cx &&
|
||||
lhs.cy == rhs.cy &&
|
||||
lhs.distortion == rhs.distortion &&
|
||||
lhs.generation == rhs.generation &&
|
||||
lhs.codec_config == rhs.codec_config;
|
||||
}
|
||||
|
||||
// MediaFrame and its payload are immutable and therefore safe to share across all protocol
|
||||
// adapters and consumers without copying. PTS/DTS use TrackDescriptor::time_base;
|
||||
// capture_time_ns is monotonic for pacing, while capture_utc_ns is optional wall time.
|
||||
class MediaFrame final {
|
||||
public:
|
||||
using Payload = std::vector<uint8_t>;
|
||||
using PayloadPtr = std::shared_ptr<const Payload>;
|
||||
|
||||
struct Config {
|
||||
TrackDescriptorPtr descriptor;
|
||||
Payload payload;
|
||||
uint64_t sequence{0};
|
||||
// Opaque producer-native timing/counter values. Their units and epoch
|
||||
// are source-defined; zero means that the source did not provide them.
|
||||
uint64_t source_timestamp{0};
|
||||
uint64_t source_frame_number{0};
|
||||
int64_t pts{0};
|
||||
int64_t dts{0};
|
||||
int64_t duration{0};
|
||||
uint64_t capture_time_ns{0};
|
||||
int64_t capture_utc_ns{0};
|
||||
bool key_frame{false};
|
||||
bool discontinuity{false};
|
||||
};
|
||||
|
||||
explicit MediaFrame(Config config)
|
||||
: descriptor(std::move(config.descriptor)),
|
||||
payload(std::make_shared<const Payload>(std::move(config.payload))),
|
||||
sequence(config.sequence),
|
||||
source_timestamp(config.source_timestamp),
|
||||
source_frame_number(config.source_frame_number),
|
||||
pts(config.pts),
|
||||
dts(config.dts),
|
||||
duration(config.duration),
|
||||
capture_time_ns(config.capture_time_ns),
|
||||
capture_utc_ns(config.capture_utc_ns),
|
||||
key_frame(config.key_frame),
|
||||
discontinuity(config.discontinuity) {
|
||||
if (!descriptor) {
|
||||
throw std::invalid_argument("MediaFrame descriptor must not be null");
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t* data() const noexcept {
|
||||
return payload->empty() ? nullptr : payload->data();
|
||||
}
|
||||
|
||||
size_t size() const noexcept {
|
||||
return payload->size();
|
||||
}
|
||||
|
||||
bool empty() const noexcept {
|
||||
return payload->empty();
|
||||
}
|
||||
|
||||
const TrackDescriptorPtr descriptor;
|
||||
const PayloadPtr payload;
|
||||
const uint64_t sequence;
|
||||
const uint64_t source_timestamp;
|
||||
const uint64_t source_frame_number;
|
||||
const int64_t pts;
|
||||
const int64_t dts;
|
||||
const int64_t duration;
|
||||
const uint64_t capture_time_ns;
|
||||
const int64_t capture_utc_ns;
|
||||
const bool key_frame;
|
||||
const bool discontinuity;
|
||||
};
|
||||
|
||||
using MediaFramePtr = std::shared_ptr<const MediaFrame>;
|
||||
|
||||
inline TrackDescriptorPtr makeTrackDescriptor(TrackDescriptor::Config config) {
|
||||
return std::make_shared<const TrackDescriptor>(std::move(config));
|
||||
}
|
||||
|
||||
inline MediaFramePtr makeMediaFrame(MediaFrame::Config config) {
|
||||
return std::make_shared<const MediaFrame>(std::move(config));
|
||||
}
|
||||
|
||||
} // namespace cmvr::media
|
||||
|
||||
#endif // CMVR_ES_COMMON_MEDIA_MEDIA_FRAME_H
|
||||
450
cmvr-es/common/types/agv/agv_types.h
Normal file
450
cmvr-es/common/types/agv/agv_types.h
Normal file
@ -0,0 +1,450 @@
|
||||
#ifndef CMVR_ES_AGV_TYPES_H
|
||||
#define CMVR_ES_AGV_TYPES_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "common/types/geometry_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
/**
|
||||
* @brief AGV 通用命令/结果错误类别。
|
||||
*
|
||||
* 这些枚举描述框架层面的通用结果。厂商或控制器特有错误码应由具体
|
||||
* AGV 实现转换,或保存在该实现私有的适配参数/细节中。
|
||||
*/
|
||||
enum class AgvErrorCode {
|
||||
OK = 0,
|
||||
NotConnected,
|
||||
AlreadyConnected,
|
||||
ConnectionFailed,
|
||||
Timeout,
|
||||
InvalidArgument,
|
||||
LocalizationLost,
|
||||
MapNotLoaded,
|
||||
TaskRejected,
|
||||
TaskFailed,
|
||||
TaskCanceled,
|
||||
CommandFailed,
|
||||
EmergencyStopped,
|
||||
Fault,
|
||||
UnsupportedCommand,
|
||||
UnknownError
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 命令的标准返回值。
|
||||
*/
|
||||
struct AgvResult {
|
||||
AgvErrorCode code{AgvErrorCode::OK};
|
||||
std::string message{"OK"};
|
||||
|
||||
bool ok() const { return code == AgvErrorCode::OK; }
|
||||
static AgvResult success() { return {AgvErrorCode::OK, "OK"}; }
|
||||
static AgvResult failure(AgvErrorCode c, const std::string& msg) { return {c, msg}; }
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 粗粒度运行模式。
|
||||
*/
|
||||
enum class AgvMode {
|
||||
Unknown = 0,
|
||||
Disconnected,
|
||||
Idle,
|
||||
Manual,
|
||||
Auto,
|
||||
Charging,
|
||||
Paused,
|
||||
Stopped,
|
||||
Fault,
|
||||
EmergencyStop
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 当前跟踪的导航任务状态。
|
||||
*/
|
||||
enum class AgvTaskState {
|
||||
None = 0,
|
||||
Waiting,
|
||||
Running,
|
||||
Paused,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 当前跟踪的导航任务类型。
|
||||
*/
|
||||
enum class AgvTaskType {
|
||||
None = 0,
|
||||
NavigateToPose,
|
||||
NavigateToStation,
|
||||
FollowPath,
|
||||
Dock,
|
||||
Charge,
|
||||
Custom
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 固定距离平移使用的距离参考模式。
|
||||
*/
|
||||
enum class AgvTranslationMode {
|
||||
Odometry = 0,
|
||||
Localization
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 车体坐标系下的平面速度。
|
||||
*
|
||||
* 线速度单位为米/秒,角速度单位为弧度/秒。
|
||||
*/
|
||||
struct AgvVelocity {
|
||||
double vx{0.0};
|
||||
double vy{0.0};
|
||||
double wz{0.0};
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief AGV 车体坐标系下的固定距离平移参数。
|
||||
*/
|
||||
struct AgvTranslation {
|
||||
double distance{0.0};
|
||||
double vx{0.0};
|
||||
double vy{0.0};
|
||||
AgvTranslationMode mode{AgvTranslationMode::Odometry};
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief 导航通用运动约束和执行选项。
|
||||
*
|
||||
* 除非具体实现另有说明,数值限制为 0 表示使用设备或控制器默认值。
|
||||
*/
|
||||
struct AgvMotionOptions {
|
||||
double max_speed{0.0};
|
||||
double max_angular_speed{0.0};
|
||||
double max_acceleration{0.0};
|
||||
double max_angular_acceleration{0.0};
|
||||
double reach_distance{0.0};
|
||||
double reach_angle{0.0};
|
||||
double speed_ratio{1.0};
|
||||
// 导航默认同步阻塞;调用方只有显式设为 true 才在任务接受后立即返回。
|
||||
bool asynchronous{false};
|
||||
int wait_timeout_ms{0};
|
||||
int poll_interval_ms{0};
|
||||
int blocked_timeout_ms{0};
|
||||
// 不带 RPC 框架依赖的取消检查。同步导航等待期间可由
|
||||
// 上层绑定 deadline/cancel;驱动不得在函数返回后保留该回调。
|
||||
std::function<bool()> cancellation_requested;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 适配器可选的实现特定参数。
|
||||
*
|
||||
* 该结构用于避免抽象接口绑定某一个控制器协议。具体 AGV 驱动可以按需
|
||||
* 解释操作名、特殊运动模式、设备特定标志等键值。
|
||||
*/
|
||||
struct AgvAdapterParams {
|
||||
std::unordered_map<std::string, std::string> values;
|
||||
|
||||
bool empty() const { return values.empty(); }
|
||||
|
||||
std::optional<std::string> getString(const std::string& key) const
|
||||
{
|
||||
const auto it = values.find(key);
|
||||
if (it == values.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::optional<double> getDouble(const std::string& key) const
|
||||
{
|
||||
const auto value = getString(key);
|
||||
if (!value) {
|
||||
return std::nullopt;
|
||||
}
|
||||
try {
|
||||
return std::stod(*value);
|
||||
} catch (...) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<bool> getBool(const std::string& key) const
|
||||
{
|
||||
const auto value = getString(key);
|
||||
if (!value) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (*value == "1" || *value == "true" || *value == "yes" || *value == "on") {
|
||||
return true;
|
||||
}
|
||||
if (*value == "0" || *value == "false" || *value == "no" || *value == "off") {
|
||||
return false;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 作为 AgvRuntimeState 一部分暴露的电池信息。
|
||||
*/
|
||||
struct AgvBatteryState {
|
||||
double percentage{0.0};
|
||||
double voltage{0.0};
|
||||
double current{0.0};
|
||||
double temperature{0.0};
|
||||
bool charging{false};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 当前运行状态快照。
|
||||
*
|
||||
* 这是 AGV 设备的主要状态查询对象。抽象接口中应避免派生出的便利
|
||||
* getter;调用方可直接从该快照读取字段。
|
||||
*/
|
||||
struct AgvRuntimeState {
|
||||
double timestamp{0.0};
|
||||
AgvMode mode{AgvMode::Unknown};
|
||||
bool connected{false};
|
||||
bool localized{false};
|
||||
bool moving{false};
|
||||
bool fault{false};
|
||||
bool emergency_stopped{false};
|
||||
math::Pose2d pose{};
|
||||
AgvVelocity velocity{};
|
||||
AgvBatteryState battery{};
|
||||
std::string current_map;
|
||||
std::string current_station;
|
||||
std::string last_error;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 抽象层可见的地图站点/路径点。
|
||||
*/
|
||||
struct AgvStation {
|
||||
std::string id;
|
||||
std::string type;
|
||||
math::Pose2d pose{};
|
||||
std::string description;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 显式导航路径中的一段站点到站点路径。
|
||||
*/
|
||||
struct AgvPathSegment {
|
||||
std::string source_station;
|
||||
std::string target_station;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV 扫图过程中产生的数据文件。
|
||||
*
|
||||
* content 可保存控制器返回的二进制内容,例如 SEER Robokit 的 rawmap zip 包。
|
||||
*/
|
||||
struct AgvMappingDataFile {
|
||||
std::string name;
|
||||
std::string content;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 从控制器增量获取的扫图数据批次。
|
||||
*/
|
||||
struct AgvMappingData {
|
||||
int start_index{0};
|
||||
int next_index{0};
|
||||
std::vector<AgvMappingDataFile> files;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 上位机请求的统一地图维度。
|
||||
*
|
||||
* 该枚举只表示上位机希望得到 2D、3D 或两者都要;不表示厂商文件格式。
|
||||
* 厂商原始地图必须由具体 AGV 驱动转换为下面的统一地图结构。
|
||||
*/
|
||||
enum class AgvMapDimension {
|
||||
Unspecified = 0,
|
||||
Map2D,
|
||||
Map3D,
|
||||
Map2DAnd3D
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 地图流中的更新类型。
|
||||
*/
|
||||
enum class AgvMapUpdateType {
|
||||
Unspecified = 0,
|
||||
Snapshot,
|
||||
Incremental,
|
||||
Reset
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一语义地图对象类型。
|
||||
*/
|
||||
enum class AgvMapObjectType {
|
||||
Unspecified = 0,
|
||||
Station,
|
||||
Line,
|
||||
Area,
|
||||
QrTag,
|
||||
Reflector,
|
||||
BinLocation,
|
||||
ExternalDevice
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 地图坐标系下的三维点,单位:米。
|
||||
*/
|
||||
struct AgvMapPoint3D {
|
||||
double x{0.0};
|
||||
double y{0.0};
|
||||
double z{0.0};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一语义对象。几何点均使用地图坐标系,单位:米。
|
||||
*/
|
||||
struct AgvMapObject {
|
||||
std::string id;
|
||||
AgvMapObjectType type{AgvMapObjectType::Unspecified};
|
||||
std::vector<AgvMapPoint3D> points;
|
||||
double heading{0.0};
|
||||
std::unordered_map<std::string, std::string> properties;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一 2D 地图。
|
||||
*
|
||||
* data 采用行优先顺序,取值约定为 -1 未知、0 空闲、100 占据。
|
||||
* 当厂商地图只提供矢量/语义元素时,data 可以为空,objects 仍然有效。
|
||||
*/
|
||||
struct AgvUnifiedMap2D {
|
||||
std::string frame_id{"map"};
|
||||
double timestamp{0.0};
|
||||
double resolution{0.0};
|
||||
std::uint32_t width{0};
|
||||
std::uint32_t height{0};
|
||||
math::Pose2d origin{};
|
||||
std::vector<std::int32_t> data;
|
||||
std::vector<AgvMapObject> objects;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一 3D 点样本,坐标单位:米。
|
||||
*/
|
||||
struct AgvMapPointSample3D {
|
||||
double x{0.0};
|
||||
double y{0.0};
|
||||
double z{0.0};
|
||||
float intensity{0.0F};
|
||||
std::uint32_t ring{0};
|
||||
double time_offset{0.0};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一 3D 占据体素。
|
||||
*/
|
||||
struct AgvMapVoxel3D {
|
||||
std::int32_t x{0};
|
||||
std::int32_t y{0};
|
||||
std::int32_t z{0};
|
||||
float probability{-1.0F};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一 3D 平面特征。
|
||||
*/
|
||||
struct AgvMapPlane3D {
|
||||
AgvMapPoint3D center;
|
||||
AgvMapPoint3D normal;
|
||||
double d{0.0};
|
||||
double radius{0.0};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一 3D 地图。
|
||||
*/
|
||||
struct AgvUnifiedMap3D {
|
||||
std::string frame_id{"map"};
|
||||
double timestamp{0.0};
|
||||
double voxel_resolution{0.0};
|
||||
std::vector<AgvMapPointSample3D> points;
|
||||
std::vector<AgvMapVoxel3D> voxels;
|
||||
std::vector<AgvMapPlane3D> planes;
|
||||
std::vector<AgvMapObject> objects;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 地图流读取参数。
|
||||
*/
|
||||
struct AgvMapStreamOptions {
|
||||
AgvMapDimension dimension{AgvMapDimension::Unspecified};
|
||||
std::string map_name;
|
||||
std::string resume_token;
|
||||
bool snapshot{true};
|
||||
bool incremental{false};
|
||||
int max_chunk_bytes{0};
|
||||
int wait_timeout_ms{1000};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 建图/扫图启动参数。
|
||||
*/
|
||||
struct AgvMappingOptions {
|
||||
AgvMapDimension dimension{AgvMapDimension::Unspecified};
|
||||
std::string map_name;
|
||||
bool real_time{false};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 统一地图流中的单条更新。
|
||||
*/
|
||||
struct AgvUnifiedMapUpdate {
|
||||
std::string map_id;
|
||||
std::string session_id;
|
||||
std::uint64_t sequence{0};
|
||||
std::string resume_token;
|
||||
AgvMapDimension dimension{AgvMapDimension::Unspecified};
|
||||
AgvMapUpdateType update_type{AgvMapUpdateType::Unspecified};
|
||||
std::string frame_id{"map"};
|
||||
double timestamp{0.0};
|
||||
bool snapshot_begin{false};
|
||||
bool snapshot_end{false};
|
||||
std::uint32_t chunk_index{0};
|
||||
std::uint32_t chunk_count{0};
|
||||
std::optional<AgvUnifiedMap2D> map_2d;
|
||||
std::optional<AgvUnifiedMap3D> map_3d;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 当前导航任务状态。
|
||||
*
|
||||
* 该状态独立于 AgvRuntimeState,因为导航任务可能处于排队、暂停、
|
||||
* 完成或失败状态,而车辆本体仍然保持连接并处于正常状态。
|
||||
*/
|
||||
struct AgvNavigationStatus {
|
||||
AgvTaskState state{AgvTaskState::None};
|
||||
AgvTaskType type{AgvTaskType::None};
|
||||
double progress{0.0};
|
||||
std::string message;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 兼容旧 AGV 状态 API 命名的别名。
|
||||
*/
|
||||
using AGVState = AgvRuntimeState;
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_AGV_TYPES_H
|
||||
@ -2,6 +2,7 @@
|
||||
#define CMVR_ES_ARM_TYPES_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@ -103,6 +104,11 @@ struct JointGroupState {
|
||||
std::vector<double> position;
|
||||
std::vector<double> velocity;
|
||||
std::vector<double> effort;
|
||||
std::uint64_t sequence{0};
|
||||
std::int64_t sample_monotonic_ns{0};
|
||||
bool position_valid{false};
|
||||
bool velocity_valid{false};
|
||||
bool effort_valid{false};
|
||||
|
||||
bool validForModel(const RobotModel& model) const
|
||||
{
|
||||
@ -157,6 +163,11 @@ struct MotionOptions {
|
||||
double jerk{5.0};
|
||||
std::vector<double> joint_velocity_limits;
|
||||
bool asynchronous{false};
|
||||
// Framework-independent cancellation check used by queued synchronous
|
||||
// motion. Cancellation after device acceptance retains a typed motion
|
||||
// barrier; the owner must call stopMotion() to confirm physical idle.
|
||||
// Drivers must not retain this callback after moveJ/moveL returns.
|
||||
std::function<bool()> cancellation_requested;
|
||||
};
|
||||
|
||||
struct ServoOptions {
|
||||
@ -165,6 +176,14 @@ struct ServoOptions {
|
||||
double gain{300.0};
|
||||
};
|
||||
|
||||
struct TorqueServoOptions {
|
||||
// The UME legacy loop runs at 800 Hz by default.
|
||||
double period{0.00125};
|
||||
// A producer must continuously refresh the latest torque command. A stale
|
||||
// command latches a fault and disables the actuator chain.
|
||||
std::uint32_t command_watchdog_ms{20};
|
||||
};
|
||||
|
||||
enum class RobotMode {
|
||||
Unknown = 0,
|
||||
Disconnected,
|
||||
@ -197,6 +216,14 @@ enum class ControlMode {
|
||||
Freedrive
|
||||
};
|
||||
|
||||
enum class JointEffortSource {
|
||||
Unspecified = 0,
|
||||
MotorEstimate,
|
||||
JointSensor,
|
||||
ForceTorqueSensor,
|
||||
Observer
|
||||
};
|
||||
|
||||
struct ArmState {
|
||||
double timestamp{0.0};
|
||||
RobotMode robot_mode{RobotMode::Unknown};
|
||||
|
||||
@ -49,7 +49,7 @@ namespace cmvr::math {
|
||||
typedef struct {
|
||||
double x; //* unit: m
|
||||
double y;
|
||||
double theta;
|
||||
double theta; //* unit: rad
|
||||
} Pose2d;
|
||||
}
|
||||
|
||||
|
||||
@ -1,609 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
|
||||
namespace cmvr::common {
|
||||
|
||||
/**
|
||||
* @brief 图像像素坐标。
|
||||
*
|
||||
* 坐标系约定:
|
||||
* - `u`:图像列坐标,向右为正,单位像素。
|
||||
* - `v`:图像行坐标,向下为正,单位像素。
|
||||
*/
|
||||
struct Pixel {
|
||||
int u{0}; // 图像像素列坐标,单位像素。
|
||||
int v{0}; // 图像像素行坐标,单位像素。
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief BGR 颜色定义。
|
||||
*/
|
||||
struct Color {
|
||||
uint8_t b{0}; // 蓝色通道,范围 [0, 255]。
|
||||
uint8_t g{255}; // 绿色通道,范围 [0, 255]。
|
||||
uint8_t r{0}; // 红色通道,范围 [0, 255]。
|
||||
|
||||
/**
|
||||
* @brief 转为 OpenCV 的 `cv::Scalar`。
|
||||
*/
|
||||
cv::Scalar toCvScalar() const {
|
||||
return cv::Scalar(static_cast<double>(b),
|
||||
static_cast<double>(g),
|
||||
static_cast<double>(r));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 预定义红色。
|
||||
*/
|
||||
static Color red() { return Color{0, 0, 255}; }
|
||||
|
||||
/**
|
||||
* @brief 预定义绿色。
|
||||
*/
|
||||
static Color green() { return Color{0, 255, 0}; }
|
||||
|
||||
/**
|
||||
* @brief 预定义蓝色。
|
||||
*/
|
||||
static Color blue() { return Color{255, 0, 0}; }
|
||||
|
||||
/**
|
||||
* @brief 预定义黄色。
|
||||
*/
|
||||
static Color yellow() { return Color{0, 255, 255}; }
|
||||
|
||||
/**
|
||||
* @brief 预定义白色。
|
||||
*/
|
||||
static Color white() { return Color{255, 255, 255}; }
|
||||
|
||||
/**
|
||||
* @brief 预定义黑色。
|
||||
*/
|
||||
static Color black() { return Color{0, 0, 0}; }
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 图像上的文本叠加配置。
|
||||
*/
|
||||
struct TextOverlay {
|
||||
std::string text; // 需要显示的字符串内容。
|
||||
Pixel position_px{}; // 文本左下角在图像像素坐标系中的位置。
|
||||
Color color{Color::green()}; // 文本颜色。
|
||||
double font_scale{0.7}; // OpenCV 字体缩放系数。
|
||||
int thickness{2}; // 文本线宽,单位像素。
|
||||
int font_face{cv::FONT_HERSHEY_SIMPLEX}; // OpenCV 字体类型。
|
||||
bool draw_background{false}; // 是否绘制文本背景框。
|
||||
Color background_color{Color::black()}; // 文本背景框颜色。
|
||||
int background_padding_px{2}; // 文本背景框四周留白,单位像素。
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 图像上的点叠加配置。
|
||||
*/
|
||||
struct PointOverlay {
|
||||
Pixel position_px{}; // 点中心在图像像素坐标系中的位置。
|
||||
Color color{Color::red()}; // 点颜色。
|
||||
int radius_px{5}; // 圆点半径,单位像素。
|
||||
int thickness{2}; // 线宽,`-1` 表示填充。
|
||||
std::string label; // 点旁边附带显示的字符串;为空时不显示。
|
||||
Pixel label_offset_px{8, -8}; // 标签相对点中心的像素偏移。
|
||||
double label_font_scale{0.6}; // 点标签字体缩放系数。
|
||||
int label_thickness{2}; // 点标签线宽,单位像素。
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 图像上的圆圈叠加配置。
|
||||
*/
|
||||
struct CircleOverlay {
|
||||
Pixel center_px{}; // 圆心在图像像素坐标系中的位置。
|
||||
int radius_px{10}; // 圆半径,单位像素。
|
||||
Color color{Color::yellow()}; // 圆圈颜色。
|
||||
int thickness{2}; // 圆圈线宽,单位像素,`-1` 表示填充。
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 图像上的十字叠加配置。
|
||||
*/
|
||||
struct CrossOverlay {
|
||||
Pixel center_px{}; // 十字中心在图像像素坐标系中的位置。
|
||||
int arm_length_px{8}; // 单侧十字臂长度,单位像素。
|
||||
Color color{Color::blue()}; // 十字颜色。
|
||||
int thickness{2}; // 十字线宽,单位像素。
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 通用图像叠加显示接口。
|
||||
*
|
||||
* 该接口不依赖任何感知或跟踪类,只抽象三类输入:
|
||||
* - 待显示的图像数据;
|
||||
* - 文本叠加项;
|
||||
* - 点叠加项。
|
||||
*/
|
||||
class ImageDisplay {
|
||||
public:
|
||||
virtual ~ImageDisplay() = default;
|
||||
|
||||
/**
|
||||
* @brief 设置窗口名称。
|
||||
* @param window_name 显示窗口名称。
|
||||
*/
|
||||
virtual void setWindowName(const std::string& window_name) = 0;
|
||||
|
||||
/**
|
||||
* @brief 设置待显示的图像。
|
||||
* @param image 输入图像,支持灰度图、BGR 图或 BGRA 图。
|
||||
*/
|
||||
virtual void setImage(const cv::Mat& image) = 0;
|
||||
|
||||
/**
|
||||
* @brief 清空所有叠加项,但保留当前图像。
|
||||
*/
|
||||
virtual void clearOverlays() = 0;
|
||||
|
||||
/**
|
||||
* @brief 添加文本叠加项。
|
||||
* @param overlay 文本叠加配置。
|
||||
*/
|
||||
virtual void showText(const TextOverlay& overlay) = 0;
|
||||
|
||||
/**
|
||||
* @brief 按位置、字符串、颜色和大小直接添加文本。
|
||||
* @param text 需要显示的字符串内容。
|
||||
* @param position_px 文本左下角在图像像素坐标系中的位置。
|
||||
* @param color 文本颜色。
|
||||
* @param font_scale OpenCV 字体缩放系数。
|
||||
* @param thickness 文本线宽,单位像素。
|
||||
*/
|
||||
virtual void showText(const std::string& text,
|
||||
const Pixel& position_px,
|
||||
const Color& color,
|
||||
double font_scale = 0.7,
|
||||
int thickness = 2) = 0;
|
||||
|
||||
/**
|
||||
* @brief 添加点叠加项。
|
||||
* @param overlay 点叠加配置。
|
||||
*/
|
||||
virtual void showPoint(const PointOverlay& overlay) = 0;
|
||||
|
||||
/**
|
||||
* @brief 按位置、颜色和大小直接添加点。
|
||||
* @param position_px 点中心在图像像素坐标系中的位置。
|
||||
* @param color 点颜色。
|
||||
* @param radius_px 圆点半径,单位像素。
|
||||
* @param thickness 线宽,`-1` 表示填充。
|
||||
* @param label 点旁边附带显示的字符串;为空时不显示。
|
||||
*/
|
||||
virtual void showPoint(const Pixel& position_px,
|
||||
const Color& color,
|
||||
int radius_px = 5,
|
||||
int thickness = 2,
|
||||
const std::string& label = {}) = 0;
|
||||
|
||||
/**
|
||||
* @brief 显示圆圈叠加项。
|
||||
* @param overlay 圆圈叠加配置。
|
||||
*/
|
||||
virtual void showCircle(const CircleOverlay& overlay) = 0;
|
||||
|
||||
/**
|
||||
* @brief 按位置、半径、颜色和线宽直接显示圆圈。
|
||||
* @param center_px 圆心在图像像素坐标系中的位置。
|
||||
* @param radius_px 圆半径,单位像素。
|
||||
* @param color 圆圈颜色。
|
||||
* @param thickness 圆圈线宽,单位像素,`-1` 表示填充。
|
||||
*/
|
||||
virtual void showCircle(const Pixel& center_px,
|
||||
int radius_px,
|
||||
const Color& color,
|
||||
int thickness = 2) = 0;
|
||||
|
||||
/**
|
||||
* @brief 显示十字叠加项。
|
||||
* @param overlay 十字叠加配置。
|
||||
*/
|
||||
virtual void showCross(const CrossOverlay& overlay) = 0;
|
||||
|
||||
/**
|
||||
* @brief 按位置、尺寸、颜色和线宽直接显示十字。
|
||||
* @param center_px 十字中心在图像像素坐标系中的位置。
|
||||
* @param arm_length_px 单侧十字臂长度,单位像素。
|
||||
* @param color 十字颜色。
|
||||
* @param thickness 十字线宽,单位像素。
|
||||
*/
|
||||
virtual void showCross(const Pixel& center_px,
|
||||
int arm_length_px,
|
||||
const Color& color,
|
||||
int thickness = 2) = 0;
|
||||
|
||||
/**
|
||||
* @brief 判断当前是否已有待显示图像。
|
||||
*/
|
||||
virtual bool hasImage() const = 0;
|
||||
|
||||
/**
|
||||
* @brief 将当前图像和叠加项渲染到输出图像。
|
||||
* @param rendered_image 输出的渲染结果图像,BGR 三通道。
|
||||
* @return 渲染成功返回 `true`。
|
||||
*/
|
||||
virtual bool render(cv::Mat& rendered_image) const = 0;
|
||||
|
||||
/**
|
||||
* @brief 显示当前渲染结果。
|
||||
* @param wait_key_ms `cv::waitKey` 等待时间,单位毫秒。
|
||||
* @return 返回 `cv::waitKey` 的按键值;若没有可显示图像则返回 `-1`。
|
||||
*/
|
||||
virtual int show(int wait_key_ms = 1) = 0;
|
||||
|
||||
/**
|
||||
* @brief 关闭显示窗口。
|
||||
*/
|
||||
virtual void close() = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief 基于 OpenCV HighGUI 的图像叠加显示实现。
|
||||
*/
|
||||
class OpenCvImageCvDisplay final : public ImageDisplay {
|
||||
public:
|
||||
/**
|
||||
* @brief 构造显示器。
|
||||
* @param window_name 显示窗口名称。
|
||||
*/
|
||||
explicit OpenCvImageCvDisplay(std::string window_name = "image_overlay")
|
||||
: window_name_(std::move(window_name)) {}
|
||||
|
||||
/**
|
||||
* @brief 设置窗口名称。
|
||||
* @param window_name 显示窗口名称。
|
||||
*/
|
||||
void setWindowName(const std::string& window_name) override {
|
||||
window_name_ = window_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 设置待显示图像。
|
||||
* @param image 输入图像,支持灰度图、BGR 图或 BGRA 图。
|
||||
*/
|
||||
void setImage(const cv::Mat& image) override {
|
||||
image_ = image.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 清空所有叠加项,但保留当前图像。
|
||||
*/
|
||||
void clearOverlays() override {
|
||||
texts_.clear();
|
||||
points_.clear();
|
||||
circles_.clear();
|
||||
crosses_.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 添加文本叠加项。
|
||||
* @param overlay 文本叠加配置。
|
||||
*/
|
||||
void showText(const TextOverlay& overlay) override {
|
||||
texts_.push_back(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按位置、字符串、颜色和大小直接添加文本。
|
||||
* @param text 需要显示的字符串内容。
|
||||
* @param position_px 文本左下角在图像像素坐标系中的位置。
|
||||
* @param color 文本颜色。
|
||||
* @param font_scale OpenCV 字体缩放系数。
|
||||
* @param thickness 文本线宽,单位像素。
|
||||
*/
|
||||
void showText(const std::string& text,
|
||||
const Pixel& position_px,
|
||||
const Color& color,
|
||||
double font_scale = 0.7,
|
||||
int thickness = 2) override {
|
||||
TextOverlay overlay;
|
||||
overlay.text = text;
|
||||
overlay.position_px = position_px;
|
||||
overlay.color = color;
|
||||
overlay.font_scale = font_scale;
|
||||
overlay.thickness = thickness;
|
||||
showText(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 添加点叠加项。
|
||||
* @param overlay 点叠加配置。
|
||||
*/
|
||||
void showPoint(const PointOverlay& overlay) override {
|
||||
points_.push_back(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按位置、颜色和大小直接添加点。
|
||||
* @param position_px 点中心在图像像素坐标系中的位置。
|
||||
* @param color 点颜色。
|
||||
* @param radius_px 圆点半径,单位像素。
|
||||
* @param thickness 线宽,`-1` 表示填充。
|
||||
* @param label 点旁边附带显示的字符串;为空时不显示。
|
||||
*/
|
||||
void showPoint(const Pixel& position_px,
|
||||
const Color& color,
|
||||
int radius_px = 5,
|
||||
int thickness = 2,
|
||||
const std::string& label = {}) override {
|
||||
PointOverlay overlay;
|
||||
overlay.position_px = position_px;
|
||||
overlay.color = color;
|
||||
overlay.radius_px = radius_px;
|
||||
overlay.thickness = thickness;
|
||||
overlay.label = label;
|
||||
showPoint(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 显示圆圈叠加项。
|
||||
* @param overlay 圆圈叠加配置。
|
||||
*/
|
||||
void showCircle(const CircleOverlay& overlay) override {
|
||||
circles_.push_back(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按位置、半径、颜色和线宽直接显示圆圈。
|
||||
* @param center_px 圆心在图像像素坐标系中的位置。
|
||||
* @param radius_px 圆半径,单位像素。
|
||||
* @param color 圆圈颜色。
|
||||
* @param thickness 圆圈线宽,单位像素,`-1` 表示填充。
|
||||
*/
|
||||
void showCircle(const Pixel& center_px,
|
||||
int radius_px,
|
||||
const Color& color,
|
||||
int thickness = 2) override {
|
||||
CircleOverlay overlay;
|
||||
overlay.center_px = center_px;
|
||||
overlay.radius_px = radius_px;
|
||||
overlay.color = color;
|
||||
overlay.thickness = thickness;
|
||||
showCircle(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 显示十字叠加项。
|
||||
* @param overlay 十字叠加配置。
|
||||
*/
|
||||
void showCross(const CrossOverlay& overlay) override {
|
||||
crosses_.push_back(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按位置、尺寸、颜色和线宽直接显示十字。
|
||||
* @param center_px 十字中心在图像像素坐标系中的位置。
|
||||
* @param arm_length_px 单侧十字臂长度,单位像素。
|
||||
* @param color 十字颜色。
|
||||
* @param thickness 十字线宽,单位像素。
|
||||
*/
|
||||
void showCross(const Pixel& center_px,
|
||||
int arm_length_px,
|
||||
const Color& color,
|
||||
int thickness = 2) override {
|
||||
CrossOverlay overlay;
|
||||
overlay.center_px = center_px;
|
||||
overlay.arm_length_px = arm_length_px;
|
||||
overlay.color = color;
|
||||
overlay.thickness = thickness;
|
||||
showCross(overlay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 判断当前是否已有待显示图像。
|
||||
*/
|
||||
bool hasImage() const override {
|
||||
return !image_.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 将当前图像和叠加项渲染到输出图像。
|
||||
* @param rendered_image 输出的渲染结果图像,BGR 三通道。
|
||||
* @return 渲染成功返回 `true`。
|
||||
*/
|
||||
bool render(cv::Mat& rendered_image) const override {
|
||||
if (!toBgrImage(image_, rendered_image)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const CircleOverlay& overlay : circles_) {
|
||||
drawCircle(rendered_image, overlay);
|
||||
}
|
||||
for (const CrossOverlay& overlay : crosses_) {
|
||||
drawCross(rendered_image, overlay);
|
||||
}
|
||||
for (const PointOverlay& overlay : points_) {
|
||||
drawPoint(rendered_image, overlay);
|
||||
}
|
||||
for (const TextOverlay& overlay : texts_) {
|
||||
drawText(rendered_image, overlay);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 显示当前渲染结果。
|
||||
* @param wait_key_ms `cv::waitKey` 等待时间,单位毫秒。
|
||||
* @return 返回 `cv::waitKey` 的按键值;若没有可显示图像则返回 `-1`。
|
||||
*/
|
||||
int show(int wait_key_ms = 1) override {
|
||||
cv::Mat rendered_image;
|
||||
if (!render(rendered_image)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!window_created_) {
|
||||
cv::namedWindow(window_name_, cv::WINDOW_NORMAL);
|
||||
window_created_ = true;
|
||||
}
|
||||
cv::imshow(window_name_, rendered_image);
|
||||
return cv::waitKey(wait_key_ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 关闭显示窗口。
|
||||
*/
|
||||
void close() override {
|
||||
if (!window_created_) {
|
||||
return;
|
||||
}
|
||||
cv::destroyWindow(window_name_);
|
||||
window_created_ = false;
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief 将输入图像转换为可叠加绘制的 BGR 三通道图像。
|
||||
* @param input 输入图像。
|
||||
* @param output 输出 BGR 图像。
|
||||
* @return 转换成功返回 `true`。
|
||||
*/
|
||||
static bool toBgrImage(const cv::Mat& input, cv::Mat& output) {
|
||||
if (input.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (input.channels() == 1) {
|
||||
cv::cvtColor(input, output, cv::COLOR_GRAY2BGR);
|
||||
return true;
|
||||
}
|
||||
if (input.channels() == 3) {
|
||||
output = input.clone();
|
||||
return true;
|
||||
}
|
||||
if (input.channels() == 4) {
|
||||
cv::cvtColor(input, output, cv::COLOR_BGRA2BGR);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 在图像上绘制文本叠加项。
|
||||
* @param image 目标图像,BGR 三通道。
|
||||
* @param overlay 文本叠加配置。
|
||||
*/
|
||||
static void drawText(cv::Mat& image, const TextOverlay& overlay) {
|
||||
const cv::Point origin(overlay.position_px.u, overlay.position_px.v);
|
||||
const int thickness = std::max(1, overlay.thickness);
|
||||
const double font_scale = std::max(0.0, overlay.font_scale);
|
||||
|
||||
if (overlay.draw_background) {
|
||||
int baseline = 0;
|
||||
const cv::Size text_size = cv::getTextSize(overlay.text,
|
||||
overlay.font_face,
|
||||
font_scale,
|
||||
thickness,
|
||||
&baseline);
|
||||
const int pad = std::max(0, overlay.background_padding_px);
|
||||
const cv::Point top_left(origin.x - pad, origin.y - text_size.height - pad);
|
||||
const cv::Point bottom_right(origin.x + text_size.width + pad, origin.y + baseline + pad);
|
||||
cv::rectangle(image,
|
||||
top_left,
|
||||
bottom_right,
|
||||
overlay.background_color.toCvScalar(),
|
||||
cv::FILLED);
|
||||
}
|
||||
|
||||
cv::putText(image,
|
||||
overlay.text,
|
||||
origin,
|
||||
overlay.font_face,
|
||||
font_scale,
|
||||
overlay.color.toCvScalar(),
|
||||
thickness,
|
||||
cv::LINE_AA);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 在图像上绘制点叠加项。
|
||||
* @param image 目标图像,BGR 三通道。
|
||||
* @param overlay 点叠加配置。
|
||||
*/
|
||||
static void drawPoint(cv::Mat& image, const PointOverlay& overlay) {
|
||||
const cv::Point center(overlay.position_px.u, overlay.position_px.v);
|
||||
const int radius = std::max(1, overlay.radius_px);
|
||||
cv::circle(image,
|
||||
center,
|
||||
radius,
|
||||
overlay.color.toCvScalar(),
|
||||
overlay.thickness,
|
||||
cv::LINE_AA);
|
||||
|
||||
if (!overlay.label.empty()) {
|
||||
TextOverlay label_overlay;
|
||||
label_overlay.text = overlay.label;
|
||||
label_overlay.position_px = Pixel{center.x + overlay.label_offset_px.u,
|
||||
center.y + overlay.label_offset_px.v};
|
||||
label_overlay.color = overlay.color;
|
||||
label_overlay.font_scale = overlay.label_font_scale;
|
||||
label_overlay.thickness = overlay.label_thickness;
|
||||
drawText(image, label_overlay);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 在图像上绘制圆圈叠加项。
|
||||
* @param image 目标图像,BGR 三通道。
|
||||
* @param overlay 圆圈叠加配置。
|
||||
*/
|
||||
static void drawCircle(cv::Mat& image, const CircleOverlay& overlay) {
|
||||
const cv::Point center(overlay.center_px.u, overlay.center_px.v);
|
||||
const int radius = std::max(1, overlay.radius_px);
|
||||
const int thickness = (overlay.thickness == 0) ? 1 : overlay.thickness;
|
||||
cv::circle(image,
|
||||
center,
|
||||
radius,
|
||||
overlay.color.toCvScalar(),
|
||||
thickness,
|
||||
cv::LINE_AA);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 在图像上绘制十字叠加项。
|
||||
* @param image 目标图像,BGR 三通道。
|
||||
* @param overlay 十字叠加配置。
|
||||
*/
|
||||
static void drawCross(cv::Mat& image, const CrossOverlay& overlay) {
|
||||
const cv::Point center(overlay.center_px.u, overlay.center_px.v);
|
||||
const int arm_length = std::max(1, overlay.arm_length_px);
|
||||
const int thickness = std::max(1, overlay.thickness);
|
||||
const cv::Scalar color = overlay.color.toCvScalar();
|
||||
cv::line(image,
|
||||
cv::Point(center.x - arm_length, center.y),
|
||||
cv::Point(center.x + arm_length, center.y),
|
||||
color,
|
||||
thickness,
|
||||
cv::LINE_AA);
|
||||
cv::line(image,
|
||||
cv::Point(center.x, center.y - arm_length),
|
||||
cv::Point(center.x, center.y + arm_length),
|
||||
color,
|
||||
thickness,
|
||||
cv::LINE_AA);
|
||||
}
|
||||
|
||||
std::string window_name_; // 显示窗口名称。
|
||||
cv::Mat image_; // 当前待显示图像。
|
||||
std::vector<TextOverlay> texts_; // 当前待绘制的文本叠加列表。
|
||||
std::vector<PointOverlay> points_; // 当前待绘制的点叠加列表。
|
||||
std::vector<CircleOverlay> circles_; // 当前待绘制的圆圈叠加列表。
|
||||
std::vector<CrossOverlay> crosses_; // 当前待绘制的十字叠加列表。
|
||||
bool window_created_{false}; // 显示窗口是否已经创建。
|
||||
};
|
||||
|
||||
} // namespace cmvr::common
|
||||
File diff suppressed because it is too large
Load Diff
209
cmvr-es/config/README.md
Normal file
209
cmvr-es/config/README.md
Normal file
@ -0,0 +1,209 @@
|
||||
# Config 模块开发指南
|
||||
|
||||
`config/` 保存 CMVR-ES 的默认运行配置。配置格式是 Protobuf TextFormat,Schema 位于 [`../../protos/cmvr/config/`](../../protos/cmvr/config/)。
|
||||
|
||||
返回[项目总览](../../README.md)。
|
||||
|
||||
## 配置树
|
||||
|
||||
```text
|
||||
cmvr_es.pb.txt
|
||||
├── logger/logger.pb.txt
|
||||
├── manager/device_manager.pb.txt
|
||||
│ └── devices/<category>/*.pb.txt
|
||||
└── manager/task_manager.pb.txt
|
||||
└── tasks/<task>/*.pb.txt
|
||||
```
|
||||
|
||||
入口文件:
|
||||
|
||||
- [`cmvr_es.pb.txt`](cmvr_es.pb.txt)
|
||||
- [`manager/device_manager.pb.txt`](manager/device_manager.pb.txt)
|
||||
- [`manager/task_manager.pb.txt`](manager/task_manager.pb.txt)
|
||||
|
||||
## 路径规则
|
||||
|
||||
无参数运行时,程序读取:
|
||||
|
||||
```text
|
||||
<cmvr_es 可执行文件所在目录>/config/cmvr_es.pb.txt
|
||||
```
|
||||
|
||||
安装后的 `output/bin/cmvr_es` 因此会读取 `output/bin/config/cmvr_es.pb.txt`;直接运行 `build/cmvr_es` 则会查找 `build/config/cmvr_es.pb.txt`,不会自动跳到安装目录。传入显式根配置时使用 `--config`:
|
||||
|
||||
```bash
|
||||
./output/bin/cmvr_es --config /etc/cmvr-es/cmvr_es.pb.txt
|
||||
```
|
||||
|
||||
设备、任务和证书等相对配置路径均以根配置文件所在目录解析。模型等资源通过 `ConfigHelper::resolveResourceFile()` 在配置根及父目录中查找;生产部署仍建议使用明确绝对路径。
|
||||
|
||||
日志配置中的相对 `directory` 以可执行文件目录解析,不以配置根解析。
|
||||
|
||||
## 新增设备配置
|
||||
|
||||
增加同类设备后端时:
|
||||
|
||||
1. 在 `protos/cmvr/config/<category>_config/` 增加后端 message;
|
||||
2. 在类别设备 message 的 `oneof backend` 中增加字段;
|
||||
3. 在 `devices/<category>/` 的 `.pb.txt` 中增加实例;
|
||||
4. 实例外层 `id` 必须唯一;
|
||||
5. 在 [`manager/device_manager.pb.txt`](manager/device_manager.pb.txt) 增加相同 `id`、正确 `type` 和配置路径;
|
||||
6. 开发默认保持 `enable: false`;
|
||||
7. 同步类别 factory 和 CMake;
|
||||
8. 在无硬件环境验证关闭状态,在真机环境单独开启。
|
||||
|
||||
设备集合中的 ID 与 DeviceManager 条目 ID 不一致时,工厂会拒绝创建。
|
||||
|
||||
## 新增任务配置
|
||||
|
||||
1. 在 `protos/cmvr/config/` 增加任务配置和 root message;
|
||||
2. 在 `tasks/<task_name>/` 增加默认 `.pb.txt`;
|
||||
3. 在 `task_manager.pb.txt` 增加唯一任务 ID;
|
||||
4. 配置正确的 `TaskType` 和 `TaskRunMode`;
|
||||
5. 周期任务设置大于零的 `control_period_s`;
|
||||
6. 服务任务使用 `TASK_RUN_MODE_BLOCKING_SERVICE`;
|
||||
7. 默认关闭依赖网络、证书或硬件的新任务。
|
||||
|
||||
任务实现流程见 [`../task/README.md`](../task/README.md)。
|
||||
|
||||
## 默认值与校验
|
||||
|
||||
- 不依赖 proto3 数值零值表达危险的生产默认值;
|
||||
- timeout、队列大小、帧大小和周期应在代码中校验;
|
||||
- 新增 loader 对不认识的 enum 和未设置的 oneof 必须明确失败;当前个别历史路径仍有退化默认行为,不应复制;
|
||||
- 设备端口、坐标系、速度和单位写入注释;
|
||||
- `enable` 应由 manager 层控制,后端内部的 enable 字段不能替代 manager 开关;
|
||||
- QUIC 任务需要在 TaskManager 中显式开启;
|
||||
- QUIC 零媒体轨道是合法配置。
|
||||
|
||||
### QUIC 多平台
|
||||
|
||||
`QuicEdgeTask` 可以同时连接多个平台。原有顶层
|
||||
`server_host`、`server_port`、`tls` 继续表示主平台;每个 `platforms` 条目会与主平台
|
||||
并行运行。也可以不配置顶层目标,只使用一个或多个 `platforms` 条目:
|
||||
|
||||
```protobuf
|
||||
platforms {
|
||||
id: "operations"
|
||||
server_host: "192.168.0.222"
|
||||
server_port: 4433
|
||||
enable_media: false
|
||||
tls {
|
||||
ca_file: "certs/cmvr-quic-ca.crt"
|
||||
server_name: "192.168.0.222"
|
||||
}
|
||||
}
|
||||
platforms {
|
||||
id: "analytics"
|
||||
server_host: "192.168.0.223"
|
||||
server_port: 4433
|
||||
enable_media: true
|
||||
tls {
|
||||
ca_file: "certs/cmvr-quic-ca.crt"
|
||||
server_name: "192.168.0.223"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
平台 ID 和 `host:port` 必须分别唯一;配置兼容主平台时,其平台 ID 使用任务
|
||||
`QuicEdgeConfig.id`,新增条目也不能与它重名。每个平台拥有独立的 QUIC 连接、
|
||||
注册会话、心跳序号、ACK 超时和重连退避,一个平台断线不会阻塞其他平台。
|
||||
`enable_media` 默认为 `false`,此时仍发送注册、心跳、网络接口和设备状态,但不会
|
||||
复制音视频;设为 `true` 才会把全局 `tracks` 转发到该平台。兼容的顶层主平台保持
|
||||
原有媒体行为。
|
||||
|
||||
### gRPC 相机实时流
|
||||
|
||||
[`tasks/grpc_server_task/grpc_server_task.pb.txt`](tasks/grpc_server_task/grpc_server_task.pb.txt)
|
||||
中的两个低延迟参数仅作用于 gRPC RGB 编码流,不改变机械臂、AGV 等控制 RPC:
|
||||
|
||||
- `camera_stream_max_pending_frames`:单个客户端允许的待发送帧数,超过后清空该
|
||||
客户端积压;默认 2;
|
||||
- `camera_stream_max_frame_age_ms`:从设备回调进入边缘系统起计算的最大帧龄,
|
||||
超过后不再发送;默认 250 ms。
|
||||
|
||||
两个字段填 0 或旧配置未包含字段时使用默认值。丢弃 H.264/H.265 帧后服务会请求
|
||||
IDR 并等待关键帧恢复。如果现场采集、编码本身稳定超过 250 ms,应根据日志中的
|
||||
`age_ms` 调高帧龄阈值,而不是增大环形队列。
|
||||
|
||||
新二进制可以读取未包含这两个字段的旧配置;旧二进制不能解析包含新字段的
|
||||
TextFormat。部署时必须同步更新程序与配置,不能只把新版
|
||||
`grpc_server_task.pb.txt` 复制给旧的 `output/bin/cmvr_es`。
|
||||
|
||||
## 配置验证
|
||||
|
||||
构建后可以用 `protoc --encode` 对单个 TextFormat 文件做语法和字段验证。例如:
|
||||
|
||||
```bash
|
||||
output/bin/protoc \
|
||||
-I protos \
|
||||
--encode=cmvr.config.QuicEdgeRootConfig \
|
||||
protos/cmvr/config/quic_edge_config/quic_edge_config.proto \
|
||||
< cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt \
|
||||
> /tmp/quic_edge_config.pb
|
||||
```
|
||||
|
||||
该命令只验证 Proto Text 解析,不验证文件、设备、证书、网络和跨字段语义。最终仍需运行组件测试和进程烟雾测试。
|
||||
|
||||
## 双边遥操配置
|
||||
|
||||
源码仓库保持唯一根入口 [`cmvr_es.pb.txt`](cmvr_es.pb.txt)。统一的
|
||||
[`manager/device_manager.pb.txt`](manager/device_manager.pb.txt) 已声明
|
||||
`ume_left`、`ume_right`、`ti5_motors` 和 `right_arm`;统一的
|
||||
[`manager/task_manager.pb.txt`](manager/task_manager.pb.txt) 已声明
|
||||
`ume_teleop` 和 gRPC server。角色差异不通过增加新的源码根配置文件表达,而由
|
||||
两台机器各自的外部部署配置决定。
|
||||
|
||||
UME 主端部署配置应只启用本机需要的 UME 设备和 `ume_teleop` Task:
|
||||
|
||||
- `ume_left`、`ume_right` 在 DeviceManager 层默认关闭;
|
||||
- [`devices/arm/ume_arms.pb.txt`](devices/arm/ume_arms.pb.txt) 内部的
|
||||
`hardware_enabled` 也默认关闭;
|
||||
- 两层硬件门必须在完成 CAN 映射、限位标定和安全验收后分别启用;
|
||||
- 当前 Task 只实现会话、重连、心跳和 latest-only 指令邮箱,尚无生产算法调用
|
||||
`submitSetpoint()`,返回 effort 也尚未接入本地触觉协调器。
|
||||
|
||||
机器人从端部署配置应只启用经过验收的机械臂设备以及所需的 gRPC server:
|
||||
|
||||
- `ti5_motors`、`right_arm` 默认关闭;
|
||||
- `ArmTeleop` 服务后端默认关闭,模型哈希必须由部署配置明确给出;
|
||||
- 当前 `MotorRobotArm::servoJ()` 仍是逐关节顺序写,不满足遥操作组伺服能力门;
|
||||
- 启动 gRPC server 不代表允许遥操作执行,也不能绕过设备层硬件门。
|
||||
|
||||
部署时应把完整配置树分别复制到两台机器的外部目录,并继续使用相同的标准文件名:
|
||||
|
||||
```text
|
||||
/etc/cmvr-es/ume/cmvr_es.pb.txt
|
||||
/etc/cmvr-es/robot/cmvr_es.pb.txt
|
||||
```
|
||||
|
||||
两套根配置都继续引用各自目录下同名的
|
||||
`manager/device_manager.pb.txt` 和 `manager/task_manager.pb.txt`。运行命令为:
|
||||
|
||||
```bash
|
||||
./output/bin/cmvr_es --config /etc/cmvr-es/ume/cmvr_es.pb.txt
|
||||
./output/bin/cmvr_es --config /etc/cmvr-es/robot/cmvr_es.pb.txt
|
||||
```
|
||||
|
||||
UME 主端需要填写从端地址、会话 manifest 和认证配置;机器人从端需要填写现场
|
||||
机械臂配置。不要把生产 IP、token、私钥或设备标定值提交到仓库默认配置。
|
||||
|
||||
## 生产配置
|
||||
|
||||
`cmake --install` 会重建 `output/bin/config/`。生产配置应复制到 `/etc/cmvr-es/` 等外部目录并显式传入。
|
||||
|
||||
- 不提交真实设备密码、token、私钥和生产地址;
|
||||
- 证书与私钥放在独立 `certs/`,使用最小读取权限;
|
||||
- 为不同站点维护独立配置根,不在运行时修改仓库样例;
|
||||
- 发布前检查所有 `enable`、IP、端口和设备 ID;
|
||||
- 变更配置 Schema 时同步 Proto 兼容性文档和平台生成代码。
|
||||
|
||||
## 提交检查
|
||||
|
||||
- [ ] TextFormat 可以被对应 root message 解析
|
||||
- [ ] ID、类别和引用路径完全一致
|
||||
- [ ] 新硬件和新网络任务默认关闭
|
||||
- [ ] 参数单位、范围和安全默认值明确
|
||||
- [ ] 没有生产凭据
|
||||
- [ ] 安装覆盖不会丢失现场配置
|
||||
- [ ] 无设备启动仍然成功
|
||||
25
cmvr-es/config/certs/cmvr-quic-ca.crt
Normal file
25
cmvr-es/config/certs/cmvr-quic-ca.crt
Normal file
@ -0,0 +1,25 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEKzCCApOgAwIBAgIUTtZCyKM8INYxZKkfwbKdpHKLjn4wDQYJKoZIhvcNAQEL
|
||||
BQAwHTEbMBkGA1UEAwwSQ01WUiBRVUlDIExvY2FsIENBMB4XDTI2MDcyNDA2NDQy
|
||||
MFoXDTM2MDcyMTA2NDQyMFowHTEbMBkGA1UEAwwSQ01WUiBRVUlDIExvY2FsIENB
|
||||
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAmq2rHldOobaemqNfWggS
|
||||
OVj3inKy6AYjfgtcXUfKs48DDbpZ9gyEd/YPJXA8C2jGPXpxzgnc7a4UCUVQZ8ah
|
||||
ddoJtFcC+Q6BgjeMVqUdUubu5Y9HpkfU3lvnp4KhzvOeFnkKtrCzYIPa2nK3zLc7
|
||||
uCiuLlB+91KQSRXPFbc6N7H/EAfGmUHIwlZGysAkRN7b2TAoR4C7E96JLVtuUQsS
|
||||
VtlEGpunSfuefFzeeZCMS6avLbB+a8Q6yUzLt6pqnheNsDB+jCCXodlJs5XS1AOB
|
||||
W2GOpGFMj7dLoTD+eBIlAlrhWFcwKjzFmtp6LGl/Jy0O+E99X4TL72oNSOdTrO2O
|
||||
iavXABz9IvWR2BrAyo5AKlTJqO6tmZw77iVti8jYi+HsXIVGQKMYwvv5k0jdHeIZ
|
||||
FaDToUbFPP/zj0m8ZraMy+8eNAhScnx6Zs56fcncBuDti6pT+zKisjV1rH/sFvZY
|
||||
wO1UvJlOEbvXrfYLPp58Aqe/toG2nV45a2Q4+x6AETV1AgMBAAGjYzBhMB0GA1Ud
|
||||
DgQWBBRdHz+g2vVmqghDZi2kEHtZfoyHZzAfBgNVHSMEGDAWgBRdHz+g2vVmqghD
|
||||
Zi2kEHtZfoyHZzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkq
|
||||
hkiG9w0BAQsFAAOCAYEASuEoMFiVcg4iTMxO2kshFTJ6LIrqqGXBn+1j+yQ1ennG
|
||||
mqPMo5fBOe/Kp3YWCnREQWu0+EEPEC9qWgIDOIm3v7ch4mZiW31GUOqae6bjprBe
|
||||
er7ySElKGZ5GefKAq++we19A6WHnNxtNAT9BE1VSKUmkxEsnIkuwd+QMmQ9eaIRm
|
||||
8RvzshWdUcyiBJg07sI3rPzPD/YpnfcYlAa2a0+oXJ3o3zlhdbs2S+9fIl+Y/zFN
|
||||
wBaUV6ZNk0RFzOCA+jUq2jU5Y1pODcot3Mp2jCHzp4uTFyVqsoqc5USRB2TUILCP
|
||||
acSbEjD9GnKaNU4miTcftnC85fnBAiZ5btZkXIs72ij+J3VW7QnbcFQG8bElngoR
|
||||
mWizh6ByPQrsvyT0evJjdjpuOzILsVTAn64m0cYpnlR4g5orcEkIJHv4DzMhpXc2
|
||||
CvpcWwk2vJrUuws/LGxDATTAcqtIUIxAkxffqUsdB/6j8fdykNCvXFwNh/uPcawd
|
||||
4kzh6dr+RFzHSMQ6oN16
|
||||
-----END CERTIFICATE-----
|
||||
40
cmvr-es/config/certs/cmvr-quic-ca.key
Normal file
40
cmvr-es/config/certs/cmvr-quic-ca.key
Normal file
@ -0,0 +1,40 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIG/wIBADANBgkqhkiG9w0BAQEFAASCBukwggblAgEAAoIBgQCaraseV06htp6a
|
||||
o19aCBI5WPeKcrLoBiN+C1xdR8qzjwMNuln2DIR39g8lcDwLaMY9enHOCdztrhQJ
|
||||
RVBnxqF12gm0VwL5DoGCN4xWpR1S5u7lj0emR9TeW+engqHO854WeQq2sLNgg9ra
|
||||
crfMtzu4KK4uUH73UpBJFc8Vtzo3sf8QB8aZQcjCVkbKwCRE3tvZMChHgLsT3okt
|
||||
W25RCxJW2UQam6dJ+558XN55kIxLpq8tsH5rxDrJTMu3qmqeF42wMH6MIJeh2Umz
|
||||
ldLUA4FbYY6kYUyPt0uhMP54EiUCWuFYVzAqPMWa2nosaX8nLQ74T31fhMvvag1I
|
||||
51Os7Y6Jq9cAHP0i9ZHYGsDKjkAqVMmo7q2ZnDvuJW2LyNiL4exchUZAoxjC+/mT
|
||||
SN0d4hkVoNOhRsU8//OPSbxmtozL7x40CFJyfHpmznp9ydwG4O2LqlP7MqKyNXWs
|
||||
f+wW9ljA7VS8mU4Ru9et9gs+nnwCp7+2gbadXjlrZDj7HoARNXUCAwEAAQKCAYAi
|
||||
e49/pNqWghoTItM9xLldWAhdcMsSH1Y3wgweDoRxqbL2U0I9cFZy0OPZBo+YQowZ
|
||||
RgwLcRbz1MBKPc3aSMWTep95uQEkaVe1YjFS2p3yLqH5AstoFjDuPmJjLWPpuVVX
|
||||
sLXS+wsOO+7lDriLdpjlagpEsHTRqbIZXPeM4YtkwbV5SyZ64ZfCPU4sYo/jW6R6
|
||||
43nDUP9Dw3Nk7XJnNlbpDigY33T4sRPIqUJ+qtsf/WGlx6gzWax6Vni+8gqxQlIe
|
||||
80XG6dHCM3UGFEdGF64PB2FuprsPWBSSau7L7I/gagiIuQbhs9VYXOanz1MQizMU
|
||||
ZdK8cqmG/bpP+uY4VQLJ5Lxu87boEllGFHBOYTCjWq0zatzGMt1/DeggLnjgfC90
|
||||
5kOzlxl403j+4K8nqiHoKpAbOatwTxFz1up6XSecsarE1RKsCq8sIH+FjjCfO1Db
|
||||
hBfv2a7/XemdcxHtl9Q/EOSDaAFOUQfFMDAc3rCH7/vonTzaaZq5ucWmjlBsv2EC
|
||||
gcEAz+cH+3x09pXVOnM7zlWrGAQk69Fj/0BGs7g3GFf8ZvI/kkbez+9J1QGItxj+
|
||||
7Dm4Ay0kgxYi3DxFWbPLHTbFpVg2CyL08IQZSXJzokwz2V/HTd1a+OgzgB/dBNDc
|
||||
V+XnxJI89+SI3VhOQZJG625l//lhHWCy2u0ULE7ZlK3ao95L86bSXQHI4dZ2nWXl
|
||||
0f4ISJmm4qkEJAY+DkQeF3UZLumd1NRxy0LBdbYVM/wZIN+sGsRdQqQ9f+ik6+aX
|
||||
YrjhAoHBAL52dJzIPIN1Z/Y9qxUrVLPE7K8Mm8KLaFIl/ztl3TFqaUvErHi66nx3
|
||||
MTwEnrQIBI31OKxB6Or2JLxYMvDTSVRV1K2tY53+K6Q8giWU4x3zFc/svyl35gkd
|
||||
U1bLdfxXqKMLrvlmVWj6/RMoH7vd/aTcidYVvwOZgtL+6RahS4LfZ9qXAyREFAJa
|
||||
VSI0HW5LLiOBLTegztT1CBVe7xb78bWFMiUkxre4XsLZYwFPzXzVPh6HloDcACDL
|
||||
FPwLrfJrFQKBwQCvGDl90UzEnF4v0vsshLQLDvp1bS1VvTGOjPhB1WBq510o+e0P
|
||||
nM1Gyvr0keWo19elPTDCAjOr3kreCHFpEkcVQRyK9o7pvad6Vx0SNDF6wpKdfm7u
|
||||
sMknAC7prmnU0XkH8c3NTTkDiiqmSObXw2u+UK48ysL3ZLIXuvS+pkk8t6yp8Pa8
|
||||
hBNGOJQ/baFH4TXixx1pScWF/YfoBfB9+w4Rl4loxN9tu7QpSgfDd29GY3qUNIsC
|
||||
5EYzYqD7WIJpD6ECgcEAkdIfdenYas14yw5r7ck/EGO00lDU8B3LwRlWUCOtNihC
|
||||
dcAeTFDPNnwLNehTmYKJ+iXFPh04Nqw9c/YTCk651dfg/RfDLTNsNlIdUqirOkLi
|
||||
cE7SDO2/MTtCkzEzI//5HNvVGx0+RyHioMgXg75yc8ZlwYLku9zMTL7dtnXHWmux
|
||||
F6qGvT1iFGsUwxsjbU4iBQzhkbWMpX70sWf9pZs/c7qGqel+OyrtYkENi/ONYAXj
|
||||
iXxFvmKxtmnFpzNJ+lABAoHBAJjs8jfEXJnJP80t93Bxg6NmfKhxUEm4ovcIeR8U
|
||||
lEfb8Ind1ICrBWGVGOAkirTFZgFAAlEjne+lT1FYgf19oC+XbxFdl/e02M8KfflS
|
||||
01+0/t6lEpefiU0dfW0dWtXOPaAVvpNgMkeMgBzB2Yz7ZNUrMypfCGk289qveWxB
|
||||
8UbO+QLjTI+cFvPsmR95Eti/nAjd2fXGeqbR+z+DdQnz4BvXLSCQCw4on2+T+mpw
|
||||
BprrEQmcdeZA8LE1zgcKtkZR1w==
|
||||
-----END PRIVATE KEY-----
|
||||
1
cmvr-es/config/certs/cmvr-quic-ca.srl
Normal file
1
cmvr-es/config/certs/cmvr-quic-ca.srl
Normal file
@ -0,0 +1 @@
|
||||
2C945D70B02014891B6E09D57E377CEFB6D18498
|
||||
22
cmvr-es/config/certs/quic-gateway.crt
Normal file
22
cmvr-es/config/certs/quic-gateway.crt
Normal file
@ -0,0 +1,22 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDuzCCAiOgAwIBAgIULJRdcLAgFIkbbgnVfjd877bRhJgwDQYJKoZIhvcNAQEL
|
||||
BQAwHTEbMBkGA1UEAwwSQ01WUiBRVUlDIExvY2FsIENBMB4XDTI2MDcyNDA2NDQz
|
||||
NloXDTI4MTAyNjA2NDQzNlowGDEWMBQGA1UEAwwNMTkyLjE2OC4wLjIyMjCCASIw
|
||||
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKdM3i1FYFKqNWJzhfhsD9nRUAuK
|
||||
pzilz5uqCKAt8lKYYC9WnLHOYdiEjcHGnGr02yd6sWFH/LBbxNhzx8M7h4S4izuO
|
||||
bhSlG1EIhkMiojzVD1e3P7YzXdEoVxTCfmMgBZQJG63GNOfzRawFYtEeGv7ndFVw
|
||||
kitCYlyTza5KlBNlWpiNOPmmx4dLTdGLUk8a5TUm0zJ+b/LyzVsWUtr9sxKmKeG8
|
||||
0/77AeiL0hQE3xUt5QROTZjRTVhNHowv410dFMJyIfY4sab8ndc4SIwE9PCKg068
|
||||
4705vbFInBS3eTvQur5VLSZLPatnXGKzCXjci1lIQX2p/QIqADMGFWIN9OECAwEA
|
||||
AaN4MHYwDwYDVR0RBAgwBocEwKgA3jAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAww
|
||||
CgYIKwYBBQUHAwEwHQYDVR0OBBYEFLmoEtsglxm3mXh4l8OF31bt2ZhnMB8GA1Ud
|
||||
IwQYMBaAFF0fP6Da9WaqCENmLaQQe1l+jIdnMA0GCSqGSIb3DQEBCwUAA4IBgQAR
|
||||
eK1mD9rJkzHe4OusimQfcuDQW+0J32e4T/34RHlW+lIj7botFaElXIzO9S80tDwq
|
||||
4d4ozNPKysqgJN9hv/BBMzJpZLwP2XozPaGLTNl1jRTCc9UhFUPrUeu0LbpQGBfC
|
||||
6Ghq42V94zPAw4lnMujnkq8botk21hclbJORQ9kblXP31IdWCgiKSFLy1NTBmQmc
|
||||
IxmR+SldMWYrWGWv/0I85AeMu6HR3+NKHmzDblm1HUHFekyC1f7sypNG+D1r8ab2
|
||||
GSijoCMKHSEOm81Vl/j5bgWQygnnIOhsLOUf2DZO6jC+VZmTKpMEJNHgwk23WBlu
|
||||
FYz/X9p5z9ZucL8aBxegj7G1fI5Ik2O05+LLeqJMfspAm6ZcnRDxCVZWQ+K/dAle
|
||||
fz+gTASzhHTsjEBeiX46LP0L2PVyBiPvNtD66e52LoM5ZigechZq91niLO+ipWdh
|
||||
xq7ryJzmaAEQKPuYaoswriWzJam07ywX9yupGHzBA6vVgGy0jPAsnGCuZXTfDyA=
|
||||
-----END CERTIFICATE-----
|
||||
17
cmvr-es/config/certs/quic-gateway.csr
Normal file
17
cmvr-es/config/certs/quic-gateway.csr
Normal file
@ -0,0 +1,17 @@
|
||||
-----BEGIN CERTIFICATE REQUEST-----
|
||||
MIICpDCCAYwCAQAwGDEWMBQGA1UEAwwNMTkyLjE2OC4wLjIyMjCCASIwDQYJKoZI
|
||||
hvcNAQEBBQADggEPADCCAQoCggEBAKdM3i1FYFKqNWJzhfhsD9nRUAuKpzilz5uq
|
||||
CKAt8lKYYC9WnLHOYdiEjcHGnGr02yd6sWFH/LBbxNhzx8M7h4S4izuObhSlG1EI
|
||||
hkMiojzVD1e3P7YzXdEoVxTCfmMgBZQJG63GNOfzRawFYtEeGv7ndFVwkitCYlyT
|
||||
za5KlBNlWpiNOPmmx4dLTdGLUk8a5TUm0zJ+b/LyzVsWUtr9sxKmKeG80/77AeiL
|
||||
0hQE3xUt5QROTZjRTVhNHowv410dFMJyIfY4sab8ndc4SIwE9PCKg0684705vbFI
|
||||
nBS3eTvQur5VLSZLPatnXGKzCXjci1lIQX2p/QIqADMGFWIN9OECAwEAAaBHMEUG
|
||||
CSqGSIb3DQEJDjE4MDYwDwYDVR0RBAgwBocEwKgA3jAOBgNVHQ8BAf8EBAMCBaAw
|
||||
EwYDVR0lBAwwCgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggEBAGIcLeCE344z
|
||||
PENI1/oONVHBzMMt5VN0P8jbkJOFgZ3a6AUhfqAmDNBr+8SBym+cX2Y9Q2BsaWAu
|
||||
TKOBN+fs+fh5/NqF0hTNvmXzp89NFK5SlsTjoC21HJvK1HTNuNW8drOxNfWgFW3/
|
||||
gSCutcsWS9hVtYrV2FHQzOvVXvXKfmuTkZE8g92P3BCkvRm+ORxI0QfVS81/Ibnv
|
||||
Yl+t/o2QCphdP+1OWzU6+Pccqi2xCyIc6jqCmh0b01zg265PTTOfICO6WQNtYcOn
|
||||
308avDDpTneGl5vWRVdmmiXPqkc+dCesoguIEDUlerFpDKKY81P2GTpfjki93K7Z
|
||||
2DJPs4P1cU0=
|
||||
-----END CERTIFICATE REQUEST-----
|
||||
@ -1,9 +0,0 @@
|
||||
agv {
|
||||
agvs {
|
||||
id: "agv_1"
|
||||
my_agv {
|
||||
ip: "127.0.0.1"
|
||||
port: 8080
|
||||
}
|
||||
}
|
||||
}
|
||||
47
cmvr-es/config/devices/agv/seer_robokit.pb.txt
Normal file
47
cmvr-es/config/devices/agv/seer_robokit.pb.txt
Normal file
@ -0,0 +1,47 @@
|
||||
agv {
|
||||
agvs {
|
||||
id: "agv_1"
|
||||
my_agv {
|
||||
ip: "127.0.0.1"
|
||||
port: 8080
|
||||
}
|
||||
}
|
||||
|
||||
agvs {
|
||||
# 当前部署的控制器型号为 SRC1100;该值是设备实例 ID,不是后端类型名。
|
||||
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
|
||||
recv_timeout_ms: 1000
|
||||
control_nick_name: "cmvr-es"
|
||||
enable_state_push: true
|
||||
state_push_interval_ms: 200
|
||||
state_push_included_fields: "x"
|
||||
state_push_included_fields: "y"
|
||||
state_push_included_fields: "angle"
|
||||
state_push_included_fields: "vx"
|
||||
state_push_included_fields: "vy"
|
||||
state_push_included_fields: "w"
|
||||
state_push_included_fields: "battery_level"
|
||||
state_push_included_fields: "battery_temp"
|
||||
state_push_included_fields: "charging"
|
||||
state_push_included_fields: "voltage"
|
||||
state_push_included_fields: "current"
|
||||
state_push_included_fields: "current_map"
|
||||
state_push_included_fields: "current_station"
|
||||
state_push_included_fields: "confidence"
|
||||
state_push_included_fields: "emergency"
|
||||
state_push_included_fields: "fatals"
|
||||
state_push_included_fields: "errors"
|
||||
enable_map_update: true
|
||||
map_update_interval_ms: 1000
|
||||
map_update_history_size: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,10 @@ arm {
|
||||
buffer_size: 50
|
||||
default_vel: 1.0
|
||||
default_acc: 2.0
|
||||
# Reserved only: current MotorRobotArm servoJ writes joints sequentially,
|
||||
# so code rejects the teleop group-servo capability even if this is true.
|
||||
# A reviewed atomic/timed group primitive is required before changing it.
|
||||
enable_teleop_group_servo: false
|
||||
}
|
||||
|
||||
kinematics {
|
||||
|
||||
@ -4,7 +4,7 @@ arm {
|
||||
|
||||
vendor {
|
||||
brand: VENDOR_ROBOT_ARM_BRAND_AUBO_ARM
|
||||
ip: "192.168.1.100"
|
||||
ip: "192.168.192.18"
|
||||
port: 30004
|
||||
dof: 6
|
||||
joint_names: "joint_1"
|
||||
@ -17,6 +17,7 @@ arm {
|
||||
tool_frame: "tool0"
|
||||
username: "aubo"
|
||||
password: "123456"
|
||||
auto_power_on_after_hardware_estop_release: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
72
cmvr-es/config/devices/arm/ume_arms.pb.txt
Normal file
72
cmvr-es/config/devices/arm/ume_arms.pb.txt
Normal file
@ -0,0 +1,72 @@
|
||||
# UME leader-arm device templates. They are deliberately disabled in
|
||||
# manager/device_manager.pb.txt and hardware_enabled remains false here.
|
||||
#
|
||||
# Before real hardware use, independently verify interface bitrate
|
||||
# (1 Mbit/s arbitration, 5 Mbit/s data, FD+BRS), motor/feedback IDs,
|
||||
# direction, zero offsets, mechanical joint limits and safe torque limits.
|
||||
# Each joint must also receive reviewed healthy_feedback_status and raw
|
||||
# temperature thresholds. They are deliberately absent below, so changing
|
||||
# hardware_enabled alone is insufficient to arm these placeholder profiles.
|
||||
arm {
|
||||
robot_arms {
|
||||
id: "ume_right"
|
||||
ume {
|
||||
can {
|
||||
dev_id: "can4"
|
||||
channel_id: 4
|
||||
interface_name: "can4"
|
||||
enable_fd: true
|
||||
bitrate_switch: true
|
||||
send_timeout_us: 100
|
||||
receive_timeout_us: 100
|
||||
receive_own_messages: false
|
||||
enable_error_frames: true
|
||||
}
|
||||
control_frequency_hz: 800
|
||||
cycle_deadline_us: 1000
|
||||
feedback_watchdog_ms: 20
|
||||
shutdown_timeout_ms: 50
|
||||
hardware_enabled: false
|
||||
|
||||
joints { joint_name: "RJ1" command_id: 1 feedback_id: 17 reported_motor_id: 1 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "RJ2" command_id: 2 feedback_id: 18 reported_motor_id: 2 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "RJ3" command_id: 3 feedback_id: 19 reported_motor_id: 3 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "RJ4" command_id: 4 feedback_id: 20 reported_motor_id: 4 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "RJ5" command_id: 5 feedback_id: 21 reported_motor_id: 5 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "RJ6" command_id: 6 feedback_id: 22 reported_motor_id: 6 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "RJ7" command_id: 7 feedback_id: 23 reported_motor_id: 7 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "RJ8" command_id: 8 feedback_id: 24 reported_motor_id: 8 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
robot_arms {
|
||||
id: "ume_left"
|
||||
ume {
|
||||
can {
|
||||
dev_id: "can5"
|
||||
channel_id: 5
|
||||
interface_name: "can5"
|
||||
enable_fd: true
|
||||
bitrate_switch: true
|
||||
send_timeout_us: 100
|
||||
receive_timeout_us: 100
|
||||
receive_own_messages: false
|
||||
enable_error_frames: true
|
||||
}
|
||||
control_frequency_hz: 800
|
||||
cycle_deadline_us: 1000
|
||||
feedback_watchdog_ms: 20
|
||||
shutdown_timeout_ms: 50
|
||||
hardware_enabled: false
|
||||
|
||||
joints { joint_name: "LJ1" command_id: 1 feedback_id: 17 reported_motor_id: 1 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "LJ2" command_id: 2 feedback_id: 18 reported_motor_id: 2 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "LJ3" command_id: 3 feedback_id: 19 reported_motor_id: 3 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "LJ4" command_id: 4 feedback_id: 20 reported_motor_id: 4 model: DAMIAO_MOTOR_MODEL_DM4340 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 8 max_torque_nm: 4 }
|
||||
joints { joint_name: "LJ5" command_id: 5 feedback_id: 21 reported_motor_id: 5 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "LJ6" command_id: 6 feedback_id: 22 reported_motor_id: 6 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "LJ7" command_id: 7 feedback_id: 23 reported_motor_id: 7 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
joints { joint_name: "LJ8" command_id: 8 feedback_id: 24 reported_motor_id: 8 model: DAMIAO_MOTOR_MODEL_DM4310 direction: 1 zero_offset_rad: 0 joint_lower_rad: -12.5 joint_upper_rad: 12.5 max_velocity_rad_s: 30 max_torque_nm: 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -146,4 +146,43 @@ camera {
|
||||
sync: false
|
||||
}
|
||||
}
|
||||
|
||||
cameras {
|
||||
id: "hikvision_cam"
|
||||
hikvision {
|
||||
ip: "192.168.192.64"
|
||||
port: 8000
|
||||
username: "admin"
|
||||
password: "okwy1688"
|
||||
channel: 1
|
||||
stream_type: 0
|
||||
link_mode: 0
|
||||
width: 1920
|
||||
height: 1080
|
||||
fps: 25
|
||||
codec: "H264"
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
stream_mode: STREAM_MODE_RGB
|
||||
buffer_size: 30
|
||||
}
|
||||
}
|
||||
cameras {
|
||||
id: "hikvision_thermal_cam"
|
||||
hikvision {
|
||||
ip: "192.168.192.65"
|
||||
port: 8000
|
||||
username: "admin"
|
||||
password: "okwy1688"
|
||||
channel: 1
|
||||
stream_type: 0
|
||||
link_mode: 0
|
||||
width: 384
|
||||
height: 288
|
||||
fps: 50
|
||||
codec: "H264"
|
||||
camera_mode: CAMERA_MODE_VIDEO
|
||||
stream_mode: STREAM_MODE_RGB
|
||||
buffer_size: 30
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@ microphone {
|
||||
id: "mic1"
|
||||
ffmpeg {
|
||||
channels: 2
|
||||
sampleRate: 44100
|
||||
sampleRate: 48000
|
||||
volume: 100
|
||||
input_device: "default"
|
||||
}
|
||||
|
||||
65
cmvr-es/config/devices/motor/ethercat_motors.pb.txt
Normal file
65
cmvr-es/config/devices/motor/ethercat_motors.pb.txt
Normal file
@ -0,0 +1,65 @@
|
||||
motor {
|
||||
id: "ethercat_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_ethercat"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_EYOU
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 12000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
profile_position_trigger_delay_ms: 2
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: true
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
slaves { motor_id: 2 alias: 0 position: 1 }
|
||||
slaves { motor_id: 3 alias: 0 position: 2 }
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
slaves { motor_id: 5 alias: 0 position: 4 }
|
||||
slaves { motor_id: 6 alias: 0 position: 5 }
|
||||
slaves { motor_id: 7 alias: 0 position: 6 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_Y" q_lb: -0.78 q_ub: 0.78 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 5 joint_name: "R_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 6 joint_name: "R_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 7 joint_name: "R_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
motor {
|
||||
id: "ethercat_motors"
|
||||
|
||||
motor_groups {
|
||||
id: "right_arm_ethercat"
|
||||
bus_type: MOTOR_BUS_ETHERCAT
|
||||
vendor: MOTOR_VENDOR_EYOU
|
||||
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
|
||||
|
||||
ethercat {
|
||||
master_index: 0
|
||||
cycle_us: 1000
|
||||
slave_op_timeout_ms: 15000
|
||||
slave_state_poll_period_ms: 10
|
||||
|
||||
cia402 {
|
||||
profile_position_trigger_delay_ms: 2
|
||||
state_transition_timeout_ms: 1200
|
||||
velocity_stop_timeout_ms: 2000
|
||||
status_poll_period_ms: 10
|
||||
stopped_velocity_tolerance_rad_s: 0.001
|
||||
}
|
||||
|
||||
dc {
|
||||
enable: false
|
||||
reference_motor_id: 1
|
||||
sync0_cycle_us: 1000
|
||||
sync0_shift_us: 0
|
||||
sync_reference_clock_period: 1
|
||||
assign_activate: 768
|
||||
sync_monitor_period_ms: 1000
|
||||
}
|
||||
|
||||
slaves { motor_id: 1 alias: 0 position: 0 }
|
||||
slaves { motor_id: 2 alias: 0 position: 1 }
|
||||
slaves { motor_id: 3 alias: 0 position: 2 }
|
||||
slaves { motor_id: 4 alias: 0 position: 3 }
|
||||
}
|
||||
|
||||
joint_limits {
|
||||
enable: true
|
||||
source: JOINT_LIMIT_SOURCE_CUSTOM
|
||||
joints { joint_name: "R_SHOULDER_P" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_R" q_lb: -0.78 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_SHOULDER_Y" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
|
||||
joints { joint_name: "R_ELBOW_R" q_lb: 0 q_ub: 2.05 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
|
||||
motors {
|
||||
motors { id: 1 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 2 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 3 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 4 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -6,7 +6,6 @@ motor {
|
||||
bus_type: MOTOR_BUS_MUJOCO
|
||||
vendor: MOTOR_VENDOR_MUJOCO
|
||||
protocol: MOTOR_PROTOCOL_MUJOCO
|
||||
tool_frame: "R_FINGER_TIP"
|
||||
mujoco {
|
||||
world_id: "mujoco_world"
|
||||
}
|
||||
|
||||
@ -6,7 +6,6 @@ motor {
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
tool_frame: "L_FINGER_TIP"
|
||||
can {
|
||||
channel_id: 0
|
||||
}
|
||||
@ -16,13 +15,13 @@ motor {
|
||||
urdf_path: "model/xiaoyan_description/dual_arm.urdf"
|
||||
}
|
||||
motors {
|
||||
motors { id: 23 joint_name: "L_SHOULDER_P" }
|
||||
motors { id: 24 joint_name: "L_SHOULDER_R" }
|
||||
motors { id: 25 joint_name: "L_SHOULDER_Y" }
|
||||
motors { id: 26 joint_name: "L_ELBOW_R" }
|
||||
motors { id: 27 joint_name: "L_WRIST_P" }
|
||||
motors { id: 28 joint_name: "L_WRIST_Y" }
|
||||
motors { id: 29 joint_name: "L_WRIST_R" }
|
||||
motors { id: 23 joint_name: "L_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 24 joint_name: "L_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 25 joint_name: "L_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 26 joint_name: "L_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 27 joint_name: "L_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 28 joint_name: "L_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 29 joint_name: "L_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,7 +30,6 @@ motor {
|
||||
bus_type: MOTOR_BUS_CAN
|
||||
vendor: MOTOR_VENDOR_TI5
|
||||
protocol: MOTOR_PROTOCOL_CANOPEN
|
||||
tool_frame: "R_FINGER_TIP"
|
||||
can {
|
||||
channel_id: 1
|
||||
}
|
||||
@ -47,13 +45,13 @@ motor {
|
||||
joints { joint_name: "R_WRIST_R" q_lb: -0.57 q_ub: 1.57 qd: 5.0 qdd: 10.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 16 joint_name: "R_SHOULDER_P" }
|
||||
motors { id: 17 joint_name: "R_SHOULDER_R" }
|
||||
motors { id: 18 joint_name: "R_SHOULDER_Y" }
|
||||
motors { id: 19 joint_name: "R_ELBOW_R" }
|
||||
motors { id: 20 joint_name: "R_WRIST_P" }
|
||||
motors { id: 21 joint_name: "R_WRIST_Y" }
|
||||
motors { id: 22 joint_name: "R_WRIST_R" }
|
||||
motors { id: 16 joint_name: "R_SHOULDER_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 17 joint_name: "R_SHOULDER_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 18 joint_name: "R_SHOULDER_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 19 joint_name: "R_ELBOW_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 20 joint_name: "R_WRIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 21 joint_name: "R_WRIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 22 joint_name: "R_WRIST_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@ -73,9 +71,9 @@ motor {
|
||||
joints { joint_name: "HEAD_R" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 32 joint_name: "HEAD_Y" }
|
||||
motors { id: 30 joint_name: "HEAD_P" }
|
||||
motors { id: 31 joint_name: "HEAD_R" }
|
||||
motors { id: 32 joint_name: "HEAD_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 30 joint_name: "HEAD_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 31 joint_name: "HEAD_R" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@ -94,8 +92,8 @@ motor {
|
||||
joints { joint_name: "WAIST_P" q_lb: -3.14 q_ub: 3.14 qd: 3.0 }
|
||||
}
|
||||
motors {
|
||||
motors { id: 4 joint_name: "WAIST_Y" }
|
||||
motors { id: 15 joint_name: "WAIST_P" }
|
||||
motors { id: 4 joint_name: "WAIST_Y" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
motors { id: 15 joint_name: "WAIST_P" encoder_counts_per_rev: 65536 gear_ratio: 101.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,17 +13,17 @@ logger {
|
||||
routes {
|
||||
level: LOG_LEVEL_WARNING
|
||||
terminal: true
|
||||
file: false
|
||||
file: true
|
||||
}
|
||||
routes {
|
||||
level: LOG_LEVEL_ERROR
|
||||
terminal: true
|
||||
file: false
|
||||
file: true
|
||||
}
|
||||
routes {
|
||||
level: LOG_LEVEL_FATAL
|
||||
terminal: true
|
||||
file: false
|
||||
file: true
|
||||
}
|
||||
|
||||
directory: "../log"
|
||||
|
||||
@ -2,6 +2,19 @@ device_manager {
|
||||
name: "cmvr_es"
|
||||
version: "0.1"
|
||||
description: "cmvr edge system version 0.1"
|
||||
init_all_motors_when_no_active_joints: true
|
||||
|
||||
# The unified safety coordinator observes all decisions while the legacy
|
||||
# gates remain authoritative during staged hardware migration.
|
||||
safety {
|
||||
mode: SHADOW
|
||||
stop_all_timeout_ms: 15000
|
||||
recovery_timeout_ms: 10000
|
||||
command_ledger_result_capacity: 4096
|
||||
command_ledger_total_id_capacity: 262144
|
||||
event_history_capacity: 2048
|
||||
fail_startup_on_missing_control_capability: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mujoco_world"
|
||||
@ -74,6 +87,13 @@ device_manager {
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "ethercat_motors"
|
||||
type: DEVICE_TYPE_MOTOR_SYSTEM
|
||||
config_file: "devices/motor/ethercat_motors.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "right_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
@ -85,14 +105,31 @@ device_manager {
|
||||
id: "aubo_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/aubo_arm.pb.txt"
|
||||
enable: false
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "huayan_arm"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/huayan_arm.pb.txt"
|
||||
enable: true
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "ume_right"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ume_arms.pb.txt"
|
||||
# Two gates must be explicitly changed after the physical safety review:
|
||||
# this entry and ume.hardware_enabled in the arm config.
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "ume_left"
|
||||
type: DEVICE_TYPE_ROBOT_ARM
|
||||
config_file: "devices/arm/ume_arms.pb.txt"
|
||||
# Two gates must be explicitly changed after the physical safety review.
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
@ -103,9 +140,41 @@ device_manager {
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "agv_1"
|
||||
# 当前部署的控制器型号为 SRC1100;该值是设备实例 ID,不是后端类型名。
|
||||
id: "src1100"
|
||||
type: DEVICE_TYPE_AGV
|
||||
config_file: "devices/agv/agv.pb.txt"
|
||||
config_file: "devices/agv/seer_robokit.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "hikvision_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
# Host-development default: keep physical cameras disabled.
|
||||
enable: false
|
||||
}
|
||||
devices {
|
||||
id: "hikvision_thermal_cam"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
# Host-development default: keep physical cameras disabled.
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "mic1"
|
||||
type: DEVICE_TYPE_MICROPHONE
|
||||
config_file: "devices/microphone/microphone.pb.txt"
|
||||
# Host-development default: keep physical audio devices disabled.
|
||||
enable: false
|
||||
}
|
||||
|
||||
devices {
|
||||
id: "spk1"
|
||||
type: DEVICE_TYPE_SPEAKER
|
||||
config_file: "devices/speaker/speaker.pb.txt"
|
||||
# Host-development default: keep physical audio devices disabled.
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,6 +20,23 @@ task_manager {
|
||||
run_mode: TASK_RUN_MODE_PERIODIC_STEP
|
||||
control_period_s: 0.002
|
||||
config_file: "tasks/self_collision_task/self_collision_task.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
tasks {
|
||||
id: "quic_edge"
|
||||
type: TASK_TYPE_QUIC_EDGE
|
||||
run_mode: TASK_RUN_MODE_BLOCKING_SERVICE
|
||||
config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt"
|
||||
# Host-development default: no QUIC Gateway or physical media devices.
|
||||
enable: true
|
||||
}
|
||||
tasks {
|
||||
id: "ume_teleop"
|
||||
type: TASK_TYPE_UME_TELEOP
|
||||
run_mode: TASK_RUN_MODE_BLOCKING_SERVICE
|
||||
config_file: "tasks/ume_teleop_task/ume_teleop_task.pb.txt"
|
||||
# Fail-safe default: configure the remote robot endpoint, manifest and
|
||||
# deployment security policy before enabling this outbound control task.
|
||||
enable: false
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,4 +3,33 @@ grpc_server {
|
||||
host: "0.0.0.0"
|
||||
port: "50052"
|
||||
enable_reflection: true
|
||||
camera_stream_max_pending_frames: 2
|
||||
camera_stream_max_frame_age_ms: 250
|
||||
|
||||
# Current small-scope deployment intentionally keeps the existing clients
|
||||
# certificate-free. Recovery remains unavailable over the network.
|
||||
security {
|
||||
transport_mode: INSECURE
|
||||
authentication_mode: DISABLED
|
||||
recovery_exposure: RECOVERY_DISABLED
|
||||
allow_insecure_non_loopback: true
|
||||
}
|
||||
|
||||
# The RobotArm adapter is implemented, but remains explicitly closed until
|
||||
# the device itself enables teleop group servo, real hashes are provisioned,
|
||||
# and group-write timing and independent stop behavior pass hardware review.
|
||||
arm_teleop_backend {
|
||||
enable: false
|
||||
device_id: "right_arm"
|
||||
# Deliberately empty placeholders are invalid when enable=true.
|
||||
model_sha256: ""
|
||||
calibration_sha256: ""
|
||||
base_frame: "PELVIS_S"
|
||||
tool_frame: "R_FINGER_TIP_FIXED"
|
||||
servo_period_s: 0.001
|
||||
max_apply_duration_us: 800
|
||||
require_powered: true
|
||||
max_initial_position_step_rad: 0.02
|
||||
max_position_step_rad: 0.003
|
||||
}
|
||||
}
|
||||
|
||||
79
cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt
Normal file
79
cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt
Normal file
@ -0,0 +1,79 @@
|
||||
quic_edge {
|
||||
id: "quic_edge"
|
||||
|
||||
# Task enablement is controlled by manager/task_manager.pb.txt. Configure a
|
||||
# reachable QUIC Gateway and TLS policy before enabling the task there.
|
||||
server_host: "192.168.0.222"
|
||||
server_port: 4433
|
||||
alpn: "cmvr-quic-edge/1"
|
||||
node_id: "cmvr-edge"
|
||||
robot_id: "CN-CMVR-MBLRV1-AIMA-20260806-001"
|
||||
software_version: "0.1"
|
||||
|
||||
# The existing cmvr-es gRPC server remains the robot-control endpoint. "auto"
|
||||
# selects a usable address from the interface snapshot sent at registration
|
||||
# and on every heartbeat.
|
||||
grpc_endpoint_host: "auto"
|
||||
grpc_endpoint_port: 50052
|
||||
grpc_endpoint_tls: false
|
||||
include_loopback_interfaces: false
|
||||
|
||||
# Local heartbeat period. The Gateway keeps this value when its registration
|
||||
# response returns heartbeat_interval_ms=0; a non-zero response overrides it.
|
||||
heartbeat_interval_ms: 5000
|
||||
control_response_timeout_ms: 1000
|
||||
|
||||
tls {
|
||||
ca_file: "certs/cmvr-quic-ca.crt"
|
||||
server_name: "192.168.0.222"
|
||||
allow_insecure: false
|
||||
}
|
||||
|
||||
# Additional platforms run concurrently with the primary endpoint above.
|
||||
# Each one has an independent connection, registration, heartbeat ACK state
|
||||
# and reconnect loop. Media forwarding is opt-in for additional platforms.
|
||||
# platforms {
|
||||
# id: "operations_backup"
|
||||
# server_host: "192.168.0.223"
|
||||
# server_port: 4433
|
||||
# enable_media: false
|
||||
# tls {
|
||||
# ca_file: "certs/cmvr-quic-ca.crt"
|
||||
# server_name: "192.168.0.223"
|
||||
# allow_insecure: false
|
||||
# }
|
||||
# }
|
||||
|
||||
reconnect {
|
||||
initial_delay_ms: 500
|
||||
maximum_delay_ms: 30000
|
||||
multiplier: 2.0
|
||||
jitter_percent: 20
|
||||
connect_timeout_ms: 5000
|
||||
}
|
||||
|
||||
maximum_datagram_bytes: 1200
|
||||
maximum_control_frame_bytes: 1048576
|
||||
# With 1200-byte DATAGRAMs and a 512-entry queue, 524288 stays below
|
||||
# the atomic batch capacity while reserving slots for control messages.
|
||||
maximum_frame_bytes: 524288
|
||||
datagram_send_queue_depth: 512
|
||||
media_poll_interval_ms: 2
|
||||
|
||||
# Zero media tracks is valid and keeps registration, IP reporting and
|
||||
# heartbeat active. Add tracks only for devices enabled in DeviceManager.
|
||||
# tracks {
|
||||
# track_id: 1
|
||||
# source_kind: SOURCE_KIND_CAMERA
|
||||
# device_id: "right_hand_cam"
|
||||
# source_track_id: "right_hand_cam/video/color"
|
||||
# enable: true
|
||||
# }
|
||||
# tracks {
|
||||
# track_id: 2
|
||||
# source_kind: SOURCE_KIND_MICROPHONE
|
||||
# device_id: "mic1"
|
||||
# source_track_id: "mic1/audio/main"
|
||||
# enable: true
|
||||
# }
|
||||
}
|
||||
35
cmvr-es/config/tasks/ume_teleop_task/ume_teleop_task.pb.txt
Normal file
35
cmvr-es/config/tasks/ume_teleop_task/ume_teleop_task.pb.txt
Normal file
@ -0,0 +1,35 @@
|
||||
ume_teleop {
|
||||
id: "ume_teleop"
|
||||
|
||||
# Deliberately left empty. The TaskManager entry is disabled by default, and
|
||||
# init fails closed if it is enabled before a robot endpoint is configured.
|
||||
server_address: ""
|
||||
|
||||
# M6 implements explicit insecure transport for isolated development only.
|
||||
# Production deployment must add and configure channel credentials first.
|
||||
allow_insecure: false
|
||||
|
||||
open_session {
|
||||
protocol_major: 1
|
||||
protocol_minor: 0
|
||||
client_instance_id: "ume-controller"
|
||||
requested_command_rate_hz: 250
|
||||
requested_state_rate_hz: 250
|
||||
watchdog_timeout_ms: 100
|
||||
requested_lease_ms: 500
|
||||
|
||||
# Replace with the manifest exported by the CMVR-ES robot instance.
|
||||
expected_robot {
|
||||
robot_id: ""
|
||||
position_unit: "rad"
|
||||
velocity_unit: "rad/s"
|
||||
effort_unit: "N*m"
|
||||
}
|
||||
}
|
||||
|
||||
reconnect {
|
||||
initial_delay_ms: 100
|
||||
maximum_delay_ms: 5000
|
||||
multiplier: 2.0
|
||||
}
|
||||
}
|
||||
367
cmvr-es/devices/README.md
Normal file
367
cmvr-es/devices/README.md
Normal file
@ -0,0 +1,367 @@
|
||||
# Devices 模块开发指南
|
||||
|
||||
`devices/` 屏蔽厂商 SDK、通信总线和硬件型号差异,对 manager、service、task 和算法层提供稳定的设备能力接口。
|
||||
|
||||
仓库真实目录名是 `cmvr-es/devices/`。设备层使用复数 `devices`,不是 `cmvr_es/device`。
|
||||
|
||||
返回[项目总览](../../README.md)。
|
||||
|
||||
## 创建链路
|
||||
|
||||
```text
|
||||
config/cmvr_es.pb.txt
|
||||
-> config/manager/device_manager.pb.txt
|
||||
-> DeviceManager
|
||||
-> DeviceFactory
|
||||
按 DeviceConfigEntry::DeviceType 选择设备大类
|
||||
-> CameraFactory / AGVFactory / RobotArmFactory / ...
|
||||
按设备配置 oneof backend 选择厂商实现
|
||||
-> 具体设备类
|
||||
-> AbstractDevice 和设备大类抽象接口
|
||||
```
|
||||
|
||||
关键文件:
|
||||
|
||||
- [`abstract_device.h`](abstract_device.h)
|
||||
- [`device_types.h`](device_types.h)
|
||||
- [`../manager/device_manager/include/device_manager.h`](../manager/device_manager/include/device_manager.h)
|
||||
- [`../manager/device_manager/src/device_factory.cpp`](../manager/device_manager/src/device_factory.cpp)
|
||||
- [`../../protos/cmvr/config/device_manager_config/device_manager_config.proto`](../../protos/cmvr/config/device_manager_config/device_manager_config.proto)
|
||||
- [`../config/manager/device_manager.pb.txt`](../config/manager/device_manager.pb.txt)
|
||||
|
||||
协议层和业务任务不应直接依赖厂商 SDK 类型。厂商错误码、报文和连接细节由具体后端转换为抽象接口的通用语义。
|
||||
|
||||
## 当前可由配置创建的设备
|
||||
|
||||
| 大类 | 抽象接口 | 类别工厂 | 当前可选后端 |
|
||||
| --- | --- | --- | --- |
|
||||
| Camera | [`camera/abstract_camera.h`](camera/abstract_camera.h) | [`camera/camera_factory.h`](camera/camera_factory.h) | UVC、RealSense、Hikvision |
|
||||
| AGV | [`agv/abstract_agv.h`](agv/abstract_agv.h) | [`agv/agv_factory.h`](agv/agv_factory.h) | MyAgv、SEER Robokit |
|
||||
| RobotArm | [`arm/robot_arm.h`](arm/robot_arm.h) | [`arm/robot_arm_factory.h`](arm/robot_arm_factory.h) | MotorRobotArm、[AUBO](arm/aubo_arm/README.md)、Huayan、UME |
|
||||
| DexHand | [`dexhand/abstract_dexhand.h`](dexhand/abstract_dexhand.h) | [`dexhand/dexhand_factory.h`](dexhand/dexhand_factory.h) | RH56DFTP、PX6AXGen3 |
|
||||
| Microphone | [`microphone/abstract_microphone.h`](microphone/abstract_microphone.h) | [`microphone/microphone_factory.h`](microphone/microphone_factory.h) | FFmpeg |
|
||||
| Speaker | [`speaker/abstract_speaker.h`](speaker/abstract_speaker.h) | [`speaker/speaker_factory.h`](speaker/speaker_factory.h) | FFmpeg |
|
||||
| BioHead | [`biohead/abstract_biohead.h`](biohead/abstract_biohead.h) | DeviceFactory 直接创建 | BioHeadRobot |
|
||||
| MotorSystem | [`motor/`](motor/README.md) | DeviceFactory 直接创建 | CAN、MuJoCo、EtherCAT |
|
||||
|
||||
代码目录存在不等于已经接入配置创建链:
|
||||
|
||||
- MechMind Proto 和实现仍存在,但当前 CameraFactory 明确拒绝创建;
|
||||
- MujocoCamera 有实现并参与部分构建,但当前没有 CameraFactory 分支;
|
||||
- Battery、Gripper、Robot、CanBus 等抽象或实现不一定已注册到 DeviceFactory;
|
||||
- 所有已注册设备共用一个全局 ID 命名空间。
|
||||
|
||||
新增能力前先确认“已有代码”“可被 CMake 构建”“可被 Factory 创建”“可被 DeviceManager 配置启用”四个状态,不要混为一谈。
|
||||
|
||||
## 新增同类厂商后端
|
||||
|
||||
以新增 Camera 后端为例。
|
||||
|
||||
### 1. 扩展配置 Proto
|
||||
|
||||
修改:
|
||||
|
||||
```text
|
||||
protos/cmvr/config/camera_config/camera_config.proto
|
||||
```
|
||||
|
||||
新增厂商 config,并加入 `CameraDeviceConfig.oneof backend`。只使用新的字段 tag,不复用 reserved 或已发布 tag。
|
||||
|
||||
### 2. 新建后端目录
|
||||
|
||||
```text
|
||||
camera/vendor_camera/
|
||||
├── CMakeLists.txt
|
||||
├── include/
|
||||
│ └── vendor_camera.h
|
||||
├── src/
|
||||
│ └── vendor_camera.cpp
|
||||
└── tests/
|
||||
└── vendor_camera_test.cpp
|
||||
```
|
||||
|
||||
### 3. 实现抽象接口
|
||||
|
||||
至少实现:
|
||||
|
||||
- `typeName()`;
|
||||
- `init()`;
|
||||
- 实际支持的 `start()` / `stop()`;
|
||||
- 状态查询和该类别核心能力;
|
||||
- 若能提供运行时健康信息,实现无阻塞的 `healthSnapshot()`;
|
||||
- 若支持实时媒体,完整实现流接口和并发停止。
|
||||
|
||||
不要为了厂商特例向抽象类加入 SDK handle、私有报文或厂商专有结构。只有多个后端都需要的稳定语义才进入抽象接口或 `common/types/`。
|
||||
|
||||
### 4. 类别工厂注册
|
||||
|
||||
在 [`camera/camera_factory.h`](camera/camera_factory.h) 的 `backend_case()` 增加创建分支。
|
||||
|
||||
AGV、DexHand、Microphone、Speaker 等遵循相同模式。新增同类后端通常不需要修改全局 DeviceFactory。
|
||||
|
||||
### 5. CMake 聚合
|
||||
|
||||
1. 在 `camera/CMakeLists.txt` 增加 `add_subdirectory(vendor_camera)`;
|
||||
2. 让类别 target 链接新后端 target;
|
||||
3. 安装需要随应用分发的共享库;
|
||||
4. 厂商 SDK 路径使用 `dependency/${ARCH}/third_party/...`,不能硬编码 x86;
|
||||
5. 需要特殊 RPATH 时参考 Hikvision、Huayan 等现有实现。
|
||||
|
||||
推荐 target 形式:
|
||||
|
||||
```cmake
|
||||
add_library(vendor_camera SHARED
|
||||
src/vendor_camera.cpp
|
||||
)
|
||||
|
||||
target_include_directories(vendor_camera
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(vendor_camera
|
||||
PUBLIC cmvr_es::proto
|
||||
PRIVATE vendor_sdk
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::vendor_camera ALIAS vendor_camera)
|
||||
install(TARGETS vendor_camera LIBRARY DESTINATION lib)
|
||||
```
|
||||
|
||||
### 6. 默认配置
|
||||
|
||||
在类别集合配置增加实例,并在 DeviceManager 配置增加同 ID 条目:
|
||||
|
||||
```protobuf
|
||||
devices {
|
||||
id: "camera_front"
|
||||
type: DEVICE_TYPE_CAMERA
|
||||
config_file: "devices/camera/camera.pb.txt"
|
||||
enable: false
|
||||
}
|
||||
```
|
||||
|
||||
新硬件默认 `enable: false`,确保无设备开发主机仍可启动。
|
||||
|
||||
## 新增全新设备大类
|
||||
|
||||
当现有抽象无法表达新设备能力时,还需要:
|
||||
|
||||
1. 在 [`device_types.h`](device_types.h) 增加 `DeviceKind` 和 `toString()`;
|
||||
2. 新增类别抽象接口;
|
||||
3. 将稳定公共数据放入 `../common/types/<category>/`;
|
||||
4. 新增配置 Proto;
|
||||
5. 在 `DeviceConfigEntry::DeviceType` 使用新的 enum 数值;
|
||||
6. 在 `DeviceFactory::DeviceFactory()` 注册 creator;
|
||||
7. 更新 DeviceManager 的 type-to-string 日志映射;
|
||||
8. 为 `getDevice<AbstractNewDevice>()` 增加显式模板实例化;
|
||||
9. 更新 `devices/CMakeLists.txt`、类别 CMake 和 device_manager target 链接;
|
||||
10. 若平台需要访问,独立增加 API Proto 和 gRPC service。
|
||||
|
||||
不得复用 `device_manager_config.proto` 中已 reserved 的 enum 数值或名称。新增设备类别不会自动生成平台 RPC。
|
||||
|
||||
## 配置和 ID
|
||||
|
||||
集合类型设备必须满足:
|
||||
|
||||
```text
|
||||
DeviceConfigEntry.id
|
||||
==
|
||||
CameraDeviceConfig / AGVDeviceConfig / ... 的外层 id
|
||||
```
|
||||
|
||||
厂商 backend 内部 ID 可以为空,由类别工厂补齐;若填写,也必须与外层 ID 相同。
|
||||
|
||||
其他约束:
|
||||
|
||||
- 相对配置路径以根 `cmvr_es.pb.txt` 所在目录解析;
|
||||
- 生产密码、token 和证书不得提交到样例配置;
|
||||
- 单个设备 init 失败时不会进入可用对象表,进程仍可能继续启动;失败条目会保留
|
||||
在 DeviceManager 状态快照中,其中已启用的失败设备会通过 QUIC heartbeat
|
||||
上报,禁用设备不会上报;
|
||||
- 有初始化依赖的设备按配置顺序排列,例如 MotorSystem 在依赖它的 RobotArm 前;
|
||||
- DeviceManager stop 遍历 unordered_map,不能依赖跨设备停止顺序;
|
||||
- DeviceManager 支持并发查询、状态快照和动态注册,但动态设备不会自动补执行
|
||||
已经发生的 `start()`,当前也没有设备移除或完整热插拔生命周期。
|
||||
|
||||
配置细节见 [`../config/README.md`](../config/README.md)。
|
||||
|
||||
## 生命周期约定
|
||||
|
||||
| 接口 | 当前语义 |
|
||||
| --- | --- |
|
||||
| 构造函数 | 保存配置和轻量校验,不启动长期工作线程 |
|
||||
| `init()` | DeviceManager 构造期间对启用设备调用 |
|
||||
| `start()` | 当前 main 不统一调用,由 RPC、媒体或其他 owner 显式触发 |
|
||||
| `startStreaming()` | 获取一个实时流生产租约 |
|
||||
| `stopStreaming()` | 释放租约,最后一份租约停止生产者 |
|
||||
| `stop()` | 完整停止设备,必须幂等 |
|
||||
| `update()` | 当前没有统一 scheduler 自动调用 |
|
||||
| 析构函数 | 回收线程、SDK callback、socket、fd 和 handle |
|
||||
|
||||
实现要求:
|
||||
|
||||
- init/start/stop 的重复调用有明确结果;
|
||||
- stop 和最后一次 stopStreaming 返回前停止所有发布;
|
||||
- 不持有 worker 退出所需的锁执行 join;
|
||||
- SDK callback 不获取停止路径长期持有的控制锁;
|
||||
- getState 使用与状态写入相同的锁;
|
||||
- 含 `std::string`、vector 等状态不能无锁复制;
|
||||
- `healthSnapshot()` 只能读取已经缓存的内存状态,必须线程安全,不能同步访问
|
||||
SDK、网络、串口或设备总线;
|
||||
- 无法提供可信健康状态时返回 `UNKNOWN`,不能用“没有观察到错误”冒充健康;
|
||||
- 析构函数调用安全停止路径;
|
||||
- callback 捕获对象前保证 owner 生命周期。
|
||||
|
||||
并发停止可参考:
|
||||
|
||||
- [`camera/uvc_camera/`](camera/uvc_camera/)
|
||||
- [`camera/hikvision_camera/`](camera/hikvision_camera/)
|
||||
- [`camera/hikvision_camera/tests/`](camera/hikvision_camera/tests/)
|
||||
|
||||
当前 main 收到退出信号只停止 TaskManager,没有显式调用 DeviceManager stop,设备析构仍必须可靠。
|
||||
|
||||
## 摄像头与麦克风实时流
|
||||
|
||||
设备实现抽象流接口后,由 [`../manager/media_source_manager/`](../manager/media_source_manager/) 适配给 gRPC 和 QUIC,不应在设备后端实现两套协议代码。
|
||||
|
||||
当前 Hub 轨道:
|
||||
|
||||
```text
|
||||
<camera-id>/video/color
|
||||
<microphone-id>/audio/main
|
||||
```
|
||||
|
||||
当前 adapter 只把 `StreamFrameData.rgbFrame` 注册为彩色视频轨道;depthFrame 尚未注册为 Hub 深度轨道。
|
||||
|
||||
### Camera 完整编码帧
|
||||
|
||||
每个 access unit 应正确填写:
|
||||
|
||||
- `rgbFrame`
|
||||
- `codec`:H.264 或 H.265
|
||||
- `width`、`height`、`fps`
|
||||
- `bKey`
|
||||
- `stream_epoch`
|
||||
- `sequence`
|
||||
- `capture_monotonic_ns`
|
||||
- `capture_utc_ns`
|
||||
- `source_timestamp`:设备 SDK 提供的原始时间戳;单位和时钟域由设备定义,未知
|
||||
时保持 0,不能直接当成 Unix 时间;
|
||||
- `source_frame_number`:设备 SDK 提供的原始帧号,未知时保持 0;
|
||||
- `pts`、`dts`
|
||||
- `time_base_num`、`time_base_den`
|
||||
- `duration`
|
||||
- `discontinuity`
|
||||
- `codec_config_generation`
|
||||
- `codec_config`
|
||||
|
||||
H.264/H.265 后端必须识别关键帧,并尽量实现 `requestKeyFrame()`。
|
||||
|
||||
Hikvision 后端优先采用 SDK 回调中的有效帧率,并保留 SDK 的 64 位原始时间戳和帧号;
|
||||
SDK 帧率无效时才回退到配置的 `fps`。这些字段用于跨层诊断,设备层不应在不了解
|
||||
SDK 时钟语义时擅自换算。
|
||||
|
||||
### Microphone 完整音频包
|
||||
|
||||
应正确填写:
|
||||
|
||||
- `data`
|
||||
- `sample_rate`
|
||||
- `channels`
|
||||
- `format` 和 `codec`
|
||||
- `nb_samples`
|
||||
- sequence、时间戳、time base、duration
|
||||
- stream epoch、discontinuity 和 codec generation
|
||||
|
||||
### 生产者重启
|
||||
|
||||
采集/编码生产者真正停止并重新启动时:
|
||||
|
||||
1. 增加 `stream_epoch`;
|
||||
2. 将 source sequence 重置为 0;
|
||||
3. 增加 `codec_config_generation`;
|
||||
4. 确保后续帧携带完整的新编码元数据;
|
||||
5. 将第一帧标记为 discontinuity;
|
||||
6. 视频从关键帧恢复输出。
|
||||
|
||||
设备后端不直接发布 `TrackDescriptor`。`device_media_source_adapter.cpp` 会根据帧元数据生成或更新 descriptor。
|
||||
|
||||
### 运行期编码配置变化
|
||||
|
||||
编码器没有重启、只在同一 stream epoch 内改变分辨率、codec config 等参数时:
|
||||
|
||||
1. 保持 `stream_epoch` 不变;
|
||||
2. 保持 sequence 连续递增;
|
||||
3. 增加 `codec_config_generation`,或让其他描述字段反映变化;
|
||||
4. 在后续帧中携带新元数据;
|
||||
5. 标记 discontinuity;
|
||||
6. H.264/H.265 从新的关键帧恢复。
|
||||
|
||||
adapter 检测到描述变化后创建新 descriptor,设备后端不要自行维护协议侧 descriptor 状态。
|
||||
|
||||
## 设备侧环形队列安全
|
||||
|
||||
现有设备后端多使用 `SPMCRingBuffer<T>`:
|
||||
|
||||
- 只允许一个逻辑生产者;
|
||||
- 每个消费者独立持有读游标;
|
||||
- 同一读游标不能跨线程并发访问;
|
||||
- 不对同一路读取混用无参 `pop()` 和带游标 `pop(index)`;
|
||||
- 需要最新帧时使用 `getLatest(index)`;
|
||||
- 不要先取 head 再分两步读取,避免检查/读取竞态;
|
||||
- 满队列覆盖旧数据是实时媒体的预期行为;
|
||||
- `waitEncodedFrame()` 必须有有限 timeout,不能永久阻塞。
|
||||
|
||||
MediaSourceManager Subscription 同样是单消费者对象,不同协议或客户端必须各自订阅。
|
||||
|
||||
发布后的 `MediaFrame`、`TrackDescriptor` 和 payload 不可再修改。
|
||||
|
||||
## 测试要求
|
||||
|
||||
至少覆盖:
|
||||
|
||||
- 配置缺失、非法参数和 ID 不一致;
|
||||
- Factory 选择正确后端;
|
||||
- init/start/stop 重复执行;
|
||||
- init 失败后无残留线程和句柄;
|
||||
- stop 与 SDK callback 并发;
|
||||
- 最后一个流租约释放后不再发布;
|
||||
- 多消费者使用独立游标;
|
||||
- 环形队列覆盖和丢帧;
|
||||
- epoch、sequence、关键帧和 codec generation;
|
||||
- 设备断开、超时和重连。
|
||||
|
||||
无硬件参考测试:
|
||||
|
||||
- [`camera/hikvision_camera/tests/hikvision_camera_callback_test.cpp`](camera/hikvision_camera/tests/hikvision_camera_callback_test.cpp)
|
||||
|
||||
```bash
|
||||
cmake -S . -B build \
|
||||
-DCMVR_ARCH=x86 \
|
||||
-DBUILD_TESTING=ON
|
||||
|
||||
cmake --build build -j"$(nproc)"
|
||||
|
||||
ctest \
|
||||
--test-dir build \
|
||||
-R '^hikvision_camera_callback_test$' \
|
||||
--output-on-failure
|
||||
```
|
||||
|
||||
新测试必须在 `BUILD_TESTING` 下使用 `add_test()` 登记。只创建 executable 不会自动被 CTest 执行。
|
||||
|
||||
## 提交检查
|
||||
|
||||
- [ ] 抽象接口没有厂商 SDK 类型
|
||||
- [ ] manager、外层配置和 backend ID 一致
|
||||
- [ ] 新硬件配置默认关闭
|
||||
- [ ] 生命周期支持重复调用
|
||||
- [ ] stop 是同步发布屏障
|
||||
- [ ] 状态读写使用同一把锁
|
||||
- [ ] 每个实时流只有一个生产者
|
||||
- [ ] 每个消费者使用独立游标
|
||||
- [ ] 时间戳、sequence 和编码元数据完整
|
||||
- [ ] Factory 和类别 CMake 均已接入
|
||||
- [ ] 厂商运行库有安装规则
|
||||
- [ ] 有无真实硬件的自动测试
|
||||
- [ ] 平台能力变化已评估 Proto 和 service
|
||||
@ -34,6 +34,23 @@ namespace cmvr::device {
|
||||
virtual bool start() { return true; }
|
||||
virtual bool stop() { return true; }
|
||||
virtual bool update() { return true; }
|
||||
virtual bool executeJsonCommand(const std::string& request_json, std::string& response_json) {
|
||||
response_json = R"({"success":false,"error_message":"JSON command unsupported"})";
|
||||
return false;
|
||||
}
|
||||
|
||||
// This hook is sampled by DeviceManager while building heartbeats. It
|
||||
// must be thread-safe and complete in bounded time while only copying
|
||||
// in-memory state through atomics or a dedicated short-held state
|
||||
// lock. Implementations must not perform device I/O, network requests,
|
||||
// or wait on a lifecycle lock held across such I/O.
|
||||
//
|
||||
// The method is intentionally non-const because several legacy device
|
||||
// categories expose non-const state getters. The returned object is a
|
||||
// value and does not expose the device lifetime to callers.
|
||||
virtual DeviceHealthSnapshot healthSnapshot() {
|
||||
return {};
|
||||
}
|
||||
|
||||
protected:
|
||||
std::string id_; // 设备名称
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
add_subdirectory(my_agv)
|
||||
add_subdirectory(seer_robokit)
|
||||
|
||||
add_library(agv INTERFACE)
|
||||
|
||||
@ -7,6 +8,7 @@ target_include_directories(agv INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(agv
|
||||
INTERFACE
|
||||
cmvr_es::device::my_agv
|
||||
cmvr_es::device::seer_robokit_agv
|
||||
cmvr_es::proto
|
||||
)
|
||||
|
||||
|
||||
@ -6,32 +6,300 @@
|
||||
#define CMVR_ES_ABSTRACT_AGV_H
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "common/types/agv/agv_types.h"
|
||||
#include "devices/abstract_device.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
enum class AgvActionKind {
|
||||
NavigateToPose,
|
||||
NavigateToStation,
|
||||
FollowPath,
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AGV/移动底盘设备抽象基类。
|
||||
*
|
||||
* 该接口只描述通用 AGV 能力。控制器特有的请求/响应字段应放在具体
|
||||
* 驱动类中;当公共 API 需要扩展点时,可通过 AgvAdapterParams 传递。
|
||||
*/
|
||||
class AbstractAGV : public AbstractDevice {
|
||||
public:
|
||||
AbstractAGV() = default;
|
||||
~AbstractAGV() override = default;
|
||||
|
||||
DeviceKind kind() const noexcept override { return DeviceKind::AGV; }
|
||||
virtual bool getState(AGVState &state) { return true; }
|
||||
|
||||
// navigation
|
||||
virtual bool eStop() { return true; }
|
||||
virtual bool goHome() { return true; }
|
||||
virtual bool moveto(math::Pose2d &location, double speed_ratio) { return true; }
|
||||
virtual bool setVelocity(math::Vec3 linear, math::Vec3 angular) { return true; }
|
||||
|
||||
// map
|
||||
virtual bool initMap(float resolution, int width, int height) { return true; }
|
||||
virtual bool updateMap() { return true; }
|
||||
virtual bool saveMap(const std::string& file_path) { return true; }
|
||||
virtual bool loadMap(const std::string& file_path) { return true; }
|
||||
|
||||
protected:
|
||||
AGVState state_;
|
||||
};
|
||||
/**
|
||||
* @brief Whether this backend provides terminal-state and stopped-motion
|
||||
* confirmation plus bounded cancellation suitable for synchronous
|
||||
* Action execution.
|
||||
*/
|
||||
virtual bool supportsSynchronousAction(AgvActionKind) const noexcept
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 获取 AGV 运行状态快照。
|
||||
*/
|
||||
virtual AgvRuntimeState runtimeState() const { return {}; }
|
||||
|
||||
/**
|
||||
* @brief 获取当前导航任务状态。
|
||||
*/
|
||||
virtual AgvNavigationStatus navigationStatus() const { return {}; }
|
||||
|
||||
/**
|
||||
* @brief 触发 AGV 急停行为。
|
||||
*/
|
||||
virtual AgvResult emergencyStop()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "emergencyStop not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 清除可恢复的 AGV 故障或告警。
|
||||
*/
|
||||
virtual AgvResult clearFault()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "clearFault not implemented");
|
||||
}
|
||||
|
||||
|
||||
virtual AgvResult relocalize(const math::Pose2d& pose)
|
||||
{
|
||||
(void)pose;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand,"relocalize not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 发起到世界/地图位姿的导航任务。
|
||||
*/
|
||||
virtual AgvResult navigateToPose(
|
||||
const math::Pose2d& pose,
|
||||
const AgvMotionOptions& options = {},
|
||||
const AgvAdapterParams& adapter_params = AgvAdapterParams{})
|
||||
{
|
||||
(void)pose;
|
||||
(void)options;
|
||||
(void)adapter_params;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "navigateToPose not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 发起到指定地图站点的导航任务。
|
||||
*/
|
||||
virtual AgvResult navigateToStation(
|
||||
const std::string& station_id,
|
||||
const AgvMotionOptions& options = {},
|
||||
const AgvAdapterParams& adapter_params = AgvAdapterParams{})
|
||||
{
|
||||
(void)station_id;
|
||||
(void)options;
|
||||
(void)adapter_params;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "navigateToStation not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 发起显式站点到站点路径导航任务。
|
||||
*/
|
||||
virtual AgvResult followPath(
|
||||
const std::vector<AgvPathSegment>& path)
|
||||
{
|
||||
(void)path;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "followPath not implemented");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief 按指定速度执行固定距离平移。
|
||||
*
|
||||
* 返回成功表示控制器已经接受命令,不表示运动已经完成。
|
||||
*/
|
||||
virtual AgvResult translate(const AgvTranslation& translation)
|
||||
{
|
||||
(void)translation;
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::UnsupportedCommand,
|
||||
"translate not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 发起显式站点到站点路径导航任务,并指定同步/异步选项。
|
||||
*
|
||||
* 保留单参数虚函数以兼容已有派生类;旧实现会由本重载转发。
|
||||
*/
|
||||
virtual AgvResult followPath(
|
||||
const std::vector<AgvPathSegment>& path,
|
||||
const AgvMotionOptions& options)
|
||||
{
|
||||
(void)options;
|
||||
return followPath(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 暂停当前导航任务,如果设备支持。
|
||||
*/
|
||||
virtual AgvResult pauseNavigation()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "pauseNavigation not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 恢复已暂停的导航任务,如果设备支持。
|
||||
*/
|
||||
virtual AgvResult resumeNavigation()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "resumeNavigation not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 取消当前导航任务,如果设备支持。
|
||||
*/
|
||||
virtual AgvResult cancelNavigation()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "cancelNavigation not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 向 AGV 下发低层速度控制指令。
|
||||
*
|
||||
* 该接口不同于导航命令。具体实现应明确速度控制在导航过程中是中断
|
||||
* 导航、与导航共存,还是被拒绝执行。
|
||||
*/
|
||||
virtual AgvResult setVelocity(const AgvVelocity& velocity)
|
||||
{
|
||||
(void)velocity;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "setVelocity not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 通过下发零速度停止低层速度控制。
|
||||
*
|
||||
* 该接口不表示取消正在执行的导航任务;取消导航请使用
|
||||
* cancelNavigation()。
|
||||
*/
|
||||
virtual AgvResult stopVelocityControl()
|
||||
{
|
||||
return setVelocity(AgvVelocity{});
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 确认 AGV 已进入可安全释放控制权的停止状态。
|
||||
*
|
||||
* 该接口只在导航任务已终止且底盘速度经过连续采样确认为零后返回
|
||||
* 成功;仅收到取消、停止或零速度命令的应答不构成成功。
|
||||
*/
|
||||
virtual AgvResult confirmMotionStopped()
|
||||
{
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::UnsupportedCommand,
|
||||
"confirmMotionStopped not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 查询 AGV 可用地图名称列表。
|
||||
*/
|
||||
virtual AgvResult listMaps(std::vector<std::string>& maps) const
|
||||
{
|
||||
(void)maps;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "listMaps not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 查询当前活动地图中的站点列表。
|
||||
*/
|
||||
virtual AgvResult listStations(std::vector<AgvStation>& stations) const
|
||||
{
|
||||
(void)stations;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "listStations not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 切换当前活动地图。
|
||||
*/
|
||||
virtual AgvResult switchMap(const std::string& map_name)
|
||||
{
|
||||
(void)map_name;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "switchMap not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按名称上传或替换地图。
|
||||
*/
|
||||
virtual AgvResult uploadMap(const std::string& map_name, const std::string& content)
|
||||
{
|
||||
(void)map_name;
|
||||
(void)content;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "uploadMap not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 按名称下载地图内容。
|
||||
*/
|
||||
virtual AgvResult downloadMap(const std::string& map_name, std::string& content) const
|
||||
{
|
||||
(void)map_name;
|
||||
(void)content;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "downloadMap not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 开始扫图/建图。
|
||||
*/
|
||||
virtual AgvResult startMapping(const AgvMappingOptions& options = {})
|
||||
{
|
||||
(void)options;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "startMapping not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 从指定下标开始获取厂商原始扫图数据。
|
||||
*
|
||||
* 该接口主要保留给具体驱动内部使用。对外 gRPC 地图流应优先使用
|
||||
* getUnifiedMapUpdate(),避免把厂商文件格式暴露给上位机。
|
||||
*/
|
||||
virtual AgvResult getMappingData(int start_index, AgvMappingData& data) const
|
||||
{
|
||||
(void)start_index;
|
||||
(void)data;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "getMappingData not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 获取统一地图更新。
|
||||
*
|
||||
* after_sequence 为 0 时通常返回最近可用的全量快照;大于 0 时返回
|
||||
* 指定序号之后的下一条更新。如果当前没有新地图,具体实现可在
|
||||
* options.wait_timeout_ms 内等待后台更新线程写入缓存。
|
||||
*/
|
||||
virtual AgvResult getUnifiedMapUpdate(
|
||||
std::uint64_t after_sequence,
|
||||
const AgvMapStreamOptions& options,
|
||||
AgvUnifiedMapUpdate& update) const
|
||||
{
|
||||
(void)after_sequence;
|
||||
(void)options;
|
||||
(void)update;
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "getUnifiedMapUpdate not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 停止扫图/建图。
|
||||
*/
|
||||
virtual AgvResult stopMapping()
|
||||
{
|
||||
return AgvResult::failure(AgvErrorCode::UnsupportedCommand, "stopMapping not implemented");
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_ABSTRACT_AGV_H
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "devices/agv/abstract_agv.h"
|
||||
#include "devices/agv/my_agv/include/my_agv.h"
|
||||
#include "seer_robokit_agv.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
@ -30,6 +31,16 @@ public:
|
||||
backend.set_id(cfg.id());
|
||||
return std::make_shared<MyAgv>(backend);
|
||||
}
|
||||
case config::AGVDeviceConfig::kSeerRobokitAgv:
|
||||
{
|
||||
if (!cfg.seer_robokit_agv().id().empty() && cfg.seer_robokit_agv().id() != cfg.id()) {
|
||||
CMVR_LOG(ERROR) << "[AGVFactory]: AGV id does not match backend id: " << cfg.id();
|
||||
return nullptr;
|
||||
}
|
||||
auto backend = cfg.seer_robokit_agv();
|
||||
backend.set_id(cfg.id());
|
||||
return std::make_shared<SeerRobokitAgv>(backend);
|
||||
}
|
||||
|
||||
case config::AGVDeviceConfig::BACKEND_NOT_SET:
|
||||
default:
|
||||
|
||||
@ -20,15 +20,13 @@ public:
|
||||
bool stop() override;
|
||||
bool update() override;
|
||||
|
||||
bool getState(AGVState& state) override;
|
||||
bool eStop() override;
|
||||
bool goHome() override;
|
||||
bool moveto(math::Pose2d& location, double speed_ratio) override;
|
||||
bool setVelocity(math::Vec3 linear, math::Vec3 angular) override;
|
||||
bool initMap(float resolution, int width, int height) override;
|
||||
bool updateMap() override;
|
||||
bool saveMap(const std::string& file_path) override;
|
||||
bool loadMap(const std::string& file_path) override;
|
||||
AgvRuntimeState runtimeState() const override;
|
||||
AgvResult emergencyStop() override;
|
||||
AgvResult navigateToPose(
|
||||
const math::Pose2d& pose,
|
||||
const AgvMotionOptions& options = {},
|
||||
const AgvAdapterParams& adapter_params = AgvAdapterParams{}) override;
|
||||
AgvResult setVelocity(const AgvVelocity& velocity) override;
|
||||
|
||||
private:
|
||||
config::MyAgvConfig config_;
|
||||
|
||||
@ -27,49 +27,27 @@ bool MyAgv::update()
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::getState(AGVState&)
|
||||
AgvRuntimeState MyAgv::runtimeState() const
|
||||
{
|
||||
return true;
|
||||
return {};
|
||||
}
|
||||
|
||||
bool MyAgv::eStop()
|
||||
AgvResult MyAgv::emergencyStop()
|
||||
{
|
||||
return true;
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
bool MyAgv::goHome()
|
||||
AgvResult MyAgv::navigateToPose(
|
||||
const math::Pose2d&,
|
||||
const AgvMotionOptions&,
|
||||
const AgvAdapterParams&)
|
||||
{
|
||||
return true;
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
bool MyAgv::moveto(math::Pose2d&, double)
|
||||
AgvResult MyAgv::setVelocity(const AgvVelocity&)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::setVelocity(math::Vec3, math::Vec3)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::initMap(float, int, int)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::updateMap()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::saveMap(const std::string&)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MyAgv::loadMap(const std::string&)
|
||||
{
|
||||
return true;
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
29
cmvr-es/devices/agv/seer_robokit/CMakeLists.txt
Normal file
29
cmvr-es/devices/agv/seer_robokit/CMakeLists.txt
Normal file
@ -0,0 +1,29 @@
|
||||
add_library(seer_robokit_agv SHARED
|
||||
src/seer_robokit_agv.cpp
|
||||
src/seer_robokit_transport.cpp
|
||||
src/seer_robokit_control.cpp
|
||||
src/seer_robokit_status.cpp
|
||||
src/seer_robokit_navigation.cpp
|
||||
src/seer_robokit_navigation_wait.cpp
|
||||
src/seer_robokit_map.cpp
|
||||
include/seer_robokit_agv.h
|
||||
include/seer_robokit_protocol.h
|
||||
include/seer_robokit_utils.h
|
||||
include/seer_robokit_navigation_utils.h
|
||||
include/seer_robokit_pgv_utils.h
|
||||
)
|
||||
|
||||
target_include_directories(seer_robokit_agv
|
||||
PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
${PROJECT_SOURCE_DIR}/cmvr-es
|
||||
)
|
||||
|
||||
target_link_libraries(seer_robokit_agv
|
||||
PUBLIC
|
||||
cmvr_es::proto
|
||||
jsoncpp
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::seer_robokit_agv ALIAS seer_robokit_agv)
|
||||
install(TARGETS seer_robokit_agv LIBRARY DESTINATION lib)
|
||||
375
cmvr-es/devices/agv/seer_robokit/README.md
Normal file
375
cmvr-es/devices/agv/seer_robokit/README.md
Normal file
@ -0,0 +1,375 @@
|
||||
# 仙工 SEER Robokit AGV 适配器
|
||||
|
||||
`SeerRobokitAgv` 将仙工 SEER Robokit TCP/IP API 适配为 CMVR 的通用
|
||||
`AbstractAGV`/`cmvr.api.AgvService`。厂商命令号、端口、抢占控制权、状态轮询、
|
||||
地图格式转换和错误码解析都封装在本目录内。
|
||||
|
||||
本项目现场使用的控制器型号仍是 SRC1100,所以设备实例 ID 保持为
|
||||
`src1100`;它只用于配置关联和 gRPC 路由,不再作为驱动实现名称。后端配置字段
|
||||
使用 `seer_robokit_agv`,目录、类、库和测试统一使用 `seer_robokit` /
|
||||
`SeerRobokitAgv` 命名。
|
||||
|
||||
从旧版本升级时,外部部署配置必须同步使用 `seer_robokit_agv { ... }`,并把
|
||||
配置路径更新为 `devices/agv/seer_robokit.pb.txt`;设备实例 ID 保持不变。程序、
|
||||
外部配置和部署脚本需要原子升级,不能把旧字段或旧路径与新二进制混用。
|
||||
|
||||
返回 [Devices 模块指南](../../README.md) 或 [项目总览](../../../../README.md)。
|
||||
|
||||
## 代码与配置
|
||||
|
||||
所有驱动头文件统一放在 `include/`,实现文件统一放在 `src/`;测试源码独立放在
|
||||
`tests/`。除 `seer_robokit_agv.h` 外,其余头文件均为驱动内部实现细节。
|
||||
|
||||
- 公共类声明:[`include/seer_robokit_agv.h`](include/seer_robokit_agv.h)
|
||||
- 导航轮询工具:
|
||||
[`include/seer_robokit_navigation_utils.h`](include/seer_robokit_navigation_utils.h)
|
||||
- PGV 参数转换:
|
||||
[`include/seer_robokit_pgv_utils.h`](include/seer_robokit_pgv_utils.h)
|
||||
- 协议常量:[`include/seer_robokit_protocol.h`](include/seer_robokit_protocol.h)
|
||||
- 通用解析工具:[`include/seer_robokit_utils.h`](include/seer_robokit_utils.h)
|
||||
- 生命周期和连接:[`src/seer_robokit_agv.cpp`](src/seer_robokit_agv.cpp)
|
||||
- TCP 帧与收发:[`src/seer_robokit_transport.cpp`](src/seer_robokit_transport.cpp)
|
||||
- 控制权与受控命令:[`src/seer_robokit_control.cpp`](src/seer_robokit_control.cpp)
|
||||
- 状态与推送缓存:[`src/seer_robokit_status.cpp`](src/seer_robokit_status.cpp)
|
||||
- 导航命令:[`src/seer_robokit_navigation.cpp`](src/seer_robokit_navigation.cpp)
|
||||
- 阻塞等待与停车确认:
|
||||
[`src/seer_robokit_navigation_wait.cpp`](src/seer_robokit_navigation_wait.cpp)
|
||||
- 地图和建图:[`src/seer_robokit_map.cpp`](src/seer_robokit_map.cpp)
|
||||
- 设备配置:
|
||||
[`../../../config/devices/agv/seer_robokit.pb.txt`](../../../config/devices/agv/seer_robokit.pb.txt)
|
||||
- DeviceManager 配置:
|
||||
[`../../../config/manager/device_manager.pb.txt`](../../../config/manager/device_manager.pb.txt)
|
||||
- gRPC API:
|
||||
[`../../../../protos/cmvr/api/agv_service.proto`](../../../../protos/cmvr/api/agv_service.proto)、
|
||||
[`../../../../protos/cmvr/api/agv_command.proto`](../../../../protos/cmvr/api/agv_command.proto)、
|
||||
[`../../../../protos/cmvr/api/agv_utils.proto`](../../../../protos/cmvr/api/agv_utils.proto)
|
||||
|
||||
## 配置和启动
|
||||
|
||||
现场配置至少需要修改控制器 IP;端口通常保持仙工默认值:
|
||||
|
||||
```textproto
|
||||
agv {
|
||||
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
|
||||
recv_timeout_ms: 1000
|
||||
control_nick_name: "cmvr-es"
|
||||
enable_state_push: true
|
||||
state_push_interval_ms: 200
|
||||
enable_map_update: true
|
||||
map_update_interval_ms: 1000
|
||||
map_update_history_size: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
还要在 `device_manager.pb.txt` 中确认同一个设备 id,并在完成现场安全检查后把
|
||||
`enable` 改为 `true`。源码默认配置故意保持关闭。
|
||||
|
||||
```textproto
|
||||
devices {
|
||||
id: "src1100"
|
||||
type: DEVICE_TYPE_AGV
|
||||
config_file: "devices/agv/seer_robokit.pb.txt"
|
||||
enable: true
|
||||
}
|
||||
```
|
||||
|
||||
构建、安装并启动:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j2
|
||||
cmake --install build
|
||||
./output/bin/cmvr_es
|
||||
```
|
||||
|
||||
`output/bin/cmvr_es` 默认读取 `output/bin/config/`。修改源码配置后需要重新安装,
|
||||
或通过程序支持的外部配置入口启动,不能只修改源码文件后继续使用旧的
|
||||
`output/` 配置。
|
||||
|
||||
## 控制器端口和命令
|
||||
|
||||
| 端口 | 主要用途 | 当前使用的命令 |
|
||||
| --- | --- | --- |
|
||||
| `19204` | 状态、站点、地图和建图文件 | `1004`、`1007`、`1020`、`1101`、`1110`、`1300`、`1301`、`1780`、`1800` |
|
||||
| `19205` | 底盘控制 | `2000`、`2010`、`2022` |
|
||||
| `19206` | 导航任务 | `3001`、`3002`、`3003`、`3051`、`3066`、`3067` |
|
||||
| `19207` | 控制权、清错、地图上传下载 | `4005`、`4009`、`4010`、`4011` |
|
||||
| `19210` | 开始/停止建图 | `6100`、`6101` |
|
||||
| `19301` | 机器人状态推送 | `9300`/`19300` 配置,`19301` 推送 |
|
||||
|
||||
所有会改变机器人或控制器状态的调用都在 SEER Robokit 子类内部先通过 `4005`
|
||||
抢权,负载为稳定的 `nick_name`,成功后才发送实际命令。普通命令集中走
|
||||
`sendControlledCommand_`;`emergencyStop` 为保证 `2000` 和导航取消之间不被
|
||||
插入其他命令,会在同一个控制序列锁内只抢一次权。只读查询不抢权。不要在
|
||||
gRPC 客户端另做一套租约逻辑。
|
||||
|
||||
## gRPC 接口概览
|
||||
|
||||
默认示例端点为 `127.0.0.1:50052`;远程部署时替换为 CMVR 服务所在主机,
|
||||
不是 SEER Robokit 原生 TCP 端口。
|
||||
|
||||
| gRPC 方法 | SEER Robokit 行为 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `getRuntimeState` | 推送缓存,缺失时查询 `1004/1007/1300` | 只读 |
|
||||
| `getNavigationStatus` | 跟踪任务查询 `1110`,无精确上下文时回退 `1020` | 只读;同步等待另用 `1101` 确认停车 |
|
||||
| `emergencyStop` | `2000`,再执行 `3003` 或 `3067` | 软件停止,不替代硬件急停 |
|
||||
| `clearFault` | `4009` | 抢权后发送无请求体命令,清除可恢复故障 |
|
||||
| `navigateToPose` | `3051` + `freeGo` | 地图绝对位姿,仅双轮差速底盘 |
|
||||
| `navigateToStation` | `3051` | 站点路径导航;PGV 二次定位也使用此方法 |
|
||||
| `followPath` | `3066` | 仙工“指定路径导航”,与 `3051` 不同 |
|
||||
| `pauseNavigation` / `resumeNavigation` | `3001` / `3002` | 导航控制 |
|
||||
| `cancelNavigation` | `3003`,路径队列使用 `3067` | 取消当前跟踪任务 |
|
||||
| `setVelocity` / `stopVelocityControl` | `2010` | 车体速度;停止时发送全零速度 |
|
||||
| `listMaps` / `listStations` | `1300` / `1301` | 只读 |
|
||||
| `switchMap` | `2022` | 会改变定位所用地图 |
|
||||
| `uploadMap` / `downloadMap` | `4010` / `4011` | 上传会抢权,下载只读 |
|
||||
| `startMapping` / `stopMapping` | `6100` / `6101` | 建图控制 |
|
||||
| `streamMap` | `1780/1800` 加内部解析和缓存 | 对外发送统一 2D/3D 地图,不暴露 `.smap` 原始格式 |
|
||||
|
||||
查询运行状态:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{"header":{"deviceId":"src1100"}}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/getRuntimeState
|
||||
```
|
||||
|
||||
查询导航状态:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{"header":{"deviceId":"src1100"}}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/getNavigationStatus
|
||||
```
|
||||
|
||||
列出地图和当前地图站点:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{"header":{"deviceId":"src1100"}}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/listMaps
|
||||
|
||||
grpcurl -plaintext \
|
||||
-d '{"header":{"deviceId":"src1100"}}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/listStations
|
||||
```
|
||||
|
||||
## 导航的同步语义
|
||||
|
||||
`navigateToPose`、`navigateToStation` 和 `followPath` 默认同步阻塞。控制器接受
|
||||
命令后,适配器继续轮询精确任务状态,并结合 `1101` 状态确认底盘已经停车;
|
||||
到达、失败、取消、遇障停止或超时后才返回。`waitTimeoutMs` 为 `0` 时使用
|
||||
适配器默认值,当前为 10 分钟;`pollIntervalMs` 为 `0` 时当前使用 200 ms。
|
||||
|
||||
连续观察到障碍阻挡且底盘已经停止后,适配器会主动取消该导航;清理结果不明确
|
||||
时还可能发送软件停止。任务不会在障碍消失后由本次调用自动恢复。等待超时、
|
||||
RPC cancel 和 deadline 到期也会进入安全取消及停车确认,因此函数返回时间可能
|
||||
晚于最初发现障碍或取消请求的时刻。
|
||||
|
||||
调用方的 gRPC deadline 必须大于预计行程时间和 `waitTimeoutMs`。RPC 被取消或
|
||||
deadline 到期时,适配器会进入安全取消/停车确认流程。显式设置
|
||||
`"asynchronous":true` 后不会等待任务终态:站点导航和指定路径导航在控制器
|
||||
接受后返回;自由导航仍会做最长约 1.5 秒的启动确认。异步成功不代表已经到点。
|
||||
|
||||
`AgvMotionOptions` 中,SEER Robokit 的 `3051` 导航当前支持:
|
||||
|
||||
| gRPC 字段 | 控制器字段 | 单位 |
|
||||
| --- | --- | --- |
|
||||
| `maxSpeed` | `max_speed` | m/s |
|
||||
| `maxAngularSpeed` | `max_wspeed` | rad/s |
|
||||
| `maxAcceleration` | `max_acc` | m/s² |
|
||||
| `maxAngularAcceleration` | `max_wacc` | rad/s² |
|
||||
| `reachDistance` | `reach_dist` | m |
|
||||
| `reachAngle` | `reach_angle` | rad |
|
||||
|
||||
`asynchronous`、`waitTimeoutMs` 和 `pollIntervalMs` 由适配器本地执行。
|
||||
`speedRatio` 当前没有对应的 SEER Robokit 序列化字段。`followPath` 的运动选项当前只
|
||||
控制同步/异步等待、超时和轮询;在没有确认 `3066` 的速度字段前,不会猜测性地
|
||||
写入每个路径段。
|
||||
|
||||
## 固定路径导航的 PGV 二次定位
|
||||
|
||||
仙工文档 [“路径导航 / 2. 固定路径导航 PGV 二次定位调整”](https://seer-group.feishu.cn/wiki/Q26SwaNoGisuLWk2vCxcPfVWn2e)
|
||||
说明 PGV 参数是 `3051 / robot_task_gotarget_req` 的顶层可选字段。因此在 CMVR
|
||||
中应调用 `navigateToStation`,不是 `followPath`。后者对应另一条
|
||||
`3066 / 指定路径导航` 协议,现有仙工资料和仓库历史都没有证明 `3066` 支持
|
||||
PGV 字段。
|
||||
|
||||
PGV 参数通过 `adapterParams.values` 传入。protobuf map 的值是字符串,
|
||||
SEER Robokit 适配器会在任何状态查询、抢权和运动命令之前完成校验,再转换为控制器
|
||||
要求的 JSON `bool`/`number`:
|
||||
|
||||
| `adapterParams.values` 键 | 输出 JSON 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `use_pgv` | `bool` | 使用上视 PGV |
|
||||
| `use_down_pgv` | `bool` | 使用下视 PGV |
|
||||
| `pgv_adjust_dist` | `number` | 最大调整半径,必须为有限非负数;用于仙工第 3/4 种调整方式 |
|
||||
| `pgv_adjust_cx` | `number` | 调整范围圆心在二维码坐标系下的 X 偏移;用于第 4 种方式 |
|
||||
| `pgv_adjust_cy` | `number` | 调整范围圆心在二维码坐标系下的 Y 偏移;用于第 4 种方式 |
|
||||
| `pgv_x_adjust` | `number` | 仅调整小车 X 方向误差;用于第 2 种方式 |
|
||||
|
||||
所有数字都必须是完整、有限的数字字符串;偏移量允许正负。适配器不臆造
|
||||
调整半径上限,也不假定上视和下视一定互斥,这些约束应由实际 PGV 安装、标定和
|
||||
当前控制器版本确定。显式的 `"false"` 和 `"0"` 仍会作为原生布尔值和数值
|
||||
发给控制器;没有给出的字段不会发送。第 2/3/4 种方式由控制器和站点配置决定,
|
||||
本接口只传递与所选方式匹配的调整参数。
|
||||
|
||||
一旦请求中出现任意 PGV 键,适配器只允许同时出现 `source_id`、`task_id` 和
|
||||
上述 PGV 字段;`operation`、`jack_height`、脚本名或未知扩展字段都会在状态
|
||||
查询和抢权前被拒绝,避免一次 PGV 导航意外夹带顶升、货叉、IO 或脚本动作。
|
||||
没有 PGV 键的既有站点导航扩展语义保持不变。
|
||||
|
||||
上视 PGV 示例。该命令会让机器人导航到 `AP1`,只能在确认地图、站点、PGV
|
||||
标定、行驶区域和急停人员后执行:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"header":{"deviceId":"src1100"},
|
||||
"stationId":"AP1",
|
||||
"options":{
|
||||
"maxSpeed":0.15,
|
||||
"maxAcceleration":0.15,
|
||||
"asynchronous":false,
|
||||
"waitTimeoutMs":300000,
|
||||
"pollIntervalMs":200
|
||||
},
|
||||
"adapterParams":{"values":{
|
||||
"use_pgv":"true",
|
||||
"pgv_adjust_dist":"0.3",
|
||||
"pgv_adjust_cx":"-0.3",
|
||||
"pgv_adjust_cy":"0"
|
||||
}}
|
||||
}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/navigateToStation
|
||||
```
|
||||
|
||||
下视 PGV 使用同一接口,把 `use_down_pgv` 设为字符串 `"true"`;其他调整
|
||||
字段是否需要传入取决于现场定位方案。如果控制器版本要求明确起点,可在同一个
|
||||
map 中增加 `"source_id":"实际起点站点"`;默认起点为 `SELF_POSITION`。
|
||||
|
||||
仙工在线文档当前有两处拼写不一致:
|
||||
|
||||
- 代码块出现了损坏字段 `pgv_adjustuse_pgv_dist`;适配器会拒绝它,正确字段是
|
||||
`pgv_adjust_dist`;
|
||||
- 表格写成 `pgv_ajdust_cy`,而示例和仓库旧版序列化代码使用
|
||||
`pgv_adjust_cy`。适配器兼容接收前者,但只向控制器输出规范字段
|
||||
`pgv_adjust_cy`;两个拼写同时出现会因歧义被拒绝。
|
||||
|
||||
C++ 调用同样复用通用扩展参数:
|
||||
|
||||
```cpp
|
||||
cmvr::device::AgvMotionOptions options;
|
||||
options.max_speed = 0.15;
|
||||
options.max_acceleration = 0.15;
|
||||
|
||||
cmvr::device::AgvAdapterParams adapter;
|
||||
adapter.values["use_pgv"] = "true";
|
||||
adapter.values["pgv_adjust_dist"] = "0.3";
|
||||
adapter.values["pgv_adjust_cx"] = "-0.3";
|
||||
adapter.values["pgv_adjust_cy"] = "0";
|
||||
|
||||
const auto result = agv.navigateToStation("AP1", options, adapter);
|
||||
```
|
||||
|
||||
## 其他导航和控制示例
|
||||
|
||||
自由导航使用地图绝对坐标,不是“相对当前位置移动多少米”。示例只展示请求
|
||||
结构,发送前必须读取当前位姿并确认目标在同一地图的安全区域:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"header":{"deviceId":"src1100"},
|
||||
"pose":{"x":1.0,"y":0.0,"theta":0.0},
|
||||
"options":{"maxSpeed":0.15,"maxAcceleration":0.15}
|
||||
}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/navigateToPose
|
||||
```
|
||||
|
||||
显式站点路径使用 `3066`:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"header":{"deviceId":"src1100"},
|
||||
"path":[
|
||||
{"sourceStation":"LM1","targetStation":"LM2"},
|
||||
{"sourceStation":"LM2","targetStation":"AP1"}
|
||||
]
|
||||
}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/followPath
|
||||
```
|
||||
|
||||
暂停、继续和取消的请求体直接是 `CommandHeader.Request`,没有外层 `header`:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext -d '{"deviceId":"src1100"}' \
|
||||
127.0.0.1:50052 cmvr.api.AgvService/pauseNavigation
|
||||
|
||||
grpcurl -plaintext -d '{"deviceId":"src1100"}' \
|
||||
127.0.0.1:50052 cmvr.api.AgvService/resumeNavigation
|
||||
|
||||
grpcurl -plaintext -d '{"deviceId":"src1100"}' \
|
||||
127.0.0.1:50052 cmvr.api.AgvService/cancelNavigation
|
||||
```
|
||||
|
||||
差速底盘的 `vy` 应保持 `0`。低层速度控制不等价于导航,并可能与已有任务
|
||||
冲突;只应在专门的速度控制测试流程中使用:
|
||||
|
||||
```bash
|
||||
grpcurl -plaintext \
|
||||
-d '{"header":{"deviceId":"src1100"},"velocity":{"vx":0.05,"vy":0,"wz":0}}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.AgvService/setVelocity
|
||||
|
||||
grpcurl -plaintext -d '{"deviceId":"src1100"}' \
|
||||
127.0.0.1:50052 cmvr.api.AgvService/stopVelocityControl
|
||||
```
|
||||
|
||||
## 错误返回
|
||||
|
||||
控制器响应中的非零 `ret_code` 和 `err_msg` 会保留在 `AgvResult.message`,并由
|
||||
gRPC 同时写入 transport status message 和反馈头的 `errorMessage`。非 OK RPC
|
||||
下,标准客户端通常不会交付响应体,因此跨客户端应以 transport status message
|
||||
为准,不要依赖反馈头仍然可见。例如:
|
||||
|
||||
```text
|
||||
SEER Robokit command failed: ret_code=43051, err_msg=planner_rejected_pose
|
||||
```
|
||||
|
||||
控制器仅返回“已接收”不等于导航完成;同步接口仍要等待精确任务终态和停车
|
||||
确认。若发送后连接中断且控制器是否执行已无法确定,错误会明确提示 outcome
|
||||
unknown,调用方不能自动重发运动命令,应先查询状态并取消或停止。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 仙工文档明确把 `3051` 定位为任务链或验证测试等单车场景接口;不要把它当作
|
||||
多车调度接口,否则可能出现路径/速度不连续等危险行为。
|
||||
- `emergencyStop` 是控制器软件停止,不是功能安全急停;真实系统必须保留可达的
|
||||
硬件急停、安全激光、碰撞条和独立安全链。
|
||||
- 首次 PGV 测试应在低速、空载、隔离区域进行,并先核对二维码坐标系、传感器
|
||||
上/下视方向、调整半径和中心偏移的标定值。
|
||||
- PGV 同步成功目前能证明精确 `3051` 任务进入终态,并连续确认两次零速度;
|
||||
仙工文档没有明确 `Completed` 是否一定覆盖 PGV 二次调整的全部阶段,仍需实机
|
||||
验证后才能据此联动机械臂。异步成功更不代表 PGV 调整完成。
|
||||
- 地图切换、地图上传和开始建图会改变控制器状态,也会先抢占控制权;不要和
|
||||
现场调度系统并行操作。
|
||||
367
cmvr-es/devices/agv/seer_robokit/include/seer_robokit_agv.h
Normal file
367
cmvr-es/devices/agv/seer_robokit/include/seer_robokit_agv.h
Normal file
@ -0,0 +1,367 @@
|
||||
#ifndef CMVR_ES_SEER_ROBOKIT_AGV_H
|
||||
#define CMVR_ES_SEER_ROBOKIT_AGV_H
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
#include "cmvr/config/agv_config/agv_config.pb.h"
|
||||
#include "devices/agv/abstract_agv.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class SeerRobokitAgvTestPeer;
|
||||
|
||||
class SeerRobokitAgv final : public AbstractAGV {
|
||||
public:
|
||||
explicit SeerRobokitAgv(const config::SeerRobokitAgvConfig& cfg);
|
||||
~SeerRobokitAgv() override;
|
||||
|
||||
std::string typeName() const override { return "SeerRobokitAgv"; }
|
||||
|
||||
bool supportsSynchronousAction(AgvActionKind kind) const noexcept override
|
||||
{
|
||||
switch (kind) {
|
||||
case AgvActionKind::NavigateToPose:
|
||||
case AgvActionKind::NavigateToStation:
|
||||
case AgvActionKind::FollowPath:
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool init() override;
|
||||
bool start() override;
|
||||
bool stop() override;
|
||||
bool update() override;
|
||||
|
||||
AgvRuntimeState runtimeState() const override;
|
||||
AgvNavigationStatus navigationStatus() const override;
|
||||
|
||||
AgvResult emergencyStop() override;
|
||||
AgvResult clearFault() override;
|
||||
AgvResult relocalize(const math::Pose2d& pose) override;
|
||||
|
||||
|
||||
AgvResult navigateToPose(
|
||||
const math::Pose2d& pose,
|
||||
const AgvMotionOptions& options = {},
|
||||
const AgvAdapterParams& adapter_params = AgvAdapterParams{}) override;
|
||||
AgvResult navigateToStation(
|
||||
const std::string& station_id,
|
||||
const AgvMotionOptions& options = {},
|
||||
const AgvAdapterParams& adapter_params = AgvAdapterParams{}) override;
|
||||
AgvResult followPath(
|
||||
const std::vector<AgvPathSegment>& path) override;
|
||||
AgvResult followPath(
|
||||
const std::vector<AgvPathSegment>& path,
|
||||
const AgvMotionOptions& options) override;
|
||||
AgvResult translate(const AgvTranslation& translation) override;
|
||||
AgvResult pauseNavigation() override;
|
||||
AgvResult resumeNavigation() override;
|
||||
AgvResult cancelNavigation() override;
|
||||
|
||||
AgvResult setVelocity(const AgvVelocity& velocity) override;
|
||||
AgvResult confirmMotionStopped() override;
|
||||
|
||||
AgvResult listMaps(std::vector<std::string>& maps) const override;
|
||||
AgvResult listStations(std::vector<AgvStation>& stations) const override;
|
||||
AgvResult switchMap(const std::string& map_name) override;
|
||||
AgvResult uploadMap(const std::string& map_name, const std::string& content) override;
|
||||
AgvResult downloadMap(const std::string& map_name, std::string& content) const override;
|
||||
AgvResult startMapping(const AgvMappingOptions& options = {}) override;
|
||||
AgvResult getMappingData(int start_index, AgvMappingData& data) const override;
|
||||
AgvResult getUnifiedMapUpdate(
|
||||
std::uint64_t after_sequence,
|
||||
const AgvMapStreamOptions& options,
|
||||
AgvUnifiedMapUpdate& update) const override;
|
||||
AgvResult stopMapping() override;
|
||||
|
||||
|
||||
|
||||
private:
|
||||
friend class SeerRobokitAgvTestPeer;
|
||||
|
||||
struct Ports {
|
||||
int status{19204};
|
||||
int control{19205};
|
||||
int navigation{19206};
|
||||
int config{19207};
|
||||
int other{19210};
|
||||
int push{19301};
|
||||
};
|
||||
|
||||
struct PoseTaskStatus {
|
||||
bool found{false};
|
||||
int state{0};
|
||||
int type{0};
|
||||
bool type_present{false};
|
||||
|
||||
double progress{0.0};
|
||||
bool progress_present{false};
|
||||
|
||||
double remaining_distance{0.0};
|
||||
bool distance_present{false};
|
||||
|
||||
std::string closest_target;
|
||||
std::string source_name;
|
||||
std::string target_name;
|
||||
std::string detail;
|
||||
};
|
||||
struct NavigationSnapshot {
|
||||
int task_status{0};
|
||||
int task_type{0};
|
||||
bool task_status_present{false};
|
||||
bool task_type_present{false};
|
||||
bool blocked{false};
|
||||
bool blocked_present{false};
|
||||
int block_reason{-1};
|
||||
std::string block_reason_raw;
|
||||
bool velocity_present{false};
|
||||
double vx{0.0};
|
||||
double vy{0.0};
|
||||
double w{0.0};
|
||||
bool emergency{false};
|
||||
std::string target_id;
|
||||
std::string active_faults;
|
||||
bool only_recoverable_blocking_faults{false};
|
||||
std::string detail;
|
||||
};
|
||||
|
||||
enum class CommandTransmissionState {
|
||||
NotSent,
|
||||
PossiblySent,
|
||||
};
|
||||
|
||||
struct TrackedNavigationContext {
|
||||
std::string token;
|
||||
std::vector<std::string> task_ids;
|
||||
AgvTaskType type{AgvTaskType::None};
|
||||
std::string target_id;
|
||||
std::vector<std::string> target_ids;
|
||||
std::uint64_t navigation_generation{0};
|
||||
std::chrono::steady_clock::time_point accepted_at{};
|
||||
bool synchronous_wait{false};
|
||||
};
|
||||
|
||||
struct PoseTaskContext {
|
||||
std::string task_id;
|
||||
math::Pose2d target{};
|
||||
double reach_distance{0.0};
|
||||
double reach_angle{0.0};
|
||||
std::uint64_t navigation_generation{0};
|
||||
std::uint64_t controller_fault_sequence_at_start{0};
|
||||
std::uint64_t control_attempt_sequence_at_start{0};
|
||||
std::uint64_t controller_fault_channel_epoch_at_start{0};
|
||||
};
|
||||
|
||||
AgvResult connect_();
|
||||
AgvResult disconnect_();
|
||||
AgvResult emergencyStopTrackedNavigation_(
|
||||
const TrackedNavigationContext* expected_navigation);
|
||||
AgvResult connectSocket_(int& sock, int port);
|
||||
AgvResult ensureOtherSocket_();
|
||||
void closeSocket_(int& sock) const;
|
||||
bool connected_() const;
|
||||
|
||||
AgvResult acquireControl_() const;
|
||||
AgvResult confirmPoseNavigationStarted_(
|
||||
const PoseTaskContext& context,
|
||||
bool accept_paused,
|
||||
const AgvMotionOptions& options) const;
|
||||
AgvResult waitForPoseNavigationTerminal_(
|
||||
const PoseTaskContext& pose_context,
|
||||
const TrackedNavigationContext& navigation_context,
|
||||
const AgvMotionOptions& options);
|
||||
AgvResult waitForTrackedNavigationTerminal_(
|
||||
const TrackedNavigationContext& context,
|
||||
const AgvMotionOptions& options);
|
||||
AgvResult queryNavigationSnapshot_(NavigationSnapshot& snapshot) const;
|
||||
AgvResult cancelTrackedNavigation_(
|
||||
const TrackedNavigationContext& context,
|
||||
std::uint64_t& accepted_generation);
|
||||
AgvResult waitForCanceledTaskToStop_(
|
||||
const TrackedNavigationContext& context,
|
||||
const AgvMotionOptions& options,
|
||||
const std::string& reason,
|
||||
bool require_global_stopped = false);
|
||||
AgvResult failAndCancelTrackedNavigation_(
|
||||
const TrackedNavigationContext& context,
|
||||
const AgvMotionOptions& options,
|
||||
AgvErrorCode error_code,
|
||||
const std::string& reason);
|
||||
AgvResult queryPoseTaskStatus_(
|
||||
const std::string& task_id,
|
||||
PoseTaskStatus& status) const;
|
||||
AgvResult queryTaskStatuses_(
|
||||
const std::vector<std::string>& task_ids,
|
||||
std::vector<PoseTaskStatus>& statuses) const;
|
||||
bool poseTargetReached_(
|
||||
const PoseTaskContext& context,
|
||||
std::string& detail) const;
|
||||
std::string cachedControllerFaultDetail_(
|
||||
std::uint64_t after_sequence = 0,
|
||||
int wait_ms = 0,
|
||||
std::uint64_t* associated_control_attempt = nullptr) const;
|
||||
int controllerFaultCaptureGraceMs_() const;
|
||||
int controllerFaultStateMaxAgeMs_() const;
|
||||
std::string freeNavigationFaultStateUnavailableDetail_() const;
|
||||
void rememberPoseTask_(const PoseTaskContext& context) const;
|
||||
void advancePoseTaskGeneration_(
|
||||
std::uint64_t navigation_generation,
|
||||
std::uint64_t control_attempt_sequence) const;
|
||||
void advancePoseTaskControlAttempt_(
|
||||
std::uint64_t control_attempt_sequence) const;
|
||||
void clearPoseTask_(std::uint64_t navigation_generation) const;
|
||||
void clearPoseTaskIfTaskId_(const std::string& task_id) const;
|
||||
bool currentPoseTask_(PoseTaskContext& context) const;
|
||||
void rememberTrackedNavigation_(
|
||||
const TrackedNavigationContext& context) const;
|
||||
void advanceTrackedNavigationGeneration_(
|
||||
std::uint64_t navigation_generation) const;
|
||||
void clearTrackedNavigation_(std::uint64_t navigation_generation) const;
|
||||
void clearTrackedNavigationIfToken_(const std::string& token) const;
|
||||
bool currentTrackedNavigation_(
|
||||
TrackedNavigationContext& context) const;
|
||||
AgvResult sendControlledCommand_(int sock,
|
||||
std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
Json::Value* response,
|
||||
std::uint64_t* accepted_navigation_generation = nullptr,
|
||||
std::uint64_t* controller_fault_sequence_at_attempt = nullptr,
|
||||
std::uint64_t* control_attempt_sequence = nullptr,
|
||||
PoseTaskContext* pose_context_to_publish = nullptr,
|
||||
bool reject_if_active_controller_fault = false,
|
||||
TrackedNavigationContext* navigation_context_to_publish = nullptr,
|
||||
bool preserve_tracked_navigation = false,
|
||||
const std::string* expected_navigation_token = nullptr,
|
||||
const std::function<bool()>* cancellation_requested = nullptr,
|
||||
const TrackedNavigationContext* expected_active_navigation = nullptr) const;
|
||||
AgvResult sendCommand_(int sock,
|
||||
std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
Json::Value* response,
|
||||
CommandTransmissionState* transmission_state = nullptr) const;
|
||||
AgvResult sendCommandRaw_(int sock,
|
||||
std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
std::string* response_payload,
|
||||
CommandTransmissionState* transmission_state = nullptr) const;
|
||||
AgvResult sendCommandNoResponse_(int sock, std::uint16_t command, const Json::Value& payload) const;
|
||||
AgvResult configurePush_();
|
||||
void startPushThread_();
|
||||
void stopPushThread_();
|
||||
void pushLoop_();
|
||||
void invalidateControllerFaultState_();
|
||||
AgvRuntimeState queryRuntimeState_() const;
|
||||
void updateCachedRuntimeState_(const Json::Value& payload);
|
||||
void startMapUpdateThread_();
|
||||
void stopMapUpdateThread_();
|
||||
void mapUpdateLoop_();
|
||||
AgvResult refreshMapCacheOnce_(const AgvMapStreamOptions& options) const;
|
||||
AgvResult parseMapFileToUpdates_(
|
||||
const std::string& file_name,
|
||||
const std::string& content,
|
||||
const AgvMapStreamOptions& options,
|
||||
std::vector<AgvUnifiedMapUpdate>& updates) const;
|
||||
AgvResult parseSeerRobokitMapArchive_(
|
||||
const std::string& file_name,
|
||||
const std::string& content,
|
||||
const AgvMapStreamOptions& options,
|
||||
std::vector<AgvUnifiedMapUpdate>& updates) const;
|
||||
AgvResult parseSeerRobokitMap2D_(
|
||||
const std::string& file_name,
|
||||
const std::string& content,
|
||||
const AgvMapStreamOptions& options,
|
||||
AgvUnifiedMapUpdate& update) const;
|
||||
AgvResult parseSeerRobokitMap3D_(
|
||||
const std::string& file_name,
|
||||
const std::string& content,
|
||||
const AgvMapStreamOptions& options,
|
||||
AgvUnifiedMapUpdate& update) const;
|
||||
void cacheMapUpdates_(std::vector<AgvUnifiedMapUpdate> updates) const;
|
||||
bool findCachedMapUpdate_(
|
||||
std::uint64_t after_sequence,
|
||||
const AgvMapStreamOptions& options,
|
||||
AgvUnifiedMapUpdate& update) const;
|
||||
bool mapUpdateMatches_(
|
||||
const AgvUnifiedMapUpdate& update,
|
||||
const AgvMapStreamOptions& options) const;
|
||||
|
||||
static std::vector<std::uint8_t> buildFrame_(std::uint16_t command, const std::string& payload);
|
||||
static std::string toJsonString_(const Json::Value& value);
|
||||
static bool parseJson_(const std::string& input, Json::Value& output, std::string& error);
|
||||
static std::string extractJson_(const std::string& raw);
|
||||
static AgvResult receiveFrame_(int sock, std::uint16_t& command, std::string& payload);
|
||||
static void applyMotionOptions_(
|
||||
Json::Value& payload,
|
||||
const AgvMotionOptions& options,
|
||||
bool include_reach_options = true);
|
||||
static void applyAdapterParams_(Json::Value& payload, const AgvAdapterParams& params);
|
||||
static AgvResult resultFromResponse_(const Json::Value& response);
|
||||
|
||||
config::SeerRobokitAgvConfig config_;
|
||||
std::string ip_;
|
||||
std::string control_nick_name_;
|
||||
int recv_timeout_ms_{1000};
|
||||
Ports ports_;
|
||||
bool state_push_enabled_{false};
|
||||
bool map_update_enabled_{false};
|
||||
int map_update_interval_ms_{1000};
|
||||
std::size_t map_update_history_size_{8};
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::mutex status_io_mutex_;
|
||||
mutable std::mutex control_sequence_mutex_;
|
||||
mutable std::atomic<std::uint64_t> navigation_generation_{0};
|
||||
mutable std::atomic<std::uint64_t> pose_task_sequence_{0};
|
||||
mutable std::atomic<std::uint64_t> control_attempt_sequence_{0};
|
||||
mutable std::atomic<std::uint64_t> controller_fault_channel_epoch_{0};
|
||||
mutable std::mutex pose_task_mutex_;
|
||||
mutable PoseTaskContext pose_task_context_;
|
||||
mutable std::mutex tracked_navigation_mutex_;
|
||||
mutable TrackedNavigationContext tracked_navigation_context_;
|
||||
mutable int sock_status_{-1};
|
||||
mutable int sock_control_{-1};
|
||||
mutable int sock_navigation_{-1};
|
||||
mutable int sock_config_{-1};
|
||||
mutable int sock_other_{-1};
|
||||
mutable int sock_push_{-1};
|
||||
std::string last_error_;
|
||||
|
||||
std::atomic<bool> push_running_{false};
|
||||
std::thread push_thread_;
|
||||
mutable std::mutex runtime_state_mutex_;
|
||||
mutable std::condition_variable runtime_state_cv_;
|
||||
AgvRuntimeState cached_runtime_state_;
|
||||
bool cached_runtime_state_valid_{false};
|
||||
std::uint64_t controller_fault_sequence_{0};
|
||||
bool controller_fault_state_observed_{false};
|
||||
std::chrono::steady_clock::time_point controller_fault_state_observed_at_{};
|
||||
std::string active_controller_fault_detail_;
|
||||
double last_controller_fault_timestamp_{0.0};
|
||||
std::string last_controller_fault_detail_;
|
||||
std::uint64_t last_controller_fault_control_attempt_{0};
|
||||
|
||||
mutable std::atomic<bool> map_update_running_{false};
|
||||
mutable std::thread map_update_thread_;
|
||||
mutable std::mutex map_update_mutex_;
|
||||
mutable std::condition_variable map_update_cv_;
|
||||
mutable std::deque<AgvUnifiedMapUpdate> cached_map_updates_;
|
||||
mutable std::uint64_t map_sequence_{0};
|
||||
mutable int next_mapping_index_{0};
|
||||
mutable std::size_t last_map_content_hash_{0};
|
||||
mutable std::string map_session_id_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_SEER_ROBOKIT_AGV_H
|
||||
@ -0,0 +1,303 @@
|
||||
#ifndef CMVR_ES_SEER_ROBOKIT_NAVIGATION_UTILS_H
|
||||
#define CMVR_ES_SEER_ROBOKIT_NAVIGATION_UTILS_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "devices/agv/abstract_agv.h"
|
||||
|
||||
namespace cmvr::device::seer_robokit::navigation {
|
||||
|
||||
constexpr auto kPoseNavigationStartTimeout = std::chrono::milliseconds(1500);
|
||||
constexpr auto kPoseNavigationPollInterval = std::chrono::milliseconds(50);
|
||||
constexpr int kPoseNavigationRequiredRunningSamples = 2;
|
||||
constexpr auto kDefaultNavigationWaitTimeout =
|
||||
std::chrono::milliseconds(600000);
|
||||
constexpr auto kDefaultNavigationBlockedTimeout =
|
||||
std::chrono::milliseconds(60000);
|
||||
constexpr auto kDefaultNavigationPollInterval =
|
||||
std::chrono::milliseconds(200);
|
||||
constexpr auto kMaximumNavigationPollInterval =
|
||||
std::chrono::milliseconds(5000);
|
||||
constexpr auto kNavigationCancellationCheckInterval =
|
||||
std::chrono::milliseconds(50);
|
||||
constexpr auto kNavigationCancelPollInterval =
|
||||
std::chrono::milliseconds(100);
|
||||
constexpr auto kNavigationCancelConfirmationTimeout =
|
||||
std::chrono::milliseconds(3000);
|
||||
constexpr int kRequiredCompletedStopSamples = 2;
|
||||
constexpr double kNavigationStopVelocityTolerance = 0.005;
|
||||
constexpr int kRobotBlockedFaultCode = 52200;
|
||||
constexpr int kMinimumControllerFaultCaptureGraceMs = 250;
|
||||
constexpr int kMaximumControllerFaultCaptureGraceMs = 5000;
|
||||
constexpr int kDefaultControllerFaultPushIntervalMs = 1000;
|
||||
constexpr int kControllerFaultPushJitterMs = 100;
|
||||
constexpr int kMinimumControllerFaultStateMaxAgeMs = 2000;
|
||||
constexpr int kControllerFaultStateMaxAgeIntervals = 5;
|
||||
constexpr double kDefaultPoseReachDistance = 0.05;
|
||||
constexpr double kDefaultPoseReachAngle = 0.10;
|
||||
constexpr double kTwoPi = 6.28318530717958647692;
|
||||
|
||||
static inline bool exactTaskStateIsActive(const int state)
|
||||
{
|
||||
return state >= 1 && state <= 3;
|
||||
}
|
||||
|
||||
static inline bool exactTaskStateIsKnownTerminal(const int state)
|
||||
{
|
||||
return state >= 4 && state <= 7;
|
||||
}
|
||||
|
||||
static inline bool globalTaskStateIsKnownTerminal(const int state)
|
||||
{
|
||||
return state == 0 || exactTaskStateIsKnownTerminal(state);
|
||||
}
|
||||
|
||||
// Some SRC firmware versions report station navigation as task type 3.
|
||||
// Exact task ids and target ids remain the primary ownership evidence.
|
||||
static inline bool exactTrackedNavigationTaskTypeMatches(
|
||||
const AgvTaskType expected_type,
|
||||
const int actual_type)
|
||||
{
|
||||
switch (expected_type) {
|
||||
case AgvTaskType::NavigateToPose:
|
||||
return actual_type == 1;
|
||||
case AgvTaskType::NavigateToStation:
|
||||
case AgvTaskType::FollowPath:
|
||||
return actual_type == 2 || actual_type == 3;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static inline bool globalNavigationTaskTypeMatches(
|
||||
const AgvTaskType expected_type,
|
||||
const int actual_type)
|
||||
{
|
||||
switch (expected_type) {
|
||||
case AgvTaskType::NavigateToPose:
|
||||
return actual_type == 1;
|
||||
case AgvTaskType::NavigateToStation:
|
||||
return actual_type == 2 || actual_type == 3;
|
||||
case AgvTaskType::FollowPath:
|
||||
return actual_type == 3;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static inline double angleDistance(const double lhs, const double rhs)
|
||||
{
|
||||
return std::abs(std::remainder(lhs - rhs, kTwoPi));
|
||||
}
|
||||
|
||||
static inline AgvResult withUnknownControllerOutcome(AgvResult result)
|
||||
{
|
||||
const auto code = result.ok() ? AgvErrorCode::CommandFailed : result.code;
|
||||
std::string detail = result.message.empty() ? "unknown transport or protocol error" : result.message;
|
||||
detail +=
|
||||
"; SEER Robokit controller outcome is unknown after the command attempt; "
|
||||
"the command may already have taken effect; do not issue another motion "
|
||||
"command automatically; query status and cancel or stop first";
|
||||
return AgvResult::failure(code, detail);
|
||||
}
|
||||
|
||||
static inline std::string makePoseTaskId(
|
||||
const std::string& device_id,
|
||||
const std::uint64_t task_sequence)
|
||||
{
|
||||
const auto timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
const std::string prefix = device_id.empty() ? "cmvr-es" : device_id;
|
||||
return prefix + "_pose_" + std::to_string(timestamp)
|
||||
+ "_" + std::to_string(task_sequence);
|
||||
}
|
||||
|
||||
static inline std::string makeNavigationTaskId(
|
||||
const std::string& device_id,
|
||||
const char* kind,
|
||||
const std::uint64_t task_sequence)
|
||||
{
|
||||
const auto timestamp = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
const std::string prefix = device_id.empty() ? "cmvr-es" : device_id;
|
||||
return prefix + "_" + kind + "_" + std::to_string(timestamp)
|
||||
+ "_" + std::to_string(task_sequence);
|
||||
}
|
||||
|
||||
static inline const char* blockReasonName(const int reason)
|
||||
{
|
||||
switch (reason) {
|
||||
case 0:
|
||||
return "ultrasonic";
|
||||
case 1:
|
||||
return "laser";
|
||||
case 2:
|
||||
return "fallingdown";
|
||||
case 3:
|
||||
return "collision";
|
||||
case 4:
|
||||
return "infrared";
|
||||
case 5:
|
||||
return "locked";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static inline std::string invalidMotionOption(const AgvMotionOptions& options)
|
||||
{
|
||||
const auto non_negative_error = [](const double value, const char* field) {
|
||||
if (!std::isfinite(value)) {
|
||||
return std::string(field) + " must be finite";
|
||||
}
|
||||
if (value < 0.0) {
|
||||
return std::string(field) + " must be non-negative";
|
||||
}
|
||||
return std::string{};
|
||||
};
|
||||
|
||||
if (auto error = non_negative_error(options.max_speed, "max_speed");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(
|
||||
options.max_angular_speed,
|
||||
"max_angular_speed");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(
|
||||
options.max_acceleration,
|
||||
"max_acceleration");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(
|
||||
options.max_angular_acceleration,
|
||||
"max_angular_acceleration");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(
|
||||
options.reach_distance,
|
||||
"reach_distance");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(options.reach_angle, "reach_angle");
|
||||
!error.empty()) return error;
|
||||
if (auto error = non_negative_error(options.speed_ratio, "speed_ratio");
|
||||
!error.empty()) return error;
|
||||
if (options.wait_timeout_ms < 0) {
|
||||
return "wait_timeout_ms must be non-negative";
|
||||
}
|
||||
if (options.blocked_timeout_ms < 0) {
|
||||
return "blocked_timeout_ms must be non-negative";
|
||||
}
|
||||
if (options.poll_interval_ms < 0) {
|
||||
return "poll_interval_ms must be non-negative";
|
||||
}
|
||||
if (options.poll_interval_ms
|
||||
> kMaximumNavigationPollInterval.count()) {
|
||||
return "poll_interval_ms must not exceed "
|
||||
+ std::to_string(kMaximumNavigationPollInterval.count());
|
||||
}
|
||||
if (options.wait_timeout_ms > 0
|
||||
&& options.poll_interval_ms > options.wait_timeout_ms) {
|
||||
return "poll_interval_ms must not exceed wait_timeout_ms";
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
static inline std::chrono::milliseconds navigationWaitTimeout(
|
||||
const AgvMotionOptions& options)
|
||||
{
|
||||
return options.wait_timeout_ms > 0
|
||||
? std::chrono::milliseconds(options.wait_timeout_ms)
|
||||
: kDefaultNavigationWaitTimeout;
|
||||
}
|
||||
|
||||
static inline std::chrono::milliseconds navigationBlockedTimeout(
|
||||
const AgvMotionOptions& options)
|
||||
{
|
||||
return options.blocked_timeout_ms > 0
|
||||
? std::chrono::milliseconds(options.blocked_timeout_ms)
|
||||
: kDefaultNavigationBlockedTimeout;
|
||||
}
|
||||
|
||||
static inline std::chrono::milliseconds navigationPollInterval(
|
||||
const AgvMotionOptions& options)
|
||||
{
|
||||
if (options.poll_interval_ms <= 0) {
|
||||
return kDefaultNavigationPollInterval;
|
||||
}
|
||||
return std::chrono::milliseconds(
|
||||
std::max(options.poll_interval_ms, 20));
|
||||
}
|
||||
|
||||
static inline bool navigationCancellationRequested(const AgvMotionOptions& options)
|
||||
{
|
||||
return options.cancellation_requested
|
||||
&& options.cancellation_requested();
|
||||
}
|
||||
|
||||
static inline void sleepForNavigationPoll(
|
||||
const std::chrono::milliseconds poll_interval,
|
||||
const std::chrono::steady_clock::time_point overall_deadline,
|
||||
const AgvMotionOptions& options)
|
||||
{
|
||||
const auto poll_deadline = std::min(
|
||||
overall_deadline,
|
||||
std::chrono::steady_clock::now() + poll_interval);
|
||||
while (std::chrono::steady_clock::now() < poll_deadline
|
||||
&& !navigationCancellationRequested(options)) {
|
||||
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
poll_deadline - std::chrono::steady_clock::now());
|
||||
if (remaining <= std::chrono::milliseconds::zero()) {
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::min(
|
||||
kNavigationCancellationCheckInterval,
|
||||
remaining));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Snapshot>
|
||||
static inline bool navigationStopped(const Snapshot& snapshot)
|
||||
{
|
||||
return snapshot.velocity_present
|
||||
&& std::abs(snapshot.vx) <= kNavigationStopVelocityTolerance
|
||||
&& std::abs(snapshot.vy) <= kNavigationStopVelocityTolerance
|
||||
&& std::abs(snapshot.w) <= kNavigationStopVelocityTolerance;
|
||||
}
|
||||
|
||||
static inline AgvResult reconciledNavigationResult(
|
||||
const AgvResult& command_result,
|
||||
AgvResult terminal_result)
|
||||
{
|
||||
if (command_result.ok()) {
|
||||
return terminal_result;
|
||||
}
|
||||
if (terminal_result.ok()) {
|
||||
terminal_result.message =
|
||||
"SEER Robokit navigation completed after an indeterminate command "
|
||||
"acknowledgment; initial_detail=" + command_result.message;
|
||||
return terminal_result;
|
||||
}
|
||||
terminal_result.message =
|
||||
"SEER Robokit navigation command acknowledgment was indeterminate: "
|
||||
+ command_result.message + "; status reconciliation: "
|
||||
+ terminal_result.message;
|
||||
return terminal_result;
|
||||
}
|
||||
|
||||
static inline bool parseFiniteDouble(const std::string& value, double& parsed)
|
||||
{
|
||||
std::size_t consumed = 0;
|
||||
try {
|
||||
parsed = std::stod(value, &consumed);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
return consumed == value.size() && std::isfinite(parsed);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::seer_robokit::navigation
|
||||
|
||||
#endif // CMVR_ES_SEER_ROBOKIT_NAVIGATION_UTILS_H
|
||||
@ -0,0 +1,141 @@
|
||||
#ifndef CMVR_ES_SEER_ROBOKIT_PGV_UTILS_H
|
||||
#define CMVR_ES_SEER_ROBOKIT_PGV_UTILS_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
#include "devices/agv/abstract_agv.h"
|
||||
#include "seer_robokit_navigation_utils.h"
|
||||
#include "seer_robokit_utils.h"
|
||||
|
||||
namespace cmvr::device::seer_robokit::pgv {
|
||||
|
||||
constexpr char kUsePgv[] = "use_pgv";
|
||||
constexpr char kPgvAdjustDist[] = "pgv_adjust_dist";
|
||||
constexpr char kPgvAdjustCx[] = "pgv_adjust_cx";
|
||||
constexpr char kPgvAdjustCy[] = "pgv_adjust_cy";
|
||||
constexpr char kPgvXAdjust[] = "pgv_x_adjust";
|
||||
constexpr char kUseDownPgv[] = "use_down_pgv";
|
||||
|
||||
// These spellings currently appear in the vendor document, but conflict with
|
||||
// its own field table/example and the repository's older working serializer.
|
||||
constexpr char kMalformedAdjustDist[] = "pgv_adjustuse_pgv_dist";
|
||||
constexpr char kAdjustCyDocumentAlias[] = "pgv_ajdust_cy";
|
||||
|
||||
static inline bool isPgvAdjustmentKey(const std::string& key)
|
||||
{
|
||||
return key == kUsePgv
|
||||
|| key == kPgvAdjustDist
|
||||
|| key == kPgvAdjustCx
|
||||
|| key == kPgvAdjustCy
|
||||
|| key == kPgvXAdjust
|
||||
|| key == kUseDownPgv
|
||||
|| key == kMalformedAdjustDist
|
||||
|| key == kAdjustCyDocumentAlias;
|
||||
}
|
||||
|
||||
static inline bool hasPgvAdjustmentParams(const AgvAdapterParams& params)
|
||||
{
|
||||
for (const auto& [key, value] : params.values) {
|
||||
(void)value;
|
||||
if (isPgvAdjustmentKey(key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the string-valued generic adapter parameters into the native JSON
|
||||
* types required by SEER Robokit API 3051. Returns an error string without
|
||||
* modifying controller state; an empty string means success.
|
||||
*/
|
||||
static inline std::string applyPgvAdjustmentParams(
|
||||
Json::Value& payload,
|
||||
const AgvAdapterParams& params)
|
||||
{
|
||||
if (params.getString(kMalformedAdjustDist)) {
|
||||
return std::string(kMalformedAdjustDist)
|
||||
+ " is a vendor-document typo; use " + kPgvAdjustDist;
|
||||
}
|
||||
if (hasPgvAdjustmentParams(params)) {
|
||||
for (const auto& [key, value] : params.values) {
|
||||
(void)value;
|
||||
if (!isPgvAdjustmentKey(key)
|
||||
&& key != "source_id"
|
||||
&& key != "task_id") {
|
||||
return "PGV adjustment must not be combined with adapter "
|
||||
"field " + key;
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto adjust_cy = params.getString(kPgvAdjustCy);
|
||||
const auto adjust_cy_alias = params.getString(kAdjustCyDocumentAlias);
|
||||
if (adjust_cy && adjust_cy_alias) {
|
||||
return std::string(kPgvAdjustCy) + " and its vendor-document alias "
|
||||
+ kAdjustCyDocumentAlias + " must not both be set";
|
||||
}
|
||||
|
||||
const auto apply_bool = [&payload, ¶ms](const char* key) {
|
||||
if (!params.getString(key)) {
|
||||
return std::string{};
|
||||
}
|
||||
const auto parsed = params.getBool(key);
|
||||
if (!parsed) {
|
||||
return std::string(key)
|
||||
+ " must be a boolean string such as true or false";
|
||||
}
|
||||
detail::jsonMember(payload, key) = *parsed;
|
||||
return std::string{};
|
||||
};
|
||||
if (auto error = apply_bool(kUsePgv); !error.empty()) {
|
||||
return error;
|
||||
}
|
||||
if (auto error = apply_bool(kUseDownPgv); !error.empty()) {
|
||||
return error;
|
||||
}
|
||||
|
||||
const auto apply_number = [&payload, ¶ms](
|
||||
const char* key,
|
||||
const bool non_negative) {
|
||||
const auto raw = params.getString(key);
|
||||
if (!raw) {
|
||||
return std::string{};
|
||||
}
|
||||
double parsed = 0.0;
|
||||
if (!navigation::parseFiniteDouble(*raw, parsed)) {
|
||||
return std::string(key) + " must be a complete finite number";
|
||||
}
|
||||
if (non_negative && parsed < 0.0) {
|
||||
return std::string(key) + " must be non-negative";
|
||||
}
|
||||
detail::jsonMember(payload, key) = parsed;
|
||||
return std::string{};
|
||||
};
|
||||
if (auto error = apply_number(kPgvAdjustDist, true); !error.empty()) {
|
||||
return error;
|
||||
}
|
||||
if (auto error = apply_number(kPgvAdjustCx, false); !error.empty()) {
|
||||
return error;
|
||||
}
|
||||
if (adjust_cy_alias) {
|
||||
double parsed = 0.0;
|
||||
if (!navigation::parseFiniteDouble(*adjust_cy_alias, parsed)) {
|
||||
return std::string(kAdjustCyDocumentAlias)
|
||||
+ " must be a complete finite number";
|
||||
}
|
||||
detail::jsonMember(payload, kPgvAdjustCy) = parsed;
|
||||
} else if (auto error = apply_number(kPgvAdjustCy, false);
|
||||
!error.empty()) {
|
||||
return error;
|
||||
}
|
||||
if (auto error = apply_number(kPgvXAdjust, false); !error.empty()) {
|
||||
return error;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::seer_robokit::pgv
|
||||
|
||||
#endif // CMVR_ES_SEER_ROBOKIT_PGV_UTILS_H
|
||||
@ -0,0 +1,41 @@
|
||||
#ifndef CMVR_ES_SEER_ROBOKIT_PROTOCOL_H
|
||||
#define CMVR_ES_SEER_ROBOKIT_PROTOCOL_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace cmvr::device::seer_robokit::protocol {
|
||||
|
||||
constexpr std::uint16_t kRobotStatusLoc = 1004;
|
||||
constexpr std::uint16_t kRobotStatusBattery = 1007;
|
||||
constexpr std::uint16_t kRobotStatusAll2 = 1101;
|
||||
constexpr std::uint16_t kRobotStatusTask = 1020;
|
||||
constexpr std::uint16_t kRobotStatusTaskPackage = 1110;
|
||||
constexpr std::uint16_t kRobotStatusMap = 1300;
|
||||
constexpr std::uint16_t kRobotStatusStation = 1301;
|
||||
constexpr std::uint16_t kRobotStatusMappingFileList = 1780;
|
||||
constexpr std::uint16_t kRobotStatusDownloadFile = 1800;
|
||||
constexpr std::uint16_t kRobotControlStop = 2000;
|
||||
constexpr std::uint16_t kRobotControlReloc = 2002;
|
||||
constexpr std::uint16_t kRobotControlMotion = 2010;
|
||||
constexpr std::uint16_t kRobotControlLoadMap = 2022;
|
||||
constexpr std::uint16_t kRobotTaskPause = 3001;
|
||||
constexpr std::uint16_t kRobotTaskResume = 3002;
|
||||
constexpr std::uint16_t kRobotTaskCancel = 3003;
|
||||
constexpr std::uint16_t kRobotTaskGoTarget = 3051;
|
||||
constexpr std::uint16_t kRobotTaskTranslate = 3055;
|
||||
constexpr std::uint16_t kRobotTaskGoTargetList = 3066;
|
||||
constexpr std::uint16_t kRobotTaskClearTargetList = 3067;
|
||||
constexpr std::uint16_t kRobotConfigLock = 4005;
|
||||
constexpr std::uint16_t kRobotConfigClearFault = 4009;
|
||||
constexpr std::uint16_t kRobotConfigUploadMap = 4010;
|
||||
constexpr std::uint16_t kRobotConfigDownloadMap = 4011;
|
||||
constexpr std::uint16_t kRobotOtherStartMapping = 6100;
|
||||
constexpr std::uint16_t kRobotOtherStopMapping = 6101;
|
||||
constexpr std::uint16_t kRobotPushConfigReq = 9300;
|
||||
constexpr std::uint16_t kRobotPushConfigRes = 19300;
|
||||
constexpr std::uint16_t kRobotPush = 19301;
|
||||
constexpr std::uint32_t kMaxFramePayloadBytes = 512U * 1024U * 1024U;
|
||||
|
||||
} // namespace cmvr::device::seer_robokit::protocol
|
||||
|
||||
#endif // CMVR_ES_SEER_ROBOKIT_PROTOCOL_H
|
||||
@ -0,0 +1,92 @@
|
||||
#ifndef CMVR_ES_SEER_ROBOKIT_UTILS_H
|
||||
#define CMVR_ES_SEER_ROBOKIT_UTILS_H
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
namespace cmvr::device::seer_robokit::detail {
|
||||
|
||||
static inline std::string systemError()
|
||||
{
|
||||
return std::strerror(errno);
|
||||
}
|
||||
|
||||
static inline Json::Value& jsonMember(
|
||||
Json::Value& value,
|
||||
const char* key)
|
||||
{
|
||||
return *value.demand(key, key + std::strlen(key));
|
||||
}
|
||||
|
||||
static inline Json::Value& jsonMember(
|
||||
Json::Value& value,
|
||||
const std::string& key)
|
||||
{
|
||||
return *value.demand(key.data(), key.data() + key.size());
|
||||
}
|
||||
|
||||
static inline const Json::Value* jsonFind(
|
||||
const Json::Value& value,
|
||||
const char* key)
|
||||
{
|
||||
return value.find(key, key + std::strlen(key));
|
||||
}
|
||||
|
||||
static inline Json::Value jsonGet(
|
||||
const Json::Value& value,
|
||||
const char* key,
|
||||
const Json::Value& fallback)
|
||||
{
|
||||
const auto* found = jsonFind(value, key);
|
||||
return found ? *found : fallback;
|
||||
}
|
||||
|
||||
static inline double nowSeconds()
|
||||
{
|
||||
const auto now = std::chrono::system_clock::now().time_since_epoch();
|
||||
return std::chrono::duration<double>(now).count();
|
||||
}
|
||||
|
||||
static inline bool jsonHas(
|
||||
const Json::Value& value,
|
||||
const char* key)
|
||||
{
|
||||
return jsonFind(value, key) != nullptr;
|
||||
}
|
||||
|
||||
static inline bool hasNumericControllerRetCode(
|
||||
const Json::Value& response)
|
||||
{
|
||||
const auto* ret_code = jsonFind(response, "ret_code");
|
||||
return ret_code
|
||||
&& (ret_code->isInt()
|
||||
|| ret_code->isUInt()
|
||||
|| ret_code->isInt64()
|
||||
|| ret_code->isUInt64());
|
||||
}
|
||||
|
||||
static inline std::string jsonValueToString(const Json::Value& value)
|
||||
{
|
||||
if (value.isString()) return value.asString();
|
||||
if (value.isBool()) return value.asBool() ? "true" : "false";
|
||||
if (value.isInt64() || value.isInt()) {
|
||||
return std::to_string(value.asInt64());
|
||||
}
|
||||
if (value.isUInt64() || value.isUInt()) {
|
||||
return std::to_string(value.asUInt64());
|
||||
}
|
||||
if (value.isDouble()) return std::to_string(value.asDouble());
|
||||
if (value.isNull()) return {};
|
||||
|
||||
Json::StreamWriterBuilder builder;
|
||||
builder["indentation"] = "";
|
||||
return Json::writeString(builder, value);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::seer_robokit::detail
|
||||
|
||||
#endif // CMVR_ES_SEER_ROBOKIT_UTILS_H
|
||||
175
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_agv.cpp
Normal file
175
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_agv.cpp
Normal file
@ -0,0 +1,175 @@
|
||||
#include "seer_robokit_agv.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kDefaultMapUpdateIntervalMs = 1000;
|
||||
constexpr std::size_t kDefaultMapUpdateHistorySize = 8;
|
||||
|
||||
} // namespace
|
||||
|
||||
SeerRobokitAgv::SeerRobokitAgv(const config::SeerRobokitAgvConfig& cfg)
|
||||
: config_(cfg),
|
||||
ip_(cfg.ip()),
|
||||
control_nick_name_(
|
||||
cfg.control_nick_name().empty()
|
||||
? (cfg.id().empty() ? "cmvr-es" : "cmvr-es:" + cfg.id())
|
||||
: cfg.control_nick_name()),
|
||||
recv_timeout_ms_(cfg.recv_timeout_ms() > 0 ? cfg.recv_timeout_ms() : 1000),
|
||||
state_push_enabled_(cfg.enable_state_push()),
|
||||
map_update_enabled_(cfg.enable_map_update()),
|
||||
map_update_interval_ms_(cfg.map_update_interval_ms() > 0 ? cfg.map_update_interval_ms() : kDefaultMapUpdateIntervalMs),
|
||||
map_update_history_size_(cfg.map_update_history_size() > 0 ? cfg.map_update_history_size() : kDefaultMapUpdateHistorySize)
|
||||
{
|
||||
id_ = cfg.id();
|
||||
if (cfg.port_status() > 0) ports_.status = cfg.port_status();
|
||||
if (cfg.port_control() > 0) ports_.control = cfg.port_control();
|
||||
if (cfg.port_nav() > 0) ports_.navigation = cfg.port_nav();
|
||||
if (cfg.port_config() > 0) ports_.config = cfg.port_config();
|
||||
if (cfg.port_other() > 0) ports_.other = cfg.port_other();
|
||||
if (cfg.port_push() > 0) ports_.push = cfg.port_push();
|
||||
|
||||
const auto result = connect_();
|
||||
if (!result.ok()) {
|
||||
CMVR_LOG(ERROR) << "[SeerRobokitAgv] Auto connect failed"
|
||||
<< ", id=" << id_
|
||||
<< ", ip=" << ip_
|
||||
<< ", error=" << result.message;
|
||||
}
|
||||
}
|
||||
|
||||
SeerRobokitAgv::~SeerRobokitAgv()
|
||||
{
|
||||
(void)disconnect_();
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::init()
|
||||
{
|
||||
return !id_.empty() && !ip_.empty();
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::start()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::stop()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::update()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::connect_()
|
||||
{
|
||||
const auto lifecycle_generation =
|
||||
navigation_generation_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
clearPoseTask_(lifecycle_generation);
|
||||
clearTrackedNavigation_(lifecycle_generation);
|
||||
stopPushThread_();
|
||||
stopMapUpdateThread_();
|
||||
|
||||
{
|
||||
// Status requests may wait for a controller receive timeout without
|
||||
// holding mutex_. Serialize lifecycle changes with that channel before
|
||||
// replacing or closing its descriptor.
|
||||
std::lock_guard<std::mutex> status_io_lock(status_io_mutex_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closeSocket_(sock_status_);
|
||||
closeSocket_(sock_control_);
|
||||
closeSocket_(sock_navigation_);
|
||||
closeSocket_(sock_config_);
|
||||
closeSocket_(sock_other_);
|
||||
closeSocket_(sock_push_);
|
||||
|
||||
if (ip_.empty()) {
|
||||
return AgvResult::failure(AgvErrorCode::InvalidArgument, "SEER Robokit AGV ip is empty");
|
||||
}
|
||||
|
||||
const auto close_all = [this]() {
|
||||
closeSocket_(sock_status_);
|
||||
closeSocket_(sock_control_);
|
||||
closeSocket_(sock_navigation_);
|
||||
closeSocket_(sock_config_);
|
||||
closeSocket_(sock_other_);
|
||||
closeSocket_(sock_push_);
|
||||
};
|
||||
|
||||
if (auto result = connectSocket_(sock_status_, ports_.status); !result.ok()) {
|
||||
close_all();
|
||||
return result;
|
||||
}
|
||||
if (auto result = connectSocket_(sock_control_, ports_.control); !result.ok()) {
|
||||
close_all();
|
||||
return result;
|
||||
}
|
||||
if (auto result = connectSocket_(sock_navigation_, ports_.navigation); !result.ok()) {
|
||||
close_all();
|
||||
return result;
|
||||
}
|
||||
if (auto result = connectSocket_(sock_config_, ports_.config); !result.ok()) {
|
||||
close_all();
|
||||
return result;
|
||||
}
|
||||
|
||||
if (state_push_enabled_) {
|
||||
const auto result = connectSocket_(sock_push_, ports_.push);
|
||||
if (!result.ok()) {
|
||||
CMVR_LOG(ERROR) << "[SeerRobokitAgv] Connect push port failed"
|
||||
<< ", id=" << id_
|
||||
<< ", port=" << ports_.push
|
||||
<< ", error=" << result.message;
|
||||
closeSocket_(sock_push_);
|
||||
}
|
||||
}
|
||||
last_error_.clear();
|
||||
}
|
||||
|
||||
if (state_push_enabled_ && sock_push_ >= 0) {
|
||||
const auto result = configurePush_();
|
||||
if (result.ok()) {
|
||||
startPushThread_();
|
||||
} else {
|
||||
CMVR_LOG(ERROR) << "[SeerRobokitAgv] Configure push failed"
|
||||
<< ", id=" << id_
|
||||
<< ", error=" << result.message;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closeSocket_(sock_push_);
|
||||
}
|
||||
}
|
||||
if (map_update_enabled_) {
|
||||
startMapUpdateThread_();
|
||||
}
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::disconnect_()
|
||||
{
|
||||
const auto lifecycle_generation =
|
||||
navigation_generation_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
clearPoseTask_(lifecycle_generation);
|
||||
clearTrackedNavigation_(lifecycle_generation);
|
||||
stopMapUpdateThread_();
|
||||
stopPushThread_();
|
||||
std::lock_guard<std::mutex> status_io_lock(status_io_mutex_);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closeSocket_(sock_status_);
|
||||
closeSocket_(sock_control_);
|
||||
closeSocket_(sock_navigation_);
|
||||
closeSocket_(sock_config_);
|
||||
closeSocket_(sock_other_);
|
||||
closeSocket_(sock_push_);
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
375
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_control.cpp
Normal file
375
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_control.cpp
Normal file
@ -0,0 +1,375 @@
|
||||
#include "seer_robokit_agv.h"
|
||||
#include "seer_robokit_navigation_utils.h"
|
||||
#include "seer_robokit_protocol.h"
|
||||
#include "seer_robokit_utils.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
using namespace seer_robokit::navigation;
|
||||
using namespace seer_robokit::protocol;
|
||||
using namespace seer_robokit::detail;
|
||||
|
||||
AgvResult SeerRobokitAgv::acquireControl_() const
|
||||
{
|
||||
Json::Value payload(Json::objectValue);
|
||||
jsonMember(payload, "nick_name") = control_nick_name_;
|
||||
|
||||
Json::Value response;
|
||||
auto result = sendCommand_(sock_config_, kRobotConfigLock, payload, &response);
|
||||
return result.ok() ? resultFromResponse_(response) : result;
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::sendControlledCommand_(
|
||||
const int sock,
|
||||
const std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
Json::Value* response,
|
||||
std::uint64_t* accepted_navigation_generation,
|
||||
std::uint64_t* controller_fault_sequence_at_attempt,
|
||||
std::uint64_t* control_attempt_sequence,
|
||||
PoseTaskContext* pose_context_to_publish,
|
||||
const bool reject_if_active_controller_fault,
|
||||
TrackedNavigationContext* navigation_context_to_publish,
|
||||
const bool preserve_tracked_navigation,
|
||||
const std::string* expected_navigation_token,
|
||||
const std::function<bool()>* cancellation_requested,
|
||||
const TrackedNavigationContext* expected_active_navigation) const
|
||||
{
|
||||
const auto canceled_before_send = [cancellation_requested]() {
|
||||
return cancellation_requested
|
||||
&& *cancellation_requested
|
||||
&& (*cancellation_requested)();
|
||||
};
|
||||
if (canceled_before_send()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit command was not sent because the caller canceled the "
|
||||
"operation before control authority was acquired");
|
||||
}
|
||||
|
||||
const auto expected_context_is_current =
|
||||
[this, expected_active_navigation]() {
|
||||
if (!expected_active_navigation) {
|
||||
return true;
|
||||
}
|
||||
TrackedNavigationContext active_context;
|
||||
return currentTrackedNavigation_(active_context)
|
||||
&& active_context.token
|
||||
== expected_active_navigation->token
|
||||
&& active_context.navigation_generation
|
||||
== expected_active_navigation->navigation_generation
|
||||
&& active_context.type
|
||||
== expected_active_navigation->type
|
||||
&& navigation_generation_.load(std::memory_order_relaxed)
|
||||
== expected_active_navigation->navigation_generation;
|
||||
};
|
||||
|
||||
// Conditional cancel ownership checks are deliberately performed without
|
||||
// the control sequencing mutex. A slow 1110/1101 response must never
|
||||
// prevent emergencyStop() from acquiring authority and sending 2000.
|
||||
// The exact local token/generation/type is revalidated under the control
|
||||
// lock both before and after authority acquisition below.
|
||||
if (expected_active_navigation) {
|
||||
if (!expected_context_is_current()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit did not start conditional navigation cancel "
|
||||
"preflight because the tracked task was already replaced or "
|
||||
"ended");
|
||||
}
|
||||
|
||||
std::vector<PoseTaskStatus> statuses;
|
||||
const auto exact_result = queryTaskStatuses_(
|
||||
expected_active_navigation->task_ids,
|
||||
statuses);
|
||||
if (!exact_result.ok()) {
|
||||
return AgvResult::failure(
|
||||
exact_result.code,
|
||||
"SEER Robokit did not send the conditional navigation cancel "
|
||||
"because exact task ownership preflight failed: "
|
||||
+ exact_result.message);
|
||||
}
|
||||
const bool all_exact_tasks_terminal = !statuses.empty()
|
||||
&& std::all_of(
|
||||
statuses.begin(),
|
||||
statuses.end(),
|
||||
[](const PoseTaskStatus& status) {
|
||||
return status.found
|
||||
&& exactTaskStateIsKnownTerminal(status.state);
|
||||
});
|
||||
if (all_exact_tasks_terminal) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
const bool exact_task_still_active = std::any_of(
|
||||
statuses.begin(),
|
||||
statuses.end(),
|
||||
[](const PoseTaskStatus& status) {
|
||||
return status.found
|
||||
&& exactTaskStateIsActive(status.state);
|
||||
});
|
||||
|
||||
NavigationSnapshot snapshot;
|
||||
const auto snapshot_result = queryNavigationSnapshot_(snapshot);
|
||||
if (!snapshot_result.ok()) {
|
||||
return AgvResult::failure(
|
||||
snapshot_result.code,
|
||||
"SEER Robokit did not send the conditional navigation cancel "
|
||||
"because 1101 ownership preflight was unavailable: "
|
||||
+ snapshot_result.message);
|
||||
}
|
||||
const bool global_active =
|
||||
exactTaskStateIsActive(snapshot.task_status);
|
||||
const bool global_type_matches =
|
||||
globalNavigationTaskTypeMatches(
|
||||
expected_active_navigation->type,
|
||||
snapshot.task_type);
|
||||
const bool target_conflicts = global_active
|
||||
&& !snapshot.target_id.empty()
|
||||
&& !expected_active_navigation->target_ids.empty()
|
||||
&& std::find(
|
||||
expected_active_navigation->target_ids.begin(),
|
||||
expected_active_navigation->target_ids.end(),
|
||||
snapshot.target_id)
|
||||
== expected_active_navigation->target_ids.end();
|
||||
if (global_active
|
||||
&& (!global_type_matches
|
||||
|| target_conflicts)) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit did not send the conditional navigation cancel "
|
||||
"because 1101 reports another active task: "
|
||||
+ snapshot.detail);
|
||||
}
|
||||
|
||||
if (!exact_task_still_active) {
|
||||
const bool clearing_path_queue =
|
||||
expected_active_navigation->type
|
||||
== AgvTaskType::FollowPath;
|
||||
const bool terminal_target_matches =
|
||||
expected_active_navigation->type
|
||||
!= AgvTaskType::NavigateToStation
|
||||
|| (!snapshot.target_id.empty()
|
||||
&& snapshot.target_id
|
||||
== expected_active_navigation->target_id);
|
||||
if (globalTaskStateIsKnownTerminal(snapshot.task_status)
|
||||
&& snapshot.task_status != 0
|
||||
&& !clearing_path_queue
|
||||
&& global_type_matches
|
||||
&& terminal_target_matches) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the permission acquisition and the following write ordered with
|
||||
// respect to other control RPCs in this process. Channel I/O serialization
|
||||
// is separate, so this must remain a distinct lock.
|
||||
std::lock_guard<std::mutex> sequence_lock(control_sequence_mutex_);
|
||||
if (expected_navigation_token) {
|
||||
TrackedNavigationContext active_context;
|
||||
const bool has_active_context =
|
||||
currentTrackedNavigation_(active_context);
|
||||
const bool expected_context_matches = expected_active_navigation
|
||||
? (has_active_context
|
||||
&& active_context.token
|
||||
== expected_active_navigation->token
|
||||
&& active_context.navigation_generation
|
||||
== expected_active_navigation->navigation_generation
|
||||
&& active_context.type
|
||||
== expected_active_navigation->type
|
||||
&& navigation_generation_.load(std::memory_order_relaxed)
|
||||
== expected_active_navigation->navigation_generation)
|
||||
: (has_active_context
|
||||
&& active_context.token == *expected_navigation_token);
|
||||
if (!expected_context_matches) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit did not send the conditional navigation cancel "
|
||||
"because the tracked task was already replaced or ended; "
|
||||
"expected_token=" + *expected_navigation_token
|
||||
+ (active_context.token.empty()
|
||||
? std::string(", active_token=<none>")
|
||||
: ", active_token=" + active_context.token));
|
||||
}
|
||||
}
|
||||
const auto attempt_sequence =
|
||||
control_attempt_sequence_.fetch_add(
|
||||
1,
|
||||
std::memory_order_relaxed) + 1;
|
||||
if (control_attempt_sequence) {
|
||||
*control_attempt_sequence = attempt_sequence;
|
||||
}
|
||||
if (pose_context_to_publish) {
|
||||
pose_context_to_publish->control_attempt_sequence_at_start =
|
||||
attempt_sequence;
|
||||
}
|
||||
|
||||
const auto authority = acquireControl_();
|
||||
if (!authority.ok()) {
|
||||
const std::string detail = authority.message.empty() ? "unknown error" : authority.message;
|
||||
return AgvResult::failure(
|
||||
authority.code,
|
||||
"SEER Robokit acquire control authority failed: " + detail);
|
||||
}
|
||||
if (expected_active_navigation && !expected_context_is_current()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit did not send the conditional navigation cancel because "
|
||||
"the tracked token, generation, or type changed while control "
|
||||
"authority was being acquired");
|
||||
}
|
||||
if (canceled_before_send()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit command was not sent because the caller canceled the "
|
||||
"operation while control authority was being acquired");
|
||||
}
|
||||
std::string controller_fault_gate_error;
|
||||
if (controller_fault_sequence_at_attempt
|
||||
|| pose_context_to_publish
|
||||
|| reject_if_active_controller_fault) {
|
||||
std::lock_guard<std::mutex> lock(runtime_state_mutex_);
|
||||
if (controller_fault_sequence_at_attempt) {
|
||||
*controller_fault_sequence_at_attempt =
|
||||
controller_fault_sequence_;
|
||||
}
|
||||
if (pose_context_to_publish) {
|
||||
pose_context_to_publish->controller_fault_sequence_at_start =
|
||||
controller_fault_sequence_;
|
||||
pose_context_to_publish
|
||||
->controller_fault_channel_epoch_at_start =
|
||||
controller_fault_channel_epoch_.load(
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
if (reject_if_active_controller_fault) {
|
||||
if (!state_push_enabled_) {
|
||||
controller_fault_gate_error =
|
||||
"controller fault state is unavailable because state push "
|
||||
"is disabled";
|
||||
} else if (!active_controller_fault_detail_.empty()) {
|
||||
controller_fault_gate_error =
|
||||
"the controller reported a fault or invalid fault state: "
|
||||
+ active_controller_fault_detail_;
|
||||
} else if (!controller_fault_state_observed_) {
|
||||
controller_fault_gate_error =
|
||||
"no state push containing fatals/errors has been observed";
|
||||
} else {
|
||||
const auto fault_state_age =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now()
|
||||
- controller_fault_state_observed_at_)
|
||||
.count();
|
||||
if (fault_state_age > controllerFaultStateMaxAgeMs_()) {
|
||||
controller_fault_gate_error =
|
||||
"the most recent fatals/errors state push is stale "
|
||||
"(age_ms=" + std::to_string(fault_state_age)
|
||||
+ ", max_age_ms="
|
||||
+ std::to_string(controllerFaultStateMaxAgeMs_())
|
||||
+ ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!controller_fault_gate_error.empty()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::Fault,
|
||||
"SEER Robokit free-navigation command was not sent because "
|
||||
+ controller_fault_gate_error);
|
||||
}
|
||||
if (canceled_before_send()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit command was not sent because the caller canceled the "
|
||||
"operation before the controller command write");
|
||||
}
|
||||
if (canceled_before_send()) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::TaskCanceled,
|
||||
"SEER Robokit command was not sent because the caller canceled the "
|
||||
"operation immediately before the controller command write");
|
||||
}
|
||||
const auto publish_navigation_generation =
|
||||
[this,
|
||||
accepted_navigation_generation,
|
||||
pose_context_to_publish,
|
||||
navigation_context_to_publish,
|
||||
preserve_tracked_navigation]() {
|
||||
const auto generation =
|
||||
navigation_generation_.fetch_add(
|
||||
1,
|
||||
std::memory_order_relaxed) + 1;
|
||||
*accepted_navigation_generation = generation;
|
||||
if (pose_context_to_publish) {
|
||||
pose_context_to_publish->navigation_generation = generation;
|
||||
rememberPoseTask_(*pose_context_to_publish);
|
||||
}
|
||||
if (navigation_context_to_publish) {
|
||||
navigation_context_to_publish->navigation_generation =
|
||||
generation;
|
||||
navigation_context_to_publish->accepted_at =
|
||||
std::chrono::steady_clock::now();
|
||||
rememberTrackedNavigation_(
|
||||
*navigation_context_to_publish);
|
||||
} else if (preserve_tracked_navigation) {
|
||||
advanceTrackedNavigationGeneration_(generation);
|
||||
} else {
|
||||
clearTrackedNavigation_(generation);
|
||||
}
|
||||
};
|
||||
CommandTransmissionState transmission_state =
|
||||
CommandTransmissionState::NotSent;
|
||||
auto result = sendCommand_(
|
||||
sock,
|
||||
command,
|
||||
payload,
|
||||
response,
|
||||
&transmission_state);
|
||||
if (!result.ok()) {
|
||||
if (accepted_navigation_generation
|
||||
&& transmission_state
|
||||
== CommandTransmissionState::PossiblySent) {
|
||||
// Once the control write has been attempted, a timeout, disconnect,
|
||||
// wrong response opcode, or malformed JSON cannot prove rejection:
|
||||
// the controller may already have executed the command.
|
||||
publish_navigation_generation();
|
||||
return withUnknownControllerOutcome(std::move(result));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (!accepted_navigation_generation) {
|
||||
return result;
|
||||
}
|
||||
if (!response) {
|
||||
publish_navigation_generation();
|
||||
return withUnknownControllerOutcome(AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit cannot confirm navigation command without a response"));
|
||||
}
|
||||
if (!hasNumericControllerRetCode(*response)) {
|
||||
publish_navigation_generation();
|
||||
return withUnknownControllerOutcome(resultFromResponse_(*response));
|
||||
}
|
||||
result = resultFromResponse_(*response);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Advance only after the controller accepted the command, and do it before
|
||||
// releasing control_sequence_mutex_. This prevents a failed cancel/pause or
|
||||
// failed authority acquisition from falsely reporting a pose task canceled,
|
||||
// while preserving the controller's actual command order under concurrency.
|
||||
publish_navigation_generation();
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
1047
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_map.cpp
Normal file
1047
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_map.cpp
Normal file
File diff suppressed because it is too large
Load Diff
1543
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_navigation.cpp
Normal file
1543
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_navigation.cpp
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
725
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_status.cpp
Normal file
725
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_status.cpp
Normal file
@ -0,0 +1,725 @@
|
||||
#include "seer_robokit_agv.h"
|
||||
#include "seer_robokit_protocol.h"
|
||||
#include "seer_robokit_utils.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <thread>
|
||||
|
||||
#include <google/protobuf/repeated_ptr_field.h>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
using namespace seer_robokit::protocol;
|
||||
using namespace seer_robokit::detail;
|
||||
|
||||
namespace {
|
||||
|
||||
bool hasFaultArray(const Json::Value& value, const char* key)
|
||||
{
|
||||
const auto* found = jsonFind(value, key);
|
||||
return found && found->isArray() && !found->empty();
|
||||
}
|
||||
|
||||
void appendStringArray(Json::Value& value, const char* key, const google::protobuf::RepeatedPtrField<std::string>& strings)
|
||||
{
|
||||
if (strings.empty()) {
|
||||
return;
|
||||
}
|
||||
Json::Value array(Json::arrayValue);
|
||||
for (const auto& item : strings) {
|
||||
array.append(item);
|
||||
}
|
||||
jsonMember(value, key) = array;
|
||||
}
|
||||
|
||||
AgvMode modeFromTaskState(const int state)
|
||||
{
|
||||
switch (state) {
|
||||
case 2:
|
||||
return AgvMode::Auto;
|
||||
case 3:
|
||||
return AgvMode::Paused;
|
||||
case 5:
|
||||
return AgvMode::Fault;
|
||||
case 6:
|
||||
return AgvMode::Stopped;
|
||||
default:
|
||||
return AgvMode::Idle;
|
||||
}
|
||||
}
|
||||
|
||||
AgvTaskState toTaskState(const int value)
|
||||
{
|
||||
switch (value) {
|
||||
case 1:
|
||||
return AgvTaskState::Waiting;
|
||||
case 2:
|
||||
return AgvTaskState::Running;
|
||||
case 3:
|
||||
return AgvTaskState::Paused;
|
||||
case 4:
|
||||
return AgvTaskState::Completed;
|
||||
case 5:
|
||||
case 7:
|
||||
return AgvTaskState::Failed;
|
||||
case 6:
|
||||
return AgvTaskState::Canceled;
|
||||
case 0:
|
||||
default:
|
||||
return AgvTaskState::None;
|
||||
}
|
||||
}
|
||||
|
||||
AgvTaskType toTaskType(const int value)
|
||||
{
|
||||
switch (value) {
|
||||
case 1:
|
||||
return AgvTaskType::NavigateToPose;
|
||||
case 2:
|
||||
return AgvTaskType::NavigateToStation;
|
||||
case 3:
|
||||
return AgvTaskType::FollowPath;
|
||||
case 100:
|
||||
return AgvTaskType::Custom;
|
||||
default:
|
||||
return AgvTaskType::None;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
AgvRuntimeState SeerRobokitAgv::runtimeState() const
|
||||
{
|
||||
AgvRuntimeState cached_state;
|
||||
bool has_cached_state = false;
|
||||
if (state_push_enabled_) {
|
||||
std::lock_guard<std::mutex> lock(runtime_state_mutex_);
|
||||
if (cached_runtime_state_valid_) {
|
||||
cached_state = cached_runtime_state_;
|
||||
has_cached_state = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (has_cached_state) {
|
||||
std::string adapter_error;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
cached_state.connected = connected_();
|
||||
adapter_error = last_error_;
|
||||
}
|
||||
if (!adapter_error.empty()) {
|
||||
if (cached_state.last_error.empty()) {
|
||||
cached_state.last_error = adapter_error;
|
||||
} else if (cached_state.last_error != adapter_error) {
|
||||
cached_state.last_error += "; adapter_error=" + adapter_error;
|
||||
}
|
||||
}
|
||||
if (!cached_state.connected) {
|
||||
cached_state.mode = AgvMode::Disconnected;
|
||||
}
|
||||
return cached_state;
|
||||
}
|
||||
|
||||
return queryRuntimeState_();
|
||||
}
|
||||
|
||||
AgvRuntimeState SeerRobokitAgv::queryRuntimeState_() const
|
||||
{
|
||||
AgvRuntimeState state;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
state.connected = connected_();
|
||||
state.last_error = last_error_;
|
||||
}
|
||||
state.mode = state.connected ? AgvMode::Idle : AgvMode::Disconnected;
|
||||
|
||||
Json::Value loc;
|
||||
if (sendCommand_(sock_status_, kRobotStatusLoc, Json::Value(Json::objectValue), &loc).ok()) {
|
||||
state.pose.x = jsonGet(loc, "x", 0.0).asDouble();
|
||||
state.pose.y = jsonGet(loc, "y", 0.0).asDouble();
|
||||
state.pose.theta = jsonGet(loc, "angle", 0.0).asDouble();
|
||||
state.localized = jsonGet(loc, "confidence", 0.0).asDouble() > 0.0;
|
||||
state.current_station = jsonGet(loc, "current_station", "").asString();
|
||||
}
|
||||
|
||||
Json::Value battery;
|
||||
if (sendCommand_(sock_status_, kRobotStatusBattery, Json::Value(Json::objectValue), &battery).ok()) {
|
||||
state.battery.percentage = jsonGet(battery, "battery_level", 0.0).asDouble();
|
||||
state.battery.temperature = jsonGet(battery, "battery_temp", 0.0).asDouble();
|
||||
state.battery.charging = jsonGet(battery, "charging", false).asBool();
|
||||
state.battery.voltage = jsonGet(battery, "voltage", 0.0).asDouble();
|
||||
state.battery.current = jsonGet(battery, "current", 0.0).asDouble();
|
||||
}
|
||||
|
||||
Json::Value map;
|
||||
if (sendCommand_(sock_status_, kRobotStatusMap, Json::Value(Json::objectValue), &map).ok()) {
|
||||
state.current_map = jsonGet(map, "current_map", "").asString();
|
||||
}
|
||||
|
||||
const auto nav = navigationStatus();
|
||||
state.moving = nav.state == AgvTaskState::Running;
|
||||
state.fault = nav.state == AgvTaskState::Failed;
|
||||
state.mode = state.fault ? AgvMode::Fault : modeFromTaskState(static_cast<int>(nav.state));
|
||||
return state;
|
||||
}
|
||||
|
||||
AgvNavigationStatus SeerRobokitAgv::navigationStatus() const
|
||||
{
|
||||
AgvNavigationStatus status;
|
||||
std::string missing_pose_task_detail;
|
||||
for (int attempt = 0; attempt < 2; ++attempt) {
|
||||
PoseTaskContext pose_context;
|
||||
if (!currentPoseTask_(pose_context)) {
|
||||
break;
|
||||
}
|
||||
const auto observed_navigation_generation =
|
||||
navigation_generation_.load(std::memory_order_relaxed);
|
||||
if (pose_context.navigation_generation
|
||||
!= observed_navigation_generation) {
|
||||
continue;
|
||||
}
|
||||
|
||||
PoseTaskStatus task_status;
|
||||
const auto result = queryPoseTaskStatus_(pose_context.task_id, task_status);
|
||||
PoseTaskContext latest_context;
|
||||
if (navigation_generation_.load(std::memory_order_relaxed)
|
||||
!= observed_navigation_generation
|
||||
|| !currentPoseTask_(latest_context)
|
||||
|| latest_context.navigation_generation
|
||||
!= pose_context.navigation_generation
|
||||
|| latest_context.task_id != pose_context.task_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
status.type = AgvTaskType::NavigateToPose;
|
||||
const auto fault_monitoring_unavailable =
|
||||
[this, &pose_context]() {
|
||||
if (controller_fault_channel_epoch_.load(
|
||||
std::memory_order_relaxed)
|
||||
!= pose_context
|
||||
.controller_fault_channel_epoch_at_start) {
|
||||
return std::string(
|
||||
"the controller fault push channel changed or was "
|
||||
"invalidated after the free-navigation command was "
|
||||
"accepted");
|
||||
}
|
||||
return freeNavigationFaultStateUnavailableDetail_();
|
||||
};
|
||||
if (!result.ok()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message = result.message;
|
||||
return status;
|
||||
}
|
||||
if (!task_status.found || task_status.state == 404) {
|
||||
std::uint64_t missing_task_fault_control_attempt = 0;
|
||||
const std::string missing_task_fault =
|
||||
cachedControllerFaultDetail_(
|
||||
pose_context.controller_fault_sequence_at_start,
|
||||
controllerFaultCaptureGraceMs_(),
|
||||
&missing_task_fault_control_attempt);
|
||||
PoseTaskContext post_missing_context;
|
||||
if (navigation_generation_.load(std::memory_order_relaxed)
|
||||
!= observed_navigation_generation
|
||||
|| !currentPoseTask_(post_missing_context)
|
||||
|| post_missing_context.navigation_generation
|
||||
!= pose_context.navigation_generation
|
||||
|| post_missing_context.task_id != pose_context.task_id) {
|
||||
continue;
|
||||
}
|
||||
if (!missing_task_fault.empty()) {
|
||||
std::string attribution;
|
||||
if (missing_task_fault_control_attempt != 0
|
||||
&& missing_task_fault_control_attempt
|
||||
!= pose_context.control_attempt_sequence_at_start) {
|
||||
attribution =
|
||||
"controller_fault_attribution=ambiguous because the "
|
||||
"fault was observed after another control command "
|
||||
"attempt had begun, ";
|
||||
}
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit tracked free-navigation task disappeared from "
|
||||
"1110 task_status_package while a new controller fault "
|
||||
"was observed: " + task_status.detail + ", "
|
||||
+ attribution + missing_task_fault;
|
||||
clearPoseTask_(pose_context.navigation_generation);
|
||||
return status;
|
||||
}
|
||||
if (const std::string unavailable =
|
||||
fault_monitoring_unavailable();
|
||||
!unavailable.empty()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit tracked free-navigation status is unsafe to "
|
||||
"accept because controller fault monitoring is "
|
||||
"unavailable: " + unavailable
|
||||
+ "; query the controller and cancel or stop before "
|
||||
"another motion command";
|
||||
return status;
|
||||
}
|
||||
missing_pose_task_detail = task_status.detail;
|
||||
clearPoseTask_(pose_context.navigation_generation);
|
||||
break;
|
||||
}
|
||||
if (task_status.type_present && task_status.type != 1) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.type = toTaskType(task_status.type);
|
||||
status.message =
|
||||
"SEER Robokit returned an unexpected task type for the tracked "
|
||||
"free-navigation task: " + task_status.detail;
|
||||
clearPoseTask_(pose_context.navigation_generation);
|
||||
return status;
|
||||
}
|
||||
status.state = toTaskState(task_status.state);
|
||||
status.progress = task_status.progress;
|
||||
status.message = task_status.detail;
|
||||
const auto controller_reported_state = status.state;
|
||||
const bool controller_state_terminal =
|
||||
controller_reported_state == AgvTaskState::Completed
|
||||
|| controller_reported_state == AgvTaskState::Failed
|
||||
|| controller_reported_state == AgvTaskState::Canceled;
|
||||
std::uint64_t fault_control_attempt = 0;
|
||||
const std::string fault = cachedControllerFaultDetail_(
|
||||
pose_context.controller_fault_sequence_at_start,
|
||||
controller_reported_state == AgvTaskState::Completed
|
||||
|| controller_reported_state == AgvTaskState::Failed
|
||||
? controllerFaultCaptureGraceMs_()
|
||||
: 0,
|
||||
&fault_control_attempt);
|
||||
PoseTaskContext post_fault_context;
|
||||
if (navigation_generation_.load(std::memory_order_relaxed)
|
||||
!= observed_navigation_generation
|
||||
|| !currentPoseTask_(post_fault_context)
|
||||
|| post_fault_context.navigation_generation
|
||||
!= pose_context.navigation_generation
|
||||
|| post_fault_context.task_id != pose_context.task_id) {
|
||||
continue;
|
||||
}
|
||||
const std::string unavailable =
|
||||
fault_monitoring_unavailable();
|
||||
if (!fault.empty()) {
|
||||
std::string attribution;
|
||||
if (fault_control_attempt != 0
|
||||
&& fault_control_attempt
|
||||
!= pose_context.control_attempt_sequence_at_start) {
|
||||
attribution =
|
||||
"controller_fault_attribution=ambiguous because the "
|
||||
"fault was observed after another control command "
|
||||
"attempt had begun, ";
|
||||
}
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit reported a new controller fault while the tracked "
|
||||
"free-navigation task had controller_task_state="
|
||||
+ std::to_string(task_status.state) + ": "
|
||||
+ task_status.detail + ", " + attribution + fault;
|
||||
if (!unavailable.empty()) {
|
||||
status.message +=
|
||||
", controller_fault_monitoring_unavailable="
|
||||
+ unavailable;
|
||||
}
|
||||
} else if (!unavailable.empty()) {
|
||||
if (controller_reported_state == AgvTaskState::Failed
|
||||
|| controller_reported_state == AgvTaskState::Canceled) {
|
||||
status.message +=
|
||||
", controller_fault_monitoring_unavailable="
|
||||
+ unavailable;
|
||||
} else {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit tracked free-navigation state is unsafe to accept "
|
||||
"because controller fault monitoring became unavailable: "
|
||||
+ unavailable
|
||||
+ "; query the controller and cancel or stop before "
|
||||
"another motion command";
|
||||
return status;
|
||||
}
|
||||
}
|
||||
if (status.state == AgvTaskState::Completed) {
|
||||
std::string pose_detail;
|
||||
const bool target_reached =
|
||||
poseTargetReached_(pose_context, pose_detail);
|
||||
PoseTaskContext post_pose_context;
|
||||
if (navigation_generation_.load(std::memory_order_relaxed)
|
||||
!= observed_navigation_generation
|
||||
|| !currentPoseTask_(post_pose_context)
|
||||
|| post_pose_context.navigation_generation
|
||||
!= pose_context.navigation_generation
|
||||
|| post_pose_context.task_id != pose_context.task_id) {
|
||||
continue;
|
||||
}
|
||||
std::uint64_t post_pose_fault_control_attempt = 0;
|
||||
const std::string post_pose_fault =
|
||||
cachedControllerFaultDetail_(
|
||||
pose_context.controller_fault_sequence_at_start,
|
||||
0,
|
||||
&post_pose_fault_control_attempt);
|
||||
if (!post_pose_fault.empty()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
std::string attribution;
|
||||
if (post_pose_fault_control_attempt != 0
|
||||
&& post_pose_fault_control_attempt
|
||||
!= pose_context
|
||||
.control_attempt_sequence_at_start) {
|
||||
attribution =
|
||||
"controller_fault_attribution=ambiguous because the "
|
||||
"fault was observed after another control command "
|
||||
"attempt had begun, ";
|
||||
}
|
||||
status.message =
|
||||
"SEER Robokit reported the tracked free-navigation task "
|
||||
"Completed, but a new controller fault was observed during "
|
||||
"target verification: " + task_status.detail + ", "
|
||||
+ attribution + post_pose_fault;
|
||||
} else if (const std::string post_pose_unavailable =
|
||||
fault_monitoring_unavailable();
|
||||
!post_pose_unavailable.empty()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit tracked free-navigation completion is unsafe to "
|
||||
"accept because controller fault monitoring became "
|
||||
"unavailable: " + post_pose_unavailable
|
||||
+ "; query the controller and cancel or stop before "
|
||||
"another motion command";
|
||||
return status;
|
||||
} else if (!target_reached) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message =
|
||||
"SEER Robokit reported the tracked free-navigation task "
|
||||
"Completed, but the requested target was not reached: "
|
||||
+ task_status.detail + ", " + pose_detail;
|
||||
} else {
|
||||
status.message += ", target_verified: " + pose_detail;
|
||||
}
|
||||
}
|
||||
if (controller_state_terminal) {
|
||||
clearPoseTask_(pose_context.navigation_generation);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
PoseTaskContext changed_context;
|
||||
if (currentPoseTask_(changed_context)) {
|
||||
status.state = AgvTaskState::Waiting;
|
||||
status.type = AgvTaskType::NavigateToPose;
|
||||
status.message =
|
||||
"SEER Robokit free-navigation task changed while its status was being "
|
||||
"queried; query navigation status again";
|
||||
return status;
|
||||
}
|
||||
|
||||
Json::Value payload(Json::objectValue);
|
||||
jsonMember(payload, "simple") = false;
|
||||
|
||||
Json::Value response;
|
||||
const auto result = sendCommand_(sock_status_, kRobotStatusTask, payload, &response);
|
||||
if (!result.ok()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message = missing_pose_task_detail.empty()
|
||||
? result.message
|
||||
: missing_pose_task_detail + "; 1020 status query failed: "
|
||||
+ result.message;
|
||||
return status;
|
||||
}
|
||||
const auto controller_result = resultFromResponse_(response);
|
||||
if (!controller_result.ok()) {
|
||||
status.state = AgvTaskState::Failed;
|
||||
status.message = missing_pose_task_detail.empty()
|
||||
? controller_result.message
|
||||
: missing_pose_task_detail + "; 1020 status query failed: "
|
||||
+ controller_result.message;
|
||||
return status;
|
||||
}
|
||||
|
||||
status.state = toTaskState(jsonGet(response, "task_status", 0).asInt());
|
||||
status.type = toTaskType(jsonGet(response, "task_type", 0).asInt());
|
||||
status.message = jsonGet(response, "move_status_info", jsonGet(response, "err_msg", "")).asString();
|
||||
if (!missing_pose_task_detail.empty()) {
|
||||
status.message = missing_pose_task_detail
|
||||
+ "; fallback_1020_status=" + std::to_string(
|
||||
jsonGet(response, "task_status", 0).asInt())
|
||||
+ ", fallback_1020_type=" + std::to_string(
|
||||
jsonGet(response, "task_type", 0).asInt())
|
||||
+ (status.message.empty() ? std::string{} : ", " + status.message);
|
||||
}
|
||||
if (const auto* task_status_package = jsonFind(response, "task_status_package")) {
|
||||
status.progress = jsonGet(*task_status_package, "percentage", 0.0).asDouble();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::configurePush_()
|
||||
{
|
||||
if (config_.state_push_included_fields_size() > 0 && config_.state_push_excluded_fields_size() > 0) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::InvalidArgument,
|
||||
"SEER Robokit push included_fields and excluded_fields cannot both be set");
|
||||
}
|
||||
|
||||
Json::Value payload(Json::objectValue);
|
||||
if (config_.state_push_interval_ms() > 0) {
|
||||
jsonMember(payload, "interval") = config_.state_push_interval_ms();
|
||||
}
|
||||
appendStringArray(payload, "included_fields", config_.state_push_included_fields());
|
||||
appendStringArray(payload, "excluded_fields", config_.state_push_excluded_fields());
|
||||
|
||||
if (payload.empty()) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
const std::string payload_text = toJsonString_(payload);
|
||||
const auto frame = buildFrame_(kRobotPushConfigReq, payload_text);
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sock_push_ < 0) {
|
||||
return AgvResult::failure(AgvErrorCode::NotConnected, "SEER Robokit push socket not connected");
|
||||
}
|
||||
if (::send(sock_push_, frame.data(), frame.size(), MSG_NOSIGNAL) != static_cast<ssize_t>(frame.size())) {
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, "SEER Robokit send push config failed: " + systemError());
|
||||
}
|
||||
|
||||
while (true) {
|
||||
std::uint16_t command = 0;
|
||||
std::string response_payload;
|
||||
const auto result = receiveFrame_(sock_push_, command, response_payload);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Json::Value response;
|
||||
std::string error;
|
||||
if (!response_payload.empty() && !parseJson_(response_payload, response, error)) {
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, error);
|
||||
}
|
||||
|
||||
if (command == kRobotPushConfigRes) {
|
||||
return resultFromResponse_(response);
|
||||
}
|
||||
if (command == kRobotPush && response.isObject()) {
|
||||
updateCachedRuntimeState_(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::startPushThread_()
|
||||
{
|
||||
if (!state_push_enabled_) {
|
||||
return;
|
||||
}
|
||||
if (push_running_.exchange(true)) {
|
||||
return;
|
||||
}
|
||||
if (sock_push_ < 0) {
|
||||
push_running_ = false;
|
||||
return;
|
||||
}
|
||||
push_thread_ = std::thread(&SeerRobokitAgv::pushLoop_, this);
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::stopPushThread_()
|
||||
{
|
||||
const bool was_running = push_running_.exchange(false);
|
||||
if (was_running) {
|
||||
int sock = -1;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sock = sock_push_;
|
||||
}
|
||||
if (sock >= 0) {
|
||||
::shutdown(sock, SHUT_RDWR);
|
||||
}
|
||||
}
|
||||
if (push_thread_.joinable()) {
|
||||
push_thread_.join();
|
||||
}
|
||||
invalidateControllerFaultState_();
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::pushLoop_()
|
||||
{
|
||||
while (push_running_) {
|
||||
int sock = -1;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sock = sock_push_;
|
||||
}
|
||||
if (sock < 0) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
continue;
|
||||
}
|
||||
|
||||
std::uint16_t command = 0;
|
||||
std::string payload;
|
||||
const auto result = receiveFrame_(sock, command, payload);
|
||||
if (!push_running_) {
|
||||
break;
|
||||
}
|
||||
if (!result.ok()) {
|
||||
if (result.code != AgvErrorCode::Timeout) {
|
||||
invalidateControllerFaultState_();
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
last_error_ = result.message;
|
||||
closeSocket_(sock_push_);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (command != kRobotPush || payload.empty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Json::Value parsed;
|
||||
std::string error;
|
||||
if (!parseJson_(payload, parsed, error)) {
|
||||
invalidateControllerFaultState_();
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
last_error_ = error;
|
||||
continue;
|
||||
}
|
||||
updateCachedRuntimeState_(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::invalidateControllerFaultState_()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(runtime_state_mutex_);
|
||||
controller_fault_channel_epoch_.fetch_add(
|
||||
1,
|
||||
std::memory_order_relaxed);
|
||||
controller_fault_state_observed_ = false;
|
||||
controller_fault_state_observed_at_ = {};
|
||||
active_controller_fault_detail_.clear();
|
||||
runtime_state_cv_.notify_all();
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::updateCachedRuntimeState_(const Json::Value& payload)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(runtime_state_mutex_);
|
||||
auto state = cached_runtime_state_valid_ ? cached_runtime_state_ : AgvRuntimeState{};
|
||||
state.timestamp = nowSeconds();
|
||||
state.connected = true;
|
||||
|
||||
if (jsonHas(payload, "x")) state.pose.x = jsonGet(payload, "x", state.pose.x).asDouble();
|
||||
if (jsonHas(payload, "y")) state.pose.y = jsonGet(payload, "y", state.pose.y).asDouble();
|
||||
if (jsonHas(payload, "angle")) state.pose.theta = jsonGet(payload, "angle", state.pose.theta).asDouble();
|
||||
if (jsonHas(payload, "vx")) state.velocity.vx = jsonGet(payload, "vx", state.velocity.vx).asDouble();
|
||||
if (jsonHas(payload, "vy")) state.velocity.vy = jsonGet(payload, "vy", state.velocity.vy).asDouble();
|
||||
if (jsonHas(payload, "w")) state.velocity.wz = jsonGet(payload, "w", state.velocity.wz).asDouble();
|
||||
if (jsonHas(payload, "battery_level")) {
|
||||
state.battery.percentage = jsonGet(payload, "battery_level", state.battery.percentage).asDouble();
|
||||
}
|
||||
if (jsonHas(payload, "battery_temp")) {
|
||||
state.battery.temperature = jsonGet(payload, "battery_temp", state.battery.temperature).asDouble();
|
||||
}
|
||||
if (jsonHas(payload, "charging")) {
|
||||
state.battery.charging = jsonGet(payload, "charging", state.battery.charging).asBool();
|
||||
}
|
||||
if (jsonHas(payload, "voltage")) {
|
||||
state.battery.voltage = jsonGet(payload, "voltage", state.battery.voltage).asDouble();
|
||||
}
|
||||
if (jsonHas(payload, "current")) {
|
||||
state.battery.current = jsonGet(payload, "current", state.battery.current).asDouble();
|
||||
}
|
||||
if (jsonHas(payload, "current_map")) {
|
||||
state.current_map = jsonGet(payload, "current_map", state.current_map).asString();
|
||||
}
|
||||
if (jsonHas(payload, "current_station")) {
|
||||
state.current_station = jsonGet(payload, "current_station", state.current_station).asString();
|
||||
}
|
||||
if (jsonHas(payload, "confidence")) {
|
||||
state.localized = jsonGet(payload, "confidence", 0.0).asDouble() > 0.0;
|
||||
}
|
||||
if (jsonHas(payload, "emergency")) {
|
||||
state.emergency_stopped = jsonGet(payload, "emergency", state.emergency_stopped).asBool();
|
||||
}
|
||||
|
||||
state.moving = std::hypot(state.velocity.vx, state.velocity.vy) > 1e-4 || std::abs(state.velocity.wz) > 1e-4;
|
||||
const bool has_fatals = jsonHas(payload, "fatals");
|
||||
const bool has_errors = jsonHas(payload, "errors");
|
||||
const bool has_fault_fields = has_fatals || has_errors;
|
||||
if (has_fault_fields) {
|
||||
const auto* fatals = jsonFind(payload, "fatals");
|
||||
const auto* errors = jsonFind(payload, "errors");
|
||||
const bool valid_fatals = !has_fatals
|
||||
|| (fatals && fatals->isArray());
|
||||
const bool valid_errors = !has_errors
|
||||
|| (errors && errors->isArray());
|
||||
const bool complete_fault_state =
|
||||
has_fatals && has_errors && valid_fatals && valid_errors;
|
||||
if (complete_fault_state) {
|
||||
controller_fault_state_observed_ = true;
|
||||
controller_fault_state_observed_at_ =
|
||||
std::chrono::steady_clock::now();
|
||||
} else {
|
||||
controller_fault_state_observed_ = false;
|
||||
controller_fault_state_observed_at_ = {};
|
||||
}
|
||||
|
||||
const bool reported_fault =
|
||||
hasFaultArray(payload, "fatals")
|
||||
|| hasFaultArray(payload, "errors");
|
||||
const bool invalid_or_incomplete_fault_state =
|
||||
!complete_fault_state && !reported_fault;
|
||||
state.fault = reported_fault
|
||||
|| invalid_or_incomplete_fault_state;
|
||||
if (state.fault) {
|
||||
std::ostringstream detail;
|
||||
detail << (reported_fault
|
||||
? "SEER Robokit controller fault"
|
||||
: "SEER Robokit controller fault state is incomplete or malformed");
|
||||
if (fatals
|
||||
&& (!fatals->isArray()
|
||||
|| !fatals->empty()
|
||||
|| !complete_fault_state)) {
|
||||
detail << ": fatals="
|
||||
<< (fatals->isNull()
|
||||
? std::string("null")
|
||||
: jsonValueToString(*fatals));
|
||||
}
|
||||
if (errors
|
||||
&& (!errors->isArray()
|
||||
|| !errors->empty()
|
||||
|| !complete_fault_state)) {
|
||||
detail << ": errors="
|
||||
<< (errors->isNull()
|
||||
? std::string("null")
|
||||
: jsonValueToString(*errors));
|
||||
}
|
||||
state.last_error = detail.str();
|
||||
if (state.last_error != active_controller_fault_detail_) {
|
||||
active_controller_fault_detail_ = state.last_error;
|
||||
++controller_fault_sequence_;
|
||||
last_controller_fault_timestamp_ = state.timestamp;
|
||||
last_controller_fault_detail_ = state.last_error;
|
||||
last_controller_fault_control_attempt_ =
|
||||
control_attempt_sequence_.load(
|
||||
std::memory_order_acquire);
|
||||
}
|
||||
} else {
|
||||
state.last_error.clear();
|
||||
active_controller_fault_detail_.clear();
|
||||
}
|
||||
}
|
||||
if (state.emergency_stopped) {
|
||||
state.mode = AgvMode::EmergencyStop;
|
||||
} else if (state.fault) {
|
||||
state.mode = AgvMode::Fault;
|
||||
} else if (state.battery.charging) {
|
||||
state.mode = AgvMode::Charging;
|
||||
} else if (state.moving) {
|
||||
state.mode = AgvMode::Auto;
|
||||
} else {
|
||||
state.mode = AgvMode::Idle;
|
||||
}
|
||||
|
||||
cached_runtime_state_ = state;
|
||||
cached_runtime_state_valid_ = true;
|
||||
runtime_state_cv_.notify_all();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
362
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_transport.cpp
Normal file
362
cmvr-es/devices/agv/seer_robokit/src/seer_robokit_transport.cpp
Normal file
@ -0,0 +1,362 @@
|
||||
#include "seer_robokit_agv.h"
|
||||
#include "seer_robokit_protocol.h"
|
||||
#include "seer_robokit_utils.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <arpa/inet.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
using namespace seer_robokit::protocol;
|
||||
using namespace seer_robokit::detail;
|
||||
|
||||
AgvResult SeerRobokitAgv::connectSocket_(int& sock, const int port)
|
||||
{
|
||||
sock = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sock < 0) {
|
||||
last_error_ = "create socket failed: " + systemError();
|
||||
return AgvResult::failure(AgvErrorCode::ConnectionFailed, last_error_);
|
||||
}
|
||||
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_port = htons(static_cast<std::uint16_t>(port));
|
||||
if (::inet_pton(AF_INET, ip_.c_str(), &address.sin_addr) <= 0) {
|
||||
closeSocket_(sock);
|
||||
last_error_ = "invalid SEER Robokit ip: " + ip_;
|
||||
return AgvResult::failure(AgvErrorCode::InvalidArgument, last_error_);
|
||||
}
|
||||
|
||||
if (::connect(sock, reinterpret_cast<sockaddr*>(&address), sizeof(address)) < 0) {
|
||||
closeSocket_(sock);
|
||||
last_error_ = "connect SEER Robokit port " + std::to_string(port) + " failed: " + systemError();
|
||||
return AgvResult::failure(AgvErrorCode::ConnectionFailed, last_error_);
|
||||
}
|
||||
|
||||
timeval timeout{};
|
||||
timeout.tv_sec = recv_timeout_ms_ / 1000;
|
||||
timeout.tv_usec = (recv_timeout_ms_ % 1000) * 1000;
|
||||
::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::ensureOtherSocket_()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sock_other_ >= 0) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
return connectSocket_(sock_other_, ports_.other);
|
||||
}
|
||||
|
||||
void SeerRobokitAgv::closeSocket_(int& sock) const
|
||||
{
|
||||
if (sock >= 0) {
|
||||
::close(sock);
|
||||
sock = -1;
|
||||
}
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::connected_() const
|
||||
{
|
||||
return sock_status_ >= 0 && sock_control_ >= 0 && sock_navigation_ >= 0 && sock_config_ >= 0;
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::sendCommand_(
|
||||
const int sock,
|
||||
const std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
Json::Value* response,
|
||||
CommandTransmissionState* transmission_state) const
|
||||
{
|
||||
std::string response_payload;
|
||||
auto result = sendCommandRaw_(
|
||||
sock,
|
||||
command,
|
||||
payload,
|
||||
&response_payload,
|
||||
transmission_state);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
if (!response) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
Json::Value parsed;
|
||||
std::string error;
|
||||
if (!parseJson_(response_payload, parsed, error)) {
|
||||
const std::string json_text = extractJson_(response_payload);
|
||||
if (json_text.empty() || !parseJson_(json_text, parsed, error)) {
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, error);
|
||||
}
|
||||
}
|
||||
|
||||
*response = std::move(parsed);
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::sendCommandRaw_(
|
||||
const int sock,
|
||||
const std::uint16_t command,
|
||||
const Json::Value& payload,
|
||||
std::string* response_payload,
|
||||
CommandTransmissionState* transmission_state) const
|
||||
{
|
||||
if (transmission_state) {
|
||||
*transmission_state = CommandTransmissionState::NotSent;
|
||||
}
|
||||
const auto exchange = [&]() {
|
||||
const std::string payload_text = payload.empty() ? std::string{} : toJsonString_(payload);
|
||||
const auto frame = buildFrame_(command, payload_text);
|
||||
const auto sent = ::send(
|
||||
sock,
|
||||
frame.data(),
|
||||
frame.size(),
|
||||
MSG_NOSIGNAL);
|
||||
if (sent > 0 && transmission_state) {
|
||||
*transmission_state = CommandTransmissionState::PossiblySent;
|
||||
}
|
||||
if (sent != static_cast<ssize_t>(frame.size())) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit send command failed: " + systemError());
|
||||
}
|
||||
|
||||
std::uint16_t response_command = 0;
|
||||
std::string payload_text_response;
|
||||
const auto result = receiveFrame_(sock, response_command, payload_text_response);
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
const auto expected_response_command = static_cast<std::uint16_t>(
|
||||
command + 10000U);
|
||||
if (response_command != expected_response_command) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit response command mismatch: expected="
|
||||
+ std::to_string(expected_response_command)
|
||||
+ ", actual=" + std::to_string(response_command));
|
||||
}
|
||||
if (response_payload) {
|
||||
*response_payload = std::move(payload_text_response);
|
||||
}
|
||||
return AgvResult::success();
|
||||
};
|
||||
const auto close_matching_socket_locked = [this, sock]() {
|
||||
if (sock == sock_status_) {
|
||||
closeSocket_(sock_status_);
|
||||
} else if (sock == sock_control_) {
|
||||
closeSocket_(sock_control_);
|
||||
} else if (sock == sock_navigation_) {
|
||||
closeSocket_(sock_navigation_);
|
||||
} else if (sock == sock_config_) {
|
||||
closeSocket_(sock_config_);
|
||||
} else if (sock == sock_other_) {
|
||||
closeSocket_(sock_other_);
|
||||
}
|
||||
};
|
||||
const auto mark_channel_desynchronized = [](AgvResult result) {
|
||||
std::string detail = result.message.empty()
|
||||
? "unknown transport or frame error"
|
||||
: result.message;
|
||||
detail +=
|
||||
"; SEER Robokit channel closed because the response stream may be "
|
||||
"desynchronized; reconnect before sending another command";
|
||||
return AgvResult::failure(result.code, detail);
|
||||
};
|
||||
|
||||
bool is_status_socket = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sock < 0) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::NotConnected,
|
||||
"SEER Robokit socket not connected");
|
||||
}
|
||||
is_status_socket = sock == sock_status_;
|
||||
}
|
||||
|
||||
if (is_status_socket) {
|
||||
// A slow 1110 status response must never hold the lifecycle/global I/O
|
||||
// mutex needed by cancelNavigation() or emergencyStop(). The dedicated
|
||||
// status lock still serializes requests on port 19204. connect_() and
|
||||
// disconnect_() take this lock before changing the descriptor.
|
||||
std::lock_guard<std::mutex> status_lock(status_io_mutex_);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sock < 0 || sock != sock_status_) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::NotConnected,
|
||||
"SEER Robokit status socket is no longer connected");
|
||||
}
|
||||
}
|
||||
auto result = exchange();
|
||||
if (!result.ok()) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
close_matching_socket_locked();
|
||||
return mark_channel_desynchronized(std::move(result));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sock < 0
|
||||
|| (sock != sock_control_
|
||||
&& sock != sock_navigation_
|
||||
&& sock != sock_config_
|
||||
&& sock != sock_other_)) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::NotConnected,
|
||||
"SEER Robokit socket is no longer connected");
|
||||
}
|
||||
auto result = exchange();
|
||||
if (!result.ok()) {
|
||||
close_matching_socket_locked();
|
||||
return mark_channel_desynchronized(std::move(result));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::sendCommandNoResponse_(
|
||||
const int sock,
|
||||
const std::uint16_t command,
|
||||
const Json::Value& payload) const
|
||||
{
|
||||
return sendCommand_(sock, command, payload, nullptr);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> SeerRobokitAgv::buildFrame_(
|
||||
const std::uint16_t command,
|
||||
const std::string& payload)
|
||||
{
|
||||
std::vector<std::uint8_t> frame(16 + payload.size(), 0);
|
||||
frame[0] = 0x5A;
|
||||
frame[1] = 0x01;
|
||||
frame[2] = 0x00;
|
||||
frame[3] = 0x01;
|
||||
const auto length = static_cast<std::uint32_t>(payload.size());
|
||||
frame[4] = static_cast<std::uint8_t>((length >> 24U) & 0xFFU);
|
||||
frame[5] = static_cast<std::uint8_t>((length >> 16U) & 0xFFU);
|
||||
frame[6] = static_cast<std::uint8_t>((length >> 8U) & 0xFFU);
|
||||
frame[7] = static_cast<std::uint8_t>(length & 0xFFU);
|
||||
frame[8] = static_cast<std::uint8_t>((command >> 8U) & 0xFFU);
|
||||
frame[9] = static_cast<std::uint8_t>(command & 0xFFU);
|
||||
std::copy(payload.begin(), payload.end(), frame.begin() + 16);
|
||||
return frame;
|
||||
}
|
||||
|
||||
std::string SeerRobokitAgv::toJsonString_(const Json::Value& value)
|
||||
{
|
||||
Json::StreamWriterBuilder builder;
|
||||
builder["indentation"] = "";
|
||||
return Json::writeString(builder, value);
|
||||
}
|
||||
|
||||
bool SeerRobokitAgv::parseJson_(const std::string& input, Json::Value& output, std::string& error)
|
||||
{
|
||||
Json::CharReaderBuilder builder;
|
||||
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
|
||||
return reader->parse(input.data(), input.data() + input.size(), &output, &error);
|
||||
}
|
||||
|
||||
std::string SeerRobokitAgv::extractJson_(const std::string& raw)
|
||||
{
|
||||
const auto begin = raw.find('{');
|
||||
const auto end = raw.rfind('}');
|
||||
if (begin == std::string::npos || end == std::string::npos || end < begin) {
|
||||
return {};
|
||||
}
|
||||
return raw.substr(begin, end - begin + 1);
|
||||
}
|
||||
|
||||
AgvResult SeerRobokitAgv::receiveFrame_(const int sock, std::uint16_t& command, std::string& payload)
|
||||
{
|
||||
const auto recv_exact = [](const int fd, std::uint8_t* data, const std::size_t size) -> AgvResult {
|
||||
std::size_t offset = 0;
|
||||
while (offset < size) {
|
||||
const ssize_t count = ::recv(fd, data + offset, size - offset, 0);
|
||||
if (count > 0) {
|
||||
offset += static_cast<std::size_t>(count);
|
||||
continue;
|
||||
}
|
||||
if (count == 0) {
|
||||
return AgvResult::failure(AgvErrorCode::NotConnected, "SEER Robokit socket closed");
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return AgvResult::failure(AgvErrorCode::Timeout, "SEER Robokit receive timeout");
|
||||
}
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, "SEER Robokit receive failed: " + systemError());
|
||||
}
|
||||
return AgvResult::success();
|
||||
};
|
||||
|
||||
std::uint8_t header[16]{};
|
||||
auto result = recv_exact(sock, header, sizeof(header));
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
if (header[0] != 0x5A) {
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, "SEER Robokit frame header is invalid");
|
||||
}
|
||||
|
||||
const auto length = (static_cast<std::uint32_t>(header[4]) << 24U)
|
||||
| (static_cast<std::uint32_t>(header[5]) << 16U)
|
||||
| (static_cast<std::uint32_t>(header[6]) << 8U)
|
||||
| static_cast<std::uint32_t>(header[7]);
|
||||
command = static_cast<std::uint16_t>((static_cast<std::uint16_t>(header[8]) << 8U) | header[9]);
|
||||
payload.clear();
|
||||
if (length == 0) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
if (length > kMaxFramePayloadBytes) {
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, "SEER Robokit frame payload is too large");
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> buffer(length);
|
||||
result = recv_exact(sock, buffer.data(), buffer.size());
|
||||
if (!result.ok()) {
|
||||
return result;
|
||||
}
|
||||
payload.assign(reinterpret_cast<const char*>(buffer.data()), buffer.size());
|
||||
return AgvResult::success();
|
||||
}
|
||||
|
||||
|
||||
AgvResult SeerRobokitAgv::resultFromResponse_(const Json::Value& response)
|
||||
{
|
||||
if (!hasNumericControllerRetCode(response)) {
|
||||
return AgvResult::failure(
|
||||
AgvErrorCode::CommandFailed,
|
||||
"SEER Robokit controller response is missing a numeric ret_code");
|
||||
}
|
||||
const auto* ret_code_value = jsonFind(response, "ret_code");
|
||||
const bool success = ret_code_value->isUInt() || ret_code_value->isUInt64()
|
||||
? ret_code_value->asUInt64() == 0
|
||||
: ret_code_value->asInt64() == 0;
|
||||
const std::string ret_code = jsonValueToString(*ret_code_value);
|
||||
const std::string message = jsonGet(response, "err_msg", "").asString();
|
||||
if (success) {
|
||||
return AgvResult::success();
|
||||
}
|
||||
std::string detail = "SEER Robokit command failed: ret_code=" + ret_code;
|
||||
if (!message.empty()) {
|
||||
detail += ", err_msg=" + message;
|
||||
}
|
||||
return AgvResult::failure(AgvErrorCode::CommandFailed, detail);
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,6 +1,7 @@
|
||||
add_subdirectory(motor_robot_arm)
|
||||
add_subdirectory(aubo_arm)
|
||||
add_subdirectory(huayan_arm)
|
||||
add_subdirectory(ume_robot_arm)
|
||||
|
||||
add_library(robot_arm INTERFACE)
|
||||
|
||||
@ -11,6 +12,7 @@ target_link_libraries(robot_arm
|
||||
cmvr_es::device::motor_robot_arm
|
||||
cmvr_es::device::aubo_arm
|
||||
cmvr_es::device::huayan_arm
|
||||
cmvr_es::device::ume_robot_arm
|
||||
cmvr_es::proto
|
||||
)
|
||||
|
||||
|
||||
@ -1,13 +1,38 @@
|
||||
add_library(aubo_arm SHARED
|
||||
src/aubo_arm.cpp
|
||||
aubo_arm.cpp
|
||||
)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
target_include_directories(aubo_arm PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
set(AUBO_SDK_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/third_party/AuboSdk/linux/include)
|
||||
set(AUBO_SDK_LIB_DIR ${CMAKE_SOURCE_DIR}/third_party/AuboSdk/linux/lib)
|
||||
set(AUBO_SDK_ROOT ${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/aubo_sdk/v0.27.1)
|
||||
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")
|
||||
if (EXISTS "${AUBO_SDK_LIB_DIR}/cmake/aubo_sdk/aubo_sdkConfig.cmake")
|
||||
list(APPEND CMAKE_PREFIX_PATH "${AUBO_SDK_LIB_DIR}/cmake")
|
||||
find_package(Qt5Core QUIET)
|
||||
if (NOT Qt5Core_FOUND AND NOT TARGET Qt5::Core)
|
||||
find_library(QT5_CORE_LIBRARY
|
||||
NAMES Qt5Core libQt5Core.so.5
|
||||
PATHS /lib /usr/lib /usr/local/lib /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu
|
||||
)
|
||||
if (QT5_CORE_LIBRARY)
|
||||
add_library(Qt5::Core UNKNOWN IMPORTED)
|
||||
set_target_properties(Qt5::Core PROPERTIES
|
||||
IMPORTED_LOCATION "${QT5_CORE_LIBRARY}"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
find_package(aubo_sdk REQUIRED CONFIG PATHS "${AUBO_SDK_LIB_DIR}/cmake/aubo_sdk" NO_DEFAULT_PATH)
|
||||
set_target_properties(aubo_sdk::aubo_sdk aubo_sdk::robot_proxy PROPERTIES
|
||||
MAP_IMPORTED_CONFIG_DEBUG Release
|
||||
)
|
||||
target_compile_definitions(aubo_arm PRIVATE CMVR_HAS_AUBO_SDK)
|
||||
target_include_directories(aubo_arm PRIVATE ${AUBO_SDK_INCLUDE_DIR})
|
||||
target_link_libraries(aubo_arm PRIVATE aubo_sdk::aubo_sdk)
|
||||
elseif (EXISTS "${AUBO_SDK_INCLUDE_DIR}/aubo_sdk/rpc.h")
|
||||
target_compile_definitions(aubo_arm PRIVATE CMVR_HAS_AUBO_SDK)
|
||||
target_include_directories(aubo_arm PRIVATE ${AUBO_SDK_INCLUDE_DIR})
|
||||
if (EXISTS "${AUBO_SDK_LIB_DIR}")
|
||||
@ -23,6 +48,8 @@ target_link_libraries(aubo_arm
|
||||
cmvr_es::proto
|
||||
PRIVATE
|
||||
glog
|
||||
jsoncpp
|
||||
Threads::Threads
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::aubo_arm ALIAS aubo_arm)
|
||||
|
||||
139
cmvr-es/devices/arm/aubo_arm/README.md
Normal file
139
cmvr-es/devices/arm/aubo_arm/README.md
Normal file
@ -0,0 +1,139 @@
|
||||
# AUBO RobotArm 与控制柜 IO
|
||||
|
||||
`AuboArm` 是 AUBO SDK v0.27.1 的 `RobotArm` 后端。控制柜 Standard 数字 IO
|
||||
通过设备通用的 `executeJsonCommand` 接口访问,远程调用复用
|
||||
`cmvr.api.ArmService/ExecuteJsonCommand`,不经过 `SystemService` 或
|
||||
`MotorService`。该 RPC 只路由到 `RobotArm`,不会把 JSON 命令转发给其他设备类型。
|
||||
旧的 `cmvr.api.SystemService/ExecuteJsonCommand` 不再注册,调用方必须更新服务路径;
|
||||
请求和响应消息结构保持不变。
|
||||
|
||||
返回 [Devices 模块指南](../../README.md) 或 [项目总览](../../../../README.md)。
|
||||
|
||||
## 代码与配置
|
||||
|
||||
- 实现:[`aubo_arm.h`](aubo_arm.h)、[`aubo_arm.cpp`](aubo_arm.cpp)
|
||||
- 设备配置:[`../../../config/devices/arm/aubo_arm.pb.txt`](../../../config/devices/arm/aubo_arm.pb.txt)
|
||||
- DeviceManager 配置:
|
||||
[`../../../config/manager/device_manager.pb.txt`](../../../config/manager/device_manager.pb.txt)
|
||||
- ArmService 实现:
|
||||
[`../../../service/grpc/server/src/grpc_arm_service.cpp`](../../../service/grpc/server/src/grpc_arm_service.cpp)
|
||||
- Proto:[`../../../../protos/cmvr/api/arm_service.proto`](../../../../protos/cmvr/api/arm_service.proto)
|
||||
|
||||
仓库配置使用 SDK RPC 端口 `30004`。现场部署必须填写真实控制器地址和凭据,
|
||||
不要把生产密码提交到默认配置。
|
||||
|
||||
## 控制柜 Standard 数字 IO
|
||||
|
||||
当前支持:
|
||||
|
||||
| `operation` | 说明 | 必填字段 |
|
||||
| --- | --- | --- |
|
||||
| `get_di` | 读取控制柜数字输入 | `index` |
|
||||
| `get_do` | 读取控制柜数字输出及其 runstate | `index` |
|
||||
| `set_do` | 设置控制柜数字输出 | `index`、`value` |
|
||||
|
||||
JSON 命令:
|
||||
|
||||
```json
|
||||
{"command":"cabinet_io","operation":"get_di","index":0}
|
||||
{"command":"cabinet_io","operation":"get_do","index":0}
|
||||
{"command":"cabinet_io","operation":"set_do","index":0,"value":true}
|
||||
```
|
||||
|
||||
`index` 从 `0` 开始,运行时根据控制器返回的 IO 数量检查范围。
|
||||
`set_do.value` 必须是 JSON 布尔值 `true` 或 `false`,不接受 `0/1` 或字符串。
|
||||
`set_do` 成功响应中的 `requested_value` 只表示 SDK 已接受请求;确认实际输出时
|
||||
必须再调用 `get_do`。
|
||||
|
||||
读取成功响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"command": "cabinet_io",
|
||||
"operation": "get_di",
|
||||
"index": 0,
|
||||
"count": 16,
|
||||
"value": false
|
||||
}
|
||||
```
|
||||
|
||||
## 通过 gRPC 调用
|
||||
|
||||
默认 gRPC 端口为 `50052`。读取 DI0:
|
||||
|
||||
```shell
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"header":{"deviceId":"aubo_arm"},
|
||||
"requestJson":"{\"command\":\"cabinet_io\",\"operation\":\"get_di\",\"index\":0}"
|
||||
}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.ArmService/ExecuteJsonCommand
|
||||
```
|
||||
|
||||
设置 DO0 为高电平:
|
||||
|
||||
```shell
|
||||
grpcurl -plaintext \
|
||||
-d '{
|
||||
"header":{"deviceId":"aubo_arm"},
|
||||
"requestJson":"{\"command\":\"cabinet_io\",\"operation\":\"set_do\",\"index\":0,\"value\":true}"
|
||||
}' \
|
||||
127.0.0.1:50052 \
|
||||
cmvr.api.ArmService/ExecuteJsonCommand
|
||||
```
|
||||
|
||||
使用源码默认配置时:
|
||||
|
||||
1. 在 `cmvr-es/config/devices/arm/aubo_arm.pb.txt` 填写正确地址和登录信息;
|
||||
2. 在 `cmvr-es/config/manager/device_manager.pb.txt` 将 `aubo_arm.enable`
|
||||
改为 `true`;
|
||||
3. 重新安装配置并启动安装产物。
|
||||
|
||||
```shell
|
||||
cmake --install build
|
||||
./output/bin/cmvr_es
|
||||
```
|
||||
|
||||
`output/bin/cmvr_es` 默认读取 `output/bin/config/`。使用 `--config` 时,应修改
|
||||
对应外部配置根。设备未启用或初始化失败时,gRPC 返回
|
||||
`Device not found: aubo_arm`。
|
||||
|
||||
## 安全与语义边界
|
||||
|
||||
- 后端使用独立 SDK RPC 会话持续读取控制器的 `SafetyModeType`、
|
||||
`RobotModeType` 和硬件急停来源;首次有效样本前、监控断线或样本过期时,
|
||||
所有 Move、Speed、Servo 和程序启动请求均按不安全状态拒绝;
|
||||
- 硬件急停会立即使当前运动 generation 失效,并在急停输入有效期间保持锁存。
|
||||
AUBO SDK 将示教器/控制柜急停报告为 `RobotEmergencyStop`,将控制器系统急停
|
||||
(外部系统急停输入)报告为 `SystemEmergencyStop`;两者在本后端都属于硬件急停。
|
||||
检测到任一硬件急停输入消失且控制器重新报告 `Normal`/`ReducedMode` 后,后端自动
|
||||
执行 `poweron()` 和 `startup()`,恢复到 `Running` 后再完成安全确认并开放新的 gRPC
|
||||
控制指令;防护停机和 Safety Fault/Violation 仍保持显式恢复语义;
|
||||
- `emergencyStop()` 使用独立的 `SoftwareEmergencyStop` 锁存。即使软件急停在真实
|
||||
硬件急停有效期间触发,后续硬件采样也不能覆盖该锁存,释放硬件急停开关不会
|
||||
自动清除软件急停;它只能通过显式安全恢复流程解除;
|
||||
- 锁存后会终止直接运动与程序、关闭 servo 模式并清理控制器轨迹。硬件急停
|
||||
自动恢复先上电到 `Idle`,在刹车释放前清理 runtime、servo 和轨迹队列,再执行
|
||||
`startup()`;到达 `Running` 后还会再次确认 `ExecId == -1`、普通队列和轨迹队列
|
||||
均为空、运行时已停止且机械臂稳定,全部成立后才能解除锁存;
|
||||
- 当前 AUBO 配置通过 `auto_power_on_after_hardware_estop_release: true` 显式启用自动
|
||||
上电。自动确认失败时继续保持 fail-closed,并允许通过 `torqueOn`/`clearFault`/
|
||||
`unlockProtectiveStop` 显式重试;本轮释放期间收到 `stopMotion()` 或 `torqueOff()`
|
||||
会取消自动上电,显式停止始终优先;
|
||||
- 恢复流程只调用 `poweron()` 和 `startup()`,不会调用 `resume`、`arbitraryResume`、
|
||||
`startMove`,也不会重新提交急停前的目标、速度、servo 指令或程序;
|
||||
- AUBO SDK 未在本地文档中保证急停期间 `clearPath` 的可用性,也未说明释放
|
||||
急停开关后的控制器恢复时序。因此自动恢复必须在释放后再次清队列并完成上述
|
||||
安全确认;无法确认时不得解除锁存。“释放开关后零位移”的最终保证仍需真机
|
||||
验证及控制器侧安全配置配合;
|
||||
- 只访问控制柜 Standard 数字 IO,不访问工具端 IO、可配置 IO 或安全 IO;
|
||||
- `set_do` 不修改输出 runstate;
|
||||
- 只有 `StandardOutputRunState::None` 的通道允许写入,否则返回
|
||||
`output_managed_by_runstate`;
|
||||
- 普通访问不会调用会重置全部输出配置的
|
||||
`setDigitalOutputRunstateDefault()`;
|
||||
- 模拟量 IO 涉及 domain、单位和量程,当前 JSON 接口不开放;
|
||||
- gRPC/JSON 返回成功不代表目标 IO 具备功能安全等级;
|
||||
- 真实写测试前应确认通道用途、负载、电气隔离、默认电平和控制器程序所有权。
|
||||
3973
cmvr-es/devices/arm/aubo_arm/aubo_arm.cpp
Normal file
3973
cmvr-es/devices/arm/aubo_arm/aubo_arm.cpp
Normal file
File diff suppressed because it is too large
Load Diff
@ -2,6 +2,8 @@
|
||||
#define CMVR_ES_AUBO_ARM_H
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
@ -21,6 +23,8 @@ public:
|
||||
std::string typeName() const override { return "AuboARM"; }
|
||||
bool init() override;
|
||||
bool stop() override;
|
||||
bool executeJsonCommand(const std::string& request_json,
|
||||
std::string& response_json) override;
|
||||
|
||||
RobotModel getRobotModel() const override { return model_; }
|
||||
std::size_t getDof() const override { return model_.dof; }
|
||||
@ -28,19 +32,22 @@ public:
|
||||
JointGroupState getJointState() const override;
|
||||
CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override;
|
||||
RobotMode getRobotMode() const override;
|
||||
SafetyMode getSafetyMode() const override { return SafetyMode::Normal; }
|
||||
ControlMode getControlMode() const override { return ControlMode::Position; }
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override;
|
||||
bool supportsActionQueueMotion() const noexcept override { return true; }
|
||||
|
||||
Result torqueOn() override;
|
||||
Result torqueOn(
|
||||
const std::function<bool()>& cancellation_requested) override;
|
||||
Result torqueOff() override;
|
||||
Result calibrateZeroQ(const std::string& joint_name) override;
|
||||
Result emergencyStop() override;
|
||||
Result protectiveStop() override { return emergencyStop(); }
|
||||
Result protectiveStop() override;
|
||||
Result setSpeedScaling(double scaling) override;
|
||||
double getSpeedScaling() const override { return speed_scaling_; }
|
||||
bool isProtectiveStopped() const override { return false; }
|
||||
bool isEmergencyStopped() const override { return emergency_stopped_; }
|
||||
bool isFault() const override { return false; }
|
||||
bool isProtectiveStopped() const override;
|
||||
bool isEmergencyStopped() const override;
|
||||
bool isFault() const override;
|
||||
|
||||
Result moveJ(const JointPositionCommand& target, const MotionOptions& options) override;
|
||||
Result speedJ(const JointVelocityCommand& velocity, double acceleration, double duration) override;
|
||||
@ -64,8 +71,8 @@ public:
|
||||
Result powerOff() override { return torqueOff(); }
|
||||
Result brakeRelease() override { return torqueOn(); }
|
||||
Result shutdown() override;
|
||||
Result clearFault() override { return Result::success(); }
|
||||
Result unlockProtectiveStop() override { return Result::success(); }
|
||||
Result clearFault() override;
|
||||
Result unlockProtectiveStop() override;
|
||||
Result loadProgram(const std::string& program_name) override;
|
||||
Result playProgram() override;
|
||||
Result pauseProgram() override;
|
||||
@ -78,16 +85,27 @@ public:
|
||||
CartesianPose fk(const std::string& base_link, const std::string& ee_link) override;
|
||||
CartesianPose fk(bool is_tcp = true) override;
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override { return {}; }
|
||||
bool busy() const override { return busy_.load(); }
|
||||
bool busy() const override;
|
||||
|
||||
private:
|
||||
enum class MotionStopKind {
|
||||
Automatic,
|
||||
Joint,
|
||||
Linear,
|
||||
};
|
||||
|
||||
Result unsupported_(const std::string& name) const;
|
||||
bool validDof_(std::size_t size, std::string& error) const;
|
||||
Result ensureConnected_(const std::string& context) const;
|
||||
Result ensureMotionReady_(const std::string& context,
|
||||
std::uint64_t& safety_epoch) const;
|
||||
Result completeSafetyRecovery_(const std::string& context,
|
||||
std::uint64_t expected_safety_epoch);
|
||||
Result unlockProtectiveStop_(
|
||||
std::optional<std::uint64_t> expected_safety_epoch);
|
||||
Result stopMotion_(MotionStopKind kind, double acceleration);
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
struct SdkState;
|
||||
#endif
|
||||
|
||||
private:
|
||||
config::RobotArmConfig cfg_;
|
||||
@ -98,14 +116,14 @@ private:
|
||||
std::string username_;
|
||||
std::string password_;
|
||||
double speed_scaling_{1.0};
|
||||
ServoOptions servo_options_;
|
||||
std::atomic<bool> connected_{false};
|
||||
std::atomic<bool> busy_{false};
|
||||
bool emergency_stopped_{false};
|
||||
std::atomic<bool> servo_mode_{false};
|
||||
std::atomic<bool> emergency_stopped_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
std::unique_ptr<SdkState> sdk_;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
45
cmvr-es/devices/arm/aubo_arm/aubo_motion_result.h
Normal file
45
cmvr-es/devices/arm/aubo_arm/aubo_motion_result.h
Normal file
@ -0,0 +1,45 @@
|
||||
#ifndef CMVR_ES_AUBO_MOTION_RESULT_H
|
||||
#define CMVR_ES_AUBO_MOTION_RESULT_H
|
||||
|
||||
namespace cmvr::device::aubo_internal {
|
||||
|
||||
enum class MotionCommandOutcome {
|
||||
CompletedWithoutMotion,
|
||||
CompletedAfterMotion,
|
||||
Cancelled,
|
||||
SubmitFailed,
|
||||
CompletionFailed,
|
||||
};
|
||||
|
||||
enum class MotionWaitResult {
|
||||
Completed,
|
||||
Cancelled,
|
||||
Failed,
|
||||
};
|
||||
|
||||
template <typename WaitForCompletion>
|
||||
MotionCommandOutcome resolveMotionCommand(
|
||||
const int return_code,
|
||||
const int success_code,
|
||||
const int request_ignore_code,
|
||||
WaitForCompletion&& wait_for_completion)
|
||||
{
|
||||
if (return_code == request_ignore_code) {
|
||||
return MotionCommandOutcome::CompletedWithoutMotion;
|
||||
}
|
||||
if (return_code != success_code) {
|
||||
return MotionCommandOutcome::SubmitFailed;
|
||||
}
|
||||
const auto wait_result = wait_for_completion();
|
||||
if (wait_result == MotionWaitResult::Cancelled) {
|
||||
return MotionCommandOutcome::Cancelled;
|
||||
}
|
||||
if (wait_result != MotionWaitResult::Completed) {
|
||||
return MotionCommandOutcome::CompletionFailed;
|
||||
}
|
||||
return MotionCommandOutcome::CompletedAfterMotion;
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::aubo_internal
|
||||
|
||||
#endif // CMVR_ES_AUBO_MOTION_RESULT_H
|
||||
369
cmvr-es/devices/arm/aubo_arm/aubo_motion_state.h
Normal file
369
cmvr-es/devices/arm/aubo_arm/aubo_motion_state.h
Normal file
@ -0,0 +1,369 @@
|
||||
#ifndef CMVR_ES_AUBO_MOTION_STATE_H
|
||||
#define CMVR_ES_AUBO_MOTION_STATE_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace cmvr::device::aubo_internal {
|
||||
|
||||
enum class MotionKind {
|
||||
None,
|
||||
Joint,
|
||||
Linear,
|
||||
};
|
||||
|
||||
struct MotionToken {
|
||||
std::uint64_t generation{0};
|
||||
MotionKind kind{MotionKind::None};
|
||||
|
||||
bool valid() const noexcept
|
||||
{
|
||||
return generation != 0 && kind != MotionKind::None;
|
||||
}
|
||||
};
|
||||
|
||||
enum class MotionStartStatus {
|
||||
Started,
|
||||
Invalid,
|
||||
Busy,
|
||||
Stopping,
|
||||
Blocked,
|
||||
};
|
||||
|
||||
struct MotionStartResult {
|
||||
MotionStartStatus status{MotionStartStatus::Busy};
|
||||
MotionToken token;
|
||||
|
||||
bool started() const noexcept
|
||||
{
|
||||
return status == MotionStartStatus::Started;
|
||||
}
|
||||
};
|
||||
|
||||
enum class MotionFinishMode {
|
||||
RestorePrevious,
|
||||
Clear,
|
||||
Retain,
|
||||
};
|
||||
|
||||
enum class StopStartStatus {
|
||||
Started,
|
||||
AlreadyStopping,
|
||||
};
|
||||
|
||||
enum class StopWaitStatus {
|
||||
Completed,
|
||||
Failed,
|
||||
Timeout,
|
||||
};
|
||||
|
||||
class StopCompletion final {
|
||||
public:
|
||||
StopWaitStatus waitFor(const std::chrono::milliseconds timeout)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
if (!cv_.wait_for(lock, timeout, [this]() { return completed_; })) {
|
||||
return StopWaitStatus::Timeout;
|
||||
}
|
||||
return succeeded_
|
||||
? StopWaitStatus::Completed
|
||||
: StopWaitStatus::Failed;
|
||||
}
|
||||
|
||||
private:
|
||||
friend class MotionState;
|
||||
|
||||
void finish(const bool succeeded)
|
||||
{
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
succeeded_ = succeeded;
|
||||
completed_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
bool completed_{false};
|
||||
bool succeeded_{false};
|
||||
};
|
||||
|
||||
struct StopRequest {
|
||||
StopStartStatus status{StopStartStatus::AlreadyStopping};
|
||||
MotionKind kind{MotionKind::None};
|
||||
MotionToken active_token;
|
||||
bool tracked_motion{false};
|
||||
std::shared_ptr<StopCompletion> completion;
|
||||
|
||||
bool started() const noexcept
|
||||
{
|
||||
return status == StopStartStatus::Started;
|
||||
}
|
||||
};
|
||||
|
||||
struct SafetyCancelResult {
|
||||
MotionKind kind{MotionKind::None};
|
||||
MotionToken active_token;
|
||||
bool tracked_motion{false};
|
||||
};
|
||||
|
||||
// Tracks one direct AUBO motion owner. MoveJ/MoveL submissions are serialized
|
||||
// through the vendor call. Speed calls release the outer mutex before their
|
||||
// potentially blocking SDK call, so the generation cancellation below also
|
||||
// closes the stop-vs-speed-submission race.
|
||||
class MotionState final {
|
||||
public:
|
||||
MotionStartResult begin(
|
||||
const MotionKind kind,
|
||||
const bool replace_retained_same_kind = false)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (kind == MotionKind::None) {
|
||||
return {MotionStartStatus::Invalid, {}};
|
||||
}
|
||||
if (stop_in_progress_) {
|
||||
return {MotionStartStatus::Stopping, {}};
|
||||
}
|
||||
if (blocked_) {
|
||||
return {MotionStartStatus::Blocked, {}};
|
||||
}
|
||||
if (owner_active_) {
|
||||
return {MotionStartStatus::Busy, {}};
|
||||
}
|
||||
if (last_kind_ != MotionKind::None &&
|
||||
(!replace_retained_same_kind || last_kind_ != kind)) {
|
||||
return {MotionStartStatus::Busy, {}};
|
||||
}
|
||||
|
||||
MotionToken token{++next_generation_, kind};
|
||||
owner_active_ = true;
|
||||
active_token_ = token;
|
||||
previous_kind_ = last_kind_;
|
||||
return {MotionStartStatus::Started, token};
|
||||
}
|
||||
|
||||
void finish(
|
||||
const MotionToken& token,
|
||||
const MotionFinishMode mode = MotionFinishMode::RestorePrevious)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!owner_active_ ||
|
||||
active_token_.generation != token.generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
owner_active_ = false;
|
||||
active_token_ = {};
|
||||
if (!stop_in_progress_ && !blocked_) {
|
||||
if (mode == MotionFinishMode::Retain) {
|
||||
last_kind_ = token.kind;
|
||||
} else if (mode == MotionFinishMode::Clear) {
|
||||
last_kind_ = MotionKind::None;
|
||||
} else {
|
||||
last_kind_ = previous_kind_;
|
||||
}
|
||||
}
|
||||
previous_kind_ = MotionKind::None;
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
|
||||
void failMotion(const MotionToken& token)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!owner_active_ ||
|
||||
active_token_.generation != token.generation) {
|
||||
return;
|
||||
}
|
||||
owner_active_ = false;
|
||||
active_token_ = {};
|
||||
last_kind_ = token.kind;
|
||||
previous_kind_ = MotionKind::None;
|
||||
blocked_ = true;
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
|
||||
StopRequest beginStop(
|
||||
const MotionKind requested_kind = MotionKind::None)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (stop_in_progress_) {
|
||||
return {
|
||||
StopStartStatus::AlreadyStopping,
|
||||
MotionKind::None,
|
||||
{},
|
||||
false,
|
||||
active_stop_completion_};
|
||||
}
|
||||
|
||||
auto completion = std::make_shared<StopCompletion>();
|
||||
stop_in_progress_ = true;
|
||||
active_stop_completion_ = completion;
|
||||
const MotionToken active = owner_active_
|
||||
? active_token_
|
||||
: MotionToken{};
|
||||
// A successful speedJoint/speedLine call may keep the controller in
|
||||
// velocity mode after the SDK function returns, even when the target
|
||||
// velocity is zero and the robot currently reports steady. Retain that
|
||||
// motion kind until a typed stop has been acknowledged.
|
||||
const bool tracked_motion =
|
||||
active.valid() || last_kind_ != MotionKind::None;
|
||||
if (active.valid()) {
|
||||
cancelled_generation_ = std::max(
|
||||
cancelled_generation_, active.generation);
|
||||
}
|
||||
MotionKind kind = MotionKind::None;
|
||||
if (active.valid()) {
|
||||
kind = active.kind;
|
||||
} else if (last_kind_ != MotionKind::None) {
|
||||
kind = last_kind_;
|
||||
} else if (requested_kind != MotionKind::None) {
|
||||
kind = requested_kind;
|
||||
} else {
|
||||
kind = last_kind_;
|
||||
}
|
||||
if (kind != MotionKind::None) {
|
||||
last_kind_ = kind;
|
||||
}
|
||||
return {
|
||||
StopStartStatus::Started,
|
||||
kind,
|
||||
active,
|
||||
tracked_motion,
|
||||
completion};
|
||||
}
|
||||
|
||||
SafetyCancelResult cancelActiveForSafety()
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const MotionToken active = owner_active_
|
||||
? active_token_
|
||||
: MotionToken{};
|
||||
if (active.valid()) {
|
||||
cancelled_generation_ = std::max(
|
||||
cancelled_generation_, active.generation);
|
||||
}
|
||||
|
||||
const MotionKind kind = active.valid()
|
||||
? active.kind
|
||||
: last_kind_;
|
||||
if (kind != MotionKind::None) {
|
||||
last_kind_ = kind;
|
||||
}
|
||||
// This block is intentionally independent of stop_in_progress_. The
|
||||
// monitor may observe the safety event while a software Stop owns the
|
||||
// stop transaction; either way no new motion may enter.
|
||||
blocked_ = true;
|
||||
owner_finished_cv_.notify_all();
|
||||
return {kind, active, active.valid() || kind != MotionKind::None};
|
||||
}
|
||||
|
||||
bool cancelled(const MotionToken& token) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return token.valid() &&
|
||||
token.generation <= cancelled_generation_;
|
||||
}
|
||||
|
||||
bool waitForOwnerExit(
|
||||
const MotionToken& token,
|
||||
const std::chrono::milliseconds timeout)
|
||||
{
|
||||
if (!token.valid()) {
|
||||
return true;
|
||||
}
|
||||
std::unique_lock lock(mutex_);
|
||||
return owner_finished_cv_.wait_for(
|
||||
lock,
|
||||
timeout,
|
||||
[this, &token]() {
|
||||
return !owner_active_ ||
|
||||
active_token_.generation != token.generation;
|
||||
});
|
||||
}
|
||||
|
||||
bool ownerActive(const MotionToken& token) const
|
||||
{
|
||||
if (!token.valid()) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard lock(mutex_);
|
||||
return owner_active_ &&
|
||||
active_token_.generation == token.generation;
|
||||
}
|
||||
|
||||
StopWaitStatus waitForStopCompletion(
|
||||
const StopRequest& request,
|
||||
const std::chrono::milliseconds timeout) const
|
||||
{
|
||||
if (!request.completion) {
|
||||
return StopWaitStatus::Failed;
|
||||
}
|
||||
return request.completion->waitFor(timeout);
|
||||
}
|
||||
|
||||
bool completeStop()
|
||||
{
|
||||
std::shared_ptr<StopCompletion> completion;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (owner_active_) {
|
||||
return false;
|
||||
}
|
||||
stop_in_progress_ = false;
|
||||
blocked_ = false;
|
||||
active_token_ = {};
|
||||
last_kind_ = MotionKind::None;
|
||||
previous_kind_ = MotionKind::None;
|
||||
completion = std::move(active_stop_completion_);
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
if (completion) {
|
||||
completion->finish(true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void failStop()
|
||||
{
|
||||
std::shared_ptr<StopCompletion> completion;
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
stop_in_progress_ = false;
|
||||
blocked_ = true;
|
||||
completion = std::move(active_stop_completion_);
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
if (completion) {
|
||||
completion->finish(false);
|
||||
}
|
||||
}
|
||||
|
||||
bool busy() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return owner_active_ || stop_in_progress_ || blocked_ ||
|
||||
last_kind_ != MotionKind::None;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable owner_finished_cv_;
|
||||
std::uint64_t next_generation_{0};
|
||||
std::uint64_t cancelled_generation_{0};
|
||||
MotionToken active_token_;
|
||||
MotionKind last_kind_{MotionKind::None};
|
||||
MotionKind previous_kind_{MotionKind::None};
|
||||
std::shared_ptr<StopCompletion> active_stop_completion_;
|
||||
bool owner_active_{false};
|
||||
bool stop_in_progress_{false};
|
||||
bool blocked_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device::aubo_internal
|
||||
|
||||
#endif // CMVR_ES_AUBO_MOTION_STATE_H
|
||||
260
cmvr-es/devices/arm/aubo_arm/aubo_safety_state.h
Normal file
260
cmvr-es/devices/arm/aubo_arm/aubo_safety_state.h
Normal file
@ -0,0 +1,260 @@
|
||||
#ifndef CMVR_ES_AUBO_SAFETY_STATE_H
|
||||
#define CMVR_ES_AUBO_SAFETY_STATE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace cmvr::device::aubo_internal {
|
||||
|
||||
// This is deliberately richer than RobotArm::SafetyMode. Recovery and
|
||||
// Violation have no lossless public mapping, but both must remain fail-closed.
|
||||
enum class SafetyCondition {
|
||||
Unknown,
|
||||
Normal,
|
||||
Reduced,
|
||||
Recovery,
|
||||
Violation,
|
||||
ProtectiveStop,
|
||||
SafeguardStop,
|
||||
SystemEmergencyStop,
|
||||
RobotEmergencyStop,
|
||||
SoftwareEmergencyStop,
|
||||
Fault,
|
||||
};
|
||||
|
||||
inline bool isMotionSafe(const SafetyCondition condition) noexcept
|
||||
{
|
||||
return condition == SafetyCondition::Normal ||
|
||||
condition == SafetyCondition::Reduced;
|
||||
}
|
||||
|
||||
inline bool isHardwareEmergencyStop(
|
||||
const SafetyCondition condition) noexcept
|
||||
{
|
||||
return condition == SafetyCondition::SystemEmergencyStop ||
|
||||
condition == SafetyCondition::RobotEmergencyStop;
|
||||
}
|
||||
|
||||
inline SafetyCondition effectiveSafetyCondition(
|
||||
const SafetyCondition reported_condition,
|
||||
const int robot_emergency_stop_source) noexcept
|
||||
{
|
||||
// The source bitmask describes robot-side inputs such as the control box
|
||||
// and teach pendant. Keep the SDK's SystemEmergencyStop classification for
|
||||
// the separate external system-emergency input.
|
||||
if (reported_condition == SafetyCondition::SystemEmergencyStop) {
|
||||
return SafetyCondition::SystemEmergencyStop;
|
||||
}
|
||||
if (robot_emergency_stop_source < 0) {
|
||||
return SafetyCondition::Unknown;
|
||||
}
|
||||
if (robot_emergency_stop_source != 0) {
|
||||
return SafetyCondition::RobotEmergencyStop;
|
||||
}
|
||||
return reported_condition;
|
||||
}
|
||||
|
||||
inline bool needsProtectiveUnlock(
|
||||
const SafetyCondition condition) noexcept
|
||||
{
|
||||
return condition == SafetyCondition::ProtectiveStop ||
|
||||
condition == SafetyCondition::Violation;
|
||||
}
|
||||
|
||||
inline bool needsInterfaceBoardRestart(
|
||||
const SafetyCondition condition) noexcept
|
||||
{
|
||||
return condition == SafetyCondition::SystemEmergencyStop ||
|
||||
condition == SafetyCondition::RobotEmergencyStop ||
|
||||
condition == SafetyCondition::Fault;
|
||||
}
|
||||
|
||||
struct SafetyPermit {
|
||||
std::uint64_t epoch{0};
|
||||
|
||||
bool valid() const noexcept { return epoch != 0; }
|
||||
};
|
||||
|
||||
struct RecoveryToken {
|
||||
std::uint64_t epoch{0};
|
||||
|
||||
bool valid() const noexcept { return epoch != 0; }
|
||||
};
|
||||
|
||||
struct SafetySnapshot {
|
||||
SafetyCondition observed{SafetyCondition::Unknown};
|
||||
SafetyCondition latched_reason{SafetyCondition::Unknown};
|
||||
std::uint64_t epoch{0};
|
||||
bool latched{false};
|
||||
bool recovery_in_progress{false};
|
||||
bool software_emergency_stop_latched{false};
|
||||
};
|
||||
|
||||
inline bool shouldAutoRecoverHardwareEmergencyStop(
|
||||
const SafetySnapshot& snapshot,
|
||||
const bool hardware_emergency_stop_was_observed,
|
||||
const int current_emergency_stop_source,
|
||||
const bool auto_power_on_enabled,
|
||||
const bool automatic_recovery_suppressed) noexcept
|
||||
{
|
||||
return auto_power_on_enabled && !automatic_recovery_suppressed &&
|
||||
hardware_emergency_stop_was_observed && snapshot.latched &&
|
||||
!snapshot.recovery_in_progress &&
|
||||
!snapshot.software_emergency_stop_latched &&
|
||||
isHardwareEmergencyStop(snapshot.latched_reason) &&
|
||||
isMotionSafe(snapshot.observed) &&
|
||||
current_emergency_stop_source == 0;
|
||||
}
|
||||
|
||||
// Hardware safety is an event, not a level. Once an unsafe state has been
|
||||
// observed, returning to Normal only changes the observed level. A separate,
|
||||
// explicit recovery must prove that the old controller operation has been
|
||||
// cancelled before new motion permits can be issued.
|
||||
class SafetyState final {
|
||||
public:
|
||||
SafetyState() = default;
|
||||
|
||||
void observe(const SafetyCondition condition)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const bool changed = observed_ != condition;
|
||||
observed_ = condition;
|
||||
if (condition == SafetyCondition::SoftwareEmergencyStop) {
|
||||
software_emergency_stop_latched_ = true;
|
||||
}
|
||||
if (isMotionSafe(condition)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bool preserve_hardware_estop_latch =
|
||||
condition == SafetyCondition::Unknown && latched_ &&
|
||||
isHardwareEmergencyStop(latched_reason_) &&
|
||||
!software_emergency_stop_latched_;
|
||||
if (!latched_ || recovery_in_progress_ ||
|
||||
(changed && !preserve_hardware_estop_latch)) {
|
||||
++epoch_;
|
||||
}
|
||||
latched_ = true;
|
||||
recovery_in_progress_ = false;
|
||||
// A physical E-stop sample can continue arriving after a software
|
||||
// E-stop request. Keep the software stop independently latched so a
|
||||
// later physical-input release can never clear it automatically.
|
||||
if (software_emergency_stop_latched_) {
|
||||
latched_reason_ = SafetyCondition::SoftwareEmergencyStop;
|
||||
} else if (!preserve_hardware_estop_latch) {
|
||||
latched_reason_ = condition;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<SafetyPermit> tryPermit() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (latched_ || !isMotionSafe(observed_)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return SafetyPermit{epoch_};
|
||||
}
|
||||
|
||||
bool validate(const SafetyPermit permit) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return permit.valid() && permit.epoch == epoch_ && !latched_ &&
|
||||
isMotionSafe(observed_);
|
||||
}
|
||||
|
||||
std::optional<RecoveryToken> beginRecovery(
|
||||
const std::uint64_t expected_epoch)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (expected_epoch == 0 || expected_epoch != epoch_ || !latched_ ||
|
||||
recovery_in_progress_ ||
|
||||
!isMotionSafe(observed_)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
recovery_in_progress_ = true;
|
||||
return RecoveryToken{epoch_};
|
||||
}
|
||||
|
||||
bool completeRecovery(
|
||||
const RecoveryToken token,
|
||||
const bool robot_running,
|
||||
const bool controller_idle,
|
||||
const bool cancellation_confirmed)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!token.valid() || token.epoch != epoch_ || !latched_ ||
|
||||
!recovery_in_progress_ || !isMotionSafe(observed_) ||
|
||||
!robot_running || !controller_idle ||
|
||||
!cancellation_confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
latched_ = false;
|
||||
recovery_in_progress_ = false;
|
||||
latched_reason_ = SafetyCondition::Unknown;
|
||||
software_emergency_stop_latched_ = false;
|
||||
++epoch_;
|
||||
return true;
|
||||
}
|
||||
|
||||
// The caller may clear the physical E-stop latch only after it has powered
|
||||
// the controller, released the brakes, and then re-confirmed an empty,
|
||||
// steady controller in Running mode. This never authorizes replaying the
|
||||
// old target, runtime program, or servo session.
|
||||
bool completeHardwareEmergencyStopRecovery(
|
||||
const RecoveryToken token,
|
||||
const bool robot_running,
|
||||
const bool controller_idle,
|
||||
const bool cancellation_confirmed)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!token.valid() || token.epoch != epoch_ || !latched_ ||
|
||||
!recovery_in_progress_ ||
|
||||
software_emergency_stop_latched_ ||
|
||||
!isHardwareEmergencyStop(latched_reason_) ||
|
||||
!isMotionSafe(observed_) || !robot_running || !controller_idle ||
|
||||
!cancellation_confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
latched_ = false;
|
||||
recovery_in_progress_ = false;
|
||||
latched_reason_ = SafetyCondition::Unknown;
|
||||
++epoch_;
|
||||
return true;
|
||||
}
|
||||
|
||||
void failRecovery(const RecoveryToken token)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (token.valid() && token.epoch == epoch_) {
|
||||
recovery_in_progress_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
SafetySnapshot snapshot() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return {
|
||||
observed_,
|
||||
latched_reason_,
|
||||
epoch_,
|
||||
latched_,
|
||||
recovery_in_progress_,
|
||||
software_emergency_stop_latched_};
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
SafetyCondition observed_{SafetyCondition::Unknown};
|
||||
SafetyCondition latched_reason_{SafetyCondition::Unknown};
|
||||
std::uint64_t epoch_{1};
|
||||
bool latched_{false};
|
||||
bool recovery_in_progress_{false};
|
||||
bool software_emergency_stop_latched_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device::aubo_internal
|
||||
|
||||
#endif // CMVR_ES_AUBO_SAFETY_STATE_H
|
||||
50
cmvr-es/devices/arm/aubo_arm/aubo_torque_on_result.h
Normal file
50
cmvr-es/devices/arm/aubo_arm/aubo_torque_on_result.h
Normal file
@ -0,0 +1,50 @@
|
||||
#ifndef CMVR_ES_AUBO_TORQUE_ON_RESULT_H
|
||||
#define CMVR_ES_AUBO_TORQUE_ON_RESULT_H
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::device::aubo_internal {
|
||||
|
||||
inline Result preservePrimaryTorqueOnFailure(
|
||||
Result primary_failure,
|
||||
const std::optional<Result>& cancellation_outcome)
|
||||
{
|
||||
if (!cancellation_outcome.has_value() ||
|
||||
cancellation_outcome->message.empty()) {
|
||||
return primary_failure;
|
||||
}
|
||||
|
||||
if (!primary_failure.message.empty()) {
|
||||
primary_failure.message += "; ";
|
||||
}
|
||||
primary_failure.message +=
|
||||
"cancellation handling: " + cancellation_outcome->message;
|
||||
return primary_failure;
|
||||
}
|
||||
|
||||
template <typename Mutation, typename FailureResult,
|
||||
typename CancellationOutcome>
|
||||
std::optional<Result> runTorqueOnControllerMutation(
|
||||
const int success_code,
|
||||
Mutation&& mutation,
|
||||
FailureResult&& failure_result,
|
||||
CancellationOutcome&& cancellation_outcome)
|
||||
{
|
||||
const int return_code = std::forward<Mutation>(mutation)();
|
||||
if (return_code != success_code) {
|
||||
auto primary_failure =
|
||||
std::forward<FailureResult>(failure_result)(return_code);
|
||||
return preservePrimaryTorqueOnFailure(
|
||||
std::move(primary_failure),
|
||||
std::forward<CancellationOutcome>(cancellation_outcome)());
|
||||
}
|
||||
return std::forward<CancellationOutcome>(cancellation_outcome)();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device::aubo_internal
|
||||
|
||||
#endif // CMVR_ES_AUBO_TORQUE_ON_RESULT_H
|
||||
@ -1,575 +0,0 @@
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <exception>
|
||||
#include <thread>
|
||||
|
||||
#include "common/base/logging/logger.h"
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
#include "aubo_sdk/rpc.h"
|
||||
#endif
|
||||
|
||||
namespace cmvr::device {
|
||||
namespace {
|
||||
|
||||
struct BusyGuard {
|
||||
std::atomic<bool>& busy;
|
||||
~BusyGuard() { busy.store(false); }
|
||||
};
|
||||
|
||||
std::vector<std::string> defaultJointNames(const std::size_t dof)
|
||||
{
|
||||
std::vector<std::string> names;
|
||||
names.reserve(dof);
|
||||
for (std::size_t i = 0; i < dof; ++i) {
|
||||
names.push_back("joint_" + std::to_string(i + 1));
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
std::string vendorBrandName(const config::VendorRobotArmBrand brand)
|
||||
{
|
||||
switch (brand) {
|
||||
case config::VENDOR_ROBOT_ARM_BRAND_AUBO_ARM:
|
||||
return "AuboARM";
|
||||
case config::VENDOR_ROBOT_ARM_BRAND_UNKNOWN:
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
struct AuboArm::SdkState {
|
||||
std::shared_ptr<arcs::aubo_sdk::RpcClient> rpc_client;
|
||||
};
|
||||
#endif
|
||||
|
||||
AuboArm::AuboArm(const config::RobotArmConfig& cfg)
|
||||
: cfg_(cfg)
|
||||
{
|
||||
id_ = cfg.id();
|
||||
if (cfg.has_vendor()) {
|
||||
vendor_cfg_ = cfg.vendor();
|
||||
}
|
||||
|
||||
ip_ = vendor_cfg_.ip();
|
||||
port_ = vendor_cfg_.port() > 0 ? vendor_cfg_.port() : 30004;
|
||||
username_ = vendor_cfg_.username().empty() ? "aubo" : vendor_cfg_.username();
|
||||
password_ = vendor_cfg_.password().empty() ? "123456" : vendor_cfg_.password();
|
||||
|
||||
const auto dof = vendor_cfg_.dof() > 0 ? static_cast<std::size_t>(vendor_cfg_.dof()) : 6U;
|
||||
model_.name = vendor_cfg_.model().empty() ? "AuboARM" : vendor_cfg_.model();
|
||||
model_.manufacturer = vendorBrandName(vendor_cfg_.brand());
|
||||
model_.dof = dof;
|
||||
model_.joint_names.assign(vendor_cfg_.joint_names().begin(), vendor_cfg_.joint_names().end());
|
||||
if (model_.joint_names.empty()) {
|
||||
model_.joint_names = defaultJointNames(dof);
|
||||
}
|
||||
if (model_.joint_names.size() != dof) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] joint_names size mismatch, id=" << id_;
|
||||
model_.joint_names = defaultJointNames(dof);
|
||||
}
|
||||
}
|
||||
|
||||
AuboArm::~AuboArm()
|
||||
{
|
||||
(void)disconnect();
|
||||
}
|
||||
|
||||
bool AuboArm::init()
|
||||
{
|
||||
if (ip_.empty()) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] ip is empty, id=" << id_;
|
||||
return false;
|
||||
}
|
||||
const auto result = connect(ip_, port_);
|
||||
if (!result.ok()) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] init failed: " << result.message;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AuboArm::stop()
|
||||
{
|
||||
return stopMotion().ok();
|
||||
}
|
||||
|
||||
ArmState AuboArm::getRobotState() const
|
||||
{
|
||||
ArmState state;
|
||||
state.connected = connected_.load();
|
||||
state.powered_on = state.connected;
|
||||
state.brake_released = state.connected;
|
||||
state.moving = busy_.load();
|
||||
state.robot_mode = getRobotMode();
|
||||
state.safety_mode = getSafetyMode();
|
||||
state.control_mode = getControlMode();
|
||||
state.emergency_stopped = emergency_stopped_;
|
||||
state.speed_scaling = speed_scaling_;
|
||||
state.actual_joint_state = getJointState();
|
||||
state.target_joint_state = state.actual_joint_state;
|
||||
return state;
|
||||
}
|
||||
|
||||
JointGroupState AuboArm::getJointState() const
|
||||
{
|
||||
JointGroupState state;
|
||||
state.position.assign(model_.dof, 0.0);
|
||||
state.velocity.assign(model_.dof, 0.0);
|
||||
state.effort.assign(model_.dof, 0.0);
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (!connected_.load() || !sdk_ || !sdk_->rpc_client) {
|
||||
return state;
|
||||
}
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] getJointState failed: robot name list is empty";
|
||||
return state;
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] getJointState failed: robot interface is null";
|
||||
return state;
|
||||
}
|
||||
const auto robot_state = robot_interface->getRobotState();
|
||||
const auto positions = robot_state->getJointPositions();
|
||||
const auto velocities = robot_state->getJointSpeeds();
|
||||
const auto n = std::min<std::size_t>(model_.dof, positions.size());
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
state.position[i] = positions[i];
|
||||
}
|
||||
const auto vn = std::min<std::size_t>(model_.dof, velocities.size());
|
||||
for (std::size_t i = 0; i < vn; ++i) {
|
||||
state.velocity[i] = velocities[i];
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] getJointState failed: " << e.what();
|
||||
}
|
||||
#endif
|
||||
return state;
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::getTcpPose(FrameType frame) const
|
||||
{
|
||||
(void)frame;
|
||||
return {};
|
||||
}
|
||||
|
||||
RobotMode AuboArm::getRobotMode() const
|
||||
{
|
||||
if (!connected_.load()) {
|
||||
return RobotMode::Disconnected;
|
||||
}
|
||||
if (emergency_stopped_) {
|
||||
return RobotMode::Stopped;
|
||||
}
|
||||
return busy_.load() ? RobotMode::Running : RobotMode::Idle;
|
||||
}
|
||||
|
||||
Result AuboArm::torqueOn()
|
||||
{
|
||||
const auto ready = ensureConnected_("torqueOn");
|
||||
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");
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] robot interface is null");
|
||||
}
|
||||
|
||||
double mass = 0.0;
|
||||
std::vector<double> cog(3, 0.0);
|
||||
std::vector<double> aom(3, 0.0);
|
||||
std::vector<double> inertia(6, 0.0);
|
||||
robot_interface->getRobotConfig()->setPayload(mass, cog, aom, inertia);
|
||||
|
||||
if (robot_interface->getRobotState()->getRobotModeType() !=
|
||||
arcs::common_interface::RobotModeType::Running) {
|
||||
robot_interface->getRobotManage()->poweron();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
robot_interface->getRobotManage()->startup();
|
||||
}
|
||||
emergency_stopped_ = false;
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm] torqueOn failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("torqueOn");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::torqueOff()
|
||||
{
|
||||
const auto ready = ensureConnected_("torqueOff");
|
||||
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");
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] robot interface is null");
|
||||
}
|
||||
robot_interface->getRobotManage()->poweroff();
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm] torqueOff failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("torqueOff");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::calibrateZeroQ(const std::string& joint_name)
|
||||
{
|
||||
(void)joint_name;
|
||||
return unsupported_("calibrateZeroQ");
|
||||
}
|
||||
|
||||
Result AuboArm::emergencyStop()
|
||||
{
|
||||
emergency_stopped_ = true;
|
||||
return stopMotion();
|
||||
}
|
||||
|
||||
Result AuboArm::setSpeedScaling(const double scaling)
|
||||
{
|
||||
if (scaling < 0.0 || scaling > 1.0) {
|
||||
return Result::failure(ArmErrorCode::InvalidArgument, "speed scaling must be in [0, 1]");
|
||||
}
|
||||
speed_scaling_ = scaling;
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result AuboArm::moveJ(const JointPositionCommand& target, const MotionOptions& options)
|
||||
{
|
||||
std::string error;
|
||||
if (!validDof_(target.position.size(), error)) {
|
||||
return Result::failure(ArmErrorCode::InvalidDof, error);
|
||||
}
|
||||
const auto ready = ensureConnected_("moveJ");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
if (busy_.exchange(true)) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] arm is busy: " + id_);
|
||||
}
|
||||
BusyGuard busy_guard{busy_};
|
||||
|
||||
#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");
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] robot interface is null");
|
||||
}
|
||||
robot_interface->getMotionControl()->setSpeedFraction(speed_scaling_);
|
||||
robot_interface->getMotionControl()->moveJoint(
|
||||
target.position,
|
||||
options.acceleration > 0.0 ? options.acceleration : 0.5,
|
||||
options.velocity > 0.0 ? options.velocity : 0.5,
|
||||
options.blend_radius,
|
||||
0);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm] moveJ failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("moveJ");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::speedJ(const JointVelocityCommand& velocity, double acceleration, double duration)
|
||||
{
|
||||
(void)velocity;
|
||||
(void)acceleration;
|
||||
(void)duration;
|
||||
return unsupported_("speedJ");
|
||||
}
|
||||
|
||||
Result AuboArm::stopJ(double acceleration)
|
||||
{
|
||||
(void)acceleration;
|
||||
return stopMotion();
|
||||
}
|
||||
|
||||
Result AuboArm::moveL(const CartesianPose& target, const MotionOptions& options, FrameType frame)
|
||||
{
|
||||
(void)frame;
|
||||
const auto ready = ensureConnected_("moveL");
|
||||
if (!ready.ok()) {
|
||||
return ready;
|
||||
}
|
||||
if (busy_.exchange(true)) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] arm is busy: " + id_);
|
||||
}
|
||||
BusyGuard busy_guard{busy_};
|
||||
|
||||
#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");
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (!robot_interface) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[AuboArm] robot interface is null");
|
||||
}
|
||||
robot_interface->getMotionControl()->setSpeedFraction(speed_scaling_);
|
||||
std::vector<double> tcp_offset(6, 0.0);
|
||||
robot_interface->getRobotConfig()->setTcpOffset(tcp_offset);
|
||||
std::vector<double> pose{target.x, target.y, target.z, target.rx, target.ry, target.rz};
|
||||
robot_interface->getMotionControl()->moveLine(
|
||||
pose,
|
||||
options.acceleration > 0.0 ? options.acceleration : 0.5,
|
||||
options.velocity > 0.0 ? options.velocity : 0.25,
|
||||
options.blend_radius,
|
||||
0);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm] moveL failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
return unsupported_("moveL");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::speedL(const CartesianVelocity& velocity, double acceleration, double duration, FrameType frame)
|
||||
{
|
||||
(void)velocity;
|
||||
(void)acceleration;
|
||||
(void)duration;
|
||||
(void)frame;
|
||||
return unsupported_("speedL");
|
||||
}
|
||||
|
||||
Result AuboArm::stopL(std::optional<double> acceleration)
|
||||
{
|
||||
(void)acceleration;
|
||||
return stopMotion();
|
||||
}
|
||||
|
||||
Result AuboArm::stopMotion()
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (!connected_.load() || !sdk_ || !sdk_->rpc_client) {
|
||||
return Result::success();
|
||||
}
|
||||
try {
|
||||
const auto robot_names = sdk_->rpc_client->getRobotNames();
|
||||
if (robot_names.empty()) {
|
||||
return Result::success();
|
||||
}
|
||||
auto robot_interface = sdk_->rpc_client->getRobotInterface(robot_names.front());
|
||||
if (robot_interface) {
|
||||
robot_interface->getMotionControl()->stopMove();
|
||||
}
|
||||
busy_.store(false);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, std::string("[AuboArm] stopMotion failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
busy_.store(false);
|
||||
return Result::success();
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::startServoMode(const ServoOptions& options)
|
||||
{
|
||||
(void)options;
|
||||
return unsupported_("startServoMode");
|
||||
}
|
||||
|
||||
Result AuboArm::servoJ(const JointPositionCommand& target)
|
||||
{
|
||||
(void)target;
|
||||
return unsupported_("servoJ");
|
||||
}
|
||||
|
||||
Result AuboArm::servoL(const CartesianPose& target, FrameType frame)
|
||||
{
|
||||
(void)target;
|
||||
(void)frame;
|
||||
return unsupported_("servoL");
|
||||
}
|
||||
|
||||
Result AuboArm::servoSpeedJ(const JointVelocityCommand& velocity)
|
||||
{
|
||||
(void)velocity;
|
||||
return unsupported_("servoSpeedJ");
|
||||
}
|
||||
|
||||
Result AuboArm::servoSpeedL(const CartesianVelocity& velocity, FrameType frame)
|
||||
{
|
||||
(void)velocity;
|
||||
(void)frame;
|
||||
return unsupported_("servoSpeedL");
|
||||
}
|
||||
|
||||
Result AuboArm::stopServoMode()
|
||||
{
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result AuboArm::connect(const std::string& ip, const int port)
|
||||
{
|
||||
if (connected_.load()) {
|
||||
return Result::success();
|
||||
}
|
||||
if (ip.empty()) {
|
||||
return Result::failure(ArmErrorCode::InvalidArgument, "[AuboArm] ip is empty");
|
||||
}
|
||||
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
sdk_ = std::make_unique<SdkState>();
|
||||
sdk_->rpc_client = std::make_shared<arcs::aubo_sdk::RpcClient>();
|
||||
sdk_->rpc_client->setRequestTimeout(1000);
|
||||
sdk_->rpc_client->connect(ip, port > 0 ? port : 30004);
|
||||
sdk_->rpc_client->login(username_, password_);
|
||||
ip_ = ip;
|
||||
port_ = port > 0 ? port : 30004;
|
||||
connected_.store(true);
|
||||
return Result::success();
|
||||
} catch (const std::exception& e) {
|
||||
sdk_.reset();
|
||||
connected_.store(false);
|
||||
return Result::failure(ArmErrorCode::ConnectionFailed,
|
||||
std::string("[AuboArm] connect failed: ") + e.what());
|
||||
}
|
||||
#else
|
||||
(void)port;
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand,
|
||||
"[AuboArm] Aubo SDK is not available in this build");
|
||||
#endif
|
||||
}
|
||||
|
||||
Result AuboArm::disconnect()
|
||||
{
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
try {
|
||||
if (sdk_ && sdk_->rpc_client) {
|
||||
sdk_->rpc_client->logout();
|
||||
sdk_->rpc_client->disconnect();
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CMVR_LOG(ERROR) << "[AuboArm] disconnect failed: " << e.what();
|
||||
}
|
||||
sdk_.reset();
|
||||
#endif
|
||||
connected_.store(false);
|
||||
busy_.store(false);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result AuboArm::shutdown()
|
||||
{
|
||||
(void)stopMotion();
|
||||
return disconnect();
|
||||
}
|
||||
|
||||
Result AuboArm::loadProgram(const std::string& program_name)
|
||||
{
|
||||
(void)program_name;
|
||||
return unsupported_("loadProgram");
|
||||
}
|
||||
|
||||
Result AuboArm::playProgram()
|
||||
{
|
||||
return unsupported_("playProgram");
|
||||
}
|
||||
|
||||
Result AuboArm::pauseProgram()
|
||||
{
|
||||
return unsupported_("pauseProgram");
|
||||
}
|
||||
|
||||
Result AuboArm::stopProgram()
|
||||
{
|
||||
return unsupported_("stopProgram");
|
||||
}
|
||||
|
||||
std::vector<double> AuboArm::ik(const std::string& base_link,
|
||||
const std::string& ee_link,
|
||||
const CartesianPose& pose)
|
||||
{
|
||||
(void)base_link;
|
||||
(void)ee_link;
|
||||
(void)pose;
|
||||
CMVR_LOG(ERROR) << "[AuboArm] ik is not implemented";
|
||||
return {};
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(const std::string& base_link, const std::string& ee_link)
|
||||
{
|
||||
(void)base_link;
|
||||
(void)ee_link;
|
||||
CMVR_LOG(ERROR) << "[AuboArm] fk(base,ee) is not implemented";
|
||||
return {};
|
||||
}
|
||||
|
||||
CartesianPose AuboArm::fk(bool is_tcp)
|
||||
{
|
||||
(void)is_tcp;
|
||||
CMVR_LOG(ERROR) << "[AuboArm] fk is not implemented";
|
||||
return {};
|
||||
}
|
||||
|
||||
Result AuboArm::unsupported_(const std::string& name) const
|
||||
{
|
||||
const std::string message = "[AuboArm] " + name + " is not implemented";
|
||||
CMVR_LOG(ERROR) << message;
|
||||
return Result::failure(ArmErrorCode::UnsupportedCommand, message);
|
||||
}
|
||||
|
||||
bool AuboArm::validDof_(const std::size_t size, std::string& error) const
|
||||
{
|
||||
if (size != model_.dof) {
|
||||
error = "[AuboArm] command dof mismatch, expected=" + std::to_string(model_.dof) +
|
||||
", actual=" + std::to_string(size);
|
||||
CMVR_LOG(ERROR) << error;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Result AuboArm::ensureConnected_(const std::string& context) const
|
||||
{
|
||||
if (!connected_.load()) {
|
||||
return Result::failure(ArmErrorCode::NotConnected,
|
||||
"[AuboArm] " + context + " failed: arm is not connected");
|
||||
}
|
||||
#if defined(CMVR_HAS_AUBO_SDK)
|
||||
if (!sdk_ || !sdk_->rpc_client) {
|
||||
return Result::failure(ArmErrorCode::NotConnected,
|
||||
"[AuboArm] " + context + " failed: SDK client is null");
|
||||
}
|
||||
#endif
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
} // namespace cmvr::device
|
||||
@ -1,5 +1,7 @@
|
||||
add_library(huayan_arm SHARED huayan_arm.cpp)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
set(HUAYAN_ARM_SDK_DIR ${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/huayan_arm/v1.0)
|
||||
|
||||
target_include_directories(huayan_arm
|
||||
@ -20,6 +22,7 @@ target_link_libraries(huayan_arm
|
||||
PRIVATE
|
||||
HR_Pro
|
||||
glog
|
||||
Threads::Threads
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::huayan_arm ALIAS huayan_arm)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -9,12 +9,18 @@
|
||||
#define CMVR_ES_HUAYAN_ROBOT_H
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "devices/arm/huayan_arm/huayan_lifecycle_state.h"
|
||||
#include "devices/arm/robot_arm.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
@ -35,15 +41,16 @@ public:
|
||||
CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override;
|
||||
RobotMode getRobotMode() const override;
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override { return servo_mode_.load() ? ControlMode::Servo : ControlMode::Position; }
|
||||
ControlMode getControlMode() const override;
|
||||
bool supportsActionQueueMotion() const noexcept override { return true; }
|
||||
|
||||
Result torqueOn() override;
|
||||
Result torqueOff() override;
|
||||
Result calibrateZeroQ(const std::string& joint_name) override;
|
||||
Result emergencyStop() override;
|
||||
Result protectiveStop() override { return emergencyStop(); }
|
||||
Result protectiveStop() override;
|
||||
Result setSpeedScaling(double scaling) override;
|
||||
double getSpeedScaling() const override { return speed_scaling_; }
|
||||
double getSpeedScaling() const override { return speed_scaling_.load(); }
|
||||
bool isProtectiveStopped() const override;
|
||||
bool isEmergencyStopped() const override;
|
||||
bool isFault() const override;
|
||||
@ -71,7 +78,7 @@ public:
|
||||
Result brakeRelease() override { return torqueOn(); }
|
||||
Result shutdown() override;
|
||||
Result clearFault() override;
|
||||
Result unlockProtectiveStop() override { return clearFault(); }
|
||||
Result unlockProtectiveStop() override;
|
||||
Result loadProgram(const std::string& program_name) override;
|
||||
Result playProgram() override;
|
||||
Result pauseProgram() override;
|
||||
@ -84,7 +91,7 @@ public:
|
||||
CartesianPose fk(const std::string& base_link, const std::string& ee_link) override;
|
||||
CartesianPose fk(bool is_tcp = true) override;
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override;
|
||||
bool busy() const override { return busy_.load(); }
|
||||
bool busy() const override;
|
||||
|
||||
private:
|
||||
struct HrState {
|
||||
@ -101,21 +108,69 @@ private:
|
||||
int connected_to_box{0};
|
||||
int blending_done{0};
|
||||
int in_pos{0};
|
||||
int emergency_signal_fault{0};
|
||||
int emergency_input{0};
|
||||
int safeguard_signal_fault{0};
|
||||
int safeguard_input{0};
|
||||
bool valid{false};
|
||||
};
|
||||
|
||||
struct RuntimeState;
|
||||
|
||||
Result ensureConnected_(const std::string& context) const;
|
||||
Result ensureMotionReady_(
|
||||
const std::string& context,
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
huayan_internal::SafetyPermit& permit) const;
|
||||
Result unsupported_(const std::string& name) const;
|
||||
Result hrResult_(int code, const std::string& context) const;
|
||||
Result motionStartFailure_(
|
||||
const std::string& context,
|
||||
huayan_internal::MotionStartStatus status) const;
|
||||
bool validDof_(std::size_t size, std::string& error) const;
|
||||
HrState readHrState_() const;
|
||||
HrState sampleHrState_(
|
||||
const std::shared_ptr<RuntimeState>& runtime) const;
|
||||
void publishHrState_(
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
const HrState& state) const;
|
||||
std::vector<double> readJointPositionRad_() const;
|
||||
std::vector<double> readJointVelocityRad_() const;
|
||||
CartesianPose readTcpPose_() const;
|
||||
CartesianVelocity readTcpVelocity_() const;
|
||||
bool readJointPositionSample_(std::vector<double>& values) const;
|
||||
bool readJointVelocitySample_(std::vector<double>& values) const;
|
||||
bool readTcpPoseSample_(CartesianPose& pose) const;
|
||||
std::vector<double> currentJointPositionDeg_() const;
|
||||
std::string nextCommandId_() const;
|
||||
Result waitMotionDone_(const std::string& context, int timeout_ms) const;
|
||||
Result waitMotionDone_(
|
||||
const std::string& context,
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
huayan_internal::MotionToken motion_token,
|
||||
huayan_internal::SafetyPermit safety_permit,
|
||||
const std::string& command_id,
|
||||
const std::vector<double>* joint_target,
|
||||
const CartesianPose* tcp_target,
|
||||
int timeout_ms,
|
||||
const std::function<bool()>& cancellation_requested = {}) const;
|
||||
bool targetReached_(
|
||||
const std::vector<double>* joint_target,
|
||||
const CartesianPose* tcp_target) const;
|
||||
bool controllerIdleStable_(
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
std::chrono::milliseconds timeout) const;
|
||||
bool terminateController_(
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
std::chrono::milliseconds timeout,
|
||||
bool stop_program) const;
|
||||
Result completeSafetyRecovery_(
|
||||
const std::string& context,
|
||||
const std::shared_ptr<RuntimeState>& runtime,
|
||||
std::uint64_t expected_epoch,
|
||||
bool enable_robot,
|
||||
bool release_software_guard);
|
||||
std::shared_ptr<RuntimeState> runtimeSnapshot_() const;
|
||||
void safetyMonitorLoop_(const std::shared_ptr<RuntimeState>& runtime);
|
||||
|
||||
private:
|
||||
config::RobotArmConfig cfg_;
|
||||
@ -127,12 +182,16 @@ private:
|
||||
unsigned int robot_id_{0};
|
||||
std::string tcp_name_{"TCP"};
|
||||
std::string ucs_name_{"Base"};
|
||||
double speed_scaling_{1.0};
|
||||
std::atomic<double> speed_scaling_{1.0};
|
||||
std::atomic<bool> connected_{false};
|
||||
std::atomic<bool> busy_{false};
|
||||
std::atomic<bool> servo_mode_{false};
|
||||
mutable std::atomic<bool> servo_mode_{false};
|
||||
std::atomic<bool> software_emergency_stopped_{false};
|
||||
std::atomic<bool> software_protective_stopped_{false};
|
||||
mutable std::mutex mutex_;
|
||||
mutable std::recursive_mutex sdk_mutex_;
|
||||
mutable std::atomic<unsigned long long> command_seq_{0};
|
||||
std::shared_ptr<RuntimeState> runtime_;
|
||||
std::thread safety_monitor_thread_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
504
cmvr-es/devices/arm/huayan_arm/huayan_lifecycle_state.h
Normal file
504
cmvr-es/devices/arm/huayan_arm/huayan_lifecycle_state.h
Normal file
@ -0,0 +1,504 @@
|
||||
#ifndef CMVR_ES_HUAYAN_LIFECYCLE_STATE_H
|
||||
#define CMVR_ES_HUAYAN_LIFECYCLE_STATE_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace cmvr::device::huayan_internal {
|
||||
|
||||
enum class MotionKind {
|
||||
None,
|
||||
Joint,
|
||||
Linear,
|
||||
SpeedJoint,
|
||||
SpeedLinear,
|
||||
Servo,
|
||||
Program,
|
||||
};
|
||||
|
||||
struct MotionToken {
|
||||
std::uint64_t generation{0};
|
||||
MotionKind kind{MotionKind::None};
|
||||
|
||||
bool valid() const noexcept
|
||||
{
|
||||
return generation != 0 && kind != MotionKind::None;
|
||||
}
|
||||
};
|
||||
|
||||
enum class MotionStartStatus {
|
||||
Started,
|
||||
Invalid,
|
||||
Busy,
|
||||
Stopping,
|
||||
Blocked,
|
||||
};
|
||||
|
||||
struct MotionStartResult {
|
||||
MotionStartStatus status{MotionStartStatus::Busy};
|
||||
MotionToken token;
|
||||
|
||||
bool started() const noexcept
|
||||
{
|
||||
return status == MotionStartStatus::Started;
|
||||
}
|
||||
};
|
||||
|
||||
enum class MotionFinishMode {
|
||||
RestorePrevious,
|
||||
Clear,
|
||||
Retain,
|
||||
};
|
||||
|
||||
enum class StopStartStatus {
|
||||
Started,
|
||||
AlreadyStopping,
|
||||
};
|
||||
|
||||
struct StopRequest {
|
||||
StopStartStatus status{StopStartStatus::AlreadyStopping};
|
||||
MotionKind kind{MotionKind::None};
|
||||
MotionToken active_token;
|
||||
bool tracked_motion{false};
|
||||
|
||||
bool started() const noexcept
|
||||
{
|
||||
return status == StopStartStatus::Started;
|
||||
}
|
||||
};
|
||||
|
||||
struct SafetyCancelResult {
|
||||
MotionKind kind{MotionKind::None};
|
||||
MotionToken active_token;
|
||||
bool tracked_motion{false};
|
||||
};
|
||||
|
||||
struct MotionSnapshot {
|
||||
MotionKind active_kind{MotionKind::None};
|
||||
MotionKind retained_kind{MotionKind::None};
|
||||
std::uint64_t active_generation{0};
|
||||
bool owner_active{false};
|
||||
bool stop_in_progress{false};
|
||||
bool blocked{false};
|
||||
};
|
||||
|
||||
// Tracks a single Huayan controller operation owner. Generation tokens make
|
||||
// completion from an older RPC harmless after Stop or a safety event has
|
||||
// cancelled it. Servo and program operations may retain their kind after the
|
||||
// submitting RPC returns; begin(kind, true) supports same-kind updates while
|
||||
// that retained controller mode remains active.
|
||||
class MotionState final {
|
||||
public:
|
||||
MotionStartResult begin(
|
||||
const MotionKind kind,
|
||||
const bool replace_retained_same_kind = false)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (kind == MotionKind::None) {
|
||||
return {MotionStartStatus::Invalid, {}};
|
||||
}
|
||||
if (stop_in_progress_) {
|
||||
return {MotionStartStatus::Stopping, {}};
|
||||
}
|
||||
if (blocked_) {
|
||||
return {MotionStartStatus::Blocked, {}};
|
||||
}
|
||||
if (owner_active_) {
|
||||
return {MotionStartStatus::Busy, {}};
|
||||
}
|
||||
if (retained_kind_ != MotionKind::None &&
|
||||
(!replace_retained_same_kind || retained_kind_ != kind)) {
|
||||
return {MotionStartStatus::Busy, {}};
|
||||
}
|
||||
|
||||
const MotionToken token{++next_generation_, kind};
|
||||
owner_active_ = true;
|
||||
active_token_ = token;
|
||||
previous_kind_ = retained_kind_;
|
||||
return {MotionStartStatus::Started, token};
|
||||
}
|
||||
|
||||
void finish(
|
||||
const MotionToken token,
|
||||
const MotionFinishMode mode = MotionFinishMode::RestorePrevious)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!owner_active_ ||
|
||||
active_token_.generation != token.generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
owner_active_ = false;
|
||||
active_token_ = {};
|
||||
if (!stop_in_progress_ && !blocked_) {
|
||||
switch (mode) {
|
||||
case MotionFinishMode::RestorePrevious:
|
||||
retained_kind_ = previous_kind_;
|
||||
break;
|
||||
case MotionFinishMode::Clear:
|
||||
retained_kind_ = MotionKind::None;
|
||||
break;
|
||||
case MotionFinishMode::Retain:
|
||||
retained_kind_ = token.kind;
|
||||
break;
|
||||
}
|
||||
}
|
||||
previous_kind_ = MotionKind::None;
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
|
||||
void failMotion(const MotionToken token)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!owner_active_ ||
|
||||
active_token_.generation != token.generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
owner_active_ = false;
|
||||
active_token_ = {};
|
||||
retained_kind_ = token.kind;
|
||||
previous_kind_ = MotionKind::None;
|
||||
blocked_ = true;
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
|
||||
StopRequest beginStop(
|
||||
const MotionKind requested_kind = MotionKind::None)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (stop_in_progress_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
stop_in_progress_ = true;
|
||||
const MotionToken active = owner_active_
|
||||
? active_token_
|
||||
: MotionToken{};
|
||||
if (active.valid()) {
|
||||
cancelled_generation_ = std::max(
|
||||
cancelled_generation_, active.generation);
|
||||
}
|
||||
|
||||
MotionKind kind = MotionKind::None;
|
||||
if (active.valid()) {
|
||||
kind = active.kind;
|
||||
} else if (retained_kind_ != MotionKind::None) {
|
||||
kind = retained_kind_;
|
||||
} else {
|
||||
kind = requested_kind;
|
||||
}
|
||||
if (kind != MotionKind::None) {
|
||||
retained_kind_ = kind;
|
||||
}
|
||||
|
||||
return {
|
||||
StopStartStatus::Started,
|
||||
kind,
|
||||
active,
|
||||
active.valid() || kind != MotionKind::None};
|
||||
}
|
||||
|
||||
SafetyCancelResult cancelActiveForSafety()
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const MotionToken active = owner_active_
|
||||
? active_token_
|
||||
: MotionToken{};
|
||||
if (active.valid()) {
|
||||
cancelled_generation_ = std::max(
|
||||
cancelled_generation_, active.generation);
|
||||
}
|
||||
|
||||
const MotionKind kind = active.valid()
|
||||
? active.kind
|
||||
: retained_kind_;
|
||||
if (kind != MotionKind::None) {
|
||||
retained_kind_ = kind;
|
||||
}
|
||||
// A hardware safety transition is independent of a concurrent
|
||||
// software Stop. New controller operations remain rejected until
|
||||
// termination is positively confirmed.
|
||||
blocked_ = true;
|
||||
owner_finished_cv_.notify_all();
|
||||
return {kind, active, active.valid() || kind != MotionKind::None};
|
||||
}
|
||||
|
||||
bool cancelled(const MotionToken token) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return token.valid() &&
|
||||
token.generation <= cancelled_generation_;
|
||||
}
|
||||
|
||||
bool waitForOwnerExit(
|
||||
const MotionToken token,
|
||||
const std::chrono::milliseconds timeout)
|
||||
{
|
||||
if (!token.valid()) {
|
||||
return true;
|
||||
}
|
||||
std::unique_lock lock(mutex_);
|
||||
return owner_finished_cv_.wait_for(
|
||||
lock,
|
||||
timeout,
|
||||
[this, token]() {
|
||||
return !owner_active_ ||
|
||||
active_token_.generation != token.generation;
|
||||
});
|
||||
}
|
||||
|
||||
bool ownerActive(const MotionToken token) const
|
||||
{
|
||||
if (!token.valid()) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard lock(mutex_);
|
||||
return owner_active_ &&
|
||||
active_token_.generation == token.generation;
|
||||
}
|
||||
|
||||
bool completeStop()
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (owner_active_) {
|
||||
return false;
|
||||
}
|
||||
stop_in_progress_ = false;
|
||||
blocked_ = false;
|
||||
active_token_ = {};
|
||||
retained_kind_ = MotionKind::None;
|
||||
previous_kind_ = MotionKind::None;
|
||||
owner_finished_cv_.notify_all();
|
||||
return true;
|
||||
}
|
||||
|
||||
void failStop()
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
stop_in_progress_ = false;
|
||||
blocked_ = true;
|
||||
owner_finished_cv_.notify_all();
|
||||
}
|
||||
|
||||
MotionSnapshot snapshot() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return {
|
||||
owner_active_ ? active_token_.kind : MotionKind::None,
|
||||
retained_kind_,
|
||||
owner_active_ ? active_token_.generation : 0,
|
||||
owner_active_,
|
||||
stop_in_progress_,
|
||||
blocked_};
|
||||
}
|
||||
|
||||
bool busy() const
|
||||
{
|
||||
const auto state = snapshot();
|
||||
return state.owner_active || state.stop_in_progress ||
|
||||
state.blocked ||
|
||||
state.retained_kind != MotionKind::None;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable owner_finished_cv_;
|
||||
std::uint64_t next_generation_{0};
|
||||
std::uint64_t cancelled_generation_{0};
|
||||
MotionToken active_token_;
|
||||
MotionKind retained_kind_{MotionKind::None};
|
||||
MotionKind previous_kind_{MotionKind::None};
|
||||
bool owner_active_{false};
|
||||
bool stop_in_progress_{false};
|
||||
bool blocked_{false};
|
||||
};
|
||||
|
||||
enum class SafetyCondition {
|
||||
Unknown,
|
||||
Normal,
|
||||
EmergencyStop,
|
||||
SafeguardStop,
|
||||
RobotFault,
|
||||
EmergencySignalFault,
|
||||
SafeguardSignalFault,
|
||||
SoftwareEmergencyStop,
|
||||
SoftwareProtectiveStop,
|
||||
};
|
||||
|
||||
struct RawSafetyState {
|
||||
bool valid{false};
|
||||
int emergency_signal_fault{0};
|
||||
int emergency_stop{0};
|
||||
int safeguard_signal_fault{0};
|
||||
int safeguard_stop{0};
|
||||
int robot_fault{0};
|
||||
bool software_emergency_stop{false};
|
||||
bool software_protective_stop{false};
|
||||
};
|
||||
|
||||
inline SafetyCondition classifySafetyCondition(
|
||||
const RawSafetyState& state) noexcept
|
||||
{
|
||||
if (!state.valid) {
|
||||
return SafetyCondition::Unknown;
|
||||
}
|
||||
if (state.emergency_signal_fault != 0) {
|
||||
return SafetyCondition::EmergencySignalFault;
|
||||
}
|
||||
if (state.safeguard_signal_fault != 0) {
|
||||
return SafetyCondition::SafeguardSignalFault;
|
||||
}
|
||||
if (state.emergency_stop != 0) {
|
||||
return SafetyCondition::EmergencyStop;
|
||||
}
|
||||
if (state.safeguard_stop != 0) {
|
||||
return SafetyCondition::SafeguardStop;
|
||||
}
|
||||
if (state.robot_fault != 0) {
|
||||
return SafetyCondition::RobotFault;
|
||||
}
|
||||
if (state.software_emergency_stop) {
|
||||
return SafetyCondition::SoftwareEmergencyStop;
|
||||
}
|
||||
if (state.software_protective_stop) {
|
||||
return SafetyCondition::SoftwareProtectiveStop;
|
||||
}
|
||||
return SafetyCondition::Normal;
|
||||
}
|
||||
|
||||
inline bool isMotionSafe(const SafetyCondition condition) noexcept
|
||||
{
|
||||
return condition == SafetyCondition::Normal;
|
||||
}
|
||||
|
||||
struct SafetyPermit {
|
||||
std::uint64_t epoch{0};
|
||||
|
||||
bool valid() const noexcept { return epoch != 0; }
|
||||
};
|
||||
|
||||
struct RecoveryToken {
|
||||
std::uint64_t epoch{0};
|
||||
|
||||
bool valid() const noexcept { return epoch != 0; }
|
||||
};
|
||||
|
||||
struct SafetySnapshot {
|
||||
SafetyCondition observed{SafetyCondition::Unknown};
|
||||
SafetyCondition latched_reason{SafetyCondition::Unknown};
|
||||
std::uint64_t epoch{0};
|
||||
bool latched{false};
|
||||
bool recovery_in_progress{false};
|
||||
};
|
||||
|
||||
// Safety inputs are events, not merely levels. Returning to Normal never
|
||||
// clears a prior unsafe event. Explicit recovery is tied atomically to the
|
||||
// event epoch, so a second event invalidates an older in-flight recovery.
|
||||
class SafetyState final {
|
||||
public:
|
||||
void observe(const RawSafetyState& raw_state)
|
||||
{
|
||||
observe(classifySafetyCondition(raw_state));
|
||||
}
|
||||
|
||||
void observe(const SafetyCondition condition)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
const bool changed = observed_ != condition;
|
||||
observed_ = condition;
|
||||
if (isMotionSafe(condition)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!latched_ || recovery_in_progress_ || changed) {
|
||||
++epoch_;
|
||||
}
|
||||
latched_ = true;
|
||||
recovery_in_progress_ = false;
|
||||
latched_reason_ = condition;
|
||||
}
|
||||
|
||||
std::optional<SafetyPermit> tryPermit() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (latched_ || !isMotionSafe(observed_)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return SafetyPermit{epoch_};
|
||||
}
|
||||
|
||||
bool validate(const SafetyPermit permit) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return permit.valid() && permit.epoch == epoch_ && !latched_ &&
|
||||
isMotionSafe(observed_);
|
||||
}
|
||||
|
||||
std::optional<RecoveryToken> beginRecovery(
|
||||
const std::uint64_t expected_epoch)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (expected_epoch == 0 || expected_epoch != epoch_ || !latched_ ||
|
||||
recovery_in_progress_ || !isMotionSafe(observed_)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
recovery_in_progress_ = true;
|
||||
return RecoveryToken{epoch_};
|
||||
}
|
||||
|
||||
bool completeRecovery(
|
||||
const RecoveryToken token,
|
||||
const bool robot_ready,
|
||||
const bool controller_idle,
|
||||
const bool cancellation_confirmed)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!token.valid() || token.epoch != epoch_ || !latched_ ||
|
||||
!recovery_in_progress_ || !isMotionSafe(observed_) ||
|
||||
!robot_ready || !controller_idle || !cancellation_confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
latched_ = false;
|
||||
recovery_in_progress_ = false;
|
||||
latched_reason_ = SafetyCondition::Unknown;
|
||||
++epoch_;
|
||||
return true;
|
||||
}
|
||||
|
||||
void failRecovery(const RecoveryToken token)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
if (token.valid() && token.epoch == epoch_) {
|
||||
recovery_in_progress_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
SafetySnapshot snapshot() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return {
|
||||
observed_,
|
||||
latched_reason_,
|
||||
epoch_,
|
||||
latched_,
|
||||
recovery_in_progress_};
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
SafetyCondition observed_{SafetyCondition::Unknown};
|
||||
SafetyCondition latched_reason_{SafetyCondition::Unknown};
|
||||
std::uint64_t epoch_{1};
|
||||
bool latched_{false};
|
||||
bool recovery_in_progress_{false};
|
||||
};
|
||||
|
||||
} // namespace cmvr::device::huayan_internal
|
||||
|
||||
#endif // CMVR_ES_HUAYAN_LIFECYCLE_STATE_H
|
||||
@ -26,6 +26,7 @@ add_executable(motor_robot_arm_mujoco_test
|
||||
target_link_libraries(motor_robot_arm_mujoco_test
|
||||
PRIVATE
|
||||
cmvr_es::device::motor_robot_arm
|
||||
cmvr_es::algorithms::arm_control
|
||||
cmvr_es::device::motor_manager
|
||||
cmvr_es::device::mujoco_motor_driver
|
||||
cmvr_es::mujoco_viewer
|
||||
|
||||
@ -36,6 +36,13 @@ public:
|
||||
RobotMode getRobotMode() const override { return RobotMode::Idle; }
|
||||
SafetyMode getSafetyMode() const override;
|
||||
ControlMode getControlMode() const override { return ControlMode::Position; }
|
||||
bool supportsTeleopGroupServo() const noexcept override
|
||||
{
|
||||
// commandCyclicPosition is currently dispatched one joint at a time.
|
||||
// A config switch cannot turn that partial-write behavior into the
|
||||
// atomic/timed group primitive required by network teleoperation.
|
||||
return false;
|
||||
}
|
||||
|
||||
Result torqueOn() override;
|
||||
Result torqueOff() override;
|
||||
@ -73,7 +80,7 @@ public:
|
||||
bool isConnected() const override { return motor_manager_ != nullptr; }
|
||||
Result powerOn() override { return torqueOn(); }
|
||||
Result powerOff() override { return torqueOff(); }
|
||||
Result brakeRelease() override { return torqueOn(); }
|
||||
Result brakeRelease() override;
|
||||
Result shutdown() override;
|
||||
Result clearFault() override { return Result::success(); }
|
||||
Result unlockProtectiveStop() override { return Result::success(); }
|
||||
@ -93,6 +100,12 @@ public:
|
||||
bool busy() const override;
|
||||
|
||||
private:
|
||||
enum class TrajectoryExecutionResult {
|
||||
Completed,
|
||||
Canceled,
|
||||
Failed,
|
||||
};
|
||||
|
||||
bool containsJoint_(const std::string& joint_name) const;
|
||||
bool validatePositionCommand_(const JointPositionCommand& cmd, std::string& error) const;
|
||||
bool validateVelocityCommand_(const JointVelocityCommand& cmd, std::string& error) const;
|
||||
@ -101,7 +114,10 @@ private:
|
||||
std::vector<double> readJointPosition_() const;
|
||||
|
||||
bool configureAlgorithms_();
|
||||
bool executeMoveLTrajectory_(const CartesianJointTrajectory& trajectory);
|
||||
TrajectoryExecutionResult executeMoveLTrajectory_(
|
||||
const CartesianJointTrajectory& trajectory,
|
||||
const std::function<bool()>& cancellation_requested,
|
||||
std::uint64_t motion_generation);
|
||||
|
||||
static CartesianVelocityController::Config toCartesianVelocityControllerConfig_(
|
||||
const config::CartesianVelocityControllerConfig& config);
|
||||
@ -117,6 +133,7 @@ private:
|
||||
std::unordered_set<std::string> joint_set_;
|
||||
std::string motor_system_id_;
|
||||
std::shared_ptr<MotorManager> motor_manager_{nullptr};
|
||||
std::uint64_t motor_control_claim_id_{0};
|
||||
|
||||
std::shared_ptr<cmvr::IKSolver> ik_solver_{nullptr};
|
||||
std::shared_ptr<JointMotionPlanner> joint_planner_{nullptr};
|
||||
@ -124,7 +141,10 @@ private:
|
||||
std::unique_ptr<CartesianVelocityController> cartesian_velocity_controller_{nullptr};
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<std::uint64_t> motion_generation_{0};
|
||||
std::atomic<bool> busy_{false};
|
||||
std::atomic<bool> powered_on_{false};
|
||||
mutable std::atomic<std::uint64_t> joint_state_sequence_{0};
|
||||
double speed_scaling_{1.0};
|
||||
bool emergency_stopped_{false};
|
||||
ServoOptions servo_options_;
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
#include "arm/motor_robot_arm/include/motor_robot_arm.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <Eigen/Dense>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
@ -28,6 +29,36 @@ struct BusyGuard {
|
||||
~BusyGuard() { busy.store(false); }
|
||||
};
|
||||
|
||||
bool cancellationRequested(
|
||||
const std::function<bool()>& cancellation_requested) noexcept
|
||||
{
|
||||
if (!cancellation_requested) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return cancellation_requested();
|
||||
} catch (...) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const config::JointLimitsConfig* configuredJointLimits(
|
||||
const config::ArmKinematicsConfig& kinematics)
|
||||
{
|
||||
switch (kinematics.algorithm_case()) {
|
||||
case config::ArmKinematicsConfig::kPinocchioDlsIkSolver:
|
||||
return &kinematics.pinocchio_dls_ik_solver()
|
||||
.joint_limit_policy()
|
||||
.limits();
|
||||
case config::ArmKinematicsConfig::kPinocchioQpIkSolver:
|
||||
return &kinematics.pinocchio_qp_ik_solver()
|
||||
.joint_limit_policy()
|
||||
.limits();
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MotorRobotArm::MotorRobotArm(const config::RobotArmConfig& cfg)
|
||||
@ -66,6 +97,39 @@ MotorRobotArm::MotorRobotArm(const config::RobotArmConfig& cfg)
|
||||
model_.manufacturer = "cmvr";
|
||||
model_.dof = static_cast<std::size_t>(dof_);
|
||||
model_.joint_names = joint_names_;
|
||||
|
||||
const auto* configured_limits = configuredJointLimits(cfg_.kinematics());
|
||||
if (configured_limits != nullptr && configured_limits->enable() &&
|
||||
configured_limits->source() ==
|
||||
config::JOINT_LIMIT_SOURCE_CUSTOM &&
|
||||
configured_limits->joints_size() == dof_) {
|
||||
bool valid_limits = true;
|
||||
model_.joint_limits.reserve(static_cast<std::size_t>(dof_));
|
||||
for (int index = 0; index < dof_; ++index) {
|
||||
const auto& source = configured_limits->joints(index);
|
||||
if (source.joint_name() != joint_names_[static_cast<std::size_t>(index)] ||
|
||||
!std::isfinite(source.q_lb()) ||
|
||||
!std::isfinite(source.q_ub()) ||
|
||||
!std::isfinite(source.qd()) ||
|
||||
source.q_lb() >= source.q_ub() ||
|
||||
source.qd() <= 0.0) {
|
||||
valid_limits = false;
|
||||
break;
|
||||
}
|
||||
JointLimit limit;
|
||||
limit.lower = source.q_lb();
|
||||
limit.upper = source.q_ub();
|
||||
limit.max_velocity = source.qd();
|
||||
limit.max_acceleration = source.qdd();
|
||||
model_.joint_limits.push_back(limit);
|
||||
}
|
||||
if (!valid_limits) {
|
||||
model_.joint_limits.clear();
|
||||
CMVR_LOG(ERROR)
|
||||
<< "[MotorRobotArm] invalid or misordered custom joint limits: "
|
||||
<< id_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MotorRobotArm::~MotorRobotArm()
|
||||
@ -73,6 +137,9 @@ MotorRobotArm::~MotorRobotArm()
|
||||
if (cartesian_velocity_controller_) {
|
||||
cartesian_velocity_controller_->shutdown();
|
||||
}
|
||||
if (motor_manager_ && motor_control_claim_id_ != 0U) {
|
||||
motor_manager_->releaseArmJoints(motor_control_claim_id_);
|
||||
}
|
||||
}
|
||||
|
||||
bool MotorRobotArm::init()
|
||||
@ -121,6 +188,16 @@ bool MotorRobotArm::init()
|
||||
CMVR_LOG(ERROR) << "[MotorRobotArm] failed to configure algorithms: " << id_;
|
||||
return false;
|
||||
}
|
||||
if (motor_control_claim_id_ == 0U) {
|
||||
std::string claim_error;
|
||||
if (!motor_manager_->claimArmJoints(
|
||||
id_, joint_names_, motor_control_claim_id_, &claim_error)) {
|
||||
CMVR_LOG(ERROR)
|
||||
<< "[MotorRobotArm] failed to claim direct motor control: "
|
||||
<< id_ << ", detail=" << claim_error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
CMVR_LOG(INFO) << "[MotorRobotArm] (init): Arm '" << id_ << "' init success";
|
||||
return true;
|
||||
}
|
||||
@ -134,7 +211,7 @@ ArmState MotorRobotArm::getRobotState() const
|
||||
{
|
||||
ArmState state;
|
||||
state.connected = motor_manager_ != nullptr;
|
||||
state.powered_on = true;
|
||||
state.powered_on = powered_on_.load(std::memory_order_acquire);
|
||||
state.brake_released = !emergency_stopped_;
|
||||
state.moving = busy();
|
||||
state.emergency_stopped = emergency_stopped_;
|
||||
@ -154,15 +231,35 @@ JointGroupState MotorRobotArm::getJointState() const
|
||||
state.position.reserve(joint_names_.size());
|
||||
state.velocity.reserve(joint_names_.size());
|
||||
state.effort.reserve(joint_names_.size());
|
||||
bool values_valid = true;
|
||||
for (const auto& joint_name : joint_names_) {
|
||||
auto motor = getMotor_(joint_name);
|
||||
if (!motor) {
|
||||
values_valid = false;
|
||||
continue;
|
||||
}
|
||||
state.position.push_back(motor->getQ());
|
||||
state.velocity.push_back(motor->getQd());
|
||||
const double position = motor->getQ();
|
||||
const double velocity = motor->getQd();
|
||||
values_valid =
|
||||
values_valid && std::isfinite(position) && std::isfinite(velocity);
|
||||
state.position.push_back(position);
|
||||
state.velocity.push_back(velocity);
|
||||
state.effort.push_back(0.0);
|
||||
}
|
||||
values_valid =
|
||||
values_valid && state.position.size() == joint_names_.size() &&
|
||||
state.velocity.size() == joint_names_.size();
|
||||
state.sequence =
|
||||
joint_state_sequence_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
state.sample_monotonic_ns =
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
state.position_valid = values_valid;
|
||||
state.velocity_valid = values_valid;
|
||||
// MotorRobotArm currently has no verified effort feedback path. The zero
|
||||
// placeholders above must never be advertised as measured torque.
|
||||
state.effort_valid = false;
|
||||
return state;
|
||||
}
|
||||
|
||||
@ -196,20 +293,46 @@ Result MotorRobotArm::torqueOn()
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
}
|
||||
motor->brake();
|
||||
if (!motor->torqueOn()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to torque on motor for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
emergency_stopped_ = false;
|
||||
powered_on_.store(true, std::memory_order_release);
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result MotorRobotArm::torqueOff()
|
||||
{
|
||||
// Until every joint reports a successful disable, the aggregate powered
|
||||
// state is unknown and therefore must not satisfy a require_powered gate.
|
||||
powered_on_.store(false, std::memory_order_release);
|
||||
for (const auto& joint_name : joint_names_) {
|
||||
auto motor = getMotor_(joint_name);
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
}
|
||||
motor->torqueOff();
|
||||
if (!motor->torqueOff() || !motor->brakeRelease()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to torque off motor for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
Result MotorRobotArm::brakeRelease()
|
||||
{
|
||||
for (const auto& joint_name : joint_names_) {
|
||||
auto motor = getMotor_(joint_name);
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady,
|
||||
"motor not found for joint: " + joint_name);
|
||||
}
|
||||
if (!motor->brakeRelease()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to release brake for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
return Result::success();
|
||||
}
|
||||
@ -230,6 +353,7 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name)
|
||||
|
||||
Result MotorRobotArm::emergencyStop()
|
||||
{
|
||||
motion_generation_.fetch_add(1, std::memory_order_acq_rel);
|
||||
if (cartesian_velocity_controller_) {
|
||||
cartesian_velocity_controller_->shutdown();
|
||||
}
|
||||
@ -238,7 +362,10 @@ Result MotorRobotArm::emergencyStop()
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
}
|
||||
motor->brake();
|
||||
if (!motor->quickStop()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to quick stop motor for joint: " + joint_name);
|
||||
}
|
||||
}
|
||||
emergency_stopped_ = true;
|
||||
return Result::success();
|
||||
@ -255,6 +382,8 @@ Result MotorRobotArm::setSpeedScaling(const double scaling)
|
||||
|
||||
Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOptions& options)
|
||||
{
|
||||
const auto motion_generation =
|
||||
motion_generation_.load(std::memory_order_acquire);
|
||||
std::string error;
|
||||
if (!validatePositionCommand_(target, error)) {
|
||||
return Result::failure(ArmErrorCode::InvalidArgument, error);
|
||||
@ -266,7 +395,12 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "[MotorRobotArm] arm is busy: " + id_);
|
||||
}
|
||||
BusyGuard busy_guard{busy_};
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (cancellationRequested(options.cancellation_requested)) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveJ canceled before planning: " + id_);
|
||||
}
|
||||
|
||||
std::vector<JointTrajectorySample> samples;
|
||||
if (!joint_planner_->planMoveJ(readJointPosition_(), target, options, speed_scaling_, samples)) {
|
||||
@ -278,16 +412,32 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti
|
||||
|
||||
std::vector<std::shared_ptr<AbstractMotor>> motors;
|
||||
motors.reserve(joint_names_.size());
|
||||
if (cancellationRequested(options.cancellation_requested)) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveJ canceled before dispatch: " + id_);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveJ canceled before dispatch: " + id_);
|
||||
}
|
||||
for (const auto& joint_name : joint_names_) {
|
||||
auto motor = getMotor_(joint_name);
|
||||
if (!motor) {
|
||||
return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name);
|
||||
return Result::failure(
|
||||
ArmErrorCode::RobotNotReady,
|
||||
"motor not found for joint: " + joint_name);
|
||||
}
|
||||
if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_POSITION) {
|
||||
motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION);
|
||||
}
|
||||
motors.push_back(std::move(motor));
|
||||
}
|
||||
}
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
constexpr double fallback_dt = 0.001;
|
||||
@ -296,9 +446,33 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti
|
||||
if (sample.position.size() != motors.size()) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed, "moveJ sample size mismatch");
|
||||
}
|
||||
if (cancellationRequested(options.cancellation_requested)) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveJ canceled during execution: " + id_);
|
||||
}
|
||||
{
|
||||
// The local generation and one complete joint frame are ordered
|
||||
// against stopMotion(). External cancellation is intentionally
|
||||
// evaluated before taking the device mutex because it is caller code.
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveJ canceled during execution: " + id_);
|
||||
}
|
||||
for (std::size_t i = 0; i < motors.size(); ++i) {
|
||||
const double qd = i < sample.velocity.size() ? sample.velocity[i] : 0.0;
|
||||
motors[i]->setTarget(sample.position[i], qd);
|
||||
const double qd =
|
||||
i < sample.velocity.size() ? sample.velocity[i] : 0.0;
|
||||
if (!motors[i]->commandCyclicPosition(
|
||||
sample.position[i], qd)) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed,
|
||||
"failed to command cyclic position for joint: " +
|
||||
motors[i]->jointName());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (k + 1 < samples.size()) {
|
||||
const double next_t = samples[k + 1].t > 0.0 ? samples[k + 1].t
|
||||
@ -331,7 +505,11 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity,
|
||||
if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY) {
|
||||
motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY);
|
||||
}
|
||||
motor->setTarget(velocity.velocity[i] * speed_scaling_);
|
||||
if (!motor->commandCyclicVelocity(velocity.velocity[i] * speed_scaling_)) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to command cyclic velocity for joint: " +
|
||||
joint_names_[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -344,6 +522,7 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity,
|
||||
|
||||
Result MotorRobotArm::stopJ(const double acceleration)
|
||||
{
|
||||
motion_generation_.fetch_add(1, std::memory_order_acq_rel);
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(joint_names_.size(), 0.0);
|
||||
return speedJ(zero, acceleration, 0.0);
|
||||
@ -353,6 +532,8 @@ Result MotorRobotArm::moveL(const CartesianPose& target,
|
||||
const MotionOptions& options,
|
||||
const FrameType frame)
|
||||
{
|
||||
const auto motion_generation =
|
||||
motion_generation_.load(std::memory_order_acquire);
|
||||
if (cartesian_velocity_controller_) {
|
||||
cartesian_velocity_controller_->shutdown();
|
||||
}
|
||||
@ -370,6 +551,12 @@ Result MotorRobotArm::moveL(const CartesianPose& target,
|
||||
}
|
||||
BusyGuard busy_guard{busy_};
|
||||
|
||||
if (cancellationRequested(options.cancellation_requested)) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveL canceled before planning: " + id_);
|
||||
}
|
||||
|
||||
std::vector<double> q_start;
|
||||
std::vector<double> qd_now;
|
||||
if (!readArmState_(q_start, qd_now)) {
|
||||
@ -394,8 +581,22 @@ Result MotorRobotArm::moveL(const CartesianPose& target,
|
||||
<< ", executable_path_m=" << trajectory.executable_path_length;
|
||||
}
|
||||
|
||||
return executeMoveLTrajectory_(trajectory) ? Result::success()
|
||||
: Result::failure(ArmErrorCode::CommandFailed, "moveL execution failed");
|
||||
switch (executeMoveLTrajectory_(
|
||||
trajectory,
|
||||
options.cancellation_requested,
|
||||
motion_generation)) {
|
||||
case TrajectoryExecutionResult::Completed:
|
||||
return Result::success();
|
||||
case TrajectoryExecutionResult::Canceled:
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"[MotorRobotArm] moveL canceled during execution: " + id_);
|
||||
case TrajectoryExecutionResult::Failed:
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed, "moveL execution failed");
|
||||
}
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandFailed, "moveL execution failed");
|
||||
}
|
||||
|
||||
Result MotorRobotArm::speedL(const CartesianVelocity& velocity,
|
||||
@ -422,16 +623,26 @@ Result MotorRobotArm::stopL(const std::optional<double> acceleration)
|
||||
|
||||
Result MotorRobotArm::stopMotion()
|
||||
{
|
||||
stopL(0.0);
|
||||
return stopJ(0.0);
|
||||
// Revoke position trajectories before stopping the velocity worker. The
|
||||
// controller fences its old worker and sends zero before joining it.
|
||||
motion_generation_.fetch_add(1, std::memory_order_acq_rel);
|
||||
if (cartesian_velocity_controller_) {
|
||||
cartesian_velocity_controller_->shutdown();
|
||||
}
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(joint_names_.size(), 0.0);
|
||||
return speedJ(zero, 0.0, 0.0);
|
||||
}
|
||||
|
||||
Result MotorRobotArm::shutdown()
|
||||
{
|
||||
motion_generation_.fetch_add(1, std::memory_order_acq_rel);
|
||||
if (cartesian_velocity_controller_) {
|
||||
cartesian_velocity_controller_->shutdown();
|
||||
}
|
||||
return stopJ(0.0);
|
||||
JointVelocityCommand zero;
|
||||
zero.velocity.assign(joint_names_.size(), 0.0);
|
||||
return speedJ(zero, 0.0, 0.0);
|
||||
}
|
||||
|
||||
Result MotorRobotArm::startServoMode(const ServoOptions& options)
|
||||
@ -457,7 +668,11 @@ Result MotorRobotArm::servoJ(const JointPositionCommand& target)
|
||||
if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_POSITION) {
|
||||
motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION);
|
||||
}
|
||||
motor->setTarget(target.position[i], 0.0);
|
||||
if (!motor->commandCyclicPosition(target.position[i], 0.0)) {
|
||||
return Result::failure(ArmErrorCode::CommandFailed,
|
||||
"failed to command cyclic position for joint: " +
|
||||
joint_names_[i]);
|
||||
}
|
||||
}
|
||||
return Result::success();
|
||||
}
|
||||
@ -704,25 +919,40 @@ bool MotorRobotArm::configureAlgorithms_()
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MotorRobotArm::executeMoveLTrajectory_(const CartesianJointTrajectory& trajectory)
|
||||
MotorRobotArm::TrajectoryExecutionResult
|
||||
MotorRobotArm::executeMoveLTrajectory_(
|
||||
const CartesianJointTrajectory& trajectory,
|
||||
const std::function<bool()>& cancellation_requested,
|
||||
const std::uint64_t motion_generation)
|
||||
{
|
||||
if (trajectory.position.empty() ||
|
||||
trajectory.velocity.size() != trajectory.position.size() ||
|
||||
trajectory.time.size() != trajectory.position.size()) {
|
||||
return false;
|
||||
return TrajectoryExecutionResult::Failed;
|
||||
}
|
||||
if (trajectory.position.size() == 1) {
|
||||
return true;
|
||||
return cancellationRequested(cancellation_requested) ||
|
||||
motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation
|
||||
? TrajectoryExecutionResult::Canceled
|
||||
: TrajectoryExecutionResult::Completed;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<AbstractMotor>> motors;
|
||||
motors.reserve(joint_names_.size());
|
||||
if (cancellationRequested(cancellation_requested)) {
|
||||
return TrajectoryExecutionResult::Canceled;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation) {
|
||||
return TrajectoryExecutionResult::Canceled;
|
||||
}
|
||||
for (const auto& joint_name : joint_names_) {
|
||||
auto motor = getMotor_(joint_name);
|
||||
if (!motor) {
|
||||
return false;
|
||||
return TrajectoryExecutionResult::Failed;
|
||||
}
|
||||
if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_POSITION) {
|
||||
motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION);
|
||||
@ -737,17 +967,36 @@ bool MotorRobotArm::executeMoveLTrajectory_(const CartesianJointTrajectory& traj
|
||||
const auto& position = trajectory.position[i];
|
||||
const auto& velocity = trajectory.velocity[i];
|
||||
if (position.size() != motors.size() || velocity.size() != motors.size()) {
|
||||
return false;
|
||||
return TrajectoryExecutionResult::Failed;
|
||||
}
|
||||
if (cancellationRequested(cancellation_requested)) {
|
||||
return TrajectoryExecutionResult::Canceled;
|
||||
}
|
||||
{
|
||||
// Keep the local stop decision and the complete joint frame in the
|
||||
// same critical section as stopMotion()/stopJ().
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation) {
|
||||
return TrajectoryExecutionResult::Canceled;
|
||||
}
|
||||
for (std::size_t j = 0; j < motors.size(); ++j) {
|
||||
motors[j]->setTarget(position[j], velocity[j]);
|
||||
if (!motors[j]->commandCyclicPosition(
|
||||
position[j], velocity[j])) {
|
||||
return TrajectoryExecutionResult::Failed;
|
||||
}
|
||||
}
|
||||
}
|
||||
next_deadline += std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
||||
std::chrono::duration<double>(dt_segment));
|
||||
std::this_thread::sleep_until(next_deadline);
|
||||
}
|
||||
|
||||
return true;
|
||||
return cancellationRequested(cancellation_requested) ||
|
||||
motion_generation_.load(std::memory_order_acquire) !=
|
||||
motion_generation
|
||||
? TrajectoryExecutionResult::Canceled
|
||||
: TrajectoryExecutionResult::Completed;
|
||||
}
|
||||
|
||||
CartesianVelocityController::Config MotorRobotArm::toCartesianVelocityControllerConfig_(
|
||||
|
||||
@ -2,12 +2,17 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
@ -99,6 +104,142 @@ struct ArmMujocoConfigCase {
|
||||
const char* config_file;
|
||||
};
|
||||
|
||||
class BlockingCartesianMotionPlanner final : public CartesianMotionPlanner {
|
||||
public:
|
||||
bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool configureMoveL(const config::MoveLPlannerConfig&) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool planMoveL(const CartesianPose&,
|
||||
const std::vector<double>&,
|
||||
const std::vector<double>&,
|
||||
double,
|
||||
double,
|
||||
double,
|
||||
FrameType,
|
||||
CartesianJointTrajectory&) override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool speedLStep(const CartesianVelocity&,
|
||||
double,
|
||||
const std::vector<double>& q_measured,
|
||||
const std::vector<double>&,
|
||||
std::vector<double>& qd_command,
|
||||
FrameType) override
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
if (step_count_++ == 0) {
|
||||
first_step_entered_ = true;
|
||||
condition_.notify_all();
|
||||
condition_.wait(lock, [&] { return release_first_step_; });
|
||||
}
|
||||
qd_command.assign(q_measured.size(), 0.4);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool updateSpeedLAcceleration(double) override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
CartesianVelocity getSpeedLCommandTwistBase() const override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
bool waitForFirstStep(const std::chrono::milliseconds timeout)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
return condition_.wait_for(
|
||||
lock, timeout, [&] { return first_step_entered_; });
|
||||
}
|
||||
|
||||
void releaseFirstStep()
|
||||
{
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
release_first_step_ = true;
|
||||
}
|
||||
condition_.notify_all();
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable condition_;
|
||||
std::size_t step_count_{0};
|
||||
bool first_step_entered_{false};
|
||||
bool release_first_step_{false};
|
||||
};
|
||||
|
||||
class VelocityCommandRecorder {
|
||||
public:
|
||||
Result record(const JointVelocityCommand& velocity, double)
|
||||
{
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
commands_.push_back(velocity.velocity);
|
||||
}
|
||||
condition_.notify_all();
|
||||
return Result::success();
|
||||
}
|
||||
|
||||
bool waitForZero(const std::chrono::milliseconds timeout)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
return condition_.wait_for(lock, timeout, [&] {
|
||||
return std::any_of(commands_.begin(), commands_.end(), isZero_);
|
||||
});
|
||||
}
|
||||
|
||||
bool waitForNonZeroAfter(const std::size_t index,
|
||||
const std::chrono::milliseconds timeout)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
return condition_.wait_for(lock, timeout, [&] {
|
||||
return index < commands_.size() &&
|
||||
std::any_of(commands_.begin() + index,
|
||||
commands_.end(),
|
||||
[](const auto& command) {
|
||||
return !isZero_(command);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
std::size_t size() const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return commands_.size();
|
||||
}
|
||||
|
||||
bool allZeroFrom(const std::size_t index) const
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
return index <= commands_.size() &&
|
||||
std::all_of(commands_.begin() + index,
|
||||
commands_.end(), isZero_);
|
||||
}
|
||||
|
||||
private:
|
||||
static bool isZero_(const std::vector<double>& command)
|
||||
{
|
||||
return std::all_of(command.begin(), command.end(), [](const double value) {
|
||||
return std::abs(value) < 1e-12;
|
||||
});
|
||||
}
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable condition_;
|
||||
std::vector<std::vector<double>> commands_;
|
||||
};
|
||||
|
||||
void PrintTo(const ArmMujocoConfigCase& value, std::ostream* os)
|
||||
{
|
||||
*os << value.name << " (" << value.config_file << ")";
|
||||
@ -314,6 +455,240 @@ TEST_P(MotorRobotArmMujocoTest, MoveL)
|
||||
EXPECT_LT(outcome.move_l_error, 0.04);
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, StopMotionDoesNotWaitForMoveJCancellationCallback)
|
||||
{
|
||||
MotionOptions options;
|
||||
options.velocity = 0.4;
|
||||
options.acceleration = 2.0;
|
||||
|
||||
std::mutex cancellation_mutex;
|
||||
std::condition_variable cancellation_condition;
|
||||
int cancellation_checks = 0;
|
||||
bool release_dispatch_check = false;
|
||||
options.cancellation_requested = [&] {
|
||||
std::unique_lock lock(cancellation_mutex);
|
||||
++cancellation_checks;
|
||||
cancellation_condition.notify_all();
|
||||
if (cancellation_checks == 3) {
|
||||
cancellation_condition.wait(lock, [&] {
|
||||
return release_dispatch_check;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
std::vector<double> target(kDof, 0.0);
|
||||
target[0] = 0.2;
|
||||
auto motion = std::async(std::launch::async, [&] {
|
||||
return arm_->moveJ(JointPositionCommand{target}, options);
|
||||
});
|
||||
|
||||
bool cancellation_blocked = false;
|
||||
{
|
||||
std::unique_lock lock(cancellation_mutex);
|
||||
cancellation_blocked = cancellation_condition.wait_for(
|
||||
lock, std::chrono::seconds(2), [&] {
|
||||
return cancellation_checks >= 3;
|
||||
});
|
||||
}
|
||||
|
||||
auto stop = std::async(std::launch::async, [&] {
|
||||
return arm_->stopMotion();
|
||||
});
|
||||
EXPECT_TRUE(cancellation_blocked);
|
||||
EXPECT_EQ(stop.wait_for(std::chrono::seconds(1)),
|
||||
std::future_status::ready);
|
||||
|
||||
{
|
||||
std::lock_guard lock(cancellation_mutex);
|
||||
release_dispatch_check = true;
|
||||
}
|
||||
cancellation_condition.notify_all();
|
||||
|
||||
const auto motion_result = motion.get();
|
||||
const auto stop_result = stop.get();
|
||||
EXPECT_EQ(motion_result.code, ArmErrorCode::CommandRejected)
|
||||
<< motion_result.message;
|
||||
EXPECT_TRUE(stop_result.ok()) << stop_result.message;
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, StopMotionDoesNotWaitForMoveLCancellationCallback)
|
||||
{
|
||||
const std::vector<double> initial{
|
||||
0.25, 1.00, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0};
|
||||
MotionOptions joint_options;
|
||||
joint_options.velocity = 2.8;
|
||||
joint_options.acceleration = 20.0;
|
||||
const auto setup = arm_->moveJ(
|
||||
JointPositionCommand{initial}, joint_options);
|
||||
ASSERT_TRUE(setup.ok()) << setup.message;
|
||||
|
||||
CartesianPose target = arm_->getTcpPose();
|
||||
target.x += 0.05;
|
||||
MotionOptions options;
|
||||
options.velocity = 0.4;
|
||||
options.acceleration = 5.0;
|
||||
options.jerk = 20.0;
|
||||
|
||||
std::mutex cancellation_mutex;
|
||||
std::condition_variable cancellation_condition;
|
||||
int cancellation_checks = 0;
|
||||
bool release_dispatch_check = false;
|
||||
options.cancellation_requested = [&] {
|
||||
std::unique_lock lock(cancellation_mutex);
|
||||
++cancellation_checks;
|
||||
cancellation_condition.notify_all();
|
||||
if (cancellation_checks == 3) {
|
||||
cancellation_condition.wait(lock, [&] {
|
||||
return release_dispatch_check;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
auto motion = std::async(std::launch::async, [&] {
|
||||
return arm_->moveL(target, options, FrameType::Base);
|
||||
});
|
||||
|
||||
bool cancellation_blocked = false;
|
||||
{
|
||||
std::unique_lock lock(cancellation_mutex);
|
||||
cancellation_blocked = cancellation_condition.wait_for(
|
||||
lock, std::chrono::seconds(2), [&] {
|
||||
return cancellation_checks >= 3;
|
||||
});
|
||||
}
|
||||
|
||||
auto stop = std::async(std::launch::async, [&] {
|
||||
return arm_->stopMotion();
|
||||
});
|
||||
EXPECT_TRUE(cancellation_blocked);
|
||||
EXPECT_EQ(stop.wait_for(std::chrono::seconds(1)),
|
||||
std::future_status::ready);
|
||||
|
||||
{
|
||||
std::lock_guard lock(cancellation_mutex);
|
||||
release_dispatch_check = true;
|
||||
}
|
||||
cancellation_condition.notify_all();
|
||||
|
||||
const auto motion_result = motion.get();
|
||||
const auto stop_result = stop.get();
|
||||
EXPECT_EQ(motion_result.code, ArmErrorCode::CommandRejected)
|
||||
<< motion_result.message;
|
||||
EXPECT_TRUE(stop_result.ok()) << stop_result.message;
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, StopMotionCancelsMoveJWithoutExternalCallback)
|
||||
{
|
||||
MotionOptions options;
|
||||
options.velocity = 0.1;
|
||||
options.acceleration = 0.5;
|
||||
|
||||
std::vector<double> target(kDof, 0.0);
|
||||
target[0] = 0.4;
|
||||
auto motion = std::async(std::launch::async, [&] {
|
||||
return arm_->moveJ(JointPositionCommand{target}, options);
|
||||
});
|
||||
|
||||
waitFor([&] { return arm_->busy(); }, std::chrono::seconds(1));
|
||||
const auto stop_result = arm_->stopMotion();
|
||||
const auto motion_result = motion.get();
|
||||
|
||||
EXPECT_TRUE(stop_result.ok()) << stop_result.message;
|
||||
EXPECT_EQ(motion_result.code, ArmErrorCode::CommandRejected)
|
||||
<< motion_result.message;
|
||||
EXPECT_FALSE(arm_->busy());
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, StopMotionCancelsMoveLWithoutExternalCallback)
|
||||
{
|
||||
const std::vector<double> initial{
|
||||
0.25, 1.00, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0};
|
||||
MotionOptions joint_options;
|
||||
joint_options.velocity = 2.8;
|
||||
joint_options.acceleration = 20.0;
|
||||
const auto setup = arm_->moveJ(
|
||||
JointPositionCommand{initial}, joint_options);
|
||||
ASSERT_TRUE(setup.ok()) << setup.message;
|
||||
|
||||
CartesianPose target = arm_->getTcpPose();
|
||||
target.x += 0.08;
|
||||
MotionOptions options;
|
||||
options.velocity = 0.1;
|
||||
options.acceleration = 1.0;
|
||||
options.jerk = 5.0;
|
||||
auto motion = std::async(std::launch::async, [&] {
|
||||
return arm_->moveL(target, options, FrameType::Base);
|
||||
});
|
||||
|
||||
waitFor([&] { return arm_->busy(); }, std::chrono::seconds(1));
|
||||
const auto stop_result = arm_->stopMotion();
|
||||
const auto motion_result = motion.get();
|
||||
|
||||
EXPECT_TRUE(stop_result.ok()) << stop_result.message;
|
||||
EXPECT_EQ(motion_result.code, ArmErrorCode::CommandRejected)
|
||||
<< motion_result.message;
|
||||
EXPECT_FALSE(arm_->busy());
|
||||
}
|
||||
|
||||
TEST(CartesianVelocityControllerTest,
|
||||
ShutdownFencesStaleWriteAndLaterSpeedLRestartsWorker)
|
||||
{
|
||||
constexpr std::size_t dof = 2;
|
||||
auto planner = std::make_shared<BlockingCartesianMotionPlanner>();
|
||||
VelocityCommandRecorder recorder;
|
||||
CartesianVelocityController controller(
|
||||
CartesianVelocityController::Config{},
|
||||
planner,
|
||||
dof,
|
||||
[](std::vector<double>& q, std::vector<double>& qd) {
|
||||
q.assign(dof, 0.0);
|
||||
qd.assign(dof, 0.0);
|
||||
return true;
|
||||
},
|
||||
[&](const JointVelocityCommand& command, const double acceleration) {
|
||||
return recorder.record(command, acceleration);
|
||||
});
|
||||
|
||||
CartesianVelocity velocity;
|
||||
velocity.vx = 0.1;
|
||||
const auto first = controller.speedL(
|
||||
velocity, 0.5, 0.0, FrameType::Base);
|
||||
ASSERT_TRUE(first.ok()) << first.message;
|
||||
const bool first_step_entered =
|
||||
planner->waitForFirstStep(std::chrono::seconds(1));
|
||||
if (!first_step_entered) {
|
||||
planner->releaseFirstStep();
|
||||
controller.shutdown();
|
||||
FAIL() << "velocity worker did not enter the blocking planner step";
|
||||
}
|
||||
|
||||
auto shutdown = std::async(std::launch::async, [&] {
|
||||
controller.shutdown();
|
||||
});
|
||||
EXPECT_TRUE(recorder.waitForZero(std::chrono::seconds(1)));
|
||||
EXPECT_EQ(shutdown.wait_for(std::chrono::milliseconds(20)),
|
||||
std::future_status::timeout);
|
||||
|
||||
const auto zero_index = recorder.size();
|
||||
planner->releaseFirstStep();
|
||||
EXPECT_EQ(shutdown.wait_for(std::chrono::seconds(1)),
|
||||
std::future_status::ready);
|
||||
shutdown.get();
|
||||
EXPECT_TRUE(recorder.allZeroFrom(zero_index));
|
||||
EXPECT_FALSE(controller.busy());
|
||||
|
||||
const auto restart_index = recorder.size();
|
||||
const auto restarted = controller.speedL(
|
||||
velocity, 0.5, 0.0, FrameType::Base);
|
||||
EXPECT_TRUE(restarted.ok()) << restarted.message;
|
||||
EXPECT_TRUE(recorder.waitForNonZeroAfter(
|
||||
restart_index, std::chrono::seconds(1)));
|
||||
controller.shutdown();
|
||||
EXPECT_FALSE(controller.busy());
|
||||
}
|
||||
|
||||
TEST_P(MotorRobotArmMujocoTest, SpeedL)
|
||||
{
|
||||
MotorRobotArm& arm = *arm_;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
#define CMVR_ES_ROBOT_ARM_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@ -28,7 +29,44 @@ public:
|
||||
virtual SafetyMode getSafetyMode() const = 0;
|
||||
virtual ControlMode getControlMode() const = 0;
|
||||
|
||||
// Queued actions require synchronous completion, cooperative cancellation
|
||||
// at the final device-submission boundary, and a bounded typed Stop which
|
||||
// returns success only after controller idle is confirmed. Backends must
|
||||
// opt in only after all of these semantics have been validated.
|
||||
virtual bool supportsActionQueueMotion() const noexcept { return false; }
|
||||
|
||||
// ArmTeleop requires an explicitly reviewed group-servo implementation.
|
||||
// Existing and vendor arms remain unavailable until their implementations
|
||||
// override this capability after timing and partial-write validation.
|
||||
virtual bool supportsTeleopGroupServo() const noexcept { return false; }
|
||||
virtual JointEffortSource jointEffortSource() const noexcept
|
||||
{
|
||||
return JointEffortSource::Unspecified;
|
||||
}
|
||||
|
||||
virtual Result torqueOn() = 0;
|
||||
// Long-running startup implementations may cooperatively observe loss of
|
||||
// their control lease. Backends which have not adopted cancellation retain
|
||||
// the legacy behavior, while still rejecting an already-cancelled request
|
||||
// before entering the vendor API.
|
||||
virtual Result torqueOn(
|
||||
const std::function<bool()>& cancellation_requested)
|
||||
{
|
||||
if (cancellation_requested) {
|
||||
try {
|
||||
if (cancellation_requested()) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"torqueOn cancelled before execution");
|
||||
}
|
||||
} catch (...) {
|
||||
return Result::failure(
|
||||
ArmErrorCode::CommandRejected,
|
||||
"torqueOn cancellation check failed");
|
||||
}
|
||||
}
|
||||
return torqueOn();
|
||||
}
|
||||
virtual Result torqueOff() = 0;
|
||||
virtual Result calibrateZeroQ(const std::string& joint_name) = 0;
|
||||
|
||||
@ -73,6 +111,27 @@ public:
|
||||
FrameType frame = FrameType::Base) = 0;
|
||||
virtual Result stopServoMode() = 0;
|
||||
|
||||
// Torque streaming is optional. Backends which do not provide an atomic
|
||||
// group torque port retain source compatibility and fail explicitly.
|
||||
virtual Result startTorqueMode(const TorqueServoOptions&)
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"torque servo mode is unsupported by this RobotArm");
|
||||
}
|
||||
virtual Result servoTorque(const JointTorqueCommand&)
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"torque servo command is unsupported by this RobotArm");
|
||||
}
|
||||
virtual Result stopTorqueMode()
|
||||
{
|
||||
return Result::failure(
|
||||
ArmErrorCode::UnsupportedCommand,
|
||||
"torque servo mode is unsupported by this RobotArm");
|
||||
}
|
||||
|
||||
virtual Result connect(const std::string& ip, int port) = 0;
|
||||
virtual Result disconnect() = 0;
|
||||
virtual bool isConnected() const = 0;
|
||||
|
||||
@ -6,9 +6,10 @@
|
||||
|
||||
#include "cmvr/config/arm_config/arm_config.pb.h"
|
||||
#include "common/base/logging/logger.h"
|
||||
#include "devices/arm/aubo_arm/include/aubo_arm.h"
|
||||
#include "devices/arm/aubo_arm/aubo_arm.h"
|
||||
#include "devices/arm/huayan_arm/huayan_arm.h"
|
||||
#include "devices/arm/motor_robot_arm/include/motor_robot_arm.h"
|
||||
#include "devices/arm/ume_robot_arm/include/ume_robot_arm.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
@ -36,6 +37,9 @@ public:
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
case config::RobotArmConfig::kUme:
|
||||
return std::make_shared<UmeRobotArm>(cfg);
|
||||
|
||||
case config::RobotArmConfig::BACKEND_NOT_SET:
|
||||
default:
|
||||
{
|
||||
|
||||
23
cmvr-es/devices/arm/ume_robot_arm/CMakeLists.txt
Normal file
23
cmvr-es/devices/arm/ume_robot_arm/CMakeLists.txt
Normal file
@ -0,0 +1,23 @@
|
||||
add_library(ume_robot_arm SHARED
|
||||
src/damiao_mit_codec.cpp
|
||||
src/damiao_can_fd_chain.cpp
|
||||
src/ume_robot_arm.cpp
|
||||
)
|
||||
|
||||
target_include_directories(ume_robot_arm PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(ume_robot_arm
|
||||
PUBLIC
|
||||
cmvr_es::device::canbus
|
||||
cmvr_es::ik_solver
|
||||
cmvr_es::common
|
||||
PRIVATE
|
||||
cmvr_es::proto
|
||||
cmvr_es::logging
|
||||
pthread
|
||||
)
|
||||
|
||||
add_library(cmvr_es::device::ume_robot_arm ALIAS ume_robot_arm)
|
||||
install(TARGETS ume_robot_arm LIBRARY DESTINATION lib)
|
||||
145
cmvr-es/devices/arm/ume_robot_arm/include/damiao_can_fd_chain.h
Normal file
145
cmvr-es/devices/arm/ume_robot_arm/include/damiao_can_fd_chain.h
Normal file
@ -0,0 +1,145 @@
|
||||
#ifndef CMVR_ES_DAMIAO_CAN_FD_CHAIN_H
|
||||
#define CMVR_ES_DAMIAO_CAN_FD_CHAIN_H
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "arm/ume_robot_arm/include/damiao_mit_codec.h"
|
||||
#include "common/types/arm/arm_types.h"
|
||||
|
||||
namespace cmvr::device {
|
||||
|
||||
class AbstractCanbus;
|
||||
|
||||
struct DamiaoJointSpec {
|
||||
std::string joint_name;
|
||||
std::uint32_t command_id{0};
|
||||
std::uint32_t feedback_id{0};
|
||||
std::uint8_t reported_motor_id{0};
|
||||
DamiaoMotorModel model{DamiaoMotorModel::Unknown};
|
||||
int direction{1};
|
||||
double zero_offset_rad{0.0};
|
||||
double joint_lower_rad{0.0};
|
||||
double joint_upper_rad{0.0};
|
||||
double max_velocity_rad_s{0.0};
|
||||
double max_torque_nm{0.0};
|
||||
std::uint16_t healthy_status_mask{0};
|
||||
std::uint8_t max_driver_temperature_raw{0};
|
||||
std::uint8_t max_motor_temperature_raw{0};
|
||||
};
|
||||
|
||||
struct DamiaoChainOptions {
|
||||
bool is_fd{true};
|
||||
bool bitrate_switch{true};
|
||||
bool hardware_enabled{false};
|
||||
};
|
||||
|
||||
struct DamiaoChainStatistics {
|
||||
std::uint64_t exchanges{0};
|
||||
std::uint64_t deadline_misses{0};
|
||||
std::uint64_t unknown_feedback{0};
|
||||
std::uint64_t duplicate_feedback{0};
|
||||
std::uint64_t rejected_commands{0};
|
||||
std::uint64_t protocol_saturations{0};
|
||||
};
|
||||
|
||||
enum class DamiaoChainState : std::uint8_t {
|
||||
Closed = 0,
|
||||
Initialized,
|
||||
Passive,
|
||||
Armed,
|
||||
Active,
|
||||
FaultLatched,
|
||||
Stopped
|
||||
};
|
||||
|
||||
class DamiaoCanFdChain {
|
||||
public:
|
||||
DamiaoCanFdChain(std::shared_ptr<AbstractCanbus> bus,
|
||||
std::vector<DamiaoJointSpec> joints,
|
||||
DamiaoChainOptions options);
|
||||
~DamiaoCanFdChain();
|
||||
|
||||
DamiaoCanFdChain(const DamiaoCanFdChain&) = delete;
|
||||
DamiaoCanFdChain& operator=(const DamiaoCanFdChain&) = delete;
|
||||
|
||||
Result init();
|
||||
Result openPassive();
|
||||
Result clearFault(std::chrono::steady_clock::time_point deadline);
|
||||
Result arm(std::chrono::steady_clock::time_point deadline);
|
||||
Result setZero(std::size_t joint_index,
|
||||
std::chrono::steady_clock::time_point deadline);
|
||||
Result exchange(const DamiaoMitCommand* joint_commands,
|
||||
std::size_t command_count,
|
||||
DamiaoJointFeedback* joint_feedback,
|
||||
std::size_t feedback_count,
|
||||
std::chrono::steady_clock::time_point deadline);
|
||||
Result disable() noexcept;
|
||||
Result latchFault(const std::string& reason) noexcept;
|
||||
void stop() noexcept;
|
||||
|
||||
DamiaoChainState state() const noexcept { return state_.load(); }
|
||||
std::size_t size() const noexcept { return joints_.size(); }
|
||||
bool hardwareEnabled() const noexcept { return options_.hardware_enabled; }
|
||||
DamiaoChainStatistics statistics() const;
|
||||
std::string lastError() const;
|
||||
const std::vector<DamiaoJointSpec>& joints() const noexcept { return joints_; }
|
||||
|
||||
private:
|
||||
Result validateConfig_() const;
|
||||
Result sendModeAll_(
|
||||
DamiaoMode mode,
|
||||
std::chrono::steady_clock::time_point deadline,
|
||||
bool expect_feedback);
|
||||
Result sendModeOne_(
|
||||
std::size_t joint_index,
|
||||
DamiaoMode mode,
|
||||
std::chrono::steady_clock::time_point deadline);
|
||||
Result receiveCycle_(
|
||||
DamiaoJointFeedback* feedback,
|
||||
std::size_t feedback_count,
|
||||
std::chrono::steady_clock::time_point deadline);
|
||||
bool sendFrames_(
|
||||
const std::vector<CanFrame>& frames,
|
||||
std::chrono::steady_clock::time_point deadline) noexcept;
|
||||
bool sendFramesBestEffort_(
|
||||
const std::vector<CanFrame>& frames) noexcept;
|
||||
bool feedbackTransportAndHealthValid_(
|
||||
const CanFrame& frame,
|
||||
const DamiaoJointSpec& joint,
|
||||
const DamiaoJointFeedback& feedback) const noexcept;
|
||||
bool latchFaultAndDisable_(const std::string& reason) noexcept;
|
||||
bool bestEffortZeroAndDisable_() noexcept;
|
||||
void setError_(const std::string& error) noexcept;
|
||||
std::size_t jointIndexForFeedbackId_(std::uint32_t id) const noexcept;
|
||||
DamiaoMitCommand toMotorCommand_(
|
||||
const DamiaoJointSpec& spec,
|
||||
const DamiaoMitCommand& command,
|
||||
bool& safety_saturated) const noexcept;
|
||||
void toJointFeedback_(const DamiaoJointSpec& spec,
|
||||
DamiaoJointFeedback& feedback) const noexcept;
|
||||
|
||||
std::shared_ptr<AbstractCanbus> bus_;
|
||||
std::vector<DamiaoJointSpec> joints_;
|
||||
DamiaoChainOptions options_;
|
||||
std::vector<CanFrame> tx_frames_;
|
||||
std::vector<CanFrame> rx_frames_;
|
||||
std::vector<DamiaoJointFeedback> feedback_scratch_;
|
||||
std::vector<bool> feedback_seen_;
|
||||
|
||||
mutable std::mutex io_mutex_;
|
||||
mutable std::mutex status_mutex_;
|
||||
std::atomic<DamiaoChainState> state_{DamiaoChainState::Closed};
|
||||
DamiaoChainStatistics statistics_;
|
||||
std::string last_error_;
|
||||
};
|
||||
|
||||
} // namespace cmvr::device
|
||||
|
||||
#endif // CMVR_ES_DAMIAO_CAN_FD_CHAIN_H
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user