예제 #1
0
def init_eeg_acquisition(parameters, save_folder,
                         clock=_Clock(), server=False):
    """
    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 = {
        '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':
            channels = ['ch{}'.format(c + 1) for c in range(16)]
            dataserver = LslDataServer(params={'name': 'LSL',
                                               'channels': channels,
                                               'hz': 256},
                                       generator=generator.random_data(
                                           channel_count=16))
            await_start(dataserver)

    Device = registry.find_device(device_name)

    # 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 = Client(device=Device(connection_params=connection_params),
                    processor=FileWriter(filename=filename),
                    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:
        client.is_calibrated = True

    return (client, dataserver)
예제 #2
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', 'raw_data.db')
    connection_params = parameters.get('connection_params', {})
    device_name = parameters.get('device', 'DSI')

    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)

    # 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),
        buffer_name=buffer_name,
        delete_archive=False,
        raw_data_file_name=parameters.get('filename', 'raw_data.csv'),
        clock=clock)

    client.start_acquisition()
    if parameters['acq_show_viewer']:
        start_viewer(display_screen=parameters['viewer_screen'])

    # 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)
예제 #3
0
 def default_data_server(self):
     return LslDataServer(device_spec=self.device_spec)
예제 #4
0
def main():
    # pylint: disable=too-many-locals
    """Creates a sample lsl 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.lsl_server import LslDataServer
    from bcipy.acquisition.datastream.server import await_start

    host = '127.0.0.1'
    port = 9000

    channel_count = 16
    sample_rate = 256
    channels = ['ch{}'.format(c + 1) for c in range(channel_count)]
    # The Protocol is for mocking data.
    server = LslDataServer(params={'name': 'LSL',
                                   'channels': channels,
                                   'hz': sample_rate},
                           generator=generator.random_data(
                               channel_count=channel_count))
    await_start(server)

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

    try:
        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")