Exemple #1
0
    def launch_process(self, peer, launch_data, restore_config=[]):
        data = launch_data
        wait = 0
        p = os.path.expanduser(data['path'])
        if not os.path.isabs(p):
            path = os.path.join(launcher_tools.obci_root(), p)
            path = os.path.abspath(path)
        else:
            path = os.path.realpath(p)

        dirname = os.path.dirname(path)
        if not launcher_tools.obci_root() in dirname:
            launcher_tools.update_pythonpath(dirname)
            launcher_tools.update_obci_syspath(dirname)
            self.env.update({"PYTHONPATH" : os.environ["PYTHONPATH"]})

            self.logger.info("PYTHONPATH UPDATED  for " + peer +\
                     "!!!!!!!!   " + str(self.env["PYTHONPATH"]))
        args = data['args']
        args = self._attach_base_config_path(path, args)
        args += ['-p', 'experiment_uuid', self.experiment_uuid]
        if peer.startswith('config_server'):
            args += ['-p', 'launcher_socket_addr', self.cs_addr]

            if restore_config:
                args += ['-p', 'restore_peers', ' '.join(restore_config)]
            # wait = 0.5
        if "log_dir" in args:
            idx = args.index("log_dir") + 1
            log_dir = args[idx]
            log_dir = os.path.join(log_dir, self.name)
            args[idx] = log_dir
        else:
            log_dir = os.path.join(CONFIG_DEFAULTS["log_dir"], self.name)
            args += ['-p', 'log_dir', log_dir]
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        proc, details = self._launch_process(path, args, data['peer_type'],
                                                    peer, env=self.env, capture_io=NO_STDIO)
        info_obj = {
            "path": path,
            "args": args,
            "peer": peer
        }
        if proc is not None:
            self.processes[peer] = proc
        else:
            self.logger.error("OBCI LAUNCH FAILED")
            send_msg(self._publish_socket, self.mtool.fill_msg("obci_launch_failed",
                                                    machine=self.machine, path=info_obj['path'],
                                                    args=info_obj['args'], details=details))
            self.processes = {}
            self.subprocess_mgr.killall(force=True)

        return proc, details, wait, info_obj
