예제 #1
0
class StreamerLSL():
	# From IPlugin
        def __init__(self, nb_channels, sample_rate, channel_type, ID):
	  """
	  nb_channnels: max number of channels
	  sample_rate: in Hz
	  channel_type: serve as identifier, eg 'PPG" or 'face'
	  ID: unique identifier associated to this stream
	    TODO: check uniqueness
	  """
	  stream_name = channel_type + "_" + str(ID)
	  print "Creating stream:", stream_name, "of type:", channel_type
	  # TODO: use cam/algo for unique id
	  stream_id = stream_name
	  
	  # Create a new stream
	  info_kinect = StreamInfo(stream_name, channel_type, nb_channels, sample_rate,'float32', stream_id);
	  
	  # make outlets
	  self.outlet_kinect = StreamOutlet(info_kinect)
	    
	# send channels values
        # sample: list of float values (one per face)
	def __call__(self, sample):
		self.outlet_kinect.push_sample(sample)
예제 #2
0
	def activate(self):
		eeg_stream = "OpenBCI_EEG"
		eeg_id = "openbci_eeg_id1"
		aux_stream = "OpenBCI_AUX"
		aux_id = "openbci_aux_id1"
		
		if len(self.args) > 0:
			eeg_stream = self.args[0]
		if len(self.args) > 1:
			eeg_id = self.args[1]
		if len(self.args) > 2:
			aux_stream = self.args[2]
		if len(self.args) > 3:
			aux_id = self.args[3]

		# Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
		print "Creating LSL stream for EEG. Name:", eeg_stream, "- ID:", eeg_id, "- data type: float32.", self.eeg_channels, "channels at", self.sample_rate, "Hz."
		info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,self.sample_rate,'float32',eeg_id);
		# NB: set float32 instead of int16 so as OpenViBE takes it into account
		print "Creating LSL stream for AUX. Name:", aux_stream, "- ID:", aux_id, "- data type: float32.", self.aux_channels, "channels at", self.sample_rate, "Hz."
		info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,self.sample_rate,'float32',aux_id);
		
		# make outlets
		self.outlet_eeg = StreamOutlet(info_eeg)
		self.outlet_aux = StreamOutlet(info_aux)
예제 #3
0
class StreamerLSL(plugintypes.IPluginExtended):
	# From IPlugin
	def activate(self):
		eeg_stream = "OpenBCI_EEG"
		eeg_id = "openbci_eeg_id1"
		aux_stream = "OpenBCI_AUX"
		aux_id = "openbci_aux_id1"
		
		if len(self.args) > 0:
			eeg_stream = self.args[0]
		if len(self.args) > 1:
			eeg_id = self.args[1]
		if len(self.args) > 2:
			aux_stream = self.args[2]
		if len(self.args) > 3:
			aux_id = self.args[3]

		# Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
		print "Creating LSL stream for EEG. Name:", eeg_stream, "- ID:", eeg_id, "- data type: float32.", self.eeg_channels, "channels at", self.sample_rate, "Hz."
		info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,self.sample_rate,'float32',eeg_id);
		# NB: set float32 instead of int16 so as OpenViBE takes it into account
		print "Creating LSL stream for AUX. Name:", aux_stream, "- ID:", aux_id, "- data type: float32.", self.aux_channels, "channels at", self.sample_rate, "Hz."
		info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,self.sample_rate,'float32',aux_id);
		
		# make outlets
		self.outlet_eeg = StreamOutlet(info_eeg)
		self.outlet_aux = StreamOutlet(info_aux)
	    
	# send channels values
	def __call__(self, sample):
		self.outlet_eeg.push_sample(sample.channel_data)
		self.outlet_aux.push_sample(sample.aux_data)

	def show_help(self):
	  	print """Optional arguments: [EEG_stream_name [EEG_stream_ID [AUX_stream_name [AUX_stream_ID]]]]
예제 #4
0
class BetaGeneratorOutlet(object):
    def __init__(self, Fs=2**14, FreqBeta=20.0, AmpBeta=100.0, AmpNoise=20.0, NCyclesPerChunk=4,
                 channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"]):
        """
        :param Fs:              Sampling rate
        :param FreqBeta:        Central frequency of beta band
        :param AmpBeta:         Amplitude of beta (uV)
        :param AmpNoise:        Amplitude of pink noise (uV)
        :param NCyclesPerChunk: Minimum number of cycles of beta in a chunk.
        :param channels:        List of channel names
        """
        # Saved arguments
        self.FreqBeta = FreqBeta
        self.AmpBeta = AmpBeta                                          # Amplitude of Beta (uV)
        self.AmpNoise = AmpNoise                                        # Amplitude of pink noise
        self.channels = channels
        # Derived variables
        chunk_dur = NCyclesPerChunk / self.FreqBeta           # Duration, in sec, of one chunk
        chunk_len = int(Fs * chunk_dur)                  # Number of samples in a chunk
        self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs     # time vector for chunk (sec)
        # Pink noise generator
        self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len)

        # Create a stream of fake 'raw' data
        raw_info = StreamInfo(name='BetaGen', type='EEG',
                           channel_count=len(self.channels), nominal_srate=Fs,
                           channel_format='float32', source_id='betagen1234')
        raw_xml = raw_info.desc()
        chans = raw_xml.append_child("channels")
        for channame in self.channels:
            chn = chans.append_child("channel")
            chn.append_child_value("label", channame)
            chn.append_child_value("unit", "microvolts")
            chn.append_child_value("type", "generated")
        self.eeg_outlet = StreamOutlet(raw_info)
        print("Created outlet with name BetaGen and type EEG")

        self.last_time = local_clock()

    def update(self, task={'phase': 'precue', 'class': 1}):
        # Convert phase and class_id into beta_amp
        if task['phase'] in ['cue', 'go']:
            beta_amp = 0 if task['class'] == 3 else self.AmpBeta
        else:
            beta_amp = self.AmpBeta / 5.0

        this_tvec = self.tvec + self.last_time  # Sample times
        # Put the signal together
        this_sig = self.AmpNoise * np.asarray(self.pinkNoiseGen.generate(), dtype=np.float32)  # Start with some pink noise
        this_sig += beta_amp * np.sin(this_tvec * 2 * np.pi * self.FreqBeta)  # Add our beta signal
        this_sig = np.atleast_2d(this_sig).T * np.ones((1, len(self.channels)), dtype=np.float32)  # Tile across channels

        time_to_sleep = max(0, this_tvec[-1] - local_clock())
        time.sleep(time_to_sleep)

        print("Beta outlet pushing signal with shape {},{} and Beta amp {}".format(this_sig.shape[0], this_sig.shape[1],
                                                                                   beta_amp))
        self.eeg_outlet.push_chunk(this_sig, timestamp=this_tvec[-1])

        self.last_time = local_clock()
예제 #5
0
    def __init__(self, class_list=[1, 3], classes_rand=True, target_list=[1, 2], targets_rand=True):
        """

        :param class_list:  A list of integers comprising different class ids. Default: [1, 3]
        :param classes_rand: If True, classes are chosen randomly from list. If False, the list is cycled. Default: True
        :param target_list: A list of integers comprising different target ids. Default: [1, 2]
        :param targets_rand: If True, targets are chosen randomly from list. If False, the list is cycled. Default: True
        """
        stream_name = 'GeneratedCentreOutMarkers'
        stream_type = 'Markers'
        outlet_info = StreamInfo(name=stream_name, type=stream_type,
                   channel_count=1, nominal_srate=0,
                   channel_format='string',
                   source_id='centreoutmarkergen1234')
        outlet_xml = outlet_info.desc()
        channels_xml = outlet_xml.append_child("channels")
        chan_xml = channels_xml.append_child("channel")
        chan_xml.append_child_value("label", "EventMarkers")
        chan_xml.append_child_value("type", "generated")
        self.outlet = StreamOutlet(outlet_info)
        print("Created outlet with name {} and type {}".format(stream_name, stream_type))

        self.class_list = class_list
        self.classes_rand = classes_rand
        self.target_list = target_list
        self.targets_rand = targets_rand
        self.next_transition = -1
        self.in_phase = 'evaluate'
        self.trial_ix = 0
        self.class_id = self.class_list[0]
        self.target_id = self.target_list[0]
예제 #6
0
 def __init__(self, signals, fs, name='NFBLab_data1'):
     self.info = StreamInfo(name=name, type='', channel_count=len(signals), source_id='nfblab42',
                            nominal_srate=fs)
     self.info.desc().append_child_value("manufacturer", "BioSemi")
     channels = self.info.desc().append_child("channels")
     for c in signals:
         channels.append_child("channel").append_child_value("name", c)
     self.outlet = StreamOutlet(self.info)
예제 #7
0
    def activate(self):
        eeg_stream = "OpenBCI_EEG"
        eeg_id = "openbci_eeg_id1"
        aux_stream = "OpenBCI_AUX"
        aux_id = "openbci_aux_id1"
        imp_stream = "OpenBCI_Impedance"
        imp_id = "openbci_imp_id1"

        if len(self.args) > 0:
            eeg_stream = self.args[0]
        if len(self.args) > 1:
            eeg_id = self.args[1]
        if len(self.args) > 2:
            aux_stream = self.args[2]
        if len(self.args) > 3:
            aux_id = self.args[3]
        if len(self.args) > 4:
            imp_stream = self.args[4]
        if len(self.args) > 5:
            imp_id = self.args[5]

        # Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
        print("Creating LSL stream for EEG. Name:" + eeg_stream + "- ID:" + eeg_id +
              "- data type: float32." + str(self.eeg_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,
                              self.sample_rate, 'float32', eeg_id)
        # NB: set float32 instead of int16 so as OpenViBE takes it into account
        print("Creating LSL stream for AUX. Name:" + aux_stream + "- ID:" + aux_id +
              "- data type: float32." + str(self.aux_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,
                              self.sample_rate, 'float32', aux_id)

        # make outlets
        self.outlet_eeg = StreamOutlet(info_eeg)
        self.outlet_aux = StreamOutlet(info_aux)

        if self.imp_channels > 0:
            print("Creating LSL stream for Impedance. Name:" + imp_stream + "- ID:" +
                  imp_id + "- data type: float32." + str(self.imp_channels) +
                  "channels at" + str(self.sample_rate) + "Hz.")
            info_imp = StreamInfo(imp_stream, 'Impedance', self.imp_channels,
                                  self.sample_rate, 'float32', imp_id)
            self.outlet_imp = StreamOutlet(info_imp)
예제 #8
0
파일: generators.py 프로젝트: nikolaims/nfb
def run_events_sim(name='events_example'):
    info = StreamInfo(name=name, type='EEG', channel_count=1, channel_format='float32', source_id='myuid34234')

    # channels labels (in accordance with XDF format, see also code.google.com/p/xdf)

    chns = info.desc().append_child("channels")
    for label in ['STIM']:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
    outlet = StreamOutlet(info)

    # send data and print some info every 5 sec
    print('now sending data...')

    while True:
        outlet.push_sample([42])
        time.sleep(1)
        print('42 sent')
    pass
예제 #9
0
class StreamerLSL(plugintypes.IPluginExtended):
    # From IPlugin
    def activate(self):
        eeg_stream = "OpenBCI_EEG"
        eeg_id = "openbci_eeg_id1"
        aux_stream = "OpenBCI_AUX"
        aux_id = "openbci_aux_id1"
        imp_stream = "OpenBCI_Impedance"
        imp_id = "openbci_imp_id1"

        if len(self.args) > 0:
            eeg_stream = self.args[0]
        if len(self.args) > 1:
            eeg_id = self.args[1]
        if len(self.args) > 2:
            aux_stream = self.args[2]
        if len(self.args) > 3:
            aux_id = self.args[3]
        if len(self.args) > 4:
            imp_stream = self.args[4]
        if len(self.args) > 5:
            imp_id = self.args[5]

        # Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
        print("Creating LSL stream for EEG. Name:" + eeg_stream + "- ID:" + eeg_id +
              "- data type: float32." + str(self.eeg_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,
                              self.sample_rate, 'float32', eeg_id)
        # NB: set float32 instead of int16 so as OpenViBE takes it into account
        print("Creating LSL stream for AUX. Name:" + aux_stream + "- ID:" + aux_id +
              "- data type: float32." + str(self.aux_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,
                              self.sample_rate, 'float32', aux_id)

        # make outlets
        self.outlet_eeg = StreamOutlet(info_eeg)
        self.outlet_aux = StreamOutlet(info_aux)

        if self.imp_channels > 0:
            print("Creating LSL stream for Impedance. Name:" + imp_stream + "- ID:" +
                  imp_id + "- data type: float32." + str(self.imp_channels) +
                  "channels at" + str(self.sample_rate) + "Hz.")
            info_imp = StreamInfo(imp_stream, 'Impedance', self.imp_channels,
                                  self.sample_rate, 'float32', imp_id)
            self.outlet_imp = StreamOutlet(info_imp)

    # send channels values
    def __call__(self, sample):
        self.outlet_eeg.push_sample(sample.channel_data)
        self.outlet_aux.push_sample(sample.aux_data)
        if self.imp_channels > 0:
            self.outlet_imp.push_sample(sample.imp_data)

    def show_help(self):
        print("""Optional arguments:
        [EEG_stream_name [EEG_stream_ID [AUX_stream_name [AUX_stream_ID [Impedance_steam_name [Impedance_stream_ID]]]]]]
        \t Defaults: "OpenBCI_EEG" / "openbci_eeg_id1" and "OpenBCI_AUX" / "openbci_aux_id1" 
        / "OpenBCI_Impedance" / "openbci_imp_id1".""")
예제 #10
0
        def __init__(self, nb_channels, sample_rate, channel_type, ID):
	  """
	  nb_channnels: max number of channels
	  sample_rate: in Hz
	  channel_type: serve as identifier, eg 'PPG" or 'face'
	  ID: unique identifier associated to this stream
	    TODO: check uniqueness
	  """
	  stream_name = channel_type + "_" + str(ID)
	  print "Creating stream:", stream_name, "of type:", channel_type
	  # TODO: use cam/algo for unique id
	  stream_id = stream_name
	  
	  # Create a new stream
	  info_kinect = StreamInfo(stream_name, channel_type, nb_channels, sample_rate,'float32', stream_id);
	  
	  # make outlets
	  self.outlet_kinect = StreamOutlet(info_kinect)
예제 #11
0
class StreamerLSL(plugintypes.IPluginExtended):
    # From IPlugin
    def activate(self):
        eeg_stream = "OpenBCI_EEG"
        eeg_id = "openbci_eeg_id1"
        aux_stream = "OpenBCI_AUX"
        aux_id = "openbci_aux_id1"
        imp_stream = "OpenBCI_Impedance"
        imp_id = "openbci_imp_id1"

        if len(self.args) > 0:
            eeg_stream = self.args[0]
        if len(self.args) > 1:
            eeg_id = self.args[1]
        if len(self.args) > 2:
            aux_stream = self.args[2]
        if len(self.args) > 3:
            aux_id = self.args[3]
        if len(self.args) > 4:
            imp_stream = self.args[4]
        if len(self.args) > 5:
            imp_id = self.args[5]

        # Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
        print "Creating LSL stream for EEG. Name:", eeg_stream, "- ID:", eeg_id, "- data type: float32.", self.eeg_channels, "channels at", self.sample_rate, "Hz."
        info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,
                              self.sample_rate, 'float32', eeg_id)
        # NB: set float32 instead of int16 so as OpenViBE takes it into account
        print "Creating LSL stream for AUX. Name:", aux_stream, "- ID:", aux_id, "- data type: float32.", self.aux_channels, "channels at", self.sample_rate, "Hz."
        info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,
                              self.sample_rate, 'float32', aux_id)

        # make outlets
        self.outlet_eeg = StreamOutlet(info_eeg)
        self.outlet_aux = StreamOutlet(info_aux)

        if self.imp_channels > 0:
            print "Creating LSL stream for Impedance. Name:", imp_stream, "- ID:", imp_id, "- data type: float32.", self.imp_channels, "channels at", self.sample_rate, "Hz."
            info_imp = StreamInfo(imp_stream, 'Impedance', self.imp_channels,
                                  self.sample_rate, 'float32', imp_id)
            self.outlet_imp = StreamOutlet(info_imp)

    # send channels values
    def __call__(self, sample):
        self.outlet_eeg.push_sample(sample.channel_data)
        self.outlet_aux.push_sample(sample.aux_data)
        if self.imp_channels > 0:
            self.outlet_imp.push_sample(sample.imp_data)

    def show_help(self):
        print """Optional arguments: [EEG_stream_name [EEG_stream_ID [AUX_stream_name [AUX_stream_ID [Impedance_steam_name [Impedance_stream_ID]]]]]]
