Exemple #1
0
def main():
    """Creates a new TCP server that serves up random EEG-like data in the
    DSI format. The server can be stopped with a Keyboard Interrupt (Ctl-C)"""

    import time
    import sys

    # Allow the script to be run from the bci root, acquisition dir, or
    # demo dir.
    sys.path.append('.')
    sys.path.append('..')
    sys.path.append('../..')

    import bcipy.acquisition.datastream.generator as generator
    import bcipy.acquisition.protocols.registry as registry
    from bcipy.acquisition.datastream.server import DataServer

    # Find the DSI protocol by name.
    protocol = registry.default_protocol('DSI')

    try:
        server = DataServer(protocol=protocol,
                            generator=generator.random_data,
                            gen_params={'channel_count': len(
                                protocol.channels)},
                            host='127.0.0.1', port=9000)
        server.start()
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Keyboard Interrupt")
        server.stop()
def main():
    """Creates a sample client that reads data from a sample TCP server
    (see demo/server.py). Data is written to a rawdata.csv file, as well as a
    buffer.db sqlite3 database. These files are written in whichever directory
    the script was run.

    The client/server can be stopped with a Keyboard Interrupt (Ctl-C)."""

    import time
    import sys

    # Allow the script to be run from the bci root, acquisition dir, or
    # demo dir.
    sys.path.append('.')
    sys.path.append('..')
    sys.path.append('../..')

    from bcipy.acquisition.datastream import generator
    from bcipy.acquisition.protocols import registry
    from bcipy.acquisition.client import DataAcquisitionClient
    from bcipy.acquisition.datastream.server import DataServer

    host = '127.0.0.1'
    port = 9000
    # The Protocol is for mocking data.
    protocol = registry.default_protocol('DSI')
    server = DataServer(protocol=protocol,
                        generator=generator.random_data,
                        gen_params={'channel_count': len(protocol.channels)},
                        host=host, port=port)

    # Device is for reading data.
    # pylint: disable=invalid-name
    Device = registry.find_device('DSI')
    dsi_device = Device(connection_params={'host': host, 'port': port})
    client = DataAcquisitionClient(device=dsi_device)

    try:
        server.start()
        client.start_acquisition()

        print("\nCollecting data for 10s... (Interrupt [Ctl-C] to stop)\n")

        while True:
            time.sleep(10)
            client.stop_acquisition()
            client.cleanup()
            print("Number of samples: {0}".format(client.get_data_len()))
            server.stop()
            print("The collected data has been written to rawdata.csv")
            break

    except KeyboardInterrupt:
        print("Keyboard Interrupt; stopping.")
        client.stop_acquisition()
        client.cleanup()
        print("Number of samples: {0}".format(client.get_data_len()))
        server.stop()
        print("The collected data has been written to rawdata.csv")
Exemple #3
0
def main():
    """Creates a sample client that reads data from a sample TCP server
    (see demo/server.py). Data is written to a buffer.db sqlite3 database
    and streamed through a GUI. These files are written in whichever directory
    the script was run.

    The client/server can be stopped with a Keyboard Interrupt (Ctl-C)."""

    import time

    from bcipy.acquisition.datastream import generator
    from bcipy.acquisition.protocols import registry
    from bcipy.acquisition.client import DataAcquisitionClient
    from bcipy.acquisition.datastream.server import DataServer
    from bcipy.gui.viewer.processor.viewer_processor import ViewerProcessor

    host = '127.0.0.1'
    port = 9000
    # The Protocol is for mocking data.
    protocol = registry.default_protocol('DSI')
    server = DataServer(protocol=protocol,
                        generator=generator.random_data,
                        gen_params={'channel_count': len(protocol.channels)},
                        host=host,
                        port=port)

    # Device is for reading data.
    # pylint: disable=invalid-name
    Device = registry.find_device('DSI')
    dsi_device = Device(connection_params={'host': host, 'port': port})
    client = DataAcquisitionClient(device=dsi_device,
                                   processor=ViewerProcessor())

    try:
        server.start()
        client.start_acquisition()
        seconds = 10
        print(
            f"\nCollecting data for {seconds}s... (Interrupt [Ctl-C] to stop)\n"
        )

        t0 = time.time()
        elapsed = 0
        while elapsed < seconds:
            time.sleep(0.1)
            elapsed = (time.time()) - t0
        client.stop_acquisition()
        client.cleanup()
        print("Number of samples: {0}".format(client.get_data_len()))
        server.stop()

    except KeyboardInterrupt:
        print("Keyboard Interrupt; stopping.")
        client.stop_acquisition()
        client.cleanup()
        print("Number of samples: {0}".format(client.get_data_len()))
        server.stop()
