ros tutorial introductorio (nueve) - biblioteca de cliente: Rospy (bajar)

Rospy diferente demostración de demostración

topic_demo

El modelo básico y similares roscpp

Descripción de la función: dos nodos, un GPS mensaje de liberación simulados (formato personalizado, incluyendo las coordenadas y estado de funcionamiento), el mensaje es aceptada y procesada (para calcular la distancia desde el origen).

/gps
传感器
处理器

pasos:

  1. paquete
  2. msg
  3. talker.cpp
  4. listener.cpp
  5. CMakeList.txt y package.xml
1. paquete
$ cd ~/catkin_ws/src
$ catkin_create_pkg topic_demo roscpp rospy std_msgs
2. msg
$ cd topic_demo/
$ mkdir msg
$ cd msg
$ vi gps.msg
# gps.msg
float32 x
float32 y
string state

Cuando termine de crear msg, el compilador genera un ~/catkin_ws/devel/lib/python2.7/dis-packages/topic_demo/msg/__init__.pyarchivo. Escribir código de importación en él

from topic_demo.msg import gps
3. pytalker.py
#!/usr/bin/env python

import rospy
from topic_demo.msg import gps

def talker():
    pub = rospy.Publisher( 'gps_info' , gps, queue_size=10)
    rospy.init_node(' pytalker ', anonymous=True)
    rate = rospy.Rate(1)
    x = 1.0
    y = 2.0
    state = 'working'
    while not rospy.is_shutdown():
        rospy.loginfo( 'Talker: GPS: x = %f, y = %f')
        pub.publish(gps(state,x,y))  # 构造了gps的临时对象,这样写更直观。
        x = 1.03 * x
        y = 1.01 * y 
        rate.sleep()
           
if __name__ == '__main__' :
    talker()
}
4. pylistener.py
#!/usr/bin/env python

import rospy
import math
from topic_demo.msg import gps

def callback(gps):
    distance = math.sqrt(math.pow(gps.x, 2) + math.pow(gps.y, 2))
    rospy.loginfo( 'Listener: GPS distance = %f, state: %s ', distance , gps.state)
    
def listener():
    rospy.init_node('pylistener')
    rospy.Subscribe( 'gps_info' , gps , callback)
    rospy.spin()
    
if __name__ == '__main__' :
    listener() 

5. CMakeLists.txt y package.xml

py no necesita compilación, aquí principalmente para archivos MSG de compilación

Aquí Insertar imagen Descripción
Aquí Insertar imagen Descripción

service_demo

El modelo básico es similar, puede hacer referencia a la plantilla.

Descripción de la función: dos nodos, una solicitud de liberación (formato personalizado), otra recibir y procesar la información del mensaje y el retorno.

response/reply
request
server
client

pasos:

  1. paquete
  2. msg
  3. server.cpp
  4. client.cpp
  5. CMakeList.txt y package.xml
1. paquete
$ cd ~/catkin_ws/src
$ catkin_create_pkg service_demo roscpp rospy std_msgs
2. srv
$ cd service_demo/
$ mkdir srv
$ vi Greeting.srv
# Greeting.srv
string name
int32 age 
---
string feedback

Cuando termine de crear SRV, el compilador genera un ~/catkin_ws/devel/lib/python2.7/dis-packages/service_demo/srv/__init__.pyarchivo. Escribir código de importación en él

from service_demo.srv import *
3. server.py
#!/usr/bin/env python

import rospy
from service_demo.srv import *

def server_srv():
    rospy.init_node(' greetings_server ')
    s = rospy.Service( 'greetings', Greeting, handle_function) #定义程序的server端
    rospy.loginfo(' Ready to handle the request:') 
    rospy.spin()
    
def handle_function(req):
    rospy.loginfo( 'Request from' , req.name , 'with age' , req.age)
    return GreetingResponse( 'Hi %s. I'm server !' %req.name)
           
if __name__ == '__main__' :
    server_srv()
4. client.py
#!/usr/bin/env python

import rospy
from service_demo.srv import *

def client_srv():
    rospy.init_node(' greetings_client ')
    rospy.wait_for_service( 'greetings')
    
    try:
        greetings_client = rospy.ServiceProxy( 'greetings' ,Greeting)
        rosp = greetings_client( 'HAN' , 20)
        rospy.loginfo(' Message From Server: %s ' %rosp.feedback ) 
    except rospy.ServiceException e:
        rospy.logwarn( 'Service call failed: %s' %e)
           
if __name__ == '__main__' :
    client_srv()
}
5. CMakeLists.txt y package.xml

A continuación, puede compilar (catkin_make) y ejecutar (rosrun) a ~

Por favor indique la fuente.
Este documento resume la Universidad China de MOOC "Android OS Getting Started"
enlace: Enlace .
Imágenes del programa de captura de vídeo

Publicado 43 artículos originales · alabanza ganado 20 · vistas 1470

Supongo que te gusta

Origin blog.csdn.net/Chen_2018k/article/details/104346422
Recomendado
Clasificación