Exemplo n.º 1
0
    def test_get_class_by_name(self):
        robot = get_class_by_name('osgar.lib.test_config:MyTestRobot')()
        self.assertEqual(robot.get_name(), 'Karel')

        node = get_class_by_name('tcp')
        self.assertEqual(node, LogTCP)

        node = get_class_by_name('udp')
        self.assertNotEqual(node, LogTCP)
Exemplo n.º 2
0
    def test_get_class_by_name(self):
        robot = get_class_by_name('osgar.lib.test_config:MyTestRobot')()
        self.assertEqual(robot.get_name(), 'Karel')

        node = get_class_by_name('tcp')
        self.assertEqual(node, LogTCP)

        node = get_class_by_name('udp')
        self.assertNotEqual(node, LogTCP)
Exemplo n.º 3
0
    def __init__(self, config, logger, application=None):
        self.modules = {}

        que = {}
        for module_name, module_config in config['modules'].items():
            out, slots = {}, {}
            for output_type in module_config['out']:
                out[output_type] = []
                slots[output_type] = []
            bus = BusHandler(logger, out=out, slots=slots, name=module_name)
            que[module_name] = bus.queue

            module_class = module_config['driver']
            if module_class == 'application':
                assert application is not None  # external application required
                module = application(module_config['init'], bus=bus)
            else:
                module = get_class_by_name(module_class)(module_config['init'],
                                                         bus=bus)

            self.modules[module_name] = module

        for from_module, to_module in config['links']:
            (from_driver, from_name), (
                to_driver,
                to_name) = from_module.split('.'), to_module.split('.')
            if to_name.startswith('slot_'):
                self.modules[from_driver].bus.slots[from_name].append(
                    getattr(self.modules[to_driver], to_name))
            else:
                self.modules[from_driver].bus.out[from_name].append(
                    (self.modules[to_driver].bus.queue, to_name))
Exemplo n.º 4
0
def replay(args, application=None):
    log = LogReader(args.logfile, only_stream_id=0)
    print("original args:", next(log)[-1])  # old arguments
    config_str = next(log)[-1]
    config = literal_eval(config_str.decode('ascii'))
    if args.config is not None:
        config = config_load(*args.config, application=application)

    names = logger.lookup_stream_names(args.logfile)
    if args.debug:
        print("streams:")
        for i, name in enumerate(names):
            print(f" {i+1:2d} {name}")

    module = args.module
    assert module in config['robot']['modules'], (
        module, list(config['robot']['modules'].keys()))
    module_config = config['robot']['modules'][module]

    inputs = {}
    for edge_from, edge_to in config['robot']['links']:
        if edge_to.split('.')[0] == module:
            if edge_from not in names:
                g_logger.warning('Missing name: %s' % edge_from)
                names.append(edge_from)
            inputs[1 + names.index(edge_from)] = edge_to.split('.')[1]

    outputs = {
        i + 1: out.split('.')[1]
        for i, out in enumerate(names) if out.startswith(f"{module}.")
    }
    if args.debug:
        print("inputs:")
        for i, name in sorted(inputs.items()):
            print(f" {i:2d} {name}")
        print("outputs:")
        for i, name in sorted(outputs.items()):
            print(f" {i:2d} {name}")

    if args.force:
        reader = LogReader(args.logfile, only_stream_id=inputs.keys())
        bus = LogBusHandlerInputsOnly(reader, inputs=inputs)
    else:
        streams = list(inputs.keys()) + list(outputs.keys())
        reader = LogReader(args.logfile, only_stream_id=streams)
        bus = LogBusHandler(reader, inputs, outputs)

    driver_name = module_config['driver']
    module_class = get_class_by_name(driver_name)
    module_instance = module_class(module_config.get('init', {}), bus=bus)

    bus.node = module_instance  # needed for slots
    return module_instance
Exemplo n.º 5
0
def replay(args, application=None):
    log = LogReader(args.logfile, only_stream_id=0)
    print("original args:", next(log)[-1])  # old arguments
    config_str = next(log)[-1]
    config = literal_eval(config_str.decode('ascii'))
    if args.config is not None:
        config = config_load(*args.config)

    names = logger.lookup_stream_names(args.logfile)
    print("stream names:")
    for name in names:
        print(" ", name)

    module = args.module
    assert module in config['robot']['modules'], (
        module, list(config['robot']['modules'].keys()))
    module_config = config['robot']['modules'][module]

    input_names = module_config['in']
    output_names = module_config['out']
    print("inputs:", input_names)
    print("outputs:", output_names)

    inputs = {}
    for edge_from, edge_to in config['robot']['links']:
        if edge_to.split('.')[0] == module:
            if edge_from not in names:
                logging.warning(f'Missing name: {edge_from}')
                names.append(edge_from)
            inputs[1 + names.index(edge_from)] = edge_to.split('.')[1]

    # start reading log from the beginning again
    if args.force:
        log = LogReader(args.logfile, only_stream_id=inputs.keys())
        bus = LogBusHandlerInputsOnly(log, inputs=inputs)
    else:
        outputs = dict([(1 + names.index('.'.join([module, name])), name)
                        for name in output_names])
        streams = list(inputs.keys()) + list(outputs.keys())
        log = LogReader(args.logfile, only_stream_id=streams)
        bus = LogBusHandler(log, inputs=inputs, outputs=outputs)

    driver_name = module_config['driver']
    if driver_name == 'application':
        assert application is not None
        module_class = application
    else:
        module_class = get_class_by_name(driver_name)
    module_instance = module_class(module_config['init'], bus=bus)
    bus.node = module_instance
    return module_instance
