当前位置: 首页>>代码示例>>Python>>正文


Python OBCIMessageTool.fill_msg方法代码示例

本文整理汇总了Python中obci.control.common.message.OBCIMessageTool.fill_msg方法的典型用法代码示例。如果您正苦于以下问题:Python OBCIMessageTool.fill_msg方法的具体用法?Python OBCIMessageTool.fill_msg怎么用?Python OBCIMessageTool.fill_msg使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在obci.control.common.message.OBCIMessageTool的用法示例。


在下文中一共展示了OBCIMessageTool.fill_msg方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: find_new_experiments_and_push_results

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def find_new_experiments_and_push_results(ctx, rq_message):
    LOGGER = logger.get_logger("eeg_AMPLIFIER_finder", "info")

    if not rq_message.amplifier_types:
        LOGGER.info("AMPLIFIER TYPES NOT SET, FINDING ALL...")
        driv = find_drivers()
    else:
        driv = []
        for amptype in rq_message.amplifier_types:

            if amptype == 'bt' or amptype == 'bluetooth':
                driv += find_bluetooth_amps()
            elif amptype == 'usb':
                driv += find_usb_amps()
            elif amptype == 'virtual':
                driv += find_virtual_amps()

    LOGGER.info("amplifiers! return to:  " + rq_message.client_push_address)
    mtool = OBCIMessageTool(message_templates)
    to_client = ctx.socket(zmq.PUSH)
    to_client.connect(rq_message.client_push_address)

    send_msg(to_client, mtool.fill_msg('eeg_amplifiers', sender_ip=socket.gethostname(),
                                       amplifier_list=driv))
    LOGGER.info("sent amplifier data... " + str(driv)[:500] + ' [...]')
    time.sleep(0.1)
开发者ID:mroja,项目名称:openbci,代码行数:28,代码来源:eeg_experiment_finder.py

示例2: ObciBaseClient

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
class ObciBaseClient(object):
    """
    Base class for communicating with OBCI peers.
    """
    def __init__(self, address):
        self.context = zmq.Context.instance()
        templates = launcher_messages.message_templates
        self.msg_factory = OBCIMessageTool(msg_templates=templates)
        self.socket = self.context.socket(zmq.REQ)
        self.socket.connect(address)
        
        # disabled bc Ubuntu LTS uses archaic zmq version
        # self.socket.RCVTIMEO = 7000
        self.poller = zmq.Poller()
        self.poller.register(self.socket, zmq.POLLIN)
        
        self.open = True

    def close(self):
        if self.open:
            self.socket.close()
            self.open = False

    def send_recv(self, message_name, **kwargs):
        data = self.msg_factory.fill_msg(message_name, **kwargs)
        self.socket.send(data)
        poll_results = self.poller.poll(7000)
        response = self.socket.recv(zmq.NOBLOCK) if poll_results else None
        return json.loads(response)
开发者ID:BrainTech,项目名称:psychopy,代码行数:31,代码来源:obci_connection.py

示例3: start_eeg_signal_experiment

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def start_eeg_signal_experiment(ctx, srv_addrs, rq_message):
    client = OBCIClient(srv_addrs, ctx)
    # server_req_socket = ctx.socket(zmq.REQ)
    #     for addr in srv_addrs:
    #         server_req_socket.connect(addr)

    amp_params = {}
    amp_params.update(rq_message.amplifier_params['additional_params'])
    del rq_message.amplifier_params['additional_params']
    amp_params.update(rq_message.amplifier_params)

    par_list = ['--peer', 'amplifier']
    for par, val in amp_params.iteritems():
        par_list += ['-p', par, unicode(val)]

    overwrites = peer_cmd.peer_overwrites_pack(par_list)
    result = client.launch(rq_message.launch_file, None, rq_message.name, overwrites)


    LOGGER.info("START EEG signal! return to:  " + rq_message.client_push_address)
    mtool = OBCIMessageTool(message_templates)
    to_client = ctx.socket(zmq.PUSH)
    to_client.connect(rq_message.client_push_address)
    if result is None:
        send_msg(to_client, mtool.fill_msg("rq_error", err_code="launch_failed",
                    details="No response from server or experiment"))
    else:
        send_msg(to_client, result.raw())
    LOGGER.info("sent eeg launch result"  + str(result)[:500] )
    time.sleep(0.1)
