Example #1
0
 def __init__(self, name=LSL_STREAM_NAMES[2], max_chunklen=8, n_channels=20):
     streams = resolve_byprop('name', name, timeout=LSL_RESOLVE_TIMEOUT)
     self.inlet = None
     self.dtype = 'float64'
     if len(streams) > 0:
         self.inlet = StreamInlet(streams[0], max_buflen=1, max_chunklen=max_chunklen)
         # self.dtype = fmt2string[self.inlet.info().channel_format()]
         print(self.dtype)
     self.n_channels = n_channels if n_channels else self.inlet.info().channel_count()
Example #2
0
    def __init__(self, name=LSL_STREAM_NAMES[2], only_this_host=False):
        if not only_this_host:
            streams = resolve_byprop('name', name, timeout=LSL_RESOLVE_TIMEOUT)
        else:
            streams = resolve_bypred("name='{}' and hostname='{}'".format(name, socket.gethostname()))

        self.inlet = None
        self.dtype = 'float64'
        if len(streams) > 0:
            self.inlet = FixedStreamInlet(streams[0], max_buflen=2)
            # self.dtype = fmt2string[self.inlet.info().channel_format()]
            print(self.dtype)
Example #3
0
def peek(stream_name):
    """ Connects to the specified stream and checks if it outputs samples """
    # TODO This functionality does not work yet
    stream = pylsl.resolve_byprop('name', stream_name)[0]
    if stream:
        inlet = pylsl.StreamInlet(stream)
        time.sleep(3)
        try:
            while True:
                sample, time_stamp = inlet.pull_sample(timeout=0)
                print('[%d] %s' % (time_stamp, sample))
        except KeyboardInterrupt:
            print('Terminating peek')
Example #4
0
def source2stream_inlet(source: Source, timeout=FOREVER) -> StreamInfo:
    streams_info =  resolve_byprop('source_id', source.source_id,
                                   timeout=timeout)
    if len(streams_info) == 1:
        stream_info = streams_info[0]
        return StreamInlet(stream_info)

    elif len(streams_info) > 1:
        raise ConnectionError(
            'More than one source found for {}'.format(source.source_id))

    else:
        raise ConnectionError(
            'No source {} found for receiving'.format(source.source_id))
Example #5
0
def main(csv_out_path):
    logger.info("Looking for Pupil Capture streams...")
    streams = pylsl.resolve_byprop("name", "pupil_capture", timeout=TIMEOUT)

    if not streams:
        logger.error("No LSL streams of name 'pupil_capture' found")
        exit(-1)

    logger.info("Connecting to {}".format(streams[0].hostname()))
    inlet = pylsl.StreamInlet(streams[0])
    inlet.open_stream(timeout=TIMEOUT)

    logger.info("Recording at {}".format(csv_out_path))
    record(inlet, csv_out_path)
Example #6
0
def start_grapher(stream_name=None, buffer_size=512):
    buffer_size = int(buffer_size)  # Can be string if given as argument!
    if stream_name:
        streams = pylsl.resolve_byprop('name', stream_name, timeout=5)
    else:
        streams = None

    if streams:
        stream_info = lslscan.get_stream_info_string(streams[0])
        print('Connecting to stream: {}'.format(stream_info))
        Grapher(streams[0], buffer_size)
    elif stream_name:
        print('No stream by name {} found...'.format(stream_name))
        lslscan.scan_ui()

    else:
        lslscan.scan_ui()
Example #7
0
def read_EEG_stream(fs=500, max_buf=2):
    # Initialize EEG stream
    # Arguments:
    #   fs: sampling frequency
    # timeout: max time to look for whether EEG stream is available (seconds)
    #   max_buf: maximum data to have in buffer (seconds)

    streamsEEG = resolve_byprop('type', 'EEG', timeout=1)
    inlet_EEG = StreamInlet(streamsEEG[0], max_buflen=max_buf)
    store_EEG = data_init(fs, 'EEG')  # Initialize object
    store_EEG.header = [
        'P7', 'P4', 'Cz', 'Pz', 'P3', 'P8', 'O1', 'O2', 'T8', 'F8', 'C4', 'F4',
        'Fp2', 'Fz', 'C3', 'F3', 'Fp1', 'T7', 'F7', 'Oz', 'PO3', 'AF3', 'FC5',
        'FC1', 'CP5', 'CP1', 'CP2', 'CP6', 'AF4', 'FC2', 'FC6', 'PO4',
        'Timestamp'
    ]
    return inlet_EEG, store_EEG
