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 from __future__ import print_function
34
35 import optparse
36 import os
37 import shutil
38 import signal
39 import subprocess
40 import sys
41 import time
42 try:
43 from UserDict import UserDict
44 except ImportError:
45 from collections import UserDict
46
47 import roslib.message
48 import roslib.packages
49
50 from .bag import Bag, Compression, ROSBagException, ROSBagFormatException, ROSBagUnindexedException
51 from .migration import MessageMigrator, fixbag2, checkbag
54 from_txt = '%s [%s]' % (old._type, old._md5sum)
55 if new is not None:
56 to_txt= '%s [%s]' % (new._type, new._md5sum)
57 else:
58 to_txt = 'Unknown'
59 print(' ' * indent + ' * From: %s' % from_txt)
60 print(' ' * indent + ' To: %s' % to_txt)
61
63 parser.values.split = True
64 if len(parser.rargs) > 0 and parser.rargs[0].isdigit():
65 print("Use of \"--split <MAX_SIZE>\" has been deprecated. Please use --split --size <MAX_SIZE> or --split --duration <MAX_DURATION>", file=sys.stderr)
66 parser.values.size = int(parser.rargs.pop(0))
67
70 process.terminate()
71 if old_handler:
72 old_handler(signum, frame)
73
76 process.send_signal(signal.SIGINT)
77 if old_handler:
78 old_handler(signum, frame)
79
82 parser = optparse.OptionParser(usage="rosbag record TOPIC1 [TOPIC2 TOPIC3 ...]",
83 description="Record a bag file with the contents of specified topics.",
84 formatter=optparse.IndentedHelpFormatter())
85
86 parser.add_option("-a", "--all", dest="all", default=False, action="store_true", help="record all topics")
87 parser.add_option("-e", "--regex", dest="regex", default=False, action="store_true", help="match topics using regular expressions")
88 parser.add_option("-x", "--exclude", dest="exclude_regex", default="", action="store", help="exclude topics matching the follow regular expression (subtracts from -a or regex)")
89 parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true", help="suppress console output")
90 parser.add_option("-o", "--output-prefix", dest="prefix", default=None, action="store", help="prepend PREFIX to beginning of bag name (name will always end with date stamp)")
91 parser.add_option("-O", "--output-name", dest="name", default=None, action="store", help="record to bag with name NAME.bag")
92 parser.add_option( "--split", dest="split", default=False, callback=handle_split, action="callback", help="split the bag when maximum size or duration is reached")
93 parser.add_option( "--max-splits", dest="max_splits", type='int', action="store", help="Keep a maximum of N bag files, when reaching the maximum erase the oldest one to keep a constant number of files.", metavar="MAX_SPLITS")
94 parser.add_option( "--size", dest="size", type='int', action="store", help="record a bag of maximum size SIZE MB. (Default: infinite)", metavar="SIZE")
95 parser.add_option( "--duration", dest="duration", type='string',action="store", help="record a bag of maximum duration DURATION in seconds, unless 'm', or 'h' is appended.", metavar="DURATION")
96 parser.add_option("-b", "--buffsize", dest="buffsize", default=256, type='int', action="store", help="use an internal buffer of SIZE MB (Default: %default, 0 = infinite)", metavar="SIZE")
97 parser.add_option("--chunksize", dest="chunksize", default=768, type='int', action="store", help="Advanced. Record to chunks of SIZE KB (Default: %default)", metavar="SIZE")
98 parser.add_option("-l", "--limit", dest="num", default=0, type='int', action="store", help="only record NUM messages on each topic")
99 parser.add_option( "--node", dest="node", default=None, type='string',action="store", help="record all topics subscribed to by a specific node")
100 parser.add_option("-j", "--bz2", dest="compression", default=None, action="store_const", const='bz2', help="use BZ2 compression")
101 parser.add_option("--lz4", dest="compression", action="store_const", const='lz4', help="use LZ4 compression")
102 parser.add_option("--tcpnodelay", dest="tcpnodelay", action="store_true", help="Use the TCP_NODELAY transport hint when subscribing to topics.")
103 parser.add_option("--udp", dest="udp", action="store_true", help="Use the UDP transport hint when subscribing to topics.")
104
105 (options, args) = parser.parse_args(argv)
106
107 if len(args) == 0 and not options.all and not options.node:
108 parser.error("You must specify a topic name or else use the '-a' option.")
109
110 if options.prefix is not None and options.name is not None:
111 parser.error("Can't set both prefix and name.")
112
113 recordpath = roslib.packages.find_node('rosbag', 'record')
114 if not recordpath:
115 parser.error("Cannot find rosbag/record executable")
116 cmd = [recordpath[0]]
117
118 cmd.extend(['--buffsize', str(options.buffsize)])
119 cmd.extend(['--chunksize', str(options.chunksize)])
120
121 if options.num != 0: cmd.extend(['--limit', str(options.num)])
122 if options.quiet: cmd.extend(["--quiet"])
123 if options.prefix: cmd.extend(["-o", options.prefix])
124 if options.name: cmd.extend(["-O", options.name])
125 if options.exclude_regex: cmd.extend(["--exclude", options.exclude_regex])
126 if options.all: cmd.extend(["--all"])
127 if options.regex: cmd.extend(["--regex"])
128 if options.compression: cmd.extend(["--%s" % options.compression])
129 if options.split:
130 if not options.duration and not options.size:
131 parser.error("Split specified without giving a maximum duration or size")
132 cmd.extend(["--split"])
133 if options.max_splits:
134 cmd.extend(["--max-splits", str(options.max_splits)])
135 if options.duration: cmd.extend(["--duration", options.duration])
136 if options.size: cmd.extend(["--size", str(options.size)])
137 if options.node:
138 cmd.extend(["--node", options.node])
139 if options.tcpnodelay: cmd.extend(["--tcpnodelay"])
140 if options.udp: cmd.extend(["--udp"])
141
142 cmd.extend(args)
143
144 old_handler = signal.signal(
145 signal.SIGTERM,
146 lambda signum, frame: _stop_process(signum, frame, old_handler, process)
147 )
148
149 old_handler = signal.signal(
150 signal.SIGINT,
151 lambda signum, frame: _send_process_sigint(signum, frame, old_handler, process)
152 )
153
154
155
156 process = subprocess.Popen(cmd)
157 process.wait()
158
161 parser = optparse.OptionParser(usage='rosbag info [options] BAGFILE1 [BAGFILE2 BAGFILE3 ...]',
162 description='Summarize the contents of one or more bag files.')
163 parser.add_option('-y', '--yaml', dest='yaml', default=False, action='store_true', help='print information in YAML format')
164 parser.add_option('-k', '--key', dest='key', default=None, action='store', help='print information on the given key')
165 parser.add_option( '--freq', dest='freq', default=False, action='store_true', help='display topic message frequency statistics')
166 (options, args) = parser.parse_args(argv)
167
168 if len(args) == 0:
169 parser.error('You must specify at least 1 bag file.')
170 if options.key and not options.yaml:
171 parser.error('You can only specify key when printing in YAML format.')
172
173 for i, arg in enumerate(args):
174 try:
175 b = Bag(arg, 'r', skip_index=not options.freq)
176 if options.yaml:
177 info = b._get_yaml_info(key=options.key)
178 if info is not None:
179 print(info)
180 else:
181 print(b)
182 b.close()
183 if i < len(args) - 1:
184 print('---')
185
186 except ROSBagUnindexedException as ex:
187 print('ERROR bag unindexed: %s. Run rosbag reindex.' % arg,
188 file=sys.stderr)
189 sys.exit(1)
190 except ROSBagException as ex:
191 print('ERROR reading %s: %s' % (arg, str(ex)), file=sys.stderr)
192 sys.exit(1)
193 except IOError as ex:
194 print('ERROR reading %s: %s' % (arg, str(ex)), file=sys.stderr)
195 sys.exit(1)
196
199 topics = []
200 for arg in parser.rargs:
201 if arg[:2] == "--" and len(arg) > 2:
202 break
203 if arg[:1] == "-" and len(arg) > 1:
204 break
205 topics.append(arg)
206 parser.values.topics.extend(topics)
207 del parser.rargs[:len(topics)]
208
211 pause_topics = []
212 for arg in parser.rargs:
213 if arg[:2] == "--" and len(arg) > 2:
214 break
215 if arg[:1] == "-" and len(arg) > 1:
216 break
217 pause_topics.append(arg)
218 parser.values.pause_topics.extend(pause_topics)
219 del parser.rargs[:len(pause_topics)]
220
223 parser = optparse.OptionParser(usage="rosbag play BAGFILE1 [BAGFILE2 BAGFILE3 ...]",
224 description="Play back the contents of one or more bag files in a time-synchronized fashion.")
225 parser.add_option("-p", "--prefix", dest="prefix", default='', type='str', help="prefix all output topics")
226 parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true", help="suppress console output")
227 parser.add_option("-i", "--immediate", dest="immediate", default=False, action="store_true", help="play back all messages without waiting")
228 parser.add_option("--pause", dest="pause", default=False, action="store_true", help="start in paused mode")
229 parser.add_option("--queue", dest="queue", default=100, type='int', action="store", help="use an outgoing queue of size SIZE (defaults to %default)", metavar="SIZE")
230 parser.add_option("--clock", dest="clock", default=False, action="store_true", help="publish the clock time")
231 parser.add_option("--hz", dest="freq", default=100, type='float', action="store", help="use a frequency of HZ when publishing clock time (default: %default)", metavar="HZ")
232 parser.add_option("-d", "--delay", dest="delay", default=0.2, type='float', action="store", help="sleep SEC seconds after every advertise call (to allow subscribers to connect)", metavar="SEC")
233 parser.add_option("-r", "--rate", dest="rate", default=1.0, type='float', action="store", help="multiply the publish rate by FACTOR", metavar="FACTOR")
234 parser.add_option("-s", "--start", dest="start", default=0.0, type='float', action="store", help="start SEC seconds into the bag files", metavar="SEC")
235 parser.add_option("-u", "--duration", dest="duration", default=None, type='float', action="store", help="play only SEC seconds from the bag files", metavar="SEC")
236 parser.add_option("--skip-empty", dest="skip_empty", default=None, type='float', action="store", help="skip regions in the bag with no messages for more than SEC seconds", metavar="SEC")
237 parser.add_option("-l", "--loop", dest="loop", default=False, action="store_true", help="loop playback")
238 parser.add_option("-k", "--keep-alive", dest="keep_alive", default=False, action="store_true", help="keep alive past end of bag (useful for publishing latched topics)")
239 parser.add_option("--try-future-version", dest="try_future", default=False, action="store_true", help="still try to open a bag file, even if the version number is not known to the player")
240 parser.add_option("--topics", dest="topics", default=[], callback=handle_topics, action="callback", help="topics to play back")
241 parser.add_option("--pause-topics", dest="pause_topics", default=[], callback=handle_pause_topics, action="callback", help="topics to pause on during playback")
242 parser.add_option("--bags", help="bags files to play back from")
243 parser.add_option("--wait-for-subscribers", dest="wait_for_subscribers", default=False, action="store_true", help="wait for at least one subscriber on each topic before publishing")
244
245 (options, args) = parser.parse_args(argv)
246
247 if options.bags:
248 args.append(options.bags)
249
250 if len(args) == 0:
251 parser.error('You must specify at least 1 bag file to play back.')
252
253 playpath = roslib.packages.find_node('rosbag', 'play')
254 if not playpath:
255 parser.error("Cannot find rosbag/play executable")
256 cmd = [playpath[0]]
257
258 if options.prefix:
259 cmd.extend(["--prefix", str(options.prefix)])
260
261 if options.quiet: cmd.extend(["--quiet"])
262 if options.pause: cmd.extend(["--pause"])
263 if options.immediate: cmd.extend(["--immediate"])
264 if options.loop: cmd.extend(["--loop"])
265 if options.keep_alive: cmd.extend(["--keep-alive"])
266 if options.try_future: cmd.extend(["--try-future-version"])
267 if options.wait_for_subscribers: cmd.extend(["--wait-for-subscribers"])
268
269 if options.clock:
270 cmd.extend(["--clock", "--hz", str(options.freq)])
271
272 cmd.extend(['--queue', str(options.queue)])
273 cmd.extend(['--rate', str(options.rate)])
274 cmd.extend(['--delay', str(options.delay)])
275 cmd.extend(['--start', str(options.start)])
276 if options.duration:
277 cmd.extend(['--duration', str(options.duration)])
278 if options.skip_empty:
279 cmd.extend(['--skip-empty', str(options.skip_empty)])
280
281 if options.topics:
282 cmd.extend(['--topics'] + options.topics)
283
284 if options.pause_topics:
285 cmd.extend(['--pause-topics'] + options.pause_topics)
286
287
288 if options.topics or options.pause_topics:
289 cmd.extend(['--bags'])
290
291 cmd.extend(args)
292
293 old_handler = signal.signal(
294 signal.SIGTERM,
295 lambda signum, frame: _stop_process(signum, frame, old_handler, process)
296 )
297
298
299 process = subprocess.Popen(cmd)
300 process.wait()
301
304 def expr_eval(expr):
305 def eval_fn(topic, m, t):
306 return eval(expr)
307 return eval_fn
308
309 parser = optparse.OptionParser(usage="""rosbag filter [options] INBAG OUTBAG EXPRESSION
310
311 EXPRESSION can be any Python-legal expression.
312
313 The following variables are available:
314 * topic: name of topic
315 * m: message
316 * t: time of message (t.secs, t.nsecs)""",
317 description='Filter the contents of the bag.')
318 parser.add_option('-p', '--print', action='store', dest='verbose_pattern', default=None, metavar='PRINT-EXPRESSION', help='Python expression to print for verbose debugging. Uses same variables as filter-expression')
319
320 options, args = parser.parse_args(argv)
321 if len(args) == 0:
322 parser.error('You must specify an in bag, an out bag, and an expression.')
323 if len(args) == 1:
324 parser.error('You must specify an out bag and an expression.')
325 if len(args) == 2:
326 parser.error("You must specify an expression.")
327 if len(args) > 3:
328 parser.error("Too many arguments.")
329
330 inbag_filename, outbag_filename, expr = args
331
332 if not os.path.isfile(inbag_filename):
333 print('Cannot locate input bag file [%s]' % inbag_filename, file=sys.stderr)
334 sys.exit(2)
335
336 if os.path.realpath(inbag_filename) == os.path.realpath(outbag_filename):
337 print('Cannot use same file as input and output [%s]' % inbag_filename, file=sys.stderr)
338 sys.exit(3)
339
340 filter_fn = expr_eval(expr)
341
342 outbag = Bag(outbag_filename, 'w')
343
344 try:
345 inbag = Bag(inbag_filename)
346 except ROSBagUnindexedException as ex:
347 print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename, file=sys.stderr)
348 sys.exit(1)
349
350 try:
351 meter = ProgressMeter(outbag_filename, inbag._uncompressed_size)
352 total_bytes = 0
353
354 if options.verbose_pattern:
355 verbose_pattern = expr_eval(options.verbose_pattern)
356
357 for topic, raw_msg, t in inbag.read_messages(raw=True):
358 msg_type, serialized_bytes, md5sum, pos, pytype = raw_msg
359 msg = pytype()
360 msg.deserialize(serialized_bytes)
361
362 if filter_fn(topic, msg, t):
363 print('MATCH', verbose_pattern(topic, msg, t))
364 outbag.write(topic, msg, t)
365 else:
366 print('NO MATCH', verbose_pattern(topic, msg, t))
367
368 total_bytes += len(serialized_bytes)
369 meter.step(total_bytes)
370 else:
371 for topic, raw_msg, t in inbag.read_messages(raw=True):
372 msg_type, serialized_bytes, md5sum, pos, pytype = raw_msg
373 msg = pytype()
374 msg.deserialize(serialized_bytes)
375
376 if filter_fn(topic, msg, t):
377 outbag.write(topic, msg, t)
378
379 total_bytes += len(serialized_bytes)
380 meter.step(total_bytes)
381
382 meter.finish()
383
384 finally:
385 inbag.close()
386 outbag.close()
387
389 parser = optparse.OptionParser(usage='rosbag fix INBAG OUTBAG [EXTRARULES1 EXTRARULES2 ...]', description='Repair the messages in a bag file so that it can be played in the current system.')
390 parser.add_option('-n', '--noplugins', action='store_true', dest='noplugins', help='do not load rulefiles via plugins')
391 parser.add_option('--force', action='store_true', dest='force', help='proceed with migrations, even if not all rules defined')
392
393 (options, args) = parser.parse_args(argv)
394
395 if len(args) < 1:
396 parser.error('You must pass input and output bag files.')
397 if len(args) < 2:
398 parser.error('You must pass an output bag file.')
399
400 inbag_filename = args[0]
401 outbag_filename = args[1]
402 rules = args[2:]
403
404 ext = os.path.splitext(outbag_filename)[1]
405 if ext == '.bmr':
406 parser.error('Input file should be a bag file, not a rule file.')
407 if ext != '.bag':
408 parser.error('Output file must be a bag file.')
409
410 outname = outbag_filename + '.tmp'
411
412 if os.path.exists(outbag_filename):
413 if not os.access(outbag_filename, os.W_OK):
414 print('Don\'t have permissions to access %s' % outbag_filename, file=sys.stderr)
415 sys.exit(1)
416 else:
417 try:
418 file = open(outbag_filename, 'w')
419 file.close()
420 except IOError as e:
421 print('Cannot open %s for writing' % outbag_filename, file=sys.stderr)
422 sys.exit(1)
423
424 if os.path.exists(outname):
425 if not os.access(outname, os.W_OK):
426 print('Don\'t have permissions to access %s' % outname, file=sys.stderr)
427 sys.exit(1)
428 else:
429 try:
430 file = open(outname, 'w')
431 file.close()
432 except IOError as e:
433 print('Cannot open %s for writing' % outname, file=sys.stderr)
434 sys.exit(1)
435
436 if options.noplugins is None:
437 options.noplugins = False
438
439 migrator = MessageMigrator(rules, plugins=not options.noplugins)
440
441 try:
442 migrations = fixbag2(migrator, inbag_filename, outname, options.force)
443 except ROSBagUnindexedException as ex:
444 print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename,
445 file=sys.stderr)
446 sys.exit(1)
447
448 if len(migrations) == 0:
449 os.rename(outname, outbag_filename)
450 print('Bag migrated successfully.')
451 else:
452 print('Bag could not be migrated. The following migrations could not be performed:')
453 for m in migrations:
454 print_trans(m[0][0].old_class, m[0][-1].new_class, 0)
455
456 if len(m[1]) > 0:
457 print(' %d rules missing:' % len(m[1]))
458 for r in m[1]:
459 print_trans(r.old_class, r.new_class,1)
460
461 print('Try running \'rosbag check\' to create the necessary rule files or run \'rosbag fix\' with the \'--force\' option.')
462 os.remove(outname)
463 sys.exit(1)
464
466 parser = optparse.OptionParser(usage='rosbag check BAG [-g RULEFILE] [EXTRARULES1 EXTRARULES2 ...]', description='Determine whether a bag is playable in the current system, or if it can be migrated.')
467 parser.add_option('-g', '--genrules', action='store', dest='rulefile', default=None, help='generate a rulefile named RULEFILE')
468 parser.add_option('-a', '--append', action='store_true', dest='append', help='append to the end of an existing rulefile after loading it')
469 parser.add_option('-n', '--noplugins', action='store_true', dest='noplugins', help='do not load rulefiles via plugins')
470 (options, args) = parser.parse_args(argv)
471
472 if len(args) == 0:
473 parser.error('You must specify a bag file to check.')
474 if options.append and options.rulefile is None:
475 parser.error('Cannot specify -a without also specifying -g.')
476 if options.rulefile is not None:
477 rulefile_exists = os.path.isfile(options.rulefile)
478 if rulefile_exists and not options.append:
479 parser.error('The file %s already exists. Include -a if you intend to append.' % options.rulefile)
480 if not rulefile_exists and options.append:
481 parser.error('The file %s does not exist, and so -a is invalid.' % options.rulefile)
482
483 if options.append:
484 append_rule = [options.rulefile]
485 else:
486 append_rule = []
487
488
489 try:
490 Bag(args[0])
491 except ROSBagUnindexedException as ex:
492 print('ERROR bag unindexed: %s. Run rosbag reindex.' % args[0], file=sys.stderr)
493 sys.exit(1)
494
495 mm = MessageMigrator(args[1:] + append_rule, not options.noplugins)
496
497 migrations = checkbag(mm, args[0])
498
499 if len(migrations) == 0:
500 print('Bag file does not need any migrations.')
501 exit(0)
502
503 print('The following migrations need to occur:')
504 all_rules = []
505 for m in migrations:
506 all_rules.extend(m[1])
507
508 print_trans(m[0][0].old_class, m[0][-1].new_class, 0)
509 if len(m[1]) > 0:
510 print(" %d rules missing:" % len(m[1]))
511 for r in m[1]:
512 print_trans(r.old_class, r.new_class, 1)
513
514 if options.rulefile is None:
515 if all_rules == []:
516 print("\nAll rules defined. Bag is ready to be migrated")
517 else:
518 print("\nTo generate rules, please run with -g <rulefile>")
519 exit(0)
520
521 output = ''
522 rules_left = mm.filter_rules_unique(all_rules)
523
524 if rules_left == []:
525 print("\nNo additional rule files needed to be generated. %s not created."%(options.rulefile))
526 exit(0)
527
528 while len(rules_left) > 0:
529 extra_rules = []
530 for r in rules_left:
531 if r.new_class is None:
532 print('The message type %s appears to have moved. Please enter the type to migrate it to.' % r.old_class._type)
533 new_type = raw_input('>')
534 new_class = roslib.message.get_message_class(new_type)
535 while new_class is None:
536 print("\'%s\' could not be found in your system. Please make sure it is built." % new_type)
537 new_type = raw_input('>')
538 new_class = roslib.message.get_message_class(new_type)
539 new_rule = mm.make_update_rule(r.old_class, new_class)
540 R = new_rule(mm, 'GENERATED.' + new_rule.__name__)
541 R.find_sub_paths()
542 new_rules = [r for r in mm.expand_rules(R.sub_rules) if r.valid == False]
543 extra_rules.extend(new_rules)
544 print('Creating the migration rule for %s requires additional missing rules:' % new_type)
545 for nr in new_rules:
546 print_trans(nr.old_class, nr.new_class,1)
547 output += R.get_class_def()
548 else:
549 output += r.get_class_def()
550 rules_left = mm.filter_rules_unique(extra_rules)
551 f = open(options.rulefile, 'a')
552 f.write(output)
553 f.close()
554
555 print('\nThe necessary rule files have been written to: %s' % options.rulefile)
556
558 parser = optparse.OptionParser(usage='rosbag compress [options] BAGFILE1 [BAGFILE2 ...]',
559 description='Compress one or more bag files.')
560 parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR')
561 parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists')
562 parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages')
563 parser.add_option('-j', '--bz2', action='store_const', dest='compression', help='use BZ2 compression', const=Compression.BZ2, default=Compression.BZ2)
564 parser.add_option( '--lz4', action='store_const', dest='compression', help='use lz4 compression', const=Compression.LZ4)
565 (options, args) = parser.parse_args(argv)
566
567 if len(args) < 1:
568 parser.error('You must specify at least one bag file.')
569
570 op = lambda inbag, outbag, quiet: change_compression_op(inbag, outbag, options.compression, options.quiet)
571
572 bag_op(args, False, lambda b: False, op, options.output_dir, options.force, options.quiet)
573
575 parser = optparse.OptionParser(usage='rosbag decompress [options] BAGFILE1 [BAGFILE2 ...]',
576 description='Decompress one or more bag files.')
577 parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR')
578 parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists')
579 parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages')
580
581 (options, args) = parser.parse_args(argv)
582
583 if len(args) < 1:
584 parser.error('You must specify at least one bag file.')
585
586 op = lambda inbag, outbag, quiet: change_compression_op(inbag, outbag, Compression.NONE, options.quiet)
587
588 bag_op(args, False, lambda b: False, op, options.output_dir, options.force, options.quiet)
589
591 parser = optparse.OptionParser(usage='rosbag reindex [options] BAGFILE1 [BAGFILE2 ...]',
592 description='Reindexes one or more bag files.')
593 parser.add_option( '--output-dir', action='store', dest='output_dir', help='write to directory DIR', metavar='DIR')
594 parser.add_option('-f', '--force', action='store_true', dest='force', help='force overwriting of backup file if it exists')
595 parser.add_option('-q', '--quiet', action='store_true', dest='quiet', help='suppress noncritical messages')
596
597 (options, args) = parser.parse_args(argv)
598
599 if len(args) < 1:
600 parser.error('You must specify at least one bag file.')
601
602 op = lambda inbag, outbag, quiet: reindex_op(inbag, outbag, options.quiet)
603
604 bag_op(args, True, lambda b: b.version > 102, op, options.output_dir, options.force, options.quiet)
605
606 -def bag_op(inbag_filenames, allow_unindexed, copy_fn, op, output_dir=None, force=False, quiet=False):
607 for inbag_filename in inbag_filenames:
608
609 try:
610 inbag = Bag(inbag_filename, 'r', allow_unindexed=allow_unindexed)
611 except ROSBagUnindexedException:
612 print('ERROR bag unindexed: %s. Run rosbag reindex.' % inbag_filename, file=sys.stderr)
613 continue
614 except (ROSBagException, IOError) as ex:
615 print('ERROR reading %s: %s' % (inbag_filename, str(ex)), file=sys.stderr)
616 continue
617
618
619 copy = copy_fn(inbag)
620
621 inbag.close()
622
623
624 if output_dir is None:
625 outbag_filename = inbag_filename
626 else:
627 outbag_filename = os.path.join(output_dir, os.path.split(inbag_filename)[1])
628
629 backup_filename = None
630 if outbag_filename == inbag_filename:
631
632 backup_filename = '%s.orig%s' % os.path.splitext(inbag_filename)
633
634 if not force and os.path.exists(backup_filename):
635 if not quiet:
636 print('Skipping %s. Backup path %s already exists.' % (inbag_filename, backup_filename), file=sys.stderr)
637 continue
638
639 try:
640 if copy:
641 shutil.copy(inbag_filename, backup_filename)
642 else:
643 os.rename(inbag_filename, backup_filename)
644 except OSError as ex:
645 print('ERROR %s %s to %s: %s' % ('copying' if copy else 'moving', inbag_filename, backup_filename, str(ex)), file=sys.stderr)
646 continue
647
648 source_filename = backup_filename
649 else:
650 if copy:
651 shutil.copy(inbag_filename, outbag_filename)
652 source_filename = outbag_filename
653 else:
654 source_filename = inbag_filename
655
656 try:
657 inbag = Bag(source_filename, 'r', allow_unindexed=allow_unindexed)
658
659
660 try:
661 if copy:
662 outbag = Bag(outbag_filename, 'a', allow_unindexed=allow_unindexed)
663 else:
664 outbag = Bag(outbag_filename, 'w')
665 except (ROSBagException, IOError) as ex:
666 print('ERROR writing to %s: %s' % (outbag_filename, str(ex)), file=sys.stderr)
667 inbag.close()
668 continue
669
670
671 try:
672 op(inbag, outbag, quiet=quiet)
673 except ROSBagException as ex:
674 print('\nERROR operating on %s: %s' % (source_filename, str(ex)), file=sys.stderr)
675 inbag.close()
676 outbag.close()
677 continue
678
679 outbag.close()
680 inbag.close()
681
682 except KeyboardInterrupt:
683 if backup_filename is not None:
684 try:
685 if copy:
686 os.remove(backup_filename)
687 else:
688 os.rename(backup_filename, inbag_filename)
689 except OSError as ex:
690 print('ERROR %s %s to %s: %s', ('removing' if copy else 'moving', backup_filename, inbag_filename, str(ex)), file=sys.stderr)
691 break
692
693 except (ROSBagException, IOError) as ex:
694 print('ERROR operating on %s: %s' % (inbag_filename, str(ex)), file=sys.stderr)
695
697 outbag.compression = compression
698
699 if quiet:
700 for topic, msg, t in inbag.read_messages(raw=True):
701 outbag.write(topic, msg, t, raw=True)
702 else:
703 meter = ProgressMeter(outbag.filename, inbag._uncompressed_size)
704
705 total_bytes = 0
706 for topic, msg, t in inbag.read_messages(raw=True):
707 msg_type, serialized_bytes, md5sum, pos, pytype = msg
708
709 outbag.write(topic, msg, t, raw=True)
710
711 total_bytes += len(serialized_bytes)
712 meter.step(total_bytes)
713
714 meter.finish()
715
717 if inbag.version == 102:
718 if quiet:
719 try:
720 for offset in inbag.reindex():
721 pass
722 except:
723 pass
724
725 for (topic, msg, t) in inbag.read_messages():
726 outbag.write(topic, msg, t)
727 else:
728 meter = ProgressMeter(outbag.filename, inbag.size)
729 try:
730 for offset in inbag.reindex():
731 meter.step(offset)
732 except:
733 pass
734 meter.finish()
735
736 meter = ProgressMeter(outbag.filename, inbag.size)
737 for (topic, msg, t) in inbag.read_messages():
738 outbag.write(topic, msg, t)
739 meter.step(inbag._file.tell())
740 meter.finish()
741 else:
742 if quiet:
743 try:
744 for offset in outbag.reindex():
745 pass
746 except:
747 pass
748 else:
749 meter = ProgressMeter(outbag.filename, outbag.size)
750 try:
751 for offset in outbag.reindex():
752 meter.step(offset)
753 except:
754 pass
755 meter.finish()
756
759 UserDict.__init__(self)
760 self._description = {}
761 self['help'] = self.help_cmd
762
763 - def add_cmd(self, name, function, description):
764 self[name] = function
765 self._description[name] = description
766
768 str = "Available subcommands:\n"
769 for k in sorted(self.keys()):
770 str += " %s " % k
771 if k in self._description.keys():
772 str +="\t%s" % self._description[k]
773 str += "\n"
774 return str
775
777 argv = [a for a in argv if a != '-h' and a != '--help']
778
779 if len(argv) == 0:
780 print('Usage: rosbag <subcommand> [options] [args]')
781 print()
782 print("A bag is a file format in ROS for storing ROS message data. The rosbag command can record, replay and manipulate bags.")
783 print()
784 print(self.get_valid_cmds())
785 print('For additional information, see http://wiki.ros.org/rosbag')
786 print()
787 return
788
789 cmd = argv[0]
790 if cmd in self:
791 self[cmd](['-h'])
792 else:
793 print("Unknown command: '%s'" % cmd, file=sys.stderr)
794 print(self.get_valid_cmds(), file=sys.stderr)
795
797 - def __init__(self, path, bytes_total, refresh_rate=1.0):
798 self.path = path
799 self.bytes_total = bytes_total
800 self.refresh_rate = refresh_rate
801
802 self.elapsed = 0.0
803 self.update_elapsed = 0.0
804 self.bytes_read = 0.0
805
806 self.start_time = time.time()
807
808 self._update_progress()
809
810 - def step(self, bytes_read, force_update=False):
811 self.bytes_read = bytes_read
812 self.elapsed = time.time() - self.start_time
813
814 if force_update or self.elapsed - self.update_elapsed > self.refresh_rate:
815 self._update_progress()
816 self.update_elapsed = self.elapsed
817
819 max_path_len = self.terminal_width() - 37
820 path = self.path
821 if len(path) > max_path_len:
822 path = '...' + self.path[-max_path_len + 3:]
823
824 bytes_read_str = self._human_readable_size(float(self.bytes_read))
825 bytes_total_str = self._human_readable_size(float(self.bytes_total))
826
827 if self.bytes_read < self.bytes_total:
828 complete_fraction = float(self.bytes_read) / self.bytes_total
829 pct_complete = int(100.0 * complete_fraction)
830
831 if complete_fraction > 0.0:
832 eta = self.elapsed * (1.0 / complete_fraction - 1.0)
833 eta_min, eta_sec = eta / 60, eta % 60
834 if eta_min > 99:
835 eta_str = '--:--'
836 else:
837 eta_str = '%02d:%02d' % (eta_min, eta_sec)
838 else:
839 eta_str = '--:--'
840
841 progress = '%-*s %3d%% %8s / %8s %s ETA' % (max_path_len, path, pct_complete, bytes_read_str, bytes_total_str, eta_str)
842 else:
843 progress = '%-*s 100%% %19s %02d:%02d ' % (max_path_len, path, bytes_total_str, self.elapsed / 60, self.elapsed % 60)
844
845 print('\r', progress, end='')
846 sys.stdout.flush()
847
849 multiple = 1024.0
850 for suffix in ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']:
851 size /= multiple
852 if size < multiple:
853 return '%.1f %s' % (size, suffix)
854
855 raise ValueError('number too large')
856
858 self.step(self.bytes_total, force_update=True)
859 print()
860
861 @staticmethod
863 """Estimate the width of the terminal"""
864 width = 0
865 try:
866 import struct, fcntl, termios
867 s = struct.pack('HHHH', 0, 0, 0, 0)
868 x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
869 width = struct.unpack('HHHH', x)[1]
870 except (IOError, ImportError):
871 pass
872 if width <= 0:
873 try:
874 width = int(os.environ['COLUMNS'])
875 except:
876 pass
877 if width <= 0:
878 width = 80
879
880 return width
881
882 -def rosbagmain(argv=None):
883 cmds = RosbagCmds()
884 cmds.add_cmd('record', record_cmd, "Record a bag file with the contents of specified topics.")
885 cmds.add_cmd('info', info_cmd, 'Summarize the contents of one or more bag files.')
886 cmds.add_cmd('play', play_cmd, "Play back the contents of one or more bag files in a time-synchronized fashion.")
887 cmds.add_cmd('check', check_cmd, 'Determine whether a bag is playable in the current system, or if it can be migrated.')
888 cmds.add_cmd('fix', fix_cmd, 'Repair the messages in a bag file so that it can be played in the current system.')
889 cmds.add_cmd('filter', filter_cmd, 'Filter the contents of the bag.')
890 cmds.add_cmd('compress', compress_cmd, 'Compress one or more bag files.')
891 cmds.add_cmd('decompress', decompress_cmd, 'Decompress one or more bag files.')
892 cmds.add_cmd('reindex', reindex_cmd, 'Reindexes one or more bag files.')
893
894 if argv is None:
895 argv = sys.argv
896
897 if '-h' in argv or '--help' in argv:
898 argv = [a for a in argv if a != '-h' and a != '--help']
899 argv.insert(1, 'help')
900
901 if len(argv) > 1:
902 cmd = argv[1]
903 else:
904 cmd = 'help'
905
906 try:
907 if cmd in cmds:
908 cmds[cmd](argv[2:])
909 else:
910 cmds['help']([cmd])
911 except KeyboardInterrupt:
912 pass
913