开发者ID:niklasrogers,项目名称:openbci,代码行数:32,代码来源:start_eeg_signal.py

示例4: broadcast_server

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def broadcast_server(server_uuid, rep_port, pub_port, bcast_port):
    mtool = OBCIMessageTool(message_templates)

    str_msg = mtool.fill_msg("server_broadcast", sender_ip=socket.gethostname(), sender=server_uuid,
                             rep_port=rep_port, pub_port=pub_port)
    str_msg += b'\n'

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(('', 0))
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    # introduction
    for i in range(10):
        try:
            s.sendto(str_msg, ('<broadcast>', bcast_port))
        except socket.error as e:
            pass
        time.sleep(0.3)

    # updates
    while True:
        try:
            s.sendto(str_msg, ('<broadcast>', bcast_port))
        except socket.error as e:
            print("[obci_server] Cannot broadcast obci_server, will try again in 1min:", str(e))
            time.sleep(53)
        time.sleep(7)

    s.close()
开发者ID:mroja,项目名称:openbci,代码行数:31,代码来源:server_scanner.py

示例5: _gather_other_server_results

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def _gather_other_server_results(ctx, this_addr, ip_list):
    exps = []
    if not ip_list:
        return exps
    mtool = OBCIMessageTool(message_templates)
    other_exps_pull = ctx.socket(zmq.PULL)
    port = other_exps_pull.bind_to_random_port('tcp://*',
                                               min_port=PORT_RANGE[0],
                                               max_port=PORT_RANGE[1], max_tries=500)

    my_push_addr = this_addr + ':' + str(port)
    LOGGER.info("my exp_data pull: " + my_push_addr)

    harvester = zmq.Poller()
    harvester.register(other_exps_pull)

    reqs = {}
    for srv_ip in ip_list:

        addr = 'tcp://' + srv_ip + ':' + net.server_rep_port()
        req = ctx.socket(zmq.REQ)
        req.connect(addr)
        send_msg(req, mtool.fill_msg('find_eeg_experiments',
                                     client_push_address='tcp://' + my_push_addr,
                                     checked_srvs=[this_addr]))
        harvester.register(req, zmq.POLLIN)
        reqs[req] = addr

    srv_responses = 0

    for i in range(len(reqs) * 50):
        socks = dict(harvester.poll(timeout=300))

        for req in socks:
            msg = recv_msg(req)
            msg = mtool.unpack_msg(msg)

            if msg.type == 'rq_ok':
                LOGGER.info("waiting for experiments from server: " + str(reqs[req]))
                harvester.unregister(req)
                req.close()

            elif msg.type == 'eeg_experiments':
                LOGGER.info("GOT EXPERIMENTS from: " + msg.sender_ip)
                exps += msg.experiment_list
                srv_responses += 1
            else:
                LOGGER.warning('strange msg:  ' + str(msg))
        if srv_responses == len(ip_list):
            print("GOT ALL eeg_experiment RESPONSES :-) [addr list:  ", ip_list, "]")
            break

    other_exps_pull.close()
    return exps
开发者ID:mroja,项目名称:openbci,代码行数:56,代码来源:eeg_experiment_finder.py

示例6: update_nearby_servers

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def update_nearby_servers(srv_data, bcast_port, ctx=None, update_push_addr=None):
    mtool = OBCIMessageTool(message_templates)

    loops_to_update = _LOOPS

    s = socket(AF_INET, SOCK_DGRAM)
    s.bind(('', bcast_port))

    notify_sock = None
    if update_push_addr is not None:
        ctx = ctx if ctx else zmq.Context()
        notify_sock = ctx.socket(zmq.PUSH)
        notify_sock.connect(update_push_addr)

    while 1:
        changed = False
        try:
            inp, out, exc = select.select([s], [], [], UPDATE_INTERVAL / _LOOPS)
        except Exception, e:
            srv_data.logger.critical("nearby_servers_update - exception: %s", str(e))
            srv_data.logger.critical("nearby_servers - aborting")
            return

        if s in inp:
            data, wherefrom = s.recvfrom(1500, 0)
            # sys.stderr.write(repr(wherefrom) + '\n')
            # sys.stdout.write(data)
            msg = unicode(data, encoding='utf-8')
            msg = msg[:-1]
            message = mtool.unpack_msg(msg)
            changed = srv_data.update(ip=wherefrom[0], hostname=message.sender_ip,
                                      uuid=message.sender, rep_port=message.rep_port,
                                      pub_port=message.pub_port)

        else:
            # print "no data"
            pass

        loops_to_update -= 1

        if loops_to_update == 0:
            loops_to_update = _LOOPS
            changed = srv_data.clean_silent()

        if changed:
            send_msg(notify_sock, mtool.fill_msg('nearby_machines',
                                                 nearby_machines=srv_data.dict_snapshot()))
