公共接口约定
========================================

.. _1-文档约定:

1. 文档约定
-----------

1.1 基本约定
~~~~~~~~~~~~

+----------------------+-----------------------------------------------+
| 项目                 | 约定                                          |
+======================+===============================================+
| C++ 命名空间         | 低层 API 使用 ``srobots``\ ；高层 API 使用    |
|                      | ``srobots::hl``\ 、\ ``srobots::hl::nrt`` 和  |
|                      | ``srobots::hl::rt``                           |
+----------------------+-----------------------------------------------+
| Python 导入路径      | ``srobots.low_level`` 和                      |
|                      | ``srobots.high_level``                        |
+----------------------+-----------------------------------------------+
| 机械臂关节数         | 7                                             |
+----------------------+-----------------------------------------------+
| 底盘速度自由度       | 3：\ ``vx``\ 、\ ``vy``\ 、\ ``wz``           |
+----------------------+-----------------------------------------------+
| 关节位置、速度、力矩 | rad、rad/s、Nm                                |
+----------------------+-----------------------------------------------+
| 末端位姿             | ``[x, y, z, qx, qy, qz, qw]``\ ，位置单位为 m |
+----------------------+-----------------------------------------------+
| 笛卡尔速度           | ``[vx, vy, vz, wx, wy, wz]``                  |
+----------------------+-----------------------------------------------+
| 力/力矩              | ``[fx, fy, fz, mx, my, mz]``                  |
+----------------------+-----------------------------------------------+
| 变换矩阵             | 4×4，按列优先排列                             |
+----------------------+-----------------------------------------------+
| 雅可比矩阵           | 6×7，按列优先排列                             |
+----------------------+-----------------------------------------------+
| RT/NRT               | RT 命令由调用方持续按控制周期发送；NRT        |
|                      | 命令提交后由控制器执行                        |
+----------------------+-----------------------------------------------+

每个条目分别列出摘要、参数、返回值和示例。C++ 和 Python 名称放在
同一条目中，表示这些语言提供相同能力；某种语言没有公开封装时会明确说明。
动态语言对 C++ 模板和借用型子对象提供等价的动态接口；各条目会说明名称和返回值
差异。

..

   实机安全：使能、切换模式、发送命令、回放记录和重置零位都可能导致机器人
   运动。调用前必须确认目标控制器、运动单元、模式、负载、工具、工作空间、
   速度限制和急停状态，并确保操作人员可以立即停止设备。


1.2 生命周期与线程约定
~~~~~~~~~~~~~~~~~~~~~~

- ``Robot`` 和 ``ObserverClient`` 构造后均未连接。
- i7 子对象借用根 ``Robot`` 的资源；IX 由 IP 构造的对象拥有连接。
- 所有运动句柄结束并释放后，再断开对应根对象。
- 状态、观察器和运动完成回调可能在应用程序主线程之外执行。
- 回调应快速返回；不要在回调中等待自身结束或销毁仍在使用的父对象。
- 多线程共享对象时，除接口明确说明外，由应用程序负责同步。
- 阻塞状态读取、\ ``wait()`` 和 ``Join()`` 都可能长时间等待。

相关运行时边界见 :doc:`SDK 架构 <architecture>`。


1.3 兼容性与定义来源
~~~~~~~~~~~~~~~~~~~~

稳定入口为安装后的低层 C++ 扁平头文件和 ``<srobots/hl/...>`` 高层头文件，
``srobots.low_level``\ 、\ ``srobots.high_level`` 两个 Python 模块。不要依赖私有 Python 原生模块、
内部命名空间或未安装头文件。

公共 C++ include 名称：

- ``<robot.h>``
- ``<logging.h>``
- ``<local_state_reader.h>``
- ``<nav_client.h>``
- ``<observer_client.h>``
- ``<scheduler.h>``
- ``<srobots/hl/common/...>``
- ``<srobots/hl/nrt/...>``
- ``<srobots/hl/rt/...>``

