import rospy
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from voice_recognition import VoiceCoordinator
from motion_executor import MotionExecutor
import traceback
import json
from queue import Empty
def load_action_config():
"""加载并返回动作配置文件内容"""
config_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"key_words.json"
)
try:
with open(config_path, 'r', encoding='utf-8') as f:
rospy.loginfo(f"成功加载动作配置文件: {config_path}")
return json.load(f)
except Exception as e:
rospy.logerr(f"加载动作配置文件 {config_path} 失败: {e}")
return {}
ACTION_CONFIG = load_action_config()
def execute_action(motion_executor, action_key):
"""
根据 action_key 从配置文件中查找动作类型和数据,并执行。
"""
if not ACTION_CONFIG:
rospy.logerr("动作配置文件为空或加载失败,无法执行任何动作。")
return
action_details = ACTION_CONFIG.get(action_key)
if not action_details:
rospy.logwarn(f"警告: 在动作配置文件中找不到 '{action_key}' 对应的配置!")
return
action_type = action_details.get("type")
action_data = action_details.get("data")
if action_data is None:
rospy.logwarn(f"警告: 动作 '{action_key}' 的 'data' 字段为空!")
return
try:
rospy.loginfo(f">>> 执行动作: {action_key} (类型: {action_type})")
if action_type == "SINGLE_STEP":
slot = json.dumps(action_data, ensure_ascii=False)
motion_executor.trigger_move_callback(slot)
elif action_type == "ARM_ACTION":
motion_executor.trigger_action_callback(action_data)
else:
rospy.logwarn(f"警告: 未知的动作类型 '{action_type}',无法执行 '{action_key}'。")
except Exception as e:
rospy.logerr(f"执行动作 {action_key} 时发生错误: {traceback.format_exc()}")
def main():
rospy.init_node('voice_control_node', anonymous=False)
def update_action_config_callback():
"""在 VoiceCoordinator 重载配置后调用,更新 main.py 的 ACTION_CONFIG"""
global ACTION_CONFIG
ACTION_CONFIG = load_action_config()
rospy.loginfo("ACTION_CONFIG 已成功更新")
try:
voice_coordinator = VoiceCoordinator(subscribe_topic="/micphone_data",
on_reload_callback=update_action_config_callback)
motion_executor = MotionExecutor()
except Exception as e:
rospy.logerr(f"初始化失败: {e}")
return
rospy.loginfo("语音控制系统启动,等待语音输入... (按 Ctrl+C 退出)")
rospy.loginfo("使用 '/voice_control/reload_keywords' 服务可以重载关键词配置")
voice_coordinator.reset_micphone_data()
while not rospy.is_shutdown():
try:
action_key = voice_coordinator.result_queue.get(timeout=0.1)
if action_key:
rospy.loginfo(f"接收到语音命令,匹配到动作: {action_key}")
execute_action(motion_executor,action_key)
except Empty:
continue
except rospy.ROSInterruptException:
rospy.loginfo("收到ctrl+c命令,程序已正常停止")
break
except Exception as e:
rospy.logerr(f"主循环发生未知错误,程序即将停止: {e}")
break
rospy.loginfo("程序已正常停止")
if __name__ == "__main__":
main()