Skip to content

1. 文档说明与公共规范 ​

本章给出接口速查索引与跨接口的公共规范。1.1 是按模块与功能分类整理的索引清单(点击接口名可直接跳转到第 2 章对应详情);1.2是通用规范(响应模型、CLI 调试、调用稳定性、安全声明);逐接口的字段、参数与示例见第 2 章与第 4 章。

1.1 API总览清单 ​

表中的 接口名称 即代码中的服务名 / 话题名 / 端口号,是检索 SDK 与源码的入口;分类、功能分类 与第 2 章章节一一对应。

分类功能分类接口名称功能描述
运动控制功能运控高层接口/aimdk_5Fmsgs/srv/GetMcAction查询运动状态
/aimdk_5Fmsgs/srv/SetMcAction设置运动状态
/aimdk_5Fmsgs/srv/SetMcMotion设置全身动作
/aimdk_5Fmsgs/srv/SetMcPresetMotion设置预设动作控制
/aima/mc/locomotion/velocity走跑控制
/aimdk_5Fmsgs/srv/SetMcInputSource设置输入源
/aimdk_5Fmsgs/srv/GetCurrentInputSource查询当前控制输入源
/aima/mc/custom/joint/command自定义上肢关节控制
运控低层接口/aima/hal/joint/command关节控制命令
/aima/hal/joint/state关节状态反馈
交互控制功能语音控制/aimdk_5Fmsgs/srv/PlayTts语音合成
/aimdk_5Fmsgs/srv/GetVolume获取音量
/aimdk_5Fmsgs/srv/SetVolume设置音量
/aimdk_5Fmsgs/srv/GetMute获取静音状态
/aimdk_5Fmsgs/srv/SetMute设置静音
/aimdk_5Fmsgs/srv/PlayAudioFile音频文件播放
/aimdk_5Fmsgs/srv/StopAudioPlay停止音频播放
TCP 端口 6001(PulseAudio simple-protocol-tcp)音频文件播放(TCP 直连)
TCP 端口 4713(PulseAudio native-protocol-tcp)音频录制(TCP 直连)
/aima/hal/audio/audio_device_list音频设备列表(查询输入/输出设备)
/aima/agent/asr_result语音识别结果
屏幕控制/aimdk_5Fmsgs/srv/PlayEmotion播放表情和视频
系统控制/aimdk_5Fmsgs/srv/MigrateSystemState系统状态迁移(重启与关机)
硬件抽象功能触觉传感器/aima/hal/touch/state头部触摸状态
视觉传感器/aima/hal/camera/CaptureJpegImage获取指定相机单帧JPEG图像
rtsp_url = "rtsp://<IP>:<Port>/live_<camera_id>"RTSP流媒体服务
电源管理/aima/hal/bms/state电源管理相关数据
/aimdk_5Fmsgs/srv/SetExt12vPower外挂算力板供电控制
灯语控制/aimdk_5Fmsgs/srv/LedStripCommand设置整机灯语样式
惯性传感器/aima/hal/imu/stateIMU 惯导状态(四元数、角速度、加速度)

1.2 接口公共说明 ​

本节汇总跨接口的通用约定:Service 与 Topic 统一以 CommonRequest / CommonResponse、CommonTaskResponse 作为请求响应外壳;命名空间集中在 /aimdk_5Fmsgs(Service)与 /aima(Topic 与 HAL);其余细则见 1.3–1.6。

1.2.1 接口响应规范 ​

SDK 采用统一的响应模型。服务调用通常返回 CommonResponse 或 CommonTaskResponse,建议遵循“框架返回码优先,业务状态码随后”的判定原则。

完整响应模型概览

字段类型语义说明
headerResponseHeaderRPC / 框架层信息。包含系统时间戳 stamp 与返回码 code。
status / stateCommonState核心业务状态。反映具体指令的执行进展,通过 .value 获取。
messagestring诊断信息。当调用非 SUCCESS 时,提供可读的错误排查描述。
task_iduint64任务标识。仅在 CommonTaskResponse 中提供,用于异步任务追踪。

1. 系统状态码语义映射 (ResponseHeader)

该结构体定义了分布式通信及框架层的响应状态。

字段类型语义说明
stampbuiltin_interfaces/Time时间戳。框架层生成的消息处理时间。
codeint64框架返回码 (Enum)。见下表枚举描述。
code值枚举标识框架解析开发者处理建议
0SUCCESS调度成功请求已被底层系统接受并进入执行序列。
1FAIL调度失败请求被拦截(如状态机冲突、资源占用或权限不足)。

2. 业务状态码语义映射 (CommonState)

以下枚举定义了整个二次开发 SDK 的全生命周期状态语义:

状态值枚举标识业务解析开发者处理建议
0UNKNOWN未知状态建议记录日志并触发系统自检或安全回退。
1SUCCESS调用成功业务逻辑正常完成或异步请求已成功入队。
2FAILURE执行失败业务规则冲突或资源报错,请查阅 message 诊断。
3ABORTED任务中止任务已被外部停止、中途取消或被高优先级任务抢占。
4TIMEOUT响应超时检查网络链路、底层驱动状态或系统负载。
5INVALID无效请求检查参数是否越界、格式是否非法或状态机切换是否受限。
6IN_MANUAL手动接管机器人处于离线物理接管或手动维护模式,拒绝指令。
100NOT_READY系统未就绪模块仍处于引导/初始化阶段,建议延时重试。
200PENDING任务排队中异步任务已受理,正处于底层执行器的资源消费序列。
300CREATED任务已创建任务实例已就绪并完成预设参数绑定,等待执行开口。
400RUNNING正在运行任务处于活动状态,正实时控制机器人硬件或消耗资源。

CommonState reason 故障原因枚举

当业务调用失败时,CommonResponse 的 status.reason 或 CommonTaskResponse 的 state.reason 字段提供具体的失败原因:

原因值枚举标识业务解析
0REASON_SUCCESS成功
1REASON_OPENBOX开箱状态中
2REASON_STARTUP_CHECK开机自检中
3REASON_SHUTDOWN关机状态中
4REASON_FROM当前形态不支持
5REASON_LOW_BATTERY低电量限制
6REASON_CHARGE正在充电中
7REASON_NO_WHITELIST动作不在白名单
8REASON_HDSHDS故障
9REASON_ACTION当前模式不支持
10REASON_OBSTACLE_FORWARD前方有障碍物
11REASON_OBSTACLE_BACK后方有障碍物
12REASON_OBSTACLE_LEFT左方有障碍物
13REASON_OBSTACLE_RIGHT右方有障碍物
14REASON_OBSTACLE_UP上方有障碍物
15REASON_TASK_RUNNING其他任务正在运行
16REASON_TARGET_STATE机器人已经是目标状态
17REASON_NOT_FOUND未找到相关动作
18REASON_NO_SKILL_LIST无可用技能列表
19REASON_FORM_MIS_MATCH无法执行任务,机器人需要处于双足站立状态
20REASON_ACTION_NOT_MATCH当前动作不匹配,无法执行动画
21REASON_ACTION_BLACKLISTED当前动作在黑名单中,无法执行动画
22REASON_NO_TRANSFER_PATH当前姿态下无法进行动作转移
23REASON_NO_ELIGIBLE_SKILL无符合条件的技能
24REASON_INDOOR_WHOLE_BODY室内模式下暂不支持该动作
25REASON_ENGINE_NOT_READY动作配置未就绪,无法执行动画
26REASON_NOT_SUPPORTED当前机型不支持该功能
27REASON_STAND_UP_IN_PROGRESS机器人正在起立,暂不能收起默认动作
28REASON_NOT_INTERRUPTIBLE当前动画不可打断
29REASON_INTERRUPT_INVALID当前动画 ID 无效,无法打断
30REASON_TRANSFORM_CONDITION当前状态不满足变形/动作执行条件

多级判别准则:开发者应首先核对 header.code == 0(系统调度成功),再结合 status.value == 1(业务逻辑成功)来判定最终结果。 故障详情获取:当调用失败(包括框架及其业务层)时,建议通过 message 字段获取具体的错误排查详情。 故障原因定位:当业务调用失败时,可通过 status.reason 字段获取具体的失败原因(详见上方 CommonState reason 故障原因枚举)。 状态码冲突提醒:部分底层模块(如运动模式控制接口)返回的 status.value 遵循 McActionStatus 协议,其 100 代码代表 RUNNING。处理反馈时请务必核对具体接口的模型定义。


1.2.2 CLI 调试指南 ​

您可以利用 ROS 2 命令行工具对上述接口进行点对点调试:

  • 服务调用 (Service Call):ros2 service call <service_name> <service_type> '<data>'
  • 话题发布 (Topic Pub):ros2 topic pub <topic_name> <message_type> '<data>'
  • 参数获取:
    • 字段溯源:载荷中的 Key 必须与对应 .srv 或 .msg 定义中的字段名严格一致。若定义存在嵌套,需按层级展开。
  • 填充规范:数值直接填写;布尔值全小写 true/false;字符串建议外层与内层引号不同(外单内双 或 外双内单均可),例如 'text: “...”' 或 ”{text: '...'}”。
  • 缺省占位:对 RequestHeader 等嵌套对象,建议直接使用 {} 占位(例如 header: {})。
  • 示例:ros2 service call /aimdk_5Fmsgs/srv/SetMcAction aimdk_msgs/srv/SetMcAction '{header: {}, source: "sdk_rpc", command: {action: {value: 201}}}'

1.2.3 接口调用稳定性提醒 ​

在代码中动态创建(实例化)新的 ROS 2 Client 后,即使 wait_for_service 返回成功,底层的通信链路可能仍需极短的时间(通常为毫秒级)来完成最终的连接匹配。

  • 现象:在 Client 刚创建后的瞬间发起的首次请求,即便网络正常,也可能出现“请求发出了但服务端没收到”的情况(在跨芯片通讯场景下较常见)。
  • 开发建议:
    1. 推荐长连接:建议在节点初始化时一次性创建 Client 并全局复用,避免在业务循环或函数内部频繁创建与销毁 Client。
    2. 增加重试或延时:如必须动态创建,建议在服务就绪后额外等待一小段时间(如 200ms),或为首次调用增加重试逻辑。

详情可参考 ROS2 官方关于 Client 匹配滞后的 技术讨论。

1.2.4 友好用户使用声明 ​

CAUTION

重要安全性须知:底层硬件控制(尤其是关节伺服)具有极高的物理操作性风险。在开始正式业务开发前,请务必先行阅读并签署本目录下的 《友好用户使用声明》。任何因不当指令导致的硬件损毁或安全事故,均由开发者承担全部后果。


2. 接口详情 ​

本SDK提供了一套完整的ROS2接口,用于控制启元机器人。接口遵循ROS2标准,支持C++和Python两种编程语言,为开发者提供灵活、高效的机器人应用开发环境。

2.1 运动控制功能 ​

介绍启元机器人的运动控制,涵盖了高层运动模式(如走跑、预设动作)的全局管控指令,以及底层关节电机(角度、力位)伺服的精细化控制接口。

核心功能

  • 高阶业务指令调用:支持通过特定宏指令(Action/Motion)一键触发机器人预设动作或轨迹。
  • 运动模式与信号源管理:支持机器人整机运动状态(如走跑、站立)的查询切换及输入源优先级配置。
  • 底层关节精细伺服控制:支持下发关节电机标定量(位置、力矩等),支持进行高频状态监控。

2.1.1 运控高层接口 ​

本模块提供高层运动指令全局管控,包含运动模式切换、输入源控制、走跑控制及预设动作触发。

2.1.1.1 运动模式控制 ​

Q1机型 运控状态机切换逻辑如下:

mermaid
graph TD
    %% 定义节点
    START(( )) -- Init --> PASSIVE

    %% 位置控制节点 (绿色系)
    PASSIVE["PASSIVE_DEFAULT<br/>零力矩急停"]
    DAMPING["DAMPING_DEFAULT<br/>阻尼急停"]
    STAND["BIPED_STAND_DEFAULT<br/>位控站立"]
    STORE["STORE_DEFAULT<br/>折叠收储"]
    PRESETBOX["播放上肢动作"]

    %% 力矩控制节点 (黄色系)
    WALK["BIPED_WALK_RUN<br/>走跑模式"]
    RUN["BIPED_RUN<br/>超能模式/跑步模式"]
    WBC["BIPED_WHOLE_BODY_CTRL<br/>全身控制模式"]
    SETMCMOTION["SetMcMotion<br/>全身动作(如 BOXING 拳击、INTRO_POSE7 亮相动作7 等)"]

    %% 自定义控制节点 (青色系)
    CUSTOM["BIPED_CUSTOM_UPPER<br/>二开上肢控制"]

    %% 过渡状态 (灰色系)
    STAND_UP["STAND_UP<br/>站起"]
    LIE_DOWN["LIE_FACE_DOWN<br/>趴下俯卧"]
    LIE_UP["LIE_FACE_UP<br/>趴下仰躺"]

    %% 跳转逻辑及接口标注
    PASSIVE <-- SetMcAction --> DAMPING

    PASSIVE -- SetMcAction --> STAND
    PASSIVE -- SetMcAction --> STAND_UP
    STAND_UP -.-> WALK

    PASSIVE -- SetMcAction --> STORE

    STAND <-- SetMcAction --> WALK

    WALK <-- SetMcAction --> CUSTOM
    CUSTOM -- SetMcAction --> STAND

    WALK <-- SetMcAction --> WBC

    PRESETBOX -- SetMcPresetMotion --- WBC

    WALK -- SetMcMotion --> SETMCMOTION
    SETMCMOTION -.-> WALK

    WALK -- SetMcAction --> LIE_DOWN
    WALK -- SetMcAction --> LIE_UP

    LIE_DOWN -.-> PASSIVE
    LIE_UP -.-> PASSIVE

    WALK <-- SetMcAction --> RUN

    %% 样式美化
    style PASSIVE fill:#d5e8d4,stroke:#82b366
    style DAMPING fill:#d5e8d4,stroke:#82b366
    style STAND fill:#d5e8d4,stroke:#82b366
    style STORE fill:#d5e8d4,stroke:#82b366
    style PRESETBOX fill:#d5e8d4,stroke:#82b366,stroke-dasharray: 5 5

    style WALK fill:#fff2cc,stroke:#d6b656
    style WBC fill:#fff2cc,stroke:#d6b656
    style SETMCMOTION fill:#fff2cc,stroke:#d6b656

    style CUSTOM fill:#d4f1f9,stroke:#3199cc

    style STAND_UP fill:#f5f5f5,stroke:#666666
    style LIE_DOWN fill:#f5f5f5,stroke:#666666
    style LIE_UP fill:#f5f5f5,stroke:#666666

⚠️ 状态切换限制:

状态的切换通常需要严格遵循上图中箭头指向的逻辑连线路径(不支持跨状态强行越级切换)。若您下发不在合法拓扑连线范围内的 Action 指令,将触发底层控制系统拦截保护。

任何状态均可直接切换至 阻尼急停 (DAMPING_DEFAULT),但阻尼急停状态只能切换至 零力矩急停 (PASSIVE_DEFAULT)。

任何状态均可直接切换至 零力矩急停 (PASSIVE_DEFAULT),但零力矩急停状态只能切换至 位控站立 (BIPED_STAND_DEFAULT)、阻尼急停 (DAMPING_DEFAULT)、折叠收储 (STORE_DEFAULT)。

在全身动作(通过 SetMcMotion 调用)执行结束后,系统将自动执行状态切换,切换至 走跑模式 (BIPED_WALK_RUN)。

仅在状态切换至 全身控制模式 (BIPED_WHOLE_BODY_CTRL) 下,方可调用 SetMcPresetMotion 接口播放预设的上肢动作。

⚠️ 位控站立模式 (BIPED_STAND_DEFAULT) 安全警告:该模式下设备无平衡调节功能,机器人不会主动抵抗外力或自动修正姿态倾斜。使用时务必确保设备处于平稳支撑环境,必要时增加外部辅助固定措施,防止设备因倾斜导致摔机损坏。

【Service】查询运动模式 ​

功能描述

查询机器人当前正在执行的运动或形态动作(Action)生命周期阶段。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/GetMcAction
  • 数据类型:aimdk_msgs/srv/GetMcAction
  • 数据流向:Robot -> Outer (状态/查询返回)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/GetMcAction aimdk_msgs/srv/GetMcAction '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/action/srv/GetMcAction.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request    # Request 部分

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
ResponseHeader    header
McActionInfo      info      # Action信息

GetMcAction 协议定义

字段数据类型描述
requestCommonRequest请求参数(包含优先级等通用配置)
headerResponseHeader响应头信息(包含序列号与状态回传)
infoMcActionInfo当前机器人运动模式的详细信息

特别说明

  • 状态轮询与业务时序控制:
    1. 动作的物理切换在下发后虽立即返回成功,但机械实际过渡可能长达数秒,此期间并发其他指令极易引发冲撞风险。
    2. 下发切换请求后,开发者需启动循环高频探测。当且仅当本接口返回的 status.value 由 200 (TRANSITION) 变更为 100 (RUNNING) 时,方可进入下一步业务逻辑。
  • 未知动作的防御性兜底解析:当探测到 info.current_action.value 等于 0 时,切勿将其简单判定为机器人处于“空闲待机态”。
    1. 在特定状态下,底层可能触发了仅驻留于配置文件中、尚未映射至公开 API 枚举表的内部保护动作,导致强制序列化回退为 0。
    2. 遇到 value = 0 无法对应已知场景时,业务逻辑必须优先提取 info.action_desc 字段。该字段能无视枚举字典限制,直接上报底层内核当前真正在跑的字符串标签。

编程示例

【Service】设置运动模式 ​

功能描述

设置合法的运动模式(如稳定站立或走跑等)。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetMcAction
  • 数据类型:aimdk_msgs/srv/SetMcAction
  • 数据流向:Outer -> Robot (控制命令/设置)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetMcAction aimdk_msgs/srv/SetMcAction '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/action/srv/SetMcAction.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
RequestHeader      header
string             source     # 触发源,语义参考 McTaskSource.msg
McActionCommand    command    # Action命令

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonTaskResponse response

SetMcAction 协议定义

字段数据类型描述
headerRequestHeader请求头
sourcestring触发源;语义参考 McTaskSource
commandMcActionCommandAction命令
responseCommonTaskResponse包含任务 ID 和业务状态

特别说明

  • 双通道调用:底层接口支持通过整型标识符 (action.value) 或字符串描述 (action_desc) 两种方式下发动作指令。
  • 解析顺序与回退逻辑:
    1. 系统优先解析 action.value。若该数值在内核枚举映射中存在(例如 1 对应 PASSIVE_DEFAULT),则直接执行对应动作。
    2. 若 action.value 为空值(0)或未定义的数值,系统将退而解析 action_desc 字段。若该字符串配置文件中定义的动作名称精确匹配,则执行对应动作。
  • 状态切换逻辑图:当前机型的运动模式状态切换规则及其闭环拓扑详见 2.1.1.1 运动模式控制 章节。
  • MIMIC 类动作切换建议:MIMIC 类模仿动作不建议通过 SetMcAction 直接切换。调用 SetMcMotion 执行此类动作时,系统会自动从 BIPED_WALK_RUN 切换至对应的全身 Action;动作完成后,再自动切回 BIPED_WALK_RUN。

SetMcAction 业务状态码 (response.state.value)

当 header.code == 0(系统调度成功)时,response.state.value 提供 SetMcAction 特有的业务结果:

状态码含义是否支持
1action 设置成功,开始切换逻辑是
-1001未定义从当前 action 切换到目标 action 的规则是
-1002当前action未定义,一般不会报是
-1003目标action未定义是
-1004机器人姿态不具备切换目标action的能力是
-1005未定义目标action的行为是
-1006目标action行为和当前action行为不支持切换是
-1007action切换超时否
-10001请求过于频繁(500ms 一次)是
-10002触发源为空,不响应请求是
  • McAction 枚举值列表: Q1机型 支持的 McAction 枚举值如下:
    常量名数值描述
    PASSIVE_DEFAULT1被动模式
    DAMPING_DEFAULT2阻尼模式
    BIPED_STAND_DEFAULT201位控站立
    STORE_DEFAULT1001折叠收储
    BIPED_WALK_RUN1002走跑
    BIPED_WHOLE_BODY_CTRL1005全身动作控制
    STAND_UP1007站起
    LIE_FACE_DOWN1009躺下-俯卧
    LIE_FACE_UP1010躺下-仰躺
    BIPED_BLIND_TERRAIN1012越障模式(室外)
    BIPED_CUSTOM_UPPER1014上肢控制
    BIPED_RUN1015超能模式/跑步模式

编程示例

【Service】设置全身动作 ​

功能描述

有别于上面那种按键触发式的固有动作控制(Action),Motion 接口专门用于运控高级开发——播放基于神经网络推理模型 (.onnx) 或是特定外部特征文件记录的动作细则序列。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetMcMotion
  • 数据类型:aimdk_msgs/srv/SetMcMotion
  • 调用方式:Call (服务客户端下发)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetMcMotion aimdk_msgs/srv/SetMcMotion '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/motion/srv/SetMcMotion.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
RequestHeader    header          # 此接口是播放全身动作接口
string           source          # 触发源,语义参考 McTaskSource.msg
int32            type            # 资源类型

# 自有模型
int32            MIMIC_QY = 1

# 灵创模型
int32            MIMIC_LC = 2

string           motion          # 全身动作名称,若motion为空,加载model中resource; 反之,从本地加载执行资源。
string           model           # onnx 模型绝对路径
string           resource        # 资源绝对路径,比如轨迹参考
bool             interrupt       # 是否打断(给后面animation接口合并预留)

# 操作类型
int32            operation

# 预先加载
int32            PRELOAD = 1

# 开始执行
int32            EXECUTION = 2

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonTaskResponse    response   # 响应头 (含 task_id)

SetMcMotion 协议定义

字段数据类型描述
headerRequestHeader请求头
sourcestring触发源;语义参考 McTaskSource
typeint32资源类型 (1: MIMIC_QY, 2: MIMIC_LC)
motionstring全身动作名称
modelstringonnx 模型绝对路径
resourcestring资源绝对路径,比如轨迹参考
interruptbool是否打断
operationint32操作类型 (1: PRELOAD 预先加载, 2: EXECUTION 开始执行)
responseCommonTaskResponse响应头 (含 task_id)

特别说明

  • 强制时序前置条件:
    1. 开启基础框架阀门:调用本接口前,必须先使用 SetMcAction 接口将系统切入指定的Action(BIPED_WALK_RUN)。
    2. 阻塞确认状态跃迁:框架开启指令发出后,切勿立刻盲发本动作。调用端必须写明轮询检测逻辑,通过比对 GetMcAction 的实时反馈,确认底层执行态彻底平稳跃迁并停留至 RUNNING 后,方能安全地下发最终动作指令。
  • 仅支持内置动作调用:
    1. 调用者必须在 motion 字段传入系统内置的合法动作名称(如 "INTRO_POSE3",系统可用的 Motion 列表参见下表)。若传入空值或未登记名称,接口将无法正常执行。 Q1机型 Motion 枚举值列表:
名称Type描述
INTRO_POSE7MIMIC亮相动作7
BOXINGMIMIC拳击
DANCE_LOCKINGMIMIC街舞-锁舞
DANCE_MJMIMIC星际滑步
DANCE_GOMIMIC_V2跃动时刻
HAPPY_PICKMIMIC_V2元气蹦蹦
DANCE_QMIMIC_V2奇妙节拍
SHOW_ENTERMIMIC_V2闪亮登场
SHOW_RETURNMIMIC_V2潇洒退场
RUN_JUMPMIMIC_V2欢乐巡游
SIUZHUANMIMIC_V2进球狂欢
DREAM_FLYMIMIC_V2梦羽轻扬
DANCE_BABYQMIMIC_V2星际萌芽
TAIJIMIMIC_V2行云太极
EXPLOSIVE_GUNFIREMIMIC_V2爆裂节拍
XINBAODAOMIMIC_V2舞蹈-新宝岛
  1. 当前服务端仅支持通过 model 字段读取启元内部动作生成平台的 ONNX 绝对路径;暂不支持通过 resource 字段读取外部资源或轨迹参考文件。其他外部模型路径也不在当前接口支持范围内。
  • 异步任务编排机制(非阻塞响应):
    1. 此服务采用非阻塞队列机制。接口返回 SUCCESS 及 task_id,仅代表动作请求校验合格且已成功入队。
    2. 由于物理动作耗时长,服务端不会阻塞等待执行结束。上层若需监控实际动作何时播完,需保存 task_id 去异步监听专属的排队进度。

编程示例

2.1.1.2 预设动作控制 ​

【Service】预设动作控制 ​

功能描述

用于控制机器人的局部或全身执行预设的动画序列。与 SetMcMotion 依赖神经网络推理不同,PresetMotion 通常播放的是基于关键帧或预录制的关节空间轨迹文件(如 .csv)。常用于礼仪挥手、比心、拍照姿态等固定交互动作。执行前需要确保机器人已进入稳定站立模式。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetMcPresetMotion
  • 数据类型:aimdk_msgs/srv/SetMcPresetMotion
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetMcPresetMotion aimdk_msgs/srv/SetMcPresetMotion '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/motion/srv/SetMcPresetMotion.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
RequestHeader     header
string            source       # 触发源,语义参考 McTaskSource.msg
McControlArea     area         # 控制区域
McPresetMotion    motion       # 预设动作
bool              interrupt    # 是否打断前一个动作
string            ani_path     # 自定义动作地址

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonTaskResponse    response

SetMcPresetMotion 协议定义

字段数据类型描述
headerRequestHeader请求头
sourcestring触发源;语义参考 McTaskSource
areaMcControlArea控制区域
motionMcPresetMotion预设动作
interruptbool是否打断前一个动作
ani_pathstring自定义动作地址
responseCommonTaskResponse-

特别说明

  • 强制时序前置条件:
    1. 开启基础框架阀门:调用本接口前,必须先使用 SetMcAction 接口将系统切入指定的Action(BIPED_WHOLE_BODY_CTRL)。
    2. 阻塞确认状态跃迁:框架开启指令发出后,切勿立刻盲发本动作。调用端必须写明轮询检测逻辑,通过比对 GetMcAction 的实时反馈,确认底层执行态彻底平稳跃迁并停留至 RUNNING 后,方能安全地下发最终动作指令。 Q1机型 支持的预设动作列表如下:
动作编号描述
0恢复默认姿态
3001招手
3002握手
3003碰拳
3004挥手
3005情绪动作 - 开心
3007双手比心
3008加油
3010伸懒腰
3012讲话动作A
3013讲话动作B
3014讲话动作C
3018拥抱
3021拒绝
3046跳舞动作A
3047跳舞动作B
3048跳舞动作C
  • 支持外部绝对路径加载:
    1. 若 ani_path 非空,优先加载其指定的 .csv 路径文件;否则退回使用 motion 枚举去匹配内置库。
    2. area 控制掩码仅作上层标识参考。系统不会基于此过滤动作,而完全依照提取出的文件曲线强驱电机。
  • 缺失强制稳态拦截机制:
    1. 服务端不设置稳态检查,在任何极端运动姿态中发出的动画预设指令都会被立即响应下发。
    2. 为避免控制权冲突导致设备动作不可控,业务端必须主动施加安全时序约束。强烈建议配合 GetMcAction 进行状态判断,确认系统已落位至稳定状态后再下发预设请求。
  • 防打断模式拒接断言特征:
    1. 当 interrupt = false,且当前系统正处于其他动画序列的播放进程中时,服务端会拒接本次新覆盖下发请求以保护原有动画完成。
    2. 被拦截时接口返回的 state 依然是 RUNNING。调用方无法通过系统态识别失败,必须协同解析头帧错误码判定:header.code == 0 代表新请求被正常响应入队,header.code == 1 即被拦截丢弃。
  • 预置自定义动作播放: Q1机型 支持用户加载自定义轨迹进行动作播放。轨迹数据需采用固定的 .csv 格式,且采样率必须严格匹配 120fps。
    1. 若在接口请求中指定了机上 .csv 文件的绝对路径,系统将尝试解析并执行该轨迹。
    2. 轨迹文件可通过 APP”手把手教学”功能录制生成(文件存储于 /home/user/custom_motions/,文件名格式为 <用户输入名称>_<时间戳>_<编号>.csv),亦可使用”灵创”工具或 Blender 等三维软件制作导出(需符合固定列定义格式)。
    3. .csv 文件示例可参考如下(仅显示前10行):
      left_shoulder_pitch_jointleft_shoulder_roll_jointleft_shoulder_yaw_jointleft_elbow_jointright_shoulder_pitch_jointright_shoulder_roll_jointright_shoulder_yaw_jointright_elbow_joint
      0.01819431781768800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01819431781768800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01819431781768800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01849949359893800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01849949359893800.1353295445442200-0.02849853038787840.79678988456726070.0145322084426880-0.14265376329422000.02788817882537840.8038089275360107
      0.01849949359893800.1356347203254700-0.02819335460662840.79678988456726070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01849949359893800.1353295445442200-0.02849853038787840.79678988456726070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01819431781768800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107
      0.01819431781768800.1353295445442200-0.02849853038787840.79648470878601070.0145322084426880-0.14234858751297000.02788817882537840.8038089275360107

编程示例

2.1.1.3 速度控制 ​

【Topic】走跑控制 ​

功能描述

控制机器人在水平面内的平移速度(前进/侧移)及转向速度。该接口专门用于接收外部(如遥控器、App 摇杆、自主导航 PNC)连续、高频发送的速度控制指令,它是所有“移动指令”的主干汇聚口。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/mc/locomotion/velocity
  • 数据类型:aimdk_msgs/msg/McLocomotionVelocity
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Publish (发布)
  • CLI 调用:ros2 topic pub /aima/mc/locomotion/velocity aimdk_msgs/msg/McLocomotionVelocity '{...}'
  • QoS:Reliable / Volatile / Depth=10
  • 频率:50 Hz ~ 100 Hz

接口定义

  • 协议路径:aimdk_msgs/mc/motion/McLocomotionVelocity.msg
msg
# ==========================================
# [话题载荷 Payload] 走跑速度控制指令结构体
# ==========================================
MessageHeader    header              # ROS2 标准头部信息(包含时间戳)
string           source              # 指令下发端口来源 (如: pad, rc, navigation)
float64          forward_velocity    # (X轴)前后前进线速度 (|v| > 0.2 m/s)
float64          lateral_velocity    # (Y轴)左右横排行线速度 (|v| > 0.2 m/s)
float64          angular_velocity    # (Z轴)原地偏航旋转角速度 (|v| > 0.2 rad/s)
float64          pitch_velocity      # 机体俯仰速度控制
float64          level

McLocomotionVelocity 协议定义

字段数据类型描述
headerMessageHeader消息头
sourcestring消息源
forward_velocityfloat64前进速度 (m/s)
lateral_velocityfloat64侧移速度 (m/s)
angular_velocityfloat64转向速度 (rad/s)
pitch_velocityfloat64预留字段,当前不生效。俯仰速度 (rad/s),正值为俯,负值为仰
levelfloat64预留字段,当前不生效。控制强度百分比

特别说明

  • 指令源仲裁与抢占机制:
    1. source 必须填入合法的自定义的已注册标识(输入源设置方法参见 输入源控制 章节)。系统基于来源优先级进行仲裁,高优先级源会自动拦截低优先级指令。
    2. 输入源冲突避免:调用走跑控制接口时,自定义的输入源标识(source)严禁与系统内置信源(如 rc、pnc、interaction、vr、app_proxy)重复使用,以防不同信源在同层级互相冲刷覆盖,引发不可预期的物理运动表现。系统内置输入源参见:内置输入源配置表。
    3. 若单一信源中断超过 1000ms,系统将自动触发“脱锁”机制释放控制权,并按序顺延至次级信源或触发安全停机。
  • 运动模式与生效时序要求:
    1. 发送速度指令前,要求机器人已通过 SetMcAction 成功切换至运动模式(如 BIPED_WALK_RUN)。
    2. 建议调用端通过 GetMcAction 确认底层状态彻底进入 RUNNING 后再下发控制指令,否则下发的走跑控制无法生效。
    3. 速度范围限制:针对 Q1机型,线速度与角速度的具体取值范围请严格参考上文的 McLocomotionVelocity 协议定义 表格。二开脚本配置的最低速度是通用参考值;不同运动模式最低速度各不相同。即使指令速度小于脚本里设定的值,机器人可能仍然会执行运动。只是低于硬件本身最低速度运行时,关节容易出现抖动、异响,不推荐这样使用。
    4. 极值速度预警:在极低速度或接近速度边界值时,整机运动控制系统为维持机体动态平衡可能会触发代偿机制,从而引发非预期的运动姿态。建议在实际控制中尽量避免下发处于该极限区间的速度指令。

编程示例

2.1.1.4 输入源控制 ​

输入源控制是一套基于优先级的“交通指挥系统”,通过对实时指令流的唯一锁定与超时脱锁监控,确保机器人在多端并发操作下的运动稳定与物理安全。

优先级配置参考如下:

优先级范围控制层级典型信源示例
100 - 80系统级控制紧急停止 (E-Stop)、安全保护模式、物理阻感回撤等
79 - 60高级控制工业遥控器 (RC)、App 手动遥控、实体摇杆等
59 - 40中级控制语音控制指令、手势动作交互控制等
39 - 20低级控制SDK 二次开发信号、PNC 仿真/自主算法等
19 - 0备用控制研发调试模式、低压测试、离线仿真补丁等

内置输入源配置表

输入源标识 (source)预设优先级别超时自动脱锁 (ms)对应物理信源说明
rc801000工业级实体遥控器 (Remote Control)
pnc801000导航规划算法 (Planning and Control)
interaction801000语音、视觉手势等交互指令源
vr701000VR 远程操控终端
app_proxy601000移动端 App 代理转发信源

仲裁逻辑满足以下三项核心准则:

  • 高优先级绝对抢占:若系统当前由低优先级信源控制,此时一旦检测到高优先级信源(如 rc)的有效指令,系统将瞬间切换“指挥锁”,低优先级源会自动被拦截并静默处理。
  • 等优先级互斥保护:当多个相同优先级的信源同时发布指令时,系统遵循“先入为主”原则。当前已获得控制权的信源会独占“指挥锁”,直到其主动停止发送或发生指令超时。
  • 超时脱锁与平滑顺延:系统为每个信源都设有 1000ms(默认)的 Watchdog。一旦当前主控源指令中断超过该阈值,系统会自动释放控制权,并按优先级降序自动寻找下一个已就绪的候补信源,以确保运动指令流的连续性。
【Service】设置输入源 ​

功能描述

动态管理多个控制信号输入源(如手柄控制、算法控制等),并执行优先级仲裁配置。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetMcInputSource
  • 数据类型:aimdk_msgs/srv/SetMcInputSource
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetMcInputSource aimdk_msgs/srv/SetMcInputSource '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/motion/srv/SetMcInputSource.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request         # Request 部分
McInputAction    action          # ADD MODIFY DELETE DISABLE ENABLE
McInputSource    input_source

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonTaskResponse    response

SetMcInputSource 协议定义

字段数据类型描述
requestCommonRequestRequest 部分
actionMcInputAction
input_sourceMcInputSource
responseCommonTaskResponse

特别说明

  • 接口 Action 与参数必填矩阵:针对不同的 action.value,对 input_source 结构的填充要求有严格区别。
动作类型 (action.value)功能说明input_source 必填参数
INPUTACTION_ADD (1001)添加新输入源name, priority, timeout
INPUTACTION_MODIFY (1002)修改现有源属性name, priority, timeout
INPUTACTION_DELETE (1003)删除输入源name
INPUTACTION_ENABLE (2001)启用输入源name
INPUTACTION_DISABLE (2002)禁用输入源name
  • 操作逻辑与隐式激活规则:
    1. 系统会校验 action 与信源的当前状态。例如对已经存在的 source 再次执行 ADD 操作会触发参数校验报错。
    2. 只要 ADD (1001) 操作成功,该信源在内存中将被默认为 Enable(开启)态并直接参与仲裁,无需额外执行启用。
  • ⚠️ 核心性能风险:修改不持久化:
    1. 本接口所做的任何修改(添加、修改、启用或禁用等)仅保存在当前运行内存(RAM)中。
    2. 此操作不会回刷 YAML 配置文件。若系统重启,所有通过本接口生效的输入源配置都将丢失,系统将恢复为配置文件预设状态。

编程示例

【Service】获取当前控制输入源 ​

功能描述

查询当前处于激活状态的控制输入源。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/GetCurrentInputSource
  • 数据类型:aimdk_msgs/srv/GetCurrentInputSource
  • 数据流向:Robot -> Outer (状态/查询返回)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/GetCurrentInputSource aimdk_msgs/srv/GetCurrentInputSource '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/mc/motion/srv/GetCurrentInputSource.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request    # Request 部分

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonTaskResponse    response
McInputSource         input_source

GetCurrentInputSource 协议定义

字段数据类型描述
requestCommonRequestRequest 部分
responseCommonTaskResponse
input_sourceMcInputSource

特别说明

  • 仲裁结果快照与控制权抖动监测:
    1. 本接口返回调用瞬间系统内真正获得“设备物理控制权”,且正在驱动底层硬件运行的唯一控制源标识。
    2. 若 name 字段在多个标识间频繁切换(控制权抖动),通常意味着系统内存在不合理的信源竞争,会导致机器人动作执行出现明显卡顿。
  • 关于空值("")的初始化状态说明:
    1. 在系统正常运行及已有信源接入的背景下,input_source.name 字段受限于默认配置一般不会为空。
    2. 仅在机器人开机启动后、尚未收到任何合法运动控制指令包的“初始化未受控”阶段,该字段才会上报为空字符串。
  • 控制权归属权与指令活跃态的区别: 接口反映的是当前时刻的“受控归属权”。即便当前主控信源因通信超时导致机器人停动,本接口在未出现新的合法抢占者前,依然会返回该控制源的标识。因此开发者不能仅凭此接口返回的标识,就断定当前信源的控制流依然是高频、持续且活跃的。
  • 业务逻辑的闭环认证基准:
    1. 本接口是验证第三方应用(如 App 或 PNC 算法)是否成功获得机器人控制权的核心判定基准。
    2. 强烈建议在执行 SetMcInputSource 提权操作后,定期通过此接口校验 name 字段的返回结果,以建立完整的控制权校验闭环。

编程示例

2.1.1.5 自定义上肢关节控制 ​

【Topic】自定义上肢关节控制 ​

功能描述

用于向 MC 层下发自定义上肢关节目标命令。MC 接收该 topic 后,会在内部按 JointCommand.name 匹配对应关节数据,并将目标值传到当前自定义上肢控制流程中。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/mc/custom/joint/command
  • 数据类型:aimdk_msgs/msg/McCustomJointCommand
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Publish (发布)
  • CLI 调用:ros2 topic pub /aima/mc/custom/joint/command aimdk_msgs/msg/McCustomJointCommand '{...}'
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:100 Hz

接口定义

  • 协议路径:aimdk_msgs/mc/motion/McCustomJointCommand.msg
msg
# ==========================================
# [话题载荷 Payload] 自定义上肢关节控制指令
# ==========================================
MessageHeader    header              # 消息头
JointCommand[]   joints              # 上肢关节目标命令数组

McCustomJointCommand 协议定义

字段数据类型描述
headerMessageHeader消息头
jointsJointCommand[]上肢关节目标命令数组

JointCommand 子结构定义

joints 数组中的元素复用 JointCommand 定义,字段含义与关节名称、位置、速度、力矩、刚度、阻尼参数保持一致。

特别说明

  • 运动模式与生效时序要求:
    1. 使用本接口时,请确保机器人原生MC正常运行。
    2. 发送自定义上肢关节命令前,必须先将机器人切换至 BIPED_CUSTOM_UPPER 模式。
    3. 建议调用端通过 GetMcAction 确认 action_desc 已进入 BIPED_CUSTOM_UPPER,且 status 已进入 RUNNING,确认机器人稳定后,再开始发布 /aima/mc/custom/joint/command。
  • 与 HAL 低层关节直控的区别:
    1. 本接口由 MC 层接收并传给自定义上肢控制流程,不等同于 /aima/hal/joint/command 的 HAL 低层伺服直控接口。
    2. 调用端不应将 McCustomJointCommand 当作 JointCommandArray 使用;两者 topic、消息类型、控制链路和安全边界均不同。
  • 数据完整性要求:
    1. 本 topic 仅控制上肢 8 个关节及腰部 2 个关节,共 10 个关节。安全起见,每帧建议完整填写这 10 个关节的目标值,其余关节可不填。
    2. joints[] 的顺序任意即可,但joints[].name 必须使用文档中列出的正式关节名称。名称缺失或拼写错误会导致对应子指令无法被 MC 正确匹配。
    3. 未填写的关节目标值会按 0 处理,可能导致关节目标突变、姿态异常或其他不可预期的物理风险。
    4. 建议以稳定的 100 Hz 频率连续发布,并保持 header.stamp 单调递增,避免控制流抖动或乱序。
  • 起止姿态安全要求:
    1. 控制发起前,必须关注机器人当前关节起始位置,避免直接下发与当前姿态偏差过大的目标命令,否则关节可能发生突变。
    2. 控制结束前,建议先将上肢及腰部关节位姿平滑恢复到默认站立状态附近,再切换到其他动作,以降低后续动作切换时的意外风险。

编程示例

2.1.2 运控低层接口 ​

本模块提供底层关节电机伺服控制,包含关节位置/力矩命令下发与自由度状态循环上报。

2.1.2.1 关节控制 ​

提供机器人全身关节电机的底层同步控制与多维状态反馈架构,支持位置、力矩及阻抗参数实时交互。

Q1机型 的关节及限位信息如下:

关节归属关节正式名称 (name)最小值 (rad)最大值 (rad)最大力矩 (N·m)
左手臂left_shoulder_pitch_joint-3.14161.570822.0
left_shoulder_roll_joint-0.08732.792522.0
left_shoulder_yaw_joint-1.57081.570822.0
left_elbow_joint-0.87271.658122.0
右手臂right_shoulder_pitch_joint-3.14161.570822.0
right_shoulder_roll_joint-2.79250.087322.0
right_shoulder_yaw_joint-1.57081.570822.0
right_elbow_joint-0.87271.658122.0
左腿部left_hip_pitch_joint-3.05431.570836.0
left_hip_roll_joint-0.69811.570836.0
left_hip_yaw_joint-1.57081.570836.0
left_knee_joint0.02.443536.0
left_ankle_pitch_joint-0.78540.436322.0
left_ankle_roll_joint-0.34910.349122.0
右腿部right_hip_pitch_joint-3.05431.570836.0
right_hip_roll_joint-1.57080.698136.0
right_hip_yaw_joint-1.57081.570836.0
right_knee_joint0.02.443536.0
right_ankle_pitch_joint-0.78540.436322.0
right_ankle_roll_joint-0.34910.349122.0
躯干腰部waist_yaw_joint-1.57081.570836.0
waist_roll_joint-0.26180.261836.0

注意事项

  1. 多级越限保护:超出表中软件限位可能触发底层固件拦截,导致电机强制关断 。
  2. 量纲与坐标系:遵循右手法则,位置单位为 rad,力矩单位为 N·m。
  3. 边缘增益管理:接近限位时建议降低 stiffness (K_p) 增益以抑制物理震荡,实现平滑落位。
【Topic】关节控制 ​

功能描述

用于下发全身关节的控制目标值(位置、速度、力矩及 PD 增益)。

⚠️ 硬件安全警告:使用底层关节控制接口前,必须确保机器人进入低层运控开发者模式,且本体的高层运控模块处于关闭状态。若高层指令与底层伺服流发生指令冲突,可能会引发剧烈的物理震颤或不可预期的异常保护行为。 进入低层运控开发者模式的指令及模式说明可参考 快速入门指南 - 开发者模式说明。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/joint/command
  • 数据类型:aimdk_msgs/msg/JointCommandArray
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Publish (发布/写入控制)
  • CLI 调用:ros2 topic pub /aima/hal/joint/command aimdk_msgs/msg/JointCommandArray '{...}'
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:1000 Hz(打开二开模式后实际可能达不到1000Hz)

接口定义

  • 协议路径:aimdk_msgs/hal/msg/JointCommandArray.msg
msg
# ==========================================
# [话题载荷 Payload] 关节控制指令数组
# ==========================================
MessageHeader    header              # 消息头
JointCommand[]   joints              # 关节指令列表

JointCommandArray 协议定义

字段数据类型描述
headerMessageHeader消息头
jointsJointCommand[]关节指令列表

JointCommand 子结构定义

  • 协议路径:aimdk_msgs/hal/msg/JointCommand.msg
msg
# ==========================================
# [子结构] 关节控制指令结构体
# ==========================================
string           name                # 关节名称
float64          position            # 目标位置 (rad)
float64          velocity            # 目标速度 (rad/s)
float64          effort              # 目标力矩 (Nm)
float64          stiffness           # 刚度系数设置
float64          damping             # 阻尼系数设置

JointCommand 协议定义

字段数据类型描述
namestring关节名称
positionfloat64目标位置 (rad)
velocityfloat64目标速度 (rad/s)
effortfloat64目标力矩 (Nm)
stiffnessfloat64刚度系数设置 (K_p)
dampingfloat64阻尼系数设置 (K_d)

特别说明

  • 控制安全与指令幅值限制:
    1. 步进增量限制:单帧位置增量绝对值禁止超过 0.2 rad。大幅度突跳会导致扭矩过激,存在减速器崩齿或母线过流风险。
    2. 软关机离线逻辑:程序运行异常或正常退出前,必须发送一帧全量空指令(设置 stiffness: 0.0, damping: 5.0),使机器人平稳进入阻尼保护态,严禁直接断连指令流。
  • 寻址逻辑与数据完整性要求:
    1. 逻辑寻址机制:底层 HAL 仅通过 name 字段作为逻辑地址匹配电机。任何字段缺失或拼写错误都将导致对应子指令被静默丢弃。
    2. 全量下发策略:强烈建议每帧下发完整的全身关节数据包(Cohesion),确保整机姿态在每一个高频权重节拍内高度同步,防止局部肢体逻辑断点。
  • 频率特性与时序确定性保障:
    1. 确定性频率保障:建议稳定维持在 500Hz - 1000Hz 之间。若频率跌至 100Hz 以下,可能会触发硬件 Watchdog 安全保护并引发电机啸叫。
    2. 时钟单调性要求:header.stamp 必须源于机载系统时钟且严格单调递增。底层总线驱动会自动丢弃任何乱序或重复的时间戳数据包,以确保物理执行的时序一致性。

编程示例

【Topic】关节状态 ​

功能描述

实时回传机器人全身电机的运行状态、传感器读数及健康信息。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/joint/state
  • 数据类型:aimdk_msgs/msg/JointStateArray
  • 数据流向:Robot -> Outer (状态反馈)
  • 调用方式:Subscribe (订阅/读取反馈)
  • CLI 调用:ros2 topic echo /aima/hal/joint/state
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:500 Hz

接口定义

  • 协议路径:aimdk_msgs/hal/msg/JointStateArray.msg
msg
# ==========================================
# [话题载荷 Payload] 关节状态上报数组
# ==========================================
MessageHeader    header              # 消息头
JointState[]     joints              # 关节状态上报列表

JointStateArray 协议定义

字段数据类型是否必填描述
headerMessageHeader选填消息头
jointsJointState[]必填关节状态上报列表

JointState 子结构定义

  • 协议路径:aimdk_msgs/hal/msg/JointState.msg
msg
# ==========================================
# [子结构] 关节状态上报结构体
# ==========================================
string           name                # 关节名称
float64          position            # 当前位置反馈 (rad)
float64          velocity            # 当前速度反馈 (rad/s)
float64          effort              # 当前力矩反馈 (Nm)
int16            coil_temp           # 线圈温度 (℃)
int16            motor_temp          # 电机温度 (℃)
uint8            motor_vol           # 电机电压 (V)

JointState 协议定义

字段数据类型描述
namestring关节名称
positionfloat64当前位置 (rad)
velocityfloat64当前速度 (rad/s)
effortfloat64当前力矩 (Nm)
coil_tempint16线圈温度 (℃)
motor_tempint16电机温度 (℃)
motor_voluint8电机电压 (V)

特别说明

  • 全量反馈与逻辑寻址机制:
    1. 状态反馈完整性:每帧均会完整上报机器人全身上下所有电机的实时状态。
    2. 解析安全建议:列表顺序通常与 JointCommandArray 保持一致,但出于安全性与逻辑鲁棒性考量,解析时强制建议通过 name 字段执行键值匹配,以防止物理总线更新导致的列表乱序风险。

编程示例

2.2 交互控制功能 ​

介绍人机交互界面,包含音量配置、文本转语音(TTS)播报以及音频采集流面板接口。

核心功能

  • 音量与音频管理:支持查询和设置整机系统主音量百分比,及获取高频原始音频流数据。
  • 语音合成播报 (TTS):提供文本一键转音频播放接口,支持语音语义化指令交互通道。
  • 屏幕联动与表情管理:支持通过调用特定索引,一键播放对应内置表情动画(Emotion)及视频。

2.2.1 语音控制 ​

本模块提供基础语音交互控制,包含系统音量调整、TTS(文本转语音)合成播放及状态流获取。

2.2.1.1 音量控制 ​

【Service】获取音量 ​

功能描述

查询机器人当前扬声器的音量设定值。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/GetVolume
  • 数据类型:aimdk_msgs/srv/GetVolume
  • 数据流向:Robot -> Outer (状态/查询返回)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/GetVolume aimdk_msgs/srv/GetVolume '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/audio/srv/GetVolume.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest     request         # 请求头

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response        # 响应头
uint32            audio_volume    # 当前音量(0~100)

GetVolume 协议定义

字段数据类型描述
requestCommonRequest请求头
responseCommonResponse响应头
audio_volumeuint32当前音量(0~100)

特别说明

  • 状态独立性与逻辑关联:

    1. 与 Mute 状态独立:GetVolume 接口仅返回系统音量刻度,与静音状态完全独立。音量和静音互不联动,需分别通过 SetVolume 和 SetMute 控制。
    2. 发声确认基准:如需确认机器人当前是否真实发声,建议结合 GetMute 接口状态进行综合逻辑判断。
  • 音量类型枚举(VolumeType):

    枚举值数值说明
    SPEAKER_BUILT_IN0x00本体扬声器
    SPEAKER_BLUETOOTH0x20蓝牙音响
    MIC0x10麦克风

    注:VolumeType 用于区分不同音频设备的音量控制目标,可通过 VolumeChange 话题获取音量类型变化。

编程示例

【Service】设置音量 ​

功能描述

设定机器人扬声器的音量值。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetVolume
  • 数据类型:aimdk_msgs/srv/SetVolume
  • 数据流向:Outer -> Robot (控制命令/设置)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetVolume aimdk_msgs/srv/SetVolume '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/audio/srv/SetVolume.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request
uint32           audio_volume    # 请求音量(0~100)

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response
uint32            audio_volume    # 播放音量(0~100)

SetVolume 协议定义

字段数据类型描述
requestCommonRequest请求头
audio_volumeuint32请求音量(0~100)
responseCommonResponse响应头
audio_volumeuint32播放音量(0~100)

特别说明

  • 音量数值边界保护机制:
    1. 参数自动截断:若请求值超出有效范围(如 > 100),系统会自动将其强制截断至 100 并返回成功,而非抛出错误。开发者无需在应用层执行严格的数值预校验。
  • 配置持久化与重启恢复逻辑:
    1. 持久化存储:该接口的操作是永久性的。最新的音量设定会自动写入系统内部配置文件。
    2. 冷启动自动加载:即使机器人执行冷重启,底层音频模块也会在初始化时自动加载上次设定的音量,确保持续的交互体验。

编程示例

【Service】获取静音状态 ​

功能描述

查询机器人当前是否处于静音输出状态。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/GetMute
  • 数据类型:aimdk_msgs/srv/GetMute
  • 数据流向:Robot -> Outer (状态/查询返回)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/GetMute aimdk_msgs/srv/GetMute '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/audio/srv/GetMute.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response
bool              is_mute     # 当前静音状态

GetMute 协议定义

字段数据类型描述
requestCommonRequest请求头
responseCommonResponse响应头
is_mutebool是否处于静音状态 (true: 已静音;false: 非静音)

特别说明

  • 音量数值与 Mute 状态的并行逻辑:
    1. 状态并行解耦:静音状态与音量值完全独立运行。机器人可以同时处于 is_mute: true 且 audio_volume: 50。两者互不联动,需分别通过 SetVolume 和 SetMute 控制。
  • 底层物理保障与状态持久化:
    1. 硬件级静音效果:在 is_mute: true 时,底层音频功放将通过物理闭环彻底屏蔽输出,确保完全零底噪输出。
    2. 配置持久化:静音状态同样会被同步至系统配置路径下。即使机器人冷重启,初始化时也会自动恢复上次设定的静音状态。

编程示例

【Service】设置静音 ​

功能描述

切换机器人扬声器的静音模式(开启或关闭)。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetMute
  • 数据类型:aimdk_msgs/srv/SetMute
  • 数据流向:Outer -> Robot (控制命令/设置)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetMute aimdk_msgs/srv/SetMute '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/audio/srv/SetMute.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request
bool             is_mute    # 请求静音状态 | true(mute) | false(unmute)

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response
bool              is_mute     # 当前静音状态

SetMute 协议定义

字段数据类型描述
requestCommonRequest请求头
is_mutebool请求静音状态
responseCommonResponse响应头
is_mutebool当前静音状态

特别说明

  • 瞬时控制优先级与静音效应:
    1. 全局瞬时静默:该接口具有系统级高优先级。一旦设为 true,全系统内所有媒体音频、语音播报及提示音将立即进入静默状态(物理功放关断)。
  • 配置持久化与重启一致性:
    1. 状态持久化保存:该接口的操作是持久化的。系统会自动将最新状态写入配置文件,并确保机器人在冷重启后依然能保持设定的静音模式。
  • 输出控制与静音独立性:
    1. 音量与静音独立控制:音量(SetVolume)与静音(SetMute)互不联动,需分别调用。取消静音后音量值保持不变,不会自动恢复或调整。
    2. 输出端专属控制:该接口仅针对扬声器输出侧(Speaker),静音操作不会对麦克风输入或语音识别(ASR)模块产生任何影响。

编程示例

2.2.1.2 语音合成 ​

【Service】语音合成 ​

功能描述

请求机器人合成并播放一段指定的文本语音(Text-To-Speech)。

网络依赖说明:无网络(离线)情况下,本接口无法播放本地未缓存的新文本 TTS 语音。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/PlayTts
  • 数据类型:aimdk_msgs/srv/PlayTts
  • 数据流向:Outer -> Robot (控制命令/触发播报)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/PlayTts aimdk_msgs/srv/PlayTts '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/interaction/srv/PlayTts.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest     header
PlayTtsRequest    tts_req

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse     header
PlayTtsResponse    tts_resp

PlayTts 协议定义

字段数据类型描述
headerCommonRequest
tts_reqPlayTtsRequest
headerCommonResponse响应头 (与 request.header 配对使用)
tts_respPlayTtsResponse播放响应回执数据

PlayTtsRequest 子结构定义

字段名 (name)数据类型描述
textstring需要合成并播放的文本内容 (建议 100 字以内)
priority_levelTtsPriorityLevel播报主优先级等级(默认建议 INTERACTION_L6)
priority_weightuint32优先级加权微调参数 (0-99),用于同级内排序
domainstring标识调用方来源(用于系统资源隔离与日志审计)
trace_idstring用于追踪单次播放请求的全局唯一 ID
is_interruptedbool是否打断现有任务 (true: 立即抢占;false: 自动排队)

PlayTtsResponse 子结构定义

字段名 (name)数据类型描述
textstring本次处理的原始文本内容
priority_levelTtsPriorityLevel任务实际被分配的主优先级等级
priority_weightuint32任务实际被分配的子加权偏差值
domainstring任务所属的业务领域标识
trace_idstring任务追踪 ID
is_successbool播报请求是否成功进入底层调度队列
error_messagestring请求失败(即 is_success: false)时的具体原因描述
estimated_durationuint32预计播报时长 (ms)。注:当前版本下由于流式合成而固定返回 0

特别说明

  • 异步触发与非阻塞特性:
    1. 播报非阻塞:PlayTts 属于异步调度服务。Service 返回 is_success: true 仅代表播报请求已进入调度队列,不代表语音已播报完毕。
  • 播报状态同步与闭环建议:
    1. 时长字段局限:由于 TTS 采用云端/本地流式合成,当前版本下 estimated_duration 固定返回 0。
    2. 任务闭环建议:系统暂未开放播报结束的话题通知。若业务逻辑需在语音播报后执行(如先说话后走动),建议通过字数预估(约 200ms/字)进行延时处理。
  • 任务优先级与仲裁策略:
    1. 复合权重计算机制 (priority_level + priority_weight): 系统通过 主优先级 与 子加权 合成计算最终权重(最终权重 = 主级 * 100 + 子权),数值越大则播放优先级越高。
      • TtsPriorityLevel (推荐主级常量列表):
        常量名 (Enum)数值 (Value)典型应用场景
        BACKGROUND_L11后台低频日志、非交互式背景提醒
        SERVICE_L22定时任务通知、设备状态常规汇报
        MISSION_L44运控任务关键节点播报(如“开始清扫”)
        INTERACTION_L66(推荐默认) 语音唤醒响应、实时交互首句
        WARNING_L88危险预警(如“避障受阻”、“传感器遮挡”)
        SAFETY_L1010(最高) 生命安全警报、紧急紧急告知
      • priority_weight (子级微调范围):0 - 99。当主级常量相同时,系统将根据子权数值进行二次排序调优(如 L6 + 10 优于 L6 + 0 播报)。
    2. 仲裁决策逻辑 (Arbitration Matrix):
      权重对比is_interrupted: true (抢占模式)is_interrupted: false (非抢占模式)
      新任务权重 >= 当前任务当前播报内容将被立即掐断(且不可恢复),新语音开始播放。仲裁优先级相同时,新任务会存入缓冲区,在当前任务播放完成后再进行新任务处理。新任务仲裁优先级大于当前任务时,强制打断当前播放任务,播放新的tts。
      新任务权重 < 当前任务请求丢弃:该请求将被直接丢弃,接口返回 is_success: false。请求丢弃:该请求将被直接丢弃,接口返回 is_success: false。
  • 系统性能与响应调优:
    1. 文本长度建议:单次播报文本建议控制在 100 字以内。由于流式合成的首包首句加载延迟,文本过长会增加初始响应时间。
  • 文本内容:TTS 对播报文本的字符类型无特殊限制,支持中英文、标点、特殊符号等。仅需注意 CLI 调用时的引号嵌套规范(见下方)。
  • CLI 调用引号规范:
    1. 引号嵌套风险:在 bash 中执行 CLI 命令时,若外层与内层使用同一种引号,内层引号会提前截断外层引号,导致字段值被截断或解析错误。
    2. 正确写法:外层与内层引号必须不同(外单内双 或 外双内单均可)。例如:
      bash
      # ✅ 外单内双
      ros2 service call /aimdk_5Fmsgs/srv/PlayTts aimdk_msgs/srv/PlayTts '{header: {}, tts_req: {text: "你好,世界!", priority_level: {value: 6}, priority_weight: 0, domain: "test", trace_id: "001", is_interrupted: true}}'
      
      # ✅ 外双内单
      ros2 service call /aimdk_5Fmsgs/srv/PlayTts aimdk_msgs/srv/PlayTts "{header: {}, tts_req: {text: '你好,世界!', priority_level: {value: 6}, priority_weight: 0, domain: 'test', trace_id: '001', is_interrupted: true}}"

编程示例

2.2.1.3 音频文件播放 ​

【Service】音频文件播放 ​

功能描述

该接口用于播放存储在机器人本地文件系统中的音频文件(如提示音、警报声、预录制语音等)。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/PlayAudioFile
  • 数据类型:aimdk_msgs/srv/PlayAudioFile
  • 数据流向:Outer -> Robot (控制命令/触发播放)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/PlayAudioFile aimdk_msgs/srv/PlayAudioFile "{request: {header: {stamp: {sec: 0, nanosec: 0}}}, file: {pkg_name: 'sdk_demo', file_name: '小星星.wav', file_path: '/robot/software/aimrt_agent/bin/cfg/q1/audio', info: {channels: 1, sample_rate: 24000, size: 0, sample_format: 'S16_LE', coding_format: 'wave'}, priority: 6, priority_weight: 0, media_role: 'Music'}}"
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/audio/srv/PlayAudioFile.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request
AudioFile        file       # 文件信息

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response

PlayAudioFile 协议定义

字段数据类型描述
requestCommonRequest请求头
fileAudioFile文件信息
responseCommonResponse响应头

特别说明

  • 音频格式与兼容性建议:
    1. 格式依赖:
      • WAV 文件:系统会自动读取 RIFF 文件头。开发者一般无需手动填写 AudioInfo。
  • 资源路径与加载性能:
    1. 路径推荐:建议在 file_path 中指定音频文件的 绝对路径。
    2. 响应时延优化:为了保证交互的即时性,建议所有的提示音文件(Assets)均控制在 1MB 以内。文件过大会导致 I/O 加载耗时增加,语音响应存在人耳可感知的延迟。
  • 仲裁优先级(暂不支持):
    1. priority 与 priority_weight 字段已预留定义,但当前版本暂未实现仲裁优先级功能。填写这两个字段不会产生优先级抢占或排队等效果,系统将按接收顺序依次播放音频文件。

编程示例

2.2.1.4 停止音频播放 ​

【Service】停止音频播放 ​

功能描述

该接口用于停止机器人当前正在播放的音频。仅对通过 PlayAudioFile 服务播放的音频有效,不影响 TCP 音频播放(play_audio_from_pc)。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/StopAudioPlay
  • 数据类型:aimdk_msgs/srv/StopAudioPlay
  • 数据流向:Outer -> Robot (控制命令/触发停止)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/StopAudioPlay aimdk_msgs/srv/StopAudioPlay "{request: {header: {stamp: {sec: 0, nanosec: 0}}}}"
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/srv/StopAudioPlay.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response

StopAudioPlay 协议定义

字段数据类型描述
requestCommonRequest请求头
responseCommonResponse响应头

特别说明

  • 使用场景:
    1. 配对使用:该接口与 PlayAudioFile 服务配对使用,用于提前终止正在播放的音频文件。
    2. 全局停止:调用该接口会停止所有当前活跃的音频播放会话,而非仅停止特定音频。
  • 响应码:
    1. code = 0:成功停止音频播放(包括无音频播放时的成功响应)。
    2. code != 0:停止失败,请检查音频管理服务状态。

编程示例

2.2.1.5 TCP音频播放 ​

【TCP】音频播放 ​

功能描述

通过 PulseAudio TCP 协议(module-simple-protocol-tcp)将音频数据流式发送到机器人扬声器播放。支持 WAV 文件(自动检测 RIFF 头并转换)和 PCM 文件(48kHz mono S16LE 直接传输)。示例脚本会自动通过 SSH 在机器人端加载 TCP 播放模块(先检查是否已加载,已加载则跳过)。

接口元数据

  • 协议类型:TCP Socket(PulseAudio simple-protocol-tcp)
  • 连接端口:6001
  • 数据格式:48kHz,单声道(mono),16-bit PCM(S16LE)
  • 数据流向:Outer -> Robot(TCP 流式传输)
  • 前置条件:示例脚本会自动通过 SSH 在机器人端加载 module-simple-protocol-tcp 模块

连接参数

参数值描述
端口6001TCP 监听端口
格式s16le16-bit 小端有符号整数
采样率4800048kHz
声道数1单声道

特别说明

  • WAV 文件支持:自动检测 RIFF 头,解析采样率、声道数等信息,并转换为 48kHz mono S16LE 格式。多声道 WAV 会进行智能混音(识别活跃通道,避免静音通道稀释信号)。非 48kHz 采样率会自动重采样。
  • 流式传输:以 100ms 为单位分块发送音频数据,通过精确定时补偿网络延迟,确保流畅播放。
  • PCM 文件:直接传输,假设格式为 48kHz mono S16LE。
  • 在机器人上直接运行:若通过 SSH 登录到机器人板子执行示例脚本,IP 参数使用 127.0.0.1 即可,无需使用机器人的外部网络 IP。

示例脚本使用方法

Python 示例(examples/python/play_audio_from_pc.py):

bash
# 基本用法
python3 examples/python/play_audio_from_pc.py <机器人IP> <音频文件>

# 播放本地 WAV 文件
python3 examples/python/play_audio_from_pc.py <机器人IP> mic_mono.wav

# 使用 SSH 密钥(机器人需要密钥登录)
python3 examples/python/play_audio_from_pc.py -i ./<机器人SN>_soc0/id_ed25519 <机器人IP> mic_mono.wav

C++ 示例(examples/cpp/src/play_audio_from_pc.cpp,编译后运行):

bash
# 基本用法
ros2 run aimdk_examples_cpp play_audio_from_pc <机器人IP> <音频文件>

# 播放本地 WAV 文件
ros2 run aimdk_examples_cpp play_audio_from_pc <机器人IP> mic_mono.wav

# 使用 SSH 密钥(机器人需要密钥登录)
ros2 run aimdk_examples_cpp play_audio_from_pc -i ./<机器人SN>_soc0/id_ed25519 <机器人IP> mic_mono.wav

前置条件:需先满足 Cpp代码运行前置条件

SSH 密钥权限说明:使用 -i SSH_KEY 参数时,密钥目录通常以 root 权限解压,需要修改为当前用户所有:

bash
sudo chown -R $USER:$USER ./<机器人SN>_soc0/
chmod 600 ./<机器人SN>_soc0/id_ed25519

其中 <机器人SN>_soc0 为密钥目录名称,每台机器人的目录名称不同。

支持的音频格式:

  • WAV 文件:自动检测 RIFF 头,转换为 48kHz mono S16LE
  • PCM 文件:48kHz mono S16LE,直接传输

输出示例:

检测到 WAV 文件,正在转换...
WAV 格式: 44100Hz, 2ch, 16bit, 220500帧 (5.0秒)
混音: 2 声道 -> 单声道 (活跃通道: ch1, ch2)
各声道峰值: ch1=28456 ch2=28456
重采样: 44100Hz -> 48000Hz
转换完成: 480000 字节 (5.0 秒)
已连接 <机器人IP>:6001,播放 mic_mono.wav ...
已播放 5.0 / 5.0 秒
播放结束

编程示例

2.2.1.6 TCP音频录制 ​

【TCP】音频录制 ​

功能描述

从机器人麦克风阵列录制多声道音频。支持两种传输模式:

  • 本机模式(在机器人上直接运行):通过 PulseAudio unix socket(共享内存)传输音频,效率更高。
  • 远程模式(在 PC 端运行):通过 PulseAudio TCP 协议(module-native-protocol-tcp)传输音频。示例脚本会自动通过 SSH 在机器人端加载 TCP 录音模块。

录制格式取决于当前连接的麦克风类型:

💡 提示:8声道格式仅适用于机器人内置麦克风阵列(aw89403)。若通过 USB 接口连接外置麦克风,录音格式会自动切换为 2声道 48kHz S24LE(24-bit)。示例脚本会自动检测并适配。

  • 内置麦(麦克风阵列 aw89403):8声道 48kHz S16LE
  • 外置麦(USB 麦克风):2声道 48kHz S24LE(24-bit)

接口元数据

  • 协议类型:PulseAudio unix socket(本机)或 TCP Socket(远程,native-protocol-tcp)
  • 连接端口:4713(仅远程模式)
  • 数据格式:48kHz,8声道 16-bit PCM(S16LE,内置麦)或 2声道 24-bit PCM(S24LE,外置麦)
  • 数据流向:Robot -> Outer
  • 采集工具:parec(PulseAudio 命令行录音工具)
  • 前置条件:远程模式需加载 module-native-protocol-tcp 模块(脚本自动处理);本机已安装 pulseaudio-utils

连接参数(内置麦)

参数值描述
端口4713PulseAudio native 协议 TCP 端口(仅远程模式)
设备alsa_input.platform-aw89403_sound.pro-input-0机器人内置麦克风阵列设备名
格式s16le16-bit 小端有符号整数
采样率4800048kHz
声道数88声道(回采 + 麦克)

声道说明(内置麦 8声道)

声道类型
ch1-2回采(扬声器播放时才有数据)
ch3-8麦克风

模式自动检测

示例脚本根据运行环境自动选择传输模式:

条件模式传输方式
在机器人上直接运行(IP 为 127.0.0.1 / localhost)本机模式PulseAudio unix socket(共享内存)
其他 IP远程模式PulseAudio TCP(端口 4713)

录音命令示例

bash
# 远程模式(PC 端运行)
PULSE_SERVER=tcp:<机器人IP>:4713 parec \
  --channels 8 --rate 48000 --format s16le \
  --device alsa_input.platform-aw89403_sound.pro-input-0 \
  --channel-map aux0,aux1,aux2,aux3,aux4,aux5,aux6,aux7 \
  > raw_8ch.pcm

# 本机模式(机器人上运行)
PULSE_SERVER=unix:/run/user/1000/pulse/native parec \
  --channels 8 --rate 48000 --format s16le \
  --device alsa_input.platform-aw89403_sound.pro-input-0 \
  --channel-map aux0,aux1,aux2,aux3,aux4,aux5,aux6,aux7 \
  > raw_8ch.pcm

parec 输出为原始 PCM 数据,必须重定向到文件,否则会直接输出到终端。录音按 Ctrl+C 停止。

特别说明

  • 回采通道(ch1-2)需要扬声器播放:ch1-2 是扬声器回采通道(echo),仅当扬声器正在播放音频时才会有有效数据。若扬声器未播放任何声音,这两个通道录到的是静音(零值)。如需测试回采通道,请先通过 play_audio_from_file 或 play_audio_from_pc 播放音频,同时录音。
  • 原始多声道数据:输出完整 8 声道 PCM 数据,不内置 VAD 或 ASR。开发者需自行处理通道分离和语音端点检测。
  • 推荐通道:ch5-6 为主要拾音通道,建议提取这两个通道进行混音后使用。示例代码中会提取 ch5-6 混合为单声道并放大 10 倍。
  • 本机依赖:需安装 pulseaudio-utils(sudo apt install pulseaudio-utils)。
  • 在机器人上直接运行:若通过 SSH 登录到机器人板子执行示例脚本,IP 参数使用 127.0.0.1 即可,自动使用共享内存传输(效率更高)。

示例脚本使用方法

Python 示例(examples/python/record_audio.py):

bash
# 基本用法(默认录音 5 秒)
python3 examples/python/record_audio.py <机器人IP>

# 指定录音时长(如 10 秒)
python3 examples/python/record_audio.py <机器人IP> 10

# 使用 SSH 密钥(机器人需要密钥登录)
python3 examples/python/record_audio.py -i ./<机器人SN>_soc0/id_ed25519 <机器人IP> 10

C++ 示例(examples/cpp/src/record_audio.cpp,编译后运行):

bash
# 基本用法(默认录音 5 秒)
ros2 run aimdk_examples_cpp record_audio <机器人IP>

# 指定录音时长(如 10 秒)
ros2 run aimdk_examples_cpp record_audio <机器人IP> 10

# 使用 SSH 密钥(机器人需要密钥登录)
ros2 run aimdk_examples_cpp record_audio -i ./<机器人SN>_soc0/id_ed25519 <机器人IP> 10

前置条件:需先满足 Cpp代码运行前置条件

SSH 密钥权限说明:使用 -i SSH_KEY 参数时,密钥目录通常以 root 权限解压,需要修改为当前用户所有:

bash
sudo chown -R $USER:$USER ./<机器人SN>_soc0/
chmod 600 ./<机器人SN>_soc0/id_ed25519

其中 <机器人SN>_soc0 为密钥目录名称,每台机器人的目录名称不同。

输出文件:

  • raw_8ch.wav:完整 8 声道原始录音数据
    • 用途:原始数据分析、自定义通道提取、算法开发
    • 注意:不可直接播放(多数播放器不支持 8 声道),可用 Audacity 等专业工具查看各通道波形
    • 包含通道:ch1-2 回采、ch3-8 麦克
  • mic_mono.wav:从 ch5-6 麦克通道提取并混合放大的单声道录音(10 倍放大)
    • 用途:直接播放试听、语音识别、语音处理
    • 播放方式:paplay mic_mono.wav 或通过 play_audio_from_pc 示例在机器人扬声器播放

输出示例:

检测到远程环境,使用 TCP 传输
已在机器人端加载录音模块 (端口 4713)
远程模式(TCP: <机器人IP>:4713),录音 5 秒...
录音中 5.0 / 5 秒  (已接收 5.0 秒)
录音 3840000 字节 (5.0 秒)
分析中...

各通道音量:
  通道 1: 平均  123.4  峰值  5678  有声
  通道 2: 平均  118.2  峰值  5432  有声
  通道 3: 平均  456.7  峰值 12345  有声
  通道 4: 平均  432.1  峰值 11234  有声
  通道 5: 平均 1234.5  峰值 28456  有声
  通道 6: 平均 1201.3  峰值 27890  有声
  通道 7: 平均  345.6  峰值  9876  有声
  通道 8: 平均  321.0  峰值  9012  有声

保存: raw_8ch.wav, mic_mono.wav
播放: paplay mic_mono.wav

编程示例

2.2.1.7 音频设备列表 ​

【Topic】音频设备列表 ​

功能描述

该话题周期性发布机器人当前的音频输入/输出设备列表。开发者可通过订阅此话题查询可用的麦克风(输入)和扬声器(输出)设备,包括内置音频设备和蓝牙设备,以及各设备的选中状态。适用于构建音频设备管理界面、蓝牙音频设备切换等场景。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/audio/audio_device_list
  • 数据类型:aimdk_msgs/msg/AudioDeviceInfoList
  • 数据流向:Robot -> Outer (反馈)
  • 调用方式:Subscribe
  • CLI 调用:ros2 topic echo /aima/hal/audio/audio_device_list
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:1 Hz

接口定义

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioDeviceInfoList.msg
msg
# ==========================================
# [话题载荷 Payload] 音频设备列表
# ==========================================

# 音频输入设备列表(麦克风)
AudioDeviceInfo[] input_list

# 音频输出设备列表(扬声器)
AudioDeviceInfo[] output_list
  • 协议路径:aimdk_msgs/hal/audio/msg/AudioDeviceInfo.msg
msg
# ==========================================
# 一块音频设备的信息
# ==========================================

# 设备索引号
int32 id              # -1: auto mode

# 设备标志符
string device_addr    # builtin_mic builtin_speaker

# 设备类型
string device_type    # builtin bluetooth

# 设备名称
string device_name    # snd_card_name bluetooth

# 是否处于选中状态
bool is_sel

AudioDeviceInfo 协议定义

字段数据类型描述
idint32设备索引号
device_addrstring设备标志符(如 builtin_mic、builtin_speaker)
device_typestring设备类型(builtin 内置、bluetooth 蓝牙)
device_namestring设备名称
is_selbool是否处于选中状态(当前正在使用的设备)

AudioDeviceInfoList 协议定义

字段数据类型描述
input_listAudioDeviceInfo[]音频输入设备列表(麦克风)
output_listAudioDeviceInfo[]音频输出设备列表(扬声器)

使用说明

  1. 设备 ID 规则:id 为 0 的设备始终是内置音频设备(builtin)。外部接入的设备(如蓝牙)从 id=1 开始依次递增分配,但 ID 是动态分配的——每次接入的顺序可能不同,同一个外部设备的 ID 在重新连接后可能会变化。因此不应将 id 值作为设备的持久标识,应使用 device_addr 来识别特定设备。
  2. 设备类型识别:通过 device_type 字段区分内置音频设备(builtin)和外部设备(如 bluetooth),便于在 UI 上分类展示。
  3. 当前选中设备:is_sel 为 true 的设备是当前正在使用的音频设备,同一列表中通常只有一个设备被选中。

编程示例

2.2.1.8 语音识别 ​

【Topic】语音识别结果 ​

功能描述

该话题发布机器人当前的 ASR(自动语音识别)转写结果。每当机器人端检测到语音输入并产生识别文本时,会发布中间结果(is_final=false)和最终结果(is_final=true)。开发者可通过订阅此话题获取语音转文本的实时结果,用于语音指令处理、对话交互等场景。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/agent/asr_result
  • 数据类型:aimdk_msgs/msg/AsrResult
  • 数据流向:Robot -> Outer (反馈)
  • 调用方式:Subscribe
  • CLI 调用:ros2 topic echo /aima/agent/asr_result
  • QoS:Best Effort / Volatile / Depth=10

接口定义

  • 协议路径:aimdk_msgs/agent/msg/AsrResult.msg
msg
# topic: /aima/agent/asr_result
MessageHeader header
# 识别文本
string text
# 事件ID,用于关联对话上下文
string event_id
# 是否为最终结果(false 表示中间/部分结果)
bool is_final
# 置信度 [0.0, 1.0]
float32 confidence
# 语言标签,如 "zh"、"en"
string language

协议定义

字段数据类型描述
headerMessageHeader消息头
textstring识别文本
event_idstring事件ID,用于关联对话上下文
is_finalbool是否为最终结果(false 表示中间/部分结果)
confidencefloat32置信度 [0.0, 1.0]
languagestring语言标签,如 zh、en

使用说明

  1. 中间结果与最终结果:is_final=false 表示当前为中间/部分识别结果,文本可能随后续语音输入变化;is_final=true 表示本轮识别已完成,文本为最终结果。
  2. 上下文关联:通过 event_id 字段可将多次 ASR 结果关联到同一次对话交互中。
  3. 置信度参考:confidence 字段提供识别置信度(0.0~1.0),可用于过滤低置信度的识别结果。

编程示例

2.2.2 屏幕控制 ​

本模块提供屏幕表情内容与联动管控,支持通过特定索引触发调用播放机器人表情动画。

2.2.2.1 表情与视频管理 ​

【Service】播放表情和视频 ​

功能描述

播放指定的机器人静态表情、动态表情序列或视频文件。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/PlayEmotion
  • 数据类型:aimdk_msgs/srv/PlayEmotion
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/PlayEmotion aimdk_msgs/srv/PlayEmotion '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/interaction/srv/PlayEmotion.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    header
string           type           # play type, "emotion", "file" or "image"
int32[]          emotion_ids    # 播放的机器人内置表情id
string[]         file_paths     # 视频路径;type=image 时传一个设备本地绝对路径或 HTTP/HTTPS 图片 URL,持续显示
int32            priority       # 优先级,系统表情默认优先级是0,数字越大优先级越高,低优先级无法打断高优先级,高优先级会打断低优先级;
int32            loop_count     # 整体配置的循环播放次数,大于0则播放具体次数。小于等于0,则表示循环播放 。默认值为1,表示播放一次

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    header

PlayEmotion 协议定义

字段数据类型描述
headerCommonRequest请求头
typestring播放类型 ("emotion"、"file" 或 "image")
emotion_idsint32[]播放的机器人内置表情id数组
file_pathsstring[]视频路径;type=image 时传一个设备本地绝对路径或 HTTP/HTTPS 图片 URL,持续显示
priorityint32播放优先级,系统表情默认优先级是0,数字越大优先级越高
loop_countint32循环播放次数 (<=0 为无限循环)
headerCommonResponse响应头

Q1机型 的 Emotion 枚举列表:

Emotion ID描述
3001平静
3002耍酷
3003开心
3004好奇
3005困惑
3006调皮
3007崇拜
3008撒娇
3009困倦
3010眨眼表情
3011闭眼
3012左右环顾
3013好奇-2
3014沮丧
3015害羞
3016生气
3017无语
3018难过
3019震惊
3020睁眼
3021断网
3022空表情
3023静音/声音为0
3025思考态
3026聆听态
3027说话态
3028低电量(30%)
3029极低电量(5%)
3030充电中
3035识别扫描
3036拍照录像
3045QQ音乐听歌
3046喜马拉雅听书

特别说明

  • 文件格式要求:格式支持与 type 字段相关,其他格式类型暂未开放。
    • type = "file":仅支持 mp4 格式的视频文件。
    • type = "image":支持 jpg、png、webp、bmp 格式的图片文件。
    • 推荐分辨率为 800×480(与屏幕分辨率一致),其他分辨率会被缩放,可能出现画面变形或黑边。
  • 播放模式切换:type 字段决定了系统解析数据的逻辑。若为 "emotion",系统将从预置表情库中查找 emotion_ids;若为 "file",则解析 file_paths 中的多媒体文件;若为 "image",则解析 file_paths 中的图片路径或 URL 并持续显示。如下情况需要特别注意:
    1. emotion_ids 只能从内置表情库选择,不支持自定义。
    2. file_paths 必须使用绝对路径(type=image 时也支持 HTTP/HTTPS URL)。
    3. type 字段是必填项,必须为 "emotion"、"file" 或 "image"。如果 type 为空或其他,即使 emotion_ids 或 file_paths 已填充,服务会在请求解析阶段返回 FAILURE,表情不会播放。
  • 循环与终止:loop_count 控制整体播放的循环次数。
    • loop_count > 0:按指定次数重复播放(例如 loop_count = 3 表示播放三遍后自动结束)。
    • loop_count = 1:默认值,播放一次后结束。
    • loop_count <= 0:表示无限循环,表情或视频将持续播放,直至收到新的 PlayEmotion 请求或系统重启。
    • loop_count 字段在 type = "image" 时不生效。

编程示例

2.2.3 系统控制 ​

本模块提供系统级状态迁移控制能力,支持对机器人执行重启或关机操作。

2.2.3.1 系统状态迁移 ​

【Service】系统状态迁移 ​
  • 接口名称:/aimdk_5Fmsgs/srv/MigrateSystemState

  • 数据类型:aimdk_msgs/srv/MigrateSystemState

  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/MigrateSystemState aimdk_msgs/srv/MigrateSystemState "{header: {header: {stamp: {sec: 0, nanosec: 0}}}, state: 'Reboot'}"

请求参数

字段名类型说明
headerCommonRequest请求头
statestring请求切换的系统状态。可选值:"Reboot"(重启)、"Shutdown"(关机)

响应参数

字段名类型说明
headerCommonResponse响应头

注意事项

  • 权限要求:调用此接口前,请确保已获取系统管理权限。重启和关机操作会影响机器人当前运行状态。
  • 安全提示:执行关机操作前,请确保机器人处于安全状态(如坐姿或躺姿),避免关机后摔倒造成损坏。
  • 重启操作:state = "Reboot" 将触发机器人系统重启,重启后恢复正常运行状态。
  • 关机操作:state = "Shutdown" 将触发机器人系统关机,需手动重新启动。

编程示例

2.3 硬件抽象功能 ​

介绍底层感知与物理能耗数据,提供触觉状态面板、电池能耗看板及 LED 灯带语义化样式控制。

核心功能

  • 底层传感状态读取:支持高频刷新和读取触觉传感器、皮肤节点的实效触摸触发信号。
  • 电源状态监控看板:提供电池主电量、温度、健康度及充放电状态的实时能耗看板查询。
  • 灯带样式语义化控制:提供 LED 灯效果流转模式管理,支持彩虹、渐变、爆闪等视觉交互渲染。

2.3.1 触觉传感器 ​

2.3.1.1 触觉传感器状态 ​

本模块提供触摸传感器的状态读取接口,支持精确检测多路皮肤节点的外界触摸触发状态。

【Topic】头部触摸状态 ​

功能描述

该话题用于实时上报机器人头部触摸传感器的状态,包括触摸传感器的触发状态(触发或未触发)。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/touch/state
  • 数据类型:aimdk_msgs/msg/TouchState
  • 数据流向:Robot -> Outer (状态反馈)
  • 调用方式:Subscribe (订阅/读取反馈)
  • CLI 调用:ros2 topic echo /aima/hal/touch/state
  • QoS:Reliable / Volatile / Depth=1
  • 频率:触发式上报

接口定义

  • 协议路径:aimdk_msgs/hal/msg/TouchState.msg
msg
# ==========================================
# [话题载荷 Payload] 机器人触摸传感器状态
# ==========================================
MessageHeader    header                         # 消息头信息
uint8            sensor_id                      # 触摸传感器 ID(Q系列:1=头部)
uint8            event_type                     # 触摸事件类型

# --- 触摸事件类型常量定义 ---
uint8            TOUCH_EVENT_SINGLE_CLICK = 1   # 单击

TouchState 协议定义

字段数据类型描述
headerMessageHeader消息头信息
sensor_iduint8触摸传感器 ID(Q系列:1=头部)
event_typeuint8触摸事件类型

Q1机型 的触摸事件类型枚举列表:

常量名数值描述
TOUCH_EVENT_SINGLE_CLICK1单击

特别说明

  • 触摸事件为触发式上报,仅在状态变化时发送,未检测到触摸时不产生消息。
  • 触摸状态仅有触发(TOUCH_EVENT_SINGLE_CLICK)和未触发两种状态。
  • Q1机型:sensor_id为1表示头部传感器。
  • 建议开发者对 header.stamp 做时间戳校验:触摸事件基于物理触发生成,在系统负载较高或通信链路抖动时可能出现事件滞后到达的情况。建议在接收到触摸消息后,将 header.stamp 中的时间戳与当前系统时间进行比较,若差值超过业务可接受的阈值(如 500ms),则应丢弃该次触摸事件,避免因滞后触发的动作与用户预期不符。

编程示例

2.3.2 视觉传感器 ​

2.3.2.1 视觉采集管理 ​

本模块提供各类视觉传感数据的采集与流转管控接口,支持多类型视觉传感器的数据获取。开发者可依据不同的 camera_id 获取对应相机的图像数据。

Q1机型 支持的视觉传感器列表如下:

相机名称camera_id
交互相机head_monocular_centra
【Service】获取相机单帧图像 ​

功能描述

该服务用于捕获相机单帧 JPEG 图像并返回 JPEG 数据,支持可选的超时时间以控制等待新帧的最长时长。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aima/hal/camera/CaptureJpegImage
  • 数据类型:aimdk_msgs/srv/CaptureJpegImage
  • 数据流向:Robot -> Outer (数据流/视频图像)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aima/hal/camera/CaptureJpegImage aimdk_msgs/srv/CaptureJpegImage '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/camera/srv/CaptureJpegImage.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request
string           camera_id     
uint32           timeout_ms    # 可选项,等待新帧的超时时间,单位 ms;为 0 时使用服务端默认值

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse    response
JpegImage         jpeg        # JPEG 图片数据

CaptureJpegImage 协议定义

字段数据类型描述
requestCommonRequest请求头
camera_idstring摄像头ID
timeout_msuint32可选项,等待新帧的超时时间,单位 ms;为 0 时使用服务端默认值
responseCommonResponse响应头
jpegJpegImageJPEG 图片数据包装体

接口返回值说明

获取单帧图片成功时,返回数据包含以下关键信息:

字段数据类型说明
jpeg.camera_idstring实际返回图像的相机 ID
jpeg.devicestring设备节点路径
jpeg.widthuint32图像宽度(像素)
jpeg.heightuint32图像高度(像素)
jpeg.framerateuint32帧率(fps)
jpeg.exposureuint32曝光值
jpeg.gainuint32模拟增益
jpeg.image.datauint8[]JPEG 图像二进制数据
jpeg.image.formatstring图像格式(通常为 "jpeg")

特别说明

  • 图像抓取:该服务为一次性抓取相机当前帧的 JPEG 图像,返回值位于响应的 jpeg 字段,类型为 JpegImage,包含相机 ID、设备名称、分辨率、帧率、曝光值、模拟增益以及 sensor_msgs/CompressedImage image(JPEG 数据)。
  • 超时设置:timeout_ms 参数用于控制等待新帧的最长时长,若在指定时间内未获取到新帧,服务返回错误;设置为 0 时使用系统默认超时时间(1000 ms)。
  • 文件大小及传输:
    • 返回的 JPEG 大小随分辨率与压缩率而变,常见分辨率下大小约为 50 KB ~ 1.5 MB。
    • 对应的业务端全链路响应时延约 100‑500 ms(受相机帧率、硬件编码及网络链路影响)。如需精确性能指标,请读取 image.data 长度并结合调用耗时进行统计。
  • 取帧频率限制:该服务为触发式 Service Call(非 Topic 流),需等待单次响应完成后方可发起下一次调用。受全链路响应时延(100~500 ms)限制,建议取帧频率为 1 fps,超过此频率可能响应超时。如需更高帧率的连续图像数据,请使用 RTSP 视频流服务。

编程示例

【RTSP】相机视频流 ​

功能描述

  • 该服务提供相机实时视频流的 RTSP 地址,客户端可通过 RTSP 协议拉取连续视频帧,适用于监控、视觉感知等场景。

接口元数据

  • 版本:1.0
  • 接口类型:RTSP
  • 协议格式:rtsp://<Robot-IP>:<Port>/live_<camera_id>
  • 数据流向:Robot -> Outer (数据流/视频流)
  • 调用方式:RTSP流媒体

特别说明

  • 获取 RTSP IP: 前置条件:确保机器人与开发PC/开发板在同一局域网下,并且防火墙已开放 RTSP 端口(默认 2554)。
    1. 有线网固定 IP:若网线直连,则可直接使用机器人固定 IPv4(默认小脑板: 10.1.1.100),启动后直接使用例如 rtsp://10.1.1.100:2554/live_head_monocular_centra 访问。
    2. 无线网 IP:机器人连接 Wi‑Fi或热点等无线网络后,运行 hostname -I 或 ip -4 addr show <iface> 获取 IP,使用例如 rtsp://<IP>:2554/live_head_monocular_centra 访问。

编程示例

2.3.3 电源管理 ​

2.3.3.1 电源状态 ​

本模块提供电池状态实时感知功能,涵盖电量、电压、电流、温度及其底层 BMS 运行状态。

【Topic】电源管理 ​

功能描述

该话题实时发布机器人内部电池包的运行数据与健康信息。开发者可通过订阅此话题,获取精确的剩余电量 (SOC)、充放电倍率及异常报警标志,用于构建电量显示、续航预估或低电保护逻辑。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/bms/state
  • 数据类型:aimdk_msgs/msg/Bms
  • 数据流向:Robot -> Outer (反馈)
  • 调用方式:Subscribe
  • CLI 调用:ros2 topic echo /aima/hal/bms/state
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:1 Hz

接口定义

  • 协议路径:aimdk_msgs/hal/msg/Bms.msg
msg
# ==========================================
# [话题载荷 Payload] BMS 电池管理状态结构体
# ==========================================
MessageHeader header        # 数据头

# 版本信息
string manufacturer         # 厂家信息
string serial_number        # 序列号
string protocol_version     # 协议版本
string hardware_version     # 硬件版本
string software_version     # 软件版本

# 电源状态
uint16 power_request
# 1-触发长按—关机请求
# 2-请求短按+长按关机请求

# 状态位和状态码
uint32 status
# bit 0:  充电标志
# bit 1:  充电过流标志
# bit 2:  放电标志
# bit 3:  放电过流标志
# bit 4:  电池短路标志
# bit 5:  电芯电压过压标志
# bit 6:  电芯电压欠压标志
# bit 7:  电池总电压过压标志
# bit 8:  电池总电压欠压标志
# bit 9:  预留:电芯检测到开路标志
# bit 10: 温感传感器检测到开路标志
# bit 11: 电芯温度超过放电温度上限标志
# bit 12: 电芯温度超过充电温度上限标志
# bit 13: 电芯温度低于放电温度下限标志
# bit 14: 电芯温度低于充电温度下限标志
# bit 15: 电芯最大压差超过上限标志
# bit 16: MOSFET禁止充电标志(表示真正故障禁用)
# bit 17: MOSFET禁止放电标志(表示真正故障禁用)
# bit 18: MOSFET 温度超过工作温度上限标志
# bit 19: 电池包均衡线电阻超过上限标志
# bit 20: 电池充满状态
# bit 21: 电池包固件版本,0是老固件,1新固件
# bit 22: 电池座key是否短接,0短接,1断开
# bit 23: 电池包异常,0正常,1异常
# bit 24: 预留:二级过温警告,0正常,1异常
# bit 25: 有线充电器插入Key是否短接,1短接,0断开
# bit 26: 无线充电器接入状态,0空闲,1接入
# bit 27: 正常关机触发状态
# bit 28: 长按关机触发状态
# bit 29~31: 保留

uint16 balance_line_resistance      # 电池包均衡线电阻(单位:mΩ)
uint32 voltage                      # 电池包电压(单位:mV)
int32 current                       # 电池包电流(单位:mA,充电为正,放电为负)
int32 power                         # 电池包输出功率(单位:mW)
float32 temperature                 # 电池包当前温度(单位:℃)
uint32 remaining_capacity           # 当前电池剩余容量(单位:mAh)
uint8 remaining_capacity_percentage # 当前电池剩余容量百分比(单位:%)
uint16 cycle_count                  # 当前电池包完整循环次数(单位:次)
uint32 cycle_total_capacity         # 总充放电容量累计(单位:mAh)

Bms 协议定义

字段数据类型是否必填描述
headerMessageHeader是数据头
manufacturerstring是厂家信息
serial_numberstring是序列号
protocol_versionstring是协议版本
hardware_versionstring是硬件版本
software_versionstring是软件版本
power_requestuint16是电源请求状态 (1:关机请求, 2:短按+长按)
statusuint32是状态位和状态码(详见位定义说明)
balance_line_resistanceuint16是均衡线电阻(单位:mΩ)
voltageuint32是电池包电压(单位:mV)
currentint32是电池包电流(单位:mA,充电为正)
powerint32是电池包输出功率(单位:mW)
temperaturefloat32是电池包当前温度(单位:℃)
remaining_capacityuint32是剩余容量(单位:mAh)
remaining_capacity_percentageuint8是剩余容量百分比(单位:%)
cycle_countuint16是完整循环次数(单位:次)
cycle_total_capacityuint32是总充放电容量累计(单位:mAh)

Bms status 位定义说明

Bit标识符 (Identifier)描述
0chargeFlag充电标志
1chargeOverCurrentFlag充电过流标志
2dischargeFlag放电标志
3dischargeOverCurrentFlag放电过流标志
4shortCircuitFlag电池短路标志
5cellOverVoltageFlag电芯电压过压标志
6cellUnderVoltageFlag电芯电压欠压标志
7batteryOverVoltageFlag电池总电压过压标志
8batteryUnderVoltageFlag电池总电压欠压标志
9cellOpenCircuit预留:电芯检测到开路标志
10tempSensorOpenCircuit温感传感器检测到开路标志
11cellDischargeOverTemp电芯温度超过放电温度上限标志
12cellChargeOverTemp电芯温度超过充电温度上限标志
13cellDischargeUnderTemp电芯温度低于放电温度上限标志
14cellChargeUnderTemp电芯温度低于充电温度上限标志
15cellMaxVoltageDiff电芯最大压差超过上限标志
16mosfetChargeDisabledMOSFET 禁止充电标志(表示真正故障禁用)
17mosfetDischargeDisabledMOSFET 禁止放电标志(表示真正故障禁用)
18mosfetOverTempMOSFET 此温度超过工作温度上限标志
19balanceLineResistanceHigh电池包均衡线电阻超过上限标志
20batteryFull电池充满状态
21firmwareVersion电池包固件版本(0:老固件 1:新固件)
22batteryKeyShort电池座 key 是否短接(0:短接 1:断开)
23batteryPackAbnormal电池包异常(0:正常 1:异常)
24secondaryOverTemp预留:二级过温警告(0:正常 1:异常)
25wiredChargerKeyShort有线充电器插入 Key 是否短接(1:短接 0:断开)
26wirelessChargerEngaged无线充电器接入状态(0:空闲 1:接入)
27normalShutdown正常关机触发状态
28longPressShutdown长按关机触发状态

特别说明

  • 机型差异:由于不同机器人机型(如 Q系列, T系列等)搭载的 BMS 硬件规格不同,上报的字段丰富程度可能存在差异。某些特定字段在特定机型上可能为 0 或无效值,属于正常现象。

编程示例

2.3.3.2 外挂算力板供电控制 ​

本模块提供外挂算力板供电管理接口,通过 XT30 连接器控制外部计算板的电源通断。

【Service】外挂算力板供电 ​

功能描述

控制机器人 XT30 接口的外挂算力板供电状态,支持开启(enable: true)或关闭(enable: false)外部计算板的电源供应。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/SetExt12vPower
  • 数据类型:aimdk_msgs/srv/SetExt12vPower
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/SetExt12vPower aimdk_msgs/srv/SetExt12vPower "{request: {}, enable: true}"
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/srv/SetExt12vPower.srv
srv
# 外挂算力板供电控制(XT30 接口)

# 请求头
CommonRequest header

# 供电使能:true=开启供电,false=关闭供电
bool enable

---
# 响应头
CommonResponse header

SetExt12vPower 协议定义

字段数据类型描述
headerCommonRequest请求头
enablebool供电使能:true=开启 12V 供电,false=关闭供电
字段数据类型描述
headerCommonResponse响应头

特别说明

  • 默认状态:外挂算力板供电默认为关闭状态,系统重启后会自动恢复为关闭状态,如需使用请重新开启。
  • XT30 接口:本接口控制机器人 XT30 连接器的 12V 电源输出,用于为外挂算力板(如 NVIDIA Jetson、树莓派等)供电。
  • 上电时序:开启供电后,建议等待 3-5 秒再尝试与外挂算力板建立通信连接,确保外部设备完成初始化。
  • 断电保护:关闭供电前,请确保外挂算力板已正常关机或进入安全状态,避免因突然断电导致数据丢失或硬件损坏。

⚠️ 使用注意

  1. 负载限制:XT30 接口最大输出电流请参照机器人硬件规格书,切勿超载使用。
  2. 防水防尘:外挂算力板及连接线缆需做好防水防尘处理,避免影响机器人整体防护等级。
  3. 热插拔警告:请勿在带电状态下插拔 XT30 连接器,以免产生电弧损坏设备。

编程示例

2.3.4 灯语控制 ​

2.3.4.1 二开灯光接口与控制逻辑说明 ​

本节说明整机灯光的状态优先级、控制权流转规则与典型灯控逻辑实例,适用于 2.3.4.2 灯光样式控制 下的全部接口。

状态优先级与显示规范 ​

整机灯光遵循高层级单向强制抢占,同层级依据条件状态切换原则:

优先级状态类型灯效控制逻辑与行为说明
P1开关机与自检白呼吸绝对抢占:系统启动自检或主动下电中生效,不可被打断。
P2物理急停 / 阻尼红快闪安全抢占:拍下急停或触发外部阻尼时生效,抢占 P3~P5。
P3系统故障 / 摔倒红呼吸故障抢占:发生阻断性故障或防摔触发时生效,抢占 P4~P5。
P4未充电 且 电量 $\le 5%$红常亮状态切换:极低电告警;连接充电器时自动切为充电态。
未充电 且 电量 $5% \sim 30%$橙常亮状态切换:低电预警;连接充电器时自动切为充电态。
已接充电器 且 正在充电绿呼吸状态切换:充电指示。
已接充电器 且 电池充满绿常亮状态切换:满电指示。
P5二次开发常规应用态开发者自定义受控默认层:常规交互(走跑、动作、语音、待机)均不抢占,开发者指令持续保持。

控制权流转与调用规范 ​
  1. 抢占接管与安全避让:
    • 应用程序下发的自定义灯光仅作用于当前硬件显示,不改变系统内部的安全与电源状态评估。
    • 当触发急停、故障或充放电状态变动时,系统自动切入对应安全指示灯效(如极低电运行中插充立即切为绿色呼吸)。在此类安全状态期间,应用程序应避免强制覆盖系统指示灯,以防现场人员误判设备物理安全状态。
  2. 状态保持与按需恢复:
    • 按需单次下发:由于常规行为不产生抢占,应用程序仅需在初始化或状态变更时调用接口下发一次指令,无需在循环线程中高频重复发送。
    • 事件解除后重发:当安全或电源状态解除时(如拔除充电器、排除故障),系统自动退出接管,但不会主动恢复历史应用灯效,亦不会强制切回默认白灯,硬件将维持当前显示。若业务需要恢复自定义灯效,建议应用程序订阅电源、故障等话题,在状态恢复正常后重新调用接口下发目标灯效。
灯控逻辑实例参照 ​
实例 1:层级单向抢占 ​
  • P2 抢占 P4(生效):在低电或充电(P4)期间拍下急停(P2),灯效立即中断并强制切换为红快闪。
  • P4 抢占 P2(不生效):在急停(P2)未释放期间插充或电量变动(P4),系统保持急停判定,灯效始终维持红快闪。

实例 2:二开控制权流转全过程 ​

假设开发者设定自定义灯效为“彩色走马灯”,全流程灯效变化如下:

  1. 触发系统故障(进入 P3):系统高优先级接管,显示红呼吸。
  2. 开发者下发灯效(彩色走马灯):整机灯光被强制覆盖为彩色走马灯(非推荐操作,安全告警期间建议主动避让)。
  3. 故障未解除且连接充电器充电:因充电(P4)低于故障(P3)无法抢占,且系统内部层级未变不触发重绘,整机维持当前彩色走马灯。
  4. 再次触发急停(重新进入 P2):系统强制抢占接管,立即切回红快闪。

2.3.4.2 灯光样式控制 ​

本模块提供灯带样式与语义化流光效果控制接口,支持高阶灯光颜色与频率渲染管控。

【Service】灯带控制 ​

功能描述

该服务用于控制机器人灯带的显示模式和颜色。通过参数可以切换灯带的预定义效果,实现状态指示、情感表达或交互提示。

接口元数据

  • 版本:1.0
  • 接口类型:Service
  • 接口名称:/aimdk_5Fmsgs/srv/LedStripCommand
  • 数据类型:aimdk_msgs/srv/LedStripCommand
  • 数据流向:Outer -> Robot (控制命令)
  • 调用方式:Service Call (调用/请求)
  • CLI 调用:ros2 service call /aimdk_5Fmsgs/srv/LedStripCommand aimdk_msgs/srv/LedStripCommand '{...}'
  • QoS:Reliable(服务默认 QoS)

接口定义

  • 协议路径:aimdk_msgs/hal/srv/LedStripCommand.srv
srv
# ==========================================
# [请求部分 Request] 客户端下发的数据结构
# ==========================================
CommonRequest    request                                # [Payload] 请求载荷
uint8            led_strip_mode                         # 灯带模式

# --- led_strip_mode 常量枚举 ---
uint8            LED_ALL_OFF                    = 0     # 全部熄灭
uint8            LED_GREEN_FLOW                 = 1     # 绿色流水
uint8            LED_RAINBOW                    = 2     # 彩虹
uint8            LED_DANCING                    = 3     # 律动
uint8            LED_TWINKLE                    = 4     # 星光闪烁
uint8            LED_TAIL_INCREASE              = 5     # 尾部渐亮
uint8            LED_TAIL_DECREASE              = 6     # 尾部渐暗
uint8            LED_FOUR_TO_TWO_LEGS           = 7     # 白色流水-蓝色流水交替
uint8            LED_TWO_TO_FOUR_LEGS           = 8     # 蓝色流水-白色流水交替
uint8            LED_START_UP                   = 9     # 白色常亮 (r=g=b=128)
uint8            LED_DISPLAY_CHARGING           = 10    # 白色流水
uint8            LED_DISPLAY_FAULT              = 11    # 红色快闪
uint8            LED_DISPLAY_25_LOW_BATTERY     = 12    # 黄色长亮
uint8            LED_DISPLAY_15_LOW_BATTERY     = 13    # 橙红闪烁
uint8            LED_DISPLAY_POWER_OFF          = 14    # 白色从亮到暗渐变
uint8            LED_DISPLAY_POWER_ON           = 15    # 白色从暗到亮渐变
uint8            LED_WHITE_FLOW                 = 16    # 白色填充
uint8            LED_WHITE_ON                   = 17    # 白色常亮 (r=g=b=150)
uint8            LED_DISPLAY_25_LOW_TRANSFORM   = 18    # 黄色流水
uint8            LED_DISPLAY_15_LOW_TRANSFORM   = 19    # 橙红流水
uint8            LED_WHITE_BREATH               = 20    # 白色呼吸
uint8            LED_CUSTOM_BREATH              = 254   # 呼吸灯效自定义模式
uint8            LED_CUSTOM_BLINK               = 255   # 闪烁灯效自定义模式

uint8            r                                      # 红色分量,自定义模式下生效
uint8            g                                      # 绿色分量,自定义模式下生效
uint8            b                                      # 蓝色分量,自定义模式下生效
uint16           period                                 # 周期,自定义模式下生效。单位ms。呼吸灯效自定义模式下,0表示常亮,非0值表示呼吸灯效从最亮到熄灭的时间。闪烁灯效自定义模式下,0表示常亮,非0值表示点亮或者熄灭的保持时间。

---
# ==========================================
# [响应部分 Response] 服务端返回的数据结构
# ==========================================
CommonResponse header

接口返回值说明

  • code = 0, status_value = 1:请求已成功接收并尝试执行
  • 其他返回值:请求失败,常见原因包括:
    • 服务器内部错误(硬件不可用、GPIO 控制失败等)
    • 超时或资源冲突
    • ...

特别说明

  • 模式分类与参数说明:
    • 预定义模式 (0-20):系统内置的灯效模式。在此模式下,r、g、b 和 period 字段被忽略,灯带会按照内部实现显示对应的颜色和动画效果。
    • 自定义呼吸灯模式 (LED_CUSTOM_BREATH = 254):用户可自定义颜色和呼吸周期。需指定 r、g、b 颜色分量(0-255)及 period 周期(单位 ms)。
      • period = 0 → 常亮
      • period > 0 → 呼吸灯效从最亮到熄灭的时间
    • 自定义闪烁灯模式 (LED_CUSTOM_BLINK = 255):用户可自定义颜色和闪烁周期。需指定 r、g、b 颜色分量(0-255)及 period 周期(单位 ms)。
      • period = 0 → 常亮
      • period > 0 → 点亮或熄灭的保持时间
  • 非法值处理:若输入值非法或超出定义范围(如使用 254 或 255 但未设置颜色参数),接口将静默忽略该指令,不做任何响应。

编程示例

2.3.5 惯性传感器 ​

2.3.5.1 IMU 状态 ​

【Topic】IMU 状态 ​

功能描述

该话题实时发布机器人 IMU(惯性测量单元)传感器数据,包含姿态四元数、角速度和线性加速度。开发者可通过订阅此话题获取机器人本体的姿态信息,用于运动控制、姿态估计、平衡检测等场景。 注意:机器人需要切换到低层运控,才能获取IMU传感器数据。

接口元数据

  • 版本:1.0
  • 接口类型:Topic
  • 接口名称:/aima/hal/imu/state
  • 数据类型:sensor_msgs/msg/Imu(ROS2 标准消息类型)
  • 数据流向:Robot -> Outer (反馈)
  • 调用方式:Subscribe
  • CLI 调用:ros2 topic echo /aima/hal/imu/state
  • QoS:Best Effort / Volatile / Depth=10
  • 频率:高频(传感器原始帧率)

接口定义

  • 协议路径:sensor_msgs/msg/Imu(ROS2 标准消息,非 aimdk_msgs 自定义类型)
msg
# ==========================================
# [话题载荷 Payload] IMU 惯性传感器状态(ROS2 标准定义)
# ==========================================
std_msgs/Header  header                            # 消息头(时间戳 + frame_id)

# --- 姿态(四元数) ---
geometry_msgs/Quaternion  orientation              # 姿态四元数 (x, y, z, w)
float64[9]                orientation_covariance    # 姿态协方差矩阵(行优先,3x3)

# --- 角速度 ---
geometry_msgs/Vector3     angular_velocity          # 角速度 (x, y, z),单位:rad/s
float64[9]                angular_velocity_covariance  # 角速度协方差矩阵(行优先,3x3)

# --- 线性加速度 ---
geometry_msgs/Vector3     linear_acceleration       # 线性加速度 (x, y, z),单位:m/s²
float64[9]                linear_acceleration_covariance  # 线性加速度协方差矩阵(行优先,3x3)

嵌套类型定义

嵌套类型字段类型说明
geometry_msgs/Quaternionxfloat64四元数 x 分量
yfloat64四元数 y 分量
zfloat64四元数 z 分量
wfloat64四元数 w 分量(标量部分)
geometry_msgs/Vector3xfloat64x 轴分量
yfloat64y 轴分量
zfloat64z 轴分量

字段说明

字段类型说明
header.stampbuiltin_interfaces/Time传感器数据采集时间戳
header.frame_idstring坐标系 ID(如 imu_link)
orientationgeometry_msgs/Quaternion姿态四元数,表示 IMU 相对于参考坐标系的旋转
orientation_covariancefloat64[9]姿态估计的协方差矩阵(行优先 3x3),全零表示协方差未知
angular_velocitygeometry_msgs/Vector3三轴角速度,单位:rad/s
angular_velocity_covariancefloat64[9]角速度协方差矩阵(行优先 3x3),全零表示协方差未知
linear_accelerationgeometry_msgs/Vector3三轴线性加速度(含重力分量),单位:m/s²
linear_acceleration_covariancefloat64[9]线性加速度协方差矩阵(行优先 3x3),全零表示协方差未知

特别说明

  • 标准消息类型:该话题使用 ROS2 标准消息 sensor_msgs/msg/Imu,无需依赖 aimdk_msgs 包。开发时确保系统已安装 ros-${ROS_DISTRO}-common-interfaces 即可。
  • 四元数姿态表示:orientation 字段以四元数 (x, y, z, w) 表示姿态,其中 w 为标量部分。四元数已归一化,满足 x² + y² + z² + w² = 1。
  • 重力分量:linear_acceleration 包含重力加速度分量。当机器人静止时,z 轴加速度约为 9.8 m/s²(重力方向)。可通过四元数旋转将重力分量分离,提取纯运动加速度。
  • 协方差矩阵:各协方差矩阵为 3x3 对称矩阵,按行优先排列(9 个元素)。若矩阵全为零,表示传感器未提供协方差信息。
  • 应用场景:
    • 姿态估计与平衡控制
    • 运动状态检测(站立 / 倒地 / 行走)
    • 传感器融合(与里程计、视觉等数据结合)

3. 消息与数据结构定义 ​

说明:本章节汇集了系统原始的 IDL 协议定义,内容与 SDK aimdk_msgs 中的物理文件严格对齐。此部分仅作为查询底层数据结构、嵌套关系及字段类型的全量技术参考(不涉及特定机型的功能裁剪)。实际业务集成时,请务必参考 2. 接口详情 章节以确认特定机型支持的可用接口范围。

3.1 公共类型定义 ​

3.1.1 通用请求与响应类型 ​

CommonRequest ​

  • 协议路径:aimdk_msgs/common/CommonRequest.msg
字段数据类型描述
headerRequestHeader请求头定义

CommonResponse ​

  • 协议路径:aimdk_msgs/common/CommonResponse.msg
字段数据类型描述
headerResponseHeader对应响应头 (含 status_code)
statusCommonState业务状态码反馈
messagestring

MessageHeader ​

  • 协议路径:aimdk_msgs/common/MessageHeader.msg
字段数据类型描述
stampbuiltin_interfaces/Time
frame_idstring
sequenceuint32
meas_stampbuiltin_interfaces/Time

CommonTaskResponse ​

  • 协议路径:aimdk_msgs/common/CommonTaskResponse.msg
字段数据类型描述
headerResponseHeader对应任务响应头 (含 task_id)
task_iduint64
stateCommonState

RequestHeader ​

  • 协议路径:aimdk_msgs/common/RequestHeader.msg
字段数据类型描述
stampbuiltin_interfaces/Time

ResponseHeader ​

  • 协议路径:aimdk_msgs/common/ResponseHeader.msg
字段数据类型描述
stampbuiltin_interfaces/Time
codeint64

CommonState ​

  • 协议路径:aimdk_msgs/common/CommonState.msg
字段数据类型描述
valueint32当前状态码
reasonuint32失败原因码

CommonState 枚举字典

常量名数值描述
UNKNOWN0未知状态。
SUCCESS1指令下发/执行成功。
FAILURE2指令执行失败,需查阅 message 实意。
ABORTED3任务被外部中止或抢占失效。
TIMEOUT4系统响应超时(网络或底层控制器未及时响应)。
INVALID5请求参数格式错误或指令当前状态非法。
IN_MANUAL6当前处于手动接管/锁定模式。
NOT_READY100系统正在启动初始化中。
PENDING200任务等待队列中。
CREATED300任务已成功创建。
RUNNING400任务正在活跃运行中。

CommonState reason 故障原因字典

常量名数值描述
REASON_SUCCESS0成功。
REASON_OPENBOX1开箱状态中。
REASON_STARTUP_CHECK2开机自检中。
REASON_SHUTDOWN3关机状态中。
REASON_FROM4当前形态不支持。
REASON_LOW_BATTERY5低电量限制。
REASON_CHARGE6正在充电中。
REASON_NO_WHITELIST7动作不在白名单。
REASON_HDS8HDS故障。
REASON_ACTION9当前模式不支持。
REASON_OBSTACLE_FORWARD10前方有障碍物。
REASON_OBSTACLE_BACK11后方有障碍物。
REASON_OBSTACLE_LEFT12左方有障碍物。
REASON_OBSTACLE_RIGHT13右方有障碍物。
REASON_OBSTACLE_UP14上方有障碍物。
REASON_TASK_RUNNING15其他任务正在运行。
REASON_TARGET_STATE16机器人已经是目标状态。
REASON_NOT_FOUND17未找到相关动作。
REASON_NO_SKILL_LIST18无可用技能列表。
REASON_FORM_MIS_MATCH19无法执行任务,机器人需要处于双足站立状态。
REASON_ACTION_NOT_MATCH20当前动作不匹配,无法执行动画。
REASON_ACTION_BLACKLISTED21当前动作在黑名单中,无法执行动画。
REASON_NO_TRANSFER_PATH22当前姿态下无法进行动作转移。
REASON_NO_ELIGIBLE_SKILL23无符合条件的技能。
REASON_INDOOR_WHOLE_BODY24室内模式下暂不支持该动作。
REASON_ENGINE_NOT_READY25动作配置未就绪,无法执行动画。
REASON_NOT_SUPPORTED26当前机型不支持该功能。
REASON_STAND_UP_IN_PROGRESS27机器人正在起立,暂不能收起默认动作。
REASON_NOT_INTERRUPTIBLE28当前动画不可打断。
REASON_INTERRUPT_INVALID29当前动画 ID 无效,无法打断。
REASON_TRANSFORM_CONDITION30当前状态不满足变形/动作执行条件。

3.2 运动控制功能 ​

3.2.1 运控高层接口 ​

McTaskSource ​

  • 协议路径:aimdk_msgs/mc/action/McTaskSource.msg
字段数据类型描述
valueint32触发源枚举值

McTaskSource 枚举字典

常量名数值描述
UNKNOWN0未知/未指定
APP1App
CLOUD2云端
RC3遥控器
SDK_RPC4SDK/RPC 直接调用
AGENT5Agent
TASK_ENGINE6Task Engine 自动任务
MC_INTERNAL7MC 内部自动切换
INSTA3608Insta360
OTHER255其他来源

McInputSource ​

  • 协议路径:aimdk_msgs/mc/motion/McInputSource.msg
字段数据类型描述
namestring输入源名称(rc/vr/app_proxy/interaction/pnc)
priorityint32输入源优先级(0-100)
timeoutint32超时时间(ms), 默认 1000 ms

McActionInfo ​

  • 协议路径:aimdk_msgs/mc/action/McActionInfo.msg
字段数据类型描述
current_actionMcAction
sourcestring当前action的触发源
action_descstring
statusMcActionStatus
switch_readyboolaction 切换是否就绪

McControlArea ​

  • 协议路径:aimdk_msgs/mc/motion/McControlArea.msg
字段数据类型描述
valueint32

常量枚举字典

常量名数值描述
NONE0没有控制区域
LEFT_HAND1左手
RIGHT_HAND2右手
HEAD4头部
WAIST8腰部

McInputAction ​

  • 协议路径:aimdk_msgs/mc/motion/McInputAction.msg
字段数据类型描述
valueint32

常量枚举字典

常量名数值描述
INPUTACTION_ADD1001添加新的输入源
INPUTACTION_MODIFY1002修改输入源配置
INPUTACTION_DELETE1003删除输入源
INPUTACTION_ENABLE2001使能输入源
INPUTACTION_DISABLE2002下使能输入源

McPresetMotion ​

  • 协议路径:aimdk_msgs/mc/motion/McPresetMotion.msg
字段数据类型描述
valueint32

常量枚举字典

常量名数值描述
Q_BECKON3001招手
Q_SHAKE_HANDS3002握手
Q_BUMP_FISTS3003碰拳
Q_WAVE_HAND3004挥手
Q_SHOW_HAPPINESS3005情绪动作 - 开心
Q_MAKE_HEART3007双手比心
Q_CHEER_ON3008加油
Q_STRETCH3010伸懒腰
Q_SPEAK_A3012讲话动作A
Q_SPEAK_B3013讲话动作B
Q_SPEAK_C3014讲话动作C
Q_HUG3018拥抱
Q_REFUSE3021拒绝
Q_DANCE_A3046跳舞动作A
Q_DANCE_B3047跳舞动作B
Q_DANCE_C3048跳舞动作C

McActionCommand ​

  • 协议路径:aimdk_msgs/mc/action/McActionCommand.msg
字段数据类型描述
actionMcAction
action_descstring

McLocomotionVelocity ​

  • 协议路径:aimdk_msgs/mc/motion/McLocomotionVelocity.msg
字段数据类型描述
headerMessageHeader
sourcestring
forward_velocityfloat64
lateral_velocityfloat64
angular_velocityfloat64
pitch_velocityfloat64
levelfloat64

McCustomJointCommand ​

  • 协议路径:aimdk_msgs/mc/motion/McCustomJointCommand.msg
字段数据类型描述
headerMessageHeader消息头
jointsJointCommand[]上肢关节目标命令数组

McActionStatus ​

  • 协议路径:aimdk_msgs/mc/action/McActionStatus.msg
字段数据类型描述
valueint32

McActionStatus 枚举字典

常量名数值描述
IDLE0空闲/未知状态
RUNNING100运行中
TRANSITION200状态切换中

McAction ​

  • 协议路径:aimdk_msgs/mc/action/McAction.msg
字段数据类型描述
valueint32

McAction 枚举字典

常量名数值描述
PASSIVE_DEFAULT1被动模式
DAMPING_DEFAULT2阻尼模式
BIPED_STAND_DEFAULT201位控站立
STORE_DEFAULT1001折叠收储
BIPED_WALK_RUN1002走跑
BIPED_WHOLE_BODY_CTRL1005全身动作控制
STAND_UP1007站起
LIE_FACE_DOWN1009躺下-俯卧
LIE_FACE_UP1010躺下-仰躺
BIPED_BLIND_TERRAIN1012越障模式(室外)
BIPED_CUSTOM_UPPER1014上肢控制
BIPED_RUN1015超能模式/跑步模式

3.2.2 运控低层接口 ​

JointCommand ​

  • 协议路径:aimdk_msgs/hal/msg/JointCommand.msg
字段数据类型描述
namestring
positionfloat64
velocityfloat64
effortfloat64
stiffnessfloat64
dampingfloat64

JointState ​

  • 协议路径:aimdk_msgs/hal/msg/JointState.msg
字段数据类型描述
namestring
positionfloat64
velocityfloat64
effortfloat64
coil_tempint16
motor_tempint16
motor_voluint8

3.3 交互控制功能 ​

3.3.1 公共交互类型 ​

TokenCommon ​

  • 协议路径:aimdk_msgs/interaction/msg/TokenCommon.msg
字段数据类型描述
sourcestring来源标识,不能为空
tokenstring令牌,可为空

3.3.2 语音控制 ​

AudioInfo ​

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioInfo.msg
字段数据类型描述
channelsuint8总声道数
sample_rateuint32采样率 (Hz)
sizeuint32单帧采样点数
sample_formatstring采样格式(如 "S16LE")
coding_formatstring编码格式(如 "wave")

AudioData ​

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioData.msg
字段数据类型描述
datauint8[]二进制原始音频数据缓冲区

AudioDeviceInfo ​

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioDeviceInfo.msg
字段数据类型描述
idint32设备索引号
device_addrstring设备标志符(如 builtin_mic、builtin_speaker)
device_typestring设备类型(如 builtin、bluetooth)
device_namestring设备名称(如 snd_card_name、bluetooth)
is_selbool是否处于选中状态

AudioDeviceInfoList ​

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioDeviceInfoList.msg
字段数据类型描述
input_listAudioDeviceInfo[]音频输入设备列表
output_listAudioDeviceInfo[]音频输出设备列表

TtsPriorityLevel ​

  • 协议路径:aimdk_msgs/interaction/msg/TtsPriorityLevel.msg
字段数据类型描述
valueuint8

TtsPriorityLevel 枚举字典

常量名数值描述
UNKNOWN0x00未知优先级
BACKGROUND_L10x01后台服务层(最低优先级)
SERVICE_L20x02主动服务层
MISSION_L40x04任务执行层
INTERACTION_L60x06交互响应层(默认值)
WARNING_L80x08危险预警层
SAFETY_L100x0a生命安全层(最高优先级)

PlayTtsRequest ​

  • 协议路径:aimdk_msgs/interaction/msg/PlayTtsRequest.msg
字段数据类型描述
textstring待播报的内容文本
priority_levelTtsPriorityLevel优先级档位
priority_weightuint32优先级加权值 (0-99)
domainstring业务域标识 (如 "navigation")
trace_idstring链路追踪 ID
is_interruptedbool是否允许打断同优先级播报

PlayTtsResponse ​

  • 协议路径:aimdk_msgs/interaction/msg/PlayTtsResponse.msg
字段数据类型描述
textstring
priority_levelTtsPriorityLevel
priority_weightuint32
domainstring
trace_idstring
is_successbool
error_messagestring
estimated_durationuint32

AudioFile ​

  • 协议路径:aimdk_msgs/hal/audio/msg/AudioFile.msg
字段数据类型描述
pkg_namestring来源包名标识
file_namestring文件名
file_pathstring文件完整绝对路径
infoAudioInfo音频格式参数
priorityuint32播放优先级 (1-10)
priority_weightuint32优先级细化加权百分比
media_rolestringPulseAudio media.role,不传默认 Music。可选值:Alert(系统告警,优先级100)、Notification(系统提示音,优先级80)、Communication(对话语音,优先级60)、Music(音乐/媒体,优先级40)。非 Music 角色播放时会自动降低(duck)音乐音量

AsrResult ​

  • 协议路径:aimdk_msgs/agent/msg/AsrResult.msg
字段数据类型描述
headerMessageHeader
textstring识别文本
event_idstring事件ID,用于关联对话上下文
is_finalbool是否为最终结果(false 表示中间/部分结果)
confidencefloat32置信度 [0.0, 1.0]
languagestring语言标签,如 zh、en

3.4 硬件抽象功能 ​

3.4.1 触觉传感器 ​

TouchState ​

  • 协议路径:aimdk_msgs/hal/msg/TouchState.msg
字段数据类型描述
headerMessageHeader
event_typeuint8

TouchState 枚举字典

常量名数值描述
TOUCH_EVENT_SINGLE_CLICK1

3.4.2 视觉传感器 ​

JpegImage ​

  • 协议路径:aimdk_msgs/hal/camera/msg/JpegImage.msg
字段数据类型描述
camera_idstring相机唯一标识符
devicestring设备节点路径信息
widthuint32图像宽度 (Pixel)
heightuint32图像高度 (Pixel)
framerateuint32采集帧率 (FPS)
exposureuint32曝光值
gainuint32模拟增益
imagesensor_msgs/CompressedImageJPEG 图像载荷 (标准 ROS 2 压缩图像格式)

3.4.3 电源管理 ​

Bms ​

  • 协议路径:aimdk_msgs/hal/msg/Bms.msg
字段数据类型描述
headerMessageHeader数据头
manufacturerstring厂家信息
serial_numberstring序列号
protocol_versionstring协议版本
hardware_versionstring硬件版本
software_versionstring软件版本
power_requestuint16电源请求 (1:关机请求, 2:短按+长按)
statusuint32状态位和状态码(详见下表)
balance_line_resistanceuint16电池包均衡线电阻 (mΩ)
voltageuint32电池包电压 (mV)
currentint32电池包电流 (mA, 充电为正)
powerint32电池包输出功率 (mW)
temperaturefloat32电池包当前温度 (℃)
remaining_capacityuint32剩余容量 (mAh)
remaining_capacity_percentageuint8剩余容量百分比 (0-100%)
cycle_countuint16完整循环次数
cycle_total_capacityuint32总充放电容量累计 (mAh)

Bms status 位定义说明

Bit 位描述
bit 0充电标志
bit 1充电过流标志
bit 2放电标志
bit 3放电过流标志
bit 4电池短路标志
bit 5电芯电压过压标志
bit 6电芯电压欠压标志
bit 7电池总电压过压标志
bit 8电池总电压欠压标志
bit 9预留:电芯检测到开路标志
bit 10温感传感器检测到开路标志
bit 11电芯温度超过放电温度上限标志
bit 12电芯温度超过充电温度上限标志
bit 13电芯温度低于放电温度下限标志
bit 14电芯温度低于充电温度下限标志
bit 15电芯最大压差超过上限标志
bit 16MOSFET 禁止充电标志(表示真正故障禁用)
bit 17MOSFET 禁止放电标志(表示真正故障禁用)
bit 18MOSFET 温度超过工作温度上限标志
bit 19电池包均衡线电阻超过上限标志
bit 20电池充满状态
bit 21电池包固件版本(0:老固件 1:新固件)
bit 22电池座 Key 是否短接(0:短接 1:断开)
bit 23电池包异常(0:正常 1:异常)
bit 24预留:二级过温警告(0:正常 1:异常)
bit 25有线充电器插入 Key 是否短接(1:短接 0:断开)
bit 26无线充电器接入状态(0:空闲 1:接入)
bit 27正常关机触发状态
bit 28长按关机触发状态

4. 编程示例 ​

本模块提供各个功能模块的示例代码,帮助开发者快速理解 ROS 2 节点编写规范及 SDK 接口调用流程。

4.0 代码运行前置条件 ​

Cpp 代码运行前置条件 ​

  1. 环境依赖:需先编译并加载 aimdk_msgs 接口依赖包。
  2. OpenCV 4.13.0 与源码编译:在工作空间根目录执行 colcon build --packages-up-to aimdk_examples_cpp --symlink-install。aimdk_opencv 会先为当前 CPU 架构从 examples/opencv 构建 RTSP 所需 OpenCV;不要使用系统中较旧的 OpenCV。
  3. 加载变量:运行前需执行 source install/setup.bash 激活工作空间环境。

Python 代码运行前置条件 ​

  1. 环境依赖:必须确保包含对 aimdk_msgs 依赖消息包的引用支持。
  2. 加载变量:运行前需执行 source install/setup.bash 激活 ROS 2 通信环境,激活后可直接使用 python3 独立载入脚本。

4.1 运动控制功能 ​

4.1.1 运控高层接口 ​

代码示例

动作控制(Service: SetMcAction) ​

动作控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp set_mc_action

cpp
/*
 MC Action and Motion Control Example Script
 
 Description:
   This script demonstrates how to control robot actions and motions using the SetMcAction and SetMcMotion services.
   Supports both interactive action mode and automatic motion execution with state machine transitions.
 
 Prerequisites:
   - MC (Motion Control) service must be running
   - Robot must be in a safe environment for motion testing
   - McActionSwitcher plans supported state transitions
 
 Usage:
   ros2 run aimdk_examples_cpp set_mc_action --ros-args -p type:=<type> -p motion:=<motion_name>
 
 Example:
   # Interactive action mode
   ros2 run aimdk_examples_cpp set_mc_action --ros-args -p type:=action
   
   # Execute specific motion with auto-transition
   ros2 run aimdk_examples_cpp set_mc_action --ros-args -p type:=motion -p motion:=INTRO_POSE7
 
 Parameters:
   - type: Control type, either 'action' or 'motion' (required)
   - action_desc: Action description string (used in action mode)
   - motion: Motion name to execute (required when type=motion)
 */
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/msg/mc_action_status.hpp"
#include "aimdk_msgs/srv/get_mc_action.hpp"
#include "aimdk_msgs/srv/set_mc_motion.hpp"
#include "mc_action_switcher.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <cstdint>
#include <memory>
#include <signal.h>
#include <string>
#include <thread>

constexpr double kServiceCallTimeoutSec = 2.0;
constexpr int kMaxRetryCount = 3;

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal) {
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class SetMcActionClient : public rclcpp::Node {
public:
  SetMcActionClient() : Node("set_mc_action_client") {
    type_ = this->declare_parameter<std::string>("type", "");
    action_desc_ = this->declare_parameter<std::string>("action_desc", "");
    motion_ = this->declare_parameter<std::string>("motion", "");

    set_motion_client_ = this->create_client<aimdk_msgs::srv::SetMcMotion>(
        "/aimdk_5Fmsgs/srv/SetMcMotion");
    get_client_ = this->create_client<aimdk_msgs::srv::GetMcAction>(
        "/aimdk_5Fmsgs/srv/GetMcAction");
    RCLCPP_INFO(this->get_logger(),
                "SetMcAction client node created with type=%s action_desc=%s "
                "motion=%s",
                type_.c_str(), action_desc_.c_str(), motion_.c_str());
  }

  bool execute() {
    if (!validate_parameters()) {
      return false;
    }

    wait_for_services();

    if (type_ == "action") {
      // Execute action only once (no loop)
      ActionInfo current;
      if (!get_action_status(current)) {
        RCLCPP_ERROR(this->get_logger(), "Failed to get current action status");
        return false;
      }

      RCLCPP_INFO(this->get_logger(), "Current Action is: %s",
                  current.action_desc.c_str());

      std::string target_action;
      if (action_desc_.empty()) {
        std::cout << "\nCurrent Action is: " << current.action_desc
                  << ", please input the expected Action according to the "
                     "motion control state machine transition "
                     "logic in the interface documentation. "
                     "The Action you need to switch: "
                  << std::flush;

        if (!std::getline(std::cin, target_action) || target_action.empty()) {
          RCLCPP_ERROR(this->get_logger(), "No target action specified");
          return false;
        }
      } else {
        target_action = action_desc_;
      }

      aimdk_examples::McActionSwitcher switcher(this->shared_from_this());
      aimdk_examples::McActionSwitchOptions options;
      options.source = "set_mc_action";
      options.total_timeout = std::chrono::seconds(20);

      const auto result = switcher.switch_to(target_action, options);
      if (result.success) {
        std::cout << "\nSwitch succeeded!" << std::endl;
      } else {
        std::cout << "Switch failed, please confirm if the expected Action "
                     "complies with the state machine transition logic"
                  << std::endl;
        RCLCPP_ERROR(this->get_logger(), "Action switch failed: %s",
                     result.message.c_str());
      }

      return result.success;
    } else if (type_ == "motion") {
      // Optimized logic for 'motion' type: Ensure robot is in BIPED_WALK_RUN
      aimdk_examples::McActionSwitcher switcher(this->shared_from_this());
      aimdk_examples::McActionSwitchOptions options;
      options.source = "set_mc_action";
      options.total_timeout = std::chrono::seconds(30);

      const auto result = switcher.switch_to("BIPED_WALK_RUN", options);
      if (!result.success) {
        RCLCPP_ERROR(this->get_logger(),
                     "Failed to switch from %s to BIPED_WALK_RUN: %s",
                     result.current_action.empty() ? "(unknown)"
                                                   : result.current_action.c_str(),
                     result.message.c_str());
        return false;
      }

      // Execute final target motion
      if (!set_motion(motion_)) {
        return false;
      }
      return wait_for_motion();
    }

    RCLCPP_ERROR(this->get_logger(), "Unsupported control type: %s",
                 type_.c_str());
    return false;
  }

private:
  struct ActionInfo {
    int32_t action_id = 0;
    std::string action_desc;
    int32_t status = aimdk_msgs::msg::McActionStatus::IDLE;
  };

  bool validate_parameters() {
    if (type_.empty()) {
      RCLCPP_ERROR(this->get_logger(),
                   "Parameter 'type' must be set. Use 'action' or 'motion'.");
      return false;
    }

    if (type_ != "action" && type_ != "motion") {
      RCLCPP_ERROR(this->get_logger(),
                   "Invalid parameter 'type': %s. Use 'action' or 'motion'.",
                   type_.c_str());
      return false;
    }

    if (type_ == "motion" && motion_.empty()) {
      RCLCPP_ERROR(this->get_logger(),
                   "Parameter 'motion' must be set when type=motion.");
      return false;
    }

    if (type_ == "motion" && motion_.empty()) {
      RCLCPP_ERROR(this->get_logger(),
                   "Parameter 'motion' must be set when type=motion.");
      return false;
    }

    return true;
  }

  // Generic retry function for service calls
  template <typename ServiceT>
  typename rclcpp::Client<ServiceT>::SharedFuture
  call_service_with_retry(
      typename rclcpp::Client<ServiceT>::SharedPtr client,
      typename ServiceT::Request::SharedPtr request,
      const std::string &service_name,
      std::chrono::milliseconds timeout = std::chrono::milliseconds(
          static_cast<int>(kServiceCallTimeoutSec * 1000)),
      int max_retries = kMaxRetryCount) {
    
    for (int i = 0; i < max_retries; ++i) {
      auto future = client->async_send_request(request);
      auto retcode = rclcpp::spin_until_future_complete(
          this->shared_from_this(), future, timeout);

      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        return future.future.share();
      }

      RCLCPP_INFO(this->get_logger(),
                  "%s attempt %d/%d timed out, retrying...",
                  service_name.c_str(), i + 1, max_retries);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    RCLCPP_ERROR(this->get_logger(),
                 "%s failed after %d attempts",
                 service_name.c_str(), max_retries);
    return typename rclcpp::Client<ServiceT>::SharedFuture();
  }

  bool set_motion(const std::string &motion_name) {
    try {
      constexpr int kMaxAttempts = 5;
      const auto request_timeout = std::chrono::seconds(1);

      for (int attempt = 1; attempt <= kMaxAttempts; ++attempt) {
        auto request =
            std::make_shared<aimdk_msgs::srv::SetMcMotion::Request>();
        request->header.stamp = this->now();
        request->source = "set_mc_action";
        request->motion = motion_name;
        request->type = aimdk_msgs::srv::SetMcMotion::Request::MIMIC_QY;
        request->interrupt = false;

        RCLCPP_INFO(this->get_logger(),
                    "Sending SetMcMotion request (%d/%d): motion=%s "
                    "interrupt=false",
                    attempt, kMaxAttempts, motion_name.c_str());

        auto future = set_motion_client_->async_send_request(request);
        auto retcode = rclcpp::spin_until_future_complete(
            shared_from_this(), future, request_timeout);

        if (retcode != rclcpp::FutureReturnCode::SUCCESS) {
          RCLCPP_WARN(this->get_logger(),
                      "SetMcMotion request attempt %d/%d failed or timed out.",
                      attempt, kMaxAttempts);
          continue;
        }

        auto response = future.get();
        const auto code = response->response.header.code;
        const auto state = response->response.state.value;

        if (code == 0 &&
            (state == aimdk_msgs::msg::CommonState::SUCCESS ||
             state == aimdk_msgs::msg::CommonState::RUNNING)) {
          RCLCPP_INFO(this->get_logger(),
                      "SetMcMotion request accepted by service: code=%ld "
                      "state=%d",
                      static_cast<long>(code), state);
          return true;
        }

        RCLCPP_WARN(this->get_logger(),
                    "SetMcMotion request attempt %d/%d was not accepted: "
                    "code=%ld state=%d",
                    attempt, kMaxAttempts, static_cast<long>(code), state);
      }

      RCLCPP_ERROR(this->get_logger(),
                   "Failed to set motion after %d attempts.", kMaxAttempts);
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

  bool wait_for_motion(
      std::chrono::seconds timeout = std::chrono::seconds(10),
      std::chrono::milliseconds poll_interval = std::chrono::milliseconds(200)) {
    auto deadline = std::chrono::steady_clock::now() + timeout;

    RCLCPP_INFO(this->get_logger(),
                "Waiting for current motion action to reach RUNNING state...");

    while (rclcpp::ok() && std::chrono::steady_clock::now() < deadline) {
      ActionInfo info;
      if (!get_action_status(info)) {
        std::this_thread::sleep_for(poll_interval);
        continue;
      }

      if (info.status == aimdk_msgs::msg::McActionStatus::RUNNING) {
        RCLCPP_INFO(this->get_logger(),
                    "Current motion action is running: action_id=%d "
                    "action_desc=%s status=%d",
                    info.action_id, info.action_desc.c_str(), info.status);
        return true;
      }

      std::this_thread::sleep_for(poll_interval);
    }

    RCLCPP_ERROR(this->get_logger(),
                 "Timed out waiting for current motion action to reach "
                 "RUNNING state.");
    return false;
  }

  bool get_action_status(ActionInfo &info) {
    try {
      auto request = std::make_shared<aimdk_msgs::srv::GetMcAction::Request>();
      request->request = aimdk_msgs::msg::CommonRequest();
      request->request.header.stamp = this->now();

      auto future = call_service_with_retry<aimdk_msgs::srv::GetMcAction>(
          get_client_, request, "GetMcAction");

      if (!future.valid()) {
        RCLCPP_WARN(this->get_logger(),
                    "Get current action request service call failed or timed "
                    "out.");
        return false;
      }

      auto response = future.get();
      info.action_id = response->info.current_action.value;
      info.action_desc = response->info.action_desc;
      info.status = response->info.status.value;
      return true;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

  template <typename ClientT>
  void wait_for_service(
      const std::shared_ptr<ClientT> &client,
      const std::string &service_name) {
    while (!client->wait_for_service(std::chrono::seconds(2))) {
      if (!rclcpp::ok()) {
        return;
      }
      RCLCPP_INFO(this->get_logger(), "Service unavailable, waiting: %s",
                  service_name.c_str());
    }
    RCLCPP_INFO(this->get_logger(), "Service available: %s",
                service_name.c_str());
  }

  void wait_for_services() {
    /* Check only the necessary services based on the operation type. */
    // GetMcAction is required for both types to query the current state
    wait_for_service(get_client_, "/aimdk_5Fmsgs/srv/GetMcAction");

    if (type_ == "motion") {
      wait_for_service(set_motion_client_, "/aimdk_5Fmsgs/srv/SetMcMotion");
    }
  }

  std::string type_;
  std::string action_desc_;
  std::string motion_;

  rclcpp::Client<aimdk_msgs::srv::SetMcMotion>::SharedPtr set_motion_client_;
  rclcpp::Client<aimdk_msgs::srv::GetMcAction>::SharedPtr get_client_;
};

int main(int argc, char *argv[]) {
  try {
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    g_node = std::make_shared<SetMcActionClient>();
    auto client = std::dynamic_pointer_cast<SetMcActionClient>(g_node);
    const bool ok = client ? client->execute() : false;

    g_node.reset();
    rclcpp::shutdown();

    return ok ? 0 : 1;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("main"),
                 "Program exited with exception: %s", e.what());
    return 1;
  }
}
动作控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/set_mc_action.py

python
#!/usr/bin/env python3

"""
MC Action and Motion Control Example Script

Description:
  This script demonstrates how to control robot actions and motions using the SetMcAction and SetMcMotion services.
  Supports both interactive action mode and automatic motion execution with state machine transitions.

Prerequisites:
  - MC (Motion Control) service must be running
  - Robot must be in a safe environment for motion testing
  - The shared action switcher plans supported state transitions

Usage:
  python3 set_mc_action.py --ros-args -p type:=<type> -p motion:=<motion_name>

Example:
  # Interactive action mode
  python3 set_mc_action.py --ros-args -p type:=action
  
  # Execute specific motion with auto-transition
  python3 set_mc_action.py --ros-args -p type:=motion -p motion:=INTRO_POSE7

Parameters:
  - type: Control type, either 'action' or 'motion' (required)
  - action_desc: Action description string (used in action mode)
  - motion: Motion name to execute (required when type=motion)
"""

import time

import rclpy
import rclpy.logging
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest, CommonState, McActionStatus, RequestHeader
from aimdk_msgs.srv import GetMcAction, SetMcMotion

from common.mc_action_switcher import McActionSwitchOptions, McActionSwitcher

SERVICE_CALL_TIMEOUT_SEC = 2.0
MAX_RETRY_COUNT = 3


class SetMcActionClient(Node):
    def __init__(self):
        super().__init__('set_mc_action_client')
        self.type = self.declare_parameter('type', '').value
        self.action_desc = self.declare_parameter('action_desc', '').value
        self.motion = self.declare_parameter('motion', '').value

        self.set_motion_client = self.create_client(
            SetMcMotion, '/aimdk_5Fmsgs/srv/SetMcMotion'
        )
        self.get_client = self.create_client(
            GetMcAction, '/aimdk_5Fmsgs/srv/GetMcAction'
        )
        self.get_logger().info(
            'SetMcAction client node created with '
            f'type={self.type} action_desc={self.action_desc} '
            f'motion={self.motion}'
        )

    def call_service_with_retry(self, client, request, service_name: str, timeout_sec=None, max_retries=None):
        """带重试机制的服务调用"""
        if timeout_sec is None:
            timeout_sec = SERVICE_CALL_TIMEOUT_SEC
        if max_retries is None:
            max_retries = MAX_RETRY_COUNT
            
        for i in range(max_retries):
            future = client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=timeout_sec)

            if future.done():
                return future

            self.get_logger().info(f'{service_name} attempt {i+1}/{max_retries} timed out, retrying...')
            time.sleep(0.2)
        
        self.get_logger().error(f'{service_name} failed after {max_retries} attempts')
        return None

    def execute(self) -> bool:
        if not self.validate_parameters():
            return False

        self.wait_for_services()

        if self.type == 'action':
            try:
                # 只执行一次动作
                current_id, current_desc, current_status = self.get_action_status()
                self.get_logger().info(f'Current Action is: {current_desc}')
                
                try:
                    if not self.action_desc:
                        target_action = input(
                        f"Current Action is: {current_desc}, please input the expected Action "
                        "according to the motion control state machine transition logic in the "
                        "interface documentation. The Action you need to switch: "
                        ).strip()
                    else:
                        target_action = self.action_desc
                except EOFError:
                    return True

                if not target_action:
                    self.get_logger().error("No target action specified")
                    return False

                switcher = McActionSwitcher(self)
                options = McActionSwitchOptions(
                    source="set_mc_action",
                    total_timeout=20.0,
                )
                result = switcher.switch_to(target_action, options)
                if result.success:
                    print("\nSwitch succeeded!")
                else:
                    print("Switch failed, please confirm if the expected Action complies with the state machine transition logic")
                    self.get_logger().error(
                        f"Action switch failed: {result.message}"
                    )
                return result.success
            except KeyboardInterrupt:
                return True
        else:
            switcher = McActionSwitcher(self)
            options = McActionSwitchOptions(
                source="set_mc_action",
                total_timeout=30.0,
            )
            result = switcher.switch_to("BIPED_WALK_RUN", options)
            if not result.success:
                current_action = result.current_action or "(unknown)"
                self.get_logger().error(
                    "Failed to switch from "
                    f"{current_action} to BIPED_WALK_RUN: {result.message}"
                )
                return False

            # Execute final target motion
            if not self.set_motion(self.motion):
                return False
            return self.wait_for_motion()

    def validate_parameters(self) -> bool:
        if not self.type:
            self.get_logger().error(
                "Parameter 'type' must be set. Use 'action' or 'motion'."
            )
            return False

        if self.type not in ('action', 'motion'):
            self.get_logger().error(
                f"Invalid parameter 'type': {self.type}. "
                "Use 'action' or 'motion'."
            )
            return False

        if self.type == 'motion' and not self.motion:
            self.get_logger().error(
                "Parameter 'motion' must be set when type=motion."
            )
            return False

        return True

    def wait_for_service(self, client, service_name: str):
        while not client.wait_for_service(timeout_sec=2.0):
            if not rclpy.ok():
                return
            self.get_logger().info(f'Service unavailable, waiting: {service_name}')
        self.get_logger().info(f'Service available: {service_name}')

    def wait_for_services(self):
        """Check only the necessary services based on the operation type."""
        # GetMcAction is required for both types to query the current state
        self.wait_for_service(self.get_client, '/aimdk_5Fmsgs/srv/GetMcAction')

        if self.type == 'motion':
            self.wait_for_service(self.set_motion_client, '/aimdk_5Fmsgs/srv/SetMcMotion')

    def set_motion(self, motion_name: str) -> bool:
        try:
            max_attempts = 5
            request_timeout_sec = 1.0

            for attempt in range(1, max_attempts + 1):
                request = SetMcMotion.Request()
                request.header = RequestHeader()
                request.header.stamp = self.get_clock().now().to_msg()
                request.source = 'set_mc_action'
                request.motion = motion_name
                request.type = SetMcMotion.Request.MIMIC_QY
                request.interrupt = False

                self.get_logger().info(
                    'Sending SetMcMotion request '
                    f'({attempt}/{max_attempts}): motion={motion_name} '
                    'interrupt=False'
                )

                future = self.set_motion_client.call_async(request)
                rclpy.spin_until_future_complete(
                    self, future, timeout_sec=request_timeout_sec
                )

                if not future.done():
                    self.get_logger().warning(
                        'SetMcMotion request attempt '
                        f'{attempt}/{max_attempts} failed or timed out.'
                    )
                    continue

                response = future.result()
                if response is None:
                    self.get_logger().warning(
                        'SetMcMotion request attempt '
                        f'{attempt}/{max_attempts} failed or timed out.'
                    )
                    continue

                code = response.response.header.code
                state = response.response.state.value
                task_id = response.response.task_id

                if code == 0 and state in (
                    CommonState.SUCCESS,
                    CommonState.RUNNING,
                ):
                    self.get_logger().info(
                        'SetMcMotion request accepted by service: '
                        f'code={code} state={state} task_id={task_id}'
                    )
                    return True

                self.get_logger().warning(
                    'SetMcMotion request attempt '
                    f'{attempt}/{max_attempts} was not accepted: '
                    f'code={code} state={state} task_id={task_id}'
                )

            self.get_logger().error(
                f'Failed to set motion after {max_attempts} attempts.'
            )
            return False
        except Exception as e:
            self.get_logger().error(f'Exception occurred: {e}')
            return False

    def wait_for_motion(
        self,
        timeout_sec: float = 10.0,
        poll_interval_sec: float = 0.2,
    ) -> bool:
        deadline = time.monotonic() + timeout_sec

        self.get_logger().info(
            'Waiting for current motion action to reach RUNNING state...'
        )

        while rclpy.ok() and time.monotonic() < deadline:
            action_id, action_desc, status = self.get_action_status()
            if action_desc is None or status is None:
                time.sleep(poll_interval_sec)
                continue

            if status == McActionStatus.RUNNING:
                self.get_logger().info(
                    'Current motion action is running: '
                    f'action_id={action_id} action_desc={action_desc} '
                    f'status={status}'
                )
                return True

            time.sleep(poll_interval_sec)

        self.get_logger().error(
            'Timed out waiting for current motion action to reach RUNNING state.'
        )
        return False

    def get_action_status(self):
        try:
            request = GetMcAction.Request()
            request.request = CommonRequest()
            request.request.header.stamp = self.get_clock().now().to_msg()

            future = self.call_service_with_retry(
                self.get_client, request, "GetMcAction"
            )
            if future is None:
                self.get_logger().warning(
                    'Get current action request service call failed or timed out.'
                )
                return None, None, None

            response = future.result()
            if response is None:
                self.get_logger().warning(
                    'Get current action request service call failed or timed out.'
                )
                return None, None, None

            return (
                response.info.current_action.value,
                response.info.action_desc,
                response.info.status.value,
            )
        except Exception as e:
            self.get_logger().error(f'Exception occurred: {e}')
            return None, None, None


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        node = SetMcActionClient()
        ok = node.execute()

        node.destroy_node()
        node = None
        if rclpy.ok():
            rclpy.shutdown()
        return 0 if ok else 1
    except KeyboardInterrupt:
        if node is not None:
            node.destroy_node()
            node = None
        if rclpy.ok():
            rclpy.shutdown()
        return 0
    except Exception as e:
        rclpy.logging.get_logger('main').error(
            f'Program exited with exception: {e}'
        )
        if node is not None:
            node.destroy_node()
            node = None
        if rclpy.ok():
            rclpy.shutdown()
        return 1


if __name__ == '__main__':
    raise SystemExit(main())

代码示例

速度控制(Topic: /aima/mc/locomotion/velocity) ​

速度控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp mc_locomotion_velocity

cpp
/*
 MC Locomotion Velocity Control Example Script
 
 Description:
   This script demonstrates how to control robot walking/running velocity via the /aima/mc/locomotion/velocity topic.
   Supports forward/backward, lateral, and angular velocity control with automatic state machine transitions.
 
 Prerequisites:
   - Robot must be in a safe environment for locomotion testing
   - MC (Motion Control) service must be running
   - McActionSwitcher plans and performs the transition to BIPED_WALK_RUN
   - Input source registration with priority 80
 
 Usage:
   ros2 run aimdk_examples_cpp mc_locomotion_velocity
   At very low speeds or near velocity limits, the control system may trigger balance compensation, causing
   unexpected motion. Avoid issuing commands in this range.
 
 Example:
   ros2 run aimdk_examples_cpp mc_locomotion_velocity
 
 Parameters:
   - forward_velocity: Forward/backward velocity in m/s (positive=forward, negative=backward)
   - lateral_velocity: Left/right lateral velocity in m/s (positive=left, negative=right)
   - angular_velocity: Rotation velocity in rad/s (positive=left, negative=right)
 */
#include "aimdk_msgs/msg/mc_locomotion_velocity.hpp"
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/message_header.hpp"
#include "aimdk_msgs/srv/get_current_input_source.hpp"
#include "aimdk_msgs/srv/set_mc_input_source.hpp"
#include "mc_action_switcher.hpp"

#include "rclcpp/rclcpp.hpp"
#include <cmath>
#include <chrono>
#include <iostream>
#include <memory>
#include <signal.h>
#include <thread>

constexpr double kServiceCallTimeoutSec = 3.0;
constexpr int kMaxRetryCount = 3;

class DirectVelocityControl : public rclcpp::Node {
public:
  DirectVelocityControl() : Node("direct_velocity_control") {
    // Create publisher
    publisher_ = this->create_publisher<aimdk_msgs::msg::McLocomotionVelocity>(
        "/aima/mc/locomotion/velocity", 10);
    // Create service clients
    set_client_ = this->create_client<aimdk_msgs::srv::SetMcInputSource>(
        "/aimdk_5Fmsgs/srv/SetMcInputSource");
    get_client_ = this->create_client<aimdk_msgs::srv::GetCurrentInputSource>(
        "/aimdk_5Fmsgs/srv/GetCurrentInputSource");
    // Minimum speed limits (0 is also OK)
    min_forward_speed_ = 0.2; // m/s
    min_lateral_speed_ = 0.2; // m/s
    min_angular_speed_ = 0.2; // rad/s

    RCLCPP_INFO(this->get_logger(), "Direct velocity control node started.");
  }

  void start_publish() {
    if (timer_ != nullptr) {
      return;
    }
    // Set timer to periodically publish velocity messages (50Hz)
    timer_ = this->create_wall_timer(
        std::chrono::milliseconds(20),
        std::bind(&DirectVelocityControl::publish_velocity, this));
  }

  // Generic retry function for service calls
  template <typename ServiceT>
  typename rclcpp::Client<ServiceT>::SharedFuture
  call_service_with_retry(
      typename rclcpp::Client<ServiceT>::SharedPtr client,
      typename ServiceT::Request::SharedPtr request,
      const std::string &service_name,
      std::chrono::milliseconds timeout = std::chrono::milliseconds(
          static_cast<int>(kServiceCallTimeoutSec * 1000)),
      int max_retries = kMaxRetryCount) {
    
    for (int i = 0; i < max_retries; ++i) {
      auto future = client->async_send_request(request);
      auto retcode = rclcpp::spin_until_future_complete(
          this->shared_from_this(), future, timeout);

      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        return future.future.share();
      }

      RCLCPP_INFO(this->get_logger(),
                  "%s attempt %d/%d timed out, retrying...",
                  service_name.c_str(), i + 1, max_retries);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    RCLCPP_ERROR(this->get_logger(),
                 "%s failed after %d attempts",
                 service_name.c_str(), max_retries);
    return typename rclcpp::Client<ServiceT>::SharedFuture();
  }

  bool register_input_source() {
    if (!wait_for_service(set_client_, "/aimdk_5Fmsgs/srv/SetMcInputSource")) {
      return false;
    }
  
    // 先清理残留的同名输入源(上次运行可能未正常释放)
    auto del_request =
        std::make_shared<aimdk_msgs::srv::SetMcInputSource::Request>();
    del_request->action.value = 1003;  // INPUTACTION_DELETE
    del_request->input_source.name = "node";
    del_request->request.header.stamp = this->now();
    auto del_future = call_service_with_retry<aimdk_msgs::srv::SetMcInputSource>(
        set_client_, del_request, "SetMcInputSource(DELETE)");
    if (del_future.valid()) {
      auto del_resp = del_future.get();
      if (del_resp->response.header.code == 0) {
        RCLCPP_INFO(this->get_logger(), "Cleaned up leftover input source 'node'");
      }
    }
  
    auto request =
        std::make_shared<aimdk_msgs::srv::SetMcInputSource::Request>();
    request->action.value = 1001;  // INPUTACTION_ADD
    request->input_source.name = "node";
    request->input_source.priority = 80;
    request->input_source.timeout = 1000;
  
    request->request.header.stamp = this->now();
    auto future = call_service_with_retry<aimdk_msgs::srv::SetMcInputSource>(
        set_client_, request, "SetMcInputSource(ADD)");
  
    if (!future.valid()) {
      RCLCPP_ERROR(this->get_logger(), "SetMcInputSource(ADD) failed after retries");
      return false;
    }
  
    auto response = future.get();
    int ret_code = response->response.header.code;
    if (ret_code != 0) {
      RCLCPP_WARN(this->get_logger(),
                  "SetMcInputSource(ADD) returned code=%d", ret_code);
      return false;
    }
    int state = response->response.state.value;
    RCLCPP_INFO(this->get_logger(),
                "Set input source succeeded: state=%d, task_id=%lu", state,
                response->response.task_id);
    return true;
  }

  bool get_current_input_source() {
    if (!wait_for_service(get_client_, "/aimdk_5Fmsgs/srv/GetCurrentInputSource")) {
      return false;
    }

    RCLCPP_INFO(this->get_logger(), "Querying current input source");

    auto request =
        std::make_shared<aimdk_msgs::srv::GetCurrentInputSource::Request>();
    request->request = aimdk_msgs::msg::CommonRequest();
    request->request.header.stamp = this->now();

    auto future = call_service_with_retry<aimdk_msgs::srv::GetCurrentInputSource>(
        get_client_, request, "GetCurrentInputSource");
    
    if (!future.valid()) {
      RCLCPP_WARN(this->get_logger(), "GetCurrentInputSource failed after retries");
      return false;
    }

    auto response = future.get();
    if (response->response.header.code == 0) {
      RCLCPP_INFO(this->get_logger(),
                  "Current input source: name=%s, priority=%d, timeout=%d",
                  response->input_source.name.c_str(),
                  response->input_source.priority,
                  response->input_source.timeout);
      return true;
    }

    RCLCPP_WARN(this->get_logger(), "GetCurrentInputSource returned code=%ld",
                response->response.header.code);
    return false;
  }

  void publish_velocity() {
    auto msg = std::make_unique<aimdk_msgs::msg::McLocomotionVelocity>();
    msg->header = aimdk_msgs::msg::MessageHeader();
    msg->header.stamp = this->now();
    msg->source = "node"; // Set message source
    msg->forward_velocity = forward_velocity_;
    msg->lateral_velocity = lateral_velocity_;
    msg->angular_velocity = angular_velocity_;
    msg->pitch_velocity = 0.0;
    msg->level = 0.0;

    publisher_->publish(std::move(msg));
  }

  void clear_velocity() {
    forward_velocity_ = 0.0;
    lateral_velocity_ = 0.0;
    angular_velocity_ = 0.0;
  }

  bool set_forward(double forward) {
    if (std::abs(forward) < 0.005) {
      forward_velocity_ = 0.0;
      return true;
    } else if (std::abs(forward) < min_forward_speed_) {
      RCLCPP_ERROR(this->get_logger(), "input value out of range, exiting");
      return false;
    } else {
      forward_velocity_ = forward;
      return true;
    }
  }

  bool set_lateral(double lateral) {
    if (std::abs(lateral) < 0.005) {
      lateral_velocity_ = 0.0;
      return true;
    } else if (std::abs(lateral) < min_lateral_speed_) {
      RCLCPP_ERROR(this->get_logger(), "input value out of range, exiting");
      return false;
    } else {
      lateral_velocity_ = lateral;
      return true;
    }
  }

  bool set_angular(double angular) {
    if (std::abs(angular) < 0.005) {
      angular_velocity_ = 0.0;
      return true;
    } else if (std::abs(angular) < min_angular_speed_) {
      RCLCPP_ERROR(this->get_logger(), "input value out of range, exiting");
      return false;
    } else {
      angular_velocity_ = angular;
      return true;
    }
  }

  bool ensure_ready_state() {
    aimdk_examples::McActionSwitcher switcher(this->shared_from_this());
    aimdk_examples::McActionSwitchOptions options;
    options.source = "locomotion_velocity_node";
    options.total_timeout = std::chrono::seconds(30);

    const auto result = switcher.switch_to("BIPED_WALK_RUN", options);
    if (!result.success) {
      RCLCPP_ERROR(this->get_logger(),
                   "Failed to switch from %s to BIPED_WALK_RUN: %s",
                   result.current_action.empty() ? "(unknown)"
                                                 : result.current_action.c_str(),
                   result.message.c_str());
    }
    return result.success;
  }

  bool release_input_source() {
    auto request =
        std::make_shared<aimdk_msgs::srv::SetMcInputSource::Request>();
    request->action.value = 1003;  // INPUTACTION_DELETE
    request->input_source.name = "node";
    request->request.header.stamp = this->now();

    auto future = call_service_with_retry<aimdk_msgs::srv::SetMcInputSource>(
        set_client_, request, "SetMcInputSource");

    if (!future.valid()) {
      RCLCPP_ERROR(this->get_logger(), "ReleaseInputSource failed after retries");
      return false;
    }

    auto response = future.get();
    int ret_code = response->response.header.code;
    if (ret_code == 0) {
      RCLCPP_INFO(this->get_logger(), "Input source released successfully.");
      return true;
    }

    RCLCPP_WARN(this->get_logger(),
                "SetMcInputSource returned code=%d", ret_code);
    return false;
  }

  void wait_for_services() {
    auto wait = [this](auto &client, const std::string &name) {
      while (!client->wait_for_service(std::chrono::seconds(2))) {
        if (!rclcpp::ok())
          return;
        RCLCPP_INFO(this->get_logger(), "Waiting for service %s...",
                    name.c_str());
      }
    };
    wait(set_client_, "/aimdk_5Fmsgs/srv/SetMcInputSource");
    wait(get_client_, "/aimdk_5Fmsgs/srv/GetCurrentInputSource");
  }

private:
  template <typename ClientT>
  bool wait_for_service(const std::shared_ptr<ClientT> &client,
                        const char *service_name) {
    while (!client->wait_for_service(std::chrono::seconds(2))) {
      if (!rclcpp::ok()) {
        return false;
      }
      RCLCPP_INFO(this->get_logger(), "Waiting for service: %s", service_name);
    }
    return true;
  }

  rclcpp::Publisher<aimdk_msgs::msg::McLocomotionVelocity>::SharedPtr
      publisher_;
  rclcpp::Client<aimdk_msgs::srv::SetMcInputSource>::SharedPtr set_client_;
  rclcpp::Client<aimdk_msgs::srv::GetCurrentInputSource>::SharedPtr get_client_;
  rclcpp::TimerBase::SharedPtr timer_;

  double forward_velocity_;
  double lateral_velocity_;
  double angular_velocity_;

  double min_forward_speed_;
  double min_lateral_speed_;
  double min_angular_speed_;
};

std::shared_ptr<DirectVelocityControl> g_node = nullptr;

void signal_handler(int signal) {
  if (g_node) {
    g_node->clear_velocity();
    g_node->release_input_source();
    RCLCPP_INFO(g_node->get_logger(),
                "Received signal %d, clearing velocity, releasing input source and shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

int main(int argc, char *argv[]) {
  rclcpp::init(argc, argv);
  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);

  g_node = std::make_shared<DirectVelocityControl>();
  auto node = g_node;

  node->wait_for_services();

  // Step 1: Ensure the robot is in BIPED_WALK_RUN state
  if (!node->ensure_ready_state()) {
    RCLCPP_ERROR(node->get_logger(), "Failed to prepare robot state for walking.");
    g_node.reset();
    rclcpp::shutdown();
    return 1;
  }

  // Step 2: Register input source
  if (!node->register_input_source()) {
    RCLCPP_ERROR(node->get_logger(),
                 "Input source registration failed, exiting");
    g_node.reset();
    rclcpp::shutdown();
    return 1;
  }

  // get and check control values
  // notice that mc has thresholds to start movement
  double forward, lateral, angular;
  std::cout << "Enter forward speed 0 or |v| >= 0.2 m/s: ";
  std::cin >> forward;
  if (!node->set_forward(forward)) {
    return 2;
  }
  std::cout << "Enter lateral speed 0 or |v| >= 0.2 m/s: ";
  std::cin >> lateral;
  if (!node->set_lateral(lateral)) {
    return 2;
  }
  std::cout << "Enter angular speed 0 or |v| >= 0.2 rad/s: ";
  std::cin >> angular;
  if (!node->set_angular(angular)) {
    return 2;
  }

  RCLCPP_INFO(node->get_logger(),
              "Start publishing velocity for 5 seconds: Forward %.2f m/s, "
              "Lateral %.2f m/s, Angular %.2f rad/s",
              forward, lateral, angular);

  node->start_publish();

  auto start_time = node->now();
  bool queried_after_publish = false;
  while ((node->now() - start_time).seconds() < 5.0) {
    if (!queried_after_publish &&
        (node->now() - start_time).seconds() > 1.0) {
      node->get_current_input_source();
      queried_after_publish = true;
    }
    rclcpp::spin_some(node);
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }

  node->clear_velocity();
  node->publish_velocity();
  RCLCPP_INFO(node->get_logger(), "5 seconds elapsed; robot stopped");

  // Step 6: Release input source
  node->release_input_source();

  g_node.reset();
  rclcpp::shutdown();
  return 0;
}
速度控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/mc_locomotion_velocity.py

python
#!/usr/bin/env python3

"""
Example client for /aima/mc/locomotion/velocity.

This script automatically handles the required state machine transitions for
safety. Locomotion control (walking/running) requires the robot to be in
BIPED_WALK_RUN mode.

Prerequisites auto-handled by this script:
  The shared MC action switcher plans a supported route from the current state
  to BIPED_WALK_RUN and waits for every intermediate action.

Flow:
  1. Detect current state and transition to BIPED_WALK_RUN.
  2. Register this node as an authorized input source (priority 80).
  3. Prompt the user for target velocities.
  4. Publish velocity commands for 5 seconds.
  5. Stop the robot by sending zero velocity.

Usage:
  python3 examples/python/mc_locomotion_velocity.py
"""

import signal
import time

import rclpy
from rclpy.node import Node

from aimdk_msgs.msg import (
    CommonRequest, McLocomotionVelocity, MessageHeader
)
from aimdk_msgs.srv import GetCurrentInputSource, SetMcInputSource

from common.mc_action_switcher import McActionSwitchOptions, McActionSwitcher

SERVICE_CALL_TIMEOUT_SEC = 3.0
MAX_RETRY_COUNT = 3


class DirectVelocityControl(Node):
    def __init__(self):
        super().__init__("direct_velocity_control")

        self.publisher = self.create_publisher(
            McLocomotionVelocity, "/aima/mc/locomotion/velocity", 10
        )
        self.set_client = self.create_client(
            SetMcInputSource, "/aimdk_5Fmsgs/srv/SetMcInputSource"
        )
        self.get_client = self.create_client(
            GetCurrentInputSource, "/aimdk_5Fmsgs/srv/GetCurrentInputSource"
        )
        self.forward_velocity = 0.0
        self.lateral_velocity = 0.0
        self.angular_velocity = 0.0

        self.min_forward_speed = 0.2
        self.min_lateral_speed = 0.2
        self.min_angular_speed = 0.2

        self.timer = None

        self.get_logger().info("Direct velocity control node started.")

    def wait_for_service(self, client, service_name: str) -> bool:
        while not client.wait_for_service(timeout_sec=2.0):
            if not rclpy.ok():
                return False
            self.get_logger().info(f"Waiting for service: {service_name}")
        return True

    def wait_for_services(self) -> bool:
        clients = [
            (self.publisher, "/aima/mc/locomotion/velocity"),
            (self.set_client, "/aimdk_5Fmsgs/srv/SetMcInputSource"),
            (self.get_client, "/aimdk_5Fmsgs/srv/GetCurrentInputSource"),
        ]
        for client, name in clients:
            if hasattr(client, 'wait_for_service'):
                if not self.wait_for_service(client, name):
                    return False
        return True

    def call_service_with_retry(self, client, request, service_name: str, timeout_sec=None, max_retries=None):
        if timeout_sec is None:
            timeout_sec = SERVICE_CALL_TIMEOUT_SEC
        if max_retries is None:
            max_retries = MAX_RETRY_COUNT
            
        for i in range(max_retries):
            future = client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=timeout_sec)

            if future.done():
                return future

            self.get_logger().info(f'{service_name} attempt {i+1}/{max_retries} timed out, retrying...')
            time.sleep(0.2)
        
        self.get_logger().error(f'{service_name} failed after {max_retries} attempts')
        return None

    def ensure_ready_state(self) -> bool:
        switcher = McActionSwitcher(self)
        options = McActionSwitchOptions(
            source="locomotion_velocity_node",
            total_timeout=30.0,
        )
        result = switcher.switch_to("BIPED_WALK_RUN", options)
        if not result.success:
            current_action = result.current_action or "(unknown)"
            self.get_logger().error(
                "Failed to switch from "
                f"{current_action} to BIPED_WALK_RUN: {result.message}"
            )
        return result.success

    def start_publish(self):
        if self.timer is None:
            self.timer = self.create_timer(0.02, self.publish_velocity)

    def register_input_source(self) -> bool:
        # Register the input source before publishing velocity.
        if not self.wait_for_service(
            self.set_client, "/aimdk_5Fmsgs/srv/SetMcInputSource"
        ):
            return False

        # 先清理残留的同名输入源(上次运行可能未正常释放)
        del_request = SetMcInputSource.Request()
        del_request.action.value = 1003  # INPUTACTION_DELETE
        del_request.input_source.name = "node"
        del_request.request.header.stamp = self.get_clock().now().to_msg()
        del_future = self.call_service_with_retry(
            self.set_client, del_request, "SetMcInputSource(DELETE)"
        )
        if del_future is not None:
            try:
                del_resp = del_future.result()
                if del_resp.response.header.code == 0:
                    self.get_logger().info("Cleaned up leftover input source 'node'")
            except Exception:
                pass

        request = SetMcInputSource.Request()
        request.action.value = 1001  # INPUTACTION_ADD
        request.input_source.name = "node"
        request.input_source.priority = 80
        request.input_source.timeout = 1000
        request.request.header.stamp = self.get_clock().now().to_msg()

        future = self.call_service_with_retry(
            self.set_client, request, "SetMcInputSource(ADD)"
        )
        if future is None:
            return False

        try:
            response = future.result()
        except Exception as exc:
            self.get_logger().error(f"SetMcInputSource failed: {exc}")
            return False

        ret_code = response.response.header.code
        state = response.response.state.value
        task_id = response.response.task_id

        if ret_code == 0:
            self.get_logger().info(
                "Set input source succeeded: "
                f"code={ret_code}, state={state}, task_id={task_id}"
            )
            return True

        self.get_logger().warning(
            "SetMcInputSource returned "
            f"code={ret_code}, state={state}, task_id={task_id}"
        )
        return False

    def get_current_input_source(self) -> bool:
        if not self.wait_for_service(
            self.get_client, "/aimdk_5Fmsgs/srv/GetCurrentInputSource"
        ):
            return False

        self.get_logger().info("Querying current input source")

        request = GetCurrentInputSource.Request()
        request.request = CommonRequest()
        request.request.header.stamp = self.get_clock().now().to_msg()

        future = self.call_service_with_retry(
            self.get_client, request, "GetCurrentInputSource"
        )
        if future is None:
            return False

        try:
            response = future.result()
        except Exception as exc:
            self.get_logger().warning(f"GetCurrentInputSource failed: {exc}")
            return False

        ret_code = response.response.header.code
        if ret_code == 0:
            self.get_logger().info(
                "Current input source: "
                f"name={response.input_source.name}, "
                f"priority={response.input_source.priority}, "
                f"timeout={response.input_source.timeout}"
            )
            return True

        self.get_logger().warning(
            f"GetCurrentInputSource returned code={ret_code}"
        )
        return False

    def publish_velocity(self):
        msg = McLocomotionVelocity()
        msg.header = MessageHeader()
        msg.header.stamp = self.get_clock().now().to_msg()
        # source must match the registered input-source name.
        msg.source = "node"
        msg.forward_velocity = self.forward_velocity
        msg.lateral_velocity = self.lateral_velocity
        msg.angular_velocity = self.angular_velocity
        msg.pitch_velocity = 0.0
        msg.level = 0.0

        self.publisher.publish(msg)

    def clear_velocity(self):
        self.forward_velocity = 0.0
        self.lateral_velocity = 0.0
        self.angular_velocity = 0.0

    def set_forward(self, forward: float) -> bool:
        if abs(forward) < 0.005:
            self.forward_velocity = 0.0
            return True
        if abs(forward) < self.min_forward_speed:
            self.get_logger().error("Input forward value out of range, exiting")
            return False
        self.forward_velocity = forward
        return True

    def set_lateral(self, lateral: float) -> bool:
        if abs(lateral) < 0.005:
            self.lateral_velocity = 0.0
            return True
        if abs(lateral) < self.min_lateral_speed:
            self.get_logger().error("Input lateral value out of range, exiting")
            return False
        self.lateral_velocity = lateral
        return True

    def set_angular(self, angular: float) -> bool:
        if abs(angular) < 0.005:
            self.angular_velocity = 0.0
            return True
        if abs(angular) < self.min_angular_speed:
            self.get_logger().error("Input angular value out of range, exiting")
            return False
        self.angular_velocity = angular
        return True

    def release_input_source(self) -> bool:
        request = SetMcInputSource.Request()
        request.action.value = 1003
        request.input_source.name = "node"
        request.request.header.stamp = self.get_clock().now().to_msg()

        future = self.call_service_with_retry(
            self.set_client, request, "SetMcInputSource"
        )
        if future is None:
            return False

        try:
            response = future.result()
        except Exception as exc:
            self.get_logger().error(f"SetMcInputSource failed: {exc}")
            return False

        ret_code = response.response.header.code

        if ret_code == 0:
            self.get_logger().info("Input source released successfully.")
            return True

        self.get_logger().warning(f"SetMcInputSource returned code={ret_code}")
        return False

def main(args=None):
    rclpy.init(args=args)
    # init 之后立即覆盖 ROS2 的 SIGINT 处理器
    # 阻止 Ctrl+C 触发 rclpy.shutdown(),保持上下文有效以释放输入源
    def _sigint_handler(sig, frame):
        raise KeyboardInterrupt
    signal.signal(signal.SIGINT, _sigint_handler)

    node = DirectVelocityControl()
    input_source_registered = False

    try:
        if not node.wait_for_services():
            return 1

        # Step 1: Ensure the robot is in BIPED_WALK_RUN state
        if not node.ensure_ready_state():
            node.get_logger().error("Failed to prepare robot state for walking.")
            return 1

        # Step 2: Register input source
        if not node.register_input_source():
            node.get_logger().error("Input source registration failed, exiting")
            return 1
        input_source_registered = True

        # Input speed must be 0, or have an absolute value at least the minimum threshold.
        try:
            print("\nEnter control velocities (forward and lateral in m/s, angular in rad/s):")
            forward = float(input("Enter forward speed 0 or |v| >= 0.2 m/s: "))
            lateral = float(input("Enter lateral speed 0 or |v| >= 0.2 m/s: "))
            angular = float(input("Enter angular speed 0 or |v| >= 0.2 rad/s: "))
        except ValueError as exc:
            node.get_logger().error(f"Invalid input: {exc}")
            return 2

        if not node.set_forward(forward):
            return 2
        if not node.set_lateral(lateral):
            return 2
        if not node.set_angular(angular):
            return 2

        node.get_logger().info(
            "Start publishing velocity for 5 seconds: "
            f"Forward {forward:.2f} m/s, "
            f"Lateral {lateral:.2f} m/s, "
            f"Angular {angular:.2f} rad/s"
        )

        node.start_publish()

        start_time = node.get_clock().now()
        queried_after_publish = False
        while (node.get_clock().now() - start_time).nanoseconds / 1e9 < 5.0:
            elapsed = (node.get_clock().now() - start_time).nanoseconds / 1e9
            if not queried_after_publish and elapsed > 1.0:
                node.get_current_input_source()
                queried_after_publish = True

            rclpy.spin_once(node, timeout_sec=0.1)
            time.sleep(0.1)

        node.clear_velocity()
        # Ensure zero velocity is published
        node.publish_velocity()
        node.get_logger().info("5 seconds elapsed; robot stopped")
        node.release_input_source()
        input_source_registered = False
        return 0
    finally:
        if input_source_registered:
            node.get_logger().info("Releasing input source on exit...")
            node.release_input_source()
        if node.timer is not None:
            node.timer.cancel()
        node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

自定义上肢关节控制(Topic: /aima/mc/custom/joint/command) ​

自定义上肢关节控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件,保持 MC 运行;示例会自动将机器人切换至 BIPED_CUSTOM_UPPER。

运行命令:ros2 run aimdk_examples_cpp upper_body_control

cpp
/**
 * Q1 Upper Body Control Example
 *
 * Description:
 *   Demonstrates how to publish upper-body joint commands to
 *   /aima/mc/custom/joint/command with aimdk_msgs/msg/McCustomJointCommand.
 *
 * Prerequisites:
 *   - MC must stay running. Do not disable the robot motion control module.
 *   - Robot must be in a safe environment for motion testing.
 *   - McActionSwitcher will transition to BIPED_CUSTOM_UPPER before publishing commands.
 *
 * Usage:
 *   ros2 run aimdk_examples_cpp upper_body_control
 */

#include "aimdk_msgs/msg/joint_command.hpp"
#include "aimdk_msgs/msg/mc_custom_joint_command.hpp"
#include "mc_action_switcher.hpp"
#include "rclcpp/rclcpp.hpp"

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <map>
#include <memory>
#include <string>
#include <thread>

namespace {

constexpr double kPublishRateHz = 100.0;
constexpr double kDefaultStiffness = 20.0;
constexpr double kDefaultDamping = 3.0;
constexpr double kPi = 3.14159265358979323846;

const std::array<std::string, 10> kJointNames = {
    "waist_roll_joint",
    "waist_yaw_joint",
    "left_shoulder_pitch_joint",
    "left_shoulder_roll_joint",
    "left_shoulder_yaw_joint",
    "left_elbow_joint",
    "right_shoulder_pitch_joint",
    "right_shoulder_roll_joint",
    "right_shoulder_yaw_joint",
    "right_elbow_joint",
};

const std::array<double, 10> kDefaultStandPositions = {
    -0.01982023485863345,
    -0.00021580613966982196,
    0.017233758101518008,
    0.22511493021261703,
    -0.003530979547924497,
    1.0186741542682025,
    0.017164215358473386,
    -0.22262401216020816,
    0.004204617106736518,
    1.0185279282650144,
};

std::atomic_bool g_stop{false};

void signal_handler(int)
{
  g_stop.store(true);
}

double smooth_step(double t)
{
  t = std::clamp(t, 0.0, 1.0);
  return 0.5 - 0.5 * std::cos(kPi * t);
}

}  // namespace

class UpperBodyControlNode : public rclcpp::Node
{
 public:
  UpperBodyControlNode() : Node("upper_body_control")
  {
    auto qos = rclcpp::QoS(rclcpp::KeepLast(10));
    qos.best_effort();
    qos.durability_volatile();

    command_pub_ =
        this->create_publisher<aimdk_msgs::msg::McCustomJointCommand>(
            "/aima/mc/custom/joint/command", qos);

    initialize_command_message();

    RCLCPP_INFO(
        this->get_logger(),
        "upper_body_control started. Make sure MC is running. The robot "
        "will auto-transition to BIPED_CUSTOM_UPPER before publishing commands.");
  }

  bool switch_to_custom_upper()
  {
    aimdk_examples::McActionSwitcher switcher(this->shared_from_this());
    aimdk_examples::McActionSwitchOptions options;
    options.source = "upper_body_control";
    options.total_timeout = std::chrono::seconds(30);

    const auto result = switcher.switch_to("BIPED_CUSTOM_UPPER", options);
    if (!result.success) {
      RCLCPP_ERROR(this->get_logger(),
                   "Failed to switch from %s to BIPED_CUSTOM_UPPER: %s",
                   result.current_action.empty() ? "(unknown)"
                                                 : result.current_action.c_str(),
                   result.message.c_str());
    }
    return result.success;
  }

  bool run_demo()
  {
    const auto stand = default_stand_positions();

    const auto wave_start = wave_pose(stand, 0.0);
    RCLCPP_INFO(this->get_logger(), "Extending right arm smoothly.");
    if (!publish_interpolation(stand, wave_start, 2.0)) {
      return false;
    }

    RCLCPP_INFO(this->get_logger(),
                "Running a small upper-body demo motion.");
    if (!publish_wave_motion(stand, 4.0)) {
      return false;
    }

    RCLCPP_INFO(this->get_logger(),
                "Returning to default upper posture.");
    if (!publish_interpolation(current_demo_pose_, stand, 2.0)) {
      return false;
    }

    return true;
  }

  void publish_default_for_shutdown()
  {
    publish_hold(default_stand_positions(), 1.0);
  }

 private:
  using Pose = std::map<std::string, double>;

  Pose default_stand_positions() const
  {
    Pose pose;
    for (size_t i = 0; i < kJointNames.size(); ++i) {
      pose[kJointNames[i]] = kDefaultStandPositions[i];
    }
    return pose;
  }

  Pose interpolate_pose(const Pose &from, const Pose &to, double alpha) const
  {
    Pose pose;
    const double s = smooth_step(alpha);
    for (const auto &name : kJointNames) {
      const double start = from.at(name);
      const double target = to.at(name);
      pose[name] = start + (target - start) * s;
    }
    return pose;
  }

  Pose wave_pose(const Pose &base, double t) const
  {
    Pose pose = base;
    pose["right_shoulder_pitch_joint"] = -0.25;
    pose["right_shoulder_roll_joint"] = -0.55;
    pose["right_elbow_joint"] = 1.10;
    pose["right_shoulder_yaw_joint"] =
        0.30 * std::sin(2.0 * kPi * 1.5 * t);
    return pose;
  }

  bool publish_interpolation(const Pose &from, const Pose &to,
                             double duration_s)
  {
    const int total_steps =
        std::max(1, static_cast<int>(duration_s * kPublishRateHz));
    auto next_tick = std::chrono::steady_clock::now();
    for (int step = 0; rclcpp::ok() && !g_stop.load() && step <= total_steps;
         ++step) {
      const double alpha =
          static_cast<double>(step) / static_cast<double>(total_steps);
      current_demo_pose_ = interpolate_pose(from, to, alpha);
      publish_pose(current_demo_pose_);
      next_tick = sleep_to_next_tick(next_tick);
    }
    return rclcpp::ok() && !g_stop.load();
  }

  bool publish_wave_motion(const Pose &base, double duration_s)
  {
    const int total_steps =
        std::max(1, static_cast<int>(duration_s * kPublishRateHz));
    auto next_tick = std::chrono::steady_clock::now();
    for (int step = 0; rclcpp::ok() && !g_stop.load() && step <= total_steps;
         ++step) {
      const double t =
          static_cast<double>(step) / static_cast<double>(total_steps);
      current_demo_pose_ = wave_pose(base, t);
      publish_pose(current_demo_pose_);
      next_tick = sleep_to_next_tick(next_tick);
    }
    return rclcpp::ok() && !g_stop.load();
  }

  bool publish_hold(const Pose &pose, double duration_s)
  {
    const int total_steps =
        std::max(1, static_cast<int>(duration_s * kPublishRateHz));
    auto next_tick = std::chrono::steady_clock::now();
    for (int step = 0; rclcpp::ok() && !g_stop.load() && step < total_steps;
         ++step) {
      publish_pose(pose);
      next_tick = sleep_to_next_tick(next_tick);
    }
    return rclcpp::ok();
  }

  std::chrono::steady_clock::time_point sleep_to_next_tick(
      std::chrono::steady_clock::time_point next_tick)
  {
    const auto now = std::chrono::steady_clock::now();
    if (next_tick > now) {
      std::this_thread::sleep_until(next_tick);
    }
    return next_tick +
           std::chrono::duration_cast<std::chrono::steady_clock::duration>(
               std::chrono::duration<double>(1.0 / kPublishRateHz));
  }

  void initialize_command_message()
  {
    command_msg_.joints.resize(kJointNames.size());

    for (size_t i = 0; i < kJointNames.size(); ++i) {
      auto &joint = command_msg_.joints[i];
      joint.name = kJointNames[i];
      joint.position = 0.0;
      joint.velocity = 0.0;
      joint.effort = 0.0;
      joint.stiffness = kDefaultStiffness;
      joint.damping = kDefaultDamping;
    }
  }

  void publish_pose(const Pose &pose)
  {
    command_msg_.header.stamp = this->now();
    command_msg_.header.sequence = sequence_++;

    for (size_t i = 0; i < kJointNames.size(); ++i) {
      command_msg_.joints[i].position = pose.at(kJointNames[i]);
    }

    command_pub_->publish(command_msg_);
  }

  rclcpp::Publisher<aimdk_msgs::msg::McCustomJointCommand>::SharedPtr command_pub_;
  aimdk_msgs::msg::McCustomJointCommand command_msg_;

  Pose current_demo_pose_;
  uint32_t sequence_ = 0;
};

int main(int argc, char *argv[])
{
  rclcpp::init(argc, argv);
  std::signal(SIGINT, signal_handler);
  std::signal(SIGTERM, signal_handler);

  auto node = std::make_shared<UpperBodyControlNode>();
  int ret = 0;

  try {
    if (!node->switch_to_custom_upper()) {
      ret = 1;
    } else {
      std::this_thread::sleep_for(std::chrono::seconds(1));
      if (!g_stop.load()) {
        if (!node->run_demo()) {
          ret = g_stop.load() ? 0 : 1;
        }
      }

      if (rclcpp::ok()) {
        node->publish_default_for_shutdown();
      }
    }
  } catch (const std::exception &e) {
    RCLCPP_ERROR(node->get_logger(), "Exception: %s", e.what());
    ret = 1;
  }

  node.reset();
  if (rclcpp::ok()) {
    rclcpp::shutdown();
  }
  return ret;
}
自定义上肢关节控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件,保持 MC 运行;示例会自动将机器人切换至 BIPED_CUSTOM_UPPER。

运行命令:python3 primebot_sdk/examples/python/upper_body_control.py

python
#!/usr/bin/env python3

"""
Q1 Custom Upper Control Example

Description:
  Demonstrates how to publish upper-body joint commands to
  /aima/mc/custom/joint/command with aimdk_msgs/msg/McCustomJointCommand.

Prerequisites:
  - MC must stay running. Do not disable the robot motion control module.
  - Robot must be in a safe environment for motion testing.
  - The shared action switcher will transition to BIPED_CUSTOM_UPPER before
    publishing commands.

Usage:
  python3 examples/python/upper_body_control.py
"""

import math
import signal
import time
from typing import Dict

import rclpy
from rclpy.node import Node
from rclpy.qos import DurabilityPolicy, HistoryPolicy, QoSProfile, ReliabilityPolicy

from aimdk_msgs.msg import (
    JointCommand,
    McCustomJointCommand,
)

from common.mc_action_switcher import McActionSwitchOptions, McActionSwitcher


PUBLISH_RATE_HZ = 100.0
DEFAULT_STIFFNESS = 20.0
DEFAULT_DAMPING = 3.0

JOINT_NAMES = [
    "waist_roll_joint",
    "waist_yaw_joint",
    "left_shoulder_pitch_joint",
    "left_shoulder_roll_joint",
    "left_shoulder_yaw_joint",
    "left_elbow_joint",
    "right_shoulder_pitch_joint",
    "right_shoulder_roll_joint",
    "right_shoulder_yaw_joint",
    "right_elbow_joint",
]

DEFAULT_STAND_POSITIONS = [
    -0.01982023485863345,
    -0.00021580613966982196,
    0.017233758101518008,
    0.22511493021261703,
    -0.003530979547924497,
    1.0186741542682025,
    0.017164215358473386,
    -0.22262401216020816,
    0.004204617106736518,
    1.0185279282650144,
]

g_stop = False


def signal_handler(_signum, _frame) -> None:
    global g_stop
    g_stop = True


def smooth_step(value: float) -> float:
    value = max(0.0, min(1.0, value))
    return 0.5 - 0.5 * math.cos(math.pi * value)


class CustomUpperControlNode(Node):
    def __init__(self) -> None:
        super().__init__("custom_upper_control")

        self.qos = QoSProfile(
            history=HistoryPolicy.KEEP_LAST,
            depth=10,
            reliability=ReliabilityPolicy.BEST_EFFORT,
            durability=DurabilityPolicy.VOLATILE,
        )

        self.command_pub = self.create_publisher(
            McCustomJointCommand, "/aima/mc/custom/joint/command", self.qos
        )
        self.current_demo_pose = self.default_stand_positions()
        self.sequence = 0

        self._command_msg = self._initialize_command_message()

        self.get_logger().info(
            "custom_upper_control started. Make sure MC is running. The robot "
            "will transition to BIPED_CUSTOM_UPPER before publishing commands."
        )

    def switch_to_custom_upper(self) -> bool:
        switcher = McActionSwitcher(self)
        options = McActionSwitchOptions(
            source="upper_body_control",
            total_timeout=30.0,
        )
        result = switcher.switch_to("BIPED_CUSTOM_UPPER", options)
        if not result.success:
            current_action = result.current_action or "(unknown)"
            self.get_logger().error(
                "Failed to switch from "
                f"{current_action} to BIPED_CUSTOM_UPPER: {result.message}"
            )
        return result.success

    def default_stand_positions(self) -> Dict[str, float]:
        return dict(zip(JOINT_NAMES, DEFAULT_STAND_POSITIONS))

    def interpolate_pose(
        self, start_pose: Dict[str, float], target_pose: Dict[str, float], alpha: float
    ) -> Dict[str, float]:
        ratio = smooth_step(alpha)
        return {
            name: start_pose[name] + (target_pose[name] - start_pose[name]) * ratio
            for name in JOINT_NAMES
        }

    def wave_pose(self, base_pose: Dict[str, float], t: float) -> Dict[str, float]:
        pose = dict(base_pose)
        pose["right_shoulder_pitch_joint"] = -0.25
        pose["right_shoulder_roll_joint"] = -0.55
        pose["right_elbow_joint"] = 1.10
        pose["right_shoulder_yaw_joint"] = 0.30 * math.sin(2.0 * math.pi * 1.5 * t)
        return pose

    def _initialize_command_message(self) -> McCustomJointCommand:
        msg = McCustomJointCommand()
        for name in JOINT_NAMES:
            joint = JointCommand()
            joint.name = name
            joint.position = 0.0
            joint.velocity = 0.0
            joint.effort = 0.0
            joint.stiffness = DEFAULT_STIFFNESS
            joint.damping = DEFAULT_DAMPING
            msg.joints.append(joint)
        return msg

    def publish_pose(self, pose: Dict[str, float]) -> None:
        msg = self._command_msg
        msg.header.stamp = self.get_clock().now().to_msg()
        msg.header.sequence = self.sequence
        self.sequence += 1

        for i, name in enumerate(JOINT_NAMES):
            msg.joints[i].position = pose[name]

        self.command_pub.publish(msg)

    def sleep_to_next_tick(self, next_tick: float) -> float:
        now = time.perf_counter()
        if next_tick > now:
            time.sleep(next_tick - now)
        return next_tick + 1.0 / PUBLISH_RATE_HZ

    def publish_interpolation(
        self, start_pose: Dict[str, float], target_pose: Dict[str, float], duration_s: float
    ) -> bool:
        total_steps = max(1, int(duration_s * PUBLISH_RATE_HZ))
        next_tick = time.perf_counter()
        for step in range(total_steps + 1):
            if not rclpy.ok() or g_stop:
                return False
            alpha = step / total_steps
            self.current_demo_pose = self.interpolate_pose(start_pose, target_pose, alpha)
            self.publish_pose(self.current_demo_pose)
            next_tick = self.sleep_to_next_tick(next_tick)
        return True

    def publish_wave_motion(self, base_pose: Dict[str, float], duration_s: float) -> bool:
        total_steps = max(1, int(duration_s * PUBLISH_RATE_HZ))
        next_tick = time.perf_counter()
        for step in range(total_steps + 1):
            if not rclpy.ok() or g_stop:
                return False
            t = step / total_steps
            self.current_demo_pose = self.wave_pose(base_pose, t)
            self.publish_pose(self.current_demo_pose)
            next_tick = self.sleep_to_next_tick(next_tick)
        return True

    def publish_hold(self, pose: Dict[str, float], duration_s: float) -> bool:
        total_steps = max(1, int(duration_s * PUBLISH_RATE_HZ))
        next_tick = time.perf_counter()
        for _ in range(total_steps):
            if not rclpy.ok():
                return False
            self.publish_pose(pose)
            next_tick = self.sleep_to_next_tick(next_tick)
        return True

    def run_demo(self) -> bool:
        stand_pose = self.default_stand_positions()

        wave_start = self.wave_pose(stand_pose, 0.0)
        self.get_logger().info("Extending right arm smoothly.")
        if not self.publish_interpolation(stand_pose, wave_start, 2.0):
            return False

        self.get_logger().info("Running a small upper-body demo motion.")
        if not self.publish_wave_motion(stand_pose, 4.0):
            return False

        self.get_logger().info("Returning to default upper posture.")
        if not self.publish_interpolation(self.current_demo_pose, stand_pose, 2.0):
            return False

        return True

    def publish_default_for_shutdown(self) -> None:
        self.publish_hold(self.default_stand_positions(), 1.0)


def main() -> int:
    rclpy.init()
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    node = CustomUpperControlNode()
    ret = 0

    try:
        if not node.switch_to_custom_upper():
            ret = 1
        else:
            time.sleep(1)
            if not g_stop and not node.run_demo():
                ret = 0 if g_stop else 1

            if rclpy.ok():
                node.publish_default_for_shutdown()
    finally:
        node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()

    return ret


if __name__ == "__main__":
    raise SystemExit(main())

代码示例

预设动作设置(Service: SetMcPresetMotion) ​

预设动作设置 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp set_preset_motion

cpp
/*
 Preset Motion Control Example Script
 
 Description:
   This script demonstrates how to execute preset motions (like waving or handshaking) using the SetMcPresetMotion service.
   Automatically handles state machine transitions for safe motion execution.
 
 Prerequisites:
   - MC (Motion Control) service must be running
   - Robot must be in a safe environment for motion testing
   - McActionSwitcher plans and performs the transition to BIPED_WHOLE_BODY_CTRL
 
 Usage:
   ros2 run aimdk_examples_cpp set_preset_motion
 
 Example:
   ros2 run aimdk_examples_cpp set_preset_motion
 
 Parameters:
   - None
 */
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/mc_preset_motion.hpp"
#include "aimdk_msgs/srv/set_mc_preset_motion.hpp"
#include "mc_action_switcher.hpp"
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <cctype>
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <memory>
#include <signal.h>
#include <string>
#include <thread>
#include <unordered_map>

constexpr double kServiceCallTimeoutSec = 2.0;
constexpr int kMaxRetryCount = 3;

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal) {
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class PresetMotionClient : public rclcpp::Node {
public:
  PresetMotionClient() : Node("preset_motion_client") {
    preset_client_ = this->create_client<aimdk_msgs::srv::SetMcPresetMotion>(
        "/aimdk_5Fmsgs/srv/SetMcPresetMotion");
    RCLCPP_INFO(this->get_logger(), "SetMcPresetMotion client node created.");
    wait_for_services();
  }

  // Generic retry function for service calls
  template <typename ServiceT>
  typename rclcpp::Client<ServiceT>::SharedFuture
  call_service_with_retry(
      typename rclcpp::Client<ServiceT>::SharedPtr client,
      typename ServiceT::Request::SharedPtr request,
      const std::string &service_name,
      std::chrono::milliseconds timeout = std::chrono::milliseconds(
          static_cast<int>(kServiceCallTimeoutSec * 1000)),
      int max_retries = kMaxRetryCount) {
    
    for (int i = 0; i < max_retries; ++i) {
      auto future = client->async_send_request(request);
      auto retcode = rclcpp::spin_until_future_complete(
          this->shared_from_this(), future, timeout);

      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        return future.future.share();
      }

      RCLCPP_INFO(this->get_logger(),
                  "%s attempt %d/%d timed out, retrying...",
                  service_name.c_str(), i + 1, max_retries);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    RCLCPP_ERROR(this->get_logger(),
                 "%s failed after %d attempts",
                 service_name.c_str(), max_retries);
    return typename rclcpp::Client<ServiceT>::SharedFuture();
  }

  bool send_request(int motion_id) {
    if (!ensure_ready_state()) {
      RCLCPP_ERROR(this->get_logger(),
                   "Failed to prepare robot state for preset motion.");
      return false;
    }

    try {
      auto request =
          std::make_shared<aimdk_msgs::srv::SetMcPresetMotion::Request>();
      request->header.stamp = this->now();
      request->source = "sdk_rpc";
      request->motion.value = motion_id;
      request->interrupt = true;

      RCLCPP_INFO(this->get_logger(),
                  "Sending preset motion request: ID=%d", motion_id);

      auto future = call_service_with_retry<aimdk_msgs::srv::SetMcPresetMotion>(
          preset_client_, request, "SetMcPresetMotion");

      if (!future.valid()) {
        RCLCPP_ERROR(this->get_logger(), "Service call failed or timed out.");
        return false;
      }

      auto response = future.get();
      if (response && response->response.header.code == 0) {
        RCLCPP_INFO(this->get_logger(), "Motion request accepted. Task ID: %lu",
                    response->response.task_id);
        return true;
      }
      
      if (response) {
        RCLCPP_ERROR(this->get_logger(),
                     "SetMcPresetMotion failed. code=%ld status=%d reason=%u",
                     response->response.header.code,
                     response->response.state.value,
                     response->response.state.reason);
      }
      
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

  bool send_custom_request(const std::string & ani_path) {
    if (!ensure_ready_state()) {
      RCLCPP_ERROR(this->get_logger(),
                   "Failed to prepare robot state for custom motion.");
      return false;
    }

    try {
      auto request =
          std::make_shared<aimdk_msgs::srv::SetMcPresetMotion::Request>();
      request->header.stamp = this->now();
      request->source = "sdk_rpc";
      request->motion.value = 0;  // not using built-in enum
      request->interrupt = true;
      request->ani_path = ani_path;  // custom motion file path

      RCLCPP_INFO(this->get_logger(),
                  "Sending custom motion request: path=%s", ani_path.c_str());

      auto future = call_service_with_retry<aimdk_msgs::srv::SetMcPresetMotion>(
          preset_client_, request, "SetMcPresetMotion");

      if (!future.valid()) {
        RCLCPP_ERROR(this->get_logger(), "Service call failed or timed out.");
        return false;
      }

      auto response = future.get();
      if (response && response->response.header.code == 0) {
        RCLCPP_INFO(this->get_logger(),
                    "Custom motion request accepted. Task ID: %lu",
                    response->response.task_id);
        return true;
      }

      if (response) {
        RCLCPP_ERROR(this->get_logger(),
                     "SetMcPresetMotion (custom) failed. code=%ld status=%d reason=%u",
                     response->response.header.code,
                     response->response.state.value,
                     response->response.state.reason);
      }

      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

private:
  void wait_for_services() {
    auto wait = [this](auto &client, const std::string &name) {
      while (!client->wait_for_service(std::chrono::seconds(2))) {
        if (!rclcpp::ok())
          return;
        RCLCPP_INFO(this->get_logger(), "Waiting for service %s...",
                    name.c_str());
      }
    };
    wait(preset_client_, "/aimdk_5Fmsgs/srv/SetMcPresetMotion");
  }

  bool ensure_ready_state() {
    aimdk_examples::McActionSwitcher switcher(this->shared_from_this());
    aimdk_examples::McActionSwitchOptions options;
    options.source = "sdk_rpc";
    options.total_timeout = std::chrono::seconds(30);

    const auto result = switcher.switch_to("BIPED_WHOLE_BODY_CTRL", options);
    if (!result.success) {
      RCLCPP_ERROR(this->get_logger(),
                   "Failed to switch from %s to BIPED_WHOLE_BODY_CTRL: %s",
                   result.current_action.empty() ? "(unknown)"
                                                 : result.current_action.c_str(),
                   result.message.c_str());
    }
    return result.success;
  }

  rclcpp::Client<aimdk_msgs::srv::SetMcPresetMotion>::SharedPtr preset_client_;
};

int main(int argc, char *argv[]) {
  try {
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    g_node = std::make_shared<PresetMotionClient>();
    auto client = std::dynamic_pointer_cast<PresetMotionClient>(g_node);

    // Choose between built-in preset and custom motion file
    std::cout << "\nOptions:" << std::endl;
    std::cout << "  [1] Play built-in preset motion" << std::endl;
    std::cout << "  [2] Play custom motion file (from teaching)" << std::endl;
    std::cout << "Enter choice (1/2): ";
    std::string choice;
    std::getline(std::cin, choice);
    choice.erase(std::remove_if(choice.begin(), choice.end(), ::isspace), choice.end());

    if (choice == "2") {
        std::cout << "\nEnter custom motion file path "
                  << "(e.g. /robot/userdata/sd/custom_motions/<用户输入名称>_<时间戳>_<编号>.csv): ";
        std::string ani_path;
        std::getline(std::cin, ani_path);
        if (ani_path.empty()) {
            std::cerr << "No path provided." << std::endl;
            g_node.reset();
            rclcpp::shutdown();
            return 1;
        }
        if (client) {
            client->send_custom_request(ani_path);
        }
        g_node.reset();
        rclcpp::shutdown();
        return 0;
    }

    // Built-in preset motion flow
    std::cout << "\nPlease refer to the interface documentation for the list of supported motions for this model." << std::endl;
    // Ask for robot series (Q or T)
    std::cout << "\nEnter robot series (Q/T): ";
    std::string robot_series;
    std::getline(std::cin, robot_series);
    // Trim whitespace and convert to uppercase
    robot_series.erase(std::remove_if(robot_series.begin(), robot_series.end(), ::isspace), robot_series.end());
    std::transform(robot_series.begin(), robot_series.end(), robot_series.begin(), ::toupper);

    std::map<int, std::string> motion_map;
    if (robot_series == "T") {
        motion_map = {{1001, "raise"}, {1002, "wave"}, {1003, "handshake"}, {1004, "airkiss"}};
    } else if (robot_series == "Q") {
        motion_map = {{3001, "wave"}, {3002, "handshake"}, {3003, "bump"}, {3004, "wave_hand"}};
    } else {
        std::cerr << "Unknown series. Please enter 'Q' or 'T'." << std::endl;
        return 1;
    }

    // Display available motions
    std::cout << "\nAvailable Preset Motions:" << std::endl;
    for (const auto &kv : motion_map) {
        std::cout << "  " << kv.first << ": " << kv.second << std::endl;
    }
    std::cout << "\nEnter preset motion ID: ";
    int motion_id = 0;
    if (!(std::cin >> motion_id)) return 0;
    // Validate selection
    if (motion_map.find(motion_id) == motion_map.end()) {
        std::cerr << "Invalid motion ID selected." << std::endl;
        return 1;
    }
    
    if (client) {
      client->send_request(motion_id);
    }
    g_node.reset();
    rclcpp::shutdown();
    return 0;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("main"), "Exited with exception: %s",
                 e.what());
    return 1;
  }
}
预设动作设置 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/set_preset_motion.py

python
#!/usr/bin/env python3

"""
Preset Motion Control Example Script

Description:
  This script demonstrates how to execute preset motions (like waving or handshaking) using the SetMcPresetMotion service.
  Automatically handles state machine transitions for safe motion execution.

Prerequisites:
  - MC (Motion Control) service must be running
  - Robot must be in a safe environment for motion testing
  - The shared action switcher will transition to BIPED_WHOLE_BODY_CTRL

Usage:
  python3 set_preset_motion.py

Example:
  python3 set_preset_motion.py

Parameters:
  - None 
"""

import sys
import time

import rclpy
import rclpy.logging
from rclpy.node import Node

from aimdk_msgs.srv import SetMcPresetMotion
from aimdk_msgs.msg import (
    McPresetMotion, RequestHeader
)

from common.mc_action_switcher import McActionSwitchOptions, McActionSwitcher

SERVICE_CALL_TIMEOUT_SEC = 2.0
MAX_RETRY_COUNT = 3

class SetMcPresetMotionClient(Node):
    def __init__(self):
        super().__init__('preset_motion_client')
        
        self.preset_client = self.create_client(
            SetMcPresetMotion, '/aimdk_5Fmsgs/srv/SetMcPresetMotion')
            
        self.get_logger().info('SetMcPresetMotion client node created.')
        self.wait_for_services()

    def wait_for_services(self):
        clients = [
            (self.preset_client, '/aimdk_5Fmsgs/srv/SetMcPresetMotion'),
        ]
        for client, name in clients:
            while not client.wait_for_service(timeout_sec=2.0):
                self.get_logger().info(f'Waiting for service {name}...')
        self.get_logger().info('All required services are available.')

    def call_service_with_retry(self, client, request, service_name: str, timeout_sec=None, max_retries=None):
        if timeout_sec is None:
            timeout_sec = SERVICE_CALL_TIMEOUT_SEC
        if max_retries is None:
            max_retries = MAX_RETRY_COUNT
            
        for i in range(max_retries):
            future = client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=timeout_sec)

            if future.done():
                return future

            self.get_logger().info(f'{service_name} attempt {i+1}/{max_retries} timed out, retrying...')
            time.sleep(0.2)
        
        self.get_logger().error(f'{service_name} failed after {max_retries} attempts')
        return None

    def ensure_ready_state(self) -> bool:
        switcher = McActionSwitcher(self)
        options = McActionSwitchOptions(
            source="sdk_rpc",
            total_timeout=30.0,
        )
        result = switcher.switch_to("BIPED_WHOLE_BODY_CTRL", options)
        if not result.success:
            current_action = result.current_action or "(unknown)"
            self.get_logger().error(
                "Failed to switch from "
                f"{current_action} to BIPED_WHOLE_BODY_CTRL: {result.message}"
            )
        return result.success

    def send_motion_request(self, motion_id: int) -> bool:
        if not self.ensure_ready_state():
            self.get_logger().error('Failed to prepare robot state for preset motion.')
            return False

        request = SetMcPresetMotion.Request()
        request.header = RequestHeader()
        request.header.stamp = self.get_clock().now().to_msg()
        request.source = 'sdk_rpc'
        request.motion = McPresetMotion()
        request.motion.value = motion_id
        request.interrupt = True

        self.get_logger().info(f'Sending preset motion request: ID={motion_id}')
        
        future = self.call_service_with_retry(
            self.preset_client, request, "SetMcPresetMotion"
        )
        if future is None:
            return False
            
        res = future.result()
        if res and res.response.header.code == 0:
            self.get_logger().info(f'Motion request accepted. Task ID: {res.response.task_id}')
            return True
        
        if res:
            self.get_logger().error(
                f'SetMcPresetMotion failed. '
                f'code={res.response.header.code} status={res.response.state.value} '
                f'reason={res.response.state.reason}'
            )

        return False

    def send_custom_motion_request(self, ani_path: str) -> bool:
        if not self.ensure_ready_state():
            self.get_logger().error('Failed to prepare robot state for custom motion.')
            return False

        request = SetMcPresetMotion.Request()
        request.header = RequestHeader()
        request.header.stamp = self.get_clock().now().to_msg()
        request.source = 'sdk_rpc'
        request.motion = McPresetMotion()
        request.motion.value = 0  # not using built-in enum
        request.interrupt = True
        request.ani_path = ani_path  # custom motion file path

        self.get_logger().info(f'Sending custom motion request: path={ani_path}')

        future = self.call_service_with_retry(
            self.preset_client, request, "SetMcPresetMotion"
        )
        if future is None:
            return False

        res = future.result()
        if res and res.response.header.code == 0:
            self.get_logger().info(f'Custom motion request accepted. Task ID: {res.response.task_id}')
            return True

        if res:
            self.get_logger().error(
                f'SetMcPresetMotion (custom) failed. '
                f'code={res.response.header.code} status={res.response.state.value} '
                f'reason={res.response.state.reason}'
            )

        return False


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        # Choose between built-in preset and custom motion file
        print("\nOptions:")
        print("  [1] Play built-in preset motion")
        print("  [2] Play custom motion file (from teaching)")
        choice = input("Enter choice (1/2): ").strip()

        if choice == "2":
            file_path = input(
                "Enter custom motion file path "
                "(e.g. /robot/userdata/sd/custom_motions/<用户自定义名称>_<时间戳>_<编号>.csv): "
            ).strip()
            if not file_path:
                print("No path provided. Exiting.")
                sys.exit(1)
            node = SetMcPresetMotionClient()
            node.send_custom_motion_request(file_path)
            return

        # Built-in preset motion flow
        print("\nPlease refer to the interface documentation for the list of supported motions for this model.")
        print("If you haven't found the motion list, you can choose recommended motions based on the robot model.")
        # Determine robot series (Q or T). In a real scenario this could be obtained from a parameter or config.
        robot_series = input("\nEnter robot series (Q/T): ").strip().upper()
        if robot_series == "T":
            motion_map = {1001: "raise", 1002: "wave", 1003: "handshake", 1004: "airkiss"}
        elif robot_series == "Q":
            motion_map = {3001: "wave", 3002: "handshake", 3003: "bump", 3004: "wave_hand"}
        else:
            print("Unknown series. Please enter 'Q' or 'T'.")
            sys.exit(1)
        print("\nAvailable Preset Motions:")
        for k, v in motion_map.items():
            print(f"  {k}: {v}")
        motion_id = int(input("\nEnter preset motion ID: "))
        node = SetMcPresetMotionClient()
        node.send_motion_request(motion_id)
    except KeyboardInterrupt:
        pass
    except Exception as e:
        print(f"Error: {e}")
    finally:
        if node: node.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()

4.1.2 运控低层接口 ​

代码示例

关节运动控制(Topic: /aima/hal/joint/command) ​

⚠️ 强烈注意:在使用本脚本前,必须确保机器人本体的高层运控模块处于关闭状态。若高层指令与底层伺服流同步下发,可能会引发剧烈的物理震颤或不可预期的硬件异常。

关节运动控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp joint_control --ros-args -p joint_names:="['joint_name']" -p target_positions:="[0.5]"

cpp
// 注意:在使用本脚本前,需首先关闭机器人本体运控模块并将机器人平躺或悬挂,否则可能出现不可预期的异常行为!
// WARNING: Before using this script, you must first disable the robot's motion control module and place the robot flat on the ground or suspend it, otherwise unexpected behavior may occur!

/**
Joint Position Control Example Script

Description:
  This script demonstrates how to control robot joint positions via the /aima/hal/joint/command topic.
  Uses Ruckig trajectory generation for smooth joint movement to target positions.

Prerequisites:
  - Robot must be placed flat on the ground or suspended
  - Robot motion control module must be disabled
  - SDK must be built: colcon build
  - Environment must be sourced: source install/setup.bash
  - Ruckig library must be available (ruckig_for_primebot)

Usage:
  ros2 run aimdk_examples_cpp joint_control --ros-args -p joint_names:="[...]" -p target_positions:="[...]"
  Before using this script, you must first disable the robot's motion control module and 
  place the robot flat on the ground or suspend it, otherwise unexpected behavior may occur!

Example:
  # Control left arm and right leg joints
  ros2 run aimdk_examples_cpp joint_control --ros-args \
    -p joint_names:="[ \
      'right_hip_pitch_joint', \
      'right_hip_roll_joint', \
      'right_hip_yaw_joint', \
      'right_knee_joint', \
      'right_ankle_pitch_joint', \
      'right_ankle_roll_joint', \
      'left_shoulder_pitch_joint', \
      'left_elbow_joint', \
      'left_shoulder_yaw_joint', \
      'left_shoulder_roll_joint' \
    ]" \
    -p target_positions:="[ \
      -1.6, 0.5, 0.0, 0.0, 0.0, 0.0, \
      -1.8, 1.5, -0.2, 0.0 \
   ]"

Parameters:
  - joint_names: List of joint names to control (required)
  - target_positions: List of target joint positions in radians (required)
  - stiffness: List of stiffness values for each joint (optional)
  - damping: List of damping values for each joint (optional)
  - default_stiffness: Default stiffness for all joints (default: 20.0)
  - default_damping: Default damping for all joints (default: 2.0)
  - max_velocity: Maximum joint velocity (default: 3.0)
*/
#include <ruckig/ruckig.hpp>
#include "aimdk_msgs/msg/joint_command_array.hpp"
#include "aimdk_msgs/msg/joint_state_array.hpp"
#include "rclcpp/rclcpp.hpp"

#include <signal.h>
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>

using DynamicRuckig = ruckig::Ruckig<ruckig::DynamicDOFs>;
using DynamicInput  = ruckig::InputParameter<ruckig::DynamicDOFs>;
using DynamicOutput = ruckig::OutputParameter<ruckig::DynamicDOFs>;
using SteadyClock   = std::chrono::steady_clock;

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down joint_control...", signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class JointControlNode : public rclcpp::Node
{
 public:
  JointControlNode() : Node("joint_control")
  {
    const std::vector<std::string> empty_joint_names;
    const std::vector<double> empty_doubles;
    joint_names_ =
      this->declare_parameter<std::vector<std::string>>("joint_names", empty_joint_names);
    target_positions_ =
      this->declare_parameter<std::vector<double>>("target_positions", empty_doubles);
    stiffness_ = this->declare_parameter<std::vector<double>>("stiffness", empty_doubles);
    damping_ =
      this->declare_parameter<std::vector<double>>("damping", empty_doubles);
    default_stiffness_ =
      this->declare_parameter<double>("default_stiffness", 20.0);
    default_damping_ =
      this->declare_parameter<double>("default_damping", 2.0);
    max_velocity_ = this->declare_parameter<double>("max_velocity", 3.0);
    max_acceleration_ =
      this->declare_parameter<double>("max_acceleration", 10.0);
    max_jerk_ = this->declare_parameter<double>("max_jerk", 25.0);
    control_period_s_ =
      this->declare_parameter<double>("control_period_s", 0.002);
    state_timeout_s_ =
      this->declare_parameter<double>("state_timeout_s", 10.0);
    publish_full_command_ =
      this->declare_parameter<bool>("publish_full_command", true);

    validate_parameters();

    dofs_ = joint_names_.size();
    fill_optional_gains();

    ruckig_ = std::make_unique<DynamicRuckig>(dofs_, control_period_s_);
    input_  = std::make_unique<DynamicInput>(dofs_);
    output_ = std::make_unique<DynamicOutput>(dofs_);

    input_->max_velocity         = std::vector<double>(dofs_, max_velocity_);
    input_->max_acceleration     = std::vector<double>(dofs_, max_acceleration_);
    input_->max_jerk             = std::vector<double>(dofs_, max_jerk_);
    input_->current_acceleration = std::vector<double>(dofs_, 0.0);
    input_->target_velocity      = std::vector<double>(dofs_, 0.0);
    input_->target_acceleration  = std::vector<double>(dofs_, 0.0);

    auto qos = rclcpp::QoS(rclcpp::KeepLast(10));
    qos.best_effort();
    qos.durability_volatile();

    command_pub_ = this->create_publisher<aimdk_msgs::msg::JointCommandArray>(
      "/aima/hal/joint/command", qos);
    state_sub_ = this->create_subscription<aimdk_msgs::msg::JointStateArray>(
      "/aima/hal/joint/state", qos,
      std::bind(&JointControlNode::on_joint_state, this, std::placeholders::_1));
    // Timer to print joint state every 10 seconds
    print_timer_ = this->create_wall_timer(
      std::chrono::seconds(10),
      std::bind(&JointControlNode::print_joint_state, this));

    wait_started_at_     = SteadyClock::now();
    state_timeout_timer_ = this->create_wall_timer(
      std::chrono::milliseconds(100),
      std::bind(&JointControlNode::check_state_timeout, this));

    RCLCPP_INFO(this->get_logger(),
                "Waiting for /aima/hal/joint/state, joints=%s, targets=%s, "
                "control_period_s=%.3f, state_timeout_s=%.3f, "
                "publish_full_command=%s",
                format_strings(joint_names_).c_str(), format_doubles(target_positions_).c_str(), control_period_s_, state_timeout_s_, publish_full_command_ ? "true" : "false");
  }

 private:
  void validate_parameters()
  {
    if (joint_names_.empty()) {
      throw std::runtime_error("Parameter 'joint_names' must not be empty.");
    }
    if (target_positions_.empty()) {
      throw std::runtime_error(
        "Parameter 'target_positions' must not be empty.");
    }
    if (joint_names_.size() != target_positions_.size()) {
      throw std::runtime_error(
        "Parameter 'joint_names' and 'target_positions' must have the same "
        "length.");
    }
    if (!stiffness_.empty() && stiffness_.size() != joint_names_.size()) {
      throw std::runtime_error(
        "Parameter 'stiffness' must be empty or match joint_names length.");
    }
    if (!damping_.empty() && damping_.size() != joint_names_.size()) {
      throw std::runtime_error(
        "Parameter 'damping' must be empty or match joint_names length.");
    }
    if (control_period_s_ <= 0.0) {
      throw std::runtime_error(
        "Parameter 'control_period_s' must be greater than zero.");
    }
    if (state_timeout_s_ <= 0.0) {
      throw std::runtime_error(
        "Parameter 'state_timeout_s' must be greater than zero.");
    }
    if (max_velocity_ <= 0.0 || max_acceleration_ <= 0.0 || max_jerk_ <= 0.0) {
      throw std::runtime_error(
        "Motion limits 'max_velocity', 'max_acceleration', and 'max_jerk' "
        "must be greater than zero.");
    }
  }

  void fill_optional_gains()
  {
    if (stiffness_.empty()) {
      stiffness_ = std::vector<double>(dofs_, default_stiffness_);
    }
    if (damping_.empty()) {
      damping_ = std::vector<double>(dofs_, default_damping_);
    }
  }

  void on_joint_state(const aimdk_msgs::msg::JointStateArray::SharedPtr msg)
  {
    latest_state_ = msg;
    if (trajectory_started_ || finished_) {
      return;
    }

    start_trajectory();
  }

  void print_joint_state()
  {
    if (!latest_state_) {
      RCLCPP_WARN(this->get_logger(), "No joint state received yet – waiting for /aima/hal/joint/state.");
      return;
    }
    std::vector<std::string> parts;
    for (const auto &joint : latest_state_->joints) {
      std::ostringstream oss;
      oss << joint.name << ": pos=" << std::fixed << std::setprecision(3) << joint.position
          << ", vel=" << joint.velocity;
      parts.push_back(oss.str());
    }
    std::string msg = "Current joint state (every 10 s): ";
    for (size_t i = 0; i < parts.size(); ++i) {
      if (i > 0) msg += ", ";
      msg += parts[i];
    }
    RCLCPP_INFO(this->get_logger(), "%s", msg.c_str());
  }

  void start_trajectory()
  {
    if (!latest_state_) {
      return;
    }

    std::unordered_map<std::string, size_t> state_index_by_name;
    state_index_by_name.reserve(latest_state_->joints.size());
    for (size_t i = 0; i < latest_state_->joints.size(); ++i) {
      state_index_by_name[latest_state_->joints[i].name] = i;
    }

    std::vector<std::string> missing_state_joints;
    std::vector<double> current_positions(dofs_, 0.0);
    std::vector<double> current_velocities(dofs_, 0.0);
    target_full_indices_.assign(dofs_, 0);

    for (size_t i = 0; i < dofs_; ++i) {
      const auto state_it = state_index_by_name.find(joint_names_[i]);
      if (state_it == state_index_by_name.end()) {
        missing_state_joints.push_back(joint_names_[i]);
        continue;
      }

      const auto &joint_state = latest_state_->joints[state_it->second];
      target_full_indices_[i] = state_it->second;
      current_positions[i]    = joint_state.position;
      current_velocities[i]   = joint_state.velocity;
    }

    if (!missing_state_joints.empty()) {
      RCLCPP_ERROR(this->get_logger(), "Missing joints in /aima/hal/joint/state: %s", format_strings(missing_state_joints).c_str());
      shutdown_with_error();
      return;
    }

    input_->current_position     = current_positions;
    input_->current_velocity     = current_velocities;
    input_->current_acceleration = std::vector<double>(dofs_, 0.0);
    input_->target_position      = target_positions_;
    input_->target_velocity      = std::vector<double>(dofs_, 0.0);
    input_->target_acceleration  = std::vector<double>(dofs_, 0.0);

    control_started_at_ = SteadyClock::now();
    trajectory_started_ = true;

    if (state_timeout_timer_) {
      state_timeout_timer_->cancel();
    }

    control_timer_ = this->create_wall_timer(
      to_timer_period(control_period_s_),
      std::bind(&JointControlNode::on_control_timer, this));

    RCLCPP_INFO(this->get_logger(),
                "Trajectory initialized from current=%s to target=%s, "
                "stiffness=%s, damping=%s",
                format_doubles(current_positions).c_str(), format_doubles(target_positions_).c_str(), format_doubles(stiffness_).c_str(), format_doubles(damping_).c_str());
  }

  void on_control_timer()
  {
    if (finished_) {
      return;
    }

    const auto cycle_start = SteadyClock::now();
    const auto result      = ruckig_->update(*input_, *output_);

    if (result != ruckig::Result::Working && result != ruckig::Result::Finished) {
      RCLCPP_ERROR(this->get_logger(), "Ruckig trajectory planning failed with result=%d", static_cast<int>(result));
      shutdown_with_error();
      return;
    }

    publish_command(output_->new_position);
    output_->pass_to_input(*input_);

    const auto cycle_end = SteadyClock::now();
    const double cycle_cost_s =
      std::chrono::duration<double>(cycle_end - cycle_start).count();
    ++cycle_count_;
    total_cycle_cost_s_ += cycle_cost_s;
    max_cycle_cost_s_ = std::max(max_cycle_cost_s_, cycle_cost_s);
    if (cycle_cost_s > control_period_s_) {
      const double overrun_s = cycle_cost_s - control_period_s_;
      ++overrun_count_;
      total_overrun_s_ += overrun_s;
      max_overrun_s_ = std::max(max_overrun_s_, overrun_s);
    }

    if (result == ruckig::Result::Finished) {
      publish_command(target_positions_);
      log_stats_and_shutdown();
    }
  }

  void publish_command(const std::vector<double> &positions)
  {
    aimdk_msgs::msg::JointCommandArray cmd;
    cmd.header.stamp    = this->now();
    cmd.header.sequence = sequence_++;
    if (latest_state_) {
      cmd.header.frame_id   = latest_state_->header.frame_id;
      cmd.header.meas_stamp = latest_state_->header.meas_stamp;
    }

    if (publish_full_command_ && latest_state_ && target_full_indices_.size() == dofs_) {
      cmd.joints.resize(latest_state_->joints.size());
      for (size_t i = 0; i < latest_state_->joints.size(); ++i) {
        auto &joint             = cmd.joints[i];
        const auto &state_joint = latest_state_->joints[i];
        joint.name              = state_joint.name;
        joint.position          = state_joint.position;
        joint.velocity          = 0.0;
        joint.effort            = 0.0;
        joint.stiffness         = default_stiffness_;
        joint.damping           = default_damping_;
      }

      for (size_t i = 0; i < dofs_; ++i) {
        const size_t full_index = target_full_indices_[i];
        if (full_index >= cmd.joints.size()) {
          continue;
        }

        auto &joint     = cmd.joints[full_index];
        joint.position  = positions[i];
        joint.stiffness = stiffness_[i];
        joint.damping   = damping_[i];
      }
    } else {
      cmd.joints.resize(dofs_);
      for (size_t i = 0; i < dofs_; ++i) {
        auto &joint     = cmd.joints[i];
        joint.name      = joint_names_[i];
        joint.position  = positions[i];
        joint.velocity  = 0.0;
        joint.effort    = 0.0;
        joint.stiffness = stiffness_[i];
        joint.damping   = damping_[i];
      }
    }

    command_pub_->publish(cmd);
  }

  void check_state_timeout()
  {
    if (trajectory_started_ || finished_) {
      return;
    }

    const double wait_s =
      std::chrono::duration<double>(SteadyClock::now() - wait_started_at_)
        .count();
    if (wait_s > state_timeout_s_) {
      RCLCPP_ERROR(this->get_logger(), "Timed out after %.3f s waiting for /aima/hal/joint/state", wait_s);
      shutdown_with_error();
    }
  }

  void shutdown_with_error()
  {
    if (finished_) {
      return;
    }

    finished_ = true;
    if (control_timer_) {
      control_timer_->cancel();
    }
    if (state_timeout_timer_) {
      state_timeout_timer_->cancel();
    }
    rclcpp::shutdown();
  }

  void log_stats_and_shutdown()
  {
    if (finished_) {
      return;
    }

    finished_ = true;
    if (control_timer_) {
      control_timer_->cancel();
    }
    if (state_timeout_timer_) {
      state_timeout_timer_->cancel();
    }

    const double runtime_s =
      std::chrono::duration<double>(SteadyClock::now() - control_started_at_)
        .count();
    const double actual_hz =
      runtime_s > 0.0 ? static_cast<double>(cycle_count_) / runtime_s : 0.0;
    const double avg_cycle_ms =
      cycle_count_ > 0
        ? (total_cycle_cost_s_ / static_cast<double>(cycle_count_)) *
            1000.0
        : 0.0;
    const double avg_overrun_ms =
      overrun_count_ > 0
        ? (total_overrun_s_ / static_cast<double>(overrun_count_)) * 1000.0
        : 0.0;
    const double trajectory_duration_s =
      output_ ? output_->trajectory.get_duration() : 0.0;

    RCLCPP_INFO(
      this->get_logger(),
      "Trajectory completed. planned_duration=%.6f s, runtime=%.6f s, "
      "cycles=%zu, actual_hz=%.2f, avg_cycle_ms=%.3f, max_cycle_ms=%.3f, "
      "overruns=%zu, avg_overrun_ms=%.3f, max_overrun_ms=%.3f",
      trajectory_duration_s, runtime_s, cycle_count_, actual_hz, avg_cycle_ms,
      max_cycle_cost_s_ * 1000.0, overrun_count_, avg_overrun_ms,
      max_overrun_s_ * 1000.0);
    rclcpp::shutdown();
  }

  static std::chrono::nanoseconds to_timer_period(double seconds)
  {
    return std::chrono::duration_cast<std::chrono::nanoseconds>(
      std::chrono::duration<double>(seconds));
  }

  static std::string format_strings(const std::vector<std::string> &values)
  {
    std::ostringstream oss;
    oss << "[";
    for (size_t i = 0; i < values.size(); ++i) {
      if (i > 0) {
        oss << ", ";
      }
      oss << values[i];
    }
    oss << "]";
    return oss.str();
  }

  static std::string format_doubles(const std::vector<double> &values)
  {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(6) << "[";
    for (size_t i = 0; i < values.size(); ++i) {
      if (i > 0) {
        oss << ", ";
      }
      oss << values[i];
    }
    oss << "]";
    return oss.str();
  }

  std::vector<std::string> joint_names_;
  std::vector<double> target_positions_;
  std::vector<double> stiffness_;
  std::vector<double> damping_;

  double default_stiffness_{20.0};
  double default_damping_{2.0};
  double max_velocity_{3.0};
  double max_acceleration_{10.0};
  double max_jerk_{25.0};
  double control_period_s_{0.002};
  double state_timeout_s_{5.0};
  bool publish_full_command_{true};
  size_t dofs_{0};
  std::vector<size_t> target_full_indices_;

  bool trajectory_started_{false};
  bool finished_{false};
  uint32_t sequence_{0};

  size_t cycle_count_{0};
  size_t overrun_count_{0};
  double total_cycle_cost_s_{0.0};
  double max_cycle_cost_s_{0.0};
  double total_overrun_s_{0.0};
  double max_overrun_s_{0.0};

  SteadyClock::time_point wait_started_at_;
  SteadyClock::time_point control_started_at_;

  std::unique_ptr<DynamicRuckig> ruckig_;
  std::unique_ptr<DynamicInput> input_;
  std::unique_ptr<DynamicOutput> output_;

  aimdk_msgs::msg::JointStateArray::SharedPtr latest_state_;
  rclcpp::Publisher<aimdk_msgs::msg::JointCommandArray>::SharedPtr command_pub_;
  rclcpp::Subscription<aimdk_msgs::msg::JointStateArray>::SharedPtr state_sub_;
  rclcpp::TimerBase::SharedPtr state_timeout_timer_;
  rclcpp::TimerBase::SharedPtr control_timer_;
  rclcpp::TimerBase::SharedPtr print_timer_;
};

int main(int argc, char **argv)
{
  rclcpp::init(argc, argv);
  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);

  try {
    auto node = std::make_shared<JointControlNode>();
    g_node    = node;
    rclcpp::spin(node);
    g_node.reset();
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("joint_control"), "Failed to start joint_control: %s", e.what());
    if (rclcpp::ok()) {
      rclcpp::shutdown();
    }
    return 1;
  }

  if (rclcpp::ok()) {
    rclcpp::shutdown();
  }
  return 0;
}
关节运动控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/joint_control.py

python
#!/usr/bin/env python3
# 注意:在使用本脚本前,需首先关闭机器人本体运控模块并将机器人平躺或悬挂,否则可能出现不可预期的异常行为!

"""
Joint Position Control Example Script

Description:
  This script demonstrates how to control robot joint positions via the /aima/hal/joint/command topic.
  Uses Ruckig trajectory generation for smooth joint movement to target positions.

Prerequisites:
  - Robot must be placed flat on the ground or suspended
  - Robot motion control module must be disabled
  - SDK must be built: colcon build
  - Environment must be sourced: source install/setup.bash
  - Ruckig library must be available (ruckig_for_primebot)

Usage:
  python3 joint_control.py --ros-args -p joint_names:="[...]" -p target_positions:="[...]"
  Before using this script, you must first disable the robot's motion control module and 
  place the robot flat on the ground or suspend it, otherwise unexpected behavior may occur!

Example:
  # Control left arm and right leg joints
   python3 examples/python/joint_control.py --ros-args \
    -p joint_names:="[ \
      'right_hip_pitch_joint', \
      'right_hip_roll_joint', \
      'right_hip_yaw_joint', \
      'right_knee_joint', \
      'right_ankle_pitch_joint', \
      'right_ankle_roll_joint', \
      'left_shoulder_pitch_joint', \
      'left_elbow_joint', \
      'left_shoulder_yaw_joint', \
      'left_shoulder_roll_joint' \
    ]" \
    -p target_positions:="[ \
      -1.6, 0.5, 0.0, 0.0, 0.0, 0.0,\
      -1.8, 1.5, -0.2, 0.0 \
    ]"

Parameters:
  - joint_names: List of joint names to control (required)
  - target_positions: List of target joint positions in radians (required)
  - stiffness: List of stiffness values for each joint (optional)
  - damping: List of damping values for each joint (optional)
  - default_stiffness: Default stiffness for all joints (default: 20.0)
  - default_damping: Default damping for all joints (default: 2.0)
  - max_velocity: Maximum joint velocity (default: 3.0)
"""

import signal
import time
from typing import List, Optional

import rclpy
import rclpy.logging
from rclpy.node import Node
from rclpy.parameter import Parameter
from rclpy.qos import DurabilityPolicy, HistoryPolicy, QoSProfile, ReliabilityPolicy

from aimdk_msgs.msg import JointCommand, JointCommandArray, JointStateArray
from ruckig_for_primebot import InputParameter, OutputParameter, Result, Ruckig


g_node: Optional["JointControlNode"] = None


def signal_handler(signum, _frame) -> None:
    if g_node is not None:
        g_node.get_logger().info(
            f"Received signal {signum}, shutting down joint_control..."
        )
    if rclpy.ok():
        rclpy.shutdown()
    raise SystemExit(signum)


class JointControlNode(Node):
    def __init__(self) -> None:
        super().__init__("joint_control")

        self.declare_parameter("joint_names", Parameter.Type.STRING_ARRAY)
        self.declare_parameter("target_positions", Parameter.Type.DOUBLE_ARRAY)
        self.declare_parameter("stiffness", Parameter.Type.DOUBLE_ARRAY)
        self.declare_parameter("damping", Parameter.Type.DOUBLE_ARRAY)
        self.default_stiffness = self.declare_parameter(
            "default_stiffness", 20.0
        ).value
        self.default_damping = self.declare_parameter("default_damping", 2.0).value
        self.max_velocity = self.declare_parameter("max_velocity", 3.0).value
        self.max_acceleration = self.declare_parameter(
            "max_acceleration", 10.0
        ).value
        self.max_jerk = self.declare_parameter("max_jerk", 25.0).value
        self.control_period_s = self.declare_parameter("control_period_s", 0.002).value
        self.state_timeout_s = self.declare_parameter("state_timeout_s", 10.0).value
        self.publish_full_command = self.declare_parameter(
            "publish_full_command", True
        ).value

        self.joint_names = list(
            self.get_parameter_or(
                "joint_names",
                Parameter("joint_names", Parameter.Type.STRING_ARRAY, []),
            ).value
        )
        self.target_positions = list(
            self.get_parameter_or(
                "target_positions",
                Parameter("target_positions", Parameter.Type.DOUBLE_ARRAY, []),
            ).value
        )
        self.stiffness = list(
            self.get_parameter_or(
                "stiffness",
                Parameter("stiffness", Parameter.Type.DOUBLE_ARRAY, []),
            ).value
        )
        self.damping = list(
            self.get_parameter_or(
                "damping",
                Parameter("damping", Parameter.Type.DOUBLE_ARRAY, []),
            ).value
        )

        self.validate_parameters()

        self.dofs = len(self.joint_names)
        self.fill_optional_gains()

        self.ruckig = Ruckig(self.dofs, self.control_period_s)
        self.input = InputParameter(self.dofs)
        self.output = OutputParameter(self.dofs)

        self.input.max_velocity = [self.max_velocity] * self.dofs
        self.input.max_acceleration = [self.max_acceleration] * self.dofs
        self.input.max_jerk = [self.max_jerk] * self.dofs
        self.input.current_acceleration = [0.0] * self.dofs
        self.input.target_velocity = [0.0] * self.dofs
        self.input.target_acceleration = [0.0] * self.dofs

        qos = QoSProfile(
            history=HistoryPolicy.KEEP_LAST,
            depth=10,
            reliability=ReliabilityPolicy.BEST_EFFORT,
            durability=DurabilityPolicy.VOLATILE,
        )

        self.command_pub = self.create_publisher(
            JointCommandArray, "/aima/hal/joint/command", qos
        )
        self.state_sub = self.create_subscription(
            JointStateArray,
            "/aima/hal/joint/state",
            self.on_joint_state,
            qos,
        )
        # Timer to print joint state every 10 seconds
        self.print_timer = self.create_timer(10.0, self.print_joint_state)

        self.latest_state: Optional[JointStateArray] = None
        self.target_full_indices: List[int] = []

        self.trajectory_started = False
        self.finished = False
        self.failed = False
        self.sequence = 0

        self.cycle_count = 0
        self.overrun_count = 0
        self.total_cycle_cost_s = 0.0
        self.max_cycle_cost_s = 0.0
        self.total_overrun_s = 0.0
        self.max_overrun_s = 0.0

        self.wait_started_at = time.perf_counter()
        self.control_started_at = 0.0

        self.state_timeout_timer = self.create_timer(0.1, self.check_state_timeout)
        self.control_timer = None

        self.get_logger().info(
            "Waiting for /aima/hal/joint/state, "
            f"joints={self.format_strings(self.joint_names)}, "
            f"targets={self.format_doubles(self.target_positions)}, "
            f"control_period_s={self.control_period_s:.3f}, "
            f"state_timeout_s={self.state_timeout_s:.3f}, "
            f"publish_full_command={'true' if self.publish_full_command else 'false'}"
        )

    def validate_parameters(self) -> None:
        if not self.joint_names:
            raise ValueError("Parameter 'joint_names' must not be empty.")
        if not self.target_positions:
            raise ValueError("Parameter 'target_positions' must not be empty.")
        if len(self.joint_names) != len(self.target_positions):
            raise ValueError(
                "Parameter 'joint_names' and 'target_positions' must have the same length."
            )
        if self.stiffness and len(self.stiffness) != len(self.joint_names):
            raise ValueError(
                "Parameter 'stiffness' must be empty or match joint_names length."
            )
        if self.damping and len(self.damping) != len(self.joint_names):
            raise ValueError(
                "Parameter 'damping' must be empty or match joint_names length."
            )
        if self.control_period_s <= 0.0:
            raise ValueError("Parameter 'control_period_s' must be greater than zero.")
        if self.state_timeout_s <= 0.0:
            raise ValueError("Parameter 'state_timeout_s' must be greater than zero.")
        if (
            self.max_velocity <= 0.0
            or self.max_acceleration <= 0.0
            or self.max_jerk <= 0.0
        ):
            raise ValueError(
                "Motion limits 'max_velocity', 'max_acceleration', and 'max_jerk' "
                "must be greater than zero."
            )

    def fill_optional_gains(self) -> None:
        if not self.stiffness:
            self.stiffness = [self.default_stiffness] * self.dofs
        if not self.damping:
            self.damping = [self.default_damping] * self.dofs

    def on_joint_state(self, msg: JointStateArray) -> None:
        self.latest_state = msg
        if self.trajectory_started or self.finished:
            return
        self.start_trajectory()

    def print_joint_state(self) -> None:
        """Print the latest joint state every 10 seconds after it is received."""
        if self.latest_state is None:
            self.get_logger().warning("No joint state received yet – waiting for /aima/hal/joint/state.")
            return
        lines = []
        for joint in self.latest_state.joints:
            lines.append(f"{joint.name}: pos={joint.position:.3f}, vel={joint.velocity:.3f}")
        self.get_logger().info("Current joint state (every 10 s): " + ", ".join(lines))

    def start_trajectory(self) -> None:
        if self.latest_state is None:
            return

        state_index_by_name = {
            joint.name: idx for idx, joint in enumerate(self.latest_state.joints)
        }
        missing_state_joints: List[str] = []
        current_positions = [0.0] * self.dofs
        current_velocities = [0.0] * self.dofs
        self.target_full_indices = [0] * self.dofs

        for i, joint_name in enumerate(self.joint_names):
            state_index = state_index_by_name.get(joint_name)
            if state_index is None:
                missing_state_joints.append(joint_name)
                continue

            joint_state = self.latest_state.joints[state_index]
            self.target_full_indices[i] = state_index
            current_positions[i] = float(joint_state.position)
            current_velocities[i] = float(joint_state.velocity)

        if missing_state_joints:
            self.get_logger().error(
                "Missing joints in /aima/hal/joint/state: "
                f"{self.format_strings(missing_state_joints)}"
            )
            self.shutdown_with_error()
            return

        self.input.current_position = current_positions
        self.input.current_velocity = current_velocities
        self.input.current_acceleration = [0.0] * self.dofs
        self.input.target_position = self.target_positions
        self.input.target_velocity = [0.0] * self.dofs
        self.input.target_acceleration = [0.0] * self.dofs

        self.control_started_at = time.perf_counter()
        self.trajectory_started = True

        if self.state_timeout_timer is not None:
            self.state_timeout_timer.cancel()

        self.control_timer = self.create_timer(
            self.control_period_s, self.on_control_timer
        )

        self.get_logger().info(
            "Trajectory initialized from "
            f"current={self.format_doubles(current_positions)} "
            f"to target={self.format_doubles(self.target_positions)}, "
            f"stiffness={self.format_doubles(self.stiffness)}, "
            f"damping={self.format_doubles(self.damping)}"
        )

    def on_control_timer(self) -> None:
        if self.finished:
            return

        cycle_start = time.perf_counter()
        result = self.ruckig.update(self.input, self.output)

        if result not in (Result.Working, Result.Finished):
            self.get_logger().error(
                f"Ruckig trajectory planning failed with result={result}"
            )
            self.shutdown_with_error()
            return

        self.publish_command(list(self.output.new_position))
        self.output.pass_to_input(self.input)

        cycle_cost_s = time.perf_counter() - cycle_start
        self.cycle_count += 1
        self.total_cycle_cost_s += cycle_cost_s
        self.max_cycle_cost_s = max(self.max_cycle_cost_s, cycle_cost_s)

        if cycle_cost_s > self.control_period_s:
            overrun_s = cycle_cost_s - self.control_period_s
            self.overrun_count += 1
            self.total_overrun_s += overrun_s
            self.max_overrun_s = max(self.max_overrun_s, overrun_s)

        if result == Result.Finished:
            self.publish_command(self.target_positions)
            self.log_stats_and_shutdown()

    def publish_command(self, positions: List[float]) -> None:
        cmd = JointCommandArray()
        cmd.header.stamp = self.get_clock().now().to_msg()
        cmd.header.sequence = self.sequence
        self.sequence += 1

        if self.latest_state is not None:
            cmd.header.frame_id = self.latest_state.header.frame_id
            cmd.header.meas_stamp = self.latest_state.header.meas_stamp

        if (
            self.publish_full_command
            and self.latest_state is not None
            and len(self.target_full_indices) == self.dofs
        ):
            for state_joint in self.latest_state.joints:
                joint = JointCommand()
                joint.name = state_joint.name
                joint.position = state_joint.position
                joint.velocity = 0.0
                joint.effort = 0.0
                joint.stiffness = self.default_stiffness
                joint.damping = self.default_damping
                cmd.joints.append(joint)

            for i, full_index in enumerate(self.target_full_indices):
                if full_index >= len(cmd.joints):
                    continue

                joint = cmd.joints[full_index]
                joint.position = float(positions[i])
                joint.stiffness = float(self.stiffness[i])
                joint.damping = float(self.damping[i])
        else:
            for i, joint_name in enumerate(self.joint_names):
                joint = JointCommand()
                joint.name = joint_name
                joint.position = float(positions[i])
                joint.velocity = 0.0
                joint.effort = 0.0
                joint.stiffness = float(self.stiffness[i])
                joint.damping = float(self.damping[i])
                cmd.joints.append(joint)

        self.command_pub.publish(cmd)

    def check_state_timeout(self) -> None:
        if self.trajectory_started or self.finished:
            return

        wait_s = time.perf_counter() - self.wait_started_at
        if wait_s > self.state_timeout_s:
            self.get_logger().error(
                "Timed out after "
                f"{wait_s:.3f} s waiting for /aima/hal/joint/state"
            )
            self.shutdown_with_error()

    def shutdown_with_error(self) -> None:
        if self.finished:
            return

        self.finished = True
        self.failed = True
        if self.control_timer is not None:
            self.control_timer.cancel()
        if self.state_timeout_timer is not None:
            self.state_timeout_timer.cancel()

    def log_stats_and_shutdown(self) -> None:
        if self.finished:
            return

        self.finished = True
        if self.control_timer is not None:
            self.control_timer.cancel()
        if self.state_timeout_timer is not None:
            self.state_timeout_timer.cancel()

        runtime_s = time.perf_counter() - self.control_started_at
        actual_hz = self.cycle_count / runtime_s if runtime_s > 0.0 else 0.0
        avg_cycle_ms = (
            self.total_cycle_cost_s / self.cycle_count * 1000.0
            if self.cycle_count > 0
            else 0.0
        )
        avg_overrun_ms = (
            self.total_overrun_s / self.overrun_count * 1000.0
            if self.overrun_count > 0
            else 0.0
        )
        trajectory_duration_s = float(self.output.trajectory.duration)

        self.get_logger().info(
            "Trajectory completed. "
            f"planned_duration={trajectory_duration_s:.6f} s, "
            f"runtime={runtime_s:.6f} s, "
            f"cycles={self.cycle_count}, "
            f"actual_hz={actual_hz:.2f}, "
            f"avg_cycle_ms={avg_cycle_ms:.3f}, "
            f"max_cycle_ms={self.max_cycle_cost_s * 1000.0:.3f}, "
            f"overruns={self.overrun_count}, "
            f"avg_overrun_ms={avg_overrun_ms:.3f}, "
            f"max_overrun_ms={self.max_overrun_s * 1000.0:.3f}"
        )

    @staticmethod
    def format_strings(values: List[str]) -> str:
        return "[" + ", ".join(values) + "]"

    @staticmethod
    def format_doubles(values: List[float]) -> str:
        return "[" + ", ".join(f"{value:.6f}" for value in values) + "]"


def main(args=None) -> int:
    global g_node

    rclpy.init(args=args)
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    node = None
    try:
        node = JointControlNode()
        g_node = node
        while rclpy.ok() and not node.finished:
            rclpy.spin_once(node, timeout_sec=0.1)
        g_node = None
        return 1 if node.failed else 0
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("joint_control").error(
            f"Failed to start joint_control: {error}"
        )
        if rclpy.ok():
            rclpy.shutdown()
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

4.2 交互控制功能 ​

4.2.1 语音控制 ​

代码示例

音频文件播放(Service: PlayAudioFile) ​

音频文件播放 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp play_audio_from_robot

cpp
/*
 @brief Example client for /aimdk_5Fmsgs/srv/PlayAudioFile (读取机器人本机磁盘音频文件播放)
 
 Default sample rate is 24kHz. Audio files must be 24kHz, 16-bit, mono WAV format.
 
 The following ROS parameters can be set via startup arguments:
 --ros-args -p <name>:=<value>
 
 Supported parameters:
   - file_name: audio file name only
   - file_path: directory containing the audio file
   - media_role: PulseAudio media.role (default: Music)
     Alert(系统告警,优先级100) | Notification(系统提示音,优先级80)
     Communication(对话语音,优先级60) | Music(音乐/媒体,优先级40)
     非 Music 角色播放时会自动降低(duck)音乐音量

 Usage:
   ros2 run aimdk_examples_cpp play_audio_from_robot --ros-args -p \
   file_name:=demo.wav -p file_path:=/tmp -p media_role:=Music \

 Examples:
   ros2 run aimdk_examples_cpp play_audio_from_robot --ros-args -p \
   file_name:=小星星.wav -p file_path:=/robot/software/aimrt_agent/bin/cfg/q1/audio \
   -p media_role:=Music
 
 Other request fields use built-in defaults and are not configurable from
 the command line in this demo.
 */
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/srv/play_audio_file.hpp"
#include "rclcpp/rclcpp.hpp"

#include <signal.h>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>

constexpr int kMaxRetryCount = 3;
constexpr std::chrono::seconds kServiceCallTimeout(5);

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...", signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class PlayAudioFileClient : public rclcpp::Node
{
 public:
  PlayAudioFileClient() : Node("play_audio_from_robot_client")
  {
    file_name_ =
      this->declare_parameter<std::string>("file_name", file_name_);
    file_path_ =
      this->declare_parameter<std::string>("file_path", file_path_);
    media_role_ =
      this->declare_parameter<std::string>("media_role", media_role_);

    client_ = this->create_client<aimdk_msgs::srv::PlayAudioFile>(service_name_);
    RCLCPP_INFO(this->get_logger(), "PlayAudioFile client node created.");
  }

  bool send_request()
  {
    if (!wait_for_service()) {
      return false;
    }

    auto request                  = std::make_shared<aimdk_msgs::srv::PlayAudioFile::Request>();
    request->request              = aimdk_msgs::msg::CommonRequest();
    request->request.header.stamp = this->now();

    // pkg_name/file_name/file_path locate the audio resource; info describes its format.
    request->file.pkg_name  = pkg_name_;
    request->file.file_name = file_name_;
    request->file.file_path = file_path_;

    if (request->file.file_name.empty()) {
      RCLCPP_ERROR(this->get_logger(), "file_name is empty.");
      return false;
    }

    request->file.info.channels      = static_cast<uint8_t>(channels_);
    request->file.info.sample_rate   = static_cast<uint32_t>(sample_rate_);
    request->file.info.size          = static_cast<uint32_t>(size_);
    request->file.info.sample_format = sample_format_;
    request->file.info.coding_format = coding_format_;
    request->file.priority           = static_cast<uint32_t>(priority_);
    request->file.priority_weight    = static_cast<uint32_t>(priority_weight_);
    request->file.media_role         = media_role_;

    RCLCPP_INFO(this->get_logger(),
                "Sending PlayAudioFile request: file=%s, path=%s, pkg=%s, "
                "ch=%d, sr=%d, fmt=%s, coding=%s, priority=%d, weight=%d",
                request->file.file_name.c_str(), request->file.file_path.c_str(), request->file.pkg_name.c_str(), channels_, sample_rate_, sample_format_.c_str(), coding_format_.c_str(), priority_, priority_weight_);

    // Retry mechanism: up to 3 attempts
    auto future = client_->async_send_request(request);
    bool completed = false;
    
    for (int i = 0; i < kMaxRetryCount; ++i) {
      auto retcode = rclcpp::spin_until_future_complete(
          shared_from_this(), future, kServiceCallTimeout);
      
      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        completed = true;
        break;
      }

      RCLCPP_INFO(this->get_logger(),
                  "PlayAudioFile attempt %d/%d timed out, retrying...",
                  i + 1, kMaxRetryCount);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      
      // Re-send request for retry
      future = client_->async_send_request(request);
    }

    if (!completed) {
      RCLCPP_ERROR(this->get_logger(), "PlayAudioFile call failed or timed out.");
      return false;
    }

    const auto response = future.get();
    if (!response) {
      RCLCPP_ERROR(this->get_logger(), "PlayAudioFile call failed or timed out.");
      return false;
    }

    const auto code     = response->response.header.code;
    const auto status   = response->response.status.value;
    // Treat code==0 or status==SUCCESS as success.
    const bool ok =
      code == 0 || status == aimdk_msgs::msg::CommonState::SUCCESS;

    if (ok) {
      RCLCPP_INFO(this->get_logger(), "PlayAudioFile accepted. code=%ld status=%d msg=%s", code, status, response->response.message.c_str());
      return true;
    }

    RCLCPP_ERROR(this->get_logger(),
                 "PlayAudioFile failed. code=%ld status=%d msg=%s",
                 code, status, response->response.message.c_str());
    return false;
  }

 private:
  bool wait_for_service()
  {
    while (!client_->wait_for_service(std::chrono::seconds(2))) {
      if (!rclcpp::ok()) {
        return false;
      }
      RCLCPP_INFO(this->get_logger(), "Waiting for service: %s", service_name_.c_str());
    }
    RCLCPP_INFO(this->get_logger(), "Service available, ready to send request.");
    return true;
  }

  std::string service_name_  = "/aimdk_5Fmsgs/srv/PlayAudioFile";
  std::string pkg_name_      = "sdk_demo";
  std::string file_name_     = "小星星.wav";
  std::string file_path_     = "/robot/software/aimrt_agent/bin/cfg/q1/audio";
  std::string sample_format_ = "S16_LE";
  std::string coding_format_ = "wave";
  int channels_              = 1;
  int sample_rate_           = 24000;
  int size_                  = 0;
  int priority_              = 6;
  int priority_weight_       = 0;
  std::string media_role_    = "Music";
  rclcpp::Client<aimdk_msgs::srv::PlayAudioFile>::SharedPtr client_;
};

int main(int argc, char *argv[])
{
  try {
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    g_node        = std::make_shared<PlayAudioFileClient>();
    auto client   = std::dynamic_pointer_cast<PlayAudioFileClient>(g_node);
    const bool ok = client ? client->send_request() : false;

    g_node.reset();
    rclcpp::shutdown();
    return ok ? 0 : 1;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("main"), "Program exited with exception: %s", e.what());
    return 1;
  }
}
音频文件播放 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/play_audio_from_robot.py

python
#!/usr/bin/env python3

"""
Audio File Playback Example Script

Description:
  This script demonstrates how to play audio files on the robot using the PlayAudioFile service.
  Default sample rate is 24kHz. Supports various audio formats with configurable parameters.

Prerequisites:
  - Robot audio service must be running
  - Audio file must exist in the specified path
  - Audio file must be 24kHz, 16-bit, mono WAV format
  - Audio output device must be working properly

Usage:
  python3 play_audio_from_robot.py --ros-args -p file_name:=<filename> -p file_path:=<directory> -p media_role:=<role>

Example:
  python3 play_audio_from_robot.py --ros-args -p file_name:=小星星.wav -p file_path:=/robot/software/aimrt_agent/bin/cfg/q1/audio -p media_role:=Music

Parameters:
  - file_name: Audio file name to play (default: 小星星.wav)
  - file_path: Directory containing the audio file (default: /robot/software/aimrt_agent/bin/cfg/q1/audio)
  - media_role: PulseAudio media.role (default: Music)
    Alert(系统告警,优先级100) | Notification(系统提示音,优先级80)
    Communication(对话语音,优先级60) | Music(音乐/媒体,优先级40)
    非 Music 角色播放时会自动降低(duck)音乐音量
"""

import rclpy
import rclpy.logging
import time
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest, CommonState
from aimdk_msgs.srv import PlayAudioFile


class PlayAudioFileClient(Node):
    def __init__(self):
        super().__init__("play_audio_from_robot_client")
        self.file_name = self.declare_parameter("file_name", "小星星.wav").value
        self.file_path = self.declare_parameter("file_path", "/robot/software/aimrt_agent/bin/cfg/q1/audio").value
        self.media_role = self.declare_parameter("media_role", "Music").value

        self.service_name = "/aimdk_5Fmsgs/srv/PlayAudioFile"
        self.pkg_name = "sdk_demo"
        self.sample_format = "S16_LE"
        self.coding_format = "wave"
        self.channels = 1
        self.sample_rate = 24000
        self.size = 0
        self.priority = 6
        self.priority_weight = 0

        self.client = self.create_client(PlayAudioFile, self.service_name)
        self.get_logger().info("PlayAudioFile client node created.")

    def wait_for_service(self) -> bool:
        while not self.client.wait_for_service(timeout_sec=2.0):
            if not rclpy.ok():
                return False
            self.get_logger().info(f"Waiting for service: {self.service_name}")
        self.get_logger().info("Service available, ready to send request.")
        return True

    def send_request(self) -> bool:
        if not self.wait_for_service():
            return False

        try:
            request = PlayAudioFile.Request()
            request.request = CommonRequest()
            request.request.header.stamp = self.get_clock().now().to_msg()

            # pkg_name/file_name/file_path locate the audio resource; info describes its format.
            request.file.pkg_name = self.pkg_name
            request.file.file_name = self.file_name
            request.file.file_path = self.file_path

            if not request.file.file_name:
                self.get_logger().error("file_name is empty.")
                return False

            request.file.info.channels = self.channels
            request.file.info.sample_rate = self.sample_rate
            request.file.info.size = self.size
            request.file.info.sample_format = self.sample_format
            request.file.info.coding_format = self.coding_format
            request.file.priority = self.priority
            request.file.priority_weight = self.priority_weight
            request.file.media_role = self.media_role

            self.get_logger().info(
                "Sending PlayAudioFile request: "
                f"file={request.file.file_name}, "
                f"path={request.file.file_path}, "
                f"pkg={request.file.pkg_name}, "
                f"ch={self.channels}, "
                f"sr={self.sample_rate}, "
                f"fmt={self.sample_format}, "
                f"coding={self.coding_format}, "
                f"priority={self.priority}, "
                f"weight={self.priority_weight}"
            )

            for i in range(3):
                future = self.client.call_async(request)
                rclpy.spin_until_future_complete(self, future, timeout_sec=5)

                if future.done():
                    break

                self.get_logger().info(f'trying ... [{i}]')
                time.sleep(0.2)
            
            if not future.done():
                self.get_logger().error("PlayAudioFile call failed or timed out.")
                return False

            response = future.result()
            if response is None:
                self.get_logger().error("PlayAudioFile call failed or timed out.")
                return False

            code = response.response.header.code
            status = response.response.status.value
            # Treat code==0 or status==SUCCESS as success.
            ok = code == 0 or status == CommonState.SUCCESS

            if ok:
                self.get_logger().info(
                    "PlayAudioFile accepted. "
                    f"code={code} status={status} msg={response.response.message}"
                )
                return True

            self.get_logger().error(
                f"PlayAudioFile failed. "
                f"code={code} status={status} "
                f"msg={response.response.message}"
            )
            return False
        except Exception as error:  # noqa: BLE001
            self.get_logger().error(f"Exception occurred: {error}")
            return False


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        node = PlayAudioFileClient()
        ok = node.send_request()
        return 0 if ok else 1
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("main").error(
            f"Program exited with exception: {error}"
        )
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

停止音频播放(Service: StopAudioPlay) ​

与 PlayAudioFile 服务配对使用,用于停止机器人当前正在播放的音频。该接口会停止所有活跃的音频播放会话。

停止音频播放 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp stop_audio_play

cpp
/*
 @file stop_audio_play.cpp
 @brief 停止音频播放示例脚本

 @description
   通过 StopAudioPlay 服务停止机器人当前正在播放的音频。
   该接口会停止所有活跃的音频播放会话。

 @prerequisites
   - 音频管理服务必须正在运行

 @usage
   ros2 run aimdk_examples_cpp stop_audio_play

 @example
   ros2 run aimdk_examples_cpp stop_audio_play
 */

#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/srv/stop_audio_play.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <csignal>
#include <memory>
#include <thread>

using namespace std::chrono_literals;

namespace
{

constexpr auto kServiceWaitInterval = 2s;
constexpr auto kServiceCallTimeout  = 5s;
constexpr int kMaxRetryCount = 3;

}  // namespace

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class StopAudioPlayClient : public rclcpp::Node
{
 public:
  StopAudioPlayClient() : Node("stop_audio_play_client")
  {
    client_ = this->create_client<aimdk_msgs::srv::StopAudioPlay>(
      "/aimdk_5Fmsgs/srv/StopAudioPlay");
    RCLCPP_INFO(this->get_logger(), "StopAudioPlay client node created.");

    while (!client_->wait_for_service(kServiceWaitInterval)) {
      if (!rclcpp::ok())
        return;
      RCLCPP_INFO(this->get_logger(), "Waiting for service...");
    }
    RCLCPP_INFO(this->get_logger(), "Service available, ready to send request.");
  }

  bool send_request()
  {
    try {
      for (int i = 0; i < kMaxRetryCount; ++i) {
        auto request = std::make_shared<aimdk_msgs::srv::StopAudioPlay::Request>();
        request->request.header.stamp = this->now();

        RCLCPP_INFO(this->get_logger(),
                    "Sending StopAudioPlay request (%d/%d)...", i + 1,
                    kMaxRetryCount);

        auto future = client_->async_send_request(request);

        if (rclcpp::spin_until_future_complete(this->get_node_base_interface(),
                                               future, kServiceCallTimeout)
            == rclcpp::FutureReturnCode::SUCCESS)
        {
          auto response = future.get();
          RCLCPP_INFO(this->get_logger(), "StopAudioPlay response code: %ld",
                      response->response.header.code);
          if (response->response.header.code == 0) {
            RCLCPP_INFO(this->get_logger(),
                        "StopAudioPlay request successful. Audio playback stopped.");
            return true;
          }
          RCLCPP_WARN(this->get_logger(),
                      "StopAudioPlay failed with code: %ld, retrying...",
                      response->response.header.code);
        } else {
          RCLCPP_WARN(this->get_logger(),
                      "StopAudioPlay timed out, retrying (%d/%d)...",
                      i + 1, kMaxRetryCount);
        }
        std::this_thread::sleep_for(1s);
      }
      RCLCPP_ERROR(this->get_logger(),
                   "StopAudioPlay failed after %d retries", kMaxRetryCount);
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "StopAudioPlay exception: %s", e.what());
      return false;
    }
  }

 private:
  rclcpp::Client<aimdk_msgs::srv::StopAudioPlay>::SharedPtr client_;
};

int main(int argc, char **argv)
{
  rclcpp::init(argc, argv);
  std::signal(SIGINT, signal_handler);
  std::signal(SIGTERM, signal_handler);

  auto node = std::make_shared<StopAudioPlayClient>();
  bool success = node->send_request();

  rclcpp::shutdown();
  return success ? 0 : 1;
}
停止音频播放 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/stop_audio_play.py

python
#!/usr/bin/env python3

"""
停止音频播放示例脚本

Description:
  通过 StopAudioPlay 服务停止机器人当前正在播放的音频。
  该接口会停止所有活跃的音频播放会话。

Prerequisites:
  - 音频管理服务必须正在运行

Usage:
  python3 stop_audio_play.py

Example:
  python3 stop_audio_play.py
"""

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_services_default

from aimdk_msgs.srv import StopAudioPlay


class StopAudioPlayClient(Node):
    def __init__(self):
        super().__init__("stop_audio_play_client")

        self.client = self.create_client(
            StopAudioPlay,
            "/aimdk_5Fmsgs/srv/StopAudioPlay",
            qos_profile=qos_profile_services_default,
        )

        self.get_logger().info("StopAudioPlay client node created.")

        while not self.client.wait_for_service(timeout_sec=2.0):
            self.get_logger().info("Waiting for service...")

        self.get_logger().info("Service available, ready to send request.")

    def send_request(self) -> bool:
        max_retry_count = 3
        for i in range(max_retry_count):
            request = StopAudioPlay.Request()
            request.request.header.stamp = self.get_clock().now().to_msg()

            self.get_logger().info(
                f"Sending StopAudioPlay request ({i + 1}/{max_retry_count})..."
            )

            future = self.client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=5.0)

            if future.done():
                response = future.result()
                if response is not None:
                    self.get_logger().info(
                        f"StopAudioPlay response code: {response.response.header.code}"
                    )
                    if response.response.header.code == 0:
                        self.get_logger().info(
                            "StopAudioPlay request successful. Audio playback stopped."
                        )
                        return True
                    else:
                        self.get_logger().warn(
                            f"StopAudioPlay failed with code: {response.response.header.code}, "
                            f"retrying ({i + 1}/{max_retry_count})..."
                        )
                else:
                    self.get_logger().warn(
                        f"StopAudioPlay returned None, retrying ({i + 1}/{max_retry_count})..."
                    )
            else:
                self.get_logger().warn(
                    f"StopAudioPlay timed out, retrying ({i + 1}/{max_retry_count})..."
                )

        self.get_logger().error(
            f"StopAudioPlay failed after {max_retry_count} retries"
        )
        return False


def main(args=None):
    rclpy.init(args=args)
    node = StopAudioPlayClient()

    try:
        success = node.send_request()
        return 0 if success else 1
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

TCP音频播放(TCP: 6001) ​

TCP音频播放 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp play_audio_from_pc <机器人IP> <音频文件>

cpp
/*
 @file play_audio_from_pc.cpp
 @brief 音频播放示例(PC 端推送)

 @description
   通过 PulseAudio TCP 协议(simple-protocol-tcp)将 PC 本地音频文件发送到机器人扬声器播放。

   支持格式:
     - WAV 文件:自动检测 RIFF 头,转换为 48kHz mono S16LE
     - PCM 文件:48kHz mono S16LE,直接传输
     - 多声道 WAV 自动智能混音:识别活跃通道,避免静音通道稀释信号
     - 非 48kHz 采样率自动重采样

 @prerequisites
   - 示例脚本会通过 SSH 自动在机器人端加载 TCP 播放模块(端口 6001)
   - 使用 SSH 密钥时:将售后提供的密钥目录(<机器人SN>_soc0/)放到 SDK 根目录下
     (与 examples/ 同级),并修改权限:
     sudo chown -R $USER:$USER ./<机器人SN>_soc0/
     chmod 600 ./<机器人SN>_soc0/id_ed25519
     然后在 SDK 根目录下执行示例命令,使用 -i ./<机器人SN>_soc0/id_ed25519 指定密钥。

 @usage
   ./build/aimdk_examples_cpp/play_audio_from_pc [-i SSH_KEY] <机器人IP> <音频文件>

   可选参数:
     -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)

 @example
   ./build/aimdk_examples_cpp/play_audio_from_pc <机器人IP> mic_mono.wav
   // 使用 SSH 密钥(网线连接时 IP 为 10.1.1.100)
   ./build/aimdk_examples_cpp/play_audio_from_pc -i ./<机器人SN>_soc0/id_ed25519 10.1.1.100 mic_mono.wav
 */

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <thread>
#include <vector>

namespace {

constexpr int kRate = 48000;
constexpr int kChannels = 1;       // Mono output
constexpr int kSampleWidth = 2;    // 16-bit = 2 bytes
constexpr int kPort = 6001;
constexpr double kChunkDuration = 0.1;  // 100ms per send chunk

std::atomic<bool> g_stop{false};

}  // namespace

static void signal_handler(int) { g_stop.store(true); }

// ---------------------------------------------------------------------------
// Auto-setup: load PulseAudio TCP modules on robot via SSH
// ---------------------------------------------------------------------------

static void setup_robot_audio_tcp(const char *robot_ip, const char *ssh_key = nullptr) {
  // 先检查模块是否已加载,已加载则跳过,避免重复输入密码
  char cmd[1024];
  if (ssh_key) {
    snprintf(cmd, sizeof(cmd),
             "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i %s run@%s '"
             "if pactl list modules short 2>/dev/null | grep -q module-simple-protocol-tcp; then "
             "echo MODULE_ALREADY_LOADED; "
             "else "
             "pactl load-module module-simple-protocol-tcp "
             "sink=@DEFAULT_SINK@ playback=true port=%d "
             "format=s16le rate=%d channels=%d listen=0.0.0.0 && "
             "echo MODULE_LOADED; "
             "fi'",
             ssh_key, robot_ip, kPort, kRate, kChannels);
  } else {
    snprintf(cmd, sizeof(cmd),
             "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 run@%s '"
             "if pactl list modules short 2>/dev/null | grep -q module-simple-protocol-tcp; then "
             "echo MODULE_ALREADY_LOADED; "
             "else "
             "pactl load-module module-simple-protocol-tcp "
             "sink=@DEFAULT_SINK@ playback=true port=%d "
             "format=s16le rate=%d channels=%d listen=0.0.0.0 && "
             "echo MODULE_LOADED; "
             "fi'",
             robot_ip, kPort, kRate, kChannels);
  }

  FILE *fp = popen(cmd, "r");
  if (!fp) {
    printf("SSH 连接失败\n");
    return;
  }
  std::string output;
  char buf[256];
  while (fgets(buf, sizeof(buf), fp)) {
    output += buf;
  }
  int ret = pclose(fp);
  (void)ret;

  if (output.find("MODULE_ALREADY_LOADED") != std::string::npos) {
    printf("播放模块已在机器人端加载(跳过加载)\n");
  } else if (output.find("MODULE_LOADED") != std::string::npos) {
    printf("已在机器人端加载播放模块 (端口 %d)\n", kPort);
  } else {
    printf("警告: 播放模块加载可能未成功(stderr 已输出到终端)\n");
  }
}

// ---------------------------------------------------------------------------
// Binary reading helpers
// ---------------------------------------------------------------------------

static uint16_t read_u16_le(const uint8_t *p) {
  return static_cast<uint16_t>(p[0]) | (static_cast<uint16_t>(p[1]) << 8);
}

static uint32_t read_u32_le(const uint8_t *p) {
  return static_cast<uint32_t>(p[0]) |
         (static_cast<uint32_t>(p[1]) << 8) |
         (static_cast<uint32_t>(p[2]) << 16) |
         (static_cast<uint32_t>(p[3]) << 24);
}

static int16_t read_s16_le(const uint8_t *p) {
  return static_cast<int16_t>(read_u16_le(p));
}

// ---------------------------------------------------------------------------
// File loading
// ---------------------------------------------------------------------------

static bool load_file(const char *path, std::vector<uint8_t> &out) {
  FILE *f = fopen(path, "rb");
  if (!f) {
    perror(path);
    return false;
  }
  fseek(f, 0, SEEK_END);
  long size = ftell(f);
  fseek(f, 0, SEEK_SET);
  if (size <= 0) { fclose(f); return false; }
  out.resize(static_cast<size_t>(size));
  size_t n = fread(out.data(), 1, out.size(), f);
  fclose(f);
  return n == out.size();
}

// ---------------------------------------------------------------------------
// WAV loader with format conversion (operates on in-memory data)
// ---------------------------------------------------------------------------

static bool is_wav_data(const std::vector<uint8_t> &data) {
  return data.size() >= 4 && memcmp(data.data(), "RIFF", 4) == 0;
}

static bool convert_wav_to_pcm(const std::vector<uint8_t> &file,
                               std::vector<uint8_t> &pcm_out) {
  if (file.size() < 44 || memcmp(file.data(), "RIFF", 4) != 0 ||
      memcmp(file.data() + 8, "WAVE", 4) != 0) {
    printf("错误: 无效的 WAV 文件\n");
    return false;
  }

  // Walk chunks to find "fmt " and "data"
  size_t pos = 12;
  int src_rate = 0, src_channels = 0, src_sampwidth = 0;
  const uint8_t *audio_data = nullptr;
  size_t audio_size = 0;

  while (pos + 8 <= file.size()) {
    uint32_t chunk_size = read_u32_le(file.data() + pos + 4);

    if (memcmp(file.data() + pos, "fmt ", 4) == 0 && chunk_size >= 16) {
      uint16_t format = read_u16_le(file.data() + pos + 8);
      if (format != 1) {
        printf("错误: 仅支持 PCM 格式 WAV (format=%d)\n", format);
        return false;
      }
      src_channels = read_u16_le(file.data() + pos + 10);
      src_rate = static_cast<int>(read_u32_le(file.data() + pos + 12));
      uint16_t bps = read_u16_le(file.data() + pos + 22);
      src_sampwidth = bps / 8;
      if (src_sampwidth != 2) {
        printf("错误: 仅支持 16-bit PCM WAV,当前 %d-bit\n", bps);
        return false;
      }
    } else if (memcmp(file.data() + pos, "data", 4) == 0) {
      audio_data = file.data() + pos + 8;
      audio_size = chunk_size;
      if (pos + 8 + audio_size > file.size()) {
        audio_size = file.size() - pos - 8;
      }
    }

    pos += 8 + chunk_size;
    if (chunk_size % 2 != 0) pos++;
  }

  if (!audio_data || audio_size == 0) {
    printf("错误: WAV 文件中未找到 data chunk\n");
    return false;
  }

  size_t n_samples = audio_size / src_sampwidth;
  double src_duration = static_cast<double>(n_samples) / src_channels / src_rate;
  printf("WAV 格式: %dHz, %dch, 16bit, %zu帧 (%.1f秒)\n",
         src_rate, src_channels, n_samples / src_channels, src_duration);

  // Parse source samples
  std::vector<int16_t> samples(n_samples);
  for (size_t i = 0; i < n_samples; ++i) {
    samples[i] = read_s16_le(audio_data + i * src_sampwidth);
  }

  // Mono mixdown if multi-channel
  std::vector<int16_t> mono;
  if (src_channels > 1) {
    // Find active channels: per-channel peak, only mix channels with signal
    std::vector<int32_t> ch_peaks(src_channels, 0);
    for (size_t i = 0; i < n_samples; i += src_channels) {
      for (int c = 0; c < src_channels && i + c < n_samples; ++c) {
        int32_t a = std::abs(static_cast<int32_t>(samples[i + c]));
        if (a > ch_peaks[c]) ch_peaks[c] = a;
      }
    }

    // A channel is "active" if its peak exceeds a noise floor
    std::vector<int> active;
    for (int c = 0; c < src_channels; ++c) {
      if (ch_peaks[c] > 200) active.push_back(c);
    }
    if (active.empty()) {
      for (int c = 0; c < src_channels; ++c) active.push_back(c);
    }

    printf("混音: %d 声道 -> 单声道 (活跃通道:", src_channels);
    for (int c : active) printf(" ch%d", c + 1);
    printf(")\n");
    printf("各声道峰值:");
    for (int c = 0; c < src_channels; ++c) printf(" ch%d=%d", c + 1, ch_peaks[c]);
    printf("\n");

    size_t n_frames = n_samples / src_channels;
    mono.resize(n_frames);
    int n_active = static_cast<int>(active.size());
    for (size_t i = 0; i < n_frames; ++i) {
      int32_t sum = 0;
      for (int c : active) {
        sum += samples[i * src_channels + c];
      }
      int32_t avg = sum / n_active;
      if (avg > 32767) avg = 32767;
      if (avg < -32768) avg = -32768;
      mono[i] = static_cast<int16_t>(avg);
    }
  } else {
    mono = std::move(samples);
  }

  // Resample to 48kHz if needed
  std::vector<int16_t> output;
  if (src_rate != kRate) {
    printf("重采样: %dHz -> %dHz\n", src_rate, kRate);
    double ratio = static_cast<double>(kRate) / src_rate;
    size_t new_len = static_cast<size_t>(mono.size() * ratio);
    output.resize(new_len);
    for (size_t i = 0; i < new_len; ++i) {
      double src_idx = static_cast<double>(i) / ratio;
      size_t idx_low = static_cast<size_t>(src_idx);
      size_t idx_high = std::min(idx_low + 1, mono.size() - 1);
      double frac = src_idx - static_cast<double>(idx_low);
      double val = mono[idx_low] * (1.0 - frac) + mono[idx_high] * frac;
      int32_t clamped = static_cast<int32_t>(val);
      if (clamped > 32767) clamped = 32767;
      if (clamped < -32768) clamped = -32768;
      output[i] = static_cast<int16_t>(clamped);
    }
  } else {
    output = std::move(mono);
  }

  // Convert to PCM bytes
  pcm_out.resize(output.size() * kSampleWidth);
  for (size_t i = 0; i < output.size(); ++i) {
    auto v = static_cast<uint16_t>(output[i]);
    pcm_out[i * 2] = static_cast<uint8_t>(v & 0xFF);
    pcm_out[i * 2 + 1] = static_cast<uint8_t>((v >> 8) & 0xFF);
  }

  return true;
}

// ---------------------------------------------------------------------------
// TCP streaming playback
// ---------------------------------------------------------------------------

static bool connect_with_timeout(int sock, const struct sockaddr *addr,
                                 socklen_t addrlen, int timeout_sec) {
  // Set non-blocking
  int flags = fcntl(sock, F_GETFL, 0);
  if (flags < 0) return false;
  fcntl(sock, F_SETFL, flags | O_NONBLOCK);

  int ret = connect(sock, addr, addrlen);
  if (ret == 0) {
    // Connected immediately
    fcntl(sock, F_SETFL, flags);
    return true;
  }
  if (errno != EINPROGRESS) {
    fcntl(sock, F_SETFL, flags);
    return false;
  }

  // Wait for connection with timeout, checking g_stop periodically
  auto deadline = std::chrono::steady_clock::now() +
                  std::chrono::seconds(timeout_sec);
  while (std::chrono::steady_clock::now() < deadline) {
    if (g_stop.load()) {
      fcntl(sock, F_SETFL, flags);
      errno = EINTR;
      return false;
    }
    auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
        deadline - std::chrono::steady_clock::now()).count();
    if (remaining <= 0) break;
    int wait_ms = static_cast<int>(std::min(remaining, 200L));

    struct pollfd pfd{};
    pfd.fd = sock;
    pfd.events = POLLOUT;
    int n = poll(&pfd, 1, wait_ms);
    if (n > 0 && (pfd.revents & POLLOUT)) {
      int err = 0;
      socklen_t len = sizeof(err);
      getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &len);
      fcntl(sock, F_SETFL, flags);
      if (err == 0) return true;
      errno = err;
      return false;
    }
    if (n < 0 && errno != EINTR) {
      fcntl(sock, F_SETFL, flags);
      return false;
    }
  }

  // Timed out or stopped
  fcntl(sock, F_SETFL, flags);
  errno = ETIMEDOUT;
  return false;
}

static bool play_pcm(const char *robot_ip, const std::vector<uint8_t> &pcm) {
  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("socket");
    return false;
  }

  struct sockaddr_in addr{};
  addr.sin_family = AF_INET;
  addr.sin_port = htons(kPort);
  if (inet_pton(AF_INET, robot_ip, &addr.sin_addr) <= 0) {
    printf("错误: 无效的 IP 地址: %s\n", robot_ip);
    close(sock);
    return false;
  }

  printf("正在连接 %s:%d ...\n", robot_ip, kPort);
  if (!connect_with_timeout(sock, reinterpret_cast<struct sockaddr *>(&addr),
                            sizeof(addr), 5)) {
    if (g_stop.load()) {
      printf("\n已取消\n");
    } else {
      perror("connect");
      printf("连接失败,请检查机器人 IP 是否正确以及 TCP 播放模块是否已加载。\n");
    }
    close(sock);
    return false;
  }

  int bytes_per_sec = kRate * kChannels * kSampleWidth;
  size_t chunk_bytes = static_cast<size_t>(bytes_per_sec * kChunkDuration);
  double total_secs = static_cast<double>(pcm.size()) / bytes_per_sec;

  printf("已连接 %s:%d,播放中...\n", robot_ip, kPort);

  auto next_send = std::chrono::steady_clock::now();
  size_t offset = 0;

  while (!g_stop.load() && offset < pcm.size()) {
    size_t remaining = pcm.size() - offset;
    size_t send_size = std::min(chunk_bytes, remaining);

    ssize_t sent = send(sock, pcm.data() + offset, send_size, MSG_NOSIGNAL);
    if (sent <= 0) {
      if (sent < 0) perror("send");
      printf("\n连接断开\n");
      break;
    }
    offset += static_cast<size_t>(sent);

    double played = static_cast<double>(offset) / bytes_per_sec;
    printf("\r已播放 %.1f / %.1f 秒", played, total_secs);
    fflush(stdout);

    // Precise timing: compensate for network/processing delay
    next_send += std::chrono::microseconds(
        static_cast<int64_t>(kChunkDuration * 1e6));
    auto now = std::chrono::steady_clock::now();
    if (next_send > now) {
      std::this_thread::sleep_for(next_send - now);
    }
  }

  printf("\n播放结束\n");
  close(sock);
  return true;
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

int main(int argc, char *argv[]) {
  if (argc < 3) {
    printf("用法: %s [-i SSH_KEY] <机器人IP> <音频文件>\n", argv[0]);
    printf("支持格式: .pcm (48kHz mono S16LE), .wav (自动转换)\n");
    printf("\n");
    printf("  可选参数:\n");
    printf("    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)\n");
    return 1;
  }

  // 解析可选参数 -i SSH_KEY
  const char *ssh_key = nullptr;
  int arg_idx = 1;
  if (argc >= 4 && strcmp(argv[1], "-i") == 0) {
    if (argc < 5) {
      printf("错误: -i 参数需要指定 SSH 私钥文件路径\n");
      return 1;
    }
    ssh_key = argv[2];
    arg_idx = 3;
  }

  const char *robot_ip = argv[arg_idx];
  const char *audio_file = argv[arg_idx + 1];

  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);

  // Auto-load TCP playback module on robot via SSH
  if (ssh_key) {
    printf("使用 SSH 密钥: %s\n", ssh_key);
  }
  setup_robot_audio_tcp(robot_ip, ssh_key);
  if (g_stop.load()) {
    printf("\n已取消\n");
    return 0;
  }

  // Load raw file data (local)
  std::vector<uint8_t> raw;
  if (!load_file(audio_file, raw)) return 1;

  // Convert to PCM (auto-detect WAV or treat as raw PCM)
  std::vector<uint8_t> pcm;
  if (is_wav_data(raw)) {
    printf("检测到 WAV 文件,正在转换...\n");
    if (!convert_wav_to_pcm(raw, pcm)) return 1;
    int bytes_per_sec = kRate * kChannels * kSampleWidth;
    printf("转换完成: %zu 字节 (%.1f 秒)\n",
           pcm.size(), static_cast<double>(pcm.size()) / bytes_per_sec);
  } else {
    printf("按 PCM 格式使用 (假设 48kHz mono S16LE)\n");
    pcm = std::move(raw);
  }

  if (pcm.empty()) {
    printf("错误: 音频数据为空\n");
    return 1;
  }

  return play_pcm(robot_ip, pcm) ? 0 : 1;
}
TCP音频播放 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/play_audio_from_pc.py <机器人IP> <音频文件>

python
#!/usr/bin/env python3

"""Play Audio Example

通过 PulseAudio TCP 协议(simple-protocol-tcp)将音频文件发送到机器人扬声器播放。

支持格式:
  - WAV 文件:自动检测 RIFF 头,转换为 48kHz mono S16LE
  - PCM 文件:48kHz mono S16LE,直接传输
  - 多声道 WAV 自动智能混音:识别活跃通道,避免静音通道稀释信号
  - 非 48kHz 采样率自动重采样

前提条件:
  - 示例脚本会通过 SSH 自动在机器人端加载 TCP 播放模块(端口 6001)
  - 使用 SSH 密钥时:将售后提供的密钥目录(<机器人SN>_soc0/)放到 SDK 根目录下
    (与 examples/ 同级),并修改权限:
    sudo chown -R $USER:$USER ./<机器人SN>_soc0/
    chmod 600 ./<机器人SN>_soc0/id_ed25519
    然后在 SDK 根目录下执行示例命令,使用 -i ./<机器人SN>_soc0/id_ed25519 指定密钥。

用法:
  python3 examples/python/play_audio_from_pc.py [-i SSH_KEY] <机器人IP> <音频文件>

  可选参数:
    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)

示例:
  python3 examples/python/play_audio_from_pc.py <机器人IP> mic_mono.wav
  # 使用 SSH 密钥(网线连接时 IP 为 10.1.1.100)
  python3 examples/python/play_audio_from_pc.py -i ./<机器人SN>_soc0/id_ed25519 10.1.1.100 mic_mono.wav
"""

import socket
import subprocess
import sys
import signal
import struct
import time
import wave
from io import BytesIO

# ===== Configuration (must match robot-side pactl parameters) =====
RATE = 48000       # Robot speaker native sample rate
CHANNELS = 1       # Mono
SAMPLE_WIDTH = 2   # 16-bit = 2 bytes
PORT = 6001


def setup_robot_audio_tcp(robot_ip, ssh_key=None):
    """Auto-load PulseAudio TCP playback module on robot via SSH.

    先检查模块是否已加载,已加载则跳过。
    SSH 输出直接显示在终端,以便用户看到密码提示并完成认证。
    """
    ssh_opts = "-o StrictHostKeyChecking=no -o ConnectTimeout=5"
    if ssh_key:
        ssh_opts += " -i %s" % ssh_key
    # 一条 SSH 命令:先检查,未加载才加载,避免重复输入密码
    cmd = (
        'ssh %s run@%s \''
        'if pactl list modules short 2>/dev/null | grep -q module-simple-protocol-tcp; then '
        'echo MODULE_ALREADY_LOADED; '
        'else '
        'pactl load-module module-simple-protocol-tcp '
        'sink=@DEFAULT_SINK@ playback=true port=%d '
        'format=s16le rate=%d channels=%d listen=0.0.0.0 && '
        'echo MODULE_LOADED; '
        'fi\''
        % (ssh_opts, robot_ip, PORT, RATE, CHANNELS)
    )
    try:
        result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
        output = result.stdout.strip()
        if "MODULE_ALREADY_LOADED" in output:
            print("播放模块已在机器人端加载(跳过加载)")
        elif "MODULE_LOADED" in output:
            print("已在机器人端加载播放模块 (端口 %d)" % PORT)
        else:
            print("警告: 播放模块加载可能未成功(stderr 已输出到终端)")
    except KeyboardInterrupt:
        print("\n已取消")
        sys.exit(0)
    except subprocess.TimeoutExpired:
        print("SSH 连接超时,请检查网络连接或机器人 IP")
        sys.exit(1)
    except Exception as e:
        print("SSH 连接失败: %s" % e)
        sys.exit(1)


def is_wav_data(data):
    """Check if data starts with RIFF header (WAV format)."""
    return len(data) >= 4 and data[:4] == b"RIFF"


def load_wav_as_pcm(data):
    """Load WAV data from bytes buffer and convert to 48kHz mono S16LE PCM bytes.

    Handles:
      - Any sample rate (resamples to 48kHz)
      - Multi-channel (mixes down to mono)
      - 16-bit PCM format

    Returns:
        PCM bytes ready for streaming.
    """
    with wave.open(BytesIO(data), "rb") as wf:
        src_rate = wf.getframerate()
        src_channels = wf.getnchannels()
        src_sampwidth = wf.getsampwidth()
        n_frames = wf.getnframes()

        if src_sampwidth != 2:
            print("警告: 仅支持 16-bit PCM WAV,当前 %d-bit" % (src_sampwidth * 8))
            sys.exit(1)

        print("WAV 格式: %dHz, %dch, 16bit, %d帧 (%.1f秒)" % (
            src_rate, src_channels, n_frames, n_frames / src_rate))

        raw = wf.readframes(n_frames)

    # Parse samples
    n_samples = len(raw) // 2
    samples = struct.unpack("<%dh" % n_samples, raw)

    # Mix down to mono if multi-channel
    if src_channels > 1:
        # Find active channels: per-channel peak, only mix channels with signal
        ch_peaks = [0] * src_channels
        for i in range(0, n_samples, src_channels):
            for c in range(min(src_channels, n_samples - i)):
                a = abs(samples[i + c])
                if a > ch_peaks[c]:
                    ch_peaks[c] = a

        # A channel is "active" if its peak exceeds a noise floor
        active = [c for c in range(src_channels) if ch_peaks[c] > 200]
        if not active:
            active = list(range(src_channels))  # all quiet, use all

        print("混音: %d 声道 -> 单声道 (活跃通道: %s)" % (
            src_channels, ", ".join("ch%d" % (c + 1) for c in active)))
        print("各声道峰值: %s" % " ".join("ch%d=%d" % (c + 1, ch_peaks[c]) for c in range(src_channels)))

        mono_samples = []
        for i in range(0, n_samples, src_channels):
            s = 0
            for c in active:
                if i + c < n_samples:
                    s += samples[i + c]
            avg = s // len(active)
            mono_samples.append(int(max(-32768, min(32767, avg))))
        samples = mono_samples
        n_samples = len(samples)

    # Resample if not 48kHz
    if src_rate != RATE:
        print("重采样: %dHz -> %dHz" % (src_rate, RATE))
        ratio = RATE / src_rate
        new_len = int(n_samples * ratio)
        resampled = []
        for i in range(new_len):
            src_idx = i / ratio
            idx_low = int(src_idx)
            idx_high = min(idx_low + 1, n_samples - 1)
            frac = src_idx - idx_low
            # Linear interpolation
            val = samples[idx_low] * (1 - frac) + samples[idx_high] * frac
            resampled.append(int(max(-32768, min(32767, val))))
        samples = resampled

    return struct.pack("<%dh" % len(samples), *samples)


def load_file(path):
    """Load file as raw bytes from local path."""
    try:
        with open(path, "rb") as f:
            return f.read()
    except IOError:
        print("错误: 无法打开本地文件: %s" % path)
        sys.exit(1)


def main():
    if len(sys.argv) < 3:
        print("用法: %s [-i SSH_KEY] <机器人IP> <audio_file>" % sys.argv[0])
        print()
        print("  可选参数:")
        print("    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)")
        print()
        print("支持格式: .pcm (48kHz mono S16LE), .wav (自动转换)")
        sys.exit(1)

    # 解析可选参数 -i SSH_KEY
    ssh_key = None
    args = sys.argv[1:]
    if args[0] == "-i":
        if len(args) < 4:
            print("错误: -i 参数需要指定 SSH 私钥文件路径")
            sys.exit(1)
        ssh_key = args[1]
        args = args[2:]

    robot_ip = args[0]
    audio_file = args[1]

    stop = False

    def on_signal(*_):
        nonlocal stop
        stop = True
    signal.signal(signal.SIGINT, on_signal)

    # Auto-load TCP playback module on robot via SSH
    if ssh_key:
        print("使用 SSH 密钥: %s" % ssh_key)
    setup_robot_audio_tcp(robot_ip, ssh_key)

    # Load raw file data (local)
    raw = load_file(audio_file)

    # Auto-detect format and convert to PCM
    if is_wav_data(raw):
        print("检测到 WAV 文件,正在转换...")
        pcm_data = load_wav_as_pcm(raw)
        print("转换完成: %d 字节 (%.1f 秒)" % (len(pcm_data), len(pcm_data) / (RATE * CHANNELS * SAMPLE_WIDTH)))
    else:
        print("按 PCM 格式使用 (假设 48kHz mono S16LE)")
        pcm_data = raw

    # Connect to robot
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5)  # 5 second connection timeout
    try:
        sock.connect((robot_ip, PORT))
    except (ConnectionRefusedError, OSError) as e:
        if isinstance(e, ConnectionRefusedError):
            print("连接被拒绝,请检查机器人 IP 是否正确以及 TCP 播放模块是否已加载。")
        else:
            print("连接失败: %s" % e)
            print("请检查机器人 IP 是否正确,以及网络是否可达")
        sys.exit(1)
    sock.settimeout(None)

    print("已连接 %s:%d,播放 %s ..." % (robot_ip, PORT, audio_file))

    # Streaming parameters
    bytes_per_sec = RATE * CHANNELS * SAMPLE_WIDTH  # 96000 bytes/sec
    chunk_duration = 0.1  # 100ms per chunk
    chunk_bytes = int(bytes_per_sec * chunk_duration)  # 9600 bytes

    total = 0
    offset = 0
    next_send_time = time.monotonic()

    while not stop and offset < len(pcm_data):
        chunk = pcm_data[offset:offset + chunk_bytes]
        offset += len(chunk)

        try:
            sock.sendall(chunk)
        except (BrokenPipeError, ConnectionResetError):
            print("\n连接断开")
            break

        total += len(chunk)
        played = total / bytes_per_sec
        total_sec = len(pcm_data) / bytes_per_sec
        # 用固定宽度避免 \r 覆盖残留字符
        print("\r已播放 %.1f / %.1f 秒   " % (played, total_sec), end="", flush=True)

        # Precise timing: sleep in small steps so Ctrl+C responds quickly
        next_send_time += chunk_duration
        while not stop and time.monotonic() < next_send_time:
            remaining = next_send_time - time.monotonic()
            if remaining > 0.01:
                time.sleep(0.01)

    print("\n播放结束              ")
    sock.close()


if __name__ == "__main__":
    main()

代码示例

音频参数控制(Service: GetVolume、SetVolume、GetMute、SetMute) ​

音频参数控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp volume_control

cpp
/*
 @file volume_control.cpp
 @brief Volume Control Demo Example Script
 
 @description
   This script demonstrates how to control robot audio volume and mute settings using TTS services.
   Includes volume adjustment, mute toggle, and TTS playback demonstration.
   Note: If a volume setting step fails, the script will continue to the next step. Please check the logs for any errors.
   The original volume is recorded at startup and automatically restored when the demo finishes or Ctrl+C is pressed.
 
 @prerequisites
   - Robot TTS service must be running
   - Audio output device must be working properly
   - Volume and mute services must be available
 
 @usage
   colcon build --packages-select aimdk_examples_cpp
   ros2 run aimdk_examples_cpp volume_control
 
 @example
   ros2 run aimdk_examples_cpp volume_control
 
 @parameters
   - None
 */

#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/tts_priority_level.hpp"
#include "aimdk_msgs/srv/get_mute.hpp"
#include "aimdk_msgs/srv/get_volume.hpp"
#include "aimdk_msgs/srv/play_tts.hpp"
#include "aimdk_msgs/srv/set_mute.hpp"
#include "aimdk_msgs/srv/set_volume.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <csignal>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <utility>

using namespace std::chrono_literals;

namespace
{

constexpr char kTtsText[] =
  "大家好,我是启元机器人。现在为你演示音频控制示例。"
  "接下来,我会先持续播报一段介绍内容,在播报过程中,系统会依次执行设置音量、查询音量、设置静音和查询静音等操作。"
  "你将听到默认音量、音量调大、音量调小、开启静音以及取消静音这几个阶段的变化。"
  "如果整段流程能够顺利完成,就说明启元的TTS播放、音量控制和静音控制链路都已经正常工作。"
  "感谢你体验启元机器人的音频控制能力。";

constexpr auto kStepInterval        = 5s;  // Delay between demo steps
constexpr auto kServiceWaitInterval = 2s;  // Poll interval while waiting for a service
constexpr auto kServiceCallTimeout  = 5s;  // Timeout for a single service request
constexpr int kMaxRetryCount = 3;          // Maximum retry attempts

}  // namespace

class VolumeControlClient : public rclcpp::Node
{
 public:
  VolumeControlClient() : Node("volume_control_client")
  {
    play_tts_client_ = this->create_client<aimdk_msgs::srv::PlayTts>(play_tts_service_);
    set_volume_client_ = this->create_client<aimdk_msgs::srv::SetVolume>(set_volume_service_);
    get_volume_client_ = this->create_client<aimdk_msgs::srv::GetVolume>(get_volume_service_);
    set_mute_client_ = this->create_client<aimdk_msgs::srv::SetMute>(set_mute_service_);
    get_mute_client_ = this->create_client<aimdk_msgs::srv::GetMute>(get_mute_service_);

    RCLCPP_INFO(this->get_logger(), "Volume control demo node created.");
  }

  bool wait_for_services()
  {
    return wait_for_service(play_tts_client_, play_tts_service_) &&
           wait_for_service(set_volume_client_, set_volume_service_) &&
           wait_for_service(get_volume_client_, get_volume_service_) &&
           wait_for_service(set_mute_client_, set_mute_service_) &&
           wait_for_service(get_mute_client_, get_mute_service_);
  }

  // ---- 信号处理 ----

  void handle_signal(int signal)
  {
    RCLCPP_INFO(this->get_logger(), "Received signal %d, will restore volume before shutdown.", signal);
    std::lock_guard<std::mutex> lock(state_mutex_);
    shutdown_requested_ = true;
  }

  bool is_shutdown_requested() const
  {
    std::lock_guard<std::mutex> lock(state_mutex_);
    return shutdown_requested_;
  }

  // ---- 业务逻辑(同步,在 main 中调用) ----

  bool run_demo()
  {
    RCLCPP_INFO(this->get_logger(), "Volume control demo starts automatically.");
    RCLCPP_INFO(this->get_logger(),
                "Volume note: on this device a larger value means a smaller "
                "actual volume.");

    // Get initial volume to restore later (optional)
    has_original_volume_ = false;
    auto get_init_response = call_service<aimdk_msgs::srv::GetVolume>(
      get_volume_client_, build_get_volume_request(), "GetVolume");
    if (get_init_response) {
      original_volume_ = get_init_response->audio_volume;
      has_original_volume_ = true;
      RCLCPP_INFO(this->get_logger(), "Initial volume: %u", original_volume_);
    } else {
      RCLCPP_WARN(this->get_logger(), "Failed to get initial volume, will skip restoration.");
    }

    if (!play_tts()) {
      RCLCPP_ERROR(this->get_logger(), "PlayTts failed.");
      return false;
    }

    // 定义演示步骤
    struct Step {
      const char *name;
      std::function<bool()> func;
    };
    std::vector<Step> steps = {
      {"设为默认音量", [this]() { return execute_volume_step(30, "设为默认音量"); }},
      {"音量调大",     [this]() { return execute_volume_step(40, "音量调大"); }},
      {"音量调小",     [this]() { return execute_volume_step(20, "音量调小"); }},
      {"设置静音",     [this]() { return execute_mute_step(true, "设置静音"); }},
      {"取消静音",     [this]() { return execute_mute_step(false, "取消静音"); }},
    };

    RCLCPP_INFO(this->get_logger(),
                "TTS accepted. The first control step will run in %ld seconds.",
                kStepInterval.count());

    for (const auto &step : steps) {
      if (is_shutdown_requested()) { break; }
      std::this_thread::sleep_for(kStepInterval);
      if (is_shutdown_requested()) { break; }
      if (!step.func()) {
        RCLCPP_ERROR(this->get_logger(),
                     "Volume control step failed: %s (continuing to next step)", step.name);
      }
    }

    // Restore original volume if available (normal finish or Ctrl+C)
    if (has_original_volume_) {
      RCLCPP_INFO(this->get_logger(), "Restoring original volume: %u", original_volume_);
      if (!execute_volume_step(original_volume_, "恢复原始音量")) {
        RCLCPP_WARN(this->get_logger(), "Failed to restore original volume.");
      }
    } else {
      RCLCPP_INFO(this->get_logger(),
                  "Volume restoration skipped (initial volume unknown).");
    }

    // Always ensure unmuted at the end
    RCLCPP_INFO(this->get_logger(), "Ensuring unmuted state before exit.");
    if (!execute_mute_step(false, "取消静音")) {
      RCLCPP_WARN(this->get_logger(), "Failed to ensure unmuted state.");
    }

    if (has_original_volume_) {
      RCLCPP_INFO(this->get_logger(),
                  "Volume control demo finished. Volume restored to %u, "
                  "mute=false. (Check logs for any failed steps)", original_volume_);
    } else {
      RCLCPP_INFO(this->get_logger(),
                  "Volume control demo finished. (Check logs for any failed steps)");
    }
    return true;
  }

  bool restore_original_volume()
  {
    if (!has_original_volume_) {
      return true;
    }

    RCLCPP_INFO(this->get_logger(), "Restoring original volume: %u", original_volume_);

    auto set_request = build_set_volume_request(original_volume_);
    auto future = set_volume_client_->async_send_request(set_request);
    auto result = rclcpp::spin_until_future_complete(
      shared_from_this(), future, 5s);

    if (result == rclcpp::FutureReturnCode::SUCCESS) {
      try {
        auto response = future.get();
        if (response) {
          RCLCPP_INFO(this->get_logger(),
                      "Volume restored to %u on interrupt.", original_volume_);
          return true;
        }
      } catch (const std::exception &e) {
        RCLCPP_WARN(this->get_logger(), "SetVolume failed: %s", e.what());
      }
    }

    RCLCPP_WARN(this->get_logger(),
                "Failed to restore original volume on interrupt.");
    return false;
  }

 private:
  bool wait_for_service(const rclcpp::ClientBase::SharedPtr &client, const std::string &service_name)
  {
    while (!client->wait_for_service(kServiceWaitInterval)) {
      if (!rclcpp::ok()) {
        return false;
      }
      RCLCPP_INFO(this->get_logger(), "Waiting for service: %s", service_name.c_str());
    }
    RCLCPP_INFO(this->get_logger(), "Service available: %s", service_name.c_str());
    return true;
  }

  // ---- 通用服务调用(使用 spin_until_future_complete,边 spin 边等) ----

  template <typename ServiceT>
  std::shared_ptr<typename ServiceT::Response> call_service(
    const typename rclcpp::Client<ServiceT>::SharedPtr &client,
    const std::shared_ptr<typename ServiceT::Request> &request,
    const char *service_name)
  {
    for (int i = 0; i < kMaxRetryCount; ++i) {
      auto future = client->async_send_request(request);
      auto result = rclcpp::spin_until_future_complete(
        shared_from_this(), future, kServiceCallTimeout);

      if (result == rclcpp::FutureReturnCode::SUCCESS) {
        try {
          auto response = future.get();
          if (response) { return response; }
        } catch (const std::exception &e) {
          RCLCPP_ERROR(this->get_logger(), "%s failed: %s", service_name, e.what());
        }
      }

      RCLCPP_INFO(this->get_logger(),
                  "%s attempt %d/%d timed out, retrying...",
                  service_name, i + 1, kMaxRetryCount);
      std::this_thread::sleep_for(200ms);
    }

    RCLCPP_ERROR(this->get_logger(),
                 "%s timed out after %d attempts (%ld s each).",
                 service_name, kMaxRetryCount, kServiceCallTimeout.count());
    return nullptr;
  }

  // ---- 请求构建 ----

  aimdk_msgs::msg::CommonRequest build_common_request()
  {
    aimdk_msgs::msg::CommonRequest req;
    req.header.stamp = this->now();
    return req;
  }

  std::shared_ptr<aimdk_msgs::srv::SetVolume::Request>
  build_set_volume_request(std::uint32_t volume)
  {
    auto req = std::make_shared<aimdk_msgs::srv::SetVolume::Request>();
    req->request = build_common_request();
    req->audio_volume = volume;
    return req;
  }

  std::shared_ptr<aimdk_msgs::srv::GetVolume::Request>
  build_get_volume_request()
  {
    auto req = std::make_shared<aimdk_msgs::srv::GetVolume::Request>();
    req->request = build_common_request();
    return req;
  }

  // ---- PlayTts ----

  bool play_tts()
  {
    auto request = std::make_shared<aimdk_msgs::srv::PlayTts::Request>();
    request->header = build_common_request();
    request->tts_req.text = kTtsText;
    request->tts_req.domain = tts_domain_;
    request->tts_req.trace_id = tts_trace_id_;
    request->tts_req.is_interrupted = true;
    request->tts_req.priority_level.value =
      aimdk_msgs::msg::TtsPriorityLevel::INTERACTION_L6;

    RCLCPP_INFO(this->get_logger(),
                "Sending PlayTts request. domain=%s trace_id=%s",
                request->tts_req.domain.c_str(), request->tts_req.trace_id.c_str());
    RCLCPP_INFO(this->get_logger(), "TTS text: %s", request->tts_req.text.c_str());

    auto response = call_service<aimdk_msgs::srv::PlayTts>(
      play_tts_client_, request, "PlayTts");
    if (!response) { return false; }

    RCLCPP_INFO(this->get_logger(),
                "PlayTts response: code=%ld status=%d is_success=%d "
                "error_message=%s",
                response->header.header.code, response->header.status.value,
                static_cast<int>(response->tts_resp.is_success),
                response->tts_resp.error_message.c_str());

    if (!response->tts_resp.is_success) {
      RCLCPP_ERROR(this->get_logger(),
                   "PlayTts failed. code=%ld status=%d reason=%u",
                   response->header.header.code,
                   response->header.status.value,
                   response->header.status.reason);
    }

    return response->tts_resp.is_success;
  }

  // ---- Volume Step ----

  bool execute_volume_step(std::uint32_t target_volume, const char *action_message)
  {
    RCLCPP_INFO(this->get_logger(),
                "Running volume step. target=%u action=%s", target_volume, action_message);

    auto set_response = call_service<aimdk_msgs::srv::SetVolume>(
      set_volume_client_, build_set_volume_request(target_volume), "SetVolume");
    if (!set_response) { return false; }

    RCLCPP_INFO(this->get_logger(),
                "SetVolume response: code=%ld status=%d audio_volume=%u",
                set_response->response.header.code,
                set_response->response.status.value,
                set_response->audio_volume);

    if (set_response->response.header.code != 0 || 
        set_response->response.status.value != aimdk_msgs::msg::CommonState::SUCCESS) {
      RCLCPP_ERROR(this->get_logger(),
                   "SetVolume failed. code=%ld status=%d reason=%u",
                   set_response->response.header.code,
                   set_response->response.status.value,
                   set_response->response.status.reason);
      return false;
    }

    auto get_response = call_service<aimdk_msgs::srv::GetVolume>(
      get_volume_client_, build_get_volume_request(), "GetVolume");
    if (!get_response) { return false; }

    RCLCPP_INFO(this->get_logger(),
                "GetVolume response: code=%ld status=%d audio_volume=%u",
                get_response->response.header.code,
                get_response->response.status.value,
                get_response->audio_volume);

     if (get_response->response.header.code != 0 || 
         get_response->response.status.value != aimdk_msgs::msg::CommonState::SUCCESS) {
       RCLCPP_ERROR(this->get_logger(),
                    "GetVolume failed. code=%ld status=%d reason=%u",
                    get_response->response.header.code,
                    get_response->response.status.value,
                    get_response->response.status.reason);
       return false;
     }

    if (get_response->audio_volume != target_volume) {
      RCLCPP_ERROR(this->get_logger(),
                   "Volume verification failed. target=%u actual=%u",
                   target_volume, get_response->audio_volume);
      return false;
    }

    RCLCPP_INFO(this->get_logger(),
                "%s,确认当前音量=%u", action_message, get_response->audio_volume);
    return true;
  }

  // ---- Mute Step ----

  bool execute_mute_step(bool target_mute, const char *action_message)
  {
    RCLCPP_INFO(this->get_logger(),
                "Running mute step. target=%d action=%s",
                static_cast<int>(target_mute), action_message);

    // Call GetMute after SetMute to verify the result.
    auto set_request                  = std::make_shared<aimdk_msgs::srv::SetMute::Request>();
    set_request->request              = build_common_request();
    set_request->is_mute              = target_mute;

    auto set_response = call_service<aimdk_msgs::srv::SetMute>(
      set_mute_client_, set_request, "SetMute");
    if (!set_response) {
      return false;
    }

    RCLCPP_INFO(this->get_logger(),
                "SetMute response: code=%ld status=%d is_mute=%d "
                "(final result is verified by GetMute)",
                set_response->response.header.code,
                set_response->response.status.value,
                static_cast<int>(set_response->is_mute));

    if (set_response->response.header.code != 0 || 
        set_response->response.status.value != aimdk_msgs::msg::CommonState::SUCCESS) {
      RCLCPP_ERROR(this->get_logger(),
                   "SetMute failed. code=%ld status=%d reason=%u",
                   set_response->response.header.code,
                   set_response->response.status.value,
                   set_response->response.status.reason);
      return false;
    }

    auto get_request                  = std::make_shared<aimdk_msgs::srv::GetMute::Request>();
    get_request->request              = build_common_request();

    auto get_response = call_service<aimdk_msgs::srv::GetMute>(
      get_mute_client_, get_request, "GetMute");
    if (!get_response) { return false; }

    RCLCPP_INFO(this->get_logger(),
                "GetMute response: code=%ld status=%d is_mute=%d",
                get_response->response.header.code,
                get_response->response.status.value,
                static_cast<int>(get_response->is_mute));

    if (get_response->response.header.code != 0 || 
        get_response->response.status.value != aimdk_msgs::msg::CommonState::SUCCESS) {
      RCLCPP_ERROR(this->get_logger(),
                   "GetMute failed. code=%ld status=%d reason=%u",
                   get_response->response.header.code,
                   get_response->response.status.value,
                   get_response->response.status.reason);
      return false;
    }

    if (get_response->is_mute != target_mute) {
      RCLCPP_ERROR(this->get_logger(),
                   "Mute verification failed. target=%d actual=%d",
                   static_cast<int>(target_mute),
                   static_cast<int>(get_response->is_mute));
      return false;
    }

    RCLCPP_INFO(this->get_logger(),
                "%s,确认当前静音状态=%d", action_message,
                static_cast<int>(get_response->is_mute));
    return true;
  }

  // ---- 成员变量 ----

  const std::string play_tts_service_   = "/aimdk_5Fmsgs/srv/PlayTts";
  const std::string set_volume_service_ = "/aimdk_5Fmsgs/srv/SetVolume";
  const std::string get_volume_service_ = "/aimdk_5Fmsgs/srv/GetVolume";
  const std::string set_mute_service_   = "/aimdk_5Fmsgs/srv/SetMute";
  const std::string get_mute_service_   = "/aimdk_5Fmsgs/srv/GetMute";
  const std::string tts_domain_         = "volume_control_demo";
  const std::string tts_trace_id_       = "volume_control_demo_trace";

  rclcpp::Client<aimdk_msgs::srv::PlayTts>::SharedPtr play_tts_client_;
  rclcpp::Client<aimdk_msgs::srv::SetVolume>::SharedPtr set_volume_client_;
  rclcpp::Client<aimdk_msgs::srv::GetVolume>::SharedPtr get_volume_client_;
  rclcpp::Client<aimdk_msgs::srv::SetMute>::SharedPtr set_mute_client_;
  rclcpp::Client<aimdk_msgs::srv::GetMute>::SharedPtr get_mute_client_;

  mutable std::mutex state_mutex_;
  bool shutdown_requested_ = false;
  std::uint32_t original_volume_ = 30;
  bool has_original_volume_ = false;
};

std::shared_ptr<VolumeControlClient> g_node = nullptr;

// 修复 ROS2 中 Ctrl+C 后优先触发 shutdown 的问题
// 自定义信号处理器只设标志,不做服务调用
void signal_handler(int signal)
{
  if (g_node) {
    g_node->handle_signal(signal);
  }
}

int main(int argc, char *argv[])
{
  rclcpp::init(argc, argv);
  std::signal(SIGINT, signal_handler);
  std::signal(SIGTERM, signal_handler);

  g_node = std::make_shared<VolumeControlClient>();
  int exit_code = 0;

  try {
    if (!g_node->wait_for_services()) {
      RCLCPP_ERROR(rclcpp::get_logger("volume_control_main"),
                   "Failed to initialize volume control demo.");
      exit_code = 1;
    } else {
      g_node->run_demo();
    }
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("volume_control_main"),
                 "Program exited with exception: %s", e.what());
    exit_code = 1;
  }

  // Ctrl+C 中断时:上下文仍有效,在此恢复音量
  if (g_node && g_node->is_shutdown_requested()) {
    g_node->restore_original_volume();
  }

  g_node.reset();
  rclcpp::shutdown();
  return exit_code;
}
音频参数控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/volume_control.py

python
#!/usr/bin/env python3

"""
Volume Control Demo Example Script

Description:
  This script demonstrates how to control robot audio volume and mute settings using TTS services.
  Includes volume adjustment, mute toggle, and TTS playback demonstration.
  Note: If a volume setting step fails, the script will continue to the next step. Please check the logs for any errors.
  The original volume is recorded at startup and automatically restored when the demo finishes or Ctrl+C is pressed.

Prerequisites:
  - Robot TTS service must be running
  - Audio output device must be working properly
  - Volume and mute services must be available

Usage:
  python3 volume_control.py

Example:
  python3 volume_control.py

Parameters:
  - None 
"""

import signal
import time

import rclpy
import rclpy.logging
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest, CommonState, TtsPriorityLevel
from aimdk_msgs.srv import GetMute, GetVolume, PlayTts, SetMute, SetVolume

TTS_TEXT = (
    "大家好,我是启元机器人。现在为你演示音频控制示例。"
    "接下来,我会先持续播报一段介绍内容,在播报过程中,系统会依次执行设置音量、查询音量、设置静音和查询静音等操作。"
    "你将听到默认音量、音量调大、音量调小、开启静音以及取消静音这几个阶段的变化。"
    "如果整段流程能够顺利完成,就说明启元的TTS播放、音量控制和静音控制链路都已经正常工作。"
    "感谢你体验启元机器人的音频控制能力。"
)

STEP_INTERVAL_SEC = 5.0
SERVICE_WAIT_SEC = 2.0
SERVICE_CALL_TIMEOUT_SEC = 5.0


class VolumeControlClient(Node):
    def __init__(self):
        super().__init__("volume_control_client")
        self.play_tts_service = "/aimdk_5Fmsgs/srv/PlayTts"
        self.set_volume_service = "/aimdk_5Fmsgs/srv/SetVolume"
        self.get_volume_service = "/aimdk_5Fmsgs/srv/GetVolume"
        self.set_mute_service = "/aimdk_5Fmsgs/srv/SetMute"
        self.get_mute_service = "/aimdk_5Fmsgs/srv/GetMute"
        self.tts_domain = "volume_control_demo"
        self.tts_trace_id = "volume_control_demo_trace"

        self.play_tts_client = self.create_client(PlayTts, self.play_tts_service)
        self.set_volume_client = self.create_client(
            SetVolume, self.set_volume_service
        )
        self.get_volume_client = self.create_client(
            GetVolume, self.get_volume_service
        )
        self.set_mute_client = self.create_client(SetMute, self.set_mute_service)
        self.get_mute_client = self.create_client(GetMute, self.get_mute_service)

        self.original_volume_ = None

        self.get_logger().info("Volume control demo node created.")

    def wait_for_services(self) -> bool:
        return (
            self._wait_for_service(self.play_tts_client, self.play_tts_service)
            and self._wait_for_service(
                self.set_volume_client, self.set_volume_service
            )
            and self._wait_for_service(
                self.get_volume_client, self.get_volume_service
            )
            and self._wait_for_service(self.set_mute_client, self.set_mute_service)
            and self._wait_for_service(self.get_mute_client, self.get_mute_service)
        )

    def _wait_for_service(self, client, service_name: str) -> bool:
        while not client.wait_for_service(timeout_sec=SERVICE_WAIT_SEC):
            if not rclpy.ok():
                return False
            self.get_logger().info(f"Waiting for service: {service_name}")

        self.get_logger().info(f"Service available: {service_name}")
        return True

    def _call_service(self, client, request, service_name: str):
        for i in range(3):
            future = client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=SERVICE_CALL_TIMEOUT_SEC)

            if future.done():
                break

            self.get_logger().info(f'trying ... [{i}]')
            time.sleep(0.2)

        if not future.done():
            self.get_logger().error(
                f"{service_name} timed out after "
                f"{int(SERVICE_CALL_TIMEOUT_SEC * 1000)} ms."
            )
            return None

        try:
            response = future.result()
        except Exception as error:  # noqa: BLE001
            self.get_logger().error(f"{service_name} failed: {error}")
            return None

        if response is None:
            self.get_logger().error(f"{service_name} returned no response.")
            return None

        return response

    def _build_common_request(self) -> CommonRequest:
        request = CommonRequest()
        request.header.stamp = self.get_clock().now().to_msg()
        return request

    def play_tts(self) -> bool:
        request = PlayTts.Request()
        request.header = self._build_common_request()
        # domain and trace_id identify this TTS request.
        request.tts_req.text = TTS_TEXT
        request.tts_req.domain = self.tts_domain
        request.tts_req.trace_id = self.tts_trace_id
        request.tts_req.is_interrupted = True
        request.tts_req.priority_weight = 0
        request.tts_req.priority_level.value = TtsPriorityLevel.INTERACTION_L6

        self.get_logger().info(
            f"Sending PlayTts request. domain={request.tts_req.domain} "
            f"trace_id={request.tts_req.trace_id}"
        )
        self.get_logger().info(f"TTS text: {request.tts_req.text}")

        response = self._call_service(
            self.play_tts_client, request, "PlayTts"
        )
        if response is None:
            return False

        self.get_logger().info(
            "PlayTts response: "
            f"code={response.header.header.code} "
            f"status={response.header.status.value} "
            f"is_success={int(response.tts_resp.is_success)} "
            f"error_message={response.tts_resp.error_message}"
        )

        if not response.tts_resp.is_success:
            self.get_logger().error(
                f"PlayTts failed. "
                f"code={response.header.code} status={response.header.status.value} "
                f"msg={response.header.message}"
            )

        return response.tts_resp.is_success

    def execute_volume_step(self, target_volume: int, action_message: str) -> bool:
        self.get_logger().info(
            f"Running volume step. target={target_volume} action={action_message}"
        )

        # Call GetVolume after SetVolume to verify the result.
        set_request = SetVolume.Request()
        set_request.request = self._build_common_request()
        set_request.audio_volume = target_volume

        set_response = self._call_service(
            self.set_volume_client, set_request, "SetVolume"
        )
        if set_response is None:
            return False

        self.get_logger().info(
            "SetVolume response: "
            f"code={set_response.response.header.code} "
            f"status={set_response.response.status.value} "
            f"audio_volume={set_response.audio_volume}"
        )

        if set_response.response.header.code != 0 or set_response.response.status.value != CommonState.SUCCESS:
            self.get_logger().error(
                f"SetVolume failed. "
                f"code={set_response.response.header.code} "
                f"status={set_response.response.status.value} "
                f"reason={set_response.response.status.reason}"
            )
            return False

        get_request = GetVolume.Request()
        get_request.request = self._build_common_request()

        get_response = self._call_service(
            self.get_volume_client, get_request, "GetVolume"
        )
        if get_response is None:
            return False

        self.get_logger().info(
            "GetVolume response: "
            f"code={get_response.response.header.code} "
            f"status={get_response.response.status.value} "
            f"audio_volume={get_response.audio_volume}"
        )

        if get_response.response.header.code != 0 or get_response.response.status.value != CommonState.SUCCESS:
            self.get_logger().error(
                f"GetVolume failed. "
                f"code={get_response.response.header.code} "
                f"status={get_response.response.status.value} "
                f"reason={get_response.response.status.reason}"
            )
            return False

        if get_response.audio_volume != target_volume:
            self.get_logger().error(
                "Volume verification failed. "
                f"target={target_volume} actual={get_response.audio_volume}"
            )
            return False

        self.get_logger().info(
            f"{action_message},确认当前音量={get_response.audio_volume}"
        )
        return True

    def execute_mute_step(self, target_mute: bool, action_message: str) -> bool:
        self.get_logger().info(
            f"Running mute step. target={int(target_mute)} action={action_message}"
        )

        # Call GetMute after SetMute to verify the result.
        set_request = SetMute.Request()
        set_request.request = self._build_common_request()
        set_request.is_mute = target_mute

        set_response = self._call_service(
            self.set_mute_client, set_request, "SetMute"
        )
        if set_response is None:
            return False

        self.get_logger().info(
            "SetMute response: "
            f"code={set_response.response.header.code} "
            f"status={set_response.response.status.value} "
            f"is_mute={int(set_response.is_mute)} "
            "(final result is verified by GetMute)"
        )

        if set_response.response.header.code != 0 or set_response.response.status.value != CommonState.SUCCESS:
            self.get_logger().error(
                f"SetMute failed. "
                f"code={set_response.response.header.code} "
                f"status={set_response.response.status.value} "
                f"reason={set_response.response.status.reason}"
            )
            return False

        get_request = GetMute.Request()
        get_request.request = self._build_common_request()

        get_response = self._call_service(self.get_mute_client, get_request, "GetMute")
        if get_response is None:
            return False

        self.get_logger().info(
            "GetMute response: "
            f"code={get_response.response.header.code} "
            f"status={get_response.response.status.value} "
            f"is_mute={int(get_response.is_mute)}"
        )

        if get_response.response.header.code != 0 or get_response.response.status.value != CommonState.SUCCESS:
            self.get_logger().error(
                f"GetMute failed. "
                f"code={get_response.response.header.code} "
                f"status={get_response.response.status.value} "
                f"reason={get_response.response.status.reason}"
            )
            return False

        if get_response.is_mute != target_mute:
            self.get_logger().error(
                "Mute verification failed. "
                f"target={int(target_mute)} actual={int(get_response.is_mute)}"
            )
            return False

        self.get_logger().info(
            f"{action_message},确认当前静音状态={int(get_response.is_mute)}"
        )
        return True

    def run_demo(self) -> bool:
        self.get_logger().info("Volume control demo starts automatically.")
        self.get_logger().info(
            "Volume note: on this device a larger value means a smaller actual volume."
        )

        self.original_volume_ = None
        get_init_request = GetVolume.Request()
        get_init_request.request = self._build_common_request()
        get_init_response = self._call_service(
            self.get_volume_client, get_init_request, "GetVolume"
        )
        if get_init_response is not None:
            self.original_volume_ = get_init_response.audio_volume
            self.get_logger().info(f"Initial volume: {self.original_volume_}")
        else:
            self.get_logger().warning("Failed to get initial volume, will skip restoration.")

        if not self.play_tts():
            self.get_logger().error("PlayTts failed.")
            return False

        steps = [
            ("设为默认音量", lambda: self.execute_volume_step(30, "设为默认音量")),
            ("音量调大", lambda: self.execute_volume_step(40, "音量调大")),
            ("音量调小", lambda: self.execute_volume_step(20, "音量调小")),
            ("设置静音", lambda: self.execute_mute_step(True, "设置静音")),
            ("取消静音", lambda: self.execute_mute_step(False, "取消静音")),
        ]

        self.get_logger().info(
            f"TTS accepted. The first control step will run in {int(STEP_INTERVAL_SEC)} seconds."
        )

        try:
            for step_name, step_func in steps:
                time.sleep(STEP_INTERVAL_SEC)
                if not step_func():
                    self.get_logger().error(f"Volume control step failed: {step_name} (continuing to next step)")
        except KeyboardInterrupt:
            pass

        # Restore original volume if available (normal finish or Ctrl+C)
        if self.original_volume_ is not None:
            self.get_logger().info(f"Restoring original volume: {self.original_volume_}")
            if not self.execute_volume_step(self.original_volume_, "恢复原始音量"):
                self.get_logger().warning("Failed to restore original volume.")
        else:
            self.get_logger().info(
                "Volume restoration skipped (initial volume unknown)."
            )

        # Always ensure unmuted at the end
        self.get_logger().info("Ensuring unmuted state before exit.")
        if not self.execute_mute_step(False, "取消静音"):
            self.get_logger().warning("Failed to ensure unmuted state.")

        if self.original_volume_ is not None:
            self.get_logger().info(
                f"Volume control demo finished. Volume restored to {self.original_volume_}, mute=false. "
                f"(Check logs for any failed steps)"
            )
        else:
            self.get_logger().info(
                "Volume control demo finished. (Check logs for any failed steps)"
            )
        return True


def main(args=None):
    rclpy.init(args=args)
    # init 之后立即覆盖 ROS2 的 SIGINT 处理器
    # 阻止 Ctrl+C 触发 rclpy.shutdown(),保持上下文有效以恢复音量
    def _sigint_handler(sig, frame):
        raise KeyboardInterrupt
    signal.signal(signal.SIGINT, _sigint_handler)
    node = None
    try:
        node = VolumeControlClient()
        if not node.wait_for_services():
            node.get_logger().error("Failed to initialize volume control demo.")
            return 1
        ok = node.run_demo()
        return 0 if ok else 1
    except KeyboardInterrupt:
        return 0
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("volume_control_main").error(
            f"Program exited with exception: {error}"
        )
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

音频录制(TCP: 4713) ​

音频录制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:./build/aimdk_examples_cpp/record_audio [-i SSH_KEY] <机器人IP> [录音秒数]

cpp
/*
 @file record_audio.cpp
 @brief 录音示例(自动检测内置麦/外置麦)

 @description
   支持本机(共享内存)和远程(TCP)两种录音模式。
   自动检测当前 PulseAudio 默认录音源,适配不同麦克风:

   内置麦(麦克风阵列 aw89403):
     - 8声道 48kHz S16LE
     - ch1-2:回采(扬声器播放时才有数据), ch3-8:麦克
     - 输出:raw_8ch.wav + mic_mono.wav(ch5-6 混合, 10倍放大)

   外置麦(USB 麦克风):
     - 2声道 48kHz S24LE(24-bit)
     - ch1-2:左右声道
     - 输出:raw_2ch.wav + mic_mono.wav(ch1-2 混合, 24→16bit)

 @prerequisites
   - 远程模式:示例脚本会通过 SSH 自动在机器人端加载 TCP 录音模块(端口 4713)
   - 本机模式:无需额外配置,直接使用 PulseAudio 本地 socket
   - 本机已安装 parec:sudo apt install pulseaudio-utils
   - 使用 SSH 密钥时:将售后提供的密钥目录(<机器人SN>_soc0/)放到 SDK 根目录下
     (与 examples/ 同级),并修改权限:
     sudo chown -R $USER:$USER ./<机器人SN>_soc0/
     chmod 600 ./<机器人SN>_soc0/id_ed25519
     然后在 SDK 根目录下执行示例命令,使用 -i ./<机器人SN>_soc0/id_ed25519 指定密钥。

 @usage
   ./build/aimdk_examples_cpp/record_audio [-i SSH_KEY] <机器人IP> [录音秒数]

   机器人IP 为 127.0.0.1 或 localhost 时自动使用本机模式(共享内存),
   否则使用远程模式(TCP)。

   可选参数:
     -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)

 @example
   # 本机录音(共享内存)
   ./build/aimdk_examples_cpp/record_audio 127.0.0.1 5

   # 远程录音(TCP)
   ./build/aimdk_examples_cpp/record_audio <机器人IP> 5

   # 远程录音(使用 SSH 密钥,网线连接时 IP 为 10.1.1.100)
   ./build/aimdk_examples_cpp/record_audio -i ./<机器人SN>_soc0/id_ed25519 10.1.1.100 5
 */

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <string>
#include <sys/stat.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <vector>

namespace {

constexpr int kRate = 48000;
constexpr const char *kBuiltinDevice = "alsa_input.platform-aw89403_sound.pro-input-0";

std::atomic<bool> g_stop{false};

// ---- Microphone profile (built-in array or USB mic) ----
struct MicProfile {
  std::string device_name;
  int channels         = 8;
  int sample_width     = 2;     // bytes per sample (2 = 16-bit, 3 = 24-bit)
  int bits_per_sample  = 16;
  std::string format   = "s16le";
  bool is_builtin      = true;
};

}  // namespace

static void signal_handler(int) { g_stop.store(true); }

// ---------------------------------------------------------------------------
// Local / remote detection
// ---------------------------------------------------------------------------

static bool is_local_robot(const char *robot_ip) {
  if (strcmp(robot_ip, "127.0.0.1") == 0 ||
      strcmp(robot_ip, "localhost") == 0 ||
      strcmp(robot_ip, "::1") == 0) {
    return true;
  }
  struct stat st;
  if (stat("/robot/software", &st) == 0 && S_ISDIR(st.st_mode)) {
    return true;
  }
  return false;
}

static std::string get_local_pulse_server() {
  const char *sockets[] = { "/run/user/1000/pulse/native" };
  for (const char *s : sockets) {
    struct stat st;
    if (stat(s, &st) == 0) {
      return std::string("unix:") + s;
    }
  }
  return "";
}

// ---------------------------------------------------------------------------
// Microphone profile detection
// ---------------------------------------------------------------------------

static std::string get_default_source(bool local_mode, const char *robot_ip, const char *ssh_key = nullptr) {
  std::string cmd;
  if (local_mode) {
    cmd = "pactl get-default-source 2>/dev/null";
  } else {
    char buf[512];
    if (ssh_key) {
      snprintf(buf, sizeof(buf),
               "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i %s run@%s '"
               "PULSE_SERVER=unix:/run/user/1000/pulse/native "
               "pactl get-default-source 2>/dev/null'",
               ssh_key, robot_ip);
    } else {
      snprintf(buf, sizeof(buf),
               "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 run@%s '"
               "PULSE_SERVER=unix:/run/user/1000/pulse/native "
               "pactl get-default-source 2>/dev/null'",
               robot_ip);
    }
    cmd = buf;
  }

  FILE *fp = popen(cmd.c_str(), "r");
  if (!fp) return "";

  std::string result;
  char buf[512];
  while (fgets(buf, sizeof(buf), fp)) result += buf;
  pclose(fp);

  // Trim trailing whitespace
  while (!result.empty() &&
         (result.back() == '\n' || result.back() == '\r' || result.back() == ' '))
    result.pop_back();
  return result;
}

// ---------------------------------------------------------------------------
// Auto-setup: load PulseAudio TCP modules on robot via SSH
//             同时检测默认录音源,合并为一次 SSH 调用避免重复输入密码
// ---------------------------------------------------------------------------

// 返回值: 默认录音源名称(空字符串表示检测失败)
// 副作用: 通过 SSH 检查/加载 TCP 录音模块,打印状态信息
static std::string setup_and_detect_source(const char *robot_ip, const char *ssh_key = nullptr) {
  // 将 TCP 模块加载检查和默认录音源查询合并到一次 SSH 会话中
  char cmd[2048];
  if (ssh_key) {
    snprintf(cmd, sizeof(cmd),
             "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i %s run@%s '"
             "export PULSE_SERVER=unix:/run/user/1000/pulse/native; "
             "if pactl list modules short 2>/dev/null | grep -q module-native-protocol-tcp; then "
             "echo __TCP_MODULE__:ALREADY_LOADED; "
             "else "
             "pactl load-module module-native-protocol-tcp "
             "auth-anonymous=1 listen=0.0.0.0 >/dev/null 2>&1 && "
             "echo __TCP_MODULE__:LOADED; "
             "fi; "
             "echo __DEFAULT_SOURCE__; "
             "pactl get-default-source 2>/dev/null"
             "'",
             ssh_key, robot_ip);
  } else {
    snprintf(cmd, sizeof(cmd),
             "ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 run@%s '"
             "export PULSE_SERVER=unix:/run/user/1000/pulse/native; "
             "if pactl list modules short 2>/dev/null | grep -q module-native-protocol-tcp; then "
             "echo __TCP_MODULE__:ALREADY_LOADED; "
             "else "
             "pactl load-module module-native-protocol-tcp "
             "auth-anonymous=1 listen=0.0.0.0 >/dev/null 2>&1 && "
             "echo __TCP_MODULE__:LOADED; "
             "fi; "
             "echo __DEFAULT_SOURCE__; "
             "pactl get-default-source 2>/dev/null"
             "'",
             robot_ip);
  }

  FILE *fp = popen(cmd, "r");
  if (!fp) {
    printf("SSH 连接失败\n");
    return "";
  }
  std::string output;
  char buf[512];
  while (fgets(buf, sizeof(buf), fp)) {
    output += buf;
  }
  int ret = pclose(fp);
  (void)ret;

  // 解析 TCP 模块加载状态
  if (output.find("__TCP_MODULE__:ALREADY_LOADED") != std::string::npos) {
    printf("录音模块已在机器人端加载(跳过加载)\n");
  } else if (output.find("__TCP_MODULE__:LOADED") != std::string::npos) {
    printf("已在机器人端加载录音模块 (端口 4713)\n");
  } else {
    printf("警告: 录音模块加载可能未成功(stderr 已输出到终端)\n");
  }

  // 解析默认录音源名称(__DEFAULT_SOURCE__ 标记之后的第一行非空内容)
  std::string source;
  auto pos = output.find("__DEFAULT_SOURCE__");
  if (pos != std::string::npos) {
    pos = output.find('\n', pos);
    if (pos != std::string::npos) {
      pos++;  // skip '\n'
      auto end = output.find('\n', pos);
      if (end == std::string::npos) end = output.size();
      source = output.substr(pos, end - pos);
      // Trim trailing whitespace
      while (!source.empty() &&
             (source.back() == '\n' || source.back() == '\r' || source.back() == ' '))
        source.pop_back();
    }
  }
  return source;
}

// ---------------------------------------------------------------------------
// Parse source name into MicProfile (shared by local and remote paths)
// ---------------------------------------------------------------------------

static MicProfile parse_mic_profile(const std::string &source) {
  MicProfile profile;
  if (source.empty()) {
    printf("无法检测默认录音源,使用内置麦默认配置\n");
    profile.device_name = kBuiltinDevice;
    return profile;
  }

  profile.device_name = source;

  if (source.find("aw89403") != std::string::npos) {
    profile = {source, 8, 2, 16, "s16le", true};
    printf("检测到内置麦(aw89403): %s\n", source.c_str());
  } else {
    profile = {source, 2, 3, 24, "s24le", false};
    printf("检测到外置麦(USB): %s\n", source.c_str());
  }

  printf("  格式: %s, %dch, %dHz, %d-bit\n",
         profile.format.c_str(), profile.channels, kRate, profile.bits_per_sample);
  return profile;
}

// ---------------------------------------------------------------------------
// Microphone profile detection (local-only path)
// ---------------------------------------------------------------------------

static MicProfile detect_mic_profile(bool local_mode, const char *robot_ip, const char *ssh_key = nullptr) {
  std::string source = get_default_source(local_mode, robot_ip, ssh_key);
  return parse_mic_profile(source);
}

// ---------------------------------------------------------------------------
// WAV file writing helpers
// ---------------------------------------------------------------------------

static void write_u16_le(FILE *f, uint16_t v) {
  uint8_t buf[2] = {
      static_cast<uint8_t>(v & 0xFF),
      static_cast<uint8_t>((v >> 8) & 0xFF),
  };
  fwrite(buf, 1, 2, f);
}

static void write_u32_le(FILE *f, uint32_t v) {
  uint8_t buf[4] = {
      static_cast<uint8_t>(v & 0xFF),
      static_cast<uint8_t>((v >> 8) & 0xFF),
      static_cast<uint8_t>((v >> 16) & 0xFF),
      static_cast<uint8_t>((v >> 24) & 0xFF),
  };
  fwrite(buf, 1, 4, f);
}

static bool write_wav(const char *path, const std::vector<uint8_t> &data,
                      int channels, int rate, int bits_per_sample) {
  FILE *f = fopen(path, "wb");
  if (!f) {
    perror(path);
    return false;
  }

  int bytes_per_sample = bits_per_sample / 8;
  uint32_t data_size = static_cast<uint32_t>(data.size());
  uint32_t riff_size = 36 + data_size;

  fwrite("RIFF", 1, 4, f);
  write_u32_le(f, riff_size);
  fwrite("WAVE", 1, 4, f);

  // fmt chunk
  fwrite("fmt ", 1, 4, f);
  write_u32_le(f, 16);                              // chunk size
  write_u16_le(f, 1);                               // PCM format
  write_u16_le(f, static_cast<uint16_t>(channels));  // channels
  write_u32_le(f, static_cast<uint32_t>(rate));      // sample rate
  write_u32_le(f, static_cast<uint32_t>(rate * channels * bytes_per_sample));  // byte rate
  write_u16_le(f, static_cast<uint16_t>(channels * bytes_per_sample));         // block align
  write_u16_le(f, static_cast<uint16_t>(bits_per_sample));                     // bits per sample

  // data chunk
  fwrite("data", 1, 4, f);
  write_u32_le(f, data_size);
  fwrite(data.data(), 1, data.size(), f);

  fclose(f);
  printf("保存: %s\n", path);
  return true;
}

// ---------------------------------------------------------------------------
// PCM sample helpers
// ---------------------------------------------------------------------------

static inline int16_t read_s16_le(const uint8_t *p) {
  return static_cast<int16_t>(
      static_cast<uint16_t>(p[0]) | (static_cast<uint16_t>(p[1]) << 8));
}

static inline void write_s16_le(uint8_t *p, int16_t v) {
  auto uv = static_cast<uint16_t>(v);
  p[0] = static_cast<uint8_t>(uv & 0xFF);
  p[1] = static_cast<uint8_t>((uv >> 8) & 0xFF);
}

static inline int16_t clamp_s16(int32_t v) {
  if (v > 32767) return 32767;
  if (v < -32768) return -32768;
  return static_cast<int16_t>(v);
}

// ---------------------------------------------------------------------------
// S24LE (24-bit signed little-endian) sample helpers
// ---------------------------------------------------------------------------

static inline int32_t read_s24_le(const uint8_t *p) {
  uint32_t val = static_cast<uint32_t>(p[0]) |
                 (static_cast<uint32_t>(p[1]) << 8) |
                 (static_cast<uint32_t>(p[2]) << 16);
  // Sign-extend from 24 bits to 32 bits
  if (val & 0x800000) {
    val |= 0xFF000000;
  }
  return static_cast<int32_t>(val);
}

static inline int16_t s24_to_s16(const uint8_t *p) {
  int32_t s24 = read_s24_le(p);
  int32_t s16 = s24 >> 8;  // arithmetic right shift preserves sign
  if (s16 > 32767) s16 = 32767;
  if (s16 < -32768) s16 = -32768;
  return static_cast<int16_t>(s16);
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

int main(int argc, char *argv[]) {
  if (argc < 2) {
    printf("用法: %s [-i SSH_KEY] <机器人IP> [录音秒数]\n", argv[0]);
    printf("\n");
    printf("  机器人IP 为 127.0.0.1 或 localhost 时自动使用本机模式(共享内存)\n");
    printf("  否则使用远程模式(TCP)\n");
    printf("\n");
    printf("  可选参数:\n");
    printf("    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)\n");
    return 1;
  }

  // 解析可选参数 -i SSH_KEY
  const char *ssh_key = nullptr;
  int arg_idx = 1;
  if (argc >= 3 && strcmp(argv[1], "-i") == 0) {
    if (argc < 4) {
      printf("错误: -i 参数需要指定 SSH 私钥文件路径\n");
      return 1;
    }
    ssh_key = argv[2];
    arg_idx = 3;
  }

  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);

  const char *robot_ip = argv[arg_idx];
  int duration = (argc > arg_idx + 1) ? atoi(argv[arg_idx + 1]) : 5;
  if (duration <= 0) duration = 5;

  // 检测本机/远程模式
  bool local_mode = is_local_robot(robot_ip);

  std::string pulse_server_value;
  MicProfile profile;
  if (local_mode) {
    pulse_server_value = get_local_pulse_server();
    if (!pulse_server_value.empty()) {
      printf("本机模式(共享内存: %s),录音 %d 秒...\n", pulse_server_value.c_str(), duration);
    } else {
      pulse_server_value = "";  // 使用 PulseAudio 默认 socket
      printf("本机模式(默认 socket),录音 %d 秒...\n", duration);
    }
    profile = detect_mic_profile(local_mode, robot_ip, ssh_key);
  } else {
    printf("检测到远程环境,使用 TCP 传输\n");
    if (ssh_key) {
      printf("使用 SSH 密钥: %s\n", ssh_key);
    }
    // 远程模式:通过一次 SSH 同时完成 TCP 模块加载 + 录音源检测(避免重复输入密码)
    std::string remote_source = setup_and_detect_source(robot_ip, ssh_key);
    if (g_stop.load()) {
      printf("\n已取消\n");
      return 0;
    }
    pulse_server_value = "tcp:" + std::string(robot_ip) + ":4713";
    printf("远程模式(TCP: %s:4713),录音 %d 秒...\n", robot_ip, duration);
    profile = parse_mic_profile(remote_source);
  }

  int channels = profile.channels;
  int sample_width = profile.sample_width;
  int bytes_per_frame = channels * sample_width;
  int bits_per_sample = profile.bits_per_sample;

  // ---- Build parec argv ----
  std::string s_channels = std::to_string(channels);
  std::string s_rate = std::to_string(kRate);
  std::string s_device = profile.device_name;

  // Build channel-map: aux0,aux1,...,auxN
  std::string s_channel_map;
  for (int i = 0; i < channels; ++i) {
    if (i > 0) s_channel_map += ',';
    s_channel_map += "aux" + std::to_string(i);
  }

  // ---- Fork/exec parec so we can kill it cleanly ----
  int pipefd[2];
  if (::pipe(pipefd) < 0) {
    perror("pipe");
    return 1;
  }

  pid_t child = fork();
  if (child < 0) {
    perror("fork");
    return 1;
  }

  if (child == 0) {
    // Child: redirect stdout to pipe, exec parec
    ::close(pipefd[0]);
    ::dup2(pipefd[1], STDOUT_FILENO);
    ::close(pipefd[1]);

    // Redirect stderr to /dev/null
    int devnull = ::open("/dev/null", O_WRONLY);
    if (devnull >= 0) {
      ::dup2(devnull, STDERR_FILENO);
      ::close(devnull);
    }

    if (!pulse_server_value.empty()) {
      ::setenv("PULSE_SERVER", pulse_server_value.c_str(), 1);
    }
    ::execlp("parec", "parec",
             "--channels", s_channels.c_str(),
             "--rate", s_rate.c_str(),
             "--format", profile.format.c_str(),
             "--device", s_device.c_str(),
             "--channel-map", s_channel_map.c_str(),
             nullptr);
    perror("execlp parec");
    _exit(1);
  }

  // Parent: close write end
  ::close(pipefd[1]);

  // ---- Read PCM data with threaded progress display ----
  int bytes_per_sec = kRate * bytes_per_frame;
  size_t total_bytes = static_cast<size_t>(bytes_per_sec) * duration;
  std::vector<uint8_t> audio;
  audio.reserve(total_bytes);

  auto start_time = std::chrono::steady_clock::now();
  std::atomic<bool> stop_display{false};

  // Progress display thread: updates every 100ms with smooth timing
  std::thread progress_thread([&]() {
    while (!stop_display.load()) {
      auto now = std::chrono::steady_clock::now();
      double elapsed = std::chrono::duration<double>(now - start_time).count();
      double display_sec = std::min(elapsed, static_cast<double>(duration));
      double received_sec = static_cast<double>(audio.size()) / bytes_per_sec;
      printf("\r录音中 %.1f / %d 秒  (已接收 %.1f 秒)", display_sec, duration, received_sec);
      fflush(stdout);
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
  });

  // Main thread: read data until target bytes received or signal
  uint8_t buf[65536];
  while (audio.size() < total_bytes && !g_stop.load()) {
    ssize_t n = ::read(pipefd[0], buf, sizeof(buf));
    if (n < 0) {
      if (errno == EINTR) continue;
      break;
    }
    if (n == 0) break;  // EOF
    audio.insert(audio.end(), buf, buf + n);
  }

  // Kill parec child and wait for exit
  ::kill(child, SIGTERM);
  int status;
  ::waitpid(child, &status, 0);

  // Stop progress thread and wait for it to finish
  stop_display.store(true);
  progress_thread.join();
  printf("\n");

  ::close(pipefd[0]);

  size_t n_frames = audio.size() / bytes_per_frame;
  double actual_secs = static_cast<double>(n_frames) / kRate;

  printf("录音 %zu 字节 (%.1f 秒)\n", audio.size(), actual_secs);

  if (n_frames == 0) {
    printf("未录制到数据,请检查:\n");
    printf("  1. 机器人 IP 是否正确\n");
    printf("  2. TCP 录音模块是否已加载\n");
    printf("  3. 是否已安装 pulseaudio-utils: sudo apt install pulseaudio-utils\n");
    return 1;
  }

  // ---- Save raw WAV (8ch or 2ch depending on mic type) ----
  const char *raw_filename = profile.is_builtin ? "raw_8ch.wav" : "raw_2ch.wav";
  write_wav(raw_filename, audio, channels, kRate, bits_per_sample);

  // ---- Per-channel analysis + mono extraction ----
  printf("分析中...\n");

  std::vector<int64_t> ch_sum(channels, 0);
  std::vector<int16_t> ch_peak(channels, 0);
  std::vector<uint8_t> mono;
  mono.reserve(n_frames * 2);  // mono is always 16-bit

  for (size_t i = 0; i < n_frames; ++i) {
    const uint8_t *frame = audio.data() + i * bytes_per_frame;

    if (profile.is_builtin) {
      // Built-in mic: 8ch S16LE, use ch5-6 (index 4,5) mixed with 10x gain
      int16_t samples[8];
      for (int c = 0; c < channels; ++c) {
        samples[c] = read_s16_le(frame + c * sample_width);
        int16_t abs_val = static_cast<int16_t>(std::abs(samples[c]));
        ch_sum[c] += abs_val;
        if (abs_val > ch_peak[c]) ch_peak[c] = abs_val;
      }
      int32_t mixed = (static_cast<int32_t>(samples[4]) + samples[5]) / 2 * 10;
      int16_t mono_sample = clamp_s16(mixed);
      uint8_t sample_buf[2];
      write_s16_le(sample_buf, mono_sample);
      mono.insert(mono.end(), sample_buf, sample_buf + 2);
    } else {
      // External USB mic: 2ch S24LE, mix ch1-2 and convert 24→16 bit
      int32_t samples[2];
      for (int c = 0; c < channels; ++c) {
        const uint8_t *sp = frame + c * sample_width;
        samples[c] = read_s24_le(sp);
        // Convert to 16-bit for stats
        int16_t s16 = s24_to_s16(sp);
        int16_t abs_val = static_cast<int16_t>(std::abs(s16));
        ch_sum[c] += abs_val;
        if (abs_val > ch_peak[c]) ch_peak[c] = abs_val;
      }
      // Average ch1-2, convert to 16-bit
      int32_t mixed = (samples[0] + samples[1]) / 2;
      int32_t s16 = mixed >> 8;
      if (s16 > 32767) s16 = 32767;
      if (s16 < -32768) s16 = -32768;
      int16_t mono_sample = static_cast<int16_t>(s16);
      uint8_t sample_buf[2];
      write_s16_le(sample_buf, mono_sample);
      mono.insert(mono.end(), sample_buf, sample_buf + 2);
    }
  }

  // ---- Save mono WAV ----
  write_wav("mic_mono.wav", mono, 1, kRate, 16);

  // ---- Print per-channel stats ----
  printf("\n各通道音量:\n");
  for (int c = 0; c < channels; ++c) {
    double avg = static_cast<double>(ch_sum[c]) / n_frames;
    const char *tag = (avg > 50) ? "有声" : "静音";
    printf("  通道 %d: 平均 %6.1f  峰值 %5d  %s\n", c + 1, avg, ch_peak[c], tag);
  }

  printf("\n保存: %s, mic_mono.wav\n", raw_filename);
  printf("播放: paplay mic_mono.wav\n");
  return 0;
}
音频录制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 examples/python/record_audio.py [-i SSH_KEY] <机器人IP> [录音秒数]

python
#!/usr/bin/env python3

"""录音示例(自动检测内置麦/外置麦)

支持本机(共享内存)和远程(TCP)两种录音模式。
自动检测当前 PulseAudio 默认录音源,适配不同麦克风:

内置麦(麦克风阵列 aw89403):
  - 8声道 48kHz S16LE
  - ch1-2:回采(扬声器播放时才有数据), ch3-8:麦克
  - 输出:raw_8ch.wav + mic_mono.wav(ch5-6 混合, 10倍放大)

外置麦(USB 麦克风):
  - 2声道 48kHz S24LE(24-bit)
  - ch1-2:左右声道
  - 输出:raw_2ch.wav + mic_mono.wav(ch1-2 混合, 24→16bit)

前提条件:
  - 远程模式:示例脚本会通过 SSH 自动在机器人端加载 TCP 录音模块(端口 4713)
  - 本机模式:无需额外配置,直接使用 PulseAudio 本地 socket
  - 本机已安装 parec:sudo apt install pulseaudio-utils
  - 使用 SSH 密钥时:将售后提供的密钥目录(<机器人SN>_soc0/)放到 SDK 根目录下
    (与 examples/ 同级),并修改权限:
    sudo chown -R $USER:$USER ./<机器人SN>_soc0/
    chmod 600 ./<机器人SN>_soc0/id_ed25519
    然后在 SDK 根目录下执行示例命令,使用 -i ./<机器人SN>_soc0/id_ed25519 指定密钥。

用法:
  python3 examples/python/record_audio.py [-i SSH_KEY] <机器人IP> [录音秒数]

  机器人IP 为 127.0.0.1 或 localhost 时自动使用本机模式(共享内存),
  否则使用远程模式(TCP)。

  可选参数:
    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)

示例:
  # 本机录音(共享内存)
  python3 examples/python/record_audio.py 127.0.0.1 5

  # 远程录音(TCP)
  python3 examples/python/record_audio.py <机器人IP> 5

  # 远程录音(使用 SSH 密钥,网线连接时 IP 为 10.1.1.100)
  python3 examples/python/record_audio.py -i ./<机器人SN>_soc0/id_ed25519 10.1.1.100 5
"""

import subprocess
import threading
import wave
import sys
import os
import time

try:
    import numpy as np
    USE_NUMPY = True
except ImportError:
    import struct
    USE_NUMPY = False
    print("警告: 未安装 numpy,分析会较慢")

RATE = 48000
BUILTIN_DEVICE = "alsa_input.platform-aw89403_sound.pro-input-0"

# 本机 PulseAudio unix socket 路径(共享内存传输)
LOCAL_PULSE_SOCKETS = [
    "/run/user/1000/pulse/native",
]


def is_local_robot(robot_ip):
    """判断是否在机器人本机运行。

    检测方式:
      1. IP 为 127.0.0.1 或 localhost
      2. 存在机器人特征目录 /robot/software/

    Returns:
        True 表示本机模式(使用共享内存),False 表示远程模式(使用 TCP)。
    """
    if robot_ip in ("127.0.0.1", "localhost", "::1"):
        return True
    if os.path.isdir("/robot/software"):
        return True
    return False


def get_local_pulse_server():
    """获取本机 PulseAudio unix socket 路径。

    Returns:
        unix socket 路径字符串,或 None(使用 PulseAudio 默认路径)。
    """
    for socket_path in LOCAL_PULSE_SOCKETS:
        if os.path.exists(socket_path):
            return "unix:%s" % socket_path
    return None


def setup_and_detect_source(robot_ip, ssh_key=None):
    """通过一次 SSH 同时完成 TCP 模块加载检查 + 默认录音源检测。

    合并两个 SSH 调用以避免重复输入密码。

    Args:
        robot_ip: 机器人 IP 地址。
        ssh_key: SSH 私钥文件路径(机器人需要密钥登录)。

    Returns:
        str: 默认录音源名称(空字符串表示检测失败)。
    """
    ssh_opts = "-o StrictHostKeyChecking=no -o ConnectTimeout=5"
    if ssh_key:
        ssh_opts += " -i %s" % ssh_key
    cmd = (
        'ssh %s run@%s \''
        'export PULSE_SERVER=unix:/run/user/1000/pulse/native; '
        'if pactl list modules short 2>/dev/null | grep -q module-native-protocol-tcp; then '
        'echo __TCP_MODULE__:ALREADY_LOADED; '
        'else '
        'pactl load-module module-native-protocol-tcp auth-anonymous=1 listen=0.0.0.0 >/dev/null 2>&1 && '
        'echo __TCP_MODULE__:LOADED; '
        'fi; '
        'echo __DEFAULT_SOURCE__; '
        'pactl get-default-source 2>/dev/null\''
        % (ssh_opts, robot_ip)
    )
    try:
        result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
        output = result.stdout
    except KeyboardInterrupt:
        print("\n已取消")
        sys.exit(0)
    except Exception as e:
        print("SSH 连接失败: %s" % e)
        sys.exit(1)

    # 解析 TCP 模块加载状态
    if "__TCP_MODULE__:ALREADY_LOADED" in output:
        print("录音模块已在机器人端加载(跳过加载)")
    elif "__TCP_MODULE__:LOADED" in output:
        print("已在机器人端加载录音模块 (端口 4713)")
    else:
        print("警告: 录音模块加载可能未成功(stderr 已输出到终端)")

    # 解析默认录音源名称(__DEFAULT_SOURCE__ 标记之后的第一行非空内容)
    source = ""
    marker = "__DEFAULT_SOURCE__"
    pos = output.find(marker)
    if pos != -1:
        rest = output[pos + len(marker):].strip()
        if rest:
            source = rest.split("\n")[0].strip()
    return source


def parse_mic_profile(source):
    """根据录音源名称解析麦克风配置字典。"""
    if not source:
        print("无法检测默认录音源,使用内置麦默认配置")
        return {
            'device': BUILTIN_DEVICE,
            'channels': 8,
            'sample_width': 2,
            'format': 's16le',
            'bits_per_sample': 16,
            'is_builtin': True,
        }

    if 'aw89403' in source:
        profile = {
            'device': source,
            'channels': 8,
            'sample_width': 2,
            'format': 's16le',
            'bits_per_sample': 16,
            'is_builtin': True,
        }
        print("检测到内置麦(aw89403): %s" % source)
    else:
        profile = {
            'device': source,
            'channels': 2,
            'sample_width': 3,
            'format': 's24le',
            'bits_per_sample': 24,
            'is_builtin': False,
        }
        print("检测到外置麦(USB): %s" % source)

    print("  格式: %s, %dch, %dHz, %d-bit" % (
        profile['format'], profile['channels'], RATE, profile['bits_per_sample']))
    return profile


# ---------------------------------------------------------------------------
# Microphone profile detection
# ---------------------------------------------------------------------------

def get_default_source(local_mode, robot_ip, ssh_key=None):
    """获取 PulseAudio 默认录音源名称。

    Args:
        local_mode: True 表示本机模式,False 表示远程模式。
        robot_ip: 机器人 IP 地址。
        ssh_key: SSH 私钥文件路径(机器人需要密钥登录)。
    """
    if local_mode:
        cmd = "pactl get-default-source"
    else:
        ssh_opts = "-o StrictHostKeyChecking=no -o ConnectTimeout=5"
        if ssh_key:
            ssh_opts += " -i %s" % ssh_key
        cmd = (
            "ssh %s run@%s '"
            "PULSE_SERVER=unix:/run/user/1000/pulse/native "
            "pactl get-default-source 2>/dev/null'"
            % (ssh_opts, robot_ip)
        )
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        return result.stdout.strip()
    except Exception:
        return ""


def detect_mic_profile(local_mode, robot_ip, ssh_key=None):
    """检测当前默认录音源,返回麦克风配置字典。

    Args:
        local_mode: True 表示本机模式,False 表示远程模式。
        robot_ip: 机器人 IP 地址。
        ssh_key: SSH 私钥文件路径(机器人需要密钥登录)。

    Returns:
        dict: {device, channels, sample_width, format, bits_per_sample, is_builtin}
    """
    source = get_default_source(local_mode, robot_ip, ssh_key)

    if not source:
        print("无法检测默认录音源,使用内置麦默认配置")
        return {
            'device': BUILTIN_DEVICE,
            'channels': 8,
            'sample_width': 2,
            'format': 's16le',
            'bits_per_sample': 16,
            'is_builtin': True,
        }

    if 'aw89403' in source:
        profile = {
            'device': source,
            'channels': 8,
            'sample_width': 2,
            'format': 's16le',
            'bits_per_sample': 16,
            'is_builtin': True,
        }
        print("检测到内置麦(aw89403): %s" % source)
    else:
        profile = {
            'device': source,
            'channels': 2,
            'sample_width': 3,
            'format': 's24le',
            'bits_per_sample': 24,
            'is_builtin': False,
        }
        print("检测到外置麦(USB): %s" % source)

    print("  格式: %s, %dch, %dHz, %d-bit" % (
        profile['format'], profile['channels'], RATE, profile['bits_per_sample']))
    return profile


# ---------------------------------------------------------------------------
# S24LE helpers
# ---------------------------------------------------------------------------

def decode_s24le_numpy(data):
    """将 S24LE 原始字节解码为 int32 numpy 数组。"""
    raw = np.frombuffer(data, dtype=np.uint8)
    n = len(raw) // 3
    raw = raw[:n * 3].reshape(n, 3)
    val = (raw[:, 0].astype(np.int32) |
           (raw[:, 1].astype(np.int32) << 8) |
           (raw[:, 2].astype(np.int32) << 16))
    val[val >= 0x800000] -= 0x1000000  # sign extend
    return val


def s24_to_s16_numpy(s24):
    """将 S24LE int32 numpy 数组转换为 int16(右移 8 位 + 钳位)。"""
    return np.clip(s24 >> 8, -32768, 32767).astype(np.int16)


def decode_s24le_bytes(data):
    """将 S24LE 原始字节解码为 int32 列表(无 numpy 路径)。"""
    samples = []
    for i in range(0, len(data) - 2, 3):
        val = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16)
        if val >= 0x800000:
            val -= 0x1000000
        samples.append(val)
    return samples


def s24_to_s16_scalar(v):
    """将 S24LE int32 标量转换为 int16。"""
    v = v >> 8
    if v > 32767:
        v = 32767
    if v < -32768:
        v = -32768
    return v


def record_pcm(robot_ip, profile, duration=5, local_mode=False):
    """Record multi-channel audio from robot via PulseAudio.

    Args:
        robot_ip: Robot IP address.
        profile: Mic profile dict from detect_mic_profile().
        duration: Recording duration in seconds.
        local_mode: True for local shared memory, False for remote TCP.

    Returns:
        Raw PCM bytes.
    """
    channels = profile['channels']
    sample_width = profile['sample_width']
    fmt = profile['format']
    device = profile['device']

    cmd = [
        'parec',
        '--channels', str(channels),
        '--rate', str(RATE),
        '--format', fmt,
        '--device', device,
        '--channel-map', ','.join(['aux%d' % i for i in range(channels)]),
    ]

    if local_mode:
        pulse_server = get_local_pulse_server()
        if pulse_server:
            env = dict(os.environ, PULSE_SERVER=pulse_server)
            print("本机模式(共享内存: %s),录音 %d 秒..." % (pulse_server, duration))
        else:
            env = dict(os.environ)
            print("本机模式(默认 socket),录音 %d 秒..." % duration)
    else:
        env = dict(os.environ, PULSE_SERVER="tcp:%s:4713" % robot_ip)
        print("远程模式(TCP: %s:4713),录音 %d 秒..." % (robot_ip, duration))
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)

    bytes_per_sec = RATE * channels * sample_width
    total_bytes = bytes_per_sec * duration
    audio = bytearray()
    start_time = time.time()
    stop_display = threading.Event()

    def progress_thread():
        """独立线程,每 0.1 秒刷新一次进度,显示平滑的真实录音时间。"""
        while not stop_display.is_set():
            elapsed = time.time() - start_time
            display_sec = min(elapsed, duration)
            received_sec = len(audio) / bytes_per_sec
            print("\r录音中 %.1f / %d 秒  (已接收 %.1f 秒)" % (display_sec, duration, received_sec), end="", flush=True)
            stop_display.wait(0.1)

    t = threading.Thread(target=progress_thread, daemon=True)
    t.start()

    # 主线程专注读数据,以接收字节数达到目标为结束条件
    while len(audio) < total_bytes and proc.poll() is None:
        chunk = proc.stdout.read1(65536)
        if chunk:
            audio.extend(chunk)
        else:
            time.sleep(0.01)

    # 停止进度显示线程
    stop_display.set()
    t.join()

    proc.terminate()
    proc.wait()

    # Drain remaining data after terminate
    while True:
        chunk = proc.stdout.read1(65536)
        if not chunk:
            break
        audio.extend(chunk)

    # 打印 parec stderr(如有错误信息)
    stderr_data = proc.stderr.read()
    if stderr_data:
        print("\nparec: %s" % stderr_data.decode(errors='replace').strip())

    print()
    return bytes(audio)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: %s [-i SSH_KEY] <机器人IP> [录音秒数]" % sys.argv[0])
        print()
        print("  机器人IP 为 127.0.0.1 或 localhost 时自动使用本机模式(共享内存)")
        print("  否则使用远程模式(TCP)")
        print()
        print("  可选参数:")
        print("    -i SSH_KEY    SSH 私钥文件路径(机器人需要密钥登录)")
        sys.exit(1)

    # 解析可选参数 -i SSH_KEY
    ssh_key = None
    args = sys.argv[1:]
    if args[0] == "-i":
        if len(args) < 3:
            print("错误: -i 参数需要指定 SSH 私钥文件路径")
            sys.exit(1)
        ssh_key = args[1]
        args = args[2:]

    robot_ip = args[0]
    duration = int(args[1]) if len(args) > 1 else 5

    # 检测本机/远程模式
    local_mode = is_local_robot(robot_ip)

    if local_mode:
        print("检测到本机环境,使用共享内存传输(效率更高)")
    else:
        print("检测到远程环境,使用 TCP 传输")
        if ssh_key:
            print("使用 SSH 密钥: %s" % ssh_key)
        # 远程模式:通过一次 SSH 同时完成 TCP 模块加载 + 录音源检测(避免重复输入密码)
        source = setup_and_detect_source(robot_ip, ssh_key)

    # 检测麦克风类型
    if local_mode:
        profile = detect_mic_profile(local_mode, robot_ip, ssh_key)
    else:
        profile = parse_mic_profile(source)
    channels = profile['channels']
    sample_width = profile['sample_width']
    bits_per_sample = profile['bits_per_sample']
    is_builtin = profile['is_builtin']

    print("麦克风配置: %s, %dch, %dHz, %d-bit" % (
        profile['format'], channels, RATE, bits_per_sample))

    data = record_pcm(robot_ip, profile, duration=duration, local_mode=local_mode)

    if not data:
        print("错误: 未录到任何音频数据,请检查 PulseAudio 连接")
        sys.exit(1)

    # Save raw WAV (8ch or 2ch depending on mic type)
    raw_filename = "raw_8ch.wav" if is_builtin else "raw_2ch.wav"
    with wave.open(raw_filename, "wb") as w:
        w.setnchannels(channels)
        w.setsampwidth(sample_width)
        w.setframerate(RATE)
        w.writeframes(data)

    bytes_per_frame = channels * sample_width
    print("录音 %d 字节 (%.1f 秒)" % (len(data), len(data) / (RATE * bytes_per_frame)))
    print("分析中...")

    if USE_NUMPY:
        if is_builtin:
            # Built-in mic: 8ch S16LE
            samples = np.frombuffer(data, dtype=np.int16).reshape(-1, channels)
            avg = np.abs(samples.astype(np.int32)).mean(axis=0)
            peak = np.abs(samples).max(axis=0)

            # Extract channels 5-6 (index 4,5), mix and amplify 10x
            mono = samples[:, [4, 5]].mean(axis=1).astype(np.float32) * 10
            mono = np.clip(mono, -32768, 32767).astype(np.int16)
        else:
            # External USB mic: 2ch S24LE
            s24_samples = decode_s24le_numpy(data).reshape(-1, channels)
            # Convert to 16-bit for analysis
            s16_samples = s24_to_s16_numpy(s24_samples)
            avg = np.abs(s16_samples.astype(np.int32)).mean(axis=0)
            peak = np.abs(s16_samples).max(axis=0)

            # Mix ch1-2, convert 24→16 bit (use integer arithmetic to keep int32 dtype)
            mixed_s24 = (s24_samples[:, 0] + s24_samples[:, 1]) // 2
            mono = s24_to_s16_numpy(mixed_s24)
    else:
        stats = [0] * channels
        peak = [0] * channels
        mono = bytearray()
        n = 0
        frame_size = bytes_per_frame
        for i in range(0, len(data) - frame_size + 1, frame_size):
            frame_data = data[i:i + frame_size]
            if is_builtin:
                # Built-in mic: 8ch S16LE
                s = struct.unpack("<%dh" % channels, frame_data)
                for c in range(channels):
                    stats[c] += abs(s[c])
                    if abs(s[c]) > peak[c]:
                        peak[c] = abs(s[c])
                mixed = (s[4] + s[5]) // 2 * 10  # Mix ch5-6, amplify 10x
                mixed = max(-32768, min(32767, mixed))
                mono.extend(struct.pack("<h", mixed))
            else:
                # External USB mic: 2ch S24LE
                s24 = decode_s24le_bytes(frame_data)
                for c in range(channels):
                    s16 = max(-32768, min(32767, s24[c] >> 8))
                    stats[c] += abs(s16)
                    if abs(s16) > peak[c]:
                        peak[c] = abs(s16)
                mixed_s24 = (s24[0] + s24[1]) // 2
                mixed_s16 = max(-32768, min(32767, mixed_s24 >> 8))
                mono.extend(struct.pack("<h", mixed_s16))
            n += 1
            if n % RATE == 0:
                print("\r处理 %.1f 秒..." % (n / RATE), end="", flush=True)
        avg = [stats[c] / n if n else 0 for c in range(channels)]
        mono = bytes(mono)
        print()

    # Save mono WAV (always 16-bit)
    with wave.open("mic_mono.wav", "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(RATE)
        if USE_NUMPY:
            w.writeframes(mono.tobytes())
        else:
            w.writeframes(mono)

    print("\n各通道音量:")
    for c in range(channels):
        tag = "有声" if avg[c] > 50 else "静音"
        print("  通道 %d: 平均 %6.1f  峰值 %5d  %s" % (c + 1, avg[c], peak[c], tag))

    print("\n保存: %s, mic_mono.wav" % raw_filename)
    print("播放: paplay mic_mono.wav")

音频设备列表(Topic: /aima/hal/audio/audio_device_list) ​

音频设备列表 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_audio_device_list

cpp
/*
 Audio Device List Monitor Example Script

 Description:
   This script demonstrates how to subscribe to the robot's audio device list topic.
   It displays available input (microphone) and output (speaker) devices with their properties.

 Prerequisites:
   - Robot audio service must be running
   - Audio devices must be properly configured

 Usage:
   ros2 run aimdk_examples_cpp get_audio_device_list

 Example:
   ros2 run aimdk_examples_cpp get_audio_device_list

 Parameters:
   - None
 */

#include "aimdk_msgs/msg/audio_device_info_list.hpp"
#include "rclcpp/rclcpp.hpp"

#include <iomanip>
#include <sstream>

class AudioDeviceListEcho : public rclcpp::Node {
public:
  AudioDeviceListEcho() : Node("get_audio_device_list") {
    auto qos = rclcpp::SensorDataQoS();
    sub_ = this->create_subscription<aimdk_msgs::msg::AudioDeviceInfoList>(
        "/aima/hal/audio/audio_device_list", qos,
        std::bind(&AudioDeviceListEcho::callback, this, std::placeholders::_1));

    RCLCPP_INFO(this->get_logger(), "Subscribing audio device list topic: %s",
                "/aima/hal/audio/audio_device_list");
  }

private:
  void callback(const aimdk_msgs::msg::AudioDeviceInfoList::SharedPtr msg) {
    std::ostringstream oss;
    oss << "AudioDeviceInfoList received\n";

    // Print input devices (microphones)
    oss << "  Input devices (" << msg->input_list.size() << "):\n";
    for (size_t i = 0; i < msg->input_list.size(); ++i) {
      const auto &dev = msg->input_list[i];
      oss << "    [" << i << "] id=" << dev.id
          << " addr=" << dev.device_addr
          << " type=" << dev.device_type
          << " name=" << dev.device_name
          << " selected=" << (dev.is_sel ? "yes" : "no") << "\n";
    }

    // Print output devices (speakers)
    oss << "  Output devices (" << msg->output_list.size() << "):\n";
    for (size_t i = 0; i < msg->output_list.size(); ++i) {
      const auto &dev = msg->output_list[i];
      oss << "    [" << i << "] id=" << dev.id
          << " addr=" << dev.device_addr
          << " type=" << dev.device_type
          << " name=" << dev.device_name
          << " selected=" << (dev.is_sel ? "yes" : "no") << "\n";
    }

    RCLCPP_INFO(this->get_logger(), "%s", oss.str().c_str());
  }
  rclcpp::Subscription<aimdk_msgs::msg::AudioDeviceInfoList>::SharedPtr sub_;
};

int main(int argc, char **argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<AudioDeviceListEcho>());
  rclcpp::shutdown();
  return 0;
}
音频设备列表 Python示例 ​

运行命令:python3 get_audio_device_list.py

python
#!/usr/bin/env python3

"""
Audio Device List Monitor Example Script

Description:
  This script demonstrates how to subscribe to the robot's audio device list topic.
  It displays available input (microphone) and output (speaker) devices with their properties.

Prerequisites:
  - Robot audio service must be running
  - Audio devices must be properly configured

Usage:
  python3 get_audio_device_list.py

Example:
  python3 get_audio_device_list.py

Parameters:
  - None
"""

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data

from aimdk_msgs.msg import AudioDeviceInfoList


class AudioDeviceListEcho(Node):
    def __init__(self):
        super().__init__("get_audio_device_list")

        self.subscription = self.create_subscription(
            AudioDeviceInfoList,
            "/aima/hal/audio/audio_device_list",
            self.callback,
            qos_profile_sensor_data,
        )

        self.get_logger().info(
            "Subscribing audio device list topic: /aima/hal/audio/audio_device_list"
        )

    def callback(self, msg: AudioDeviceInfoList):
        lines = ["AudioDeviceInfoList received"]

        # Print input devices (microphones)
        lines.append(f"  Input devices ({len(msg.input_list)}):")
        for i, dev in enumerate(msg.input_list):
            selected = "yes" if dev.is_sel else "no"
            lines.append(
                f"    [{i}] id={dev.id} "
                f"addr={dev.device_addr} "
                f"type={dev.device_type} "
                f"name={dev.device_name} "
                f"selected={selected}"
            )

        # Print output devices (speakers)
        lines.append(f"  Output devices ({len(msg.output_list)}):")
        for i, dev in enumerate(msg.output_list):
            selected = "yes" if dev.is_sel else "no"
            lines.append(
                f"    [{i}] id={dev.id} "
                f"addr={dev.device_addr} "
                f"type={dev.device_type} "
                f"name={dev.device_name} "
                f"selected={selected}"
            )

        self.get_logger().info("\n".join(lines))


def main(args=None):
    rclpy.init(args=args)
    node = AudioDeviceListEcho()
    try:
        rclpy.spin(node)
        return 0
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

语音识别(Topic: /aima/agent/asr_result) ​

语音识别 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_asr_result

cpp
/*
 ASR Result Monitor Example Script

 Description:
   This script demonstrates how to subscribe to the robot's ASR (Automatic Speech Recognition) result topic.
   It displays real-time speech-to-text results including recognized text, confidence, and event context.

 Prerequisites:
   - Robot ASR service must be running
   - Microphone hardware must be operational

 Usage:
   ros2 run aimdk_examples_cpp get_asr_result

 Example:
   ros2 run aimdk_examples_cpp get_asr_result

 Parameters:
   - None
 */

#include "aimdk_msgs/msg/asr_result.hpp"
#include "rclcpp/rclcpp.hpp"

#include <iomanip>
#include <sstream>

class AsrResultEcho : public rclcpp::Node {
public:
  AsrResultEcho() : Node("get_asr_result") {
    auto qos = rclcpp::SensorDataQoS();
    sub_ = this->create_subscription<aimdk_msgs::msg::AsrResult>(
        "/aima/agent/asr_result", qos,
        std::bind(&AsrResultEcho::callback, this, std::placeholders::_1));

    RCLCPP_INFO(this->get_logger(), "Subscribing ASR topic: %s",
                "/aima/agent/asr_result");
  }

private:
  void callback(const aimdk_msgs::msg::AsrResult::SharedPtr msg) {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(6);
    oss << "AsrResult received\n"
        << "  frame_id:   " << msg->header.frame_id << "\n"
        << "  sequence:   " << msg->header.sequence << "\n"
        << "  stamp:      " << rclcpp::Time(msg->header.stamp).seconds() << " s\n"
        << "  text:       " << msg->text << "\n"
        << "  event_id:   " << msg->event_id << "\n"
        << "  is_final:   " << (msg->is_final ? "true" : "false") << "\n"
        << "  confidence: " << msg->confidence << "\n"
        << "  language:   " << msg->language;

    RCLCPP_INFO_THROTTLE(this->get_logger(), *this->get_clock(), 500, "%s",
                         oss.str().c_str());
  }
  rclcpp::Subscription<aimdk_msgs::msg::AsrResult>::SharedPtr sub_;
};

int main(int argc, char **argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<AsrResultEcho>());
  rclcpp::shutdown();
  return 0;
}
语音识别 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 get_asr_result.py

python
#!/usr/bin/env python3

"""
ASR Result Monitor Example Script

Description:
  This script demonstrates how to subscribe to the robot's ASR (Automatic Speech Recognition) result topic.
  It displays real-time speech-to-text results including recognized text, confidence, and event context.

Prerequisites:
  - Robot ASR service must be running
  - Microphone hardware must be operational

Usage:
  python3 get_asr_result.py

Example:
  python3 get_asr_result.py

Parameters:
  - None
"""

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data

from aimdk_msgs.msg import AsrResult


class AsrResultEcho(Node):
    def __init__(self):
        super().__init__("get_asr_result")

        self.subscription = self.create_subscription(
            AsrResult,
            "/aima/agent/asr_result",
            self.callback,
            qos_profile_sensor_data,
        )

        self.get_logger().info("Subscribing ASR topic: /aima/agent/asr_result")

    @staticmethod
    def _to_seconds(stamp) -> float:
        return float(stamp.sec) + float(stamp.nanosec) / 1_000_000_000.0

    def callback(self, msg: AsrResult):
        lines = [
            "AsrResult received",
            f"  frame_id:   {msg.header.frame_id}",
            f"  sequence:   {msg.header.sequence}",
            f"  stamp:      {self._to_seconds(msg.header.stamp):.6f} s",
            f"  text:       {msg.text}",
            f"  event_id:   {msg.event_id}",
            f"  is_final:   {msg.is_final}",
            f"  confidence: {msg.confidence:.4f}",
            f"  language:   {msg.language}",
        ]

        self.get_logger().info("\n".join(lines))


def main(args=None):
    rclpy.init(args=args)
    node = AsrResultEcho()
    try:
        rclpy.spin(node)
        return 0
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

4.2.2 屏幕控制 ​

代码示例

表情播放(Service: PlayEmotion) ​

表情播放 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp play_emotion

cpp
/*
 Emotion Playback Example Script

 Description:
   This script demonstrates how to play robot emotions using the PlayEmotion service.
   Supports built-in emotion IDs, custom emotion file paths, and image display.

 Prerequisites:
   - Robot emotion service must be running
   - Emotion files must be available on the robot

 Usage:
   ros2 run aimdk_examples_cpp play_emotion --ros-args -p type:=<type> -p emotion_ids:="[...]" -p file_paths:="[...]"

 Example:
   # Play built-in emotion with ID 3003
   ros2 run aimdk_examples_cpp play_emotion --ros-args -p type:=emotion -p emotion_ids:="[3003]"

   # Play custom emotion from file
   ros2 run aimdk_examples_cpp play_emotion --ros-args -p type:=file -p file_paths:="['/path/to/emotion.mp4']"

   # Display an image
   ros2 run aimdk_examples_cpp play_emotion --ros-args -p type:=image -p file_paths:="['/path/to/image.png']"

 Parameters:
   - type: Emotion type, 'emotion', 'file' or 'image' (default: emotion)
   - emotion_ids: List of built-in emotion IDs to play (default: [3003])
   - file_paths: List of custom emotion file paths or image URLs (optional)
 */
#include "aimdk_msgs/srv/play_emotion.hpp"
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "rclcpp/rclcpp.hpp"

#include <signal.h>
#include <chrono>
#include <cstdint>
#include <exception>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

constexpr int kMaxRetryCount = 3;
constexpr std::chrono::seconds kServiceCallTimeout(2);

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...", signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class PlayEmotionClient : public rclcpp::Node
{
 public:
  PlayEmotionClient() : Node("play_emotion_client")
  {
    type_        = this->declare_parameter<std::string>("type", "emotion");
    emotion_ids_ = this->declare_parameter<std::vector<int64_t>>(
      "emotion_ids", std::vector<int64_t>{3003});
    file_paths_ = this->declare_parameter<std::vector<std::string>>(
      "file_paths", std::vector<std::string>{});

    client_ = this->create_client<aimdk_msgs::srv::PlayEmotion>(
      "/aimdk_5Fmsgs/srv/PlayEmotion");
    RCLCPP_INFO(this->get_logger(), "PlayEmotion client node created.");

    while (!client_->wait_for_service(std::chrono::seconds(2))) {
      if (!rclcpp::ok())
        return;
      RCLCPP_INFO(this->get_logger(), "Waiting for service...");
    }
  }

  bool send_request()
  {
    try {
      if (!validate_parameters()) return false;

    bool ok = call_service(type_, emotion_ids_, file_paths_);

      if (!ok) {
        RCLCPP_ERROR(this->get_logger(), "PlayEmotion request failed after all attempts.");
        return false;
      }
      return true;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

 private:
  bool call_service(const std::string &type, const std::vector<int64_t> &emotion_ids, const std::vector<std::string> &file_paths)
  {
    auto request                 = std::make_shared<aimdk_msgs::srv::PlayEmotion::Request>();
    request->header.header.stamp = this->now();
    request->type                = type;
    request->priority            = priority_;
    request->loop_count          = loop_count_;

    for (auto id : emotion_ids)
      request->emotion_ids.push_back(static_cast<int32_t>(id));
    request->file_paths = file_paths;

    RCLCPP_INFO(this->get_logger(), "Sending PlayEmotion request: type=%s", type.c_str());

    // Retry mechanism: up to 3 attempts
    auto future = client_->async_send_request(request);
    bool completed = false;
    
    for (int i = 0; i < kMaxRetryCount; ++i) {
      auto retcode = rclcpp::spin_until_future_complete(
          shared_from_this(), future, kServiceCallTimeout);
      
      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        completed = true;
        break;
      }

      RCLCPP_INFO(this->get_logger(),
                  "PlayEmotion attempt %d/%d timed out, retrying...",
                  i + 1, kMaxRetryCount);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      
      // Re-send request for retry
      future = client_->async_send_request(request);
    }

    if (!completed) {
      return false;
    }

    auto res    = future.get();
    if (!res) {
      return false;
    }
    
    auto code   = res->header.header.code;
    auto status = res->header.status.value;

    if (code == 0 || status == aimdk_msgs::msg::CommonState::SUCCESS) {
      RCLCPP_INFO(this->get_logger(), "Request accepted (code=%ld, status=%d).", code, status);
      return true;
    }
    
    RCLCPP_ERROR(this->get_logger(),
                 "PlayEmotion failed. code=%ld status=%d msg=%s",
                 code, status, res->header.message.c_str());
    return false;
  }

  bool validate_parameters()
  {
    if (type_ != "emotion" && type_ != "file" && type_ != "image") return false;
    if (type_ == "emotion" && emotion_ids_.empty()) return false;
    if ((type_ == "file" || type_ == "image") && file_paths_.empty()) return false;
    return true;
  }

  std::string type_;
  std::vector<int64_t> emotion_ids_;
  std::vector<std::string> file_paths_;
  int32_t priority_   = 0;
  int32_t loop_count_ = 1;
  rclcpp::Client<aimdk_msgs::srv::PlayEmotion>::SharedPtr client_;
};

int main(int argc, char *argv[])
{
  try {
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    g_node      = std::make_shared<PlayEmotionClient>();
    auto client = std::dynamic_pointer_cast<PlayEmotionClient>(g_node);
    bool ok     = client ? client->send_request() : false;

    g_node.reset();
    rclcpp::shutdown();
    return ok ? 0 : 1;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("main"), "Exited with exception: %s", e.what());
    return 1;
  }
}
表情播放 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/play_emotion.py

python
#!/usr/bin/env python3

"""
Emotion Playback Example Script

Description:
  This script demonstrates how to play robot emotions using the PlayEmotion service.
  Supports built-in emotion IDs, custom emotion file paths, and image display.

Prerequisites:
  - Robot emotion service must be running
  - Emotion files must be available on the robot

Usage:
  python3 play_emotion.py --ros-args -p type:=<type> -p emotion_ids:="[...]" -p file_paths:="[...]"

Example:
  # Play built-in emotion with ID 3003
  python3 play_emotion.py --ros-args -p type:=emotion -p emotion_ids:="[3003]"

  # Play custom emotion from file
  python3 play_emotion.py --ros-args -p type:=file -p file_paths:="['/path/to/emotion.mp4']"

  # Display an image
  python3 play_emotion.py --ros-args -p type:=image -p file_paths:="['/path/to/image.png']"

Parameters:
  - type: Emotion type, 'emotion', 'file' or 'image' (default: emotion)
  - emotion_ids: List of built-in emotion IDs to play (default: [3003])
  - file_paths: List of custom emotion file paths or image URLs (optional)
"""

import rclpy
import time

import rclpy.logging
from rclpy.node import Node
from rclpy.parameter import Parameter

from aimdk_msgs.msg import CommonRequest, CommonState
from aimdk_msgs.srv import PlayEmotion


class PlayEmotionClient(Node):
    def __init__(self):
        super().__init__("play_emotion_client")
        self.declare_parameter("type", "emotion")
        self.declare_parameter("emotion_ids", [3003])
        self.declare_parameter("file_paths", Parameter.Type.STRING_ARRAY)

        self.type = self.get_parameter("type").value
        self.emotion_ids = self.get_parameter_or(
            "emotion_ids",
            Parameter("emotion_ids", Parameter.Type.INTEGER_ARRAY, [3003]),
        ).value
        self.file_paths = self.get_parameter_or(
            "file_paths",
            Parameter("file_paths", Parameter.Type.STRING_ARRAY, []),
        ).value
        self.priority = 0
        self.loop_count = 1

        self.client = self.create_client(PlayEmotion, "/aimdk_5Fmsgs/srv/PlayEmotion")
        self.get_logger().info("PlayEmotion client node created.")

        while not self.client.wait_for_service(timeout_sec=2.0):
            self.get_logger().info("Waiting for service...")
        self.get_logger().info("Service available, ready to send request.")

    def send_request(self) -> bool:
        try:
            if not self.validate_parameters():
                return False

            ok = self._call_service(self.type, list(self.emotion_ids), list(self.file_paths))

            if not ok:
                self.get_logger().error("PlayEmotion request failed after all attempts.")
                return False

            return True
        except Exception as error:  # noqa: BLE001
            self.get_logger().error(f"Exception occurred: {error}")
            return False

    def _call_service(self, msg_type, emotion_ids, file_paths) -> bool:
        request = PlayEmotion.Request()
        request.header = CommonRequest()
        request.header.header.stamp = self.get_clock().now().to_msg()
        request.type = msg_type
        request.priority = self.priority
        request.loop_count = self.loop_count
        request.emotion_ids = emotion_ids
        request.file_paths = file_paths

        self.get_logger().info(
            f"Sending PlayEmotion request: type={msg_type}, "
            f"emotion_ids={emotion_ids}, file_paths={file_paths}"
        )

        for i in range(3):
            future = self.client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=2.0)

            if future.done():
                break

            self.get_logger().info(f'trying ... [{i}]')
            time.sleep(0.2)

        if not future.done():
            return False

        response = future.result()
        if response is None:
            return False

        code = response.header.header.code
        status = response.header.status.value
        if code == 0 or status == CommonState.SUCCESS:
            self.get_logger().info(f"Request accepted (code={code}, status={status}).")
            return True

        self.get_logger().error(
            f"PlayEmotion failed. "
            f"code={code} status={status} "
            f"msg={response.header.message}"
        )
        return False

    def validate_parameters(self) -> bool:
        if self.type not in ("emotion", "file", "image"):
            self.get_logger().error(
                f"Invalid parameter 'type': {self.type}. Use 'emotion', 'file' or 'image'."
            )
            return False

        if self.type == "emotion" and not self.emotion_ids:
            self.get_logger().error(
                "Parameter 'emotion_ids' must be set when type=emotion."
            )
            return False

        if self.type in ("file", "image") and not self.file_paths:
            self.get_logger().error(
                "Parameter 'file_paths' must be set when type=file or type=image."
            )
            return False

        return True


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        node = PlayEmotionClient()
        ok = node.send_request()
        return 0 if ok else 1
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("main").error(
            f"Program exited with exception: {error}"
        )
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

4.3 硬件抽象功能 ​

4.3.1 触觉传感器 ​

代码示例

读取触觉状态(Topic: /aima/hal/touch/state) ​

读取触觉状态 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_touch_state

cpp
/*
 Touch State Monitor Example Script
 
 Description:
   This script demonstrates how to subscribe to the robot's touch state topic.
   It displays real-time touch event information including event type, timestamp, and sequence number.
 
 Prerequisites:
   - Robot touch sensor service must be running
   - Touch sensor hardware must be operational
 
 Usage:
   ros2 run aimdk_examples_cpp get_touch_state
 
 Example:
   ros2 run aimdk_examples_cpp get_touch_state
 
 Parameters:
   - None
 */

#include "aimdk_msgs/msg/touch_state.hpp"
#include "rclcpp/rclcpp.hpp"

#include <iomanip>
#include <sstream>

class TouchStateEcho : public rclcpp::Node {
public:
  TouchStateEcho() : Node("get_touch_state") {
    auto qos = rclcpp::SensorDataQoS();
    sub_ = this->create_subscription<aimdk_msgs::msg::TouchState>(
        "/aima/hal/touch/state", qos,
        std::bind(&TouchStateEcho::callback, this, std::placeholders::_1));

    RCLCPP_INFO(this->get_logger(), "Subscribing touch topic: %s",
                "/aima/hal/touch/state");
  }

private:
  void callback(const aimdk_msgs::msg::TouchState::SharedPtr msg) {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(6);
    // event_type is the primary field of interest.
    oss << "TouchState received\n"
        << "  frame_id: " << msg->header.frame_id << "\n"
        << "  sequence: " << msg->header.sequence << "\n"
        << "  stamp:    " << rclcpp::Time(msg->header.stamp).seconds() << " s\n"
        << "  meas:     " << rclcpp::Time(msg->header.meas_stamp).seconds() << " s\n"
        << "  sensor:   " << static_cast<int>(msg->sensor_id) << "\n"
        << "  event:    " << static_cast<int>(msg->event_type);

    // Throttle logs to avoid flooding the console.
    RCLCPP_INFO_THROTTLE(this->get_logger(), *this->get_clock(), 500, "%s",
                         oss.str().c_str());
  }
  rclcpp::Subscription<aimdk_msgs::msg::TouchState>::SharedPtr sub_;
};

int main(int argc, char **argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<TouchStateEcho>());
  rclcpp::shutdown();
  return 0;
}
读取触觉状态 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/get_touch_state.py

python
#!/usr/bin/env python3

"""
Touch State Monitor Example Script

Description:
  This script demonstrates how to subscribe to the robot's touch state topic.
  It displays real-time touch event information including event type, timestamp, and sequence number.

Prerequisites:
  - Robot touch sensor service must be running
  - Touch sensor hardware must be operational

Usage:
  python3 get_touch_state.py

Example:
  python3 get_touch_state.py

Parameters:
  - None
"""

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data

from aimdk_msgs.msg import TouchState


class TouchStateEcho(Node):
    def __init__(self):
        super().__init__("get_touch_state")

        self.subscription = self.create_subscription(
            TouchState,
            "/aima/hal/touch/state",
            self.callback,
            qos_profile_sensor_data,
        )

        self.get_logger().info("Subscribing touch topic: /aima/hal/touch/state")

    @staticmethod
    def _to_seconds(stamp) -> float:
        return float(stamp.sec) + float(stamp.nanosec) / 1_000_000_000.0

    def callback(self, msg: TouchState):
        # event_type is the primary field of interest.
        lines = [
            "TouchState received",
            f"  frame_id: {msg.header.frame_id}",
            f"  sequence: {msg.header.sequence}",
            f"  stamp:    {self._to_seconds(msg.header.stamp):.6f} s",
            f"  meas:     {self._to_seconds(msg.header.meas_stamp):.6f} s",
            f"  sensor:   {int(msg.sensor_id)}",
            f"  event:    {int(msg.event_type)}",
        ]

        self.get_logger().info("\n".join(lines))


def main(args=None):
    rclpy.init(args=args)
    node = TouchStateEcho()
    try:
        rclpy.spin(node)
        return 0
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

4.3.2 视觉传感器 ​

摄像头单帧数据获取(Service: CaptureJpegImage) ​

摄像头单帧数据获取 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_jpg

cpp
/*
 Camera JPEG Capture Example Script
 
 Description:
   This script demonstrates how to call the CaptureJpegImage service to capture a JPEG image from the robot's camera.
   Supports multiple camera devices and interactive camera selection.
 
 Prerequisites:
   - Robot camera service must be running
   - Camera hardware must be operational
   - CaptureJpegImage service must be available
 
 Usage:
   ros2 run aimdk_examples_cpp get_jpg --ros-args -p camera_id:=<camera_id> -p output_file:=<path> -p timeout_ms:=<milliseconds>
 
 Example:
   # Interactive mode (will prompt for camera_id)
   ros2 run aimdk_examples_cpp get_jpg --ros-args -p output_file:=/tmp/camera_capture.jpg
   
   # Specify camera and output path
   ros2 run aimdk_examples_cpp get_jpg --ros-args -p camera_id:=head_monocular_centra -p output_file:=/tmp/my_photo.jpg
 
 Parameters:
   - camera_id: Camera identifier (interactive prompt if not provided)
   - timeout_ms: Wait time for a fresh JPEG frame in milliseconds (Default: 5000, Min: 6000)
   - output_file: Local JPEG output path (Default: /tmp/camera_capture.jpg)
 */
#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/srv/capture_jpeg_image.hpp"
#include "rclcpp/rclcpp.hpp"

#include <algorithm>
#include <chrono>
#include <cstdint>
#include <ctime>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <signal.h>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

namespace {

constexpr char kDefaultServiceName[] =
    "/aima/hal/camera/CaptureJpegImage";
constexpr char kDefaultOutputFile[] = "/tmp/camera_capture.jpg";
constexpr int kDefaultRequestTimeoutMs = 5000;
constexpr int kServiceWaitSeconds = 2;
constexpr int kMinCallTimeoutMs = 6000;
constexpr int kMaxRetryCount = 3;

std::shared_ptr<rclcpp::Node> g_node = nullptr;

std::string get_camera_id_from_user() {
  std::cout << "\n" << std::string(60, '=') << std::endl;
  std::cout << "The list of Q series Camera IDs is as follows:" << std::endl;
  std::cout << std::string(60, '=') << std::endl;
  std::cout << "  head_monocular_centra  - Head monocular central camera" << std::endl;
  std::cout << std::string(60, '=') << std::endl;
  std::cout << "For camera_id corresponding to different robot configurations, please refer to the interface documentation." << std::endl;
  std::cout << std::endl;
  
  std::cout << "\nPlease enter camera ID: ";
  std::string camera_id;
  std::getline(std::cin, camera_id);
  
  // Trim whitespace
  size_t start = camera_id.find_first_not_of(" \t\r\n");
  if (start == std::string::npos) {
    std::cout << "\nError: camera_id cannot be empty." << std::endl;
    std::cout << "Exiting...\n" << std::endl;
    std::exit(1);
  }
  size_t end = camera_id.find_last_not_of(" \t\r\n");
  camera_id = camera_id.substr(start, end - start + 1);
  
  std::cout << "\nUsing camera_id: " << camera_id << std::endl;
  std::cout << std::string(60, '=') << "\n" << std::endl;
  
  return camera_id;
}

std::filesystem::path prepare_output_path(const std::string &output_file) {
  std::filesystem::path output_path(
    output_file.empty() ? std::string(kDefaultOutputFile) : output_file);

  const auto extension = output_path.extension().string();
  if (extension != ".jpg" && extension != ".jpeg" && extension != ".JPG" &&
      extension != ".JPEG") {
    throw std::invalid_argument(
        "output_file must use the .jpg or .jpeg extension.");
  }

  const auto parent = output_path.parent_path();
  if (!parent.empty()) {
    std::error_code ec;
    std::filesystem::create_directories(parent, ec);
    if (ec) {
      throw std::runtime_error("Failed to create directory " +
                               parent.string() + ": " + ec.message());
    }
  }

  return output_path;
}

class CaptureJpegClient : public rclcpp::Node {
public:
  CaptureJpegClient(const std::string &camera_id) : Node("get_jpg") {
    service_name_ =
        this->declare_parameter<std::string>("service_name", kDefaultServiceName);
    timeout_ms_ =
        this->declare_parameter<int>("timeout_ms", kDefaultRequestTimeoutMs);
    output_file_ = this->declare_parameter<std::string>("output_file", "");
    camera_id_ = camera_id;  // Use the camera_id passed from user input

    if (service_name_.empty()) {
      throw std::invalid_argument("service_name must not be empty.");
    }

    if (timeout_ms_ < 0) {
      throw std::invalid_argument("timeout_ms must be greater than or equal to 0.");
    }

    output_path_ = prepare_output_path(output_file_);
    client_ = this->create_client<aimdk_msgs::srv::CaptureJpegImage>(
        service_name_);

    RCLCPP_INFO(this->get_logger(),
                "CaptureJpegImage client created. service=%s camera_id=%s "
                "timeout_ms=%d output_file=%s",
                service_name_.c_str(), camera_id_.empty() ? "(default)" : camera_id_.c_str(),
                timeout_ms_,
                output_path_.string().c_str());
  }

  bool capture_once() {
    if (!wait_for_service()) {
      return false;
    }

    auto request =
        std::make_shared<aimdk_msgs::srv::CaptureJpegImage::Request>();
    request->request = aimdk_msgs::msg::CommonRequest();
    request->request.header.stamp = this->now();
    request->camera_id = camera_id_;
    request->timeout_ms = static_cast<std::uint32_t>(timeout_ms_);

    RCLCPP_INFO(this->get_logger(),
                "Sending CaptureJpegImage request: camera_id=%s timeout_ms=%u",
                camera_id_.empty() ? "(default)" : camera_id_.c_str(),
                request->timeout_ms);

    // Retry mechanism: up to 3 attempts
    auto future = client_->async_send_request(request);
    const auto call_timeout = std::chrono::milliseconds(
        std::max(kMinCallTimeoutMs, timeout_ms_ + 1000));
    
    bool completed = false;
    for (int i = 0; i < kMaxRetryCount; ++i) {
      const auto retcode = rclcpp::spin_until_future_complete(
          shared_from_this(), future, call_timeout);

      if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
        completed = true;
        break;
      }

      RCLCPP_INFO(this->get_logger(),
                  "CaptureJpegImage attempt %d/%d timed out, retrying...",
                  i + 1, kMaxRetryCount);
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      
      // Re-send request for retry
      future = client_->async_send_request(request);
    }

    if (!completed) {
      RCLCPP_ERROR(this->get_logger(),
                   "CaptureJpegImage timed out after %lld ms.",
                   static_cast<long long>(call_timeout.count()));
      return false;
    }

    const auto response = future.get();
    if (!response) {
      RCLCPP_ERROR(this->get_logger(),
                   "CaptureJpegImage returned an empty response.");
      return false;
    }

    return save_response(*response);
  }

  void request_shutdown(int signal) {
    if (stop_requested_) {
      return;
    }

    stop_requested_ = true;
    RCLCPP_INFO(this->get_logger(),
                "Received signal %d, shutting down get_jpg...", signal);
    rclcpp::shutdown();
  }

private:
  bool wait_for_service() {
    while (!stop_requested_ &&
           !client_->wait_for_service(std::chrono::seconds(kServiceWaitSeconds))) {
      if (!rclcpp::ok()) {
        return false;
      }
      RCLCPP_INFO(this->get_logger(), "Waiting for service: %s",
                  service_name_.c_str());
    }

    if (stop_requested_ || !rclcpp::ok()) {
      return false;
    }

    RCLCPP_INFO(this->get_logger(), "Service available: %s",
                service_name_.c_str());
    return true;
  }

  bool save_response(const aimdk_msgs::srv::CaptureJpegImage::Response &response) {
    const auto code = response.response.header.code;
    const auto status = response.response.status.value;
    if (code != 0 && status != aimdk_msgs::msg::CommonState::SUCCESS) {
      RCLCPP_ERROR(this->get_logger(),
                   "CaptureJpegImage failed. code=%ld status=%d msg=%s", code,
                   status, response.response.message.c_str());
      return false;
    }

    const auto &jpeg = response.jpeg;
    const auto &image = jpeg.image;
    if (image.data.empty()) {
      RCLCPP_ERROR(this->get_logger(),
                   "CaptureJpegImage returned empty JPEG data.");
      return false;
    }

    std::ofstream output_stream(
        output_path_, std::ios::binary | std::ios::out | std::ios::trunc);
    if (!output_stream.is_open()) {
      RCLCPP_ERROR(this->get_logger(), "Failed to open output file: %s",
                   output_path_.string().c_str());
      return false;
    }

    output_stream.write(reinterpret_cast<const char *>(image.data.data()),
                        static_cast<std::streamsize>(image.data.size()));
    if (!output_stream) {
      RCLCPP_ERROR(this->get_logger(), "Failed to write JPEG file: %s",
                   output_path_.string().c_str());
      return false;
    }
    output_stream.close();

    RCLCPP_INFO(
        this->get_logger(),
        "JPEG saved: file=%s bytes=%zu format=%s camera_id=%s device=%s "
        "width=%u height=%u framerate=%u exposure=%u gain=%u frame_id=%s",
        output_path_.string().c_str(), image.data.size(), image.format.c_str(),
        jpeg.camera_id.c_str(), jpeg.device.c_str(), jpeg.width, jpeg.height,
        jpeg.framerate, jpeg.exposure, jpeg.gain, image.header.frame_id.c_str());
    return true;
  }

  std::string service_name_;
  std::string camera_id_;
  int timeout_ms_{kDefaultRequestTimeoutMs};
  std::string output_file_;
  std::filesystem::path output_path_;
  bool stop_requested_{false};
  rclcpp::Client<aimdk_msgs::srv::CaptureJpegImage>::SharedPtr client_;
};

void signal_handler(int signal) {
  if (!rclcpp::ok()) {
    return;
  }

  if (g_node) {
    if (auto node = std::dynamic_pointer_cast<CaptureJpegClient>(g_node)) {
      node->request_shutdown(signal);
    } else {
      RCLCPP_INFO(g_node->get_logger(),
                  "Received signal %d, shutting down get_jpg...", signal);
      rclcpp::shutdown();
    }
    g_node.reset();
    return;
  }

  rclcpp::shutdown();
}

}  // namespace

int main(int argc, char *argv[]) {
  try {
    // Get camera_id from user input before creating the node
    std::string camera_id = get_camera_id_from_user();
    
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    auto node = std::make_shared<CaptureJpegClient>(camera_id);
    g_node = node;
    const bool ok = node->capture_once();

    g_node.reset();
    rclcpp::shutdown();
    return ok ? 0 : 1;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("get_jpg"),
                 "Program exited with exception: %s", e.what());
    return 1;
  }
}
摄像头单帧数据获取 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/get_jpg.py

python
#!/usr/bin/env python3

"""
Camera JPEG Capture Example Script

Description:
  This script demonstrates how to call the CaptureJpegImage service to capture a JPEG image from the robot's camera.
  Supports multiple camera devices and interactive camera selection.

Prerequisites:
  - Robot camera service must be running
  - Camera hardware must be operational
  - CaptureJpegImage service must be available

Usage:
  python3 get_jpg.py --ros-args -p camera_id:=<camera_id> -p output_file:=<path> -p timeout_ms:=<milliseconds>

Example:
  # Interactive mode (will prompt for camera_id)
  python3 get_jpg.py
  
  # Specify camera and output path
  python3 get_jpg.py --ros-args -p camera_id:=head_monocular_centra -p output_file:=/tmp/my_photo.jpg

Parameters:
  - camera_id: Camera identifier (interactive prompt if not provided)
  - timeout_ms: Wait time for a fresh JPEG frame in milliseconds (Default: 5000, Min: 6000)
  - output_file: Local JPEG output path (Default: /tmp/camera_capture.jpg)
"""

from pathlib import Path
import sys
import time

import rclpy
import rclpy.logging
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest, CommonState
from aimdk_msgs.srv import CaptureJpegImage



DEFAULT_SERVICE_NAME = "/aima/hal/camera/CaptureJpegImage"
DEFAULT_OUTPUT_FILE = "/tmp/camera_capture.jpg"
DEFAULT_REQUEST_TIMEOUT_MS = 5000
SERVICE_WAIT_SECONDS = 2.0
MIN_CALL_TIMEOUT_MS = 6000


def prepare_output_path(output_file: str) -> Path:
    output_path = Path(output_file or DEFAULT_OUTPUT_FILE).expanduser()
    if output_path.suffix.lower() not in {".jpg", ".jpeg"}:
        raise ValueError("output_file must use the .jpg or .jpeg extension.")

    output_path.parent.mkdir(parents=True, exist_ok=True)
    return output_path


def get_camera_id_from_user() -> str:
    """Interactively get camera_id from user input."""
    print("\n" + "="*60)
    print("The list of Q series Camera IDs is as follows:")
    print("="*60)
    print("  head_monocular_centra  - 头部单目中央相机")
    print("="*60)
    print("For camera_id corresponding to different robot configurations, please refer to the interface documentation.")
    print("")
    camera_id = input("\nPlease enter camera ID: ").strip()
    
    if not camera_id:
        print("\nError: camera_id cannot be empty.")
        print("Exiting...\n")
        sys.exit(1)
    
    print(f"\nUsing camera_id: {camera_id}")
    print("="*60 + "\n", flush=True)
    return camera_id


class CaptureJpegClient(Node):
    def __init__(self, camera_id: str) -> None:
        super().__init__("get_jpg")

        self.service_name = self.declare_parameter(
            "service_name", DEFAULT_SERVICE_NAME
        ).value
        self.timeout_ms = self.declare_parameter(
            "timeout_ms", DEFAULT_REQUEST_TIMEOUT_MS
        ).value
        self.output_file = self.declare_parameter("output_file", "").value 
        self.camera_id = camera_id  

        if not self.service_name:
            raise ValueError("service_name must not be empty.")

        if self.timeout_ms < 0:
            raise ValueError("timeout_ms must be greater than or equal to 0.")

        self.output_path = prepare_output_path(self.output_file)
        self.client = self.create_client(CaptureJpegImage, self.service_name)

        # 打印客户端创建成功日志
        self.get_logger().info(
            "CaptureJpegImage client created. "
            f"service={self.service_name} "
            f"camera_id={self.camera_id} "
            f"timeout_ms={self.timeout_ms} "
            f"output_file={self.output_path}"
        )

    def wait_for_service(self) -> bool:
        while not self.client.wait_for_service(timeout_sec=SERVICE_WAIT_SECONDS):
            if not rclpy.ok():
                return False
            self.get_logger().info(f"Waiting for service: {self.service_name}")

        self.get_logger().info(f"Service available: {self.service_name}")
        return True

    def capture_once(self) -> bool:
        if not self.wait_for_service():
            return False

        request = CaptureJpegImage.Request()
        request.request = CommonRequest()
        request.request.header.stamp = self.get_clock().now().to_msg()
        request.camera_id = self.camera_id
        request.timeout_ms = self.timeout_ms

        self.get_logger().info(
            f"Sending CaptureJpegImage request: timeout_ms={request.timeout_ms}"
        )

        for i in range(3):
            future = self.client.call_async(request)
            call_timeout_sec = max(MIN_CALL_TIMEOUT_MS, self.timeout_ms + 1000) / 1000.0
            rclpy.spin_until_future_complete(self, future, timeout_sec=call_timeout_sec)

            if future.done():
                break

            self.get_logger().info(f'trying ... [{i}]')
            time.sleep(0.2)
            
        if not future.done():
            self.get_logger().error(
                f"CaptureJpegImage timed out after {int(call_timeout_sec * 1000)} ms."
            )
            return False

        response = future.result()
        if response is None:
            self.get_logger().error("CaptureJpegImage returned an empty response.")
            return False

        return self.save_response(response)

    def save_response(self, response: CaptureJpegImage.Response) -> bool:
        code = response.response.header.code
        status = response.response.status.value
        if code != 0 and status != CommonState.SUCCESS:
            self.get_logger().error(
                f"CaptureJpegImage failed. "
                f"code={code} status={status} msg={response.response.message}"
            )
            return False

        jpeg = response.jpeg
        image = jpeg.image
        jpeg_bytes = bytes(image.data)
        if not jpeg_bytes:
            self.get_logger().error("CaptureJpegImage returned empty JPEG data.")
            return False

        try:
            self.output_path.write_bytes(jpeg_bytes)
        except OSError:
            self.get_logger().error(f"Failed to write JPEG file: {self.output_path}")
            return False

        self.get_logger().info(
            "JPEG saved: "
            f"file={self.output_path} "
            f"bytes={len(jpeg_bytes)} "
            f"format={image.format} "
            f"camera_id={jpeg.camera_id} "
            f"device={jpeg.device} "
            f"width={jpeg.width} "
            f"height={jpeg.height} "
            f"framerate={jpeg.framerate} "
            f"exposure={jpeg.exposure} "
            f"gain={jpeg.gain} "
            f"frame_id={image.header.frame_id}"
        )
        return True


def main(args=None) -> int:
    rclpy.init(args=args)
    node = None

    try:
        camera_id = get_camera_id_from_user()
        
        node = CaptureJpegClient(camera_id)
        return 0 if node.capture_once() else 1
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("get_jpg").error(
            f"Program exited with exception: {error}"
        )
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

视频流获取(RTSP: rtsp://<IP>:<Port>/live_<camera_id>) ​

视频流获取 Cpp示例 ​

执行前置:需满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_video_stream

cpp
/*
 RTSP Video Stream Reader Example Script
 
 Description:
   This script demonstrates how to read video streams from the robot's cameras via RTSP protocol.
   Supports multiple camera devices and saves video to MP4 format.
 
 Prerequisites:
   - Robot RTSP service must be running
   - Camera hardware must be operational
   - OpenCV 4.13.0 is provided by the SDK's aimdk_opencv source package
   - Network connection to robot must be available
 
 Usage:
   ros2 run aimdk_examples_cpp get_video_stream --camera <camera_id> --ip <robot_ip> --output <path> --duration <seconds>
 
 Example:
   # Interactive mode (will prompt for camera and IP)
   ros2 run aimdk_examples_cpp get_video_stream
   
   # Specify camera, IP, and output path
   ros2 run aimdk_examples_cpp get_video_stream --camera head_monocular_centra --ip 10.1.1.100 --output /tmp/my_video.mp4 --duration 10
 
 Parameters:
   - camera_id: Camera identifier (interactive prompt if not provided)
   - robot_ip: Robot IP address (interactive prompt if not provided)
   - output_file: MP4 output file path (default: /tmp/video_capture.mp4)
   - capture_seconds: Stop automatically after this many seconds (default: 5.0)
 */

#include <opencv2/core.hpp>
#include <opencv2/core/utils/logger.hpp>
#include <opencv2/videoio.hpp>

#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace {

constexpr char kRtspUrl[] = "rtsp://{ip}:2554/live_{camera_id}";
constexpr char kDefaultOutputFile[] = "/tmp/video_capture.mp4";
constexpr double kDefaultCaptureSeconds = 5.0;
constexpr int kLogEveryNFrames = 100;
constexpr double kDefaultFallbackFps = 25.0;
constexpr int kOpenTimeoutMs = 5000;
constexpr int kReadTimeoutMs = 5000;
constexpr char kMp4Codec[] = "mp4v";

std::atomic<bool> g_stop_requested{false};

struct Options {
  std::string output_file{kDefaultOutputFile};
  double capture_seconds{kDefaultCaptureSeconds};
  std::string camera_id{""};
  std::string robot_ip{""};
};

std::string format_double(double value) {
  std::ostringstream stream;
  stream << std::fixed << std::setprecision(3) << value;
  return stream.str();
}

void print_usage(const char *program) {
  std::cout
      << "Usage: " << program
      << " [--camera_id CAMERA_ID] [--robot_ip ROBOT_IP]"
      << " [--output_file OUTPUT_FILE] [--capture_seconds CAPTURE_SECONDS]\n\n"
      << "Read decoded frames from the RTSP stream and save MP4.\n\n"
      << "Options:\n"
      << "  -h, --help                  Show this help message and exit.\n"
      << "  --camera_id CAMERA_ID       Camera identifier (e.g., head_monocular_centra).\n"
      << "  --camera CAMERA_ID          Alias of --camera_id.\n"
      << "  --robot_ip ROBOT_IP         Robot IP address (e.g., 10.1.1.100).\n"
      << "  --ip ROBOT_IP               Alias of --robot_ip.\n"
      << "  --output_file OUTPUT_FILE   Output MP4 file path.\n"
      << "  --output OUTPUT_FILE        Alias of --output_file.\n"
      << "  --capture_seconds SEC       Stop automatically after this many\n"
      << "                              seconds. Use <= 0 to run forever.\n"
      << "  --duration SEC              Alias of --capture_seconds.\n\n"
      << "RTSP URL Format: " << kRtspUrl << "\n"
      << "Default MP4 output: " << kDefaultOutputFile << '\n';
}

std::string require_value(int argc, char **argv, int *index,
                          const std::string &option_name) {
  if (*index + 1 >= argc) {
    throw std::invalid_argument("missing value for " + option_name);
  }
  ++(*index);
  return argv[*index];
}

double parse_double(const std::string &text, const std::string &option_name) {
  std::size_t parsed = 0;
  const double value = std::stod(text, &parsed);
  if (parsed != text.size()) {
    throw std::invalid_argument("invalid value for " + option_name + ": " + text);
  }
  return value;
}

std::string prompt_input(const std::string &message, const std::string &default_value) {
  std::cout << "\n" << message << " [" << default_value << "]: ";
  std::string input;
  std::getline(std::cin, input);
  
  if (input.empty()) {
    return default_value;
  }
  
  // Trim whitespace
  size_t start = input.find_first_not_of(" \t\r\n");
  if (start == std::string::npos) {
    return default_value;
  }
  size_t end = input.find_last_not_of(" \t\r\n");
  return input.substr(start, end - start + 1);
}

void print_camera_list() {
  std::cout << std::string(60, '=') << std::endl;
  std::cout << "The list of Q series Camera IDs is as follows:" << std::endl;
  std::cout << std::string(60, '=') << std::endl;
  std::cout << "  head_monocular_centra  - Head monocular central camera" << std::endl;
  std::cout << std::string(60, '=') << std::endl;
  std::cout << "For camera_id corresponding to different robot configurations, please refer to the interface documentation." << std::endl;
  std::cout << std::endl;
}

std::string build_rtsp_url(const std::string &ip, const std::string &camera_id) {
  std::string url = kRtspUrl;
  
  // Replace {ip}
  size_t ip_pos = url.find("{ip}");
  if (ip_pos != std::string::npos) {
    url.replace(ip_pos, 4, ip);
  }
  
  // Replace {camera_id}
  size_t camera_pos = url.find("{camera_id}");
  if (camera_pos != std::string::npos) {
    url.replace(camera_pos, 11, camera_id);
  }
  
  return url;
}

Options parse_args(int argc, char **argv) {
  Options options;

  for (int i = 1; i < argc; ++i) {
    const std::string argument = argv[i];

    if (argument == "-h" || argument == "--help") {
      print_usage(argv[0]);
      std::exit(0);
    }

    if (argument == "--camera_id" || argument == "--camera") {
      options.camera_id = require_value(argc, argv, &i, argument);
      continue;
    }

    if (argument.rfind("--camera_id=", 0) == 0) {
      options.camera_id = argument.substr(std::string("--camera_id=").size());
      continue;
    }

    if (argument.rfind("--camera=", 0) == 0) {
      options.camera_id = argument.substr(std::string("--camera=").size());
      continue;
    }

    if (argument == "--robot_ip" || argument == "--ip") {
      options.robot_ip = require_value(argc, argv, &i, argument);
      continue;
    }

    if (argument.rfind("--robot_ip=", 0) == 0) {
      options.robot_ip = argument.substr(std::string("--robot_ip=").size());
      continue;
    }

    if (argument.rfind("--ip=", 0) == 0) {
      options.robot_ip = argument.substr(std::string("--ip=").size());
      continue;
    }

    if (argument == "--output_file" || argument == "--output") {
      options.output_file = require_value(argc, argv, &i, argument);
      continue;
    }

    if (argument.rfind("--output_file=", 0) == 0) {
      options.output_file = argument.substr(std::string("--output_file=").size());
      continue;
    }

    if (argument.rfind("--output=", 0) == 0) {
      options.output_file = argument.substr(std::string("--output=").size());
      continue;
    }

    if (argument == "--capture_seconds" || argument == "--duration") {
      options.capture_seconds =
          parse_double(require_value(argc, argv, &i, argument), argument);
      continue;
    }

    if (argument.rfind("--capture_seconds=", 0) == 0) {
      options.capture_seconds = parse_double(
          argument.substr(std::string("--capture_seconds=").size()),
          "--capture_seconds");
      continue;
    }

    if (argument.rfind("--duration=", 0) == 0) {
      options.capture_seconds = parse_double(
          argument.substr(std::string("--duration=").size()), "--duration");
      continue;
    }

    throw std::invalid_argument("unknown argument: " + argument);
  }

  // Interactive input for robot_ip if not provided
  if (options.robot_ip.empty()) {
    options.robot_ip = prompt_input("Please enter robot IP address", "");
    if (options.robot_ip.empty()) {
      throw std::invalid_argument("robot_ip must not be empty.");
    }
  }

  // Interactive input for camera_id if not provided
  if (options.camera_id.empty()) {
    print_camera_list();
    options.camera_id = prompt_input("Please enter camera ID", "");
    if (options.camera_id.empty()) {
      throw std::invalid_argument("camera_id must not be empty.");
    }
  }

  if (options.output_file.empty()) {
    throw std::invalid_argument("output_file must not be empty");
  }

  return options;
}

void signal_handler(int) { g_stop_requested.store(true); }

class RtspVideoStreamReader {
public:
  explicit RtspVideoStreamReader(const Options &options)
      : output_file_(options.output_file),
        capture_seconds_(options.capture_seconds),
        camera_id_(options.camera_id),
        robot_ip_(options.robot_ip),
        rtsp_url_(build_rtsp_url(robot_ip_, camera_id_)),
        output_path_(prepare_output_file(output_file_)) {}

  ~RtspVideoStreamReader() {
    release_resources();
    log_summary();
  }

  int run() {
    open_capture();

    while (!g_stop_requested.load()) {
      cv::Mat frame;
      if (!capture_.read(frame) || frame.empty()) {
        throw std::runtime_error("Failed to read frame from the RTSP stream.");
      }

      handle_frame(frame);
      if (should_stop()) {
        std::cout << "Reached capture_seconds=" << format_double(capture_seconds_)
                  << ", shutting down." << std::endl;
        break;
      }
    }

    if (g_stop_requested.load()) {
      std::cout << "Capture interrupted by user." << std::endl;
    }

    return 0;
  }

private:
  static std::filesystem::path prepare_output_file(const std::string &output_file) {
    std::filesystem::path output_path(output_file);
    if (output_path.extension() != ".mp4") {
      throw std::invalid_argument("output_file must use the .mp4 extension.");
    }

    const auto parent = output_path.parent_path();
    if (!parent.empty()) {
      std::error_code ec;
      std::filesystem::create_directories(parent, ec);
      if (ec) {
        throw std::runtime_error("Failed to create directory " +
                                 parent.string() + ": " + ec.message());
      }
    }

    return output_path;
  }

  bool try_open_capture(int api_preference, const std::string &backend_label,
                        bool quiet_opencv_logs) {
    capture_.release();

    const auto previous_log_level = cv::utils::logging::getLogLevel();
    try {
      if (quiet_opencv_logs) {
        cv::utils::logging::setLogLevel(cv::utils::logging::LOG_LEVEL_SILENT);
      }

      const std::vector<int> open_params = {
          cv::CAP_PROP_OPEN_TIMEOUT_MSEC, kOpenTimeoutMs,
          cv::CAP_PROP_READ_TIMEOUT_MSEC, kReadTimeoutMs,
      };
      const bool opened = capture_.open(rtsp_url_, api_preference, open_params);
      cv::utils::logging::setLogLevel(previous_log_level);
      if (!opened || !capture_.isOpened()) {
        capture_.release();
        return false;
      }
    } catch (const cv::Exception &) {
      cv::utils::logging::setLogLevel(previous_log_level);
      capture_.release();
      return false;
    }

    backend_name_ = backend_label;
    try {
      backend_name_ = capture_.getBackendName();
    } catch (const cv::Exception &) {
    }

    std::cout << "Opened RTSP stream: backend=" << backend_name_
              << " open_timeout_ms=" << kOpenTimeoutMs
              << " read_timeout_ms=" << kReadTimeoutMs << std::endl;
    return true;
  }

  void open_capture() {
    if (try_open_capture(cv::CAP_FFMPEG, "FFMPEG", false)) {
      return;
    }

    std::cout << "FFMPEG backend open failed, falling back to the default backend."
              << std::endl;
    if (try_open_capture(cv::CAP_ANY, "DEFAULT", true)) {
      return;
    }

    throw std::runtime_error(std::string("Failed to open RTSP stream: ") +
                             rtsp_url_);
  }

  static bool is_valid_fps(double value) {
    return value > 0.0 && value < 1000.0;
  }

  double resolve_output_fps() const {
    const double stream_fps = capture_.get(cv::CAP_PROP_FPS);
    if (is_valid_fps(stream_fps)) {
      return stream_fps;
    }
    return kDefaultFallbackFps;
  }

  void create_output_writer() {
    output_writer_.open(output_path_.string(),
                        cv::VideoWriter::fourcc(kMp4Codec[0], kMp4Codec[1],
                                                kMp4Codec[2], kMp4Codec[3]),
                        output_fps_, cv::Size(frame_width_, frame_height_));
    if (!output_writer_.isOpened()) {
      output_writer_.release();
      throw std::runtime_error("Failed to create output file: " +
                               output_path_.string());
    }
  }

  void write_frame(const cv::Mat &frame) {
    if (!output_writer_.isOpened()) {
      return;
    }

    try {
      output_writer_.write(frame);
    } catch (const cv::Exception &error) {
      throw std::runtime_error("Failed while writing to " + output_path_.string() +
                               ": " + error.what());
    }

    if (!output_writer_.isOpened()) {
      throw std::runtime_error("Video writer closed unexpectedly during capture.");
    }
  }

  void log_first_frame(const cv::Mat &frame) const {
    std::cout << "First frame received: resolution=" << frame_width_ << 'x'
              << frame_height_ << " channels=" << frame.channels()
              << " payload_bytes=" << frame.total() * frame.elemSize()
              << " stream_fps=" << format_double(stream_fps_)
              << " output_fps=" << format_double(output_fps_)
              << " backend=" << backend_name_ << std::endl;
  }

  void handle_frame(const cv::Mat &frame) {
    const auto frame_bytes =
        static_cast<std::uint64_t>(frame.total() * frame.elemSize());
    ++frame_count_;
    total_frame_bytes_ += frame_bytes;

    if (!first_frame_received_) {
      first_frame_received_ = true;
      first_frame_time_ = std::chrono::steady_clock::now();
      frame_width_ = frame.cols;
      frame_height_ = frame.rows;

      const double stream_fps = capture_.get(cv::CAP_PROP_FPS);
      if (is_valid_fps(stream_fps)) {
        stream_fps_ = stream_fps;
      }
      output_fps_ = resolve_output_fps();
      create_output_writer();

      log_first_frame(frame);
      std::cout << "MP4 output file: " << output_path_.string() << std::endl;
      if (capture_seconds_ > 0) {
        std::cout << "The reader will stop "
                  << format_double(capture_seconds_)
                  << " second(s) after the first frame." << std::endl;
      } else {
        std::cout << "Auto stop disabled. Press Ctrl+C to exit." << std::endl;
      }
    }

    // `frame` is the decoded image read from the RTSP stream.
    // Feed it directly into your vision algorithm here.
    // Example:
    // auto result = your_algorithm(frame);
    write_frame(frame);

    if (kLogEveryNFrames > 0 &&
        frame_count_ % static_cast<std::uint64_t>(kLogEveryNFrames) == 0 &&
        first_frame_received_) {
      const auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                                  std::chrono::steady_clock::now() -
                                  first_frame_time_)
                                  .count();
      std::cout << "Received " << static_cast<unsigned long long>(frame_count_)
                << " frames, total_frame_bytes="
                << static_cast<unsigned long long>(total_frame_bytes_)
                << ", elapsed=" << static_cast<long long>(elapsed_ms) << " ms"
                << std::endl;
    }
  }

  bool should_stop() const {
    if (!first_frame_received_ || capture_seconds_ <= 0) {
      return false;
    }

    const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::steady_clock::now() - first_frame_time_);
    return elapsed.count() >= static_cast<long long>(capture_seconds_ * 1000.0);
  }

  void release_resources() {
    if (capture_.isOpened()) {
      capture_.release();
    }

    if (output_writer_.isOpened()) {
      output_writer_.release();
    }
  }

  void log_summary() {
    if (summary_logged_) {
      return;
    }
    summary_logged_ = true;

    if (!first_frame_received_) {
      std::cerr << "No video frame received before shutdown." << std::endl;
      return;
    }

    const auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                                std::chrono::steady_clock::now() -
                                first_frame_time_)
                                .count();
    std::cout << "Video stream summary: frames="
              << static_cast<unsigned long long>(frame_count_)
              << " total_frame_bytes="
              << static_cast<unsigned long long>(total_frame_bytes_)
              << " elapsed=" << static_cast<long long>(elapsed_ms)
              << " ms resolution=" << frame_width_ << 'x' << frame_height_
              << " stream_fps=" << format_double(stream_fps_)
              << " output_fps=" << format_double(output_fps_)
              << " backend=" << backend_name_ << std::endl;
    std::cout << "Captured MP4 file: " << output_path_.string() << std::endl;
  }

  std::string output_file_;
  double capture_seconds_{kDefaultCaptureSeconds};
  std::string camera_id_;
  std::string robot_ip_;
  std::string rtsp_url_;
  std::filesystem::path output_path_;
  cv::VideoCapture capture_;
  cv::VideoWriter output_writer_;
  bool first_frame_received_{false};
  bool summary_logged_{false};
  std::uint64_t frame_count_{0};
  std::uint64_t total_frame_bytes_{0};
  std::chrono::steady_clock::time_point first_frame_time_{};
  int frame_width_{0};
  int frame_height_{0};
  double stream_fps_{0.0};
  double output_fps_{0.0};
  std::string backend_name_;
};

} // namespace

int main(int argc, char **argv) {
  try {
    std::signal(SIGINT, signal_handler);
    std::signal(SIGTERM, signal_handler);

    const Options options = parse_args(argc, argv);
    RtspVideoStreamReader reader(options);
    return reader.run();
  } catch (const std::exception &error) {
    std::cerr << "Error: " << error.what() << std::endl;
    return 1;
  }
}
视频流获取 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/get_video_stream.py

python
#!/usr/bin/env python3

"""
RTSP Video Stream Reader Example Script

Description:
  This script demonstrates how to read video streams from the robot's cameras via RTSP protocol.
  Supports multiple camera devices and saves video to MP4 format.

Prerequisites:
  - Robot RTSP service must be running
  - Camera hardware must be operational
  - OpenCV must be installed (opencv-python)
  - Network connection to robot must be available

Usage:
  python3 get_video_stream.py --camera <camera_id> --ip <robot_ip> --output <path> --duration <seconds>

Example:
  # Interactive mode (will prompt for camera and IP)
  python3 get_video_stream.py
  
  # Specify camera, IP, and output path
  python3 get_video_stream.py --camera head_monocular_centra --ip 10.1.1.100 --output /tmp/my_video.mp4 --duration 10

Parameters:
  - camera_id: Camera identifier (interactive prompt if not provided)
  - robot_ip: Robot IP address (interactive prompt if not provided)
  - output_file: MP4 output file path (default: /tmp/video_capture.mp4)
  - capture_seconds: Stop automatically after this many seconds (default: 5.0)
"""

from __future__ import annotations

import argparse
from pathlib import Path
import sys
import time
from typing import Any

RTSP_URL = "rtsp://{ip}:2554/live_{camera_id}"
DEFAULT_OUTPUT_FILE = "/tmp/video_capture.mp4"
DEFAULT_CAPTURE_SECONDS = 5.0
DEFAULT_LOG_EVERY_N_FRAMES = 100
DEFAULT_FALLBACK_FPS = 25.0
DEFAULT_OPEN_TIMEOUT_MS = 5000
DEFAULT_READ_TIMEOUT_MS = 5000
MP4_CODEC = "mp4v"


def load_opencv() -> Any:
    try:
        import cv2
    except ImportError as error:
        raise RuntimeError(
            "This example requires `opencv-python`. Install it in the runtime "
            "environment before running the script."
        ) from error

    return cv2


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Read decoded frames from the fixed RTSP stream and save MP4.",
        epilog=f"Default MP4 output: {DEFAULT_OUTPUT_FILE}",
    )
    parser.add_argument(
        "--output_file",
        "--output",
        dest="output_file",
        default=DEFAULT_OUTPUT_FILE,
        help="Output MP4 file path.",
    )
    parser.add_argument(
        "--capture_seconds",
        "--duration",
        dest="capture_seconds",
        type=float,
        default=DEFAULT_CAPTURE_SECONDS,
        help="Stop automatically after this many seconds. Use <= 0 to run forever.",
    )
    parser.add_argument(
        "--camera_id",
        "--camera",
        dest="camera_id",
        default=None,  
        help="Camera identifier (e.g., head_monocular_centra).",
    )
    parser.add_argument(
        "--robot_ip",
        "--ip",
        dest="robot_ip",
        default=None,  
        help="Robot IP address (e.g., 10.1.1.100).",
    )
    
    args = parser.parse_args()
    
    if args.robot_ip is None:
        print()
        print("robot_ip is required. Please provide it via command line argument.")
        args.robot_ip = input("Please enter robot IP address : ").strip()
        if not args.robot_ip:
            sys.exit(1) 
    
    if args.camera_id is None:
        print()
        print("\n" + "="*60)
        print("The list of Q series Camera IDs is as follows:")
        print("="*60)
        print("  head_monocular_centra  - 头部单目中央相机")
        print("="*60)
        print("For camera_id corresponding to different robot configurations, please refer to the interface documentation.")
        print("")
        args.camera_id = input("Please enter camera ID : ").strip()
        if not args.camera_id:
            sys.exit(1)
    
    return args


class RtspVideoStreamReader:
    def __init__(self, args: argparse.Namespace) -> None:
        self.cv2 = load_opencv()
        self.output_file = args.output_file
        self.capture_seconds = args.capture_seconds
        self.camera_id = args.camera_id    
        self.robot_ip = args.robot_ip
        self.url = RTSP_URL.format(
            ip=self.robot_ip,
            camera_id=self.camera_id
        )
        self.log_every_n_frames = DEFAULT_LOG_EVERY_N_FRAMES

        self.capture = None
        self.output_path = self._prepare_output_file(self.output_file)
        self.output_writer = None
        self.first_frame_received = False
        self.summary_logged = False
        self.frame_count = 0
        self.total_frame_bytes = 0
        self.first_frame_monotonic = None
        self.frame_width = 0
        self.frame_height = 0
        self.stream_fps = 0.0
        self.output_fps = 0.0
        self.backend_name = ""

    def _prepare_output_file(self, output_file: str) -> Path:
        output_path = Path(output_file).expanduser()
        if output_path.suffix.lower() != ".mp4":
            raise ValueError("output_file must use the .mp4 extension.")

        output_path.parent.mkdir(parents=True, exist_ok=True)
        return output_path

    def _try_open_capture(
        self,
        api_preference: int,
        backend_label: str,
        quiet_opencv_logs: bool = False,
    ):
        capture = self.cv2.VideoCapture()
        previous_log_level = None

        try:
            if quiet_opencv_logs and hasattr(self.cv2, "getLogLevel") and hasattr(
                self.cv2, "setLogLevel"
            ):
                previous_log_level = self.cv2.getLogLevel()
                self.cv2.setLogLevel(0)

            try:
                opened = capture.open(
                    self.url,
                    api_preference,
                    [
                        self.cv2.CAP_PROP_OPEN_TIMEOUT_MSEC,
                        DEFAULT_OPEN_TIMEOUT_MS,
                        self.cv2.CAP_PROP_READ_TIMEOUT_MSEC,
                        DEFAULT_READ_TIMEOUT_MS,
                    ],
                )
            except TypeError:
                opened = capture.open(self.url, api_preference)
        except self.cv2.error:
            capture.release()
            return None
        finally:
            if previous_log_level is not None:
                self.cv2.setLogLevel(previous_log_level)

        if not opened or not capture.isOpened():
            capture.release()
            return None

        actual_backend = backend_label
        try:
            actual_backend = capture.getBackendName()
        except self.cv2.error:
            pass

        print(
            "Opened RTSP stream: backend=%s open_timeout_ms=%d read_timeout_ms=%d"
            % (
                actual_backend,
                DEFAULT_OPEN_TIMEOUT_MS,
                DEFAULT_READ_TIMEOUT_MS,
            ),
            flush=True,
        )
        self.backend_name = actual_backend
        return capture

    def _open_capture(self) -> None:
        self.capture = self._try_open_capture(self.cv2.CAP_FFMPEG, "FFMPEG")
        if self.capture is not None:
            return

        print(
            "FFMPEG backend open failed, falling back to the default backend.",
            flush=True,
        )
        self.capture = self._try_open_capture(
            self.cv2.CAP_ANY,
            "DEFAULT",
            quiet_opencv_logs=True,
        )
        if self.capture is not None:
            return

        raise RuntimeError(f"Failed to open RTSP stream: {self.url}")

    def _is_valid_fps(self, value: float) -> bool:
        return value > 0.0 and value < 1000.0

    def _resolve_output_fps(self) -> float:
        stream_fps = self.capture.get(self.cv2.CAP_PROP_FPS)
        if self._is_valid_fps(stream_fps):
            return stream_fps

        return DEFAULT_FALLBACK_FPS

    def _create_output_writer(self) -> None:
        self.output_writer = self.cv2.VideoWriter(
            str(self.output_path),
            self.cv2.VideoWriter_fourcc(*MP4_CODEC),
            self.output_fps,
            (self.frame_width, self.frame_height),
        )
        if not self.output_writer.isOpened():
            self.output_writer.release()
            self.output_writer = None
            raise RuntimeError(f"Failed to create output file: {self.output_path}")

    def _write_frame(self, frame) -> None:
        if self.output_writer is None:
            return

        try:
            self.output_writer.write(frame)
        except self.cv2.error as error:
            raise RuntimeError(
                f"Failed while writing to {self.output_path}: {error}"
            ) from error

        if not self.output_writer.isOpened():
            raise RuntimeError("Video writer closed unexpectedly during capture.")

    def _log_first_frame(self, frame) -> None:
        payload_bytes = frame.nbytes
        print(
            "First frame received: resolution=%dx%d channels=%d payload_bytes=%d "
            "stream_fps=%.3f output_fps=%.3f backend=%s"
            % (
                self.frame_width,
                self.frame_height,
                1 if frame.ndim == 2 else frame.shape[2],
                payload_bytes,
                self.stream_fps,
                self.output_fps,
                self.backend_name,
            ),
            flush=True,
        )

    def _handle_frame(self, frame) -> None:
        frame_bytes = frame.nbytes
        self.frame_count += 1
        self.total_frame_bytes += frame_bytes

        if not self.first_frame_received:
            self.first_frame_received = True
            self.first_frame_monotonic = time.monotonic()
            self.frame_height, self.frame_width = frame.shape[:2]

            stream_fps = self.capture.get(self.cv2.CAP_PROP_FPS)
            if self._is_valid_fps(stream_fps):
                self.stream_fps = stream_fps
            self.output_fps = self._resolve_output_fps()
            self._create_output_writer()

            self._log_first_frame(frame)
            print(f"MP4 output file: {self.output_path}", flush=True)
            if self.capture_seconds > 0:
                print(
                    "The reader will stop %.3f second(s) after the first frame."
                    % self.capture_seconds,
                    flush=True,
                )
            else:
                print("Auto stop disabled. Press Ctrl+C to exit.", flush=True)

        # `frame` is the decoded image read from the RTSP stream.
        # Feed it directly into your vision algorithm here.
        # Example:
        # result = your_algorithm(frame)
        self._write_frame(frame)

        if (
            self.log_every_n_frames > 0
            and self.frame_count % self.log_every_n_frames == 0
            and self.first_frame_monotonic is not None
        ):
            elapsed_ms = int((time.monotonic() - self.first_frame_monotonic) * 1000)
            print(
                "Received %d frames, total_frame_bytes=%d, elapsed=%d ms"
                % (
                    self.frame_count,
                    self.total_frame_bytes,
                    elapsed_ms,
                ),
                flush=True,
            )

    def _should_stop(self) -> bool:
        if (
            not self.first_frame_received
            or self.capture_seconds <= 0
            or self.first_frame_monotonic is None
        ):
            return False

        return time.monotonic() - self.first_frame_monotonic >= self.capture_seconds

    def _release_resources(self) -> None:
        if self.capture is not None:
            self.capture.release()
            self.capture = None

        if self.output_writer is not None:
            self.output_writer.release()
            self.output_writer = None

    def log_summary(self) -> None:
        if self.summary_logged:
            return
        self.summary_logged = True

        if not self.first_frame_received or self.first_frame_monotonic is None:
            print("No video frame received before shutdown.", flush=True)
            return

        elapsed_ms = int((time.monotonic() - self.first_frame_monotonic) * 1000)
        print(
            "Video stream summary: frames=%d total_frame_bytes=%d elapsed=%d ms "
            "resolution=%dx%d stream_fps=%.3f output_fps=%.3f backend=%s"
            % (
                self.frame_count,
                self.total_frame_bytes,
                elapsed_ms,
                self.frame_width,
                self.frame_height,
                self.stream_fps,
                self.output_fps,
                self.backend_name,
            ),
            flush=True,
        )
        print(f"Captured MP4 file: {self.output_path}", flush=True)

    def run(self) -> int:
        self._open_capture()
        try:
            while True:
                ok, frame = self.capture.read()
                if not ok or frame is None or frame.size == 0:
                    raise RuntimeError("Failed to read frame from the RTSP stream.")

                self._handle_frame(frame)
                if self._should_stop():
                    print(
                        "Reached capture_seconds=%.3f, shutting down."
                        % self.capture_seconds,
                        flush=True,
                    )
                    break
        except KeyboardInterrupt:
            print("Capture interrupted by user.", flush=True)
        finally:
            self._release_resources()
            self.log_summary()

        return 0


def main() -> int:
    try:
        args = parse_args()
        reader = RtspVideoStreamReader(args)
        return reader.run()
    except Exception as error:  # noqa: BLE001
        print(f"Error: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())

4.3.3 电源管理 ​

代码示例

读取电源状态(Topic: /aima/hal/bms/state) ​

读取电源状态 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp get_bms_state

cpp
/*
 BMS State Monitor Example Script
 
 Description:
   This script demonstrates how to subscribe to the robot's Battery Management System (BMS) state topic.
   It displays real-time battery information including voltage, current, temperature, and remaining capacity.
 
 Prerequisites:
   - Robot BMS service must be running
   - Battery must be connected and operational
 
 Usage:
   ros2 run aimdk_examples_cpp get_bms_state
 
 Example:
   ros2 run aimdk_examples_cpp get_bms_state
 
 Parameters:
   - None
 */

#include "aimdk_msgs/msg/bms.hpp"
#include "rclcpp/rclcpp.hpp"

#include <iomanip>
#include <sstream>

class BmsStateEcho : public rclcpp::Node {
public:
  BmsStateEcho() : Node("get_bms_state") {
    auto qos = rclcpp::SensorDataQoS();
    sub_ = this->create_subscription<aimdk_msgs::msg::Bms>(
        "/aima/hal/bms/state", qos,
        std::bind(&BmsStateEcho::callback, this, std::placeholders::_1));

    RCLCPP_INFO(this->get_logger(), "Subscribing bms topic: %s",
                "/aima/hal/bms/state");
  }

private:
  void callback(const aimdk_msgs::msg::Bms::SharedPtr msg) {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(3);
    
    oss << "BmsState received\n";
    
    oss << "  manufacturer:                 " << msg->manufacturer << "\n"
        << "  serial_number:                " << msg->serial_number << "\n"
        << "  protocol_version:             " << msg->protocol_version << "\n"
        << "  hardware_version:             " << msg->hardware_version << "\n"
        << "  software_version:             " << msg->software_version << "\n";
    
    oss << "  power_request:                " << msg->power_request << "\n";
    
    oss << "  status:                       " << msg->status << "\n"
        << "    bit 0 (充电):               " << ((msg->status & 0x01) ? "是" : "否") << "\n"
        << "    bit 1 (充电过流):           " << ((msg->status & 0x02) ? "是" : "否") << "\n"
        << "    bit 2 (放电):               " << ((msg->status & 0x04) ? "是" : "否") << "\n"
        << "    bit 3 (放电过流):           " << ((msg->status & 0x08) ? "是" : "否") << "\n"
        << "    bit 4 (电池短路):           " << ((msg->status & 0x10) ? "是" : "否") << "\n"
        << "    bit 20 (充满状态):          " << ((msg->status & (1 << 20)) ? "是" : "否") << "\n"
        << "    bit 23 (电池包异常):        " << ((msg->status & (1 << 23)) ? "是" : "否") << "\n";
    
    oss << "  balance_line_resistance:      " << msg->balance_line_resistance << " mOhm\n"
        << "  voltage:                      " << (msg->voltage / 1000.0) << " V\n"
        << "  current:                      " << (msg->current / 1000.0) << " A\n"
        << "  power:                        " << (msg->power / 1000.0) << " W\n"
        << "  temperature:                  " << msg->temperature << " °C\n"
        << "  remaining_capacity:           " << msg->remaining_capacity << " mAh\n"
        << "  remaining_capacity_pct:       " << static_cast<int>(msg->remaining_capacity_percentage) << " %\n"
        << "  cycle_count:                  " << msg->cycle_count << "\n"
        << "  cycle_total_capacity:         " << (msg->cycle_total_capacity / 1000.0) << " Ah\n";

    RCLCPP_INFO(this->get_logger(), "%s", oss.str().c_str());
  }
  rclcpp::Subscription<aimdk_msgs::msg::Bms>::SharedPtr sub_;
};

int main(int argc, char **argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<BmsStateEcho>());
  rclcpp::shutdown();
  return 0;
}
读取电源状态 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/get_bms_state.py

python
#!/usr/bin/env python3

"""
BMS State Monitor Example Script

Description:
  This script demonstrates how to subscribe to the robot's Battery Management System (BMS) state topic.
  It displays real-time battery information including voltage, current, temperature, and remaining capacity.

Prerequisites:
  - Robot BMS service must be running
  - Battery must be connected and operational

Usage:
  python3 get_bms_state.py

Example:
  python3 get_bms_state.py

Parameters:
  - None
"""

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data

from aimdk_msgs.msg import Bms


class BmsStateEcho(Node):
    def __init__(self):
        super().__init__("get_bms_state")

        self.subscription = self.create_subscription(
            Bms,
            "/aima/hal/bms/state",
            self.callback,
            qos_profile_sensor_data,
        )

        self.get_logger().info("Subscribing bms topic: /aima/hal/bms/state")

    @staticmethod
    def _fmt3(value) -> str:
        return f"{float(value):.3f}"

    def callback(self, msg: Bms):
        lines = [
            "BmsState received",
            f"  manufacturer:                 {msg.manufacturer}",
            f"  serial_number:                {msg.serial_number}",
            f"  protocol_version:             {msg.protocol_version}",
            f"  hardware_version:             {msg.hardware_version}",
            f"  software_version:             {msg.software_version}",
            f"  power_request:                {msg.power_request}",
            f"  status:                       {msg.status}",
            f"  balance_line_resistance:      {msg.balance_line_resistance} mOhm",
            f"  voltage:                      {self._fmt3(msg.voltage / 1000.0)} V",
            f"  current:                      {self._fmt3(msg.current / 1000.0)} A",
            f"  power:                        {self._fmt3(msg.power / 1000.0)} W",
            f"  temperature:                  {self._fmt3(msg.temperature)} °C",
            f"  remaining_capacity:           {msg.remaining_capacity} mAh",
            f"  remaining_capacity_percentage:{int(msg.remaining_capacity_percentage)} %",
            f"  cycle_count:                  {msg.cycle_count}",
            f"  cycle_total_capacity:         {self._fmt3(msg.cycle_total_capacity / 1000.0)} Ah",
        ]

        self.get_logger().info("\n".join(lines))


def main(args=None):
    rclpy.init(args=args)
    node = BmsStateEcho()
    try:
        rclpy.spin(node)
        return 0
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

代码示例

外挂算力板供电(Service: SetExt12vPower) ​

外挂算力板供电 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp set_ext12v_power

cpp
/*
 @file set_ext12v_power.cpp
 @brief 外挂算力板供电控制示例脚本

 @description
   通过 SetExt12vPower 服务控制机器人 XT30 接口的外挂算力板供电状态。
   支持开启(enable: true)或关闭(enable: false)外部计算板的电源供应。

   注意:关闭供电前,请确保外挂算力板已正常关机或进入安全状态。

 @prerequisites
   - 外挂算力板供电服务必须正在运行
   - XT30 接口已正确连接外部计算板

 @usage
   ros2 run aimdk_examples_cpp set_ext12v_power [on|off]

 @example
   ros2 run aimdk_examples_cpp set_ext12v_power on    # 开启供电
   ros2 run aimdk_examples_cpp set_ext12v_power off   # 关闭供电

 @parameters
   - enable: 供电使能(true=开启,false=关闭)
 */

#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/srv/set_ext12v_power.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <csignal>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <thread>

using namespace std::chrono_literals;

namespace
{

constexpr auto kServiceWaitInterval = 2s;
constexpr auto kServiceCallTimeout  = 5s;
constexpr int kMaxRetryCount = 3;

}  // namespace

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class SetExt12vPowerClient : public rclcpp::Node
{
 public:
  SetExt12vPowerClient() : Node("set_ext12v_power_client")
  {
    client_ = this->create_client<aimdk_msgs::srv::SetExt12vPower>(
      "/aimdk_5Fmsgs/srv/SetExt12vPower");
    RCLCPP_INFO(this->get_logger(), "SetExt12vPower client node created.");

    while (!client_->wait_for_service(kServiceWaitInterval)) {
      if (!rclcpp::ok())
        return;
      RCLCPP_INFO(this->get_logger(), "Waiting for service...");
    }
    RCLCPP_INFO(this->get_logger(), "Service available, ready to send request.");
  }

  bool send_request(bool enable)
  {
    try {
      RCLCPP_INFO(this->get_logger(),
                  "Sending SetExt12vPower request: enable=%s",
                  enable ? "true" : "false");

      for (int i = 0; i < kMaxRetryCount; ++i) {
        auto request = std::make_shared<aimdk_msgs::srv::SetExt12vPower::Request>();
        request->request.header.stamp = this->now();
        request->enable = enable;

        auto future = client_->async_send_request(request);
        auto retcode = rclcpp::spin_until_future_complete(
          shared_from_this(), future, kServiceCallTimeout);

        if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
          auto response = future.get();
          RCLCPP_INFO(this->get_logger(), "SetExt12vPower response code: %ld",
                      response->header.header.code);
          if (response->header.header.code == 0) {
            RCLCPP_INFO(this->get_logger(),
                        "SetExt12vPower request successful. External compute board power: %s",
                        enable ? "ON" : "OFF");
            return true;
          }
          RCLCPP_WARN(this->get_logger(),
                      "SetExt12vPower failed with code: %ld, retrying (%d/%d)...",
                      response->header.header.code, i + 1, kMaxRetryCount);
        } else {
          RCLCPP_WARN(this->get_logger(),
                      "SetExt12vPower timed out, retrying (%d/%d)...",
                      i + 1, kMaxRetryCount);
        }
        if (i + 1 < kMaxRetryCount) {
          std::this_thread::sleep_for(1s);
        }
      }
      RCLCPP_ERROR(this->get_logger(),
                   "SetExt12vPower failed after %d retries", kMaxRetryCount);
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "SetExt12vPower exception: %s", e.what());
      return false;
    }
  }

 private:
  rclcpp::Client<aimdk_msgs::srv::SetExt12vPower>::SharedPtr client_;
};

int main(int argc, char **argv)
{
  rclcpp::init(argc, argv);
  std::signal(SIGINT, signal_handler);
  std::signal(SIGTERM, signal_handler);

  // 解析命令行参数
  bool enable = true;  // 默认开启
  if (argc > 1) {
    std::string arg = argv[1];
    if (arg == "on" || arg == "true" || arg == "1") {
      enable = true;
    } else if (arg == "off" || arg == "false" || arg == "0") {
      enable = false;
    } else {
      std::cout << "Usage: " << argv[0] << " [on|off]" << std::endl;
      std::cout << "  on   : 开启外挂算力板供电 (default)" << std::endl;
      std::cout << "  off  : 关闭外挂算力板供电" << std::endl;
      rclcpp::shutdown();
      return 1;
    }
  }

  auto node = std::make_shared<SetExt12vPowerClient>();
  bool success = node->send_request(enable);

  rclcpp::shutdown();
  return success ? 0 : 1;
}
外挂算力板供电 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/set_ext12v_power.py

python
#!/usr/bin/env python3

"""
外挂算力板供电控制示例脚本

Description:
  通过 SetExt12vPower 服务控制机器人 XT30 接口的外挂算力板供电状态。
  支持开启(enable: true)或关闭(enable: false)外部计算板的电源供应。

  注意:关闭供电前,请确保外挂算力板已正常关机或进入安全状态。

Prerequisites:
  - 外挂算力板供电服务必须正在运行
  - XT30 接口已正确连接外部计算板

Usage:
  python3 set_ext12v_power.py [on|off]

Example:
  python3 set_ext12v_power.py on    # 开启供电
  python3 set_ext12v_power.py off   # 关闭供电

Parameters:
  - enable: 供电使能(True=开启,False=关闭)
"""

import sys

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_services_default

from aimdk_msgs.srv import SetExt12vPower


class SetExt12vPowerClient(Node):
    def __init__(self):
        super().__init__("set_ext12v_power_client")

        self.client = self.create_client(
            SetExt12vPower,
            "/aimdk_5Fmsgs/srv/SetExt12vPower",
            qos_profile=qos_profile_services_default,
        )

        self.get_logger().info("SetExt12vPower client node created.")

        while not self.client.wait_for_service(timeout_sec=2.0):
            self.get_logger().info("Waiting for service...")

        self.get_logger().info("Service available, ready to send request.")

    def send_request(self, enable: bool = True) -> bool:
        request = SetExt12vPower.Request()
        request.enable = enable

        self.get_logger().info(
            f"Sending SetExt12vPower request: enable={enable}"
        )

        max_retry_count = 3
        for i in range(max_retry_count):
            future = self.client.call_async(request)
            rclpy.spin_until_future_complete(self, future, timeout_sec=5.0)

            if future.done():
                response = future.result()
                if response is not None:
                    self.get_logger().info(
                        f"SetExt12vPower response code: {response.header.header.code}"
                    )
                    if response.header.header.code == 0:
                        state_str = "ON" if enable else "OFF"
                        self.get_logger().info(
                            f"SetExt12vPower request successful. "
                            f"External compute board power: {state_str}"
                        )
                        return True
                    else:
                        self.get_logger().warn(
                            f"SetExt12vPower failed with code: {response.header.header.code}, "
                            f"retrying ({i + 1}/{max_retry_count})..."
                        )
                else:
                    self.get_logger().warn(
                        f"SetExt12vPower returned None, retrying ({i + 1}/{max_retry_count})..."
                    )
            else:
                self.get_logger().warn(
                    f"SetExt12vPower timed out, retrying ({i + 1}/{max_retry_count})..."
                )

        self.get_logger().error(
            f"SetExt12vPower failed after {max_retry_count} retries"
        )
        return False


def main(args=None):
    rclpy.init(args=args)

    # 解析命令行参数
    enable = True  # 默认开启
    if sys.argv[1:]:
        arg = sys.argv[1].lower()
        if arg in ("on", "true", "1"):
            enable = True
        elif arg in ("off", "false", "0"):
            enable = False
        else:
            print(f"Usage: {sys.argv[0]} [on|off]")
            print(f"  on   : 开启外挂算力板供电 (default)")
            print(f"  off  : 关闭外挂算力板供电")
            return 1

    node = SetExt12vPowerClient()

    try:
        success = node.send_request(enable)
        return 0 if success else 1
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == "__main__":
    raise SystemExit(main())

4.3.4 灯语控制 ​

灯语控制(Service: LedStripCommand) ​

灯语控制 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp play_lights

cpp
/*
 LED Light Control Example Script
 
 Description:
   This script demonstrates how to control the robot's LED strip lights using the LedStripCommand service.
   Supports custom color settings and animation modes.
 
 Prerequisites:
   - Robot LED service must be running
   - LED hardware must be operational
 
 Usage:
   ros2 run aimdk_examples_cpp play_lights
 
 Example:
   ros2 run aimdk_examples_cpp play_lights
 
 Parameters:
   - None
 */

#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/srv/led_strip_command.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <cstdint>
#include <exception>
#include <iostream>
#include <memory>
#include <signal.h>
#include <thread>
#include <unordered_map>

constexpr int kMaxRetryCount = 3;
constexpr std::chrono::milliseconds kServiceCallTimeout(2000);

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal) {
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class PlayLightsClient : public rclcpp::Node {
public:
  PlayLightsClient() : Node("play_lights_client") {
    client_ = this->create_client<aimdk_msgs::srv::LedStripCommand>(
        "/aimdk_5Fmsgs/srv/LedStripCommand");
    RCLCPP_INFO(this->get_logger(), "LedStripCommand client node created.");

    while (!client_->wait_for_service(std::chrono::seconds(2))) {
      if (!rclcpp::ok()) {
        return;
      }
      RCLCPP_INFO(this->get_logger(), "Service unavailable, waiting...");
    }
    RCLCPP_INFO(this->get_logger(),
                "Service available, ready to send request.");
  }

  bool send_request(uint8_t led_strip_mode, uint8_t r, uint8_t g, uint8_t b,
                    uint16_t period) {
    try {
      auto request =
          std::make_shared<aimdk_msgs::srv::LedStripCommand::Request>();
      request->request = aimdk_msgs::msg::CommonRequest();
      request->led_strip_mode = led_strip_mode;
      request->r = r;
      request->g = g;
      request->b = b;
      request->period = period;

      RCLCPP_INFO(this->get_logger(),
                  "Sending LedStripCommand request: led_strip_mode=%u, "
                  "r=%u, g=%u, b=%u, period=%u",
                  static_cast<unsigned int>(request->led_strip_mode),
                  static_cast<unsigned int>(request->r),
                  static_cast<unsigned int>(request->g),
                  static_cast<unsigned int>(request->b),
                  static_cast<unsigned int>(request->period));

      // Retry mechanism: up to 3 attempts
      request->request.header.stamp = this->now();
      auto future = client_->async_send_request(request);
      bool completed = false;
      
      for (int i = 0; i < kMaxRetryCount; ++i) {
        auto retcode = rclcpp::spin_until_future_complete(
            shared_from_this(), future, kServiceCallTimeout);
        
        if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
          completed = true;
          break;
        }

        RCLCPP_INFO(this->get_logger(),
                    "LedStripCommand attempt %d/%d timed out, retrying...",
                    i + 1, kMaxRetryCount);
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        
        // Re-send request for retry
        future = client_->async_send_request(request);
      }

      if (!completed) {
        RCLCPP_ERROR(this->get_logger(),
                     "LedStripCommand service timeout.");
        return false;
      }

      auto response = future.get();
      if (!response) {
        RCLCPP_ERROR(this->get_logger(),
                     "LedStripCommand service call failed.");
        return false;
      }
      
      const auto code = response->header.header.code;  
      const auto status_value = response->header.status.value; 
      RCLCPP_INFO(this->get_logger(),
                  "Response: code=%ld, status_value=%d", code,
                  static_cast<int>(status_value));

      if (code == 0 && status_value == 1) {  // SUCCESS = 1
        RCLCPP_INFO(this->get_logger(),
                    "LedStripCommand request accepted.");
        return true;
      }

      RCLCPP_ERROR(this->get_logger(),
                   "LedStripCommand failed. code=%ld status=%d msg=%s",
                   code, static_cast<int>(status_value),
                   response->header.message.c_str());
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "Exception occurred: %s", e.what());
      return false;
    }
  }

private:
  rclcpp::Client<aimdk_msgs::srv::LedStripCommand>::SharedPtr client_;
};

int main(int argc, char *argv[]) {
  try {
    rclcpp::init(argc, argv);
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    uint8_t led_strip_mode =
        aimdk_msgs::srv::LedStripCommand::Request::LED_WHITE_ON;
    uint8_t r = 0;
    uint8_t g = 0;
    uint8_t b = 0;
    uint16_t period = 0;

    int mode_input = 0;
    std::cout << "Enter led_strip_mode (default "
              << static_cast<int>(led_strip_mode) << "): ";
    std::cin >> mode_input;
    led_strip_mode = static_cast<uint8_t>(mode_input);

     if (led_strip_mode == aimdk_msgs::srv::LedStripCommand::Request::LED_CUSTOM_BREATH ||
         led_strip_mode == aimdk_msgs::srv::LedStripCommand::Request::LED_CUSTOM_BLINK) {
      int channel_input = 0;
      int period_input = 1000;

      std::cout << "Enter r (default 0): ";
      std::cin >> channel_input;
      r = static_cast<uint8_t>(channel_input);

      std::cout << "Enter g (default 0): ";
      std::cin >> channel_input;
      g = static_cast<uint8_t>(channel_input);

      std::cout << "Enter b (default 255): ";
      channel_input = 255;
      std::cin >> channel_input;
      b = static_cast<uint8_t>(channel_input);

      std::cout << "Enter period(ms, default 1000): ";
      std::cin >> period_input;
      period = static_cast<uint16_t>(period_input);
    }

    g_node = std::make_shared<PlayLightsClient>();
    auto client = std::dynamic_pointer_cast<PlayLightsClient>(g_node);
    bool ok = false;
    if (client) {
      ok = client->send_request(led_strip_mode, r, g, b, period);
    }

    g_node.reset();
    rclcpp::shutdown();
    return ok ? 0 : 1;
  } catch (const std::exception &e) {
    RCLCPP_ERROR(rclcpp::get_logger("main"),
                 "Program exited with exception: %s", e.what());
    return 1;
  }
}
灯语控制 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 primebot_sdk/examples/python/play_lights.py

python
#!/usr/bin/env python3

"""
LED Light Control Example Script

Description:
  This script demonstrates how to control the robot's LED strip lights using the LedStripCommand service.
  Supports custom color settings and animation modes.

Prerequisites:
  - Robot LED service must be running
  - LED hardware must be operational

Usage:
  python3 play_lights.py

Example:
  python3 play_lights.py

Parameters:
  - None 
"""

import rclpy
import time
import rclpy.logging
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest
from aimdk_msgs.srv import LedStripCommand


class PlayLightsClient(Node):
    def __init__(self):
        super().__init__("play_lights_client")
        self.client = self.create_client(
            LedStripCommand, "/aimdk_5Fmsgs/srv/LedStripCommand"
        )
        self.get_logger().info("LedStripCommand client node created.")

        while not self.client.wait_for_service(timeout_sec=2.0):
            self.get_logger().info("Service unavailable, waiting...")

        self.get_logger().info("Service available, ready to send request.")

    def send_request(
        self,
        led_strip_mode: int,
        r: int,
        g: int,
        b: int,
        period: int,
    ) -> bool:
        try:
            request = LedStripCommand.Request()
            request.request = CommonRequest()
            request.request.header.stamp = self.get_clock().now().to_msg()
            request.led_strip_mode = led_strip_mode
            request.r = r
            request.g = g
            request.b = b
            request.period = period

            self.get_logger().info(
                "Sending LedStripCommand request: "
                f"led_strip_mode={request.led_strip_mode}, "
                f"r={request.r}, g={request.g}, b={request.b}, "
                f"period={request.period}"
            )

            for i in range(3):
                future = self.client.call_async(request)
                rclpy.spin_until_future_complete(self, future, timeout_sec=2.0)

                if future.done():
                    break

                self.get_logger().info(f'trying ... [{i}]')
                time.sleep(0.2)

            if not future.done():
                self.get_logger().error("LedStripCommand service timeout.")
                return False

            response = future.result()
            if response is None:
                self.get_logger().error("LedStripCommand service call failed.")
                return False

            code = response.header.header.code  
            status_value = response.header.status.value 
            # 打印响应信息
            self.get_logger().info(
                f"Response: code={code}, status_value={status_value}"
            )

            if code == 0 and status_value == 1:  # 判断是否成功
                self.get_logger().info("LedStripCommand request accepted.")
                return True

            self.get_logger().error(
                f"LedStripCommand failed. "
                f"code={code} status={status_value} "
                f"msg={response.header.message}"
            )
            return False
        except Exception as error:  # noqa: BLE001
            self.get_logger().error(f"Exception occurred: {error}")
            return False


def read_int(prompt: str, default: int) -> int:
    text = input(prompt).strip()
    if text == "":
        return default
    return int(text)


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        led_strip_mode = read_int(
            f"Enter led_strip_mode (default {LedStripCommand.Request.LED_WHITE_ON}): ",
            LedStripCommand.Request.LED_WHITE_ON,
        )
        r = 0
        g = 0
        b = 0
        period = 0

        if led_strip_mode in (LedStripCommand.Request.LED_CUSTOM_BREATH, 
                              LedStripCommand.Request.LED_CUSTOM_BLINK):
            r = read_int("Enter r (default 0): ", 0)
            g = read_int("Enter g (default 0): ", 0)
            b = read_int("Enter b (default 255): ", 255)
            period = read_int("Enter period(ms, default 1000): ", 1000)

        node = PlayLightsClient()
        ok = node.send_request(led_strip_mode, r, g, b, period)
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()
        return 0 if ok else 1
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("main").error(
            f"Program exited with exception: {error}"
        )
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()
        return 1


if __name__ == "__main__":
    raise SystemExit(main())

4.4 系统控制模块 ​

4.4.1 系统状态迁移 ​

系统重启与关机(Service: MigrateSystemState) ​

系统重启与关机 Cpp示例 ​

执行前置:需先满足 Cpp代码运行前置条件

运行命令:ros2 run aimdk_examples_cpp migrate_system_state

cpp
/*
 @file migrate_system_state.cpp
 @brief 系统重启、关机示例脚本

 @description
   通过 MigrateSystemState 服务请求机器人执行系统状态迁移(如重启、关机)。
   该接口在系统管理层实现,通过状态机机制完成安全的状态切换。

   警告:调用此接口后,系统将进入安全的重启、关机流程,依次停止各子系统服务后执行重启、关机。
   请确保在调用前已保存重要数据。

   ⚠ 摔机风险警告:本接口不会自动切换机器人动作状态。执行前务必先通过上层
   业务逻辑将机器人切换至趴下(Prone)或零力矩等安全姿态,否则重启、关机过程中
   关节失去力矩支撑,机器人可能直接摔倒造成硬件损坏!

 @prerequisites
   - 系统状态管理服务必须正在运行
   - 机器人在安全状态下可执行重启、关机
   - ⚠ 机器人已切换至趴下或零力矩等安全姿态(本接口不会自动切换动作)

 @usage
   ros2 run aimdk_examples_cpp migrate_system_state

 @example
   ros2 run aimdk_examples_cpp migrate_system_state

 @parameters
   - state: 目标系统状态(如 "Reboot"/"Shutdown")
 */

#include "aimdk_msgs/msg/common_request.hpp"
#include "aimdk_msgs/msg/common_state.hpp"
#include "aimdk_msgs/srv/migrate_system_state.hpp"
#include "rclcpp/rclcpp.hpp"

#include <chrono>
#include <csignal>
#include <memory>
#include <string>
#include <thread>
#include <iostream>

using namespace std::chrono_literals;

namespace
{

constexpr auto kServiceWaitInterval = 2s;
constexpr auto kServiceCallTimeout  = 5s;
constexpr int kMaxRetryCount = 3;

}  // namespace

std::shared_ptr<rclcpp::Node> g_node = nullptr;

void signal_handler(int signal)
{
  if (g_node) {
    RCLCPP_INFO(g_node->get_logger(), "Received signal %d, shutting down...",
                signal);
    g_node.reset();
  }
  rclcpp::shutdown();
  exit(signal);
}

class MigrateSystemStateClient : public rclcpp::Node
{
 public:
  MigrateSystemStateClient() : Node("migrate_system_state_client")
  {
    client_ = this->create_client<aimdk_msgs::srv::MigrateSystemState>(
      "/aimdk_5Fmsgs/srv/MigrateSystemState");
    RCLCPP_INFO(this->get_logger(), "MigrateSystemState client node created.");

    while (!client_->wait_for_service(kServiceWaitInterval)) {
      if (!rclcpp::ok())
        return;
      RCLCPP_INFO(this->get_logger(), "Waiting for service...");
    }
    RCLCPP_INFO(this->get_logger(), "Service available, ready to send request.");
  }

  bool send_request(const std::string &state = "Reboot")
  {
    try {
      RCLCPP_INFO(this->get_logger(),
                  "Sending MigrateSystemState request: state=%s", state.c_str());

      for (int i = 0; i < kMaxRetryCount; ++i) {
        auto request = std::make_shared<aimdk_msgs::srv::MigrateSystemState::Request>();
        request->header.header.stamp = this->now();
        request->state = state;

        auto future = client_->async_send_request(request);
        auto retcode = rclcpp::spin_until_future_complete(
          shared_from_this(), future, kServiceCallTimeout);

        if (retcode == rclcpp::FutureReturnCode::SUCCESS) {
          auto response = future.get();
          RCLCPP_INFO(this->get_logger(), "MigrateSystemState response code: %ld",
                      response->header.header.code);
          if (response->header.header.code == 0) {
            RCLCPP_INFO(this->get_logger(),
                        "MigrateSystemState request successful. Robot is transitioning to state: %s...",
                        state.c_str());
            return true;
          }
          RCLCPP_WARN(this->get_logger(),
                      "MigrateSystemState failed with code: %ld, retrying (%d/%d)...",
                      response->header.header.code, i + 1, kMaxRetryCount);
        } else {
          RCLCPP_WARN(this->get_logger(),
                      "MigrateSystemState timed out, retrying (%d/%d)...",
                      i + 1, kMaxRetryCount);
        }
        if (i + 1 < kMaxRetryCount) {
          std::this_thread::sleep_for(1s);
        }
      }
      RCLCPP_ERROR(this->get_logger(),
                   "MigrateSystemState failed after %d retries", kMaxRetryCount);
      return false;
    } catch (const std::exception &e) {
      RCLCPP_ERROR(this->get_logger(), "MigrateSystemState exception: %s", e.what());
      return false;
    }
  }

 private:
  rclcpp::Client<aimdk_msgs::srv::MigrateSystemState>::SharedPtr client_;
};

int main(int argc, char **argv)
{
  rclcpp::init(argc, argv);
  std::signal(SIGINT, signal_handler);
  std::signal(SIGTERM, signal_handler);

  int choice = 0;
  std::cout << "Select system operation:" << std::endl;
  std::cout << "  1. Reboot (重启)" << std::endl;
  std::cout << "  2. Shutdown (关机)" << std::endl;
  std::cout << "Enter choice (default 1): ";
  std::cin >> choice;

  std::string state;
  if (choice == 2) {
    state = "Shutdown";
  } else {
    state = "Reboot";
  }

  auto node = std::make_shared<MigrateSystemStateClient>();
  bool success = node->send_request(state);

  rclcpp::shutdown();
  return success ? 0 : 1;
}
系统重启与关机 Python示例 ​

执行前置:需先满足 Python代码运行前置条件

运行命令:python3 examples/python/migrate_system_state.py

python
#!/usr/bin/env python3

"""
系统重启、关机示例脚本

Description:
  通过 MigrateSystemState 服务请求机器人执行系统状态迁移(如重启、关机)。
  该接口在系统管理层实现,通过状态机机制完成安全的状态切换。

  警告:调用此接口后,系统将进入安全的重启、关机流程,依次停止各子系统服务后执行重启、关机。
  请确保在调用前已保存重要数据。

  ⚠ 摔机风险警告:本接口不会自动切换机器人动作状态。执行前务必先通过上层
  业务逻辑将机器人切换至趴下(Prone)或零力矩等安全姿态,否则重启、关机过程中
  关节失去力矩支撑,机器人可能直接摔倒造成硬件损坏!

Prerequisites:
  - 系统状态管理服务必须正在运行
  - 机器人在安全状态下可执行重启、关机
  - ⚠ 机器人已切换至趴下或零力矩等安全姿态(本接口不会自动切换动作)

Usage:
  python3 migrate_system_state.py

Example:
  python3 migrate_system_state.py

Parameters:
  - state: 目标系统状态(如 "Reboot"/"Shutdown")
"""

import time

import rclpy
import rclpy.logging
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.node import Node

from aimdk_msgs.msg import CommonRequest
from aimdk_msgs.srv import MigrateSystemState

SERVICE_WAIT_SEC = 2.0
SERVICE_CALL_TIMEOUT_SEC = 5.0
MAX_RETRY_COUNT = 3

SERVICE_NAME = "/aimdk_5Fmsgs/srv/MigrateSystemState"


class MigrateSystemStateClient(Node):
    """MigrateSystemState service client node."""

    def __init__(self):
        super().__init__("migrate_system_state_client")

        self.cb_group = ReentrantCallbackGroup()

        self.client = self.create_client(
            MigrateSystemState,
            SERVICE_NAME,
            callback_group=self.cb_group,
        )

        self.get_logger().info("MigrateSystemState client node created.")

        while not self.client.wait_for_service(timeout_sec=SERVICE_WAIT_SEC):
            if not rclpy.ok():
                return
            self.get_logger().info("Waiting for service...")
        self.get_logger().info("Service available, ready to send request.")

    def send_request(self, state: str = "Reboot") -> bool:
        """
        Send MigrateSystemState request.

        Args:
            state: Target system state (e.g., "Reboot").

        Returns:
            True if request was successful, False otherwise.
        """
        request = MigrateSystemState.Request()
        request.header = CommonRequest()
        request.header.header.stamp = self.get_clock().now().to_msg()
        request.state = state

        self.get_logger().info(
            f"Sending MigrateSystemState request: state={state}"
        )

        for attempt in range(1, MAX_RETRY_COUNT + 1):
            future = self.client.call_async(request)
            rclpy.spin_until_future_complete(
                self, future, timeout_sec=SERVICE_CALL_TIMEOUT_SEC
            )

            if future.done():
                try:
                    response = future.result()
                except Exception as error:  # noqa: BLE001
                    self.get_logger().error(f"MigrateSystemState failed: {error}")
                    return False

                if response is None:
                    self.get_logger().error("MigrateSystemState returned no response.")
                    return False

                code = response.header.header.code
                if code == 0:
                    self.get_logger().info(
                        f"MigrateSystemState request successful. "
                        f"Robot is transitioning to state: {state}..."
                    )
                    return True

                self.get_logger().error(
                    f"MigrateSystemState failed with code: {code}, "
                    f"retrying ({attempt}/{MAX_RETRY_COUNT})..."
                )
            else:
                self.get_logger().warning(
                    f"MigrateSystemState timed out, retrying ({attempt}/{MAX_RETRY_COUNT})..."
                )

            if attempt < MAX_RETRY_COUNT:
                time.sleep(1.0)

        self.get_logger().error(
            f"MigrateSystemState failed after {MAX_RETRY_COUNT} retries"
        )
        return False


def main(args=None):
    rclpy.init(args=args)
    node = None
    try:
        print("Select system operation:")
        print("  1. Reboot (重启)")
        print("  2. Shutdown (关机)")
        choice = input("Enter choice (default 1): ").strip()

        if choice == "2":
            state = "Shutdown"
        else:
            state = "Reboot"

        node = MigrateSystemStateClient()
        ok = node.send_request(state)
        return 0 if ok else 1
    except Exception as error:  # noqa: BLE001
        rclpy.logging.get_logger("main").error(
            f"Program exited with exception: {error}"
        )
        return 1
    finally:
        if node is not None:
            node.destroy_node()
        if rclpy.ok():
            rclpy.shutdown()
if __name__ == "__main__":
    raise SystemExit(main())