语言封装的接口定义来源：

- ``src/python/srobots/low_level.py``
- ``src/python/srobots/high_level.py``
- ``src/python/srobots/nav.py``

构建和运行依赖见\ :doc:`系统要求 <../overview/system_requirements>`\ ，安装与链接方式见
:doc:`安装 C++ <../installation/install_cpp>`\ ；架构和兼容机制见
:doc:`SDK 架构 <architecture>`\ 。

.. _2-安装与导入:

2. 安装与导入
-------------

发行目录的 C++ 与 Python 集成方式见 :doc:`../installation/install_cpp` 和
:doc:`../installation/install_python`。使用同一目录中的头文件、Python 模块和运行库。

2.1 C++ 头文件
~~~~~~~~~~~~~~

C++ 低层头文件使用 ``<robot.h>``\ 、\ ``<observer_client.h>`` 等扁平名称；
高层头文件统一位于 ``<srobots/hl/...>``\ 。除声明另有说明外，同一对象上的
并发调用由应用程序负责同步。

C++ 低层接口对不可用能力采用统一保证：返回 ``ResultCode`` 的方法返回
``ResultCode::NotSupported``\ ；返回其他值或 ``void`` 的方法抛出
``srobots::RobotError``\ ，其 ``code`` 为 ``ResultCode::NotSupported``\ 、
``domain`` 为 ``RobotErrorDomain::User``\ ，\ ``message`` 包含操作名。控制器或
底层 C API 返回的其他失败也通过 ``RobotError`` 保留具体结果码。构造阶段无法
取得兼容 C API、资源创建失败和本地调用约束仍可能分别抛出
``std::runtime_error``\ 、\ ``std::logic_error`` 或标准库异常。析构函数不抛出异常。

状态、Observer、调度器和高层运动回调可能在 SDK 内部线程执行。传给回调的状态、
数据包和状态指针只在回调期间有效；\ ``user_data`` 必须保持有效，直到取消注册
操作返回。回调应快速返回，不应在回调中销毁其所属句柄或等待自身退出。

2.1.1 本地 SDK 信息
^^^^^^^^^^^^^^^^^^^^^^^^

``srobots::getSdkInfo()`` （头文件 ``sdk_info.h``）、Python
``srobots.low_level.get_sdk_info()``
读取实际加载的 ``libsrobot.so`` 的构建信息。无参数，不需要创建 Robot、不连接
控制器、不启动线程、不改变控制权或使能状态。

C++ 返回拥有字符串的 ``SdkInfo``，Python 返回字典：

* ``control_api``：当前为 ``unified-v1``，表示
  I7／IX 统一控制接口合约，与机器人型号、RPC 协议版本分别管理。
* ``version``：SDK 发布版本，不是服务端版本。
* ``git_commit``：构建提交号；构建时无法取得则为空。

接口可并发调用，返回值可独立保存和修改。查询同步完成，没有超时参数；原生元数据
查询不分配内存，语言层字符串和字典转换可能分配，应在初始化时调用，不放入实时循环。
旧库没有对应函数槽位时抛出 ``RobotError``，错误码为 ``NotSupported``／
``NOT_SUPPORTED``；其他错误保留原错误码。旧 Python 包可能根本没有此函数，
可用 ``hasattr(low_level, "get_sdk_info")`` 检查，不能将导入错误视为旧版标志。

.. code-block:: cpp

   #include <sdk_info.h>
   const auto info = srobots::getSdkInfo();

.. code-block:: python

   from srobots import low_level
   info = low_level.get_sdk_info()
   print(info["control_api"], info["version"], info["git_commit"])

2.2 日志配置
~~~~~~~~~~~~