Example #8
0
def start_grapher(stream_name=None, buffer_size=512):
    buffer_size = int(buffer_size)  # Can be string if given as argument!
    if stream_name:
        streams = pylsl.resolve_byprop("name", stream_name, timeout=5)
    else:
        streams = None

    if streams:
        stream_info = lslscan.get_stream_info_string(streams[0])
        print("Connecting to stream: {}".format(stream_info))
        Grapher(streams[0], buffer_size)
    elif stream_name:
        print("No stream by name {} found...".format(stream_name))
        lslscan.scan_ui()

    else:
        lslscan.scan_ui()
    def receiver(self):
        """ Receive data from an LSL stream and store it in a circular
            buffer.
        """

        streams = []

        while not streams:
            print("Trying to connect to the stream: " + self.lsl_stream_name)
            streams = lsl.resolve_byprop('name',
                                         self.lsl_stream_name,
                                         timeout=10)
            if not streams:
                print("\tStream not found, re-trying...")

        inlet = lsl.StreamInlet(streams[0], max_buflen=1)
        print("\tDone")

        i = 0
        self.primary_last_time.value = 0  # init the last_time value
        while self.run_state.value:
            x, t = inlet.pull_sample()
            self.primary_last_sample_received.value = time.time()

            self.primary_lock.acquire()  # LOCK-ON

            for k in range(self.primary_n_channels):
                self.primary_channel_data[k][self.primary_wptr.value] = x[k]

            if t is None:
                t = self.primary_last_time.value + self.primary_sampling_rate

            self.primary_time_array[self.primary_wptr.value] = t
            self.primary_last_time.value = t

            i += 1
            self.primary_wptr.value = i % self.primary_buffer_size
            self.primary_lock.release()  # LOCK-OFF

            # is the buffer full
            if (0 == self.primary_buffer_full.value) and (
                    i >= self.primary_buffer_size):
                self.primary_buffer_full.value = 1
        # Ending run, clear inlet
        inlet.close_stream()
Example #10
0
    def start_sensor(self):
        # connect to the sensor
        self.dreader = DEAPReader(self.sampling_rate)
        self.stream_process = threading.Thread(target=self.dreader.run,
                                               args=(self.deap_data,
                                                     self.outlet))

        self.stream_process.start()
        self.streams = resolve_byprop('name', self.lsl_data_type, timeout=1)
        if len(self.streams) < 1:
            raise AttributeError(
                'Unable to find LSL Stream with given type {0}'.format(
                    self.lsl_data_type))
        self.inlet = StreamInlet(self.streams[0])
        self.inlet.open_stream()
        print(
            'LSLInletInterface: resolved, created and opened inlet for lsl stream with type '
            + self.lsl_data_type)
Example #11
0
def setup():
    # setup LSL
    global outlet
    streams = resolve_byprop('name', LSL_STREAM_NAME, timeout=5)
    '''
  try:
  inlet = StreamInlet(streams[0])
  except IndexError:
  raise ValueError('Make sure stream name="%s", is opened first.'
  % LSL_STREAM_NAME)
  '''
    running = True

    info = StreamInfo(LSL_BCI_STREAM_NAME, 'eeg', LSL_BCI_NUM_CHANNELS,
                      LSL_BCI_SAMPLE_RATE, 'float32', 'uid2')
    outlet = StreamOutlet(info)

    print('lsl stream has been setup')
Example #12
0
    def receiver(self):
        """ Receive data from an LSL stream and store it in a circular
            buffer.
        """

        streams = []

        while not streams:
            print("Trying to connect to the stream: " + self.lsl_stream_name)
            streams = lsl.resolve_byprop(
                'name',
                self.lsl_stream_name,
                timeout=10)
            if not streams:
                print("\tStream not found, re-trying...")

        inlet = lsl.StreamInlet(streams[0], max_buflen=1)
        print("\tDone")

        i = 0
        self.last_time.value = 0  # init the last_time value
        while self.run_state.value:
            x, t = inlet.pull_sample()

            self.lock_primary.acquire()  # LOCK-ON

            for k in range(self.n_channels):
                self.channel_data[k][self.wptr.value] = x[k]

            if t is None:
                t = self.last_time.value + self.sampling_rate

            self.time_array[self.wptr.value] = t
            self.last_time.value = t

            i += 1
            self.wptr.value = i % self.buffer_size
            self.lock_primary.release()  # LOCK-OFF

            # is the buffer full
            if (0 == self.buffer_full.value) and (i >= self.buffer_size):
                self.buffer_full.value = 1
        # Ending run, clear inlet
        inlet.close_stream()
    def __init__(self):

        self.buffer = buffer
        print("looking for an EEG stream...")
        self.streams = resolve_byprop('type', 'EEG', timeout=2)
        if len(self.streams) == 0:
            raise (RuntimeError("Cant find EEG stream"))
        print("Start aquiring data")
        self.stream = self.streams[0]
        self.inlet = StreamInlet(self.stream, max_chunklen=buffer)
        self.count = 0
        self.chunks = 5
        self.avg_len = 10
        self.lazy_low = 0.9
        self.lazy_high = 1.1
        self.buf = CircularBuffer(self.chunks)

        self.noise = {
            'Delta': False,
            'Theta': False,
            'Alpha': False,
            'Beta': False
        }

        self.state = {
            'Delta': 'Low',
            'Theta': 'Low',
            'Alpha': 'Low',
            'Beta': 'Low'
        }

        self.low_bound = {
            'Delta': self.lazy_low,
            'Theta': self.lazy_low,
            'Alpha': self.lazy_low,
            'Beta': self.lazy_low
        }
        self.high_bound = {
            'Delta': self.lazy_high,
            'Theta': self.lazy_high,
            'Alpha': self.lazy_high,
            'Beta': self.lazy_high
        }
        self._stop_loop = False