예제 #12
0
    def create_lsl_output(self):
        """Creates an LSL Stream outlet"""
        info = StreamInfo(name=self.lsl_streamname,
                          type='Markers',
                          channel_count=1,
                          channel_format='int8',
                          nominal_srate=IRREGULAR_RATE,
                          source_id='marker_stream',
                          handle=None)

        if self.flash_mode == 1:
            info.desc().append_child_value('flash_mode', 'Row and Column')
        elif self.flash_mode == 2:
            info.desc().append_child_value('flash_mode', 'Single Value')

        info.desc().append_child_value('num_rows', str(self.number_of_rows))
        info.desc().append_child_value('num_cols', str(self.number_of_columns))

        return StreamOutlet(info)
예제 #13
0
    def __init__(self, device_info):
        n_chan = device_info['adc_mask'].count(1)
        self.exg_fs = device_info['sampling_rate']
        orn_fs = 20

        info_exg = StreamInfo(name=device_info["device_name"] + "_ExG",
                              type='ExG',
                              channel_count=n_chan,
                              nominal_srate=self.exg_fs,
                              channel_format='float32',
                              source_id=device_info["device_name"] + "_ExG")
        info_exg.desc().append_child_value("manufacturer", "Mentalab")
        channels = info_exg.desc().append_child("channels")
        for i, mask in enumerate(device_info['adc_mask']):
            if mask == 1:
                channels.append_child("channel")\
                    .append_child_value("name", EXG_CHANNELS[i])\
                    .append_child_value("unit", EXG_UNITS[i])\
                    .append_child_value("type", "ExG")

        info_orn = StreamInfo(name=device_info["device_name"] + "_ORN",
                              type='ORN',
                              channel_count=9,
                              nominal_srate=orn_fs,
                              channel_format='float32',
                              source_id=device_info["device_name"] + "_ORN")
        info_orn.desc().append_child_value("manufacturer", "Mentalab")
        channels = info_exg.desc().append_child("channels")
        for chan, unit in zip(ORN_CHANNELS, ORN_UNITS):
            channels.append_child("channel") \
                .append_child_value("name", chan) \
                .append_child_value("unit", unit) \
                .append_child_value("type", "ORN")

        info_marker = StreamInfo(name=device_info["device_name"] + "_Marker",
                                 type='Markers',
                                 channel_count=1,
                                 nominal_srate=0,
                                 channel_format='int32',
                                 source_id=device_info["device_name"] +
                                 "_Markers")

        logger.info(
            "LSL Streams have been created with names/source IDs as the following:\n"
            + "\t\t\t\t\t" + device_info["device_name"] + "_ExG\n" +
            "\t\t\t\t\t" + device_info["device_name"] + "_ORN\n" +
            "\t\t\t\t\t" + device_info["device_name"] + "_Markers\n")
        self.orn_outlet = StreamOutlet(info_orn)
        self.exg_outlet = StreamOutlet(info_exg)
        self.marker_outlet = StreamOutlet(info_marker)
예제 #14
0
    def create_lsl(self):
        # default parameters
        eeg_name = 'OpenBCI_EEG'
        eeg_type = 'EEG'
        eeg_chan = self.eeg_channels
        eeg_hz = self.sample_rate
        eeg_data = 'double64'
        eeg_id = 'openbci_eeg_id'

        # create StreamInfo
        self.info_eeg = StreamInfo(eeg_name, eeg_type, eeg_chan, eeg_hz,
                                   eeg_data, eeg_id)

        # channel locations
        chns = self.info_eeg.desc().append_child('channels')
        if self.eeg_channels == 16:
            labels = [
                'Fp1', 'Fp2', 'C3', 'C4', 'T5', 'T6', 'O1', 'O2', 'F7', 'F8',
                'F3', 'F4', 'T3', 'T4', 'P3', 'P4'
            ]
        else:
            labels = ['Fp1', 'Fp2', 'C3', 'C4', 'T5', 'T6', 'O1', 'O2']
        for label in labels:
            ch = chns.append_child("channel")
            ch.append_child_value('label', label)
            ch.append_child_value('unit', 'microvolts')
            ch.append_child_value('type', 'EEG')

        # additional Meta Data
        self.info_eeg.desc().append_child_value('manufacturer', 'OpenBCI Inc.')
        # create StreamOutlet
        self.outlet_eeg = StreamOutlet(self.info_eeg)

        print("--------------------------------------\n" +
              "LSL Configuration: \n" + "  Stream: \n" + "      Name: " +
              eeg_name + " \n" + "      Type: " + eeg_type + " \n" +
              "      Channel Count: " + str(eeg_chan) + "\n" +
              "      Sampling Rate: " + str(eeg_hz) + "\n" +
              "      Channel Format: " + eeg_data + " \n" +
              "      Source Id: " + eeg_id + " \n" +
              "Electrode Location Montage:\n" + str(labels) + "\n" +
              "---------------------------------------\n")
예제 #15
0
def stream():
    #print(address)
    #print(name)
    print(
        "Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n"
    )

    info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 16, 250, 'float32',
                          'OpenBCItestEEG')

    # print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

    # info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

    info_eeg.desc().append_child_value("manufacturer", "OpenBCI")
    eeg_channels = info_eeg.desc().append_child("channels")

    for c in [
            'Fp1', 'Fp2', 'C3', 'C4', 'P7', 'P8', 'O1', 'O2', 'F7', 'F8', 'F3',
            'F4', 'T7', 'T8', 'P3', 'P4'
    ]:
        eeg_channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    # eeg_outlet = StreamOutlet(eeg_info, LSL_EEG_CHUNK)

    outlet_eeg = StreamOutlet(info_eeg)

    # outlet_aux = StreamOutlet(info_aux)

    def lsl_streamers(sample):
        outlet_eeg.push_sample(
            np.array(sample.channels_data) * SCALE_FACTOR_EEG)
        # outlet_aux.push_sample(np.array(sample.aux_data)*SCALE_FACTOR_AUX)

    #board = OpenBCICyton(port='COM3', daisy=True)
    board = OpenBCICyton(port='/dev/tty.usbserial-DM01N7JO', daisy=True)

    board.start_stream(lsl_streamers)
예제 #16
0
def initializeOutlet(interface):
    """
    Initializes and returns an LSL outlet
    :param interface: Interface
        the Python interface to communicate with node
    :return: StreamOutlet
        returns a labstreaminglayer StreamOutlet
    """
    numChans = None
    while not numChans:
        msg = interface.recv()
        try:
            dicty = json.loads(msg)
            numChans = dicty.get('numChans')
            sampleRate = dicty.get('sampleRate')
        except ValueError as e:
            print(e)
    info = StreamInfo('OpenBCI_EEG', 'EEG', numChans, sampleRate, 'float32',
                      'myuid34234')
    outlet = StreamOutlet(info)
    print('init')
    return outlet
    def activate(self):
        eeg_stream = "OpenBCI_EEG"
        eeg_id = "openbci_eeg_id1"
        aux_stream = "OpenBCI_AUX"
        aux_id = "openbci_aux_id1"
        imp_stream = "OpenBCI_Impedance"
        imp_id = "openbci_imp_id1"

        if len(self.args) > 0:
            eeg_stream = self.args[0]
        if len(self.args) > 1:
            eeg_id = self.args[1]
        if len(self.args) > 2:
            aux_stream = self.args[2]
        if len(self.args) > 3:
            aux_id = self.args[3]
        if len(self.args) > 4:
            imp_stream = self.args[4]
        if len(self.args) > 5:
            imp_id = self.args[5]

        # Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
        print("Creating LSL stream for EEG. Name:" + eeg_stream + "- ID:" +
              eeg_id + "- data type: float32." + str(self.eeg_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,
                              self.sample_rate, 'float32', eeg_id)
        # NB: set float32 instead of int16 so as OpenViBE takes it into account
        print("Creating LSL stream for AUX. Name:" + aux_stream + "- ID:" +
              aux_id + "- data type: float32." + str(self.aux_channels) +
              "channels at" + str(self.sample_rate) + "Hz.")
        info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,
                              self.sample_rate, 'float32', aux_id)

        # make outlets
        self.outlet_eeg = StreamOutlet(info_eeg)
        self.outlet_aux = StreamOutlet(info_aux)

        if self.imp_channels > 0:
            print("Creating LSL stream for Impedance. Name:" + imp_stream +
                  "- ID:" + imp_id + "- data type: float32." +
                  str(self.imp_channels) + "channels at" +
                  str(self.sample_rate) + "Hz.")
            info_imp = StreamInfo(imp_stream, 'Impedance', self.imp_channels,
                                  self.sample_rate, 'float32', imp_id)
            self.outlet_imp = StreamOutlet(info_imp)
