Exemplo n.º 1
0
    def __init__(self, addresses, type=None, external_config_file=None):
        super(ConfiguredMultiplexerServer, self).__init__(addresses, type)

        self.ready_to_work = False
        self.external_config_file = external_config_file
        self.config = PeerControl(peer=self)

        self.logger = get_logger(self.config.peer_id,
                            file_level=self.get_param('file_log_level'),
                            stream_level=self.get_param('console_log_level'),
                            mx_level=self.get_param('mx_log_level'),
                            sentry_level=self.get_param('sentry_log_level'),
                            conn=self.conn,
                            log_dir=self.get_param('log_dir'),
                            obci_peer=self)
        self.config.logger = self.logger

        self.config.connection = self.conn
        self.config.peer_validate_params = self.validate_params
        self.config.peer_params_changed = self.params_changed

        result, details = self.config.initialize_config(self.conn)


        if not result:
            self.bad_initialization_result(result, details)
        else:
            self.validate_params(self.config.param_values())
Exemplo n.º 2
0
    def __init__(self, addresses, type, external_config_file=None):

        self.conn = connect_client(addresses=addresses, type=type)
        self.ready_to_work = False
        self.external_config_file = external_config_file
        self.config = PeerControl(peer=self)

        self.logger = get_logger(self.config.peer_id,
                            file_level=self.get_param('file_log_level'),
                            stream_level=self.get_param('console_log_level'),
                            mx_level=self.get_param('mx_log_level'),
                            conn=self.conn,
                            log_dir=self.get_param('log_dir'))
        self.config.logger = self.logger

        self.config.connection = self.conn
        self.config.peer_validate_params = self.validate_params
        self.config.peer_params_change = self.params_changed
        result, details = self.config.initialize_config(self.conn)


        if not result:
            self.logger.critical(
                        'Config initialisation FAILED: {0}'.format(details))
            sys.exit(1)
        else:
            self.validate_params(self.config.param_values())
Exemplo n.º 3
0
    def __init__(self, addresses, type, external_config_file=None):

        self.conn = connect_client(addresses=addresses, type=type)
        self.ready_to_work = False
        self.external_config_file = external_config_file
        self.config = PeerControl(peer=self)

        self.logger = get_logger(
            self.config.peer_id,
            file_level=self.get_param('file_log_level'),
            stream_level=self.get_param('console_log_level'),
            mx_level=self.get_param('mx_log_level'),
            sentry_level=self.get_param('sentry_log_level'),
            conn=self.conn,
            log_dir=self.get_param('log_dir'),
            obci_peer=self)
        self.config.logger = self.logger

        self.config.connection = self.conn
        self.config.peer_validate_params = self.validate_params
        self.config.peer_params_change = self.params_changed
        result, details = self.config.initialize_config(self.conn)

        if not result:
            self.logger.critical(
                'Config initialisation FAILED: {0}'.format(details))
            sys.exit(1)
        else:
            self.validate_params(self.config.param_values())
Exemplo n.º 4
0
    def __init__(self, proc_description,
                                reg_timeout_desc=None,
                                monitoring_optflags=PING,
                                logger=None):

        self.desc = proc_description

        self.must_register = reg_timeout_desc is not None
        self._status_lock = threading.RLock()
        self._status = UNKNOWN if self.must_register else RUNNING
        self._status_details = None

        self.ping_it = monitoring_optflags & PING
        self.check_returncode = monitoring_optflags & RETURNCODE if \
                                        self.desc.pid is not None else False

        self.logger = logger or get_logger(
                                'subprocess_monitor'+'-'+self.desc.name+'-'+str(self.desc.pid),
                                stream_level='info')
        self.set_registration_timeout_handler(reg_timeout_desc)
        self.registration_data = None

        self._stop_monitoring = False
        self._ping_thread = None
        self._ping_retries = 8
        self._returncode_thread = None
        self._mtool = OBCIMessageTool(message_templates)
        self._ctx = None
        self.rq_sock = None
        self._poller = PollingObject()

        self.delete = False
Exemplo n.º 5
0
    def __init__(self,
                 proc_description,
                 reg_timeout_desc=None,
                 monitoring_optflags=PING,
                 logger=None):

        self.desc = proc_description

        self.must_register = reg_timeout_desc is not None
        self._status_lock = threading.RLock()
        self._status = UNKNOWN if self.must_register else RUNNING
        self._status_details = None

        self.ping_it = monitoring_optflags & PING
        self.check_returncode = monitoring_optflags & RETURNCODE if \
            self.desc.pid is not None else False

        self.logger = logger or get_logger(
            'subprocess_monitor' + '-' + self.desc.name + '-' +
            str(self.desc.pid),
            stream_level='info')
        self.set_registration_timeout_handler(reg_timeout_desc)
        self.registration_data = None

        self._stop_monitoring = False
        self._ping_thread = None
        self._ping_retries = 8
        self._returncode_thread = None
        self._mtool = OBCIMessageTool(message_templates)
        self._ctx = None
        self.rq_sock = None
        self._poller = PollingObject()

        self.delete = False