Exemplo n.º 6
0
def main():
    import argparse
    import os.path
    global g_rotation_offset_rad

    parser = argparse.ArgumentParser(description='View lidar scans')
    parser.add_argument('logfile', help='recorded log file')
    parser.add_argument('--legacy',
                        help='use old text lidar log format',
                        action='store_true')

    parser.add_argument('--lidar', help='stream ID')

    pose = parser.add_mutually_exclusive_group()
    pose.add_argument('--pose2d', help='stream ID for pose2d messages')
    pose.add_argument('--pose3d', help='stream ID for pose3d messages')

    parser.add_argument('--camera', help='stream ID for JPEG images')

    parser.add_argument('--callback', help='callback function for lidar scans')

    parser.add_argument('--rotate',
                        help='rotate poses by angle in degrees, offset',
                        type=float,
                        default=0.0)

    args = parser.parse_args()
    if not any([args.lidar, args.pose2d, args.pose3d, args.camera]):
        print("Available streams:")
        for stream in lookup_stream_names(args.logfile):
            print("  ", stream)
        return

    callback = None
    if args.callback is not None:
        callback = get_class_by_name(args.callback)

    filename = os.path.basename(args.logfile)
    g_rotation_offset_rad = math.radians(args.rotate)
    if args.legacy:
        lidarview(scans_gen_legacy(args.logfile),
                  caption_filename=filename,
                  callback=callback)
    else:
        with Framer(args.logfile,
                    lidar_name=args.lidar,
                    pose2d_name=args.pose2d,
                    pose3d_name=args.pose3d,
                    camera_name=args.camera) as framer:
            lidarview(framer, caption_filename=filename, callback=callback)
Exemplo n.º 7
0
    def __init__(self, config, logger):
        self.stop_requested = threading.Event()
        self.sigint_received = False
        self.modules = {}

        self.bus = Bus(logger)
        for module_name, module_config in config['modules'].items():
            klass = get_class_by_name(module_config['driver'])
            self.modules[module_name] = klass(module_config['init'],
                                              bus=self.bus.handle(module_name))

        for sender, receiver in config['links']:
            self.bus.connect(sender, receiver, self.modules)

        signal.signal(signal.SIGINT, self.request_stop)
Exemplo n.º 8
0
def main(args_in=None, startswith=None):
    import argparse
    import os.path
    global g_rotation_offset_rad, g_lidar_fov_deg, MAX_SCAN_LIMIT, WINDOW_SIZE

    parser = argparse.ArgumentParser(description='View lidar scans')
    parser.add_argument('logfile', help='recorded log file')

    parser.add_argument('--lidar', help='stream ID')
    parser.add_argument('--lidar2', help='stream ID of second lidar (back or slope)')
    parser.add_argument('--lidar-limit', help='display scan limit in millimeters',
                        type=int, default=MAX_SCAN_LIMIT)
    pose = parser.add_mutually_exclusive_group()
    pose.add_argument('--pose2d', help='stream ID for pose2d messages')
    pose.add_argument('--pose3d', help='stream ID for pose3d messages')

    parser.add_argument('--camera', help='stream ID for JPEG images')
    parser.add_argument('--camera2', help='stream ID for 2nd JPEG images')
    parser.add_argument('--bbox', help='stream ID for detection bounding box')

    parser.add_argument('--joint', help='stream ID joint angle for articulated robots (Kloubak)')

    parser.add_argument('--keyframes', help='stream ID typically for artifacts detection')
    parser.add_argument('--title', help='stream ID of data to be displayed in title')

    parser.add_argument('--window-size', help='set window size in pixels', type=int, nargs=2)

    parser.add_argument('--callback', help='callback function for lidar scans')

    parser.add_argument('--rotate', help='rotate poses by angle in degrees, offset',
                        type=float, default=0.0)

    parser.add_argument('--deg', help='lidar field of view in degrees',
                        type=float, default=270)

    parser.add_argument('--jump', '-j', help='jump to given time in seconds', type=int)

    parser.add_argument('--create-video', help='filename of output video')

    args = parser.parse_args(args_in)

    p = pathlib.Path(args.logfile)
    if p.is_dir():
        if startswith is not None:
            g = iter(child for child in p.iterdir() if child.name.startswith(startswith))
        else:
            g = p.iterdir()
        args.logfile = max(g, key=lambda a: a.stat().st_mtime)
        print(args.logfile)

    if not any([args.lidar, args.pose2d, args.pose3d, args.camera]):
        print("Available streams:")
        for stream in lookup_stream_names(args.logfile):
            print("  ", stream)
        return

    callback = None
    if args.callback is not None:
        callback = get_class_by_name(args.callback)

    if args.lidar_limit is not None:
        MAX_SCAN_LIMIT = args.lidar_limit
    if args.window_size is not None:
        WINDOW_SIZE = args.window_size

    filename = os.path.basename(args.logfile)
    g_rotation_offset_rad = math.radians(args.rotate)
    g_lidar_fov_deg = args.deg
    with Framer(args.logfile, lidar_name=args.lidar, lidar2_name=args.lidar2, pose2d_name=args.pose2d, pose3d_name=args.pose3d,
                camera_name=args.camera, camera2_name=args.camera2, bbox_name=args.bbox, joint_name=args.joint,
                keyframes_name=args.keyframes, title_name=args.title) as framer:
        lidarview(framer, caption_filename=filename, callback=callback, out_video=args.create_video, jump=args.jump)