首次创建 ``Robot`` 时，SDK 默认在进程当前工作目录写入 ``srobot.log``\ ，
默认级别为 WARN，仅启用文件输出，并在 ERROR 及以上级别刷新。每个日志文件达到
10 MiB 后轮转，最多保留 5 个轮转文件。若当前目录不可写，SDK 会关闭这个默认
sink，且不会因此使 ``Robot`` 构造失败。应用可在创建 ``Robot`` 前调用日志配置
接口，修改文件路径和级别、单独启用控制台输出，或同时关闭文件与控制台以禁用
SDK 日志。显式配置的文件 sink 创建失败时，配置调用仍返回失败。SDK 使用自己的
异步线程池，不修改 spdlog 的默认 logger、全局线程池、全局格式或定时刷新器。

异步队列满时采用 ``overrun_oldest``\ 。应用可读取累计丢弃计数并纳入健康监控；
需要确保此前日志已经写入时，可显式刷新。SDK 会转义外部字符串中的换行和控制
字符，并遮蔽日志消息中的绝对路径。日志仍可能包含运行状态，生产环境应限制日志
文件权限与保留周期。

``callback`` 可将所有达到配置级别的日志转发到应用自己的 logger。它在 SDK
异步日志线程执行，应快速返回，不得在回调内再次配置日志。C++ 的
``callback_user_data`` 必须保持有效，直到后续配置替换或关闭回调并返回。若需
捕获所有级别，将 ``level`` 设为 TRACE，并可将 ``file_path`` 置空以仅使用外部
logger。

.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   #include <logging.h>

   srobots::LoggingOptions logging;
   logging.file_path = "/var/log/robot-app/srobot.log";
   logging.level = srobots::LogLevel::Warn;
   logging.callback = forward_to_app_logger;
   logging.callback_user_data = &app_logger;
   const auto result = srobots::configureLogging(logging);

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>
   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   from srobots import low_level

   logging = low_level.LoggingOptions()
   logging.file_path = "/var/log/robot-app/srobot.log"
   logging.level = low_level.LogLevel.WARN
   result = low_level.configure_logging(logging, app_logger.warning)
   dropped = low_level.logging_dropped_count()


.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

各语言的常用导入方式如下：

.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   #include <robot.h>
   #include <local_state_reader.h>
   #include <observer_client.h>
   #include <scheduler.h>
   #include <drive_error_catalog.h>
   #include <srobots/hl/nrt/robot.hpp>
   #include <srobots/hl/rt/robot.hpp>

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   from srobots import high_level, low_level, nav

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

``srobots._low_level`` 和 ``srobots._high_level`` 是私有原生模块，不属于稳定导入
路径。Python 软件包必须与构建时使用的 CPython 次版本和机器体系结构一致。

.. _14-错误处理:

14. 错误处理
------------

统一错误类型为 C++ ``ResultCode``/``RobotError``\ 、Python
``low_level.ResultCode``/``high_level.ResultCode`` 和 ``RobotError``\ 。
常用值包括 ``OK``\ 、
``NOT_READY``\ 、\ ``FAILED``\ 、\ ``NETWORK_ERROR``\ 、\ ``CONTROL_PREEMPTED``\ 、
``SERVER_SHUTDOWN``\ 、\ ``TIMEOUT``\ 、\ ``BUSY``\ 、\ ``REJECTED``\ 、\ ``INVALID_ARGUMENT``\ 、
``NOT_SUPPORTED`` 和 ``PRECONDITION_FAILED``\ 。

- C++ 低层命令通常返回 ``ResultCode``\ ，查询接口可通过输出参数区分合法的
  ``false``/无新样本和查询错误。
- C++ 低层返回值或 ``void`` 接口无法通过正常返回值表达失败时抛出
  ``RobotError``\ 。异常的 ``code``、\ ``domain`` 和 ``message`` 字段可直接读取；
  缺失函数表能力固定报告 ``ResultCode::NotSupported``\ 。
- C++ 高层提交和等待返回 ``Result<T>``\ ；其成功仅表示取得值，运动结果还应检查
  ``MotionStatus::result`` 和 ``phase``\ 。