开发者ID:BrainTech,项目名称:openbci,代码行数:49,代码来源:server_scanner.py

示例7: ConfigServer

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
class ConfigServer(BaseMultiplexerServer):
    @log_crash
    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"))
        self.logger.info("connections count ::::::::: %s", self.conn.connections_count())
开发者ID:BrainTech,项目名称:openbci,代码行数:48,代码来源:config_server.py

示例8: broadcast_server

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
def broadcast_server(server_uuid, rep_port, pub_port, bcast_port):
    mtool = OBCIMessageTool(message_templates)

    msg = mtool.fill_msg("server_broadcast", sender_ip=gethostname(), sender=server_uuid,
                         rep_port=rep_port, pub_port=pub_port)
    msg += u'\n'
    str_msg = msg.encode('utf-8')

    s = socket(AF_INET, SOCK_DGRAM)
    s.bind(('', 0))
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

    # introduction
    for i in range(10):
        try:
            s.sendto(str_msg, ('<broadcast>', bcast_port))
        except error, e:
            pass
        time.sleep(0.3)
开发者ID:BrainTech,项目名称:openbci,代码行数:21,代码来源:server_scanner.py

示例9: kill

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
    def kill(self):
        # send "kill" to the process or kill request to its supervisor?
        self.stop_monitoring()
        if not self._ctx:
            self._ctx = zmq.Context()
        rq_sock = self._ctx.socket(zmq.REQ)
        try:
            rq_sock.connect(self.rq_address)
            mtool = OBCIMessageTool(message_templates)
            poller = PollingObject()
            send_msg(rq_sock, mtool.fill_msg("kill_process", pid=self.pid, machine=self.machine_ip))
            res, _ = poller.poll_recv(rq_sock, timeout=5000)
        finally:
            rq_sock.close()
        if res:
            res = mtool.unpack_msg(res)
            print "Response to kill request: ", res

            with self._status_lock:
                self._status = TERMINATED
开发者ID:BrainTech,项目名称:openbci,代码行数:22,代码来源:remote_process.py