예제 #18
0
    def __setup_output_stream(self, stream_name, stream_type):
        """
        Initialize a LSL outlet of particular name and type

        Parameters
        ----------
        stream_name : str
            Name of LSL outlet to initialize. Can be anything.
        stream_type : str
            Type of LSL outlet to initialze. Typical choices are 'marker', 'data',
            or 'eeg'.

        Returns
        -------
        outlet : LSL Outlet
            Creates a LSL-ready outlet for streaming data over the network.

        """
        # Identify the type of data we are sending back.
        if stream_type.casefold() == 'marker'.casefold():
            info = StreamInfo(stream_name,
                              stream_type,
                              channel_count=1,
                              nominal_srate=0,
                              channel_format='string',
                              source_id='single314uid')
        elif stream_type.casefold() == 'data'.casefold():
            info = StreamInfo(stream_name,
                              stream_type,
                              channel_count=1,
                              nominal_srate=0,
                              source_id='single314uid')

        # Make the stream outlet using the infor provided above
        print('...setting up LSL outlet object...')
        outlet = StreamOutlet(info)

        return outlet
예제 #19
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
    def _setup_outlet(self):
        sample_size = self.CONNECTIONS * len(self.freqParams)
        if sample_size == 0:
            return

        info = StreamInfo('RValues', 'Markers', sample_size, IRREGULAR_RATE,
                          cf_float32, "RValues-{}".format(getpid()))
        info.desc().append_child_value("correlation", "R")

        mappings = info.desc().append_child("mappings")
        buffer_keys = list(self.buffers.keys())
        pair_index = [
            a for a in list(
                product(np.arange(0, len(buffer_keys)),
                        np.arange(0, len(buffer_keys)))) if a[0] < a[1]
        ]

        for pair in pair_index:
            mappings.append_child("mapping") \
                .append_child_value("from", buffer_keys[pair[0]]) \
                .append_child_value("to", buffer_keys[pair[1]])

        return StreamOutlet(info)
예제 #21
0
def create_noisy_test_source(freq=10, noise_freq=60, sps=250):
    '''
    create fake lsl stream of source data
    '''
    assert freq < (sps / 2), "frequence must be less than nquist"
    stream_name = "Test_Signal_" + str(freq) + "_Hz_"
    stream_id = stream_name + time.strftime("_%d_%m_%Y_%H_%M_%S_")
    info = StreamInfo(stream_name, 'EEG', 8, 250, 'float32', stream_id)
    outlet = StreamOutlet(info)
    delay = 1.0 / sps

    def _target():
        idx = 0
        while True:
            time.sleep(delay)
            idx += 1
            new_val = np.sin(2 * np.pi * freq *
                             (idx * delay)) + np.sin(2 * np.pi * noise_freq *
                                                     (idx * delay))
            outlet.push_sample([new_val for i in range(8)])

    _thread = Thread(target=_target)
    _thread.start()
예제 #22
0
    def create_lsl_output(self):
        """Creates an LSL Stream outlet"""
        info = StreamInfo(
            name=self.config.lsl_streamname.get(),
            type="P300_Marker",
            channel_count=1,
            channel_format="int8",
            nominal_srate=IRREGULAR_RATE,
            source_id="marker_stream",
            handle=None,
        )

        if self.config.flash_mode == 1:
            info.desc().append_child_value("flash_mode", "Row and Column")
        elif self.config.flash_mode == 2:
            info.desc().append_child_value("flash_mode", "Single Value")

        info.desc().append_child_value("num_rows",
                                       str(self.config.number_of_rows.get()))
        info.desc().append_child_value(
            "num_cols", str(self.config.number_of_columns.get()))

        return StreamOutlet(info)
예제 #23
0
    def __init__(self, Fs=2**14, FreqBeta=20.0, AmpBeta=100.0, AmpNoise=20.0, NCyclesPerChunk=4,
                 channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"]):
        """
        :param Fs:              Sampling rate
        :param FreqBeta:        Central frequency of beta band
        :param AmpBeta:         Amplitude of beta (uV)
        :param AmpNoise:        Amplitude of pink noise (uV)
        :param NCyclesPerChunk: Minimum number of cycles of beta in a chunk.
        :param channels:        List of channel names
        """
        # Saved arguments
        self.FreqBeta = FreqBeta
        self.AmpBeta = AmpBeta                                          # Amplitude of Beta (uV)
        self.AmpNoise = AmpNoise                                        # Amplitude of pink noise
        self.channels = channels
        # Derived variables
        chunk_dur = NCyclesPerChunk / self.FreqBeta           # Duration, in sec, of one chunk
        chunk_len = int(Fs * chunk_dur)                  # Number of samples in a chunk
        self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs     # time vector for chunk (sec)
        # Pink noise generator
        self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len)

        # Create a stream of fake 'raw' data
        raw_info = StreamInfo(name='BetaGen', type='EEG',
                           channel_count=len(self.channels), nominal_srate=Fs,
                           channel_format='float32', source_id='betagen1234')
        raw_xml = raw_info.desc()
        chans = raw_xml.append_child("channels")
        for channame in self.channels:
            chn = chans.append_child("channel")
            chn.append_child_value("label", channame)
            chn.append_child_value("unit", "microvolts")
            chn.append_child_value("type", "generated")
        self.eeg_outlet = StreamOutlet(raw_info)
        print("Created outlet with name BetaGen and type EEG")

        self.last_time = local_clock()
예제 #24
0
def InitLslArduino():

    name = 'HX711'
    type = 'ForceSensor'
    n_channels = 1
    srate = 80

    info = StreamInfo(name, type, n_channels, srate, 'float32', 'IntTrmr1001')

    # append some meta-data
    info.desc().append_child_value("manufacturer", "Arduino")
    channel_names = ['ForceSensor']
    chns = info.desc().append_child("channels")
    for label in channel_names:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
        ch.append_child_value("unit", "a.u.")
        ch.append_child_value("type", "Arduino")

    # next make an outlet; we set the transmission chunk size to 32 samples and
    # the outgoing buffer size to 360 seconds (max.)
    outlet = StreamOutlet(info, 80, 30)

    return outlet
예제 #25
0
class SignalsOutlet:
    def __init__(self, signals, fs, name='NFBLab_data1'):
        self.info = StreamInfo(name=name, type='', channel_count=len(signals), source_id='nfblab42',
                               nominal_srate=fs)
        self.info.desc().append_child_value("manufacturer", "BioSemi")
        channels = self.info.desc().append_child("channels")
        for c in signals:
            channels.append_child("channel").append_child_value("name", c)
        self.outlet = StreamOutlet(self.info)

    def push_sample(self, data):
        self.outlet.push_sample(data)

    def push_repeated_chunk(self, data, n=1):
        #chunk = repeat(data, n).reshape(-1, n).T.tolist()
        #self.outlet.push_chunk(chunk)
        for k in range(n):
            self.outlet.push_sample(data)

    def push_chunk(self, data, n=1):
        self.outlet.push_chunk(data)
예제 #26
0
class SignalsOutlet:
    def __init__(self, signals, fs):
        self.info = StreamInfo(name='NFBLab_data', type='', channel_count=len(signals), source_id='nfblab42',
                               nominal_srate=fs)
        self.info.desc().append_child_value("manufacturer", "BioSemi")
        channels = self.info.desc().append_child("channels")
        for c in signals:
            channels.append_child("channel").append_child_value("name", c)
        self.outlet = StreamOutlet(self.info)

    def push_sample(self, data):
        self.outlet.push_sample(data)

    def push_repeated_chunk(self, data, n=1):
        #chunk = repeat(data, n).reshape(-1, n).T.tolist()
        #self.outlet.push_chunk(chunk)
        for k in range(n):
            self.outlet.push_sample(data)

    def push_chunk(self, data, n=1):
        self.outlet.push_chunk(data)
예제 #27
0
def present(duration=120, eeg=None, save_fn=None, iti = 0.5, soa = 3.0, jitter = 0.2, 
            n_trials = 150, cf1 = 1000, amf1 = 40):

    # Create markers stream outlet
    info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
    outlet = StreamOutlet(info)

    markernames = [1]
    start = time()

    # Set up trial parameters
    record_duration = np.float32(duration)

    # Set up trial list
    stim_freq = np.zeros((n_trials,), dtype=int)
    trials = DataFrame(dict(stim_freq=stim_freq, timestamp=np.zeros(n_trials)))

    # Setup graphics
    mywin = visual.Window([1920, 1080], monitor='testMonitor', units='deg',
                          fullscr=True)
    fixation = visual.GratingStim(win=mywin, size=0.2, pos=[0, 0], sf=0,
                                  rgb=[1, 0, 0])
    fixation.setAutoDraw(True)


    def generate_am_waveform(carrier_freq, am_freq, secs=1, sample_rate=44100,
                             am_type='sine'):
        """Generate an amplitude-modulated waveform.

        Generate a sine wave amplitude-modulated by a second sine wave or a
        Gaussian envelope with standard deviation = period_AM/8.

        Args:
            carrier_freq (float): carrier wave frequency, in Hz
            am_freq (float): amplitude modulation frequency, in Hz

        Keyword Args:
            secs (float): duration of the stimulus, in seconds
            sample_rate (float): sampling rate of the sound, in Hz
            am_type (str): amplitude-modulation type
                'gaussian' -> Gaussian with std defined by `gaussian_std`
                'sine' -> sine wave
            gaussian_std_ratio (float): only used if `am_type` is 'gaussian'.
                Ratio between AM period and std of the Gaussian envelope. E.g.,
                gaussian_std = 8 means the Gaussian window has 8 standard
                deviations around its mean inside one AM period.

        Returns:
            (numpy.ndarray): sound samples
        """
        t = np.arange(0, secs, 1./sample_rate)

        if am_type == 'gaussian':
            period = int(sample_rate / am_freq)
            std = period / gaussian_std_ratio
            norm_window = stats.norm.pdf(np.arange(period), period / 2, std)
            norm_window /= np.max(norm_window)
            n_windows = int(np.ceil(secs * am_freq))
            am = np.tile(norm_window, n_windows)
            am = am[:len(t)]

        elif am_type == 'sine':
            am = np.sin(2 * np.pi * am_freq * t)

        carrier = 0.5 * np.sin(2 * np.pi * carrier_freq * t) + 0.5
        am_out = carrier * am

        return am_out


    # Generate stimuli
    am1 = generate_am_waveform(cf1, amf1, secs=soa, sample_rate=44100)

    aud1 = sound.Sound(am1)
    aud1.setVolume(0.8)

    auds = [aud1]

    mywin.flip()
    
    # start the EEG stream=
    if eeg:
        if save_fn is None:  # If no save_fn passed, generate a new unnamed save file
            save_fn = generate_save_fn(eeg.device_name, 'ssaep', 'unnamed')
            print(f'No path for a save file was passed to the experiment. Saving data to {save_fn}')
        eeg.start(save_fn,duration=record_duration)
    

    for ii, trial in trials.iterrows():
        # Intertrial interval
        core.wait(iti + np.random.rand() * jitter)

        # Select stimulus frequency
        ind = trials['stim_freq'].iloc[ii]
        auds[ind].stop() 
        auds[ind].play()
        
        # Push sample
        if eeg: 
            timestamp = time()
            if eeg.backend == 'muselsl':
                marker = [markernames[ind]]
                marker = list(map(int, marker)) 
            else:
                marker = markernames[ind]
            eeg.push_sample(marker=marker, timestamp=timestamp)
            
        # offset
        core.wait(soa)
        mywin.flip()
        if len(event.getKeys()) > 0:
            break
        if (time() - start) > record_duration:
            break

        event.clearEvents()
        
    # Cleanup
    if eeg: eeg.stop()

    mywin.close()