Exemplo n.º 6
0
 def __init__(self, zmq_ctx, uuid, logger=None, obci_dns=None):
     self._processes = {}
     self._ctx = zmq_ctx
     self.uuid = uuid
     self.logger = logger or get_logger('subprocess_monitor',
                             stream_level='warning')
     self.obci_dns = obci_dns
     self._mtool = OBCIMessageTool(message_templates)
     self.poller = PollingObject()
     self._proc_lock = threading.RLock()
Exemplo n.º 7
0
 def __init__(self, zmq_ctx, uuid, logger=None, obci_dns=None):
     self._processes = {}
     self._ctx = zmq_ctx
     self.uuid = uuid
     self.logger = logger or get_logger('subprocess_monitor',
                                        stream_level='warning')
     self.obci_dns = obci_dns
     self._mtool = OBCIMessageTool(message_templates)
     self.poller = PollingObject()
     self._proc_lock = threading.RLock()
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
    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
Exemplo n.º 10
0
    def __init__(self, source_addresses=None,
                 rep_addresses=None, pub_addresses=None, name='obci_control_peer'):

        # TODO TODO TODO !!!!
        # cleaner subclassing of obci_control_peer!!!
        self.hostname = socket.gethostname()
        self.source_addresses = source_addresses if source_addresses else []
        self.rep_addresses = rep_addresses
        self.pub_addresses = pub_addresses
        self._all_sockets = []
        self._pull_addr = 'inproc://publisher_msg'
        self._push_addr = 'inproc://publisher'
        self._subpr_push_addr = 'inproc://subprocess_info'

        self.uuid = str(uuid.uuid4())
        self.name = str(name)
        self.type = self.peer_type()

        log_dir = os.path.join(settings.OBCI_CONTROL_LOG_DIR,
                               self.name + '-' + self.uuid[:8])
        if not hasattr(self, 'logger'):
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)
            self.logger = get_logger(self.peer_type(), log_dir=log_dir,
                                     stream_level=net_tools.peer_loglevel(), obci_peer=self)

        self.mtool = self.message_tool()

        if not hasattr(self, "ctx"):
            self.ctx = zmq.Context()

        self.subprocess_mgr = SubprocessMonitor(self.ctx, self.uuid, logger=self.logger)
        self.net_init()

        if self.source_addresses:
            self.registration_response = self.register()
            self._handle_registration_response(self.registration_response)
        else:
            self.registration_response = None

        self.interrupted = False
        signal.signal(signal.SIGTERM, self.signal_handler())
        signal.signal(signal.SIGINT, self.signal_handler())
Exemplo n.º 11
0
    def __init__(self, source_addresses=None,
                 rep_addresses=None, pub_addresses=None, name='obci_control_peer'):

        # TODO TODO TODO !!!!
        # cleaner subclassing of obci_control_peer!!!
        self.hostname = socket.gethostname()
        self.source_addresses = source_addresses if source_addresses else []
        self.rep_addresses = rep_addresses
        self.pub_addresses = pub_addresses
        self._all_sockets = []
        self._pull_addr = 'inproc://publisher_msg'
        self._push_addr = 'inproc://publisher'
        self._subpr_push_addr = 'inproc://subprocess_info'

        self.uuid = str(uuid.uuid4())
        self.name = str(name)
        self.type = self.peer_type()

        log_dir = os.path.join(settings.OBCI_CONTROL_LOG_DIR,
                               self.name + '-' + self.uuid[:8])
        if not hasattr(self, 'logger'):
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)
            self.logger = get_logger(self.peer_type(), log_dir=log_dir,
                                     stream_level=net_tools.peer_loglevel(), obci_peer=self)

        self.mtool = self.message_tool()

        if not hasattr(self, "ctx"):
            self.ctx = zmq.Context()

        self.subprocess_mgr = SubprocessMonitor(self.ctx, self.uuid, logger=self.logger)
        self.net_init()

        if self.source_addresses:
            self.registration_response = self.register()
            self._handle_registration_response(self.registration_response)
        else:
            self.registration_response = None

        self.interrupted = False
        signal.signal(signal.SIGTERM, self.signal_handler())
        signal.signal(signal.SIGINT, self.signal_handler())