- 稳定 Python 低层封装成功时直接返回值或 ``None``\ ，失败时抛出
  ``low_level.RobotError``\ ；异常的 ``code`` 属性保存 ``ResultCode``\ 。
- Python 高层提交和等待失败时抛出 ``high_level.RobotError``\ ；直接返回错误码的
  方法仍需与 ``high_level.ResultCode.OK`` 比较。
- ``NOT_SUPPORTED`` 表示当前库或控制器不提供能力，不是可重试网络错误。

.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   const auto code = robot.disconnect();
   if (code == srobots::ResultCode::NotSupported) {
     // 当前库不提供此能力；不要按网络错误重试。
   }

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>
   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   try:
       robot.disconnect()
   except low_level.RobotError as error:
       if error.code == low_level.ResultCode.NOT_SUPPORTED:
           pass  # 不按网络错误重试


.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   if (code != srobots::ResultCode::OK) {
     // 记录并处理错误，不继续发送相关命令。
   }

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   try:
       robot.enable()
   except low_level.RobotError as error:
       print(error.code)

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. _141-formaterlabel--format_er_label:

14.1 ``formatErLabel()`` / ``format_er_label()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**摘要：** 将驱动器或服务端关节错误码格式化为稳定标签。

======== ========================
参数     说明
======== ========================
``code`` 驱动器或服务端关节错误码
======== ========================

**返回值：** 标签字符串，例如驱动器错误使用 ``Er`` 前缀；功能不可用时抛出异常。


.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   const std::string label = srobots::formatErLabel(code);

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   label = low_level.format_er_label(code)

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. _142-lookupdriveerror--lookup_drive_error:

14.2 ``lookupDriveError()`` / ``lookup_drive_error()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**摘要：** 查询错误目录中的名称和说明。

======== ========================
参数     说明
======== ========================
``code`` 驱动器或服务端关节错误码
======== ========================

**返回值：** C++ 返回 ``std::optional<DriveErrorInfo>``\ ；Python 返回
``(label, name, description)``\ 。未知或零错误码分别返回
``std::nullopt`` 或 ``None``\ 。

.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   const auto info = srobots::lookupDriveError(code);

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   info = low_level.lookup_drive_error(code)

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. _143-formatjointdrivealarms--format_joint_drive_alarms:

14.3 ``formatJointDriveAlarms()`` / ``format_joint_drive_alarms()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**摘要：** 格式化一组逐关节错误码，忽略值为零的条目。

======================== ==================
参数                     说明
======================== ==================
``unit_name`` / ``unit`` 显示用运动单元名称
``codes``                16 位错误码数组
``count``                仅 C++；数组元素数
======================== ==================

**返回值：** 格式化后的多关节告警字符串；没有非零错误时返回空字符串。


.. raw:: html

   <details open>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   const auto text = srobots::formatJointDriveAlarms("left", codes.data(),
                                                     codes.size());

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   text = low_level.format_joint_drive_alarms("left", codes)

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. _144-format_drive_alarm_line--formatdrivealarmline:

14.4 ``format_drive_alarm_line()`` / ``formatDriveAlarmLine()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**摘要：** Python 格式化一条带运动单元名和关节序号的告警。
C++ 没有同名便捷函数，可组合 ``formatErLabel()`` 和 ``lookupDriveError()``\ 。

========= ==================
参数      说明
========= ==================
``unit``  显示用运动单元名称
``joint`` 关节序号
``code``  错误码
========= ==================

**返回值：** Python 返回单行告警字符串。

.. raw:: html

   <details>
   <summary><strong>Python</strong></summary>

.. code:: python

   line = low_level.format_drive_alarm_line("left", 3, code)

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>

.. raw:: html

   <details>
   <summary><strong>C++</strong></summary>

.. code:: cpp

   const auto label = srobots::formatErLabel(code);
   const auto info = srobots::lookupDriveError(code);

.. container:: sdk-example-reference

   参考示例：无

.. raw:: html

   </details>


