pygame.init() #pygame.mouse.set_visible(False) from screen import screen from drawstuff import * study_time = int(time.time()) print(study_time) word_fname = '../data/words_latest.csv'.format(study_time) words = get_words() words.to_csv(word_fname) info = StreamInfo('Ganglion_EEG', 'Markers', 1, 0.0, 'int32', 'marker') outlet = StreamOutlet(info) def check_for_key(key=K_ESCAPE): while True: event = pygame.event.poll() if event.type == 0: return False elif event.dict.get('key', -1) == key: return True def check_for_escape(): return check_for_key(K_ESCAPE)
import serial from pylsl import StreamInfo, StreamOutlet ser = serial.Serial('COM4', 115200) C = "" R = "" V = "" info = StreamInfo(name='GSR', type='Voltage', channel_count=1, channel_format='string', source_id='GSR_Voltage') outlet = StreamOutlet(info) while True: ser_bytes = (ser.readline()).decode("utf-8") if ser_bytes[0] == "C": C = ser_bytes[1:-2] #print(C) elif ser_bytes[0] == "R": R = ser_bytes[1:-2] #print(R) elif ser_bytes[0] == "V": V = ser_bytes[1:-2] #print(V) outlet.push_sample([V])
from pyOpenBCI import OpenBCICyton from pylsl import StreamInfo, StreamOutlet import numpy as np SCALE_FACTOR_EEG = (4500000) / 24 / (2**23 - 1) #uV/count SCALE_FACTOR_AUX = 0.002 / (2**4) print("Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n") info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 8, 250, 'float32', 'OpenBCItestEEG') print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n") info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX') 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) #print(np.array(sample.aux_data)*SCALE_FACTOR_AUX) board = OpenBCICyton(port='/dev/cu.usbserial-DM00D7TW') board.write_command('/2') # change the cyton AUX board mode to Analog mode. board.start_stream(lsl_streamers)
# needed for creating timestamp import time # needed just for testing from random import random as rand # pyLSL module from pylsl import StreamInfo, StreamOutlet, local_clock # setting of informations about LSL stream info = StreamInfo('TestStream', 'Markers', 8, 100, 'int32', 'TestID0605') outlet = StreamOutlet(info, 32, 360) print("Now sending data...") n = 0 while True: sample = '' # sample = [n, n, n, n, n, n, n, n] sample = [0, 0, 0, 0, 0, 0, 0, 0] stamp = local_clock() outlet.push_sample(sample, stamp) time.sleep(0.01) # n = n + 1
"--backend", dest="backend", type='string', default="auto", help="pygatt backend to use. can be auto, gatt or bgapi") parser.add_option( "-i", "--interface", dest="interface", type='string', default=None, 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])
# comas=False, mode='rt' # ) # data extraction/ cleanup data = zip(*data) data = list(data) # choose the channel data = np.asanyarray(data[:12]) data = data.astype(np.float) # first create a new stream info (here we set the name to BioSemi, # the content-type to EEG, 8 channels, 250 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, 250, 'float32', 'myuid34234') # next make an outlet outlet = StreamOutlet(info) print("now sending data...") i = 0 while True: mysample = [] # make a new random 8-channel sample; this is converted into a # pylsl.vectorf (the data type that is expected by push_sample) for j in range(1, data.__len__() - 3): mysample.append(data[j][i]) # now send it and wait for a bit outlet.push_sample(mysample) time.sleep(0.005)
eEvent = IEE_EmoEngineEventCreate() IS_GetTimeFromStart = libEDK.IS_GetTimeFromStart IS_GetTimeFromStart.argtypes = [ctypes.c_void_p] IS_GetTimeFromStart.restype = c_float IEE_EmoEngineEventGetEmoState = libEDK.IEE_EmoEngineEventGetEmoState IEE_EmoEngineEventGetEmoState.argtypes = [c_void_p, c_void_p] IEE_EmoEngineEventGetEmoState.restype = c_int IEE_EmoStateCreate = libEDK.IEE_EmoStateCreate IEE_EmoStateCreate.restype = c_void_p eState = IEE_EmoStateCreate() print("Creating LSL outelt...", end='') info = StreamInfo('EPOCH', 'FreqBand', 14 * 5, 2, 'float32', 'uniqueid') # append some meta-data channelList = array('I', [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) channelListLabel = [ "AF3", "F7", "F3", "FC5", "T7", "P7", "O1", "O2", "P8", "T8", "FC6", "F4", "F8", "AF4" ] info.desc().append_child_value("manufacturer", "Emotiv") channels = info.desc().append_child("channels") for c in channelListLabel: channels.append_child("channel") \ .append_child_value("label", c + "_theta") \ .append_child_value("unit", "uV^2/Hz") \ .append_child_value("type", "frequency") channels.append_child("channel") \
def stream(address, backend='auto', interface=None, name=None): bluemuse = backend == 'bluemuse' if not bluemuse: if not address: found_muse = find_muse(name) if not found_muse: return else: address = found_muse['address'] name = found_muse['name'] info = StreamInfo('Muse', 'EEG', MUSE_NB_CHANNELS, MUSE_SAMPLING_RATE, 'float32', 'Muse%s' % 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, LSL_CHUNK) def push_eeg(data, timestamps): for ii in range(LSL_CHUNK): outlet.push_sample(data[:, ii], timestamps[ii]) muse = Muse(address=address, callback_eeg=push_eeg, backend=backend, interface=interface, name=name) if (bluemuse): 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() return didConnect = muse.connect() if (didConnect): print('Connected.') muse.start() print('Streaming...') while time() - muse.last_timestamp < AUTO_DISCONNECT_DELAY: try: sleep(1) except KeyboardInterrupt: muse.stop() muse.disconnect() break print('Disconnected.')
# content-type is set to 'Markers', because then other programs will know how # to interpret the content #Defining variables to define stream information stream_name = 'MyMarkerStream' stream_type = 'Markers' number_of_channels = 1 #A value of 0 is made for the sampling rate # to signify an irregular sampling rate sampling_rate = 0 data_type = 'string' unique_id = 'myuidw43536' #Defining the stream info = StreamInfo(stream_name, stream_type, number_of_channels, sampling_rate, data_type, unique_id) # next make an outlet outlet = StreamOutlet(info) print("now sending markers...") # Defining the marker strings markernames = ['Test', 'Blah', 'Marker', 'XXX', 'Testtest', 'Test-1-2-3'] #Infinte while loop while True: # pick a sample to send an wait for a bit # The function random.choice() picks one of the # markers at random from the markernames list.
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 None sine data will be sent) :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 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.0 / freq) c += 1 pass
def present(duration=120, stim_types=None, itis=None, secs=0.07, volume=0.8): #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') 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) 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)) # 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() # Send marker timestamp = time.time() outlet.push_sample([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
if len(argv) < 2: port = "COM4" print(f"""=======WARNING======= Pass the port number as an input argument when running the script. E.g.: >python send_serial_read_LSL.py COM4 ===================== Trying with the default port {port}...""") port = "COM4" else: port = argv[1] print(f"Opening port {port}.") # create stream info: # StreamInfo(name, type, channels, sampling rate (0=irregular), datatype, unique ID) info = StreamInfo('AlarmMarkersTest', 'Markers', 1, 0, 'string', 'arduinoTroll') # next make an outlet outlet = StreamOutlet(info) # To find out which port (COMx) the alarmbox is connected to run the windows # 'Device manager'. # # This code-block listenes for input on the serial port, there are two types # of events that send markers to the serial port: # # 1. Triggering of an alarm sends "alarm" # 2. The toggle switch is flipped: sends the reaction time in ms (e.g. 1400) # # The code tries to read data from the serial port continously. # If it recieves a signal corresponding to a trigger-event or reaction-event
import serial, time 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
import time from random import random as rand from pylsl import StreamInfo, StreamOutlet num_channels = 8 info = StreamInfo('BioSemi', 'EEG', num_channels, 100, 'float32', 'myuid34234') outlet = StreamOutlet(info) print("Now sending data...") while True: mysample = [rand() for _ in range(num_channels)] outlet.push_sample(mysample) time.sleep(0.01)