class BCNIDataServer(mp.Process):
    """Server for streaming example LSL data taken from BNCI-Horizon.

    Inherits form multiprocessing.Process so instantiate and call self.start()

    Args:
        filename: This will be passed on as the filname argument to a testserver.BNCIData instance

    """
    def __init__(self, subject_number: int):
        mp.Process.__init__(self)
        self.data = BCNIData(subject_number)

    # noinspection PyAttributeOutsideInit
    def second_init(self):
        """Used because otherwise multiprocessing cannot pickle LSL instances"""

        # LSL Settings
        self.eeg_streamname = "testeeg_stream"
        self.marker_streamname = "marker_stream"
        self.period_time = 1.0 / self.data.samplerate  # seconds

        # EEG stream
        self.eeg_info = StreamInfo(
            name=self.eeg_streamname,
            nominal_srate=self.data.samplerate,
            type="EEG",
            channel_count=self.data.num_channels,
            channel_format="float32",
            source_id="eeg_stream_test",
            handle=None,
        )
        self.lsl_eeg = StreamOutlet(self.eeg_info)

        # Marker Stream
        self.marker_info = StreamInfo(
            name=self.marker_streamname,
            type="P300_Marker",
            nominal_srate=IRREGULAR_RATE,
            channel_count=1,
            channel_format="int8",
            source_id="marker_stream",
            handle=None,
        )
        self.marker_info.desc().append_child_value("flash_mode",
                                                   self.data.flash_mode)
        self.marker_info.desc().append_child_value("num_rows", "6")
        self.marker_info.desc().append_child_value("num_cols", "6")
        self.lsl_marker = StreamOutlet(self.marker_info)

    def run(self):
        self.second_init()

        # Stream data
        print("Server started...")
        print("EEG samples stream: '" + self.eeg_streamname + "'")
        print("P300 Markers stream: '" + self.marker_streamname + "'")

        # Hack to start later in the dataset
        self.data.set_counter(3000)

        while True:
            timestamp = self.data.get_timestamp()
            eeg_data = self.data.get_eeg_data()
            marker = self.data.get_marker()
            self.data.increase_counter()

            self.lsl_eeg.push_sample(eeg_data, timestamp)

            # Push only non zero markers
            if marker[0] != 0:
                self.lsl_marker.push_sample(marker, timestamp)

            time.sleep(self.period_time)
예제 #29
0
from pylsl import StreamInfo, StreamOutlet

# parameters for com port
# TODO: from command line
port = '/dev/ttyACM0'
baudrate = 115200
# 2ms pause in arduino firmware: 500Hz
samplingrate = 500
# rate for spamming stdout
displaySamplingRate = 10

ser = serial.Serial(port, baudrate)

# create LSL StreamOutlet
info = StreamInfo('breath','breath',1,samplingrate,'float32','conphyturebreathing1337')
outlet = StreamOutlet(info)

# some time for init?
#time.sleep(0.5)

n=0
while True:
  line = ser.readline()
  value = 0
  # convert string to float (remove trailing line break at the same time...)
  try:
    value = float(line)
  except:
    # silently discard conversion problem
    pass
  #TODO: won't work if rates not dividers
예제 #30
0
파일: lsl_send.py 프로젝트: nikolaims/nfb
import time
from random import random as rand

from pylsl import StreamInfo, StreamOutlet, local_clock
import numpy as np

# first create a new stream info (here we set the name to BioSemi,
# the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
# last value would be the serial number of the device or some other more or
# less locally unique identifier for the stream as far as available (you
# could also omit it but interrupted connections wouldn't auto-recover)
fs = 1000
info = StreamInfo('BioSemi', 'EEG', 2)

# next make an outlet
outlet = StreamOutlet(info)

print("now sending data...")
n_samples = fs * 100
recorder = np.zeros((n_samples, 2))

t = 0
t_start = local_clock()
while True:
    if t > n_samples - 2:
        break
    clock = local_clock()
    if clock - t_start > (t+1)/fs:
        # make a new random 8-channel sample; this is converted into a
        # pylsl.vectorf (the data type that is expected by push_sample)
        second = int(clock)
예제 #31
0
###setup variable related to pic and trial number here###
trials = 400
low_rate = 0.8
high_rate = 0.2

total_parts = 20
self_count = 5
fam_count = 5
place_count = 10

###create our stream variables###
info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')

###next make an outlet to record the streamed data###
outlet = StreamOutlet(info)

###setup GPIO pins and initialise pygame###
pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.init()
pygame.display.init()
pygame.mixer.init()

###setup the display screen and fixation###
pygame.mouse.set_visible(0)
disp_info = pygame.display.Info()
screen = pygame.display.set_mode((disp_info.current_w, disp_info.current_h),
                                 pygame.FULLSCREEN)
x_center = disp_info.current_w / 2
y_center = disp_info.current_h / 2
black = pygame.Color(0, 0, 0)
# Program duration (based on command sequence)
number_of_trials = 3
after_trial_pause = 90
command_display_time = 7
fixation_display_time = 3

# Flickering frequency for the Up-Down-Left-Right stimulus
monitor_to_use = 1
square_left_number_frames = 3  # 3 frames ON and 3 frames OFF to make 10 Hz
square_right_number_frames = 5  # 5 frames ON and 5 frames OFF to make 6 Hz
square_up_number_frames = 4  # 4 frames ON and 4 frames OFF to make 7.5 Hz
square_down_number_frames = 4  # 4 frames ON BUT 3 frames OFF to make 8.57 Hz

# Create LSL inlet and send the first event "Waiting..." during the pause everything is being set up
info = StreamInfo("MyMarkerStream", "Markers", 1, 0, "string", "Experiment01")
outlet = StreamOutlet(info)
outlet.push_sample(["Waiting..."])
time.sleep(1)

# Create an artificial pause to give time to prepare LSL recording externally
clock_object = core.Clock()
recording_pause = 10
countdown_time = core.CountdownTimer(recording_pause)
while countdown_time.getTime() > 0:
    elapsed_time = clock_object.getTime()
clock_object.reset()
elapsed_time = 0
# ----------------------------------------------------------------------------------------------------------------------