Example #14
0
    def __init__(self, source_id='classifier_output'):
        """
        Parameters
        ----------
        source_id : str
            Pylsl stream source_id for incoming data
            Default 'classifier_output'
        """
        print("looking for stream \"" + str(source_id) + "\"...")
        # streams = resolve_byprop('source_id', source_id, timeout=5)
        streams = resolve_byprop('source_id', source_id, timeout=5)
        if not streams:
            raise TimeoutError('Stream \"' + str(source_id) +
                               '\" not found, timeout expired.')

        self.inlet = StreamInlet(
            streams[0], max_buflen=1
        )  # max_buflen=1 for real time (samples will be dropped instead instead of buffered)
        print('found')
Example #15
0
 def __init__(self, sensor_type='eeg', port=1331):
     print("Starting EEG Data Handler...")
     ctx = zmq.Context()
     self.sensor_type = sensor_type
     self.sock = ctx.socket(zmq.PUB)
     self.sock.setsockopt(zmq.SNDTIMEO, 1000)
     self.sock.setsockopt(zmq.LINGER, 1000)
     self.sock.setsockopt(zmq.IMMEDIATE, 1)
     self.sock.bind(f"tcp://127.0.0.1:{port}")
     self.current_lsl_streams = pylsl.resolve_byprop('type',
                                                     'EEG',
                                                     timeout=5)
     print(type(self.current_lsl_streams))
     print("Started")
     if self.sensor_type == 'eeg':
         # Set our data type to our chunk
         self.dtype = EEGDataChunk(4, 12, None)
     else:
         print("other types are not implemented...")
Example #16
0
    def _muse_get_recent(self,
                         n_samples: int = 256,
                         restart_inlet: bool = False):
        if self._muse_recent_inlet and not restart_inlet:
            inlet = self._muse_recent_inlet
        else:
            # Initiate a new lsl stream
            streams = resolve_byprop("type",
                                     "EEG",
                                     timeout=mlsl_cnsts.LSL_SCAN_TIMEOUT)
            if not streams:
                raise Exception(
                    "Couldn't find any stream, is your device connected?")
            inlet = StreamInlet(streams[0],
                                max_chunklen=mlsl_cnsts.LSL_EEG_CHUNK)
            self._muse_recent_inlet = inlet

        info = inlet.info()
        sfreq = info.nominal_srate()
        description = info.desc()
        n_chans = info.channel_count()

        self.sfreq = sfreq
        self.info = info
        self.n_chans = n_chans

        timeout = (n_samples / sfreq) + 0.5
        samples, timestamps = inlet.pull_chunk(timeout=timeout,
                                               max_samples=n_samples)

        samples = np.array(samples)
        timestamps = np.array(timestamps)

        ch = description.child("channels").first_child()
        ch_names = [ch.child_value("label")]
        for i in range(n_chans):
            ch = ch.next_sibling()
            lab = ch.child_value("label")
            if lab != "":
                ch_names.append(lab)

        df = pd.DataFrame(samples, index=timestamps, columns=ch_names)
        return df
Example #17
0
    def listen_speed_markers(self):
        count = 0
        while self.controller.running:
            streams = resolve_byprop('name', 'Oddball_speed', timeout=1)

            if len(streams) > 0:
                inlet = StreamInlet(streams[0])
                print("oddball_speed stream found ")
                while self.controller.running:
                    sample, timestamp = inlet.pull_sample(timeout=1)
                    if timestamp is not None:
                        print("got new speed %s at time %s" %
                              (sample[0], timestamp))
                        self.ITI = int(sample[0])

                print('Close listening socket')
            else:
                print(count, "oddball_speed inlet not found")
                count += 1
    def _graph_lsl(self):
        print('checking if stream has be initialized')
        self.streams = resolve_byprop('name', 'bci', timeout=2.5)
        try:
            self.inlet = StreamInlet(self.streams[0])
        except IndexError:
            raise ValueError('Make sure stream name=bci is opened first.')
        while self.running:
            # initial run
            self.sample, self.timestamp = self.inlet.pull_sample(timeout=5)
            # time correction to sync to local_clock()
            try:
                if self.timestamp is not None and self.sample is not None:
                    self.timestamp = self.timestamp + self.inlet.time_correction(
                        timeout=5)

            except TimeoutError:
                pass
            self.SecondTimes.append(
                self.sample[1])  #add time stamps to array 'timeValSeconds'
            self.ProcessedSig.append(
                self.sample[0])  #add processed signal values to 'processedSig'

            self.count = self.count + 1

            if ((self.count % 20 == 0) and
                (self.count !=
                 0)):  #every 20 samples (ie ~ 0.10 s) is when plot updates
                self.lineHandle[0].set_ydata(self.ProcessedSig)
                self.lineHandle[0].set_xdata(self.SecondTimes)
                #plt.xlim(0, 5)
                plt.xlim(self.SecondTimes[0], self.SecondTimes[-1])
                plt.ylim(0, 10)
                plt.pause(0.01)

            if (self.count >= 399):
                self.ProcessedSig.pop(0)
                self.SecondTimes.pop(0)

        plt.pause(0.01)
        print('closing graphing utility')
        self.inlet.close_stream()
