admin管理员组

文章数量:1667032

使用ChatGPT控制ROS TurtleBot:基于Json格式的GPT内容解析机器人控制方案🤖🐢

在开始之前,请确保你已经阅读了本喵之前的基础文章的内容【系列教程】ChatGPT+ROS:打造智能无人机自主飞行的下一代解决方案✈️【一】将chatgpt集成到ROS中,本文同样也是创新满满哦~你将了解到有关ChatGPT生成动作序列的相关内容

目录

  • 🔧 环境准备
    • 安装ROS
    • 配置TurtleBot环境
  • 🤖 集成ChatGPT
  • 📡 构建控制命令接口
    • 定义接受指令的ROS节点
    • 构建ChatGPT到ROS的命令转换逻辑
  • 🚀 实现TurtleBot的基础移动控制
    • 简单实例,直线移动
    • 简单实例,转弯控制
  • 🚀 DEMO实战演示
    • GPT环境搭建
    • 演示脚本

使用ChatGPT控制ROS TurtleBot:深入指南🤖🐢

🔧 环境准备

安装ROS

在本喵的教程:
【系列教程】ChatGPT+ROS:打造智能无人机自主飞行的下一代解决方案✈️【一】将chatgpt集成到ROS中
中有详细介绍哦

启动turtlebot

终端中启用

roscore

新建终端,启用

rosrun turtlesim turtlesim_node

小海龟界面就启动啦~

🤖 集成ChatGPT

想要集成ChatGPT在ROS中,详情请见以下内容~:
【系列教程】ChatGPT+ROS:打造智能无人机自主飞行的下一代解决方案✈️【一】将chatgpt集成到ROS中

📡 构建控制命令接口

在开始构建以前,我们必须了解一个概念,那就是json格式,json格式对于我们用chatgpt给出控制代码及指令非常有用,比如一个基础的控制端:
在设计机器人控制系统时,我们希望确保命令的格式既灵活又标准化。使用JSON格式,我们可以轻松定义复杂的命令结构,比如:

{
  "action": "move",
  "parameters": {
    "speed": 0.5,
    "distance": 2,
    "angular_speed": 0.0
  }
}

control.py中,我们通过解析JSON命令(ChatGPT给出的),并转换为TurtleBot的移动和旋转操作。这里,逻辑应该处理不同类型的动作,如“前进”、“后退”、“左转”和“右转”。

🚀 控制TurtleBot

实例:使用动作序列进行探索

假设ChatGPT生成了以下动作序列来探索环境:

[
  {"action": "move", "parameters": {"speed": 0.5, "distance": 2, "angular_speed": 0.0}},
  {"action": "rotate", "parameters": {"angular_speed": 1.0, "angle": 90}},
  {"action": "move", "parameters": {"speed": 0.5, "distance": 1, "angular_speed": 0.0}}
  {"action": "vision","parameters":{"speed": 0.5}} //假设存在类似于Yolov8视觉跟踪等效果
]

我们的control.py脚本会逐一执行这些动作,实现一系列探索动作。

实现TurtleBot的基础移动控制

直线移动

终端中输入

rostopic pub /turtle1/cmd_vel geometry_msgs/Twist "linear:
  x: 0.5
  y: 0.0
  z: 0.0
angular:
  x: 0.0
  y: 0.0
  z: 0.0" -r 10     

-r代表发送频率 10hz
运行效果如下~:

转弯控制

终端中输入

rostopic pub /turtle1/cmd_vel geometry_msgs/Twist "linear:
  x: 0.0
  y: 0.0
  z: 0.0
angular:
  x: 0.0
  y: 0.0
  z: 1.0" -r 10

运行效果如下~:

GPT环境搭建

  • mianchat.py【设置了代理的代码bash_url=https://oneapi.xty.app/v1】
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import httpx
from openai import OpenAI

# 初始化OpenAI客户端
client = OpenAI(
   base_url="https://oneapi.xty.app/v1",
   api_key="API_key",  # 请替换为您的API密钥
   http_client=httpx.Client(
       base_url="https://oneapi.xty.app/v1",  #
       follow_redirects=True,
   ),
)

