diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index e9176f14..c6ada27b 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -147,7 +147,7 @@ device_manager { id: "src1100" type: DEVICE_TYPE_AGV config_file: "devices/agv/agv.pb.txt" - enable: true + enable: false } devices { diff --git a/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt b/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt index c951fc35..d0afd0d0 100644 --- a/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt +++ b/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt @@ -1,34 +1,84 @@ option(CMVR_HEAD_BUILD_TESTING "Build head-only offline tests" OFF) +set(CMVR_HEAD_ERPC_ROOT + "${PROJECT_SOURCE_DIR}/dependency/${ARCH}/third_party/erpc/v1.14.0" + CACHE PATH "Official eRPC 1.14.0 SDK prefix") + +foreach(required lib/liberpc.a include/erpc/erpc_version.h) + if(NOT EXISTS "${CMVR_HEAD_ERPC_ROOT}/${required}") + message(FATAL_ERROR + "Missing eRPC SDK file: ${CMVR_HEAD_ERPC_ROOT}/${required}") + endif() +endforeach() + +find_package(Threads REQUIRED) + +add_library(cmvr_head_erpc_sdk STATIC IMPORTED) + +set_target_properties(cmvr_head_erpc_sdk PROPERTIES + IMPORTED_LOCATION "${CMVR_HEAD_ERPC_ROOT}/lib/liberpc.a" + INTERFACE_INCLUDE_DIRECTORIES "${CMVR_HEAD_ERPC_ROOT}/include/erpc" + INTERFACE_LINK_LIBRARIES Threads::Threads) + add_library(head_usb SHARED src/usb_head_erpc_client.cpp src/usb_head_serial_transport.cpp src/usb_biohead.cpp) -target_include_directories(head_usb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(head_usb + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(head_usb PRIVATE cmvr_es::hardware cmvr_es::proto - cmvr_es::logging) + cmvr_es::logging + cmvr_head_erpc_sdk) add_library(cmvr::device::head_usb ALIAS head_usb) + install(TARGETS head_usb LIBRARY DESTINATION lib) if(BUILD_TESTING OR CMVR_HEAD_BUILD_TESTING) enable_testing() - add_executable(usb_head_erpc_client_test tests/usb_head_erpc_client_test.cpp) + + add_executable(usb_head_erpc_client_test + tests/usb_head_erpc_client_test.cpp) + target_link_libraries(usb_head_erpc_client_test PRIVATE cmvr::device::head_usb pthread) - add_test(NAME usb_head_erpc_client_test COMMAND usb_head_erpc_client_test) - add_executable(usb_head_serial_transport_test tests/usb_head_serial_transport_test.cpp) + + add_test( + NAME usb_head_erpc_client_test + COMMAND usb_head_erpc_client_test) + + add_executable(usb_head_serial_transport_test + tests/usb_head_serial_transport_test.cpp) + target_link_libraries(usb_head_serial_transport_test PRIVATE cmvr::device::head_usb pthread) - add_test(NAME usb_head_serial_transport_test COMMAND usb_head_serial_transport_test) - add_executable(usb_biohead_test tests/usb_biohead_test.cpp) + + add_test( + NAME usb_head_serial_transport_test + COMMAND usb_head_serial_transport_test) + + add_executable(usb_biohead_test + tests/usb_biohead_test.cpp) + target_link_libraries(usb_biohead_test PRIVATE - cmvr::device::head_usb cmvr_es::proto gtest gtest_main pthread) - add_test(NAME usb_biohead_test COMMAND usb_biohead_test) - set_tests_properties(usb_head_erpc_client_test usb_head_serial_transport_test usb_biohead_test + cmvr::device::head_usb + cmvr_es::proto + gtest + gtest_main + pthread) + + add_test( + NAME usb_biohead_test + COMMAND usb_biohead_test) + + set_tests_properties( + usb_head_erpc_client_test + usb_head_serial_transport_test + usb_biohead_test PROPERTIES ENVIRONMENT "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}:${CMAKE_SOURCE_DIR}/output/lib:${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/grpc/v1.76.0/lib") -endif() +endif() \ No newline at end of file diff --git a/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h index cded5e03..af590f36 100644 --- a/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h +++ b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h @@ -14,57 +14,58 @@ namespace cmvr::device { -// eRPC service 1 only. A successful reply acknowledges a command; it is not -// position feedback. No operation reconnects or retries a movement automatically. -class UsbHeadErpcClient final { -public: - using Target = std::pair; + class UsbHeadErpcClient final { + public: + using Target = std::pair; - explicit UsbHeadErpcClient( - std::unique_ptr<::cmvr::AbstractSerialTransport> serial, - std::chrono::milliseconds timeout = std::chrono::milliseconds(2000)); - // Deterministic sequence seed for offline protocol tests. - UsbHeadErpcClient(std::unique_ptr<::cmvr::AbstractSerialTransport> serial, - std::chrono::milliseconds timeout, - std::uint32_t sequence_seed); - ~UsbHeadErpcClient(); + explicit UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout = + std::chrono::milliseconds(2000)); - UsbHeadErpcClient(const UsbHeadErpcClient&) = delete; - UsbHeadErpcClient& operator=(const UsbHeadErpcClient&) = delete; + UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout, + std::uint32_t sequence_seed); - void open(const std::string& port_name, int baud_rate = 115200); - void close(); - bool isOpen() const; + ~UsbHeadErpcClient(); - bool setConstraints(const std::string& id, float velocity_rad_s, - float acceleration_rad_s2, float jerk_rad_s3); - bool setPositionGain(const std::string& id, float gain); - bool setMode(std::int32_t mode); - bool setUpdatePeriodMs(std::uint32_t period_ms); - // Empty move is allowed for the source client's no-target protocol probe. - // The caller must check for its expected -22 response explicitly. - std::int32_t move(const std::vector& targets); - std::int32_t moveJ(const std::vector& angles_rad); + UsbHeadErpcClient(const UsbHeadErpcClient&) = delete; -private: - using Clock = std::chrono::steady_clock; + UsbHeadErpcClient& operator=( + const UsbHeadErpcClient&) = delete; - std::vector call(std::uint8_t method, - const std::vector& arguments, - bool boolean_result); - std::vector readExact(std::size_t count, - Clock::time_point deadline); - void closeAfterFailure() noexcept; + void open( + const std::string& port_name, + int baud_rate = 115200); - std::unique_ptr<::cmvr::AbstractSerialTransport> serial_; - std::chrono::milliseconds timeout_; - std::uint32_t sequence_; - std::vector pending_; - std::string port_name_; - int baud_rate_{0}; - mutable std::mutex transaction_mutex_; -}; + void close(); + + bool isOpen() const; + + bool setConstraints( + const std::string& id, + float velocity_rad_s, + float acceleration_rad_s2, + float jerk_rad_s3); + + bool setPositionGain( + const std::string& id, + float gain); + + bool setMode(std::int32_t mode); + + bool setUpdatePeriodMs(std::uint32_t period_ms); + + std::int32_t move(const std::vector& targets); + + std::int32_t moveJ(const std::vector& angles_rad); + + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace cmvr::device -#endif // CMVR_ES_USB_HEAD_ERPC_CLIENT_H +#endif // CMVR_ES_USB_HEAD_ERPC_CLIENT_H \ No newline at end of file diff --git a/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp index 53143795..04e8d3ae 100644 --- a/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp +++ b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp @@ -1,330 +1,914 @@ #include "../include/usb_head_erpc_client.h" -#include #include #include #include +#include #include #include #include +#include + +#include "erpc_basic_codec.hpp" +#include "erpc_client_manager.h" +#include "erpc_crc16.hpp" +#include "erpc_framed_transport.hpp" +#include "erpc_version.h" namespace cmvr::device { namespace { -constexpr std::size_t kFrameHeaderSize = 6; -constexpr std::size_t kMessageHeaderSize = 8; -constexpr std::size_t kMaxBodySize = 4096; -constexpr std::size_t kMaxTargets = 5; +static_assert( + ERPC_VERSION_NUMBER == 11400, + "USB head requires eRPC 1.14.0"); -void append16(std::vector& out, std::uint16_t value) -{ - out.push_back(static_cast(value)); - out.push_back(static_cast(value >> 8)); -} +// 将项目串口接入官方 FramedTransport。 +// 帧封装、CRC 和类型编解码由官方 SDK 处理。 +class SdkFramedSerialTransport final : public erpc::FramedTransport { +public: + using Clock = std::chrono::steady_clock; -void append32(std::vector& out, std::uint32_t value) -{ - for (unsigned shift = 0; shift < 32; shift += 8) { - out.push_back(static_cast(value >> shift)); + static constexpr std::size_t kFrameHeaderSize = 6; + static constexpr std::size_t kMaxBodySize = 4096; + + explicit SdkFramedSerialTransport( + ::cmvr::AbstractSerialTransport& serial); + + ~SdkFramedSerialTransport() override = default; + + SdkFramedSerialTransport( + const SdkFramedSerialTransport&) = delete; + + SdkFramedSerialTransport& operator=( + const SdkFramedSerialTransport&) = delete; + + void beginTransaction( + Clock::time_point deadline, + std::size_t expected_reply_body_size); + + void endTransaction() noexcept; + void reset() noexcept; + + const std::string& lastError() const noexcept + { + return last_error_; } + + erpc_status_t send(erpc::MessageBuffer* message) override; + erpc_status_t receive(erpc::MessageBuffer* message) override; + +protected: + erpc_status_t underlyingSend( + const std::uint8_t* data, + std::uint32_t size) override; + + erpc_status_t underlyingReceive( + std::uint8_t* data, + std::uint32_t size) override; + + erpc_status_t underlyingReceive( + erpc::MessageBuffer* message, + std::uint32_t size, + std::uint32_t offset) override; + +private: + erpc_status_t checkReady(); + + erpc_status_t fail( + erpc_status_t status, + std::string message); + + erpc_status_t sdkFailure( + erpc_status_t status, + const char* operation); + + ::cmvr::AbstractSerialTransport& serial_; + + // 官方 CRC 实现,初始值与现有控制板一致。 + erpc::Crc16 crc_{0xEF4A}; + + Clock::time_point deadline_{}; + std::size_t expected_reply_body_size_{0}; + bool transaction_active_{false}; + + std::vector pending_; + std::string last_error_; +}; + +SdkFramedSerialTransport::SdkFramedSerialTransport( + ::cmvr::AbstractSerialTransport& serial) + : serial_(serial) +{ + setCrc16(&crc_); } -std::uint16_t read16(const std::vector& data, std::size_t offset) +void SdkFramedSerialTransport::beginTransaction( + Clock::time_point deadline, + std::size_t expected_reply_body_size) { - return static_cast(data.at(offset)) | - static_cast(data.at(offset + 1)) << 8; -} - -std::uint32_t read32(const std::vector& data, std::size_t offset) -{ - std::uint32_t value = 0; - for (unsigned index = 0; index < 4; ++index) { - value |= static_cast(data.at(offset + index)) << (8 * index); + if (transaction_active_) { + throw std::logic_error( + "An eRPC transaction is already active"); } - return value; + + if (expected_reply_body_size < 8 + || expected_reply_body_size > kMaxBodySize) { + throw std::invalid_argument( + "Invalid expected eRPC reply body size"); + } + + if (!pending_.empty()) { + throw std::runtime_error( + "Unexpected bytes remain before eRPC request"); + } + + last_error_.clear(); + deadline_ = deadline; + expected_reply_body_size_ = expected_reply_body_size; + transaction_active_ = true; } -std::uint16_t crc16(const std::vector& data) +void SdkFramedSerialTransport::endTransaction() noexcept { - std::uint16_t crc = 0xEF4A; - for (const std::uint8_t byte : data) { - crc ^= static_cast(byte) << 8; - for (unsigned bit = 0; bit < 8; ++bit) { - crc = static_cast( - (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1); + transaction_active_ = false; + deadline_ = {}; + expected_reply_body_size_ = 0; +} + +void SdkFramedSerialTransport::reset() noexcept +{ + endTransaction(); + pending_.clear(); + last_error_.clear(); +} + +erpc_status_t SdkFramedSerialTransport::fail( + erpc_status_t status, + std::string message) +{ + last_error_ = std::move(message); + return status; +} + +erpc_status_t SdkFramedSerialTransport::checkReady() +{ + if (!transaction_active_) { + return fail( + kErpcStatus_InvalidArgument, + "eRPC transaction deadline is not established"); + } + + if (Clock::now() >= deadline_) { + return fail( + kErpcStatus_Timeout, + "USB head transaction deadline exceeded"); + } + + if (!serial_.isOpen()) { + return fail( + kErpcStatus_ConnectionClosed, + "USB head serial transport is not open"); + } + + return kErpcStatus_Success; +} + +erpc_status_t SdkFramedSerialTransport::sdkFailure( + erpc_status_t status, + const char* operation) +{ + if (status != kErpcStatus_Success && last_error_.empty()) { + last_error_ = + std::string("Official eRPC ") + operation + + " failed, status=" + + std::to_string(static_cast(status)); + + if (status == kErpcStatus_CrcCheckFailed) { + last_error_ += " (frame CRC mismatch)"; } } - return crc; + + return status; } -std::uint16_t headerCrc(std::uint16_t size, std::uint16_t body_crc) +erpc_status_t SdkFramedSerialTransport::send( + erpc::MessageBuffer* message) { - std::vector size_bytes; - std::vector crc_bytes; - append16(size_bytes, size); - append16(crc_bytes, body_crc); - return static_cast(crc16(size_bytes) + crc16(crc_bytes)); -} + try { + const auto ready = checkReady(); -void appendString(std::vector& out, const std::string& value) -{ - if (value.empty() || value.size() > 64 || value.find('\0') != std::string::npos) { - throw std::invalid_argument("USB head servo ID must contain 1..64 non-NUL bytes"); + if (ready != kErpcStatus_Success) { + return ready; + } + + if (!message + || !message->get() + || message->getUsed() < kFrameHeaderSize + 8 + || message->getUsed() > message->getLength() + || message->getUsed() - kFrameHeaderSize > kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid or oversized eRPC request buffer"); + } + + return sdkFailure( + erpc::FramedTransport::send(message), + "send"); + } catch (const std::exception& error) { + return fail( + kErpcStatus_SendFailed, + std::string("USB head send failed: ") + error.what()); + } catch (...) { + return fail( + kErpcStatus_SendFailed, + "Unknown USB head send failure"); } - append32(out, static_cast(value.size())); - out.insert(out.end(), value.begin(), value.end()); } -void appendFloat(std::vector& out, float value) +erpc_status_t SdkFramedSerialTransport::receive( + erpc::MessageBuffer* message) +{ + try { + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + const auto required = + kFrameHeaderSize + expected_reply_body_size_; + + if (!message + || !message->get() + || message->getLength() < required) { + return fail( + kErpcStatus_MemoryError, + "eRPC reply buffer is too small"); + } + + erpc::MessageBuffer bounded( + message->get(), + static_cast(required)); + + const auto status = + erpc::FramedTransport::receive(&bounded); + + if (status != kErpcStatus_Success) { + message->setUsed(0); + return sdkFailure(status, "receive"); + } + + if (bounded.getUsed() != required) { + message->setUsed(0); + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply length mismatch"); + } + + if (!pending_.empty()) { + message->setUsed(0); + return fail( + kErpcStatus_ReceiveFailed, + "USB head received unexpected trailing bytes"); + } + + const auto after_receive = checkReady(); + + if (after_receive != kErpcStatus_Success) { + message->setUsed(0); + return after_receive; + } + + message->setUsed(bounded.getUsed()); + return kErpcStatus_Success; + } catch (const std::exception& error) { + if (message) { + message->setUsed(0); + } + + return fail( + kErpcStatus_ReceiveFailed, + std::string("USB head receive failed: ") + error.what()); + } catch (...) { + if (message) { + message->setUsed(0); + } + + return fail( + kErpcStatus_ReceiveFailed, + "Unknown USB head receive failure"); + } +} + +erpc_status_t SdkFramedSerialTransport::underlyingSend( + const std::uint8_t* data, + std::uint32_t size) +{ + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + if (!data + || size < kFrameHeaderSize + || size > kFrameHeaderSize + kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid eRPC frame write size"); + } + + const std::vector bytes(data, data + size); + + if (!serial_.write(bytes)) { + return fail( + Clock::now() >= deadline_ + ? kErpcStatus_Timeout + : kErpcStatus_SendFailed, + "USB head write failed: " + serial_.lastError()); + } + + return checkReady(); +} + +erpc_status_t SdkFramedSerialTransport::underlyingReceive( + erpc::MessageBuffer* message, + std::uint32_t size, + std::uint32_t offset) +{ + if (!message + || !message->get() + || offset > message->getLength() + || size > message->getLength() - offset) { + return fail( + kErpcStatus_MemoryError, + "Invalid eRPC receive buffer bounds"); + } + + if (offset == 0) { + if (size != kFrameHeaderSize) { + return fail( + kErpcStatus_ReceiveFailed, + "Unexpected eRPC frame header size"); + } + } else if (offset != kFrameHeaderSize + || size != expected_reply_body_size_) { + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply length mismatch"); + } + + return erpc::FramedTransport::underlyingReceive( + message, size, offset); +} + +erpc_status_t SdkFramedSerialTransport::underlyingReceive( + std::uint8_t* data, + std::uint32_t size) +{ + if (!data || size > kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid eRPC receive size"); + } + + while (pending_.size() < size) { + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + const auto remaining = deadline_ - Clock::now(); + + if (remaining <= Clock::duration::zero()) { + return fail( + kErpcStatus_Timeout, + "USB head reply deadline exceeded"); + } + + auto wait = + std::chrono::duration_cast( + remaining); + + if (wait.count() == 0) { + wait = std::chrono::milliseconds(1); + } + + std::vector chunk; + + if (!serial_.read(size - pending_.size(), wait, chunk) + || chunk.empty()) { + return fail( + Clock::now() >= deadline_ + ? kErpcStatus_Timeout + : kErpcStatus_ReceiveFailed, + "USB head reply incomplete: " + serial_.lastError()); + } + + if (pending_.size() > kMaxBodySize + kFrameHeaderSize + || chunk.size() + > kMaxBodySize + kFrameHeaderSize - pending_.size()) { + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply exceeds receive limit"); + } + + pending_.insert( + pending_.end(), chunk.begin(), chunk.end()); + } + + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + std::memcpy(data, pending_.data(), size); + pending_.erase(pending_.begin(), pending_.begin() + size); + + return kErpcStatus_Success; +} + +// 官方 Codec 负责类型编解码;这里保留严格的 bool ACK 检查。 +class StrictCodec final : public erpc::BasicCodec { +public: + using erpc::BasicCodec::read; + + void read(bool& value) override + { + std::uint8_t encoded{0}; + erpc::BasicCodec::read(encoded); + + if (isStatusOk() && encoded > 1) { + updateStatus(kErpcStatus_InvalidArgument); + } + + value = encoded == 1; + } +}; + +class CodecFactory final : public erpc::CodecFactory { +public: + erpc::Codec* create() override + { + return new (std::nothrow) StrictCodec; + } + + void dispose(erpc::Codec* codec) override + { + delete codec; + } +}; + +class BufferFactory final : public erpc::MessageBufferFactory { +public: + erpc::MessageBuffer create() override + { + auto* data = new (std::nothrow) std::uint8_t[4102]; + return erpc::MessageBuffer(data, data ? 4102 : 0); + } + + void dispose(erpc::MessageBuffer* buffer) override + { + delete[] buffer->get(); + } +}; + +class ClientManager final : public erpc::ClientManager { +public: + explicit ClientManager(std::uint32_t seed) + { + m_sequence = seed; + } + + void begin(std::uint8_t method) + { + method_ = method; + } + + erpc::RequestContext createRequest(bool oneway) override + { + if (m_sequence + == std::numeric_limits::max()) { + m_sequence = 0; + } + + return erpc::ClientManager::createRequest(oneway); + } + +protected: + void verifyReply(erpc::RequestContext& request) override + { + auto* codec = request.getCodec(); + + codec->reset(m_transport->reserveHeaderSize()); + + erpc::message_type_t type{}; + std::uint32_t service{}; + std::uint32_t method{}; + std::uint32_t sequence{}; + + codec->startReadMessage( + type, service, method, sequence); + + if (codec->isStatusOk() + && (type != erpc::message_type_t::kReplyMessage + || service != 1 + || method != method_ + || sequence != request.getSequence())) { + codec->updateStatus(kErpcStatus_ExpectedReply); + } + } + +private: + std::uint8_t method_{0}; +}; + +void checkId(const std::string& id) +{ + if (id.empty() + || id.size() > 64 + || id.find('\0') != std::string::npos) { + throw std::invalid_argument( + "USB head servo ID must contain 1..64 non-NUL bytes"); + } +} + +void checkFinite(float value) { - static_assert(sizeof(float) == sizeof(std::uint32_t)); - static_assert(std::numeric_limits::is_iec559); if (!std::isfinite(value)) { - throw std::invalid_argument("USB head arguments must be finite float32 values"); + throw std::invalid_argument( + "USB head arguments must be finite float32 values"); } - std::uint32_t bits; - std::memcpy(&bits, &value, sizeof(bits)); - append32(out, bits); -} - -std::int32_t integerResult(const std::vector& data) -{ - const auto bits = read32(data, 0); - std::int32_t value; - std::memcpy(&value, &bits, sizeof(value)); - return value; } } // namespace +struct UsbHeadErpcClient::Impl { + using Clock = std::chrono::steady_clock; + + std::unique_ptr<::cmvr::AbstractSerialTransport> serial; + std::chrono::milliseconds timeout; + mutable std::mutex mutex; + + std::string port; + int baud{0}; + + SdkFramedSerialTransport transport; + CodecFactory codec_factory; + BufferFactory buffer_factory; + ClientManager manager; + + Impl( + std::unique_ptr<::cmvr::AbstractSerialTransport> wire, + std::chrono::milliseconds budget, + std::uint32_t seed) + : serial(std::move(wire)), + timeout(budget), + transport(*serial), + manager(seed) + { + manager.setTransport(&transport); + manager.setCodecFactory(&codec_factory); + manager.setMessageBufferFactory(&buffer_factory); + } + + void failClosed() noexcept + { + transport.reset(); + + try { + serial->close(); + } catch (...) { + } + } + + void checkStatus(erpc::Codec& codec) + { + if (!codec.isStatusOk()) { + throw std::runtime_error( + "Official eRPC status=" + + std::to_string( + static_cast(codec.getStatus())) + + ": " + transport.lastError()); + } + } + + template + Result invoke( + std::uint8_t method, + EncodeArguments encode_arguments) + { + static_assert( + std::is_same_v + || std::is_same_v, + "Head service returns only bool or int32"); + + std::lock_guard lock(mutex); + + if (!serial->isOpen()) { + throw std::runtime_error( + "USB head is not connected"); + } + + const auto deadline = Clock::now() + timeout; + + try { + transport.beginTransaction( + deadline, method <= 4 ? 9 : 12); + + manager.begin(method); + + Result result{}; + + { + auto request = manager.createRequest(false); + + struct ReleaseRequest { + ClientManager& manager; + erpc::RequestContext& request; + + ~ReleaseRequest() + { + manager.releaseRequest(request); + } + } release{manager, request}; + + auto* codec = request.getCodec(); + + if (!codec) { + throw std::runtime_error( + "Cannot allocate eRPC request buffer/codec"); + } + + codec->startWriteMessage( + erpc::message_type_t::kInvocationMessage, + 1, + method, + request.getSequence()); + + encode_arguments(*codec); + checkStatus(*codec); + + manager.performRequest(request); + checkStatus(*codec); + + codec->read(result); + checkStatus(*codec); + } + + if (Clock::now() >= deadline) { + throw std::runtime_error( + "USB head reply deadline exceeded"); + } + + transport.endTransaction(); + return result; + } catch (const std::exception& error) { + const std::string reason = error.what(); + + failClosed(); + + throw std::runtime_error( + "USB head method " + std::to_string(method) + + " result unconfirmed; disconnected without retry. " + "Command may already have taken effect: " + + reason); + } catch (...) { + failClosed(); + throw; + } + } +}; + UsbHeadErpcClient::UsbHeadErpcClient( std::unique_ptr<::cmvr::AbstractSerialTransport> serial, std::chrono::milliseconds timeout) - : UsbHeadErpcClient(std::move(serial), timeout, std::random_device{}()) + : UsbHeadErpcClient( + std::move(serial), + timeout, + std::random_device{}()) { } UsbHeadErpcClient::UsbHeadErpcClient( std::unique_ptr<::cmvr::AbstractSerialTransport> serial, - std::chrono::milliseconds timeout, std::uint32_t sequence_seed) - : serial_(std::move(serial)), timeout_(timeout), sequence_(sequence_seed) + std::chrono::milliseconds timeout, + std::uint32_t seed) { - if (!serial_ || timeout_.count() <= 0) { - throw std::invalid_argument("USB head transport and positive timeout are required"); + if (!serial || timeout.count() <= 0) { + throw std::invalid_argument( + "USB head transport and positive timeout are required"); } + + impl_ = std::make_unique( + std::move(serial), timeout, seed); } UsbHeadErpcClient::~UsbHeadErpcClient() { - try { close(); } catch (...) { } + try { + close(); + } catch (...) { + } } -void UsbHeadErpcClient::open(const std::string& port_name, int baud_rate) +void UsbHeadErpcClient::open( + const std::string& port, + int baud) { - if (port_name.empty() || baud_rate <= 0) { - throw std::invalid_argument("USB head serial port and positive baud rate are required"); + if (port.empty() || baud <= 0) { + throw std::invalid_argument( + "USB head serial port and positive baud rate are required"); } - std::lock_guard lock(transaction_mutex_); - if (serial_->isOpen()) { - if (port_name != port_name_ || baud_rate != baud_rate_) { - throw std::logic_error("Close USB head before changing serial configuration"); + + std::lock_guard lock(impl_->mutex); + + if (impl_->serial->isOpen()) { + if (port != impl_->port || baud != impl_->baud) { + throw std::logic_error( + "Close USB head before changing serial configuration"); } + return; } - pending_.clear(); + + impl_->transport.reset(); + try { - if (!serial_->open({port_name, baud_rate})) { - throw std::runtime_error("Cannot open USB head port: " + serial_->lastError()); + if (!impl_->serial->open({port, baud})) { + throw std::runtime_error( + "Cannot open USB head port: " + + impl_->serial->lastError()); } - if (!serial_->flushInput()) { - throw std::runtime_error("Cannot clear USB head input: " + serial_->lastError()); + + if (!impl_->serial->flushInput()) { + throw std::runtime_error( + "Cannot clear USB head input: " + + impl_->serial->lastError()); } - port_name_ = port_name; - baud_rate_ = baud_rate; + + impl_->port = port; + impl_->baud = baud; } catch (...) { - closeAfterFailure(); + impl_->failClosed(); throw; } } void UsbHeadErpcClient::close() { - std::lock_guard lock(transaction_mutex_); - pending_.clear(); - if (serial_->isOpen() && !serial_->close()) { - throw std::runtime_error("Cannot close USB head port: " + serial_->lastError()); + std::lock_guard lock(impl_->mutex); + + impl_->transport.reset(); + + if (impl_->serial->isOpen() + && !impl_->serial->close()) { + throw std::runtime_error( + "Cannot close USB head port: " + + impl_->serial->lastError()); } } bool UsbHeadErpcClient::isOpen() const { - std::lock_guard lock(transaction_mutex_); - return serial_->isOpen(); + std::lock_guard lock(impl_->mutex); + return impl_->serial->isOpen(); } -void UsbHeadErpcClient::closeAfterFailure() noexcept +bool UsbHeadErpcClient::setConstraints( + const std::string& id, + float velocity, + float acceleration, + float jerk) { - pending_.clear(); - try { serial_->close(); } catch (...) { } + checkId(id); + checkFinite(velocity); + checkFinite(acceleration); + checkFinite(jerk); + + if (velocity <= 0 || acceleration <= 0 || jerk <= 0) { + throw std::invalid_argument( + "USB head motion limits must be positive"); + } + + return impl_->invoke(1, [&](erpc::Codec& codec) { + codec.writeString( + static_cast(id.size()), + id.c_str()); + + codec.write(velocity); + codec.write(acceleration); + codec.write(jerk); + }); } -std::vector UsbHeadErpcClient::readExact( - std::size_t count, Clock::time_point deadline) +bool UsbHeadErpcClient::setPositionGain( + const std::string& id, + float gain) { - while (pending_.size() < count) { - const auto remaining = deadline - Clock::now(); - if (remaining <= Clock::duration::zero()) { - throw std::runtime_error("USB head reply deadline exceeded"); - } - auto wait = std::chrono::duration_cast(remaining); - if (wait.count() == 0) wait = std::chrono::milliseconds(1); - std::vector chunk; - if (!serial_->read(count - pending_.size(), wait, chunk) || chunk.empty()) { - throw std::runtime_error("USB head reply incomplete: " + serial_->lastError()); - } - if (chunk.size() > kMaxBodySize + kFrameHeaderSize - pending_.size()) { - throw std::runtime_error("USB head reply exceeds receive limit"); - } - pending_.insert(pending_.end(), chunk.begin(), chunk.end()); - } - if (Clock::now() >= deadline) { - throw std::runtime_error("USB head reply deadline exceeded"); - } - std::vector result(pending_.begin(), pending_.begin() + count); - pending_.erase(pending_.begin(), pending_.begin() + count); - return result; -} + checkId(id); + checkFinite(gain); -std::vector UsbHeadErpcClient::call( - std::uint8_t method, const std::vector& arguments, - bool boolean_result) -{ - if (arguments.size() > kMaxBodySize - kMessageHeaderSize) { - throw std::invalid_argument("USB head request exceeds frame limit"); + if (gain < 0) { + throw std::invalid_argument( + "USB head position gain must be nonnegative"); } - std::lock_guard lock(transaction_mutex_); - if (!serial_->isOpen()) throw std::runtime_error("USB head is not connected"); - if (++sequence_ == 0) ++sequence_; - std::vector body{0, method, 1, 1}; - append32(body, sequence_); - body.insert(body.end(), arguments.begin(), arguments.end()); - const auto size = static_cast(body.size()); - const auto checksum = crc16(body); - std::vector frame; - append16(frame, headerCrc(size, checksum)); - append16(frame, size); - append16(frame, checksum); - frame.insert(frame.end(), body.begin(), body.end()); - try { - const auto deadline = Clock::now() + timeout_; - if (!serial_->write(frame)) { - throw std::runtime_error("USB head write failed: " + serial_->lastError()); - } - const auto header = readExact(kFrameHeaderSize, deadline); - const auto reply_size = read16(header, 2); - const auto reply_crc = read16(header, 4); - if (read16(header, 0) != headerCrc(reply_size, reply_crc)) { - throw std::runtime_error("USB head frame header CRC mismatch"); - } - const std::size_t expected_size = kMessageHeaderSize + (boolean_result ? 1 : 4); - if (reply_size != expected_size) { - throw std::runtime_error("USB head reply length mismatch"); - } - const auto reply = readExact(reply_size, deadline); - if (crc16(reply) != reply_crc) { - throw std::runtime_error("USB head reply body CRC mismatch"); - } - if (reply[0] != 2 || reply[1] != method || reply[2] != 1 || reply[3] != 1 || - read32(reply, 4) != sequence_) { - throw std::runtime_error("USB head reply type/method/service/version/sequence mismatch"); - } - if (boolean_result && reply[8] > 1) { - throw std::runtime_error("USB head reply boolean must be 0 or 1"); - } - if (!pending_.empty()) { - throw std::runtime_error("USB head received unexpected trailing bytes"); - } - return {reply.begin() + kMessageHeaderSize, reply.end()}; - } catch (const std::exception& error) { - closeAfterFailure(); - throw std::runtime_error("USB head method " + std::to_string(method) + - " result unconfirmed; disconnected without retry. Command may already " - "have taken effect: " + error.what()); - } catch (...) { - closeAfterFailure(); - throw; - } -} + return impl_->invoke(2, [&](erpc::Codec& codec) { + codec.writeString( + static_cast(id.size()), + id.c_str()); -bool UsbHeadErpcClient::setConstraints(const std::string& id, float velocity_rad_s, - float acceleration_rad_s2, float jerk_rad_s3) -{ - if (velocity_rad_s <= 0 || acceleration_rad_s2 <= 0 || jerk_rad_s3 <= 0) { - throw std::invalid_argument("USB head motion limits must be positive"); - } - std::vector args; - appendString(args, id); - appendFloat(args, velocity_rad_s); - appendFloat(args, acceleration_rad_s2); - appendFloat(args, jerk_rad_s3); - return call(1, args, true)[0] != 0; -} - -bool UsbHeadErpcClient::setPositionGain(const std::string& id, float gain) -{ - if (gain < 0) throw std::invalid_argument("USB head position gain must be nonnegative"); - std::vector args; - appendString(args, id); - appendFloat(args, gain); - return call(2, args, true)[0] != 0; + codec.write(gain); + }); } bool UsbHeadErpcClient::setMode(std::int32_t mode) { - if (mode < 0 || mode > 2) throw std::invalid_argument("USB head mode must be 0, 1 or 2"); - std::vector args; - append32(args, static_cast(mode)); - return call(3, args, true)[0] != 0; + if (mode < 0 || mode > 2) { + throw std::invalid_argument( + "USB head mode must be 0, 1 or 2"); + } + + return impl_->invoke(3, [&](erpc::Codec& codec) { + codec.write(mode); + }); } -bool UsbHeadErpcClient::setUpdatePeriodMs(std::uint32_t period_ms) +bool UsbHeadErpcClient::setUpdatePeriodMs( + std::uint32_t period) { - if (period_ms < 1 || period_ms > 100) { - throw std::invalid_argument("USB head update period must be 1..100 ms"); + if (period < 1 || period > 100) { + throw std::invalid_argument( + "USB head update period must be 1..100 ms"); } - std::vector args; - append32(args, period_ms); - return call(4, args, true)[0] != 0; + + return impl_->invoke(4, [&](erpc::Codec& codec) { + codec.write(period); + }); } -std::int32_t UsbHeadErpcClient::move(const std::vector& targets) +std::int32_t UsbHeadErpcClient::move( + const std::vector& targets) { - if (targets.size() > kMaxTargets) { - throw std::invalid_argument("USB head supports at most five targets"); + if (targets.size() > 5) { + throw std::invalid_argument( + "USB head supports at most five targets"); } - std::vector args; + std::set seen; - append32(args, static_cast(targets.size())); + for (const auto& target : targets) { + checkId(target.first); + checkFinite(target.second); + if (!seen.insert(target.first).second) { - throw std::invalid_argument("USB head servo ID repeated in target batch"); + throw std::invalid_argument( + "USB head servo ID repeated in target batch"); } - appendString(args, target.first); - appendFloat(args, target.second); } - return integerResult(call(5, args, false)); + + return impl_->invoke( + 5, + [&](erpc::Codec& codec) { + codec.startWriteList( + static_cast(targets.size())); + + for (const auto& target : targets) { + codec.writeString( + static_cast( + target.first.size()), + target.first.c_str()); + + codec.write(target.second); + } + }); } -std::int32_t UsbHeadErpcClient::moveJ(const std::vector& angles_rad) +std::int32_t UsbHeadErpcClient::moveJ( + const std::vector& angles) { - if (angles_rad.size() > kMaxTargets) { - throw std::invalid_argument("USB head supports at most five joint targets"); + if (angles.size() > 5) { + throw std::invalid_argument( + "USB head supports at most five joint targets"); } - std::vector args; - append32(args, static_cast(angles_rad.size())); - for (const auto angle : angles_rad) appendFloat(args, angle); - return integerResult(call(6, args, false)); + + for (const auto value : angles) { + checkFinite(value); + } + + return impl_->invoke( + 6, + [&](erpc::Codec& codec) { + codec.startWriteList( + static_cast(angles.size())); + + for (const auto value : angles) { + codec.write(value); + } + }); } -} // namespace cmvr::device +} // namespace cmvr::device \ No newline at end of file diff --git a/request.txt b/request.txt index bb291fa4..2a8b5a7b 100644 --- a/request.txt +++ b/request.txt @@ -38,5 +38,6 @@ third_party/matplotplusplus/1.2.0 third_party/ethercat/v1.7.0 third_party/huayan_robot/v1.0 third_party/aubo_sdk/v0.27.1 +third_party/erpc/v1.14.0