Ejemplo n.º 1
0
    def test_check_type(self):
        # check_type() currently does not do harder checks like
        # type-checking class types.  as soon as it does, it will need
        # test to validate this.
        from roslib.message import check_type, SerializationError
        from roslib.rostime import Time, Duration
        valids = [
            ('byte', 1),
            ('byte', -1),
            ('string', ''),
            ('string', 'a string of text'),
            ('int32[]', []),
            ('int32[]', [1, 2, 3, 4]),
            ('time', Time()),
            ('time', Time.from_sec(1.0)),
            ('time', Time(10000)),
            ('time', Time(1000, -100)),
            ('duration', Duration()),
            ('duration', Duration()),
            ('duration', Duration(100)),
            ('duration', Duration(-100, -100)),
        ]

        for t, v in valids:
            try:
                check_type('n', t, v)
            except Exception, e:
                traceback.print_exc()
                raise Exception("failure type[%s] value[%s]: %s" %
                                (t, v, str(e)))
Ejemplo n.º 2
0
    def specify(self, typeStr, obj):
        if isinstance(typeStr, TypeType):
            cls = typeStr
        elif isinstance(typeStr, list):
            lst = []
            for i in xrange(len(typeStr)):
                lst.append(self.specify(typeStr[i], obj[i]))
            return lst
        elif typeStr != self.braces.sub('', typeStr):
            return [self.specify(self.braces.sub('', typeStr), x) for x in obj]
        elif typeStr in self.atomics:
            if typeStr == 'string':
                return obj.encode('ascii', 'ignore')
            return obj
        elif typeStr == 'time' or typeStr == 'duration':
            inst = None
            if typeStr == 'time':
                inst = Time()
            else:
                inst = Duration()
            if 'nsecs' in obj and 'secs' in obj:
                inst.nsecs = obj['nsecs']
                inst.secs = obj['secs']
            else:
                inst = rospy.get_rostime()
            return inst
        else:
            if typeStr == 'Header':
                typeStr = 'std_msgs/Header'
            cls = self.msgClassFromTypeString(typeStr)

        if not hasattr(cls, '__call__'):
            return None
        inst = cls()
        for i in xrange(len(cls._slot_types)):
            field = cls.__slots__[i]
            typ = cls._slot_types[i]
            if field in obj:
                value = self.specify(typ, obj[field])
                if value != None:
                    setattr(inst, field, value)
                else:
                    print "Warning: passed object was only partially specified."
            elif typ == 'time' or typ == 'duration':
                setattr(inst, field, rospy.get_rostime())
            elif typ == 'Header' or typ == 'std_msgs/Header':
                inst.header.stamp = rospy.get_rostime()
        return inst
Ejemplo n.º 3
0
	def specify(self, typeStr, obj):
		if isinstance(typeStr,TypeType):
			cls = typeStr
		elif isinstance(typeStr,list):
			lst = []
			for i in xrange(len(typeStr)):
				lst.append(self.specify(typeStr[i],obj[i]))
			return lst
		elif typeStr != self.braces.sub('',typeStr):
			return [self.specify(self.braces.sub('',typeStr), x) for x in obj]
		elif typeStr in self.atomics:
			if typeStr == 'string':
				return obj.encode('ascii','ignore')
			return obj
		elif typeStr == 'time' or typeStr == 'duration':
			inst = None
			if typeStr == 'time':
				inst = Time()
			else:
				inst = Duration()
			if 'nsecs' in obj and 'secs' in obj:
				inst.nsecs = obj['nsecs']
				inst.secs = obj['secs']
			else:
				inst = rospy.get_rostime()
			return inst
		else:
			if typeStr == 'Header':
				typeStr = 'std_msgs/Header'
			cls = self.msgClassFromTypeString(typeStr)

		if not hasattr(cls,'__call__'):
			return None
		inst = cls()
		for i in xrange(len(cls._slot_types)):
			field = cls.__slots__[i]
			typ = cls._slot_types[i]
			if field in obj:
				value = self.specify(typ,obj[field])
				if value != None:
					setattr(inst,field,value)
				else:
					print "Warning: passed object was only partially specified."
			elif typ=='time' or typ=='duration':
				setattr(inst, field, rospy.get_rostime())
			elif typ=='Header' or typ=='std_msgs/Header':
				inst.header.stamp = rospy.get_rostime()
		return inst