def user_message_callback(data):
   rospy.loginfo("Received from user: %s", data.data)

   # 向GPT发送请求,并获取回复
   chat_completion = client.chat.completions.create(
       model="gpt-3.5-turbo",
       messages=[
           {
 "role": "system", 
 "content": "You are a helpful ROS assistant specifically for controlling a TurtleBot. Please provide responses in the following JSON format for a combination of moving forward and then rotating in place: {\"action\": \"move\",\"speed\": {\"linear\": {\"x\": [linear speed value for moving forward or backward],\"y\": 0},\"angular\": {\"x\": 0,\"y\": 0}},\"distance\": [distance value],\"angular_speed\": {\"linear\": {\"x\": [value]},\"angular\": {\"z\": [angular speed value for rotation]}}}. The 'speed' value controls the linear speed for moving forward or backward (use positive values for forward movement and negative values for backward movement). The 'distance' specifies how far to move before rotating. The 'angular_speed' controls the angular velocity for rotating in place after moving (use positive values for left turns and negative values for right turns)."
}
,
           {"role": "user", "content": data.data}  # 使用接收到的用户消息
       ]
   )

   # 获取GPT的回复
   gpt_reply = chat_completion.choices[0].message.content
   rospy.loginfo("GPT Reply: %s", gpt_reply)

   # 发布GPT的回复
   gpt_reply_pub.publish(gpt_reply)

if __name__ == '__main__':
   try:
       rospy.init_node('chatgpt_ros_node', anonymous=True)

       # 订阅用户消息
       rospy.Subscriber("user_to_gpt", String, user_message_callback)

       # 创建发布者,用于发布GPT的回复
       gpt_reply_pub = rospy.Publisher("gpt_reply_to_user", String, queue_size=10)

       rospy.spin()
   except rospy.ROSInterruptException:
       pass

其中关键内容,特化GPT的基本属性:
messages=[ { "role": "system", "content": "You are a helpful ROS assistant specifically for controlling a TurtleBot. Please provide responses in the following JSON format for a combination of moving forward and then rotating in place: {\"action\": \"move\",\"speed\": {\"linear\": {\"x\": [linear speed value for moving forward or backward],\"y\": 0},\"angular\": {\"x\": 0,\"y\": 0}},\"distance\": [distance value],\"angular_speed\": {\"linear\": {\"x\": [value]},\"angular\": {\"z\": [angular speed value for rotation]}}}. The 'speed' value controls the linear speed for moving forward or backward (use positive values for forward movement and negative values for backward movement). The 'distance' specifies how far to move before rotating. The 'angular_speed' controls the angular velocity for rotating in place after moving (use positive values for left turns and negative values for right turns)." }

  • control.py【通过ChatGPT控制小乌龟的代码】
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist

pub = None

def callback(data):
    rospy.loginfo("Received: %s", data.data)
    
    try:
        command = json.loads(data.data)

        # 处理命令
        handle_action(command)
    except json.JSONDecodeError as e:
        rospy.logerr("Error decoding JSON: %s", e)
    except KeyError as e:
        rospy.logerr("Missing key in JSON data: %s", e)

def handle_action(command):
    global pub
    twist = Twist()
    
    if command["action"] == "move":
        rospy.loginfo("Moving turtle")
        # 使用新的JSON格式设置线速度和角速度
        twist.linear.x = command["speed"]["linear"]["x"]
        twist.linear.y = 0
        # 默认情况下, y速度应该为0, 因此这不需要改变
        
        # 发布 Twist 消息以开始移动
        pub.publish(twist)
        
        # 根据速度和距离计算需要移动的时间
        time_to_move = command["distance"] / command["speed"]["linear"]["x"]
        
        # 等待直到移动完成
        rospy.sleep(time_to_move)
        
        # 停止移动
        twist.linear.x = 0
        pub.publish(twist)
        
        # 停止后开始旋转
        rospy.loginfo("Rotating turtle")
        twist.angular.z = command["angular_speed"]["angular"]["z"]
        pub.publish(twist)
        
        # 旋转需要的时间或其他逻辑(如果需要)根据您的需求进行处理

    else:
        rospy.logerr("Unknown action: %s", command.get("action"))

def listener():
    global pub
    rospy.init_node('control_listener', anonymous=True)
    # 初始化发布者
    pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
    # 订阅 gpt_reply_to_user 话题
    rospy.Subscriber("gpt_reply_to_user", String, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()

演示脚本

启动mainchat.pycontrol.py
你可以选择创建包含该节点的功能包,也可以终端输入

python mainchat.py
python control.py

直接运行
确保你已经启动了小海龟仿真
在新的终端中输入,让小海龟去小黑子家

rostopic pub /user_to_gpt std_msgs/String "data: 'let the turtle go to xiaoheizi home,this is so far,and the turtle is so fast'"

运行结果~

本文标签: 无人机黑子自主解决方案智能