ros话题通信-自定义msg

由于毕设是做ros机器人相关的上位机,因此本专题是做毕设所有过程的记录
学习资料参考内容如下:
B站Autolabor初级教程教学
Autolabor初级教程教学文档
主要是想记录自己的踩过的所有坑,内容可能比较零散,想看比较系统完备的知识请去参考上面两个链接

1. 创建msg文件

ros话题通信-自定义msg_第1张图片
在功能包目录下创建msg文件夹,创建msg文件

2. 编写msg文件

string name
uint16 age
float64 height

有点类似于c语言的结构体?

3.配置package.xmlCMakeLists.txt

  • 按照官方说法,创建玩msg文件还得配置两个文件
    package.xml
    ros话题通信-自定义msg_第2张图片
    CMakeLists.txt
    ros话题通信-自定义msg_第3张图片
    ros话题通信-自定义msg_第4张图片
    ros话题通信-自定义msg_第5张图片
  • but~由于我们用的是roboware studio 因此我们创建完msg文件后,系统都自动帮我们配置了哈哈哈哈哈,就是这么无敌

4.编译生成文件

我们点击debug按钮编译生成文件
ros话题通信-自定义msg_第6张图片
在这个目录下会生成一个py文件

# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from pub_topic/person.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct


class person(genpy.Message):
  _md5sum = "81ccf2097ef38ca6466e5a60ea1f8e49"
  _type = "pub_topic/person"
  _has_header = False #flag to mark the presence of a Header object
  _full_text = """string name
uint16 age
float64 height
"""
  __slots__ = ['name','age','height']
  _slot_types = ['string','uint16','float64']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       name,age,height

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(person, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.name is None:
        self.name = ''
      if self.age is None:
        self.age = 0
      if self.height is None:
        self.height = 0.
    else:
      self.name = ''
      self.age = 0
      self.height = 0.

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self.name
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('%length, length, _x))
      _x = self
      buff.write(_get_struct_Hd().pack(_x.age, _x.height))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      end = 0
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.name = str[start:end].decode('utf-8')
      else:
        self.name = str[start:end]
      _x = self
      start = end
      end += 10
      (_x.age, _x.height,) = _get_struct_Hd().unpack(str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill


  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self.name
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('%length, length, _x))
      _x = self
      buff.write(_get_struct_Hd().pack(_x.age, _x.height))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      end = 0
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.name = str[start:end].decode('utf-8')
      else:
        self.name = str[start:end]
      _x = self
      start = end
      end += 10
      (_x.age, _x.height,) = _get_struct_Hd().unpack(str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
def _get_struct_I():
    global _struct_I
    return _struct_I
_struct_Hd = None
def _get_struct_Hd():
    global _struct_Hd
    if _struct_Hd is None:
        _struct_Hd = struct.Struct(")
    return _struct_Hd

让给我们看看这个文件好像貌似是定义了一个类,可以看到他定义类的 slot 属性,用它来声明实例属性的列表,可以用来减少内存空间的目的。并且类的属性名和我们msg文件内容是一样的

5.mgs生成的py文件的路径问题

从上面描述我们可以发现msg生成的python文件就是一个类,但他生成的路径我觉得是有点反人类的,所有我的解决方法是直接把python文件移到scripts这个文件夹里面去,这样我们不就可以直接用相对路径导入这个类了吗

ros话题通信-自定义msg_第7张图片
ros话题通信-自定义msg_第8张图片

6.代码实现

我们创建一个pub_msg.py文件

from msg._person import person
import rospy

if __name__ == "__main__":
    rospy.init_node("junhao")
    pub = rospy.Publisher("msg1",person, queue_size=10)
    p = person()
    p.name = "junhao"
    p.age = 18
    p.height = 1.95
    rate = rospy.Rate(1)
    while not rospy.is_shutdown():
        pub.publish(p)
        rospy.loginfo(f"发布的话题消息为:{p.name}-{p.age}-{p.height}")
        rate.sleep()

对应的订阅者代码为sub_msg.py


#!/usr/bin/env python3
"""
    需求: 实现基本的话题通信,一方发布数据,一方接收数据,
         实现的关键点:
         1.发送方
         2.接收方
         3.数据(此处为普通文本)


    消息订阅方:
        订阅话题并打印接收到的消息

    实现流程:
        1.导包 
        2.初始化 ROS 节点:命名(唯一)
        3.实例化 订阅者 对象
        4.处理订阅的消息(回调函数)
        5.设置循环调用回调函数

"""
#1.导包 
import rospy
from std_msgs.msg import String
from msg._person import person

def doMsg(msg):
    rospy.loginfo(f"接受者收到的数据-{msg.name}-{msg.age}-{msg.height}")

if __name__ == "__main__":
    #2.初始化 ROS 节点:命名(唯一)
    rospy.init_node("listener_p")
    #3.实例化 订阅者 对象
    sub = rospy.Subscriber("msg1",person,doMsg,queue_size=10)
    #4.处理订阅的消息(回调函数)
    #5.设置循环调用回调函数
    rospy.spin()

从发布者我们只是在rospy.Publisher这个接口传入了person这个类,并实例化了一个对象传入了publish这个接口,而订阅者的代码是传入了话题名称,然后再回调函数中调用

你可能感兴趣的:(ROS学习,python,机器人,开发语言)