Example #19
0
    def __init__(self):
        from muselsl import stream, list_muses
        from pylsl import StreamInlet, resolve_byprop

        muses = list_muses()

        # stream module connects with Muse, but doesn't start streaming data
        self.muse_ble_connect = multiprocessing.Process(
            target=stream, args=(muses[0]["address"], ))
        self.muse_ble_connect.start()

        time.sleep(10)

        self.streams = resolve_byprop("type", "EEG", timeout=2)
        self.inlet = StreamInlet(self.streams[0], max_chunklen=1)

        Helmet.__init__(self)

        self.channels_number = 4
        self.sampling_rate = 256
Example #20
0
 def run(self):
     sinfo = pylsl.resolve_byprop("name", "localite_marker")[0]
     stream = pylsl.StreamInlet(sinfo)
     msg = []
     time.sleep(1)
     msg, t1 = stream.pull_chunk()
     self.running = True
     while self.running:
         try:
             msg, t1 = stream.pull_chunk()
             print(msg)
             if msg == []:
                 time.sleep(0.001)
             else:
                 self.running = False
         except pylsl.pylsl.LostError:
             break
     self.msg = msg
     self.t1 = t1
     del stream
Example #21
0
    def __init__(self, device, max_chunklen=0, stream_type='EEG'):

        streams = resolve_byprop('type', stream_type, timeout=2)
        if len(streams) == 0:
            raise RuntimeError('no EEG stream found')

        inlet, timecorrect, info, descrition, sampling_f, num_channels = self.get_Stream_Info(
            streams)

        ## getting the names of the channels, not sure if this is needed
        ch = descrition.child('channels').first_child()
        self.ch_names = [ch.child_value('label')]
        for i in range(1, num_channels):
            ch = ch.next_sibling()
            self.ch_names.append(ch.child_value('label'))

        ## getting the buffer lengths, epoch lengths, overlap
        buffer_len = 15  ## change to a user input (or from device)
        epoch_len = 1  #same as above comment
        overlap_len = 0.8  # this is also dependent of the device file
Example #22
0
    def __init__(self):
        # check device manager for correct COM port.
        self.board = bci.OpenBCIBoard(port='COM3',
                                      filter_data=True,
                                      daisy=False)

        # setup LSL
        streams = resolve_byprop('name', self.LSL_STREAM_NAME, timeout=2.5)
        try:
            self.inlet = StreamInlet(streams[0])
        except IndexError:
            raise ValueError('Make sure stream name="%s", is opened first.' %
                             LSL_STREAM_NAME)

        self.running = True
        self.samples = []

        info = StreamInfo(self.LSL_BCI_STREAM_NAME, 'eeg',
                          self.LSL_BCI_NUM_CHANNELS, self.LSL_BCI_SAMPLE_RATE,
                          'float32', 'uid2')
        self.outlet = StreamOutlet(info)
    def __init__(self):
        print("looking for an EEG stream...")
        streams = resolve_byprop("type", "EEG")

        # create a new inlet to read from the stream
        proc_flags = proc_clocksync | proc_dejitter | proc_monotonize
        self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)

        # The following is an example of how to read stream info
        stream_info = self.inlet.info()
        stream_Fs = stream_info.nominal_srate()
        stream_xml = stream_info.desc()
        chans_xml = stream_xml.child("channels")
        chan_xml_list = []
        ch = chans_xml.child("channel")
        while ch.name() == "channel":
            chan_xml_list.append(ch)
            ch = ch.next_sibling("channel")
        self.channel_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
        print("Reading from inlet named {} with channels {} sending data at {} Hz".format(stream_info.name(),
                                                                                          self.channel_names, stream_Fs))