# ----------------------------------------------------------------------------------------------------------------------
예제 #33
0
class robot():

    is_start = False
    is_lsl = False
    is_update_request = False
    is_new_data = False

    devices = []
    command_buf = []

    pos_outlet = None
    cur_outlet = None

    def __init__(self, serial_port=None, *args, **kwargs):
        self.serial_port = serial.Serial()
        self.pos_outlet = None
        self.cur_outlet = None

        self.connect_serial(serial_port)

        super(robot, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

    def start(self):
        self.is_start = True
        self.is_update_request = True
        self.mainloop = self.mainloop()

    def stop(self):
        self.is_start = False
        self.is_update_request = False
        del self.mainloop

    @threaded
    def mainloop(self, sleep_interval: float = 0.01):
        """
        Main loop that process at maximum 100Hz,
        sleep_interval: Because we use separate thread to parallel control qbrobot without block the process, this value also affect sampling frequency of the data
        Task:
        ask position current and stiffness from all device within the robot.
        process return answer from each device and give data to appropriate device.
        update and send data though LSL.
        check command buffer and send all data within command buffer to robot.
        """

        print("start mainloop")
        while True:
            time.sleep(sleep_interval)
            if not self.is_start:
                break
            if not self.serial_port.isOpen():
                print("serial_port is not connect to robot.")
                break

            if self.is_update_request is True:
                self.__send_request()

            data_in = self.serial_port.read_all()
            if len(data_in) > 0:
                self.__update_data(data_in)

            if self.is_new_data is True:
                self.update_lsl()
                self.is_new_data = False

            #print("in mainloop")
            com_len = len(self.command_buf)
            if com_len > 0:
                for item in self.command_buf:
                    command = self.command_buf.pop(0)
                    self.serial_port.write(command)
        print("break from mainloop")

    def __del__(self):
        """
        deconstrutor to take care of lsl and serial port and ensure it correctly closed.
        """
        if DEBUG:
            print("start deconstrutor")
        if self.is_start is True:
            self.stop()
        if self.is_lsl is True:
            self.stop_lsl()
        if self.serial_port.isOpen():
            self.serial_port.close()

    def connect_serial(
            self, serial_port: serial.tools.list_ports_common.ListPortInfo):
        """
        function taking care of connect robot with serial port.
        serial_port: element of list_ports.comports(), see pyserial for further information
        """
        if serial_port is None:
            print(
                "serial_port is not correct, initial manual serial port selection."
            )

            while serial_port is None:
                comlist = list_ports.comports()
                id = 0
                for element in comlist:
                    if element:
                        id = id + 1
                        print("ID: " + str(id) + " -- Portname: " +
                              str(element) + "\n")
                port = int(input("Enter a port number: "))
                if port - 1 < len(comlist):
                    serial_port = comlist[port - 1]
                else:
                    print("Wrong serial port selected, try again")

            self.openRS485(serial_port)
            #self.add_device(1, "Hand Grip/Open", "softhand")
            #self.add_device(2, "Wrist Flex/Exten", "qbmove")
            #self.add_device(3, "Wrist Pron/Supi", "qbmove")

            for item in self.devices:
                item.activate()
        elif type(serial_port) is serial.tools.list_ports_common.ListPortInfo:
            self.openRS485(serial_port)
        else:
            pass

    def add_device(self,
                   device_id: int = 1,
                   name: str = "",
                   dtype: str = "softhand"):
        """
        add device according to device_id
        device_id:int, device_id future check communication model before create device will be implement.
        name:str, just a name of device.
        dtype:str, type of device following service.qbcommand.qbrobot_type enum.
        """
        if self.is_update_request:
            print(
                "Please add all device before start robot, stop, del and recreate robot"
            )
            return
        if self.serial_port is None:
            print(
                "Please connect robot to serial port first to confirm the connectivity"
            )
            return
        if self.command_buf is None:
            print("Warning, command buffer do not initialize")

        new_device = device(device_id, name, dtype, self.serial_port,
                            self.command_buf)
        new_device.activate()
        self.devices.append(new_device)
        if self.is_lsl:
            print("Each device need to reconfigurate lsl.")
            self.stop_lsl()
            self.start_lsl()

    def start_lsl(self):
        """
        initial lsl communication and allow data to send according to number of device in the robot
        """
        self.pos_outlet = StreamOutlet(
            StreamInfo('Softhand Position Data', 'Position',
                       3 * len(self.devices), 100, 'int16', 'myshpos20191002'))
        self.cur_outlet = StreamOutlet(
            StreamInfo('Softhand Current Data', 'Current',
                       2 * len(self.devices), 100, 'int16', 'myshcur20191002'))
        self.is_lsl = True

    def stop_lsl(self):
        """
        recycle lsl communication
        """
        self.pos_outlet = None
        self.cur_outlet = None
        self.is_lsl = False

    def update_lsl(self):
        """
        send new data from each devices though lsl communication.
        """
        if self.is_lsl:
            value = []
            for device_i in self.devices:
                if device_i.pos is not None:
                    value = value + device_i.pos
            if len(value) == (3 * len(self.devices)):
                self.pos_outlet.push_sample(value)
            value = []
            for device_i in self.devices:
                if device_i.cur is not None:
                    value = value + device_i.cur
            if len(value) == (2 * len(self.devices)):
                self.cur_outlet.push_sample(value)

    def __update_data(self, data_in: bytes):
        """
        Private function for send binary data for update each devices.
        data_in: bytes, bytes data that separate by "::"
        """
        datas = data_in.split(str.encode('::'))
        for data in datas:
            if len(data) > 0:
                for device_i in self.devices:
                    if device_i.checkDeviceID(data[0]):
                        device_i.updateData(data)
        self.is_new_data = True

    def __send_request(self):
        """
        Private function for add request data for each device in robot.
        """
        if self.is_start == True:
            for device_i in self.devices:
                device_i.getPosition()
                device_i.getCurrent()
        else:
            print("Stop send request")
            return

    def openRS485(self, port):
        """
        open serial port to robot and also configurate the communication protocol according to RS485
        port: serial_port
        """
        self.serial_port = serial.Serial(port.device, BAUD_RATE, timeout=1)
        self.serial_port.rs485_mode = rs485.RS485Settings()
        return 1

    def movedevice(self,
                   device_num: int,
                   position: int = 0,
                   percentStiffness: int = 0):
        """
        move device according to device number: keep for compatibility, will be removed in future
        device_num: int, index of robot device
        position: int, position in integer
        percentStiffness: stiffness in 0 to 100
        """
        if not 0 <= device_num < len(self.devices):
            print("device_num outside device in robot between 0 and %d" %
                  (len(self.devices)))
            return 0
        if not self.devices[device_num].POS_RANGE[
                0] <= position <= self.devices[device_num].POS_RANGE[1]:
            print("position outside the device range between %d and %d" %
                  (self.devices[device_num].POS_RANGE))
            return 0
        if not 0 <= percentStiffness <= 100:
            print("percentStiffness is between 0 and 100")
            return 0

        stiffrange = self.devices[device_num].STF_RANGE[1] - self.devices[
            device_num].STF_RANGE[0]
        stiffness = ((percentStiffness / 100) *
                     stiffrange) + self.devices[device_num].STF_RANGE[0]

        self.devices[device_num].sendPosStiff(int(position), int(stiffness))
        return 1

    def get_device(self, device_id: int):
        """
        get the device for outside controller, use with care.
        device_id: id of the device you want to control.
        """
        for item in self.devices:
            if item.device_id == device_id:
                return item
        print("No device id = %d" % (device_id))
        return None
예제 #34
0
 
import sys; sys.path.append('./lib') # help python find pylsl relative to this example program
from pylsl import StreamInfo, StreamOutlet
import random
import time

# first create a new stream info (here we set the name to MyMarkerStream, the content-type to Markers, 1 channel, irregular sampling rate, and string-valued data)
# The last value would be the locally unique identifier for the stream as far as available, e.g. program-scriptname-subjectnumber (you could also omit it but interrupted connections wouldn't auto-recover).
# The important part is that the content-type is set to 'Markers', because then other programs will know how to interpret the content
info = StreamInfo('MyMarkerStream','Markers',1,0,'string','myuidw43536');

# next make an outlet
outlet = StreamOutlet(info)

print("now sending markers...")
markernames = ['coucou', 'OVTK_GDF_Start_Of_Trial', 'OVTK_StimulationId_Label_01']
while True:
        mark = random.choice(markernames)
        print "Sending: ", mark
        # pick a sample to send an wait for a bit
        outlet.push_sample([mark])
        time.sleep(random.random()*3)
예제 #35
0
    def __init__(self, port_num=None):
        """
        Initializes the feedback.

        You should not override this method, override on_init instead. If you
        must override this method, make sure to call
        ``Feedback.__init__(self, pp)`` before anything else in your overridden
        __init__ method.
        """

        self._data = None
        self.logger = logging.getLogger("FB." + self.__class__.__name__)
        """Inherited by all sub classes. Use this for logging."""

        self.logger.debug("Loaded my logger.")
        # Setup the parallel port
        self._pport = None
        if sys.platform == 'win32':
            try:
                from ctypes import windll
                self._pport = windll.inpout32

            except:
                self.logger.warning("Could not load inpout32.dll. Please make sure it is located in the system32 directory")
        else:
            try:
                import parallel
                self._pport = parallel.Parallel()
            except:
                self.logger.warning("Unable to open parallel port! Please install pyparallel to use it.")
        if port_num != None:
            self._port_num = port_num # used in windows only''
        else:
            self._port_num = 0x378
        self._playEvent = Event()
        self._shouldQuit = False

        # Initialize with dummy values so we cann call safely .cancel
        self._triggerResetTimer = Timer(0, None)
        self._triggerResetTime = 0.01

        self.udp_markers_host = '127.0.0.1'
        self.udp_markers_port = 12344

        self.ov_tcp_tag_enable = False
        self.ov_tcp_tag_host = '127.0.0.1'
        self.ov_tcp_tag_port = 15361
        self._ov_tcp_tag_socket = self._ov_tcp_tag_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print 'init base',self._ov_tcp_tag_socket


        #self.tcp_markers_enable = False
        #self.tcp_markers_host = '127.0.0.1'
        #self.tcp_markers_port = 12344

        self._has_lsl = False
        try:
            from pylsl import StreamInfo, StreamOutlet
            self._has_lsl = True
        except:
            self.logger.warning("Could not import LabStreamingLayer. Ignore, if you don't want to send LSL Markers.")

        if self._has_lsl:
            try:
                # name: PyffMarkerStream, content-type: Markers,
                # channels: 1, irregular sampling rate,
                # type: string, id: pyffmarker
                info = StreamInfo('PyffMarkerStream', 'Markers', 1, 0, 'string', 'pyffmarker')
                self._lsl_outlet = StreamOutlet(info)
            except:
                self.logger.error("Unable to Create LSL Marker Outlet, but LSL is installed.")
                self._has_lsl = False
예제 #36
0
파일: stream.py 프로젝트: xloem/muse-lsl
def stream(
    address,
    backend='auto',
    interface=None,
    name=None,
    ppg_enabled=False,
    acc_enabled=False,
    gyro_enabled=False,
    eeg_disabled=False,
    timeout=AUTO_DISCONNECT_DELAY,
):
    # If no data types are enabled, we warn the user and return immediately.
    if eeg_disabled and not ppg_enabled and not acc_enabled and not gyro_enabled:
        print(
            'Stream initiation failed: At least one data source must be enabled.'
        )
        return

    # For any backend except bluemuse, we will start LSL streams hooked up to the muse callbacks.
    if backend != 'bluemuse':
        if not address:
            found_muse = find_muse(name)
            if not found_muse:
                return
            else:
                address = found_muse['address']
                name = found_muse['name']

        if not eeg_disabled:
            eeg_info = StreamInfo('Muse', 'EEG', MUSE_NB_EEG_CHANNELS,
                                  MUSE_SAMPLING_EEG_RATE, 'float32',
                                  'Muse%s' % address)
            eeg_info.desc().append_child_value("manufacturer", "Muse")
            eeg_channels = eeg_info.desc().append_child("channels")

            for c in ['TP9', 'AF7', 'AF8', 'TP10', 'Right AUX']:
                eeg_channels.append_child("channel") \
                    .append_child_value("label", c) \
                    .append_child_value("unit", "microvolts") \
                    .append_child_value("type", "EEG")

            eeg_outlet = StreamOutlet(eeg_info, LSL_EEG_CHUNK)

        if ppg_enabled:
            ppg_info = StreamInfo('Muse', 'PPG', MUSE_NB_PPG_CHANNELS,
                                  MUSE_SAMPLING_PPG_RATE, 'float32',
                                  'Muse%s' % address)
            ppg_info.desc().append_child_value("manufacturer", "Muse")
            ppg_channels = ppg_info.desc().append_child("channels")

            for c in ['PPG1', 'PPG2', 'PPG3']:
                ppg_channels.append_child("channel") \
                    .append_child_value("label", c) \
                    .append_child_value("unit", "mmHg") \
                    .append_child_value("type", "PPG")

            ppg_outlet = StreamOutlet(ppg_info, LSL_PPG_CHUNK)

        if acc_enabled:
            acc_info = StreamInfo('Muse', 'ACC', MUSE_NB_ACC_CHANNELS,
                                  MUSE_SAMPLING_ACC_RATE, 'float32',
                                  'Muse%s' % address)
            acc_info.desc().append_child_value("manufacturer", "Muse")
            acc_channels = acc_info.desc().append_child("channels")

            for c in ['X', 'Y', 'Z']:
                acc_channels.append_child("channel") \
                    .append_child_value("label", c) \
                    .append_child_value("unit", "g") \
                    .append_child_value("type", "accelerometer")

            acc_outlet = StreamOutlet(acc_info, LSL_ACC_CHUNK)

        if gyro_enabled:
            gyro_info = StreamInfo('Muse', 'GYRO', MUSE_NB_GYRO_CHANNELS,
                                   MUSE_SAMPLING_GYRO_RATE, 'float32',
                                   'Muse%s' % address)
            gyro_info.desc().append_child_value("manufacturer", "Muse")
            gyro_channels = gyro_info.desc().append_child("channels")

            for c in ['X', 'Y', 'Z']:
                gyro_channels.append_child("channel") \
                    .append_child_value("label", c) \
                    .append_child_value("unit", "dps") \
                    .append_child_value("type", "gyroscope")

            gyro_outlet = StreamOutlet(gyro_info, LSL_GYRO_CHUNK)

        def push(data, timestamps, outlet):
            for ii in range(data.shape[1]):
                outlet.push_sample(data[:, ii], timestamps[ii])

        push_eeg = partial(push,
                           outlet=eeg_outlet) if not eeg_disabled else None
        push_ppg = partial(push, outlet=ppg_outlet) if ppg_enabled else None
        push_acc = partial(push, outlet=acc_outlet) if acc_enabled else None
        push_gyro = partial(push, outlet=gyro_outlet) if gyro_enabled else None

        muse = Muse(address=address,
                    callback_eeg=push_eeg,
                    callback_ppg=push_ppg,
                    callback_acc=push_acc,
                    callback_gyro=push_gyro,
                    backend=backend,
                    interface=interface,
                    name=name)

        didConnect = muse.connect()

        if (didConnect):
            print('Connected.')
            muse.start()

            eeg_string = " EEG" if not eeg_disabled else ""
            ppg_string = " PPG" if ppg_enabled else ""
            acc_string = " ACC" if acc_enabled else ""
            gyro_string = " GYRO" if gyro_enabled else ""

            print("Streaming%s%s%s%s..." %
                  (eeg_string, ppg_string, acc_string, gyro_string))

            while time() - muse.last_timestamp < timeout:
                try:
                    sleep(1)
                except KeyboardInterrupt:
                    muse.stop()
                    muse.disconnect()
                    break

            print('Disconnected.')

    # For bluemuse backend, we don't need to create LSL streams directly, since these are handled in BlueMuse itself.
    else:
        # Toggle all data stream types in BlueMuse.
        subprocess.call(
            'start bluemuse://setting?key=eeg_enabled!value={}'.format(
                'false' if eeg_disabled else 'true'),
            shell=True)
        subprocess.call(
            'start bluemuse://setting?key=ppg_enabled!value={}'.format(
                'true' if ppg_enabled else 'false'),
            shell=True)
        subprocess.call(
            'start bluemuse://setting?key=accelerometer_enabled!value={}'.
            format('true' if acc_enabled else 'false'),
            shell=True)
        subprocess.call(
            'start bluemuse://setting?key=gyroscope_enabled!value={}'.format(
                'true' if gyro_enabled else 'false'),
            shell=True)

        muse = Muse(address=address,
                    callback_eeg=None,
                    callback_ppg=None,
                    callback_acc=None,
                    callback_gyro=None,
                    backend=backend,
                    interface=interface,
                    name=name)
        muse.connect()

        if not address and not name:
            print('Targeting first device BlueMuse discovers...')
        else:
            print('Targeting device: ' +
                  ':'.join(filter(None, [name, address])) + '...')
        print(
            '\n*BlueMuse will auto connect and stream when the device is found. \n*You can also use the BlueMuse interface to manage your stream(s).'
        )
        muse.start()
예제 #37
0
data_format = 'float32'
data_number_channels = 8
data_sampling_rate = 50
data_push_interval = 1/data_sampling_rate
stream_name = 'RandomVectors'
stream_type = 'EEG'
device_name = 'Sample_PC'
stream_info = StreamInfo(stream_name,
                         stream_type,
                         data_number_channels,
                         data_sampling_rate,
                         data_format,
                         device_name)

# Create Outlet
outlet = StreamOutlet(stream_info)

# Using an infinite loop, send data
print("Now sending data through a "+stream_type+" Stream...")
sample_data = list(range(data_number_channels))

while True:
    # Create sample that will be send (a random column vector in this case)
    for loop_var in range(data_number_channels):
        sample_data[loop_var] = random.random()

    # Push the sample on the outlet (creates the streaming)
    outlet.push_sample(sample_data)

    # Wait the required time to generate the desired sampling rate
    time.sleep(data_push_interval)
예제 #38
0
import time
from random import random as rand

from pylsl import StreamInfo, StreamOutlet, local_clock
import numpy as np

# first create a new stream info (here we set the name to BioSemi,
# the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
# last value would be the serial number of the device or some other more or
# less locally unique identifier for the stream as far as available (you
# could also omit it but interrupted connections wouldn't auto-recover)
fs = 1000
info = StreamInfo('python', 'EEG', 2)

# next make an outlet
outlet = StreamOutlet(info)

from pylsl import StreamInlet, resolve_stream
print('resolving stream')
streams = resolve_stream('name', 'matlab')
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
print('resolved')

t = 0
mean_time = 0
while True:
    #time.sleep(0.002)
    t += 1
    clock = local_clock()
    outlet.push_sample([0, 1])
예제 #39
0
# retrieve MAC address
parser = argparse.ArgumentParser(description='Stream phibe channels using LSL.')
parser.add_argument("device_mac", help="MAC address of the MAC device")
args = parser.parse_args()

# will likely interpolate data if greater than 1Hz
samplingrate = 64

# start of data packet
START_BYTE = 0xA0

# create LSL StreamOutlet
print "creating LSL outlet sampling rate:", samplingrate, "Hz"
info_phibe = StreamInfo('phi','phi',2,samplingrate,'float32','conphyture-phibe')
outlet_phibe = StreamOutlet(info_phibe, max_buffered=1)

class Board(Peripheral):
    def __init__(self, addr):
        # list of channels
        self.nbChans = 2
        self.buffer = ''
        # current position
        self.head = 0
        self.samples = []
        self.read_state = 0

        print "connecting to device", addr
        Peripheral.__init__(self, addr)
        print "...connected"
예제 #40
0
after_trial_pause = 20            # Pause in seconds
command_display_time = 5          # In seconds
arrow_display = False             # Arrows start being displayed first, show fixation when value is False
command_time_counter = 1

time_flip_counter = 0
trial_indicator_text_stimulus = visual.TextStim(win=window_handle, text=' ', pos=[0, -3])
trial_indicator_text_stimulus.setAutoDraw(True)
executed_command = 0
# ----------------------------------------------------------------------------------------------------------------------


# ----------------------------------------------------------------------------------------------------------------------
# Create an outlet to transmit data (event markers) using LSL
info = StreamInfo('MyMarkerStream', 'Markers', 1, 0, 'string', 'Experiment01')
outlet = StreamOutlet(info)
outlet.push_sample(['Waiting...'])
time.sleep(10)
# ----------------------------------------------------------------------------------------------------------------------

# Pre-allocate the event time log matrix
events_per_trial = (len(command_sequence)*2)+1
event_matrix = np.zeros([2, (number_of_trials*events_per_trial)+1])

EVENT_LEFT = 1
EVENT_RIGHT = 2
EVENT_UP = 3
EVENT_DOWN = 4
EVENT_FACE = 5
EVENT_CROSS = 6
EVENT_REST = 7
예제 #41
0
from OSC import OSCServer
import sys
from time import sleep

from pylsl import StreamInfo, StreamOutlet

server = OSCServer(("localhost", 7110))
server.timeout = 0
run = True

# Make your pylsl connection
info = StreamInfo('LSL Marker Stream', 'Markers', 1, 0, 'string',
                  'myuidw43536')

# next make an outlet
outlet = StreamOutlet(info)


# this method of reporting timeouts only works by convention
# that before calling handle_request() field .timed_out is
# set to False
def handle_timeout(self):
    self.timed_out = True


# funny python's way to add a method to an instance of a class
import types
server.handle_timeout = types.MethodType(handle_timeout, server)


def user_callback(path, tags, args, source):
예제 #42
0
    help="The interface to use, 'hci0' for gatt or a com port for bgapi")