Ejemplo n.º 4
0
    def test_check_types_valid(self):
        '''Test directly a bunch of valid combinations to check_types.

        check_type will throw an exception when it fails
        '''
        roslib.message.check_type('test', 'uint8[]', 'byteDataIsAStringInPy')
        roslib.message.check_type('test', 'char[]', 'byteDataIsAStringInPy')
        roslib.message.check_type('test', 'uint8[]', [3, 4, 5])
        roslib.message.check_type('test', 'uint8[]', (3, 4, 5))
        roslib.message.check_type('test', 'char[]', [3, 4, 5])
        roslib.message.check_type('test', 'int32[]', [3, 4, 5])
        roslib.message.check_type('test', 'int32', -5)
        roslib.message.check_type('test', 'int64', -5)
        roslib.message.check_type('test', 'int16', -5)
        roslib.message.check_type('test', 'int8', -5)
        roslib.message.check_type('test', 'uint32', 5)
        roslib.message.check_type('test', 'uint64', 5)
        roslib.message.check_type('test', 'uint16', 5)
        roslib.message.check_type('test', 'uint8', 5)
        roslib.message.check_type('test', 'bool', True)
        roslib.message.check_type('test', 'bool', False)
        roslib.message.check_type('test', 'bool', 0)
        roslib.message.check_type('test', 'bool', 1)
        roslib.message.check_type('test', 'string', 'IAmAString')
        roslib.message.check_type('test', 'time', Time())
        roslib.message.check_type('test', 'duration', Duration(5))
Ejemplo n.º 5
0
    def test_check_type(self):
        # check_type() currently does not do harder checks like
        # type-checking class types.  as soon as it does, it will need
        # test to validate this.
        from roslib.message import check_type, SerializationError
        from roslib.rostime import Time, Duration
        valids = [
            ('byte', 1), ('byte', -1),
            ('string', ''), ('string', 'a string of text'),
            ('int32[]', []),
            ('int32[]', [1, 2, 3, 4]),
            ('time', Time()), ('time', Time.from_sec(1.0)),
            ('time', Time(10000)), ('time', Time(1000, -100)),
            ('duration', Duration()),('duration', Duration()), 
            ('duration', Duration(100)), ('duration', Duration(-100, -100)),
                  ]

        for t, v in valids:
            try:
                check_type('n', t, v)
            except Exception, e:
                traceback.print_exc()
                raise Exception("failure type[%s] value[%s]: %s"%(t, v, str(e)))
Ejemplo n.º 6
0
    numMsgsCopied = 0
    bagStartTimeSec = None
    for topic, msg, t in bag.read_messages():
        
        timeSec = t.to_sec()
        if bagStartTimeSec == None:
            bagStartTimeSec = timeSec

        timeSec -= bagStartTimeSec
        if timeSec < startTime:
            continue
        elif timeSec > endTime:
            break
        
        curTime = timeOffset + timeSec - startTime
        rosTime = Time.from_sec( curTime )
        msg.header.seq = curSeq
        msg.header.stamp = rosTime
        outputBag.write( topic, msg, rosTime )
        
        numMsgsCopied += 1
        curSeq += 1
        lastTime = curTime

    if numMsgsCopied == 0:
        print "No messages found within given time period for", bagFileSlice[ 0 ]
    else:
        print numMsgsCopied
        
    bag.close()
    
Ejemplo n.º 7
0
    def test_sub_str_plot_fields(self):
        from rostopic import _str_plot_fields
        from std_msgs.msg import String, Int32, Header
        from test_rostopic.msg import Simple, TVals, Floats, Arrays, Embed

        from roslib.rostime import Time, Duration
        from rostopic import create_field_filter

        # str plotting requires rospy time, we fix time to a set time
        import rospy.rostime
        rospy.rostime.set_rostime_initialized(True)
        rospy.rostime._set_rostime(Time(0, 1234))
        r_time = Time(0, 5678)

        # prepare test values
        simple_v = Simple(1, -2, 3, -4, 'a', 7, 8, 9, 'bar')
        simple_d = 'time,field.b,field.int16,field.int32,field.int64,field.c,field.uint16,field.uint32,field.uint64,field.str'
        simple_nostr = 'time,field.b,field.int16,field.int32,field.int64,field.c,field.uint16,field.uint32,field.uint64'

        arrays_v = Arrays([-1],
                          chr(2) + chr(3), [3, 4, 5], [6, 7, 8],
                          ['a1', 'b2', 'b3'],
                          [Time(123, 456), Time(78, 90)])
        arrays_d = 'time,field.int8_arr0,field.uint8_arr0,field.uint8_arr1,field.int32_arr0,field.int32_arr1,field.int32_arr2,field.uint32_arr0,field.uint32_arr1,field.uint32_arr2,field.string_arr0,field.string_arr1,field.string_arr2,field.time_arr0,field.time_arr1'
        arrays_nostr = 'time,field.int8_arr0,field.uint8_arr0,field.uint8_arr1,field.int32_arr0,field.int32_arr1,field.int32_arr2,field.uint32_arr0,field.uint32_arr1,field.uint32_arr2,field.time_arr0,field.time_arr1'

        embed_v = Embed(simple_v, arrays_v)
        embed_d = simple_d.replace('field.',
                                   'field.simple.') + ',' + arrays_d.replace(
                                       'field.', 'field.arrays.')[5:]
        embed_nostr = simple_nostr.replace(
            'field.', 'field.simple.') + ',' + arrays_nostr.replace(
                'field.', 'field.arrays.')[5:]
        embed_noarr = simple_d.replace('field.', 'field.simple.')
        embed_nostr_noarr = simple_nostr.replace('field.', 'field.simple.')

        # test over all combinations of field filters
        f = create_field_filter(echo_nostr=False, echo_noarr=False)
        m = String()
        self.assertEquals("time,field.data", _str_plot_fields(m, 'field', f))
        m = String('foo')
        self.assertEquals('time,field.data', _str_plot_fields(m, 'field', f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot_fields(m, 'field', f)
        self.assertEquals('time,field.t,field.d', v)
        m = simple_v
        self.assertEquals(simple_d, _str_plot_fields(m, 'field', f))
        m = arrays_v
        self.assertEquals(arrays_d, _str_plot_fields(m, 'field', f))
        m = embed_v
        self.assertEquals(embed_d, _str_plot_fields(m, 'field', f))

        f = create_field_filter(echo_nostr=True, echo_noarr=False)
        m = String()
        self.assertEquals("time,", _str_plot_fields(m, 'field', f))
        m = String('foo')
        self.assertEquals('time,', _str_plot_fields(m, 'field', f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot_fields(m, 'field', f)
        self.assertEquals('time,field.t,field.d', v)
        m = simple_v
        self.assertEquals(simple_nostr, _str_plot_fields(m, 'field', f))
        m = arrays_v
        self.assertEquals(arrays_nostr, _str_plot_fields(m, 'field', f))
        m = embed_v
        self.assertEquals(embed_nostr, _str_plot_fields(m, 'field', f))

        f = create_field_filter(echo_nostr=False, echo_noarr=True)
        m = String()
        self.assertEquals("time,field.data", _str_plot_fields(m, 'field', f))
        m = String('foo')
        self.assertEquals("time,field.data", _str_plot_fields(m, 'field', f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot_fields(m, 'field', f)
        self.assertEquals('time,field.t,field.d', v)
        m = simple_v
        self.assertEquals(simple_d, _str_plot_fields(m, 'field', f))
        m = arrays_v
        self.assertEquals('time,', _str_plot_fields(m, 'field', f))
        m = embed_v
        self.assertEquals(embed_noarr, _str_plot_fields(m, 'field', f))

        f = create_field_filter(echo_nostr=True, echo_noarr=True)
        m = String()
        self.assertEquals("time,", _str_plot_fields(m, 'field', f))
        m = String('foo')
        self.assertEquals('time,', _str_plot_fields(m, 'field', f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot_fields(m, 'field', f)
        self.assertEquals('time,field.t,field.d', v)
        m = simple_v
        self.assertEquals(simple_nostr, _str_plot_fields(m, 'field', f))
        m = arrays_v
        self.assertEquals('time,', _str_plot_fields(m, 'field', f))
        m = embed_v
        self.assertEquals(embed_nostr_noarr, _str_plot_fields(m, 'field', f))
Ejemplo n.º 8
0
    def test_strify_message(self):
        # strify message is part of roslib, but we want to test with
        # rostopic's field filters.  It's also the case that
        # roslib.messages cannot be unit tested within the ROS stack
        # -- part of the reason it needs to be moved elsewhere.
        from std_msgs.msg import String, Int32, Header
        from test_rostopic.msg import Simple, TVals, Floats, Arrays, Embed

        from roslib.rostime import Time, Duration
        from roslib.message import strify_message
        from rostopic import create_field_filter

        simple_v = Simple(1, -2, 3, -4, 'a', 7, 8, 9, 'bar')
        simple_d = {
            'b': 1,
            'int16': -2,
            'int32': 3,
            'int64': -4,
            'c': 'a',
            'uint16': 7,
            'uint32': 8,
            'uint64': 9,
            'str': 'bar'
        }
        simple_nostr = simple_d.copy()
        del simple_nostr['str']

        arrays_v = Arrays([-1],
                          chr(2) + chr(3), [3, 4, 5], [6, 7, 8],
                          ['a1', 'b2', 'b3'],
                          [Time(123, 456), Time(78, 90)])
        arrays_d = {
            'int8_arr': [-1],
            'uint8_arr': [2, 3],
            'int32_arr': [3, 4, 5],
            'uint32_arr': [6, 7, 8],
            'string_arr': ['a1', 'b2', 'b3'],
            'time_arr': [{
                'secs': 123,
                'nsecs': 456
            }, {
                'secs': 78,
                'nsecs': 90
            }]
        }
        arrays_nostr = arrays_d.copy()
        del arrays_nostr['string_arr']

        embed_v = Embed(simple_v, arrays_v)
        embed_d = {'simple': simple_d, 'arrays': arrays_d}

        f = create_field_filter(echo_nostr=False, echo_noarr=False)
        m = String()
        self.assertEquals("data: ''", strify_message(m, field_filter=f))
        m = String('foo')
        self.assertEquals('data: foo', strify_message(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(
            {
                't': {
                    'secs': 123,
                    'nsecs': 456
                },
                'd': {
                    'secs': 78,
                    'nsecs': 90
                }
            }, v)
        m = simple_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(simple_d, v)
        m = arrays_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(arrays_d, v)
        m = embed_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(embed_d, v)

        f = create_field_filter(echo_nostr=True, echo_noarr=False)
        m = String()
        self.assertEquals('', strify_message(m, field_filter=f))
        m = String('foo')
        self.assertEquals('', strify_message(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(
            {
                't': {
                    'secs': 123,
                    'nsecs': 456
                },
                'd': {
                    'secs': 78,
                    'nsecs': 90
                }
            }, v)
        m = simple_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(simple_nostr, v)
        m = arrays_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(arrays_nostr, v)
        m = embed_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals({'simple': simple_nostr, 'arrays': arrays_nostr}, v)

        f = create_field_filter(echo_nostr=False, echo_noarr=True)
        m = String()
        self.assertEquals("data: ''", strify_message(m, field_filter=f))
        m = String('foo')
        self.assertEquals('data: foo', strify_message(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(
            {
                't': {
                    'secs': 123,
                    'nsecs': 456
                },
                'd': {
                    'secs': 78,
                    'nsecs': 90
                }
            }, v)
        m = simple_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(simple_d, v)
        m = arrays_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(None, v)
        m = embed_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals({'simple': simple_d, 'arrays': None}, v)

        f = create_field_filter(echo_nostr=True, echo_noarr=True)
        m = String()
        self.assertEquals('', strify_message(m, field_filter=f))
        m = String('foo')
        self.assertEquals('', strify_message(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(
            {
                't': {
                    'secs': 123,
                    'nsecs': 456
                },
                'd': {
                    'secs': 78,
                    'nsecs': 90
                }
            }, v)
        m = simple_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals(simple_nostr, v)
        m = embed_v
        v = yaml.load(strify_message(m, field_filter=f))
        self.assertEquals({'simple': simple_nostr, 'arrays': None}, v)
Ejemplo n.º 9
0
    def test_str_plot(self):
        from rostopic import _str_plot
        from std_msgs.msg import String, Int32, Header
        from test_rostopic.msg import Simple, TVals, Floats, Arrays, Embed

        from roslib.rostime import Time, Duration
        from rostopic import create_field_filter

        # str plotting requires rospy time, we fix time to a set time
        import rospy.rostime
        rospy.rostime.set_rostime_initialized(True)
        rospy.rostime._set_rostime(Time(0, 1234))
        r_time = Time(0, 5678)

        # prepare test values
        simple_v = Simple(1, -2, 3, -4, 'a', 7, 8, 9, 'bar')
        simple_d = '1234,1,-2,3,-4,a,7,8,9,bar'
        simple_nostr = '1234,1,-2,3,-4,a,7,8,9'

        arrays_v = Arrays([-1],
                          chr(2) + chr(3), [3, 4, 5], [6, 7, 8],
                          ['a1', 'b2', 'b3'],
                          [Time(123, 456), Time(78, 90)])
        arrays_d = '1234,-1,2,3,3,4,5,6,7,8,a1,b2,b3,123000000456,78000000090'
        arrays_nostr = '1234,-1,2,3,3,4,5,6,7,8,123000000456,78000000090'

        embed_v = Embed(simple_v, arrays_v)
        embed_d = simple_d + ',' + arrays_d[5:]

        # test current_time override
        m = String('foo')
        self.assertEquals('5678,foo',
                          _str_plot(m, current_time=r_time, field_filter=None))

        # test over all combinations of field filters
        f = create_field_filter(echo_nostr=False, echo_noarr=False)
        m = String()
        self.assertEquals("1234,", _str_plot(m, field_filter=f))
        m = String('foo')
        self.assertEquals('1234,foo', _str_plot(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot(m, field_filter=f)
        self.assertEquals('1234,123000000456,78000000090', v)
        m = simple_v
        self.assertEquals(simple_d, _str_plot(m, field_filter=f))
        m = arrays_v
        self.assertEquals(arrays_d, _str_plot(m, field_filter=f))
        m = embed_v
        self.assertEquals(embed_d, _str_plot(m, field_filter=f))

        f = create_field_filter(echo_nostr=True, echo_noarr=False)
        m = String()
        self.assertEquals("1234,", _str_plot(m, field_filter=f))
        m = String('foo')
        self.assertEquals('1234,', _str_plot(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot(m, field_filter=f)
        self.assertEquals('1234,123000000456,78000000090', v)
        m = simple_v
        self.assertEquals(simple_nostr, _str_plot(m, field_filter=f))
        m = arrays_v
        self.assertEquals(arrays_nostr, _str_plot(m, field_filter=f))
        m = embed_v
        self.assertEquals(simple_nostr + arrays_nostr[4:],
                          _str_plot(m, field_filter=f))

        f = create_field_filter(echo_nostr=False, echo_noarr=True)
        m = String()
        self.assertEquals("1234,", _str_plot(m, field_filter=f))
        m = String('foo')
        self.assertEquals('1234,foo', _str_plot(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot(m, field_filter=f)
        self.assertEquals('1234,123000000456,78000000090', v)
        m = simple_v
        self.assertEquals(simple_d, _str_plot(m, field_filter=f))
        m = arrays_v
        self.assertEquals('1234,', _str_plot(m, field_filter=f))
        m = embed_v
        self.assertEquals(simple_d, _str_plot(m, field_filter=f))

        f = create_field_filter(echo_nostr=True, echo_noarr=True)
        m = String()
        self.assertEquals("1234,", _str_plot(m, field_filter=f))
        m = String('foo')
        self.assertEquals('1234,', _str_plot(m, field_filter=f))
        m = TVals(Time(123, 456), Duration(78, 90))
        v = _str_plot(m, field_filter=f)
        self.assertEquals('1234,123000000456,78000000090', v)
        m = simple_v
        self.assertEquals(simple_nostr, _str_plot(m, field_filter=f))
        m = arrays_v
        self.assertEquals('1234,', _str_plot(m, field_filter=f))
        m = embed_v
        self.assertEquals(simple_nostr, _str_plot(m, field_filter=f))
Ejemplo n.º 10
0
    def test_fill_message_args_embed_time(self):
        from roslib.rostime import Time, Duration
        from roslib.message import fill_message_args
        from test_roslib_comm.msg import FillEmbedTime

        # test fill_message_args with embeds and time vals
        # time t
        # duration d
        # std_msgs/String str_msg
        # std_msgs/String[] str_msg_array
        # int32 i32

        tests = []
        m = FillEmbedTime()
        fill_message_args(m, [{}])
        self.assertEquals(m.t, Time())
        self.assertEquals(m.d, Duration())
        self.assertEquals(m.str_msg.data, '')
        self.assertEquals(m.str_msg_array, [])
        self.assertEquals(m.i32, 0)

        # list tests
        # - these should be equivalent
        equiv = [
            [[10, 20], [30, 40], ['foo'], [['bar'], ['baz']], 32],
            [{
                'secs': 10,
                'nsecs': 20
            }, {
                'secs': 30,
                'nsecs': 40
            }, ['foo'], [['bar'], ['baz']], 32],
            [[10, 20], [30, 40], {
                'data': 'foo'
            }, [['bar'], ['baz']], 32],
            [[10, 20], [30, 40], ['foo'], [{
                'data': 'bar'
            }, {
                'data': 'baz'
            }], 32],
            [{
                't': [10, 20],
                'd': [30, 40],
                'str_msg': {
                    'data': 'foo'
                },
                'str_msg_array': [{
                    'data': 'bar'
                }, {
                    'data': 'baz'
                }],
                'i32': 32
            }],
            [{
                't': {
                    'secs': 10,
                    'nsecs': 20
                },
                'd': [30, 40],
                'str_msg': {
                    'data': 'foo'
                },
                'str_msg_array': [{
                    'data': 'bar'
                }, {
                    'data': 'baz'
                }],
                'i32': 32
            }],
        ]
        for test in equiv:
            m = FillEmbedTime()
            try:
                fill_message_args(m, test)
            except Exception, e:
                self.fail("failed to fill with : %s\n%s" %
                          (str(test), traceback.format_exc()))

            self.assertEquals(m.t, Time(10, 20))
            self.assertEquals(m.d, Duration(30, 40))
            self.assertEquals(m.str_msg.data, 'foo')
            self.assertEquals(len(m.str_msg_array), 2, m.str_msg_array)
            self.assertEquals(m.str_msg_array[0].data, 'bar')
            self.assertEquals(m.str_msg_array[1].data, 'baz')
            self.assertEquals(m.i32, 32)
Ejemplo n.º 11
0
    def test_strify_yaml(self):
        import yaml

        def roundtrip(m):
            yaml_text = strify_message(m)
            print yaml_text
            loaded = yaml.load(yaml_text)
            print "loaded", loaded
            new_inst = m.__class__()
            if loaded is not None:
                fill_message_args(new_inst, [loaded])
            else:
                fill_message_args(new_inst, [])
            return new_inst

        # test YAML roundtrip. strify_message doesn't promise this
        # yet, but want to use it in this way in some demo toolchains
        from roslib.message import Message, strify_message, fill_message_args

        class M1(Message):
            __slots__ = []
            _slot_types = []

            def __init__(self):
                pass

        self.assertEquals(M1(), roundtrip(M1()))

        class M2(Message):
            __slots__ = ['str', 'int', 'float', 'bool', 'list']
            _slot_types = ['string', 'int32', 'float32', 'bool', 'int32[]']

            def __init__(self,
                         str_=None,
                         int_=None,
                         float_=None,
                         bool_=None,
                         list_=None):
                self.str = str_
                self.int = int_
                self.float = float_
                self.bool = bool_
                self.list = list_

        val = M2('string', 123456789101112, 5678., True, [1, 2, 3])
        self.assertEquals(val, roundtrip(val))
        # test with empty string and empty list
        val = M2('', -1, 0., False, [])
        self.assertEquals(val, roundtrip(val))

        class M3(Message):
            __slots__ = ['m2']
            _slot_types = ['test_roslib/M2']

            def __init__(self, m2=None):
                self.m2 = m2 or M2()

        val = M3(M2('string', -1, 0., False, []))
        self.assertEquals(val, roundtrip(val))

        # test array of Messages field. We can't use M4 or M5 because fill_message_args has to instantiate the embedded type
        from test_roslib_comm.msg import ArrayOfMsgs
        from std_msgs.msg import String, Time, MultiArrayLayout, MultiArrayDimension
        dims1 = [
            MultiArrayDimension(*args)
            for args in [('', 0, 0), ('x', 1, 2), ('y of z', 3, 4)]
        ]
        dims2 = [MultiArrayDimension('hello world', 91280, 1983274)]
        times = [
            Time(roslib.rostime.Time(*args))
            for args in [(0, ), (12345, 6789), (1, 1)]
        ]
        val = ArrayOfMsgs(
            [String(''), String('foo'),
             String('bar of soap')],
            times,
            [MultiArrayLayout(dims1, 0),
             MultiArrayLayout(dims2, 12354)],
        )
        self.assertEquals(val, roundtrip(val))
Ejemplo n.º 12
0
    def test_strify_message(self):
        # this is a bit overtuned, but it will catch regressions
        from roslib.message import Message, strify_message

        class M1(Message):
            __slots__ = []
            _slot_types = []

            def __init__(self):
                pass

        self.assertEquals('', strify_message(M1()))

        class M2(Message):
            __slots__ = ['str', 'int', 'float', 'bool', 'list']
            _slot_types = ['string', 'int32', 'float32', 'bool', 'int32[]']

            def __init__(self, str_, int_, float_, bool_, list_):
                self.str = str_
                self.int = int_
                self.float = float_
                self.bool = bool_
                self.list = list_

        self.assertEquals(
            """str: string
int: 123456789101112
float: 5678.0
bool: True
list: [1, 2, 3]""",
            strify_message(
                M2('string', 123456789101112, 5678., True, [1, 2, 3])))

        self.assertEquals(
            """str: ''
int: -1
float: 0.0
bool: False
list: []""", strify_message(M2('', -1, 0., False, [])))

        class M3(Message):
            __slots__ = ['m2']
            _slot_types = ['M1']

            def __init__(self, m2):
                self.m2 = m2

        self.assertEquals(
            """m2: 
  str: string
  int: -1
  float: 0.0
  bool: False
  list: []""", strify_message(M3(M2('string', -1, 0., False, []))))

        # test array of Messages field
        class M4(Message):
            __slots__ = ['m2s']
            _slot_types = ['M2[]']

            def __init__(self, m2s):
                self.m2s = m2s

        self.assertEquals(
            """m2s: 
  - 
    str: string
    int: 1234
    float: 5678.0
    bool: True
    list: [1, 2, 3]
  - 
    str: string
    int: -1
    float: 0.0
    bool: False
    list: []""",
            strify_message(
                M4([
                    M2('string', 1234, 5678., True, [1, 2, 3]),
                    M2('string', -1, 0., False, []),
                ])))
        # test Time and Duration
        from roslib.rostime import Time, Duration

        class M5(Message):
            __slots__ = ['t', 'd']
            _slot_types = ['time', 'duration']

            def __init__(self, t, d):
                self.t = t
                self.d = d

        self.assertEquals(
            """t: 
  secs: 987
  nsecs: 654
d: 
  secs: 123
  nsecs: 456""", strify_message(M5(Time(987, 654), Duration(123, 456))))

        # test final clause of strify -- str anything that isn't recognized
        self.assertEquals("set([1])", strify_message(set([1])))
Ejemplo n.º 13
0
    numMsgsCopied = 0
    bagStartTimeSec = None
    for topic, msg, t in bag.read_messages():

        timeSec = t.to_sec()
        if bagStartTimeSec == None:
            bagStartTimeSec = timeSec

        timeSec -= bagStartTimeSec
        if timeSec < startTime:
            continue
        elif timeSec > endTime:
            break

        curTime = timeOffset + timeSec - startTime
        rosTime = Time.from_sec(curTime)
        msg.header.seq = curSeq
        msg.header.stamp = rosTime
        outputBag.write(topic, msg, rosTime)

        numMsgsCopied += 1
        curSeq += 1
        lastTime = curTime

    if numMsgsCopied == 0:
        print "No messages found within given time period for", bagFileSlice[0]
    else:
        print numMsgsCopied

    bag.close()