示例10: EEGExperimentFinder

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
class EEGExperimentFinder(object):

    def __init__(self, srv_addrs, ctx, client_push_address, nearby_servers):
        self.ctx = ctx
        self.server_req_socket = self.ctx.socket(zmq.REQ)
        for addr in srv_addrs:
            self.server_req_socket.connect(addr)

        self.poller = PollingObject()
        self.mtool = OBCIMessageTool(message_templates)
        self.nearby_servers = nearby_servers
        self._amplified_cache = {}

    def _running_experiments(self):
        send_msg(self.server_req_socket, self.mtool.fill_msg("list_experiments"))
        exp_list, details = self.poll_recv(self.server_req_socket, 2000)
        if not exp_list:
            LOGGER.error("Connection to obci_server failed. (list_experiments)")
            return None

        exps = exp_list.exp_data
        running = []
        for exp in exps.values():
            if exp['status_name'] == launcher_tools.RUNNING or \
                    exp['status_name'] == launcher_tools.LAUNCHING:
                running.append(exp)
        return running

    def find_amplified_experiments(self):
        running_exps = self._running_experiments()
        amplified = []
        for exp in running_exps:
            LOGGER.info("Found running experiment: " + str(exp['name']))
            infos = self._info_amplified(exp)

            if infos is not None:
                print("Found experiments...", str(infos)[:500])
                amplified += infos

        return amplified

    def _info_amplified(self, exp_desc):
        amp_options = []
        LOGGER.info("Processing experiment " + str(exp_desc['name']) +
                    "w/ addr: " + str(exp_desc['rep_addrs']))
        tcp_addrs = exp_desc['tcp_addrs']
        rep_addrs = net.choose_not_local(exp_desc['rep_addrs'])

        if not rep_addrs:
            rep_addrs = net.choose_local(exp_desc['rep_addrs'], ip=True)

        rep_addr = rep_addrs.pop()

        pub_addrs = net.choose_not_local(exp_desc['pub_addrs'])
        if not pub_addrs:
            pub_addrs = net.choose_local(exp_desc['pub_addrs'], ip=True)
        pub_addr = pub_addrs.pop()
        tcp_addr = tcp_addrs.pop()

        LOGGER.info("Chosen experiment addresses: REP -- " +
                    str(rep_addr) + ", PUB -- " + str(pub_addr))

        req_sock = self.ctx.socket(zmq.REQ)
        try:
            req_sock.connect(rep_addr)

            send_msg(req_sock, self.mtool.fill_msg('get_experiment_info'))
            res, details = self.poll_recv(req_sock, 4000)
        finally:
            req_sock.close()

        if not res:
            LOGGER.error("Connection failed (experiment " + exp_desc['name'] +
                         "), get_experiment_info")
            return None
        exp_info = res.dict()  # json.loads(res)
        for field in ["peers_status", "details"]:
            del exp_info["experiment_status"][field]

        peer_list = exp_info["peers"]
        if not self._has_mx(peer_list):
            LOGGER.info("Experiment " + exp_desc['name'] +
                        " does not have a multiplexer.")
            return None

        maybe_amps = self._amp_like_peers(peer_list)
        if not maybe_amps:
            LOGGER.info("Experiment " + exp_desc['name'] +
                        " -- no amplifier.")
            return None

        req_sock = self.ctx.socket(zmq.REQ)
        try:
            req_sock.connect(rep_addr)
            for peer in maybe_amps:
                info, params = self._get_amp_info(req_sock, peer)
                if not self._is_amplifier(info, params):
                    LOGGER.info("Experiment " + exp_desc['name'] +
                                " -- peer " + str(peer) + "is not an amplifier.")
                    continue
#.........这里部分代码省略.........
开发者ID:mroja,项目名称:openbci,代码行数:103,代码来源:eeg_experiment_finder.py

示例11: SubprocessMonitor

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]

#.........这里部分代码省略.........
                                        path=path,
                                        args=args,
                                        machine_ip=machine,
                                        pid=popen_obj.pid)

        # io_handler will be None if no stdio is captured
        io_handler = start_stdio_handler(popen_obj, std_actions,
                                                    ':'.join([machine, path, name]),
                                                    stdout_log, stderr_log)

        new_proc = LocalProcess(process_desc, popen_obj, io_handler=io_handler,
                            reg_timeout_desc=timeout_desc,
                            monitoring_optflags=monitoring_optflags,
                            logger=self.logger)

        if monitoring_optflags & PING:
            new_proc._ctx = self._ctx

        with self._proc_lock:
            self._processes[(machine, popen_obj.pid)] = new_proc

        new_proc.start_monitoring()

        return new_proc, None

    def new_remote_process(self, path, args, proc_type, name,
                                machine_ip, conn_addr,
                                capture_io= STDOUT | STDIN,
                                stdout_log=None,
                                stderr_log=None,
                                register_timeout_desc=None,
                                monitoring_optflags=PING):
        """Send a request to conn_addr for a process launch. By default
        the process will be monitored with ping requests and locally by the
        remote peer."""


        timeout_desc = register_timeout_desc

        rq_message = self._mtool.fill_msg('launch_process',
                                path=path,
                                args=args, proc_type=proc_type,
                                name=name,
                                machine_ip=machine_ip,
                                capture_io=capture_io,
                                stdout_log=stdout_log,
                                stderr_log=stderr_log)

        rq_sock = self._ctx.socket(zmq.REQ)

        try:
            rq_sock.connect(conn_addr)
        except zmq.ZMQError as e:
            det = "Could not connect to {0}, err: {1}, {2}".format(
                                                            conn_addr, e, e.args)
            self.logger.error(det)
            return None, det

        self.logger.info("SENDING LAUNCH REQUEST  {0}  {1}  {2} {3}".format(
                                machine_ip, _DEFAULT_TIMEOUT_MS, 'ms', conn_addr))

        send_msg(rq_sock, rq_message)
        result, details = self.poller.poll_recv(rq_sock, _DEFAULT_TIMEOUT_MS)

        rq_sock.close()

        if not result:
            details = details + "  [address was: {0}]".format(conn_addr)
            self.logger.error(details)
            return None, details
        else:
            result = self._mtool.unpack_msg(result)

        if result.type == 'rq_error':
            det = "REQUEST FAILED" + str(result.err_code) + ':' + str(result.details)
            self.logger.error(det)
            return None, det
        elif result.type == 'launched_process_info':
            self.logger.info("REQUEST SUCCESS  %s", result.dict())
            process_desc = ProcessDescription(proc_type=result.proc_type,
                                            name=result.name,
                                            path=result.path,
                                            args=args,
                                            machine_ip=result.machine,
                                            pid=result.pid)

            new_proc = RemoteProcess(process_desc, conn_addr,
                                reg_timeout_desc=timeout_desc,
                                monitoring_optflags=monitoring_optflags,
                                logger=self.logger)

            if monitoring_optflags & PING:
                new_proc._ctx = self._ctx

            with self._proc_lock:
                self._processes[(result.machine, result.pid)] = new_proc

            new_proc.start_monitoring()

            return new_proc, None