Example #24
0
    def __init__(self):
        Thread.__init__(self)
        # Enough for 1 sec at 256 Hz                                                                               
        self.BUFFER = 256
        print("looking for an EEG stream...")
        self.streams = resolve_byprop('type', 'EEG', timeout=2)
        
        if len(self.streams) == 0:
            raise(RuntimeError("Cant find EEG stream"))
        print("Start aquiring data")

        self.stream = self.streams[0]

        self.inlet = StreamInlet(self.stream, max_chunklen=BUFFER)
        self.times = []
        self.count = 0
        self.chunks = 3
        self.ave_len = 10
        self.ave = [0.0, 0.0]
        self.buf = CircularBuffer(self.chunks)
        self.state = 'noise'
Example #25
0
 def update(self):
     if not self._inlet:
         self.logger.debug(
             f"Resolving stream with {self._prop} {self._value}")
         streams = resolve_byprop(self._prop,
                                  self._value,
                                  timeout=self._timeout)
         if not streams:
             return
         self.logger.debug("Stream acquired")
         self._inlet = StreamInlet(streams[0])
         info = self._inlet.info()
         self._meta = {
             "name": info.name(),
             "type": info.type(),
             "rate": info.nominal_srate(),
             "info": str(info.as_xml()).replace("\n", "").replace("\t", ""),
         }
         if isinstance(self._channels, list):
             self._labels = self._channels
         else:
             description = info.desc()
             channel = description.child("channels").first_child()
             self._labels = [channel.child_value("label")]
             for _ in range(info.channel_count() - 1):
                 channel = channel.next_sibling()
                 self._labels.append(channel.child_value("label"))
     if self._inlet:
         values, stamps = self._inlet.pull_chunk(
             max_samples=self._max_samples)
         if stamps:
             stamps = pd.to_datetime(stamps, format=None, unit=self._unit)
             if self._sync == "local":
                 stamps += self._offset
             elif self._sync == "network":
                 stamps = (stamps + np.timedelta64(
                     self._inlet.time_correction() * 1e9, "ns") +
                           self._offset)
         self.o.set(values, stamps, self._labels, self._meta)
def record_eeg_filtered(r_length,
                        freq,
                        channel_i,
                        notch=False,
                        filter_state=None):
    streams = resolve_byprop('type', 'EEG', timeout=2)

    inlet = StreamInlet(streams[0], max_chunklen=12)
    """ Records EEG data from headset

    Arguments:

    r_length  -- how many seconds of data to record
    freq      -- sample rate
    channel_i -- channels to keep data from

    Returns:

    data      -- array of recorded data [sample, channel]

    """

    data, timestamps = inlet.pull_chunk(timeout=r_length + 1,
                                        max_samples=int(freq * r_length))

    data = np.array(data)[:, channel_i]

    if notch:
        if filter_state is None:
            filter_state = np.tile(lfilter_zi(NOTCH_B, NOTCH_A),
                                   (data.shape[1], 1)).T

        data, filter_state = lfilter(NOTCH_B,
                                     NOTCH_A,
                                     data,
                                     axis=0,
                                     zi=filter_state)

    return data
    def startRecording(self):
        self.recording = True

        try:
            while (self.recording == True):
                streams = resolve_byprop('type', 'EEG', timeout=2)
                inlet = StreamInlet(streams[0], max_chunklen=12)
                # Obtain EEG data from the LSL stream
                eeg_data, timestamp = inlet.pull_chunk(
                    timeout=1, max_samples=int(self.SHIFT_LENGTH * self.freq))

                ch_data = np.array(eeg_data)[:, self.INDEX_CHANNEL]

                # Update EEG data and apply filter
                self.eeg_raw, self.filter_state = BCI.update_buffer(
                    self.eeg_raw,
                    ch_data,
                    notch=True,
                    filter_state=self.filter_state)

        except KeyboardInterrupt:
            print("Exception")
def read_marker_stream(stream_name='alphaStream'):
    '''
    Reads stream from an outlet (alphaStream from run_CL script)
    
    '''
    index_alpha = []
    alpha_created = []
    streams = resolve_byprop('type', 'Markers', timeout=10)
    for i in range(len(streams)):
        if (streams[i].name() == stream_name):
            index_alpha.append(i)
            alpha_created.append(streams[i].created_at())
    if index_alpha:
        if len(index_alpha) > 1:
            #print("Not unique marker stream name, using most recent one")
            index_alpha = index_alpha[np.argmax(alpha_created)]
        #print ("alpha stream available")
        #inlet = StreamInlet(streams[index_alpha[0]]) #REAL ONE
        inlet = StreamInlet(streams[index_alpha[0]])
    else:
        print('Warning: No marker inlet available')
    return inlet