(options, args) = parser.parse_args()

info = info = StreamInfo('Muse', 'EEG', 5, 256, 'float32',
                         'Muse%s' % options.address)

info.desc().append_child_value("manufacturer", "Muse")
channels = info.desc().append_child("channels")

for c in ['TP9', 'AF7', 'AF8', 'TP10', 'Right AUX']:
    channels.append_child("channel") \
        .append_child_value("label", c) \
        .append_child_value("unit", "microvolts") \
        .append_child_value("type", "EEG")
outlet = StreamOutlet(info, 12, 360)


def process(data, timestamps):
    for ii in range(12):
        outlet.push_sample(data[:, ii], timestamps[ii])


muse = Muse(address=options.address,
            callback_eeg=process,
            backend=options.backend,
            time_func=local_clock,
            interface=options.interface,
            name=options.name)

muse.connect()
예제 #43
0
class Feedback(object):
    """
    Base class for all feedbacks.

    This class provides methods which are called by the FeedbackController on
    certain events. Override the methods as needed.

    As a bare minimum you should override the :func:`on_play` method in your
    derived class to do anything useful.

    To get the data from control signals, you can use the `_data` variable
    in your feedback which will always hold the latest control signal.

    To get the data from the interaction signals, you can use the variable
    names just as sent by the GUI.

    This class provides the :func:`send_parallel` method which you can use to
    send arbitrary data to the parallel port. You don't have to override this
    method in your feedback.

    Example::

        from FeedbackBase.Feedback import Feedback

        class MyFeedback(Feedback):

        def on_init(self):
            self.logger.debug("Feedback successfully loaded.")

        def on_play(self):
            self.logger.debug("Feedback started.")

        def on_quit(self):
            self.logger.debug("Feedback quit.")

    """

    def __init__(self, port_num=None):
        """
        Initializes the feedback.

        You should not override this method, override on_init instead. If you
        must override this method, make sure to call
        ``Feedback.__init__(self, pp)`` before anything else in your overridden
        __init__ method.
        """

        self._data = None
        self.logger = logging.getLogger("FB." + self.__class__.__name__)
        """Inherited by all sub classes. Use this for logging."""

        self.logger.debug("Loaded my logger.")
        # Setup the parallel port
        self._pport = None
        if sys.platform == 'win32':
            try:
                from ctypes import windll
                self._pport = windll.inpout32

            except:
                self.logger.warning("Could not load inpout32.dll. Please make sure it is located in the system32 directory")
        else:
            try:
                import parallel
                self._pport = parallel.Parallel()
            except:
                self.logger.warning("Unable to open parallel port! Please install pyparallel to use it.")
        if port_num != None:
            self._port_num = port_num # used in windows only''
        else:
            self._port_num = 0x378
        self._playEvent = Event()
        self._shouldQuit = False

        # Initialize with dummy values so we cann call safely .cancel
        self._triggerResetTimer = Timer(0, None)
        self._triggerResetTime = 0.01

        self.udp_markers_host = '127.0.0.1'
        self.udp_markers_port = 12344

        self.ov_tcp_tag_enable = False
        self.ov_tcp_tag_host = '127.0.0.1'
        self.ov_tcp_tag_port = 15361
        self._ov_tcp_tag_socket = self._ov_tcp_tag_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print 'init base',self._ov_tcp_tag_socket


        #self.tcp_markers_enable = False
        #self.tcp_markers_host = '127.0.0.1'
        #self.tcp_markers_port = 12344

        self._has_lsl = False
        try:
            from pylsl import StreamInfo, StreamOutlet
            self._has_lsl = True
        except:
            self.logger.warning("Could not import LabStreamingLayer. Ignore, if you don't want to send LSL Markers.")

        if self._has_lsl:
            try:
                # name: PyffMarkerStream, content-type: Markers,
                # channels: 1, irregular sampling rate,
                # type: string, id: pyffmarker
                info = StreamInfo('PyffMarkerStream', 'Markers', 1, 0, 'string', 'pyffmarker')
                self._lsl_outlet = StreamOutlet(info)
            except:
                self.logger.error("Unable to Create LSL Marker Outlet, but LSL is installed.")
                self._has_lsl = False


    #
    # Internal routines not inteded for overwriting
    #
    def _on_control_event(self, data):
        """
        Store the data in the feedback and call on_control_event.

        You should not override this method, use on_control_event instead.
        """
        self._data = data
        self.on_control_event(data)

    def _on_interaction_event(self, data):
        """
        Store the variable-value pairs in the feedback and call
        on_interaction_event.

        You should not override this method, use on_interaction_event instead.
        """
        data2 = dict()
        for key in data:
            # Oh man, das wird sich nochmal raechen!
            # Originalversion:
            #self.__setattr__(key, data[key])
            # Problem: Variablen wie feedback_opt.fb_port oder
            # fedback_opt(1).bla
            # Loesung: nehme nur den Namen nach dem letzten Punkt
            key2 = key.split(".")[ - 1]
            #self.__setattr__(self.PREFIX+key2, data[key])
            self.__setattr__(key2, data[key])
            data2[key2] = data[key]

        self.on_interaction_event(data2)

    def _on_init(self):
        """
        Calls on_init.

        You should not override this method, use on_init instead.
        """
        self.on_init()

    def _on_play(self):
        """
        Calls on_play.

        You should not override this method, use on_play instead.
        """
        self._udp_markers_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # self.logger.info("Sending markers via TCP enabled")
        #if self.tcp_markers_enable:
        #    self.logger.info("Connecting to " + self.tcp_markers_host + ":" + str(self.tcp_markers_port))
        #    self._tcp_markers_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #    self._tcp_markers_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #    self._tcp_markers_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        #    self._tcp_markers_socket.connect((self.tcp_markers_host, self.tcp_markers_port))
        #    self.logger.info("Sending markers via TCP/IP enabled.")
        self.on_play()

    def _on_pause(self):
        """
        Calls on_pause.

        You should not override this method, use on_pause instead.
        """
        self.on_pause()

    def _on_stop(self):
        """
        Calls on_stop.

        You should not override this method, use on_stop instead.
        """
        self.on_stop()

    def _on_quit(self):
        """
        Calls on_quit.

        You should not override this method, use on_quit instead.
        """
        self._shouldQuit = True
        self._playEvent.set()
        self.on_quit()


    #
    # Empty routines intended to be overwritten by derived classes
    #
    def on_init(self):
        """
        This method is called right after the feedback object was loaded by the
        FeedbackController.

        Override this method to initialize everything you need before the
        feedback starts.
        """


        self.logger.debug("on_init not implemented yet!")


    def on_play(self):
        """
        This method is called by the FeedbackController when it received a
        "Play" event via interaction signal.

        Override this method to actually start your feedback.
        """
        self.logger.debug("on_play not implemented yet!")


    def on_pause(self):
        """
        This method is called by the FeedbackController when it received a
        "Pause" event via interaction signal.

        Override this method to pause your feedback.
        """
        self.logger.debug("on_pause not implemented yet!")


    def on_stop(self):
        """
        This method is called by the FeedbackController when it received a
        "Stop" event.

        Override this method to stop your feedback. It should be possible to
        start again when receiving the :func:`on_start` event.
        """
        self._ov_tcp_tag_socket.close()
        self.logger.debug("on_stop not implemented yet!")


    def on_quit(self):
        """
        This Method is called just before the FeedbackController will destroy
        the feedback object. The FeedbackController will not destroy the
        feedback object until this method has returned.

        Override this method to cleanup everything as needed or save information
        before the object gets destroyed.
        """
        self.logger.debug("on_quit not implemented yet!")


    def on_interaction_event(self, data):
        """
        This method is called after the FeedbackController received a
        interaction signal. The FeedbackController parses the signal, extracts
        the variable-value pairs, stores them as object-variables in your
        feedback and calls this method.

        If the FeedbackController detects a "play", "pause" or "quit"
        signal, it calls the appropriate ``on-method`` after this method has
        returned.

        If the FeedbackController detects an "init" signal, it calls
        :func:`on_init` before :func:`on_interaction_event`!

        Override this method if you want to react on interaction events.


        :param data: The content of the interaction signal.
        :type data: dict

        """
        self.logger.debug("on_interaction_event not implemented yet!")


    def on_control_event(self, data):
        """
        This method is called after the FeedbackController received a control
        signal. The FeedbackController parses the signal, extracts the values
        stores the resulting tuple in the object-variable "data" and calls this
        method.

        Override this method if you want to react on control events.

        :param data: The content of the control signal
        :type data: dict

        """
        self.logger.debug("on_control_event not implemented yet!")


    #
    # Common routines for all feedbacks
    #
    def send_parallel(self, data, reset=True):
        """Sends the data to the parallel port.

        The data is sent to the parallel port. After a short amount of
        time the parallel port is reset automatically.

        :param data: Data to be sent to the parallel port
        :type data: int

        """
        self.logger.info("Trigger: %s :%s" % (str(datetime.datetime.now()), str(data)))
        if reset == True:
            # A new trigger arrived before we could reset the old one
            self._triggerResetTimer.cancel()
        if self._pport:
            if sys.platform == 'win32':
                self._pport.Out32(self._port_num, data)
            else:
                self._pport.setData(data)
            if reset:
                self._triggerResetTimer = threading.Timer(self._triggerResetTime, self.send_parallel, (0x0, False))
                self._triggerResetTimer.start()


    def send_udp(self, data):
        """Sends the data to UDP.

        Similar to :func:`send_parallel`. The data is send through UDP.
        ``send_udp`` will append an ``'\n'`` character to the end of
        ``data`` before sending it.

        :param data: Data to be sent to the UDP port.
        :type data: str
            the marker.

        """
        self._udp_markers_socket.sendto(data + '\n',
                                        (self.udp_markers_host, self.udp_markers_port))


    def send_lsl(self, data):
        """Sends Marker via LSL.

        Parameters
        ----------
        data : str
            the marker

        """
        if not self._has_lsl:
            self.logger.error("Lab Streaming Layer is not available, no markers have been sent!")
            # logger.error("Lab Streaming Layer is not available, no markers have been sent!")
            return
        self._lsl_outlet.push_sample([data])

    """

    """
    def send_ov_tcp_tag(self, event):

        # create the three pieces of the tag, padding, event_id and timestamp
        padding = [0] * 8
        event_id = list(self.to_byte(event, 8))
        # send tag
        self._ov_tcp_tag_socket.sendall(bytearray(padding + event_id + padding))

    """
    Used by send_ov_tcp_tag
    """
    # transform a value into an array of byte values in little-endian order.
    def to_byte(self, value, length):
        for x in range(length):
            yield value % 256
            value //= 256

    #def send_tcp(self, data):
    #    """Sends marker via TCP/IP.
    #
    #    Parameters
    #    ----------
    #    data : str
    #        the marker. The string must end with '\n'.
    #
    #    """
    #    self._tcp_markers_socket.send(data)


    def _get_variables(self):
        """Return a dictionary of variables and their values."""
        # try everything from self.__dict__:
        # must be pickable
        self.logger.debug("Preparing variables.")
        d = {}
        for key, val in self.__dict__.iteritems():
            if key.startswith("_"):
                continue
            try:
                self.logger.debug("Trying to pickle %s %s" % (key, val))
                s = pickle.dumps(val, pickle.HIGHEST_PROTOCOL)
            except:
                self.logger.warning("Unable to pickle %s" % key)
                continue
            d[key] = val
        self.logger.debug("Returning variables.")
        return d

    def save_variables(self, filename):
        """Save all variables which are pickleable in JSON format.

        :param filename: The file where to store the variables.
        :type filename: str

        """
        # the json pickler cannot pickle everything the python pickler can,
        # prune away the variables which are not pickable, to avoid exception
        var_clean = dict()
        for k, v in self.__dict__.iteritems():
            if k.startswith("_"):
                continue
            try:
                json.dumps(v)
            except TypeError:
                continue
            var_clean[k] = v
        filehandle = open(filename, 'w')
        json.dump(var_clean, filehandle, indent=4, sort_keys=True)
        filehandle.close()

    def load_variables(self, filename):
        """Load variables from file and (over)write object attributes with
        their values.

        :param filename: The file where the variables are stored.
        :type filename: str

        This method expects the file to be in the same format as the
        save_variables method produces (currently JSON).
        """
        filehandle = open(filename, 'r')
        var = json.load(filehandle)
        filehandle.close()
        self.__dict__.update(var)

    def _playloop(self):
        """Loop which ensures that on_play always runs in main thread.

        Do not overwrite in derived classes unless you know what you're doing.
        """
        self._shouldQuit = False
        while 1:
            self._playEvent.wait()
            if self._shouldQuit:
                break
            try:
                self.logger.debug("Starting on_play.")
                self._on_play()
            except:
                # The feedback's main thread crashed and we need to take care
                # that the pipe does not run full, otherwise the feedback
                # controller freezes on the last pipe[foo].send()
                # So let's just terminate the feedback process.
                self.logger.exception("on_play threw an exception:")
                return
            self._playEvent.clear()
            self.logger.debug("on_play terminated.")
        self.logger.debug("_playloop terminated.")