开发者ID:karolaug,项目名称:openbci,代码行数:104,代码来源:subprocess_monitor.py

示例12: str

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
    ctx = zmq.Context()

    server_req = ctx.socket(zmq.REQ)
    server_req.connect(my_addr + ':' + net.server_rep_port())

    exp_info_pull = ctx.socket(zmq.PULL)

    port = exp_info_pull.bind_to_random_port('tcp://*',
                                             min_port=PORT_RANGE[0],
                                             max_port=PORT_RANGE[1], max_tries=500)

    client_push_addr = my_addr + ':' + str(port)
    print(client_push_addr)

    send_msg(server_req, mtool.fill_msg('find_eeg_experiments',
                                        client_push_address=client_push_addr))
    msg, details = pl.poll_recv(server_req, 5000)
    if not msg:
        print("srv request timeout!")
        server_req.close()
        sys.exit(1)

    response = mtool.unpack_msg(msg)

    if not response.type == 'rq_ok':
        print("whaaa?")
        sys.exit(1)

    msg, details = pl.poll_recv(exp_info_pull, 20000)

    if not msg:
开发者ID:mroja,项目名称:openbci,代码行数:33,代码来源:test_server_experiment_finder.py

示例13: OBCIClient

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
class OBCIClient(object):
    default_timeout = 5000

    def __init__(self, server_addresses, zmq_context=None):
        self.ctx = zmq_context if zmq_context else zmq.Context()

        self.server_addresses = server_addresses
        self.server_req_socket = None
        self.init_server_socket(server_addresses)

        # self = zmq.Poller()
        # self.register(self.server_req_socket, zmq.POLLIN)
        self.poller = PollingObject()

        self.mtool = OBCIMessageTool(message_templates)
        self.dns = net.DNS()

    def init_server_socket(self, srv_addrs):
        if self.server_req_socket is not None:
            print("server socket restart")
            self.server_req_socket.close()

        self.server_req_socket = self.ctx.socket(zmq.REQ)

        for addr in srv_addrs:
            print(addr)
            self.server_req_socket.connect(addr)

    def launch(self, launch_file=None, sandbox_dir=None, name=None, overwrites=None):
        result = self.send_create_experiment(launch_file, sandbox_dir, name, overwrites)
        print("create result:", result)
        if not result:
            self.init_server_socket(self.server_addresses)
            return result
        if result.type != "experiment_created":
            return result
        print(result)
        machine = result.origin_machine
        addrs = [addr for addr in result.rep_addrs if self._addr_connectable(addr, machine)]

        return self.send_start_experiment(addrs)

    def morph(self, exp_strname, launch_file, name=None, overwrites=None, leave_on=None):
        response = self.get_experiment_contact(exp_strname)
        exp_sock = self.ctx.socket(zmq.REQ)

        try:
            if response.type == "rq_error" or response.type == "no_data":
                return response
            for addr in response.rep_addrs:
                exp_sock.connect(addr)

            msg = self.mtool.fill_msg('morph_to_new_scenario', launch_file=launch_file,
                                      name=name, overwrites=overwrites, leave_on=leave_on)
            send_msg(exp_sock, msg)

            response, details = self.poll_recv(exp_sock, 6000)
            return response
        finally:
            exp_sock.close()

    def _addr_connectable(self, addr, machine):
        return machine == socket.gethostname() or \
            (net.is_ip(addr) and not net.addr_is_local(addr))

    def start_chosen_experiment(self, exp_strname):
        response = self.get_experiment_contact(exp_strname)

        if response.type == "rq_error" or response.type == "no_data":
            return response

        return self.send_start_experiment(response.rep_addrs)

    def send_start_experiment(self, exp_addrs):
        exp_sock = self.ctx.socket(zmq.REQ)
        try:
            for addr in exp_addrs:
                exp_sock.connect(addr)

                send_msg(exp_sock, self.mtool.fill_msg("start_experiment"))
                reply, details = self.poll_recv(exp_sock, 20000)

                # print reply
                return reply
        finally:
            exp_sock.close()

    def force_kill_experiment(self, strname):
        pass

    def get_experiment_contact(self, strname):
        send_msg(self.server_req_socket, self.mtool.fill_msg("get_experiment_contact",
                                                             strname=strname))
        response, details = self.poll_recv(self.server_req_socket, self.default_timeout)
        return response

    def ping_server(self, timeout=50):
        send_msg(self.server_req_socket, self.mtool.fill_msg("ping"))
        response, details = self.poll_recv(self.server_req_socket, timeout)