Exemple #2
0
    def get_run_args(self,multiplexer_address):
        host,port=multiplexer_address

        exe=self.config.get_param('driver_executable')
        exe=os.path.join(obci_root(), exe)
        print exe
        args = [exe, '-v', self.config.get_param('samples_per_packet')]

        if port:
            args += ["-h",str(host),'-p',str(port)]

        if self.config.has_param("usb_device") and self.config.has_param("bluetooth_device"):
            usb = self.config.get_param("usb_device")
            if usb:
                args.extend(["-d", usb])
            elif self.config.get_param("bluetooth_device"):
                args.extend(["-b", self.config.get_param("bluetooth_device")])
            else:
                raise Exception("usb_device or bluetooth_device is required")

        if self.config.has_param("amplifier_responses"):
            if self.config.get_param("amplifier_responses"):
                args.extend(["-r", self.config.get_param("amplifier_responses")])
        if self.config.has_param("dump_responses"):
            if self.config.get_param("dump_responses"):
                args.extend(["--save_responses", self.config.get_param("dump_responses")])

        #FIXME FIXME
        if "gtec" in exe:
            args.extend(["-d", os.path.join(os.path.dirname(exe), "simple_gtec_driver")])
        return args
    def __init__(self, obci_client, server_ip=None, presets=None):
        super(OBCILauncherEngine, self).__init__()
        self.logger = get_logger('launcherGUIEngine', obci_peer=self)
        self.server_ip = server_ip
        self.client = obci_client
        self.ctx = obci_client.ctx

        self.mtool = self.client.mtool
        self.mtool.add_templates(self.internal_msg_templates)

        self._cached_nearby_machines = {}
        if presets:
            self.preset_path = os.path.join(
                launcher_tools.obci_root(), ''.join(['control/gui/presets/', presets, '.ini']))
        else:
            self.preset_path = os.path.join(launcher_tools.obci_root(), PRESETS)
        self.user_preset_path = USER_PRESETS

        # create home preset directory if it does not exists
        preset_dir = os.path.basename(self.user_preset_path)
        if not os.path.exists(os.path.expanduser(preset_dir)):
            os.makedirs(preset_dir)

        self.experiments = self.prepare_experiments()

        self.obci_poller = zmq.Poller()

        self.monitor_push = self.ctx.socket(zmq.PUSH)
        self.monitor_addr = 'inproc://obci_monitor' + str(uuid.uuid4())[:4]
        self.monitor_push.bind(self.monitor_addr)

        self._stop_monitoring = False
        srv_addr = 'tcp://' + server_ip + ':' + net.server_pub_port() if server_ip else None
        self.obci_monitor_thr = threading.Thread(target=self.obci_monitor,
                                                 args=[self.ctx, self.monitor_addr,
                                                       srv_addr])
        self.obci_monitor_thr.daemon = True
        self.obci_monitor_thr.start()

        self.obci_state_change.connect(self.handle_obci_state_change)

        for exp in self.experiments:
            if exp.launcher_data is not None:
                self._exp_connect(exp.launcher_data)

        self.details_mode = MODE_ADVANCED
    def __init__(self, obci_client, server_ip=None, presets=None):
        super(OBCILauncherEngine, self).__init__()
        self.logger = get_logger('launcherGUIEngine', obci_peer=self)
        self.server_ip = server_ip
        self.client = obci_client
        self.ctx = obci_client.ctx

        self.mtool = self.client.mtool
        self.mtool.add_templates(self.internal_msg_templates)

        self._cached_nearby_machines = {}
        if presets:
            self.preset_path = os.path.join(launcher_tools.obci_root(), ''.join(['control/gui/presets/', presets, '.ini']))
        else:
            self.preset_path = os.path.join(launcher_tools.obci_root(), PRESETS)
        self.user_preset_path = USER_PRESETS

        # create home preset directory if it does not exists
        preset_dir = os.path.basename(self.user_preset_path)
        if not os.path.exists(os.path.expanduser(preset_dir)):
            os.makedirs(preset_dir)

        self.experiments = self.prepare_experiments()

        self.obci_poller = zmq.Poller()

        self.monitor_push = self.ctx.socket(zmq.PUSH)
        self.monitor_addr = 'inproc://obci_monitor' + str(uuid.uuid4())[:4]
        self.monitor_push.bind(self.monitor_addr)

        self._stop_monitoring = False
        srv_addr = 'tcp://' + server_ip + ':' + net.server_pub_port() if server_ip else None
        self.obci_monitor_thr = threading.Thread(target=self.obci_monitor,
                                                 args=[self.ctx, self.monitor_addr,
                                                       srv_addr])
        self.obci_monitor_thr.daemon = True
        self.obci_monitor_thr.start()

        self.obci_state_change.connect(self.handle_obci_state_change)

        for exp in self.experiments:
            if exp.launcher_data is not None:
                self._exp_connect(exp.launcher_data)

        self.details_mode = MODE_ADVANCED
Exemple #5
0
    def __init__(self):
        self.number_of_decisions = 8
        self.number_of_states = 1

        # A list of all configs defined for every single state.
        self.states_configs = [
            'state', 'letters', 'actions', 'letters_solver', 'actions_solver'
        ]

        # A list of all configs defined as globals,
        # not assigned to any particular state.
        self.other_configs = []
        tahoe_path = os.path.join(obci_root(), 'devices', 'tahoe_http.py')

        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # !!! Only keys defined in states_configs and other_configs
        # will be visible in your application.!!!
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        # States transition matrix
        self.state = self.number_of_states * [self.number_of_decisions * [0]]
        self.state[0] = [0, 0, 0, 0, 0, 0, 0, 0]

        # Letters definition for every state. Normally for every state it should be a collection of strings.
        self.letters = self.number_of_states * [
            self.number_of_decisions * [""]
        ]
        self.letters[0] = [[u"Lamp(off)", u"Lampa(on)"],
                           [u"Muzyka(off)", u"Muzyka(on)"], '', '', '', '', '',
                           u'Koniec']
        self.letters_solver = self.number_of_states * [
            self.number_of_decisions * [""]
        ]
        self.letters_solver[0] = [
            'solve(0)', 'solve(1)', '', '', '', '', '', ''
        ]

        self.actions = self.number_of_states * [
            self.number_of_decisions * [""]
        ]

        self.actions[0] = [[
            'run_ext(\'' + tahoe_path + '  on 1\')',
            'run_ext(\'' + tahoe_path + '  off 1\')'
        ],
                           [
                               'run_ext(\'' + tahoe_path + '  on 2\')',
                               'run_ext(\'' + tahoe_path + '  off 2\')'
                           ], '', '', '', '', '',
                           self._finish_action()]

        self.actions_solver = self.number_of_states * [
            self.number_of_decisions * [""]
        ]
        self.actions_solver[0] = [
            'solve(0)', 'solve(1)', '', '', '', '', '', ''
        ]