Exemplo n.º 12
0
    def __init__(self, addresses):
        super(ConfigServer, self).__init__(addresses=addresses, type=peers.CONFIG_SERVER)
        self._configs = {}
        self._ext_configs = {}
        self._ready_peers = []
        self.__to_all = False
        self.mtool = OBCIMessageTool(message_templates)
        self.launcher_sock = None
        params, other_params = PeerCmd().parse_cmd()

        self.addr = params['local_params'].get('launcher_socket_addr', '')

        self.exp_uuid = params['local_params'].get('experiment_uuid', '')
        self.log_dir = params['local_params'].get('log_dir', None)
        self.logger = get_logger('config_server', log_dir=self.log_dir,
                                conn=self.conn,
                                file_level=params['local_params'].get('file_log_level', None),
                                mx_level=params['local_params'].get('mx_log_level', None),
                                stream_level=params['local_params'].get('console_log_level', None))
        self._old_configs = self._stored_config()
        self._restore_peers = params['local_params'].get('restore_peers', '').split()

        for peer in self._restore_peers:
            if peer in self._old_configs["local"]:
                self._configs[peer] = dict(self._old_configs["local"][peer])
                self._ready_peers.append(peer)
            if peer in self._old_configs["ext"]:
                self._ext_configs[peer] = dict(self._old_configs["ext"][peer])

        if self.addr != '':
            self.ctx = zmq.Context()
            self.launcher_sock = self.ctx.socket(zmq.PUSH)
            try:
                self.launcher_sock.connect(self.addr)

            except Exception, e:
                self.logger.error("failed to connect to address " +\
                                             self.addr + " !!!")
                self.launcher_sock = None
            else:
                self.logger.info("OK: connected to " + self.addr)

                send_msg(self.launcher_sock, self.mtool.fill_msg("config_server_ready"))
Exemplo n.º 13
0
    def __init__(self, presets=None):
        '''
        Constructor
        '''
        QMainWindow.__init__(self)

        self.presets = presets

        self.logger = get_logger('launcherGUI', obci_peer=self)

        self.setupUi(self)
        self.basic_title = self.windowTitle()

        self.exp_states = {}
        self.exp_widgets = {}

        self.scenarioTab.setTabText(0, "Scenario")
        self.scenarioTab.setTabsClosable(True)
        self.log_engine = obci_log_engine.LogEngine(self.scenarioTab)

        self.engine_server_setup()

        self._nearby_machines = self.engine.nearby_machines()

        self.scenarios.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.scenarios.setColumnCount(2)
        self.scenarios.setHeaderLabels(["Scenario", "Status"])
        self.scenarios.setColumnWidth(0, 300)

        self.scenarios.itemClicked.connect(self._setInfo)
        self.scenarios.currentItemChanged.connect(self._setInfo)

        self.details_mode.currentIndexChanged.connect(self.update_user_interface)

        self.parameters.setHeaderLabels(["Name", 'Value', 'Info'])
        self.parameters.itemClicked.connect(self._itemClicked)
        self.parameters.itemChanged.connect(self._itemChanged)
        self.parameters.itemDoubleClicked.connect(self._itemDoubleClicked)
        self.parameters.setColumnWidth(0, 200)
        self.parameters.setColumnWidth(1, 400)

        self.machines_dialog = ConnectToMachine(self)
        self.select_amplifier_dialog = SelectAmplifierDialog(self)

        self.start_button.clicked.connect(self._start)
        self.stop_button.clicked.connect(self._stop)
        # self.reset_button.clicked.connect(self._reset)
        # self.ampselect_pushButton.clicked.connect(self._amp_select)
        self.store_container.hide()
        self.store_checkBox.stateChanged.connect(self._update_store)
        self.store_dir_chooser.clicked.connect(self._choose_dir)

        self._params = []
        self._scenarios = []

        self.details_mode.addItems(MODES)

        self.engine_reinit.connect(self.engine_server_setup)

        self.setupMenus()
        self.setupActions()
        self.update_user_interface(None)
        self.showMaximized()
        if os.environ.get('OBCI_INSTALL_DIR') != None:
            PyQt4.QtGui.QMessageBox.information(self, "Non standard OpenBCI directory",
                                                "OpenBCI is launched from local directory: " + os.environ.get('OBCI_INSTALL_DIR') + ', to start default package version launch "obci_local_remove" in terminal.')
Exemplo n.º 14
0
def get_logger(p_name, p_level='info'):
    """Return logger with p_name as name. And logging level p_level.
    p_level should be in (starting with the most talkactive):
    'debug', 'info', 'warning', 'error', 'critical'."""
    return openbci_logging.get_logger(p_name, p_level)
Exemplo n.º 15
0
#!/usr/bin/env python
#
# Author:
#      Mateusz Kruszynski <*****@*****.**>
#

from multiplexer.multiplexer_constants import peers, types
from obci.analysis.obci_signal_processing import types_utils

from obci.configs import variables_pb2
from obci.utils import openbci_logging as logger

LOGGER = logger.get_logger('tags_helper', 'info')


def pack_tag_from_tag(tag_dict):
    return pack_tag(tag_dict['start_timestamp'], tag_dict['end_timestamp'],
                    tag_dict['name'], tag_dict['desc'], tag_dict['channels'])