#.........这里部分代码省略.........
开发者ID:mroja,项目名称:openbci,代码行数:103,代码来源:obci_client.py

示例14: OBCIConnection

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]
class OBCIConnection(object):
    """
    Synchronous OBCI connection.
    """
    def __init__(self, address):
        templates = launcher_messages.message_templates
        self.msg_factory = OBCIMessageTool(msg_templates=templates)
        self.netstring_codec = NetstringCodec()
        self.address = address
        self.experiment_uuid = None
    
    def close(self):
        self.connection.close()
    
    def open(self):
        self.connection = socket.create_connection(self.address, timeout=30)
    
    def send_recv(self, message_name, **kwargs):
        message_json = self.msg_factory.fill_msg(message_name, **kwargs)
        message_netstring = self.netstring_codec.encode(message_json)
        self.open()
        self.connection.send(message_netstring)
        response_json = self.netstring_codec.decode(self.connection)
        self.close()
        response_dict = self.msg_factory.decode_msg(response_json)
        return response_dict
    
    def get_amp_list(self):
        message = self.msg_factory.fill_msg("find_eeg_amplifiers")
        message = self.netstring_codec.encode(message)
        self.open()
        self.connection.send(message)
        response_text = self.netstring_codec.decode(self.connection)
        response = self.msg_factory.decode_msg(response_text)
        self.close()
        amp_list = response["amplifier_list"]
        return amp_list
    
    def start_eeg_signal(self, name, launch_file, amplifier_params):
        message = self.msg_factory.fill_msg("start_eeg_signal", launch_file=launch_file, amplifier_params=amplifier_params, name=name)
        message_text = self.netstring_codec.encode(message)
        self.open()
        self.connection.send(message_text)
        response_text = self.netstring_codec.decode(self.connection)
        response = self.msg_factory.decode_msg(response_text)
        self.close()
        return response["sender"]
    
    def get_experiment_contact(self, name):
        response = self.send_recv("get_experiment_contact", strname=name)
        self.experiment_uuid = response["uuid"]
        return self.experiment_uuid
    
    def stop_experiment(self, experiment_uuid=None):
        if not experiment_uuid:
            experiment_uuid = self.experiment_uuid
        message = self.msg_factory.fill_msg("kill_experiment", strname=experiment_uuid)
        message_text = self.netstring_codec.encode(message)
        self.open()
        self.connection.send(message_text)
        response_text = self.netstring_codec.decode(self.connection)
        self.close()
        response = self.msg_factory.decode_msg(response_text)
        return response
    
    def create_experiment(self, name="unnamed"):
        message = self.msg_factory.fill_msg("create_experiment", name=name)
        message_text = self.netstring_codec.encode(message)
        self.open()
        self.connection.send(message_text)
        response_text = self.netstring_codec.decode(self.connection)
        self.close()
        return self.msg_factory.decode_msg(response_text)
    
    def set_experiment_scenario(self, launch_file_path="", scenario=""):
        return self.send_recv("set_experiment_scenario", launch_file_path=launch_file_path, scenario=scenario)
    
    def start_experiment(self):
        return self.send_recv("start_experiment")
    
    def get_nearby_servers(self):
        response = self.send_recv("list_nearby_machines")
        return response