예제 #44
0
unfilt_face_list = unfilt_face_list.tolist()
hfilt_face_list = hfilt_face_list.tolist()
vfilt_face_list = vfilt_face_list.tolist()

###combine the above with our face_order###
###then combine everything into one list and shuffle###
unfilt_face_list = zip(unfilt_face_list, face_order)
hfilt_face_list = zip(hfilt_face_list, face_order)
vfilt_face_list = zip(vfilt_face_list, face_order)

image_type = unfilt_face_list + hfilt_face_list + vfilt_face_list
shuffle(image_type)

# Create markers stream outlet
info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
outlet = StreamOutlet(info)

markernames = [1, 2, 3]
start = time()

# Set up trial parameters
n_trials = len(image_type)
iti = 0.9
soa = 0.2
jitter = 0.2

trial_resp = []
trial_type = []
trial_pic = []
trial_direction = []
예제 #45
0
파일: generators.py 프로젝트: nikolaims/nfb
def run_eeg_sim(freq=None, chunk_size=0, source_buffer=None, name='example', labels=None):
    """
    Make LSL Stream Outlet and send source_buffer data or simulate sin data
    :param n_channels: number of channels
    :param freq: frequency
    :param chunk_size: chunk size
    :param source_buffer: buffer for samples to push (if it's None sine data will be sended)
    :param name: name of outlet
    :return:
    """
    # default freq
    freq = freq or 500

    # labels and n_channels
    labels = labels or ch_names32
    n_channels = len(labels) if labels is not None else 32

    # stream info
    info = StreamInfo(name=name, type='EEG', channel_count=n_channels, nominal_srate=freq,
                      channel_format='float32', source_id='myuid34234')

    # channels labels (in accordance with XDF format, see also code.google.com/p/xdf)

    chns = info.desc().append_child("channels")
    for label in labels:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
    outlet = StreamOutlet(info, chunk_size=chunk_size)

    # send data and print some info every 5 sec
    print('now sending data...')
    t0 = time.time()
    t = t0
    c = 1
    ampl = 10
    freqs = np.arange(n_channels)*5 + 10
    sample = np.zeros((n_channels,))
    if source_buffer is not None:
        source_buffer = np.concatenate([source_buffer.T, source_buffer.T[::-1]]).T

    while True:
        # if source_buffer is not None get sample from source_buffer
        # else simulate sin(a*t)*sin(b*t)
        if source_buffer is not None:
            sample[:source_buffer.shape[0]] = source_buffer[:, c % source_buffer.shape[1]]
        else:
            sample = np.sin(2 * np.pi * time.time() * 50) * 0 + np.sin(2 * np.pi * time.time() * freqs)
            # sample *= (np.sin(2 * np.pi * time.time() * 0.25) + 1) * ampl
            sample *= c % (500 * 4) * ampl

        if c % 20000 > 10000:
            sample[0] *= 1
        # push sample end sleep 1/freq sec
        outlet.push_sample(sample)
        time.sleep(1. / freq)
        # print time, frequency and samples count every 5 sec
        if c % (freq * 5) == 0:
            t_curr = time.time()
            print('t={:.1f}, f={:.2f}, c={}'.format(t_curr - t0, 1. / (t_curr - t) * freq * 5, c))
            t = t_curr
        c += 1
    pass
예제 #46
0
def present(duration=120,
            stim_types=None,
            itis=None,
            additional_labels={},
            secs=0.07,
            volume=0.8):

    # additional_labels is dict with column names as keys and column vecs as values,
    # that will be added to the dataframe

    #def present(duration=120, n_trials=10, iti=0.3, soa=0.2, jitter=0.2,
    #            secs=0.2, volume=0.8, random_state=None):

    # Create markers stream outlet
    #info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
    #info = StreamInfo('Markers', 'Markers', 1 + len(additional_labels), 0, 'int32', 'myuidw43536')
    info = StreamInfo('Markers', 'Markers', 1 + len(additional_labels), 0,
                      'float32', 'myuidw43536')

    outlet = StreamOutlet(info)

    #np.random.seed(random_state)
    markernames = [1, 2]
    start = time.time()

    # Set up trial parameters
    record_duration = np.float32(duration)

    # Initialize stimuli
    #aud1 = sound.Sound('C', octave=5, sampleRate=44100, secs=secs)
    aud1 = sound.Sound(440,
                       secs=secs)  #, octave=5, sampleRate=44100, secs=secs)
    aud1.setVolume(volume)

    #aud2 = sound.Sound('D', octave=6, sampleRate=44100, secs=secs)
    aud2 = sound.Sound(528, secs=secs)
    aud2.setVolume(volume)
    auds = [aud1, aud2]

    # Setup trial list
    #sound_ind = np.random.binomial(1, 0.25, n_trials)
    #itis = iti + np.random.rand(n_trials) * jitter
    #trials = DataFrame(dict(sound_ind=sound_ind, iti=itis))
    #trials['soa'] = soa
    #trials['secs'] = secs
    trials = DataFrame(dict(sound_ind=stim_types, iti=itis))

    for col_name, col_vec in additional_labels.items():
        trials[col_name] = col_vec

    # Setup graphics
    mywin = visual.Window([1920, 1080],
                          monitor='testMonitor',
                          units='deg',
                          fullscr=True)
    fixation = visual.GratingStim(win=mywin,
                                  size=0.2,
                                  pos=[0, 0],
                                  sf=0,
                                  rgb=[1, 0, 0])
    fixation.setAutoDraw(True)
    mywin.flip()

    for ii, trial in trials.iterrows():

        # Intertrial interval
        time.sleep(trial['iti'])

        # Select and play sound
        ind = int(trial['sound_ind'])
        auds[ind].stop()
        auds[ind].play()

        additional_stamps = []
        for k in additional_labels.keys():
            additional_stamps += [trial[k]]

        # Send marker
        timestamp = time.time()
        #outlet.push_sample([markernames[ind]], timestamp)

        outlet.push_sample(additional_stamps + [markernames[ind]], timestamp)

        # Offset
        #time.sleep(soa)
        #if (time.time() - start) > record_duration:
        #    break

        # offset
        #core.wait(soa)

        if len(event.getKeys()) > 0 or (time.time() - start) > record_duration:
            break
        event.clearEvents()

        #if len(event.getKeys()) > 0 or (time() - start) > record_duration:
        #    break
        #event.clearEvents()

    # Cleanup
    mywin.close()

    return trials
예제 #47
0
class MarkersGeneratorOutlet(object):
    phases = {
        'precue': {'next': 'cue', 'duration': 1.0},
        'cue': {'next': 'go', 'duration': 0.5},
        'go': {'next': 'evaluate', 'duration': 5.0},
        'evaluate': {'next': 'precue', 'duration': 0.1}
    }

    def __init__(self, class_list=[1, 3], classes_rand=True, target_list=[1, 2], targets_rand=True):
        """

        :param class_list:  A list of integers comprising different class ids. Default: [1, 3]
        :param classes_rand: If True, classes are chosen randomly from list. If False, the list is cycled. Default: True
        :param target_list: A list of integers comprising different target ids. Default: [1, 2]
        :param targets_rand: If True, targets are chosen randomly from list. If False, the list is cycled. Default: True
        """
        stream_name = 'GeneratedCentreOutMarkers'
        stream_type = 'Markers'
        outlet_info = StreamInfo(name=stream_name, type=stream_type,
                   channel_count=1, nominal_srate=0,
                   channel_format='string',
                   source_id='centreoutmarkergen1234')
        outlet_xml = outlet_info.desc()
        channels_xml = outlet_xml.append_child("channels")
        chan_xml = channels_xml.append_child("channel")
        chan_xml.append_child_value("label", "EventMarkers")
        chan_xml.append_child_value("type", "generated")
        self.outlet = StreamOutlet(outlet_info)
        print("Created outlet with name {} and type {}".format(stream_name, stream_type))

        self.class_list = class_list
        self.classes_rand = classes_rand
        self.target_list = target_list
        self.targets_rand = targets_rand
        self.next_transition = -1
        self.in_phase = 'evaluate'
        self.trial_ix = 0
        self.class_id = self.class_list[0]
        self.target_id = self.target_list[0]

    def update(self):
        now = local_clock()
        if (now > self.next_transition):

            # Transition phase
            self.in_phase = self.phases[self.in_phase]['next']
            self.next_transition = now + self.phases[self.in_phase]['duration']

            # Send markers
            out_string = "undefined"
            if self.in_phase == 'precue':
                # transition from evaluate to precue
                # print("Previous class_id: {}, target_id: {}".format(self.class_id, self.target_id))
                self.trial_ix += 1
                self.target_id = random.choice(self.target_list) if self.targets_rand else self.target_list[
                    (self.target_list.index(self.target_id) + 1) % len(self.target_list)]
                self.class_id = random.choice(self.class_list) if self.classes_rand else self.class_list[
                    (self.class_list.index(self.class_id) + 1) % len(self.class_list)]
                # print("New class_id: {}, target_id: {}".format(self.class_id, self.target_id))
                out_string = "NewTrial {}, Class {}, Target {}".format(self.trial_ix, self.class_id, self.target_id)
            elif self.in_phase == 'cue':
                # transition from precue to cue
                out_string = "TargetCue, Class {}, Target {}".format(self.class_id, self.target_id)
            elif self.in_phase == 'go':
                # transition from cue to go
                out_string = "GoCue, Class {}, Target {}".format(self.class_id, self.target_id)
            elif self.in_phase == 'evaluate':
                # transition from go to evaluate
                hit_string = "Hit" if random.randint(0, 1) == 1 else "Miss"
                out_string = "{}, Class {}, Target {}".format(hit_string, self.class_id, self.target_id)
            print("Marker outlet pushing string: {}".format(out_string))
            self.outlet.push_sample([out_string,])

            return True
        return False
예제 #48
0
"""Example program to demonstrate how to send a multi-channel time series to
LSL."""

import time
from random import random as rand

from pylsl import StreamInfo, StreamOutlet

# first create a new stream info (here we set the name to BioSemi,
# the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
# last value would be the serial number of the device or some other more or
# less locally unique identifier for the stream as far as available (you
# could also omit it but interrupted connections wouldn't auto-recover)
info = StreamInfo('BioSemi', 'EEG', 8, 100, 'float32', 'myuid34234')

# next make an outlet
outlet = StreamOutlet(info)

print("now sending data...")
while True:
    # make a new random 8-channel sample; this is converted into a
    # pylsl.vectorf (the data type that is expected by push_sample)
    mysample = [rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand()]
    # now send it and wait for a bit
    outlet.push_sample(mysample)
    time.sleep(0.01)
# CODE TO SEND PREVIOUSLY RECORDED EEG DATA VIA AN LSL DATA OUTLET

# CODE AUTHORED BY: SHAWHIN TALEBI

import time
import csv
from pylsl import StreamInfo, StreamOutlet

# initialize the info for an 64 element LSL EEG outlet
info = StreamInfo('BioSemi', 'EEG', 64, 100, 'float32', 'surface')
# create an outlet from the info
outlet = StreamOutlet(info)

# send data
print("now sending data...")
# open EEGsample.csv
with open('EEGsample.csv') as csvfile:
    # read the .csv file
    readCSV = csv.reader(csvfile, delimiter=',')

    # start forever while loop to stream data
    while True:
        # for every row of data in .csv file
        for row in readCSV:
            # if the row corresponds to the header move to next row
            if row[0] == 'Fp1':
                continue
            # initialize a data list
            data = []
            # for every element in the row convert it from a string to a float
            # and store it in data
예제 #50
0
def main(argv):
    srate = 100
    name = 'LSLExampleAmp'
    type = 'EEG'
    channel_names = ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]
    n_channels = len(channel_names)
    help_string = 'SendData.py -s <sampling_rate> -n <stream_name> -t <stream_type>'
    try:
        opts, args = getopt.getopt(argv,
                                   "hs:n:t:",
                                   longopts=["srate=", "name=", "type"])
    except getopt.GetoptError:
        print(help_string)
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(help_string)
            sys.exit()
        elif opt in ("-s", "--srate"):
            srate = float(arg)
        elif opt in ("-n", "--name"):
            name = arg
        elif opt in ("-t", "--type"):
            type = arg

    # first create a new stream info (here we set the name to BioSemi,
    # the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
    # last value would be the serial number of the device or some other more or
    # less locally unique identifier for the stream as far as available (you
    # could also omit it but interrupted connections wouldn't auto-recover).
    info = StreamInfo(name, type, n_channels, srate, 'float32', 'myuid2424')

    # append some meta-data
    info.desc().append_child_value("manufacturer", "LSLExampleAmp")
    chns = info.desc().append_child("channels")
    for label in channel_names:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
        ch.append_child_value("unit", "microvolts")
        ch.append_child_value("type", "EEG")
    info.desc().append_child_value("manufacturer", "LSLExamples")
    cap = info.desc().append_child("cap")
    cap.append_child_value("name", "ComfyCap")
    cap.append_child_value("size", "54")
    cap.append_child_value("labelscheme", "10-20")

    # next make an outlet; we set the transmission chunk size to 32 samples and
    # the outgoing buffer size to 360 seconds (max.)
    outlet = StreamOutlet(info, 32, 360)

    print("now sending data...")
    start_time = local_clock()
    sent_samples = 0
    while True:
        elapsed_time = local_clock() - start_time
        required_samples = int(srate * elapsed_time) - sent_samples
        if required_samples > 0:
            # make a chunk==array of length required_samples, where each element in the array
            # is a new random n_channels sample vector
            mychunk = [[rand() for chan_ix in range(n_channels)]
                       for samp_ix in range(required_samples)]
            # get a time stamp in seconds (we pretend that our samples are actually
            # 125ms old, e.g., as if coming from some external hardware)
            stamp = local_clock() - 0.125
            # now send it and wait for a bit
            outlet.push_chunk(mychunk, stamp)
            sent_samples += required_samples
        time.sleep(0.02)
예제 #51
0
# retrieve MAC address
parser = argparse.ArgumentParser(description='Stream heart rate of bluetooth BLE compatible devices using LSL.')
parser.add_argument("device_mac", help="MAC address of the MAC device")
args = parser.parse_args()

# ugly global variable go retrieve value from delegate
last_bpm = 0
last_rr = 0

# will likely interpolate data if greater than 1Hz
samplingrate = 16

# create LSL StreamOutlet
print "creating LSL outlet for heart-rate, sampling rate:", samplingrate, "Hz"
info_hr = StreamInfo('hr','hr',1,samplingrate,'float32','conphyturehr1337')
outlet_hr = StreamOutlet(info_hr)

print "creating LSL outlet for RR intervals, sampling rate:", samplingrate, "Hz"
info_rr = StreamInfo('rr','rr',1,samplingrate,'float32','conphyturehr1337')
outlet_rr = StreamOutlet(info_rr)

class HRM(Peripheral):
    def __init__(self, addr):
        print "connecting to device", addr, " in random mode"
        Peripheral.__init__(self, addr, addrType=ADDR_TYPE_RANDOM)
        print "...connected"

if __name__=="__main__":
    cccid = AssignedNumbers.client_characteristic_configuration
    hrmid = AssignedNumbers.heart_rate
    hrmmid = AssignedNumbers.heart_rate_measurement
예제 #52
0
import sys; sys.path.append('..') # help python find pylsl relative to this example program
from pylsl import StreamInfo, StreamOutlet, local_clock
import random
import time

# first create a new stream info (here we set the name to BioSemi, the content-type to EEG, 8 channels, 100 Hz, and float-valued data)
# The last value would be the serial number of the device or some other more or less locally unique identifier for the stream as far as available (you could also omit it but interrupted connections wouldn't auto-recover).
info = StreamInfo('BioSemi','EEG',8,100,'float32','myuid2424');

# append some meta-data
info.desc().append_child_value("manufacturer","BioSemi")
channels = info.desc().append_child("channels")
for c in ["C3","C4","Cz","FPz","POz","CPz","O1","O2"]:
	channels.append_child("channel").append_child_value("name",c).append_child_value("unit","microvolts").append_child_value("type","EEG")

# next make an outlet; we set the transmission chunk size to 32 samples and the outgoing buffer size to 360 seconds (max.)
outlet = StreamOutlet(info,32,360)

print("now sending data...")
while True:
	# make a new random 8-channel sample; this is converted into a pylsl.vectorf (the data type that is expected by push_sample)
	mysample = [random.random(),random.random(),random.random(),random.random(),random.random(),random.random(),random.random(),random.random()]
    # get a time stamp in seconds (we pretend that our samples are actually 125ms old, e.g., as if coming from some external hardware)
	stamp = local_clock()-0.125
	# now send it and wait for a bit
	outlet.push_sample(mysample,stamp)
	time.sleep(0.01)
예제 #53
0
"""Example program to demonstrate how to send string-valued markers into LSL."""

import random
import time

from pylsl import StreamInfo, StreamOutlet

# first create a new stream info (here we set the name to MyMarkerStream,
# the content-type to Markers, 1 channel, irregular sampling rate,
# and string-valued data) The last value would be the locally unique
# identifier for the stream as far as available, e.g.
# program-scriptname-subjectnumber (you could also omit it but interrupted
# connections wouldn't auto-recover). The important part is that the
# content-type is set to 'Markers', because then other programs will know how
#  to interpret the content
info = StreamInfo('MyMarkerStream', 'Markers', 1, 0, 'string', 'myuidw43536')

# next make an outlet
outlet = StreamOutlet(info)

print("now sending markers...")
markernames = ['Test', 'Blah', 'Marker', 'XXX', 'Testtest', 'Test-1-2-3']
while True:
    # pick a sample to send an wait for a bit
    outlet.push_sample([random.choice(markernames)])
    time.sleep(random.random()*3)
import sys
from random import randint
from random import shuffle
from datetime import datetime
import numpy as np
import pandas as pd
import pygame
import RPi.GPIO as GPIO
from pylsl import StreamInfo, StreamOutlet, local_clock

###create our stream variables###
info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')

###next make an outlet to record the streamed data###
outlet = StreamOutlet(info)

###initialise pygame###
GPIO.setmode(GPIO.BCM)
pygame.mixer.pre_init(44100, -16, 2, 1024)
pygame.init()
pygame.display.set_mode((1, 1))
pygame.mixer.init()

###variables for filenames and save locations###
partnum = '001'
device = 'Muse'
filename = 'Auditory_P3_Stroke_Study'
exp_loc = 'Auditory_P3_Stroke_Study'
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ready_tone = '/home/pi/research_experiments/Experiments/Stimuli/Sounds/Auditory_Oddball/2000hz_tone.wav'
import sys
sys.path.append('..')
from pylsl import StreamInfo, StreamOutlet
import time

# first resolve a marker stream on the lab network
info = StreamInfo('MyMarkerStream', 'Markers', 1, 0, 'string', 'Experiment01')
outlet = StreamOutlet(info)

data_sampling_rate = 512                                # Desired sampling rate
time_reduction_factor = 1.2
data_push_interval = float(1/data_sampling_rate) * ((100-time_reduction_factor)/100)     # To recreate sampling rate
cumulative_time = time.clock()


while True:
        # get a new sample (you can also omit the timestamp part if you're not interested in it)
        outlet.push_sample(['Nothing'])
        cumulative_time = time.clock()

        push_interval_elapsed = time.clock()
        push_interval_target = (push_interval_elapsed + data_push_interval)
        while push_interval_elapsed <= push_interval_target:
            push_interval_elapsed = time.clock()

예제 #56
0
class Send(Node):
    """Send to a LSL stream.

    Attributes:
        i (Port): Default data input, expects DataFrame.

    Args:
        name (string): The name of the stream.
        type (string): The content type of the stream, .
        format (string): The format type for each channel. Currently, only ``double64`` and ``string`` are supported.
        rate (float): The nominal sampling rate. Set to ``0.0`` to indicate a variable sampling rate.
        source (string, None): The unique identifier for the stream. If ``None``, it will be auto-generated.

    Example:
        .. literalinclude:: /../examples/lsl.yaml
           :language: yaml

    """

    _dtypes = {"double64": np.number, "string": np.object}

    def __init__(self,
                 name,
                 type="Signal",
                 format="double64",
                 rate=0.0,
                 source=None):
        if not source:
            source = str(uuid.uuid4())
        self._name = name
        self._type = type
        self._format = format
        self._rate = rate
        self._source = source
        self._outlet = None

    def update(self):
        if isinstance(self.i.data, pd.core.frame.DataFrame):
            if not self._outlet:
                labels = list(
                    self.i.data.select_dtypes(
                        include=[self._dtypes[self._format]]))
                info = StreamInfo(
                    self._name,
                    self._type,
                    len(labels),
                    self._rate,
                    self._format,
                    self._source,
                )
                channels = info.desc().append_child("channels")
                for label in labels:
                    if not isinstance("string", type(label)):
                        label = str(label)
                    channels.append_child("channel").append_child_value(
                        "label", label)
                self._outlet = StreamOutlet(info)
            values = self.i.data.select_dtypes(
                include=[self._dtypes[self._format]]).values
            stamps = self.i.data.index.values.astype(np.float64)
            for row, stamp in zip(values, stamps):
                self._outlet.push_sample(row, stamp)
예제 #57
0
	except TypeError:
		print "MAC address (%s) is not defined..." %macAddress
		print "connecting to BITalino(%s)..." 
	except ValueError:
		print "MAC address (%s) is not defined..." %macAddress
		print "connecting to BITalino(%s)..." 
	
# Set battery threshold
device.battery(batteryThreshold)
# Read BITalino version
print device.version()
print "connected to BITalino(%s)" %macAddress
print "creating Signal stream..."
info = StreamInfo('BiTalino','BiTalino',+len(acqChannels),samplingRate,'float32','myuid34234');
# next make an outlet
outlet = StreamOutlet(info)
print"created Signal stream : %s" %info.name()
print("starting acquisition...")
# Start Acquisition
device.start(samplingRate, acqChannels)
# Read samples
while 1:
	data=device.read(nSamples)
	print data
 	outlet.push_sample(data[0][defaultChannel+1:])

# Turn BITalino led on
device.trigger(digitalOutput)
# Stop acquisition
device.stop()
# Close connection