Exemple #6
0
 def _process_experiment_scenario(self, json_scenario):
     jsonpar = launch_file_parser.LaunchJSONParser(
         launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
     inbuf = io.BytesIO(json_scenario.encode('utf-8'))
     jsonpar.parse(inbuf, self.exp_config)
     print "MY PEEEEERS:", self.exp_config.peers.keys()
     rd, details = self.exp_config.config_ready()
     if rd:
         self.status.set_status(launcher_tools.READY_TO_LAUNCH)
     else:
         self.status.set_status(launcher_tools.NOT_READY, details=details)
         print rd, details
     return True, None
    def get_run_args(self,multiplexer_address):

        host,port=multiplexer_address
        exe=self.config.get_param('driver_executable')
        exe = os.path.join(obci_root(), exe)
        v=self.config.get_param('samples_per_packet')
        args=[exe,"-h",str(host),'-p',str(port),'-v',v]

        # if self.config.get_param("amplifier_responses"):
        #     args.extend(["-r", self.config.get_param("amplifier_responses")])
        # if self.config.get_param("dump_responses"):
        #     args.extend(["--save_responses", self.config.get_param("dump_responses")])
        return args
 def _process_experiment_scenario(self, json_scenario):
     jsonpar = launch_file_parser.LaunchJSONParser(
                     launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
     inbuf = io.BytesIO(json_scenario.encode('utf-8'))
     jsonpar.parse(inbuf, self.exp_config)
     print "MY PEEEEERS:", self.exp_config.peers.keys()
     rd, details = self.exp_config.config_ready()
     if rd:
         self.status.set_status(launcher_tools.READY_TO_LAUNCH)
     else:
         self.status.set_status(launcher_tools.NOT_READY, details=details)
         print rd, details
     return True, None
Exemple #9
0
    def get_run_args(self, multiplexer_address):

        host,port = multiplexer_address
        exe = self.config.get_param('driver_executable')
        exe = os.path.join(obci_root(), exe)
        v = self.config.get_param('samples_per_packet')
        simple_driver = os.path.join(os.path.dirname(exe), "simple_gtec_driver")
        rate = int(float(self.config.get_param('sampling_rate')))
        channels = self.config.get_param('active_channels')
        device_no = self.config.get_param('device_index')
        args = [exe, "-h" , str(host), '-p', str(port), '-v', v, "-d", simple_driver,
                    '-s', str(rate), '-c', channels, '-i', device_no]
	self.logger.info("ARGUMENTS: "+ str(args))
        return args
Exemple #10
0
    def __init__(self):
        self.number_of_decisions = 8
        self.number_of_states = 1

        # A list of all configs defined for every single state.
        self.states_configs = ['state', 'letters', 'actions', 'letters_solver', 'actions_solver']

        # A list of all configs defined as globals,
        # not assigned to any particular state.
        self.other_configs = []
        tahoe_path = os.path.join(obci_root(), 'devices', 'tahoe_http.py')

        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # !!! Only keys defined in states_configs and other_configs
        # will be visible in your application.!!!
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        # States transition matrix
        self.state = self.number_of_states * [self.number_of_decisions * [0]]
        self.state[0] = [0, 0, 0, 0, 0, 0, 0, 0]

        # Letters definition for every state. Normally for every state it should be a collection of strings.
        self.letters = self.number_of_states * [self.number_of_decisions * [""]]
        self.letters[0] = [
            [u"Lamp(off)", u"Lampa(on)"],
            [u"Muzyka(off)", u"Muzyka(on)"],
            '', '',
            '', '', '', u'Koniec']
        self.letters_solver = self.number_of_states * [self.number_of_decisions * [""]]
        self.letters_solver[0] = [
            'solve(0)', 'solve(1)',
            '', '',
            '', '', '', '']

        self.actions = self.number_of_states * [self.number_of_decisions * [""]]

        self.actions[0] = [
            ['run_ext(\''+tahoe_path+'  on 1\')', 'run_ext(\''+tahoe_path+'  off 1\')'],
            ['run_ext(\''+tahoe_path+'  on 2\')', 'run_ext(\''+tahoe_path+'  off 2\')'],
            '', '',
            '', '', '', self._finish_action()]

        self.actions_solver = self.number_of_states * [self.number_of_decisions * [""]]
        self.actions_solver[0] = [
            'solve(0)', 'solve(1)',
            '', '',
            '', '', '', '']
Exemple #11
0
    def _launch_processes(self, launch_data, restore_config=[]):
        proc, details = None, None
        success = True
        path, args = None, None

        self.status = launcher_tools.LAUNCHING

        ldata = []
        if 'config_server' in launch_data:
            ldata.append(('config_server', launch_data['config_server']))
        if 'amplifier' in launch_data:
            ldata.append(('amplifier', launch_data['amplifier']))
        for peer, data in launch_data.items():
            if (peer, data) not in ldata:
                ldata.append((peer, data))

        for peer, data in ldata:  # self.launch_data.iteritems():
            wait = 0
            if peer.startswith('mx'):
                continue
            path = os.path.join(launcher_tools.obci_root(), data['path'])
            args = data['args']
            if peer.startswith('config_server'):
                args += ['-p', 'launcher_socket_addr', self.cs_addr]
                args += ['-p', 'experiment_uuid', self.experiment_uuid]

                if restore_config:
                    args += ['-p', 'restore_peers', ' '.join(restore_config)]
                wait = 0.4
            proc, details = self._launch_process(path, args, data['peer_type'],
                                                 peer, env=self.env, capture_io=NO_STDIO)
            if proc is not None:
                self.processes[peer] = proc
            else:
                success = False
                break
            time.sleep(wait)
        if success:
            send_msg(self._publish_socket, self.mtool.fill_msg("all_peers_launched",
                                                               machine=self.machine))
        else:
            print(self.name, '[', self.type, ']', "OBCI LAUNCH FAILED")
            send_msg(self._publish_socket, self.mtool.fill_msg("obci_launch_failed",
                                                               machine=self.machine, path=path,
                                                               args=args, details=details))
            self.processes = {}
            self.subprocess_mgr.killall()
Exemple #12
0
    def _launch_processes(self, launch_data, restore_config=[]):
        proc, details = None, None
        success = True
        path, args = None, None

        self.status = launcher_tools.LAUNCHING

        ldata = []
        if 'config_server' in launch_data:
            ldata.append(('config_server', launch_data['config_server']))
        if 'amplifier' in launch_data:
            ldata.append(('amplifier', launch_data['amplifier']))
        for peer, data in launch_data.iteritems():
            if (peer, data) not in ldata:
                ldata.append((peer, data))

        for peer, data in ldata:#self.launch_data.iteritems():
            wait = 0
            if peer.startswith('mx'):
                continue
            path = os.path.join(launcher_tools.obci_root(), data['path'])
            args = data['args']
            if peer.startswith('config_server'):
                args += ['-p', 'launcher_socket_addr', self.cs_addr]
                args += ['-p', 'experiment_uuid', self.experiment_uuid]
                
                if restore_config:
                    args += ['-p', 'restore_peers', ' '.join(restore_config)]
                wait = 0.4
            proc, details = self._launch_process(path, args, data['peer_type'],
                                                        peer, env=self.env, capture_io=NO_STDIO)
            if proc is not None:
                self.processes[peer] = proc
            else:
                success = False
                break
            time.sleep(wait)
        if success:
            send_msg(self._publish_socket, self.mtool.fill_msg("all_peers_launched",
                                                    machine=self.machine))
        else:
            print self.name,'[', self.type, ']', "OBCI LAUNCH FAILED"
            send_msg(self._publish_socket, self.mtool.fill_msg("obci_launch_failed",
                                                    machine=self.machine, path=path,
                                                    args=args, details=details))
            self.processes = {}
            self.subprocess_mgr.killall()
    def _launch_processes(self, launch_data, restore_config=[]):
        proc, details = None, None
        success = True
        path, args = None, None

        self.status = launcher_tools.LAUNCHING

        ldata = []
        if "config_server" in launch_data:
            ldata.append(("config_server", launch_data["config_server"]))
        if "amplifier" in launch_data:
            ldata.append(("amplifier", launch_data["amplifier"]))
        for peer, data in launch_data.iteritems():
            if (peer, data) not in ldata:
                ldata.append((peer, data))

        for peer, data in ldata:  # self.launch_data.iteritems():
            wait = 0
            if peer.startswith("mx"):
                continue
            path = os.path.join(launcher_tools.obci_root(), data["path"])
            args = data["args"]
            if peer.startswith("config_server"):
                args += ["-p", "launcher_socket_addr", self.cs_addr]
                args += ["-p", "experiment_uuid", self.experiment_uuid]

                if restore_config:
                    args += ["-p", "restore_peers", " ".join(restore_config)]
                wait = 0.4
            proc, details = self._launch_process(path, args, data["peer_type"], peer, env=self.env, capture_io=NO_STDIO)
            if proc is not None:
                self.processes[peer] = proc
            else:
                success = False
                break
            time.sleep(wait)
        if success:
            send_msg(self._publish_socket, self.mtool.fill_msg("all_peers_launched", machine=self.machine))
        else:
            print self.name, "[", self.type, "]", "OBCI LAUNCH FAILED"
            send_msg(
                self._publish_socket,
                self.mtool.fill_msg("obci_launch_failed", machine=self.machine, path=path, args=args, details=details),
            )
            self.processes = {}
            self.subprocess_mgr.killall()
Exemple #14
0
    def get_run_args(self, multiplexer_address):

        host, port = multiplexer_address
        exe = self.config.get_param('driver_executable')
        exe = os.path.join(obci_root(), exe)
        v = self.config.get_param('samples_per_packet')
        simple_driver = os.path.join(os.path.dirname(exe),
                                     "simple_gtec_driver")
        rate = int(float(self.config.get_param('sampling_rate')))
        channels = self.config.get_param('active_channels')
        device_no = self.config.get_param('device_index')
        args = [
            exe, "-h",
            str(host), '-p',
            str(port), '-v', v, "-d", simple_driver, '-s',
            str(rate), '-c', channels, '-i', device_no
        ]
        self.logger.info("ARGUMENTS: " + str(args))
        return args
Exemple #15
0
    def get_run_args(self, multiplexer_address):
        host, port = multiplexer_address

        exe = self.config.get_param('driver_executable')
        exe = os.path.join(obci_root(), exe)
        print exe
        args = [exe, '-v', self.config.get_param('samples_per_packet')]

        if port:
            args += ["-h", str(host), '-p', str(port)]

        if self.config.has_param("usb_device") and self.config.has_param(
                "bluetooth_device"):
            usb = self.config.get_param("usb_device")
            if usb:
                args.extend(["-d", usb])
            elif self.config.get_param("bluetooth_device"):
                args.extend(["-b", self.config.get_param("bluetooth_device")])
            else:
                raise Exception("usb_device or bluetooth_device is required")

        if self.config.has_param("amplifier_responses"):
            if self.config.get_param("amplifier_responses"):
                args.extend(
                    ["-r", self.config.get_param("amplifier_responses")])
        if self.config.has_param("dump_responses"):
            if self.config.get_param("dump_responses"):
                args.extend([
                    "--save_responses",
                    self.config.get_param("dump_responses")
                ])

        #FIXME FIXME
        if "gtec" in exe:
            args.extend([
                "-d",
                os.path.join(os.path.dirname(exe), "simple_gtec_driver")
            ])
        return args
Exemple #16
0
    def make_experiment_config(self):
        launch_parser = launch_file_parser.LaunchFileParser(
            launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
        if not self.launch_file:
            return False, "Empty scenario."

        try:
            with open(launcher_tools.expand_path(self.launch_file)) as f:
                launch_parser.parse(f, self.exp_config, apply_globals=True)
        except Exception as e:
            self.status.set_status(launcher_tools.NOT_READY, details=str(e))
            print "config errror   ", str(e)
            return False, str(e)

        rd, details = self.exp_config.config_ready()
        if rd:
            self.status.set_status(launcher_tools.READY_TO_LAUNCH)
        else:
            self.status.set_status(launcher_tools.NOT_READY, details=details)
            print rd, details

        return True, None
    def make_experiment_config(self):
        launch_parser = launch_file_parser.LaunchFileParser(
                            launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
        if not self.launch_file:
            return False, "Empty scenario."

        try:
            with open(launcher_tools.expand_path(self.launch_file)) as f:
                launch_parser.parse(f, self.exp_config, apply_globals=True)
        except Exception as e:
            self.status.set_status(launcher_tools.NOT_READY, details=str(e))
            print "config errror   ", str(e)
            return False, str(e)

        rd, details = self.exp_config.config_ready()
        if rd:
            self.status.set_status(launcher_tools.READY_TO_LAUNCH)
        else:
            self.status.set_status(launcher_tools.NOT_READY, details=details)
            print rd, details

        return True, None
#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
import bluetooth
import os

from obci.control.launcher.launcher_tools import obci_root, READY_TO_LAUNCH

_DESC_BASE_PATH = os.path.join(obci_root(), 'drivers/eeg/driver_discovery')

_TYPES = ['Porti7', 'MobiMini', 'Mobi5']
_BT_DESCS = {
                'Porti7' : 'amplifier_porti7_bluetooth.json',
                'MobiMini' : 'amplifier_mobimini.json',
                'Mobi5' : 'amplifier_mobi5.json'
            }
_AMP_PEER = 'drivers/eeg/cpp_amplifiers/amplifier_tmsi.py'
_SCENARIO = 'scenarios/amplifier/tmsi_amp_signal.ini'

def _find_bluetooth_amps():
    try:
        nearby_devices = bluetooth.discover_devices(duration=3, lookup_names = True)
    except bluetooth.BluetoothError, e:
        print "ERROR:  ", str(e)
        nearby_devices = []

    found = []
    for addr, name in nearby_devices:
        is_amp, amp_type = _check_amp_name(name)
        if is_amp:
    def _launch_processes(self, launch_data, restore_config=[]):
        proc, details = None, None
        success = True
        path, args = None, None

        self.status = launcher_tools.LAUNCHING

        ldata = []
        if 'config_server' in launch_data:
            ldata.append(('config_server', launch_data['config_server']))
        if 'amplifier' in launch_data:
            ldata.append(('amplifier', launch_data['amplifier']))
        for peer, data in launch_data.iteritems():
            if (peer, data) not in ldata:
                ldata.append((peer, data))

        for peer, data in ldata:#self.launch_data.iteritems():
            wait = 0
            if peer.startswith('mx'):
                continue
            p = os.path.expanduser(data['path'])
            if not os.path.isabs(p):
                path = os.path.join(launcher_tools.obci_root(), p)
            else:
                path = os.path.realpath(p)

            dirname = os.path.dirname(path)
            if not launcher_tools.obci_root() in dirname:
                launcher_tools.update_pythonpath(dirname)
                launcher_tools.update_obci_syspath(dirname)
                self.env.update({"PYTHONPATH" : os.environ["PYTHONPATH"]})

                self.logger.info("PYTHONPATH UPDATED  for " + peer +\
                         "!!!!!!!!   " + str(self.env["PYTHONPATH"]))
            args = data['args']
            if peer.startswith('config_server'):
                args += ['-p', 'launcher_socket_addr', self.cs_addr]
                args += ['-p', 'experiment_uuid', self.experiment_uuid]

                if restore_config:
                    args += ['-p', 'restore_peers', ' '.join(restore_config)]
                wait = 0.4
            if "log_dir" in args:
                idx = args.index("log_dir") + 1
                log_dir = args[idx]
                log_dir = os.path.join(log_dir, self.name)
                args[idx] = log_dir
            else:
                log_dir = os.path.join(CONFIG_DEFAULTS["log_dir"], self.name)
                args += ['-p', 'log_dir', log_dir]
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)

            proc, details = self._launch_process(path, args, data['peer_type'],
                                                        peer, env=self.env, capture_io=NO_STDIO)
            if proc is not None:
                self.processes[peer] = proc
            else:
                success = False
                break
            time.sleep(wait)
        if success:
            send_msg(self._publish_socket, self.mtool.fill_msg("all_peers_launched",
                                                    machine=self.machine))
        else:
            self.logger.error("OBCI LAUNCH FAILED")
            send_msg(self._publish_socket, self.mtool.fill_msg("obci_launch_failed",
                                                    machine=self.machine, path=path,
                                                    args=args, details=details))
            self.processes = {}
            self.subprocess_mgr.killall(force=True)
Exemple #20
0
def restart_scenario(conn, new_scenario, comment="Wait...", leave_on=[], overwrites=[]):
	"""
	new_scenario: scenario_path relative to obci_root
	overwrites:   {'peer_id' : ['-p', 'param_name', 'param_value',
									'-p', 'etc', 'etc',
								'-f' 'config_ini_file_path_relative_to_obci_root']}

	leave_on:  ['list', 'of', 'peer_ids', 'which', 'are', 'in', 'both', 'scenarios',
					'and', 'we', 'do','not', 'want', 'them', 'to', 'restart']
	"""

	if new_scenario.startswith('/') or new_scenario.startswith('~'):
		new_scenario = os.path.expanduser(new_scenario)
	else:
		new_scenario = os.path.join(obci_root(), new_scenario)

	conf_msg = cmsg.fill_msg(types.GET_CONFIG_PARAMS,
				 sender='',
				 param_names=['experiment_uuid'],
				 receiver='config_server')

	try:
		reply = conn.query(message=conf_msg,
				   type=types.GET_CONFIG_PARAMS)
	except OperationFailed:
		print "OperationFailed (in restart_scenario) Could not connect to config server"
		reply = None
	except OperationTimedOut:
		print  "Operation timed out! (in restart_scenario) (could not connect to config server)"
		reply = None

	if reply == None:
		return

	if reply.type == types.CONFIG_ERROR:
		print "(in restart_scenario) could not acquire current experiment uuid"
		return

	elif reply.type == types.CONFIG_PARAMS:
		reply_msg = cmsg.unpack_msg(reply.type, reply.message)
		params = cmsg.params2dict(reply_msg)
		if not 'experiment_uuid' in params:
			print "no experiment_uuid!!!"
		else:
			uid = params['experiment_uuid']
			if not uid:
				print 'experiment uuid unset!!!'
			else:
				ovr_list = ['--ovr']

				for peer in overwrites:
					scan = overwrites[peer]
					params = overwrites[peer]
					cut = 0
					while scan:
						if '-f' in scan:
							ind = scan.index('-f')
							params[cut+ind+1] = os.path.join(params[cut+ind+1])
							cut = cut+ind+1
							scan = params[cut:]
						else: break

					# for i in range(len(params)):
					# 	params[i] = params[i].replace(" ", "\ ")
					# 	print params[i]


					ovr_list += ['--peer', peer]
					ovr_list += params

				# leave_on_str = '' if not leave_on else ' --leave_on ' + ' '.join(leave_on)
				# overwr_str = '' if not overwrites else ' '.join(ovr_list)
				# command = "sleep 0.5 && obci morph " + str(uid) + " " + new_scenario + \
				# 		" " + leave_on_str  + overwr_str + " &"
				obci_call = ["obci"]
				try:
					subprocess.call(obci_call)
				except: # (OSError, WindowsError) can't call launcher like that
					obci_call = ["python", os.path.join(obci_root(), "control", "launcher", "obci_script.py")]

				subpr_call = obci_call + ['morph', str(uid), new_scenario, '--leave_on'] + leave_on + ovr_list
				print "---------------\n", subpr_call, "\n--------------"
				subprocess.call(subpr_call)
Exemple #21
0
def get_file_path(dir_name, file_name):
    if not os.path.isabs(os.path.expanduser(dir_name)) and len(dir_name) != 0:
        dir_name = os.path.normpath(os.path.join(obci_root(), dir_name))
    return os.path.expanduser(os.path.normpath(os.path.join(os.path.normpath(dir_name), file_name)))
#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
import os

from obci.control.launcher.launcher_tools import obci_root, READY_TO_LAUNCH
from obci.control.peer.peer_config import PeerConfig
from obci.drivers.eeg.driver_comm import DriverComm

_DESC_BASE_PATH = os.path.join(obci_root(), 'drivers/eeg/driver_discovery')

_TYPES = ['Porti7']

_USB_DESCS = {
    'Porti7': 'amplifier_porti7_usb.json',
    'SynFi': 'amplifier_tmsi_synfi.json'
}
_AMP_PEER = 'drivers/eeg/cpp_amplifiers/amplifier_tmsi.py'
_AMP_EXECUTABLE = 'drivers/eeg/cpp_amplifiers/tmsi_amplifier'
_SCENARIO = 'scenarios/amplifier/tmsi_amp_signal.ini'


def _find_usb_amps():
    dev_path = os.path.realpath('/dev')
    amps = [dev for dev in os.listdir(dev_path) if\
                dev.startswith('fusbi')]

    synfi_amps = [dev for dev in os.listdir(dev_path) if\
                dev.startswith('synfi')]
    amps = [os.path.join(dev_path, dev) for dev in amps]
Exemple #23
0
def get_file_path(dir_name, file_name):
    if not os.path.isabs(os.path.expanduser(dir_name)) and len(dir_name) != 0:
        dir_name = os.path.normpath(os.path.join(obci_root(), dir_name))
    return os.path.expanduser(os.path.normpath(os.path.join(os.path.normpath(dir_name), file_name)))
Exemple #24
0
    def _save(self, p_file_obj, dump_dir=None):
        json.dump(self.dic, p_file_obj)

def serialize_scenario_json(p_system_config):
    buf = io.BytesIO()
    ser = LaunchFileSerializerJSON()
    ser.serialize(p_system_config, None, buf)
    return unicode(buf.getvalue())

if __name__ == '__main__':
    import launch_file_parser
    import system_config

    launch_parser = launch_file_parser.LaunchFileParser(
                            launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
    config = system_config.OBCIExperimentConfig()
    status = launcher_tools.ExperimentStatus()
    with open(launcher_tools.expand_path('scenarios/cebit/switch/hci_switch_mult_dummy.ini')) as f:
        launch_parser.parse(f, config)
    rd, details = config.config_ready()
    print rd, details
    print "INFO A"
    print config.all_param_values('amplifier')
    print "\n *********************************\n"
    json_ser = serialize_scenario_json(config)
    print json_ser

    jsonpar = launch_file_parser.LaunchJSONParser(
                        launcher_tools.obci_root(), settings.DEFAULT_SCENARIO_DIR)
    inbuf = io.BytesIO(json_ser.encode(encoding='utf-8'))
Exemple #25
0
def restart_scenario(conn, new_scenario, comment="Wait...", leave_on=[], overwrites=[]):
	"""
	new_scenario: scenario_path relative to obci_root
	overwrites:   {'peer_id' : ['-p', 'param_name', 'param_value', 
									'-p', 'etc', 'etc',
								'-f' 'config_ini_file_path_relative_to_obci_root']}

	leave_on:  ['list', 'of', 'peer_ids', 'which', 'are', 'in', 'both', 'scenarios',
					'and', 'we', 'do','not', 'want', 'them', 'to', 'restart']
	"""

	if new_scenario.startswith('/') or new_scenario.startswith('~'):
		new_scenario = os.path.expanduser(new_scenario)
	else:
		new_scenario = os.path.join(obci_root(), new_scenario)

	conf_msg = cmsg.fill_msg(types.GET_CONFIG_PARAMS,
				 sender='',
				 param_names=['experiment_uuid'],
				 receiver='config_server')

	try:
		reply = conn.query(message=conf_msg,
				   type=types.GET_CONFIG_PARAMS)
	except OperationFailed:
		print "OperationFailed (in restart_scenario) Could not connect to config server"
		reply = None
	except OperationTimedOut:
		print  "Operation timed out! (in restart_scenario) (could not connect to config server)"
		reply = None

	if reply == None:
		return

	if reply.type == types.CONFIG_ERROR:
		print "(in restart_scenario) could not acquire current experiment uuid"
		return

	elif reply.type == types.CONFIG_PARAMS:
		reply_msg = cmsg.unpack_msg(reply.type, reply.message)
		params = cmsg.params2dict(reply_msg)
		if not 'experiment_uuid' in params:
			print "no experiment_uuid!!!"
		else:
			uid = params['experiment_uuid']
			if not uid:
				print 'experiment uuid unset!!!'
			else:
				ovr_list = ['--ovr']

				for peer in overwrites:
					scan = overwrites[peer]
					params = overwrites[peer]
					cut = 0
					while scan:
						if '-f' in scan:
							ind = scan.index('-f')
							params[cut+ind+1] = os.path.join(obci_root(), params[cut+ind+1])
							cut = cut+ind+1
							scan = params[cut:]
						else: break

					# for i in range(len(params)):
					# 	params[i] = params[i].replace(" ", "\ ")
					# 	print params[i]


					ovr_list += ['--peer', peer]
					ovr_list += params

				# leave_on_str = '' if not leave_on else ' --leave_on ' + ' '.join(leave_on)
				# overwr_str = '' if not overwrites else ' '.join(ovr_list)
				# command = "sleep 0.5 && obci morph " + str(uid) + " " + new_scenario + \
				# 		" " + leave_on_str  + overwr_str + " &"
				

				subpr_call = ['obci', 'morph', str(uid), new_scenario, '--leave_on'] + leave_on + ovr_list
				print "---------------\n", subpr_call, "\n--------------"
				subprocess.call(subpr_call)