Example #29
0
  def __init__(self):
    pupil_queue = Queue()
    self.pupil_proc = Process(target=pupil_capture.alternate_launch,
                              args=((pupil_queue), ))
    self.pupil_proc.start()

    while True:
      pupil_msg = pupil_queue.get()
      print(pupil_msg)
      if 'tcp' in pupil_msg:
        self.ipc_sub_url = pupil_msg
      if 'EYE_READY' in pupil_msg:
        break

    context = zmq.Context()
    self.socket = zmq.Socket(context, zmq.SUB)
    monitor = self.socket.get_monitor_socket()

    self.socket.connect(self.ipc_sub_url)
    while True:
      status = recv_monitor_message(monitor)
      if status['event'] == zmq.EVENT_CONNECTED:
        break
      elif status['event'] == zmq.EVENT_CONNECT_DELAYED:
        pass
    print('Capturing from pupil on url %s.' % self.ipc_sub_url)
    self.socket.subscribe('pupil')

    # setup LSL
    streams = resolve_byprop('name', LSL_STREAM_NAME, timeout=2.5)
    try:
      self.inlet = StreamInlet(streams[0])
    except IndexError:
      raise ValueError('Make sure stream name="%s", is opened first.'
          % LSL_STREAM_NAME)

    self.running = True
    self.samples = []
Example #30
0
 def update(self):
     if not self._inlet:
         self.logger.debug(
             f'Resolving stream with {self._prop} {self._value}')
         streams = resolve_byprop(self._prop,
                                  self._value,
                                  timeout=self._timeout)
         if not streams: return
         self.logger.debug('Stream acquired')
         self._inlet = StreamInlet(streams[0])
         info = self._inlet.info()
         self._meta = {
             'name': info.name(),
             'type': info.type(),
             'rate': info.nominal_srate(),
             'info': str(info.as_xml()).replace('\n', '').replace('\t', '')
         }
         if isinstance(self._channels, list):
             self._labels = self._channels
         else:
             description = info.desc()
             channel = description.child('channels').first_child()
             self._labels = [channel.child_value('label')]
             for _ in range(info.channel_count() - 1):
                 channel = channel.next_sibling()
                 self._labels.append(channel.child_value('label'))
     if self._inlet:
         values, stamps = self._inlet.pull_chunk(
             max_samples=self._max_samples)
         if stamps:
             stamps = np.array(stamps)
             if self._sync == 'local':
                 stamps += self._offset
             elif self._sync == 'network':
                 stamps = stamps + self._inlet.time_correction(
                 ) + self._offset
             stamps = pd.to_datetime(stamps, format=None, unit=self._unit)
         self.o.set(values, stamps, self._labels, self._meta)
Example #31
0
def start_client(server_name):
    """
    Search and connect to an LSL server

    Params
    ------
    server_name:
        Name of the server to search

    Returns
    -------
    inlet:
        LSL client object

    """
    print('Searching for LSL server %s' % server_name)
    while True:
        streamInfos = pylsl.resolve_byprop("name", server_name)
        for sinfo in streamInfos:
            print('Found %s' % sinfo.name())
        '''
        if len(streamInfos) > 1:
            print('>> Error: More than 1 server with the same name %s found. Stopping.'% server_name)
            sys.exit(-1)
        elif len(streamInfos)==1:
            sinfo= streamInfos[0]
            break
        else:
            print('[cnbi_lsl] No desired LSL server found. Keep searching...')
            time.sleep(1.0)
        '''
        if len(streamInfos) == 0:
            print('[cnbi_lsl] No desired LSL server found. Keep searching...')
            time.sleep(1.0)
        else:
            sinfo = streamInfos[0]
            break
    return pylsl.StreamInlet(sinfo)
Example #32
0
def read_marker_stream(stream_name='MyMarkerStream3'):
    '''
    Initializes the marker stream (time stamps of the EEG data).
    
    # Arguments
        stream_name: string
    
     # Returns
        inlet_marker: pylsl object
            The marker/trigger inlet from experimentFunctions.py script.
            
        store_marker: class object
    '''
    index_lsl = []
    lsl_created = []
    streams = resolve_byprop('type', 'Markers',
                             timeout=10)  # Look for stream(s)
    for i in range(len(streams)):
        if (streams[i].name() == stream_name):
            index_lsl.append(i)
            lsl_created.append(
                streams[i].created_at())  # Store when the stream was created
    if index_lsl:
        if len(index_lsl) > 1:  # Multiple streams available
            print("Not unique marker stream name, using the most recent one")
            index_lsl = index_lsl[np.argmax(lsl_created)]
        else:  # One stream available
            index_lsl = index_lsl[np.argmax(lsl_created)]
        print("lsl stream available")
        inlet_marker = StreamInlet(streams[index_lsl])
        store_marker = data_init(settings.samplingRate,
                                 'marker')  # Initialize marker object
        store_marker.header = ['Marker', 'Timestamp']
    else:
        inlet_marker = []
        print('Warning: No marker inlet available')

    return inlet_marker, store_marker
Example #33
0
def dataReaderLSL(streamName, q):
    while True:
        print("Waiting for LSL stream")
        try:
            results = resolve_byprop(prop='name', value=streamName)
            while len(results) == 0:
                time.sleep(0.25)
            info = results[0]
            inlet = StreamInlet(info, recover=False)
            print("Streaming...")
            # Read data in forever
            try:
                while True:
                    data = inlet.pull_sample()
                    if data:
                        q.put(np.array(data[0]))
                    time.sleep(1 / 200)
            except Exception as e:
                print(e)
                pass
        except Exception as e:
            print(e)
            pass