def pack_tag(p_start_timestamp,
             p_end_timestamp,
             p_tag_name,
             p_tag_desc={},
             p_tag_channels=""):
    """Return tag with given values. 
    Returned tag is serialised to string.
    Parameters:
    - p_start_timestamp - float 
    - p_end_timestamp - float
    - p_tag_name - string
Exemplo n.º 16
0
#!/usr/bin/env python3
#
# Author:
#      Mateusz Kruszynski <*****@*****.**>
#

from obci.mx_legacy.multiplexer_constants import types
from obci.analysis.obci_signal_processing import types_utils

from obci.configs import variables_pb2
from obci.utils import openbci_logging as logger


LOGGER = logger.get_logger('tags_helper', 'info')


def pack_tag_from_tag(tag_dict):
    return pack_tag(tag_dict['start_timestamp'], tag_dict['end_timestamp'],
                    tag_dict['name'], tag_dict['desc'], tag_dict['channels'])


def pack_tag(p_start_timestamp, p_end_timestamp,
             p_tag_name, p_tag_desc={}, p_tag_channels=""):
    """Return tag with given values.
    Returned tag is serialised to string.
    Parameters:
    - p_start_timestamp - float
    - p_end_timestamp - float
    - p_tag_name - string
    - p_tag_desc - dictionary
    - p_tag_channels - string like "0 6 7" - numbers of channels
Exemplo n.º 17
0
    def __init__(self):
        '''
        Constructor
        '''
        QMainWindow.__init__(self)

        self.logger = get_logger('launcherGUI', obci_peer=self)

        self.setupUi(self)
        self.basic_title = self.windowTitle()

        self.exp_states = {}
        self.exp_widgets = {}

        self.scenarioTab.setTabText(0, "Scenario")
        self.scenarioTab.setTabsClosable(True)
        self.log_engine = obci_log_engine.LogEngine(self.scenarioTab)

        self.engine_server_setup()

        self._nearby_machines = self.engine.nearby_machines()

        self.scenarios.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.scenarios.setColumnCount(2)
        self.scenarios.setHeaderLabels(["Scenario", "Status"])
        self.scenarios.setColumnWidth(0, 300)

        self.scenarios.itemClicked.connect(self._setInfo)
        self.scenarios.currentItemChanged.connect(self._setInfo)

        self.details_mode.currentIndexChanged.connect(self.update_user_interface)

        self.parameters.setHeaderLabels(["Name", 'Value', 'Info'])
        self.parameters.itemClicked.connect(self._itemClicked)
        self.parameters.itemChanged.connect(self._itemChanged)
        self.parameters.itemDoubleClicked.connect(self._itemDoubleClicked)
        self.parameters.setColumnWidth(0, 200)
        self.parameters.setColumnWidth(1, 400)

        self.machines_dialog = ConnectToMachine(self)
        self.select_amplifier_dialog = SelectAmplifierDialog(self)

        self.start_button.clicked.connect(self._start)
        self.stop_button.clicked.connect(self._stop)
        #self.reset_button.clicked.connect(self._reset)
        #self.ampselect_pushButton.clicked.connect(self._amp_select)
        self.store_container.hide()
        self.store_checkBox.stateChanged.connect(self._update_store)
        self.store_dir_chooser.clicked.connect(self._choose_dir)

        self._params = []
        self._scenarios = []

        self.details_mode.addItems(MODES)

        self.engine_reinit.connect(self.engine_server_setup)

        self.setupMenus()
        self.setupActions()
        self.update_user_interface(None)
        self.showMaximized()
        if os.environ.get('OBCI_INSTALL_DIR') != None:
            PyQt4.QtGui.QMessageBox.information(self, "Non standard OpenBCI directory",
                                                "OpenBCI is launched from local directory: "+os.environ.get('OBCI_INSTALL_DIR')+', to start default package version launch "obci_local_remove" in terminal.')
Exemplo n.º 18
0
from obci.utils import openbci_logging as logger


DISCOVERY_MODULE_NAMES = [
    'amplifier_virtual_discovery',
    'amplifier_tmsi_bt_discovery',
    'amplifier_tmsi_usb_discovery',
]
BASE_MODULE = 'obci.drivers.eeg.driver_discovery'

LOADED_MODULE_NAMES = []

discovery_modules = []

LOGGER = logger.get_logger("DriverDiscovery", "info")

for mod_name in DISCOVERY_MODULE_NAMES:
    name = BASE_MODULE + '.' + mod_name
    try:
        __import__(name)

    except ImportError:
        LOGGER.error("could not import discovery module %s" % name)
        continue
    discovery_modules.append(sys.modules[name])
    LOADED_MODULE_NAMES.append(mod_name)


def find_drivers():
    return _find_amps(discovery_modules)