开发者ID:BrainTech,项目名称:psychopy,代码行数:85,代码来源:obci_connection.py

示例15: Process

# 需要导入模块: from obci.control.common.message import OBCIMessageTool [as 别名]
# 或者: from obci.control.common.message.OBCIMessageTool import fill_msg [as 别名]

#.........这里部分代码省略.........
        self.logger.info("{0} [{1}]  REGISTERED!!! {2}".format(
                                            self.name, self.proc_type, reg_data.machine_ip))
        #print "ping:", self.ping_it, "ret:", self.check_returncode
        with self._status_lock:
            self._status = RUNNING
        #TODO validate registration data
        self.registration_data = reg_data
        self.logger.info("reg_data" + str(vars(reg_data)))
        if self.ping_it:
            if not self._ctx:
                self._ctx = zmq.Context()
            self.rq_sock = self._ctx.socket(zmq.REQ)
            for addr in reg_data.rep_addrs:
                if reg_data.machine_ip != socket.gethostname() and\
                                                        net.addr_is_local(addr):
                    continue
                self.logger.debug(self.name + "connecting to " + addr)
                self.rq_sock.connect(addr)


    def stop_monitoring(self):
        if self.reg_timer:
            self.reg_timer.cancel()
            self.reg_timer = None
        self._stop_monitoring = True

        if self._ping_thread is not None:
            self.logger.info("%s, %s, %s",
                            self.proc_type, self.name ,"Joining ping thread")
            
            self._ping_thread.join()
        if self._returncode_thread is not None:
            self.logger.info("%s  %s  %s",
                            self.proc_type,self.name, "joining returncode thread")
            self._returncode_thread.join()
        self.logger.info("monitor for: %s, %s, %s", 
                    self.proc_type,self.name, "  ...monitoring threads stopped.")

    def finished(self):
        finished = True
        if self._ping_thread is not None:
            finished = not self._ping_thread.is_alive()
        if self._returncode_thread is not None:
            finished = finished and not self._returncode_thread.is_alive()
        return finished

    def process_is_running(self):
        running = True
        if self._ping_thread is not None:
            running = self._ping_thread.is_alive()
        if self._returncode_thread is not None:
            running = running and self._returncode_thread.is_alive()
        return running

    def start_monitoring(self):
        if self.ping_it:
            self._ping_thread = threading.Thread(target=self.ping_monitor, args=())
            self._ping_thread.daemon = True
            self._ping_thread.start()
        if self.check_returncode:
            self._returncode_thread = threading.Thread(target=self.returncode_monitor, args=())
            self._returncode_thread.daemon = True
            self._returncode_thread.start()

    def ping_monitor(self):
        is_alive = True
        try:
            while not self._stop_monitoring and is_alive:
                time.sleep(2)
                if self.rq_sock is not None:
                    send_msg(self.rq_sock, self._mtool.fill_msg('ping'))
                    result = None
                    while self._ping_retries and not result and not self._stop_monitoring:
                        result, det = self._poller.poll_recv(socket=self.rq_sock, timeout=1500)
                    if not result and not self._stop_monitoring:
                        self.logger.info("%s %s %s", 
                                self.proc_type, self.name, "NO RESPONSE TO PING!")
                        with self._status_lock:
                            if self._status not in [FAILED, FINISHED]:
                                self._status = NON_RESPONSIVE
                                self._status_details = 'ping response timeout'
                            print "status:", self._status
                            is_alive = False
        finally:
            self.rq_sock.close(linger=0)


    def returncode_monitor(self):
        raise NotImplementedError()

    def kill(self):
        raise NotImplementedError()

    def mark_delete(self):
        with self._status_lock:
            self.delete = True

    def marked_delete(self):
        with self._status_lock:
            return self.delete
开发者ID:niklasrogers,项目名称:openbci,代码行数:104,代码来源:process.py


注:本文中的obci.control.common.message.OBCIMessageTool.fill_msg方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。