Exemple #4
0
def main():
    """Initialize and run the server."""
    import argparse

    from bcipy.acquisition.datastream.generator import file_data, random_data
    from bcipy.acquisition.protocols.registry import protocol_with, \
        default_protocol

    parser = argparse.ArgumentParser()
    parser.add_argument('-H', '--host', default='127.0.0.1')
    parser.add_argument('-p', '--port', type=int, default=8844)
    parser.add_argument('-f',
                        '--filename',
                        default=None,
                        help="file containing data to be streamed; "
                        "if missing, random data will be served.")
    args = parser.parse_args()

    if args.filename:
        daq_type, sample_hz, channels = _settings(args.filename)
        protocol = protocol_with(daq_type, sample_hz, channels)
        generator, params = (file_data, {'filename': args.filename})
    else:
        protocol = default_protocol('DSI')
        channel_count = len(protocol.channels)
        generator, params = (random_data, {'channel_count': channel_count})

    try:
        server = DataServer(protocol=protocol,
                            generator=generator,
                            gen_params=params,
                            host=args.host,
                            port=args.port)
        log.debug("New server created")
        server.start()
        log.debug("Server started")
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Keyboard Interrupt")
        server.stop()
Exemple #5
0
def init_eeg_acquisition(parameters: dict,
                         save_folder: str,
                         clock=CountClock(),
                         server: bool = False):
    """Initialize EEG Acquisition.

    Initializes a client that connects with the EEG data source and begins
    data collection.

    Parameters
    ----------
        parameters : dict
            configuration details regarding the device type and other relevant
            connection information.
             {
               "acq_device": str,
               "acq_host": str,
               "acq_port": int,
               "buffer_name": str,
               "raw_data_name": str
             }
        clock : Clock, optional
            optional clock used in the client; see client for details.
        server : bool, optional
            optionally start a server that streams random DSI data; defaults
            to true; if this is True, the client will also be a DSI client.
    Returns
    -------
        (client, server) tuple
    """

    # Initialize the needed DAQ Parameters
    host = parameters['acq_host']
    port = parameters['acq_port']

    parameters = {
        'acq_show_viewer': parameters['acq_show_viewer'],
        'viewer_screen': 1 if int(parameters['stim_screen']) == 0 else 0,
        'buffer_name': save_folder + '/' + parameters['buffer_name'],
        'device': parameters['acq_device'],
        'filename': save_folder + '/' + parameters['raw_data_name'],
        'connection_params': {
            'host': host,
            'port': port
        }
    }

    # Set configuration parameters (with default values if not provided).
    buffer_name = parameters.get('buffer_name', 'buffer.db')
    connection_params = parameters.get('connection_params', {})
    device_name = parameters.get('device', 'DSI')
    filename = parameters.get('filename', 'rawdata.csv')

    dataserver = False
    if server:
        if device_name == 'DSI':
            protocol = registry.default_protocol(device_name)
            dataserver, port = start_socket_server(protocol, host, port)
            connection_params['port'] = port
        elif device_name == 'LSL':
            channel_count = 16
            sample_rate = 256
            channels = ['ch{}'.format(c + 1) for c in range(channel_count)]
            dataserver = LslDataServer(
                params={
                    'name': 'LSL',
                    'channels': channels,
                    'hz': sample_rate
                },
                generator=generator.random_data(channel_count=channel_count))
            await_start(dataserver)
        else:
            raise ValueError(
                'Server (fake data mode) for this device type not supported')

    Device = registry.find_device(device_name)

    filewriter = FileWriter(filename=filename)
    proc = filewriter
    if parameters['acq_show_viewer']:
        proc = DispatchProcessor(
            filewriter,
            ViewerProcessor(display_screen=parameters['viewer_screen']))

    # Start a client. We assume that the channels and fs will be set on the
    # device; add a channel parameter to Device to override!
    client = DataAcquisitionClient(
        device=Device(connection_params=connection_params),
        processor=proc,
        buffer_name=buffer_name,
        clock=clock)

    client.start_acquisition()

    # If we're using a server or data generator, there is no reason to
    # calibrate data.
    if server and device_name != 'LSL':
        client.is_calibrated = True

    return (client, dataserver)
Exemple #6
0
    parser = argparse.ArgumentParser()
    parser.add_argument('-H', '--host', default='127.0.0.1')
    parser.add_argument('-p', '--port', type=int, default=8844)
    parser.add_argument('-f',
                        '--filename',
                        default=None,
                        help="file containing data to be streamed; "
                        "if missing, random data will be served.")
    args = parser.parse_args()

    if args.filename:
        daq_type, fs, channels = _settings(args.filename)
        protocol = protocol_with(daq_type, fs, channels)
        generator, params = (file_data, {'filename': args.filename})
    else:
        protocol = default_protocol('DSI')
        channel_count = len(protocol.channels)
        generator, params = (random_data, {'channel_count': channel_count})

    try:
        server = DataServer(protocol=protocol,
                            generator=generator,
                            gen_params=params,
                            host=args.host,
                            port=args.port)
        logging.debug("New server created")
        server.start()
        logging.debug("Server started")
        while True:
            time.sleep(1)
    except KeyboardInterrupt: