00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 import roslib; roslib.load_manifest('hrl_lib')
00031 import rospy
00032
00033 import std_srvs.srv as srv
00034 from hrl_msgs.msg import FloatArray
00035
00036
00037 from rospy.impl.tcpros import DEFAULT_BUFF_SIZE
00038
00039 import time
00040 import numpy as np
00041 import geometry_msgs.msg as gm
00042 import sensor_msgs.msg as sm
00043 import threading
00044
00045
00046
00047
00048
00049
00050 def ros_to_dict(msg):
00051 d = {}
00052 for f in msg.__slots__:
00053 val = eval('msg.%s' % f)
00054 methods = dir(val)
00055 if 'to_time' in methods:
00056 val = eval('val.to_time()')
00057 elif '__slots__' in methods:
00058 val = ros_to_dict(val)
00059 d[f] = val
00060 return d
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074 def np_to_pointcloud(points_mat, frame):
00075 pc = sm.PointCloud()
00076 pc.header.stamp = rospy.get_rostime()
00077 pc.header.frame_id = frame
00078 for i in range(points_mat.shape[1]):
00079 p32 = gm.Point32()
00080 p32.x = points_mat[0,i]
00081 p32.y = points_mat[1,i]
00082 p32.z = points_mat[2,i]
00083 pc.points.append(p32)
00084 return pc
00085
00086 def np_to_colored_pointcloud(points_mat, intensity, frame):
00087 pc = np_to_pointcloud(points_mat, frame)
00088 pc.channels.append(sm.ChannelFloat32())
00089 pc.channels[0].name = 'intensity'
00090 pc.channels[0].values = intensity.A1.tolist()
00091 return pc
00092
00093
00094
00095
00096
00097 def np_to_rgb_pointcloud(points_mat, intensities, frame):
00098 pc = np_to_pointcloud(points_mat, frame)
00099 pc.channels.append(sm.ChannelFloat32())
00100 pc.channels[0].name = 'r'
00101 pc.channels[0].values = intensities[2,:].A1.tolist()
00102
00103 pc.channels.append(sm.ChannelFloat32())
00104 pc.channels[1].name = 'g'
00105 pc.channels[1].values = intensities[1,:].A1.tolist()
00106
00107 pc.channels.append(sm.ChannelFloat32())
00108 pc.channels[2].name = 'b'
00109 pc.channels[2].values = intensities[0,:].A1.tolist()
00110 return pc
00111
00112 def pointcloud_to_np(pc):
00113 plist = []
00114 for p in pc.points:
00115 plist.append([p.x, p.y, p.z])
00116 return np.matrix(plist).T
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137 def bag_iter(file_name, topics=[]):
00138 f = open(file_name)
00139 tdict = {}
00140 for t in topics:
00141 tdict[t] = True
00142
00143 for r in rosrecord.logplayer(f):
00144 if tdict.has_key(r[0]):
00145 yield r
00146
00147 f.close()
00148
00149
00150
00151
00152
00153
00154
00155
00156 def bag_sel_(file_name, topics=[]):
00157 print 'deprecated'
00158 d = {}
00159 for topic, msg, t in bag_iter(file_name, topics):
00160 if not d.has_key(topic):
00161 d[topic] = []
00162 d[topic].append((topic, msg, t.to_time()))
00163 return d
00164
00165 def bag_sel(file_name, topics=[]):
00166 d = {}
00167 for topic, msg, t in bag_iter(file_name, topics):
00168 if not d.has_key(topic):
00169 d[topic] = {'topic':[], 'msg':[], 't':[]}
00170 d[topic]['topic'].append(topic)
00171 d[topic]['msg'].append(msg)
00172 d[topic]['t'].append(t.to_time())
00173
00174 return d
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188 def wrap(f, inputs=[], response=srv.EmptyResponse, verbose=False):
00189 def _f(request):
00190 arguments = [eval('request.' + arg) for arg in inputs]
00191 if verbose:
00192 print 'Function', f, 'called with args:', arguments
00193 try:
00194 returns = f(*arguments)
00195 if returns == None:
00196 return response()
00197 else:
00198 return response(*returns)
00199 except Exception, e:
00200 print e
00201 return _f
00202
00203 def ignore_return(f):
00204 def _f(*args):
00205 f(*args)
00206 return _f
00207
00208 class UnresponsiveServerError(Exception):
00209 def __init__(self, value):
00210 self.value = value
00211 def __str__(self):
00212 return repr(self.value)
00213
00214
00215
00216 class FloatArrayListener:
00217
00218
00219
00220
00221
00222
00223
00224 def __init__(self, node_name, listen_channel, frequency):
00225 try:
00226 print node_name, ': inited node.'
00227 rospy.init_node(node_name, anonymous=True)
00228 except rospy.ROSException, e:
00229
00230 pass
00231
00232 self.reading = None
00233 self.last_message_number = None
00234 self.last_msg_time = None
00235 self.last_call_back = None
00236
00237 self.delay_tolerance = 300.0 / 1000.0
00238 self.delay_time = None
00239 self.time_out = 1.2
00240 self.count = 0
00241
00242 self.error = False
00243
00244 def callback(msg):
00245 msg_time = msg.header.stamp.to_time()
00246 msg_number = msg.header.seq
00247 self.reading = np.matrix(msg.data, 'f').T, msg_number
00248
00249
00250 if self.last_msg_time == None:
00251 self.last_msg_time = msg_time
00252
00253 time_diff = msg_time - self.last_msg_time
00254 if time_diff > self.delay_tolerance:
00255 self.delay_time = msg_time - self.last_msg_time
00256
00257 self.last_msg_time = msg_time
00258
00259 ctime = time.time()
00260
00261
00262
00263
00264
00265 self.last_call_back = ctime
00266 self.count = self.count + 1
00267
00268 rospy.Subscriber(listen_channel, FloatArray, callback)
00269 self.node_name = node_name
00270 print node_name,': subscribed to', listen_channel
00271
00272 def _check_timeout(self):
00273 if self.last_call_back != None:
00274
00275 time_diff = time.time() - self.last_call_back
00276 if time_diff > self.delay_tolerance:
00277 print self.node_name, ': have not heard back from publisher in', 1000*time_diff, 'ms'
00278 time.sleep(5/1000.0)
00279
00280 if time_diff > 1.0:
00281 self.error = True
00282
00283 if time_diff > self.time_out:
00284
00285
00286
00287 print "FloatArrayListener: Server have not responded for %.2f ms" % (1000 * time_diff)
00288
00289
00290
00291
00292
00293
00294 def read(self, fresh=True):
00295 if not fresh and self.reading == None:
00296 return None
00297 else:
00298 t = time.time()
00299 while self.reading == None:
00300 time.sleep(1.0)
00301 print self.node_name, ': no readings for %.2f s' % (time.time() - t)
00302
00303 reading = self.reading
00304 if fresh:
00305 while reading[1] == self.last_message_number:
00306
00307 time.sleep(1/1000.0)
00308 if self.delay_time != None:
00309 delay_time = self.delay_time
00310 self.delay_time = None
00311 print 'WARNING: delayed by', delay_time * 1000.0
00312 reading = self.reading
00313 else:
00314 self._check_timeout()
00315
00316 self.last_message_number = reading[1]
00317 return reading[0]
00318
00319
00320
00321
00322 class GenericListener:
00323
00324
00325
00326
00327
00328
00329
00330
00331 def __init__(self, node_name, message_type, listen_channel,
00332 frequency, message_extractor=None, queue_size=None):
00333 try:
00334 print node_name, ': inited node.'
00335 rospy.init_node(node_name, anonymous=True)
00336 except rospy.ROSException, e:
00337 pass
00338 self.last_msg_returned = None
00339 self.last_call_back = None
00340 self.delay_tolerance = 1/frequency
00341 self.reading = {'message':None, 'msg_id':-1}
00342 self.curid = 0
00343 self.message_extractor = message_extractor
00344
00345 def callback(*msg):
00346
00347 if 'header' in dir(msg):
00348 if msg.__class__ == ().__class__:
00349 msg_number = msg[0].header.seq
00350 else:
00351 msg_number = msg.header.seq
00352 else:
00353 msg_number = self.curid
00354 self.curid += 1
00355
00356
00357 if len(msg) == 1:
00358 msg = msg[0]
00359
00360 self.reading = {'message':msg, 'msg_id':msg_number}
00361
00362
00363 self.last_call_back = time.time()
00364
00365 if message_type.__class__ == [].__class__:
00366 import message_filters
00367 subscribers = [message_filters.Subscriber(channel, mtype) for channel, mtype in zip(listen_channel, message_type)]
00368 queue_size = 10
00369 ts = message_filters.TimeSynchronizer(subscribers, queue_size)
00370 ts.registerCallback(callback)
00371 else:
00372 rospy.Subscriber(listen_channel, message_type, callback,
00373 queue_size = queue_size)
00374
00375 self.node_name = node_name
00376
00377 rospy.loginfo('%s: subscribed to %s' % (node_name, listen_channel))
00378
00379 def _check_for_delivery_hiccups(self):
00380
00381 if self.last_call_back != None:
00382
00383 time_diff = time.time() - self.last_call_back
00384
00385 if time_diff > self.delay_tolerance:
00386 print self.node_name, ': have not heard back from publisher in', time_diff, 's'
00387
00388 def _wait_for_first_read(self, quiet=False):
00389 if not quiet:
00390 rospy.loginfo('%s: waiting for reading ...' % self.node_name)
00391 while self.reading['message'] == None and not rospy.is_shutdown():
00392 time.sleep(0.1)
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402 def read(self, allow_duplication=False, willing_to_wait=True, warn=False, quiet=True):
00403 if allow_duplication:
00404 if willing_to_wait:
00405 raise RuntimeError('Invalid settings for read.')
00406 else:
00407
00408
00409 reading = self.reading
00410 self.last_msg_returned = reading['msg_id']
00411 if self.message_extractor is not None:
00412 return self.message_extractor(reading['message'])
00413 else:
00414 return reading['message']
00415 else:
00416 if willing_to_wait:
00417
00418 self._wait_for_first_read(quiet)
00419 while self.reading['msg_id'] == self.last_msg_returned and not rospy.is_shutdown():
00420 if warn:
00421 self._check_for_delivery_hiccups()
00422 time.sleep(1/1000.0)
00423 reading = self.reading
00424 self.last_msg_returned = reading['msg_id']
00425 if self.message_extractor is not None:
00426 return self.message_extractor(reading['message'])
00427 else:
00428 return reading['message']
00429 else:
00430
00431 if self.last_msg_returned == self.reading['msg_id']:
00432 return None
00433 else:
00434 reading = self.reading
00435 self.last_msg_returned = reading['msg_id']
00436 if self.message_extractor is not None:
00437 return self.message_extractor(reading['message'])
00438 else:
00439 return reading['message']
00440
00441
00442
00443
00444
00445 class RateListener():
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489 def __init__(self, rate, name, data_class, callback=None, callback_args=None,
00490 queue_size=None, buff_size=DEFAULT_BUFF_SIZE, tcp_nodelay=False):
00491 self.rate = rate
00492 self.callback = callback
00493 self.lasttime = 0.0
00494 self.sub = rospy.Subscriber(name, data_class, self._process_msg, callback_args,
00495 queue_size, buff_size, tcp_nodelay)
00496
00497 def _process_msg(self, data, callback_args=None):
00498 delay = rospy.Time.now().to_sec() - self.lasttime
00499 if delay >= self.rate or self.lasttime == 0.0:
00500 if callback_args == None:
00501 self.callback(data)
00502 else:
00503 self.callback(data, callback_args)
00504 self.lasttime = rospy.Time.now().to_sec()
00505
00506 def unregister(self):
00507 self.sub.unregister()
00508
00509 def get_num_connections():
00510 return self.sub.get_num_connections()
00511
00512
00513 class RateCaller():
00514
00515 def __init__(self, func, rate, args=None):
00516 self.func = func
00517 self.rate = rate
00518 self.args = args
00519 self.thread = None
00520 self.is_running = False
00521 self.beg_time = None
00522
00523 def run(self):
00524 if not self.is_running:
00525 self.beg_time = time.time()
00526 self.num_time = 0
00527 self.thread = threading.Timer(self.rate, self._run)
00528 self.is_running = True
00529 self.thread.start()
00530
00531 def _run(self):
00532 if self.is_running:
00533 if self.args is None:
00534 self.func()
00535 else:
00536 self.func(*self.args)
00537 self.num_time += 1
00538
00539 diff_time = time.time() - self.beg_time
00540 timer_len = self.rate * (self.num_time + 1) - diff_time
00541 if timer_len <= 0.:
00542 timer_len = 0.
00543 self.thread = threading.Timer(timer_len, self._run)
00544 self.thread.start()
00545
00546 def stop(self):
00547 if self.thread is not None and self.is_running:
00548 self.thread.cancel()
00549 self.is_running = False
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561
00562
00563
00564
00565
00566
00567
00568 def call_save_service(service_name, service_def, params, filename=None):
00569 srv = rospy.ServiceProxy(service_name, service_def)
00570 try:
00571 resp = srv(*params)
00572 if not filename is None:
00573 save_pickle(resp, filename)
00574 srv.close()
00575 return resp
00576 except rospy.ServiceException, e:
00577 print "Service error"
00578 srv.close()
00579 return None
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609
00610
00611
00612
00613
00614
00615
00616
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626
00627
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649
00650
00651
00652
00653
00654
00655
00656
00657
00658
00659
00660
00661
00662
00663
00664
00665
00666
00667
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694
00695
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710
00711
00712
00713
00714
00715
00716
00717
00718
00719
00720
00721
00722
00723
00724
00725
00726
00727
00728
00729
00730
00731
00732
00733
00734
00735
00736
00737
00738
00739
00740
00741
00742
00743
00744
00745
00746
00747
00748
00749
00750
00751
00752
00753
00754
00755