• ros话题通信-自定义msg


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

    1. 创建msg文件

    在这里插入图片描述
    在功能包目录下创建msg文件夹,创建msg文件

    2. 编写msg文件

    string name
    uint16 age
    float64 height
    
    • 1
    • 2
    • 3

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

    3.配置package.xmlCMakeLists.txt

    • 按照官方说法,创建玩msg文件还得配置两个文件
      package.xml
      在这里插入图片描述
      CMakeLists.txt
      在这里插入图片描述
      在这里插入图片描述
      在这里插入图片描述
    • but~由于我们用的是roboware studio 因此我们创建完msg文件后,系统都自动帮我们配置了哈哈哈哈哈,就是这么无敌

    4.编译生成文件

    我们点击debug按钮编译生成文件
    在这里插入图片描述
    在这个目录下会生成一个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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148

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

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

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

    在这里插入图片描述
    在这里插入图片描述

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    对应的订阅者代码为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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

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

  • 相关阅读:
    mysql进阶学习 - concat函数
    项目管理工具DHTMLX Gantt灯箱元素配置教程:配置灯箱元素
    极限多标签学习之SwiftXML
    【日常系列】LeetCode《18·二叉树3》
    AcWing周赛 70 && LeetCode单周赛 312
    mfc140.dll怎么安装?mfc140.dll丢失安装详细解决方法
    Haproxy负载均衡集群
    Linux性能监控命令_pidstat & 统计进程信息
    状态机的技术选型看这篇就够了,最后一个直叫好!!!
    可变参数与日志demo
  • 原文地址:https://blog.csdn.net/weixin_46187354/article/details/127785712