Beispiel #1
0
def initialiseFromConfig(config, send_queues, recv_queues):
    from collections import defaultdict
    from ev3sim.robot import initialise_bot, RobotInteractor

    ev3sim.visual.utils.GLOBAL_COLOURS = config.get("colours", {})
    # Keep track of index w.r.t. filename.
    robot_paths = defaultdict(lambda: 0)
    for index, robot in enumerate(config.get("robots", [])):
        robot_path = find_abs(robot, allowed_areas=bot_locations())
        initialise_bot(config, robot_path, f"Robot-{index}",
                       robot_paths[robot_path])
        robot_paths[robot_path] += 1
        ScriptLoader.instance.setRobotQueues(f"Robot-{index}",
                                             send_queues[index],
                                             recv_queues[index])
    for opt in config.get("interactors", []):
        try:
            ScriptLoader.instance.addActiveScript(fromOptions(opt))
        except Exception as exc:
            print(
                f"Failed to load interactor with the following options: {opt}. Got error: {exc}"
            )
    SettingsManager.instance.setMany(config["settings"])
    if ScriptLoader.instance.active_scripts:
        ScriptLoader.instance.startUp()
        ScriptLoader.instance.loadElements(config.get("elements", []))
        for interactor in ScriptLoader.instance.active_scripts:
            if isinstance(interactor, RobotInteractor):
                interactor.connectDevices()
        for interactor in ScriptLoader.instance.active_scripts:
            interactor.startUp()
    else:
        print("No interactors successfully loaded. Quitting...")
Beispiel #2
0
def runFromConfig(config, shared):
    from ev3sim.robot import initialise_bot, RobotInteractor
    from ev3sim.file_helper import find_abs

    sl = ScriptLoader(**config.get("loader", {}))
    sl.setSharedData(shared)
    sl.active_scripts = []
    ev3sim.visual.utils.GLOBAL_COLOURS = config.get("colours", {})
    for index, robot in enumerate(config.get("robots", [])):
        robot_path = find_abs(robot,
                              allowed_areas=[
                                  "local", "local/robots/", "package",
                                  "package/robots/"
                              ])
        initialise_bot(config, robot_path, f"Robot-{index}")
    for opt in config.get("interactors", []):
        try:
            sl.active_scripts.append(fromOptions(opt))
        except Exception as exc:
            print(
                f"Failed to load interactor with the following options: {opt}. Got error: {exc}"
            )
    if sl.active_scripts:
        sl.startUp(**config.get("screen", {}))
        sl.loadElements(config.get("elements", []))
        for interactor in sl.active_scripts:
            if isinstance(interactor, RobotInteractor):
                interactor.connectDevices()
        sl.simulate()
    else:
        print("No interactors successfully loaded. Quitting...")
Beispiel #3
0
def initialise_device(deviceData, parentObj, index, preview_mode=False):
    classes = find_abs("devices/classes.yaml")
    devices = yaml.safe_load(open(classes, "r"))
    name = deviceData["name"]
    if name not in devices:
        raise ValueError(f"Unknown device type {name}")
    fname = find_abs(devices[name], allowed_areas=device_locations())
    with open(fname, "r") as f:
        try:
            config = yaml.safe_load(f)
            utils.GLOBAL_COLOURS.update(config.get("colours", {}))
            mname, cname = config["class"].rsplit(".", 1)
            import importlib

            klass = getattr(importlib.import_module(mname), cname)
            relative_location = deviceData.get("position", [0, 0])
            relative_rotation = deviceData.get("rotation", 0) * np.pi / 180
            device = klass(parentObj, relative_location, relative_rotation)
            for i, opt in enumerate(config.get("interactors", [])):
                res = opt.get("kwargs", {})
                res.update({
                    "device": device,
                    "parent": parentObj,
                    "relative_location": relative_location,
                    "relative_rotation": relative_rotation,
                    "device_index": index,
                    "single_device_index": i,
                    "port": deviceData["port"],
                    "zPos": deviceData.get("zPos", 0),
                })
                if preview_mode:
                    for i in range(len(res.get("elements", []))):
                        res["elements"][i]["physics"] = True
                opt["kwargs"] = res
                interactor = fromOptions(opt)
                if not hasattr(parentObj, "device_interactors"):
                    parentObj.device_interactors = []
                parentObj.device_interactors.append(interactor)
                ScriptLoader.instance.addActiveScript(interactor)
        except yaml.YAMLError as exc:
            print(
                f"An error occurred while loading devices. Exited with error: {exc}"
            )
Beispiel #4
0
def initialise_device(deviceData, parentObj, index):
    classes = find_abs('devices/classes.yaml')
    devices = yaml.safe_load(open(classes, 'r'))
    name = deviceData['name']
    if name not in devices:
        raise ValueError(f"Unknown device type {name}")
    fname = find_abs(devices[name],
                     allowed_areas=['local/devices/', 'package/devices/'])
    with open(fname, 'r') as f:
        try:
            config = yaml.safe_load(f)
            utils.GLOBAL_COLOURS.update(config.get('colours', {}))
            mname, cname = config['class'].rsplit('.', 1)
            import importlib
            klass = getattr(importlib.import_module(mname), cname)
            relative_location = deviceData.get('position', [0, 0])
            relative_rotation = deviceData.get('rotation', 0) * np.pi / 180
            device = klass(parentObj, relative_location, relative_rotation)
            for i, opt in enumerate(config.get('interactors', [])):
                res = opt.get('kwargs', {})
                res.update({
                    'device': device,
                    'parent': parentObj,
                    'relative_location': relative_location,
                    'relative_rotation': relative_rotation,
                    'device_index': index,
                    'single_device_index': i,
                    'port': deviceData['port'],
                })
                opt['kwargs'] = res
                interactor = fromOptions(opt)
                if not hasattr(parentObj, 'device_interactors'):
                    parentObj.device_interactors = []
                parentObj.device_interactors.append(interactor)
                # Device interactors always act first.
                ScriptLoader.instance.active_scripts.insert(0, interactor)
        except yaml.YAMLError as exc:
            print(
                f"An error occured while loading devices. Exited with error: {exc}"
            )