Example #34
0
 def __init__(self, lsl_data_type, num_channels,
              sampling_rate):  # default board_id 2 for Cyton
     self.lsl_data_type = lsl_data_type
     self.lsl_num_channels = num_channels
     self.sampling_rate = sampling_rate
     with open('data/s01.dat', "rb") as f:
         deap_data = pickle.load(f, encoding="latin1")
     deap_data = np.array(deap_data['data'])
     # flatten so we have a continuous stream
     self.deap_data = deap_data.reshape(
         deap_data.shape[1], deap_data.shape[0] * deap_data.shape[2])
     self.dreader = None
     self.stream_process = None
     info = StreamInfo('DEAP Simulation', 'EEG', num_channels,
                       self.sampling_rate, 'float32', 'deapcontinuous')
     self.outlet = StreamOutlet(info, 32, 360)
     self.streams = resolve_byprop('name', self.lsl_data_type, timeout=1)
     if len(self.streams) < 1:
         raise AttributeError(
             'Unable to find LSL Stream with given type {0}'.format(
                 lsl_data_type))
     self.inlet = StreamInlet(self.streams[0])
     pass
Example #35
0
def dataReaderLSLChunk(streamName, q):
    while True:
        print("Waiting for LSL stream")
        try:
            results = resolve_byprop(prop='name', value=streamName)
            while len(results) == 0:
                time.sleep(0.25)
            info = results[0]
            inlet = StreamInlet(info, recover=False)
            print("Streaming...")
            # Read data in forever
            try:
                while True:
                    chunk, timestamps = inlet.pull_chunk()
                    if len(chunk) > 0:
                        q.put(np.array(chunk[len(chunk) - 1]))
                    time.sleep(1 / 120)
            except Exception as e:
                print(e)
                pass
        except Exception as e:
            print(e)
            pass
Example #36
0
    def _initialize(self):

        stream_infos = lsl.resolve_byprop(
            'name',
            self.source_name,
            timeout=self.SECONDS_TO_WAIT_FOR_THE_STREAM)
        if len(stream_infos) == 0:
            raise ValueError('Cannot find LSL stream with name {}'.format(
                self.source_name))
        elif len(stream_infos) > 1:
            raise ValueError('Multiple LSL streams with name {}.'.format(
                self.source_name))
        else:
            info = stream_infos[0]
            # self._inlet = lsl.StreamInlet(info)
            self._inlet = FixedStreamInlet(info)
            self._inlet.open_stream()
            frequency = info.nominal_srate()
            self.dtype = DTYPE
            channel_labels, channel_types = read_channel_labels_from_info(
                self._inlet.info())
            self.mne_info = mne.create_info(channel_labels,
                                            frequency,
                                            ch_types=channel_types)
    def __init__(self):
        print("looking for an EEG stream...")
        streams = resolve_byprop("type", "EEG")

        # create a new inlet to read from the stream
        proc_flags = proc_clocksync | proc_dejitter | proc_monotonize
        self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)

        # The following is an example of how to read stream info
        stream_info = self.inlet.info()
        stream_Fs = stream_info.nominal_srate()
        stream_xml = stream_info.desc()
        chans_xml = stream_xml.child("channels")
        chan_xml_list = []
        ch = chans_xml.child("channel")
        while ch.name() == "channel":
            chan_xml_list.append(ch)
            ch = ch.next_sibling("channel")
        self.channel_names = [
            ch_xml.child_value("label") for ch_xml in chan_xml_list
        ]
        print(
            "Reading from inlet named {} with channels {} sending data at {} Hz"
            .format(stream_info.name(), self.channel_names, stream_Fs))
    def listen_mouse_events(self):
        count = 0
        while self.controller.running:
            streams = resolve_byprop('name', 'MouseButtons', timeout=1)

            if len(streams) > 0:
                inlet = StreamInlet(streams[0])
                print("oddball_speed stream found ")
                while self.controller.running:
                    sample, timestamp = inlet.pull_sample(timeout=1)

                    # mouse_event = "MouseButtonRight pressed"
                    mouse_event = "MouseButtonX2 pressed"
                    if timestamp is not None and sample[0] == mouse_event:
                        if time.time() - self.last_pressed > 3:
                            self.last_pressed = time.time()
                            self.counting = not self.counting
                            print("got new speed %s at time %s" %
                                  (sample[0], timestamp))

                print('Close listening socket')
            else:
                print(count, "MouseButtons inlet not found")
            count += 1
