예제 #1
0
 def setUp(self):
     """Run before each test."""
     self.server = LslDataServer(
         params={
             'name': 'LSL',
             'channels': self.channels,
             'hz': self.hz
         },
         generator=generator.random_data(channel_count=self.channel_count),
         include_meta=self.include_meta,
         add_markers=True)
     await_start(self.server)
예제 #2
0
def main():
    """Initialize and start the server."""
    import time
    import argparse

    from bcipy.acquisition.datastream.generator import file_data, random_data

    default_channels = ['ch' + str(i + 1) for i in range(16)]

    parser = argparse.ArgumentParser()
    parser.add_argument('-f',
                        '--filename',
                        default=None,
                        help="file containing data to be streamed; "
                        "if missing, random data will be served.")
    parser.add_argument('-c',
                        '--channels',
                        default=','.join(default_channels),
                        help='comma-delimited list')
    parser.add_argument('-s',
                        '--sample_rate',
                        default='256',
                        help='sample rate in hz')

    parser.add_argument('-m', '--markers', action="store_true", default=False)
    parser.add_argument('-n', '--name', default='LSL')
    args = parser.parse_args()

    params = {
        'channels': args.channels.split(','),
        'hz': int(args.sample_rate)
    }

    # Generate data from the file if provided, otherwise random data.
    generator = file_data(filename=args.filename) if args.filename \
        else random_data(channel_count=len(params['channels']))

    markers = True if args.markers else False
    try:
        server = LslDataServer(params=params,
                               generator=generator,
                               add_markers=markers,
                               name=args.name)

        logging.debug("New server created")
        server.start()
        logging.debug("Server started")
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Keyboard Interrupt")
        server.stop()
예제 #3
0
    def __init__(self,
                 queue,
                 freq=1 / 100,
                 generator=random_data(),
                 maxiters=None):

        super(Producer, self).__init__()
        self.daemon = True
        self._running = True

        self.freq = freq
        self.generator = generator
        self.maxiters = maxiters
        self.queue = queue
예제 #4
0
    def test_random_with_custom_encoder(self):
        """Random generator should allow a custom encoder."""

        channel_count = 10
        gen = random_data(encoder=CustomEncoder(),
                          channel_count=channel_count)

        data = [next(gen) for _ in range(100)]

        self.assertEqual(len(data), 100)
        for _count, record in data:
            self.assertEqual(len(record), channel_count)

        self.assertEqual(data[0][0], 1)
        self.assertEqual(data[99][0], 100)
예제 #5
0
    def test_random_high_low_values(self):
        """Random generator should allow user to set value ranges."""
        channel_count = 10
        low = -100
        high = 100
        gen = random_data(low=-100, high=100,
                          channel_count=channel_count)
        data = [next(gen) for _ in range(100)]

        self.assertEqual(len(data), 100)

        for record in data:
            self.assertEqual(len(record), channel_count)
            for value in record:
                self.assertTrue(low <= value <= high)
예제 #6
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)
예제 #7
0
 def test_random_generator(self):
     """Test default parameters for random generator"""
     gen = random_data()
     data = [next(gen) for _ in range(100)]
     self.assertEqual(len(data), 100)
예제 #8
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")