Example #39
0
if __name__ == "__main__":

    """ 0. PARSE ARGUMENTS """
    parser = argparse.ArgumentParser(description='BCI Workshop example 2')
    parser.add_argument('channels', metavar='N', type=int, nargs='*',
        default=[0, 1, 2, 3],
        help='channel number to use. If not specified, all the channels are used')

    args = parser.parse_args()

    """ 1. CONNECT TO EEG STREAM """

    # Search for active LSL stream
    print('Looking for an EEG stream...')
    streams = resolve_byprop('type', 'EEG', timeout=2)
    if len(streams) == 0:
        raise RuntimeError('Can\'t find EEG stream.')

    # Set active EEG stream to inlet and apply time correction
    print("Start acquiring data")
    inlet = StreamInlet(streams[0], max_chunklen=12)
    eeg_time_correction = inlet.time_correction()

    # Get the stream info, description, sampling frequency, number of channels
    info = inlet.info()
    description = info.desc()
    fs = int(info.nominal_srate())
    n_channels = info.channel_count()

    # Get names of all channels
Example #40
0
import tkinter as tk

from eegstream.gui import Monitor
from eegstream.streaming.signal import SignalInterface

if __name__ == "__main__":
    from pylsl import resolve_byprop, StreamInlet
    from eegstream.devices import OpenBCI8

    source_id = OpenBCI8.source_id
    window = 2.0
    print("looking for a stream...")
    stream_info = resolve_byprop("source_id", source_id, timeout=1)[0]
    print(stream_info)
    stream_inlet = StreamInlet(stream_info)
    signal_interface = SignalInterface(stream_inlet, window)

    monitor = Monitor(signal_interface)
    monitor.start_mainloop()
Example #41
0
    def __init__(self, stream_name='EOG', srate=500):
        """ Initialize the PyGERT-object

        Args:
            stream_name <string>: name of the lsl stream to connect to
        """

        self._is_trained = False

        if stream_name:  # This needs error handling!
            self._stream_handle = lsl.resolve_byprop('name', stream_name)[0]
            self._inlet = lsl.StreamInlet(self._stream_handle)
            self.srate = self._stream_handle.nominal_srate()
        else:
            self.srate = srate  # Fix this later

        # Configure filters
        filt_len = 150
        stop_limit1 = 500 / self.srate
        stop_limit2 = 40
        wn1 = stop_limit1 / (self.srate/2)
        wn2 = stop_limit2 / (self.srate/2)

        self._group_delay = (filt_len - 1) / 2

        self._b1 = sig.firwin(filt_len, wn1)
        self._b2 = sig.firwin(filt_len, wn2)
        self._z1_h = sig.lfilter_zi(self._b1, 1)
        self._z1_v = sig.lfilter_zi(self._b1, 1)
        self._z2_h = sig.lfilter_zi(self._b2, 1)
        self._z2_v = sig.lfilter_zi(self._b2, 1)

        self._eog_h_prev1 = 0
        self._eog_v_prev1 = 0
        self._eog_h_prev2 = 0
        self._eog_v_prev2 = 0

        # Buffers
        self._MAX_SACCADE_LENGTH = .2
        self._MAX_BLINK_LEN = .5
        self._MIN_SACCADE_LEN = .01
        self._MIN_BLINK_LEN = .2
        self._MIN_SACCADE_GAP = .1

        buffer_len_saccade = round(self._MAX_SACCADE_LENGTH * self.srate)
        buffer_len_blink = round(self._MAX_BLINK_LEN * self.srate)
        self._norm_d2 = np.zeros(buffer_len_saccade)
        self._eog_v2 = np.zeros(buffer_len_blink)
        self._psn = np.zeros(buffer_len_saccade)

        self._fix_prob_mass = 0

        self._saccade_samples = 0
        self._saccade_prob = 0

        self._blink_samples = 0
        self._blink_prob = 0

        self._n = 0
        self._n_sac = 0
        self._n_blink = 0

        self._SAC_START = []
        self._SAC_END = []
        self._SAC_DUR = []
        self._SAC_PROB = []

        self._BLI_START = []
        self._BLI_END = []
        self._BLI_DUR = []
        self._BLI_PROB = []

        # Flags
        self._blink_on = False
        self._saccade_on = False
import sys
from pylsl import StreamInlet, resolve_byprop
import numpy as np

from eegstream.devices import Experiment, OpenBCI8


if __name__ == '__main__':
    assert len(sys.argv) > 0, 'No experiment name provided'
    filename = sys.argv[1]
    timequant = 0.100 #s

    print("looking for device stream")
    device = OpenBCI8
    bci_info = resolve_byprop('source_id', device.source_id, timeout=1)[0]
    print("Device stream discovered")
    print('Looking for GUI source')
    experiment_info = resolve_byprop('source_id', Experiment.source_id,
                                       timeout=100)[0]
    print('GUI source discovered')

    #print(experiment_info, bci_info)

    experiment_inlet = StreamInlet(experiment_info)
    bci_inlet = StreamInlet(bci_info)

    bci_results = [[], []]
    experiment_results = [[], []]

    print('Recording')