def __init__(self, frecs): self.signal = signal self.headset = Emotiv(display_output=False) gevent.spawn(self.analizeProccess) gevent.sleep(0) self.frecs = frecs pass
def analizeProccess(self): headset = Emotiv(display_output = False) gevent.spawn(headset.setup) gevent.sleep(0) packets = {}; bufferLenght = 128*3 sensors = "O1 O2".split(' ') print "analize" for name in sensors: packets[name] = [] pass while True: p = headset.dequeue() if p != None: for name in sensors: packets[name].append(p.sensors[name]['value']) pass if len(packets[sensors[0]]) >= bufferLenght: self.signal = self.analize(packets,sensors,bufferLenght,[8,12]) #print self.signal for name in sensors: packets[name] = packets[name][5:] pass pass gevent.sleep(0) pass
def epocBuffer(self): cont = 0 logging.debug("Iniciando buffer del epoc") headset = Emotiv(display_output=False) gevent.spawn(headset.setup) gevent.sleep(0) showFillMessage = True while self.epocBufferState: packet = headset.dequeue() key.acquire() if packet == None: logging.debug("Error, paquete nulo") else: #print packet.gyro_x, packet.gyro_y self.packages.append(packet) #print packet.sensors['O2']['value'] if len(self.packages) > self.bufferlength: if showFillMessage: logging.debug("Buffer lleno con " + str(self.bufferlength) + " paquetes") showFillMessage ^= True self.packages = self.packages[10:] gevent.sleep(0) key.release() pass headset.close() logging.debug("Buffer detenido") pass
def __init__(self, input): threading.Thread.__init__(self) self.headset = Emotiv() self.f3 = input['F3'] self.f4 = input['F4'] self.af3 = input['AF3'] self.af4 = input['AF4']
def console_gather() : os.system('clear') headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) packets = 0 now = datetime.now() filename = str(now.time()) + "_" + str(now.date()) while True : dir = str(input("Choose input: \n 1. up\n 2. down\n 3. left\n 4. right\n 0. neutral\n")) if dir in ['1','2','3','4','0'] : break filename += "_" + dir if TEST : filename = "TEST_" + filename buffers = [] names = 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' ') for name in names : buffers.append(sensor_buffer(name)) print "Training will start in..."; sleep(1); print "3..."; sleep(1); print "2..."; sleep(1); print "1..."; sleep(1); print "Focus!" qualities = [] timeout = time() + 12 while True: if time() > timeout : break packet = headset.dequeue() for buffer in buffers : buffer.update( packet ) packets += 1 gevent.sleep(0) headset.close() quality = 0. f = open("./data/" + filename,'w') columns = [] for name in names : columns.append(str(name)) columns.append('Q' + str(name)) f.write(','.join(columns)) f.write('\n') while packets > 0 : for buffer in buffers : f.write( buffer.pop() ) f.write('\n') packets -= 1 f.close() print "Finished reading, saved to file %s" % filename for buffer in buffers : print "Sensor %s mean quality: %.2f" % (buffer.name, buffer.mean_quality())
def __init__(self): super(EmoGetter, self).__init__() self.headset = Emotiv() gevent.spawn(self.headset.setup) gevent.sleep(0) self.running = True
def run(self): self.headset = Emotiv() gevent.spawn(self.headset.setup) gevent.sleep(0) print("Serial Number: %s" % self.headset.serial_number) while True: packet = self.headset.dequeue() self.f3.insert(packet.sensors['F3']['value']) self.f4.insert(packet.sensors['F4']['value']) self.af3.insert(packet.sensors['AF3']['value']) self.af4.insert(packet.sensors['AF4']['value']) gevent.sleep(0)
def session(): headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) labels = ['0', '1', '2', '3', '4'] for label in labels: os.system('clear') print "Training for class: ", label raw_input("Press Enter to start training...") class_gather(label, headset) headset.close()
def session() : headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) labels = ['0', '1', '2', '3', '4'] for label in labels : os.system('clear') print "Training for class: ", label raw_input("Press Enter to start training..." ) class_gather(label, headset) headset.close()
def epoc_publish_frames(): # Setup ROS publisher. publisher = rospy.Publisher('epoc/frames', EEGFrame) # Open a connection to the Emotiv EPOC. headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(1) # Initialize ROS node+publisher. rospy.init_node('epoc_publish') # Start the publishing loop. rospy.loginfo('Starting publishing loop...') published_count = 0 try: while not rospy.is_shutdown(): # Get the next packet from the EPOC. packet = headset.dequeue() frame_header = Header(published_count, rospy.Time.now(), '/epoc') frame_accel_x = packet.sensors['X']['value'] frame_accel_y = packet.sensors['Y']['value'] frame_signals = [ packet.sensors[channel]['value'] for channel in channels] frame_qualities = [ packet.sensors[channel]['quality'] for channel in channels] frame = EEGFrame( frame_header, frame_accel_x, frame_accel_y, 14, channels, frame_signals, frame_qualities) # Publish the the EEG channels and accelerometer values. publisher.publish(frame) # Update and print information count. published_count += 1 print('\rPublished: %d' % published_count, end='') gevent.sleep(0) except rospy.ROSInterruptException: headset.close()
def run(self): O1_buff = ring_buffer(self.tw) i = 0 #old=0 #old2=0 with Emotiv(display_output=False, verbose=True, write=False) as headset: try: while not self._stop.isSet(): packet = headset.dequeue() if packet is not None: i = i + 1 data = [] for name in electrodes.split(' '): data.append([ packet.sensors[name]['value'], packet.sensors[name]['quality'] ]) O1_buff.write(data) #print(time.time()-old) #old=time.time() pass if i == self.step: self.flag1.set() self.q1.put(O1_buff.list_ret()) self.flag1.clear() i = 0 #print(time.time()-old2) #old2=time.time() except: pass
def _initOldEmotiv(self, display_output, write_to_file): self.emotiv = Emotiv(display_output, write_to_file) gevent.spawn(self.emotiv.setup) gevent.sleep(0) if not self._isOldEmotivConnected(): self.emotiv.close() self._loadDummyData()
def test_repr(): data = get_test_data() packet = Emotiv(data) # tests #214 assert packet.battery == 0
def read(queue): print "Started" with Emotiv(write_values=False) as headset: while True: packet = headset.dequeue() if packet is not None and queue is not None: queue.put(packet)
def main(): if not platform.system() == 'Windows': screen = Xlib() else: screen = WinMouse() width = screen.width height = screen.height cursor_x, cursor_y = width // 2, height // 2 with Emotiv(display_output=True, verbose=False) as headset: while headset.running: updated = False try: packet = headset.dequeue() if packet is None: continue if abs(packet.sensors['X']['value']) > 1: cursor_x -= packet.sensors['X']['value'] updated = True if abs(packet.sensors['Y']['value']) > 1: cursor_y += packet.sensors['Y']['value'] updated = True cursor_x = max(0, min(cursor_x, width)) cursor_y = max(0, min(cursor_y, height)) if updated: screen.move_mouse(cursor_x, cursor_y) time.sleep(0.001) except: pass
def main(self): with Emotiv(display_output=False, verbose=False, write=True, output_path="/home/leonardo/Documents/eeg_hmi/signals") as emotiv: self.time = time.time() while emotiv.running: try: packet = emotiv.dequeue() print np.round((time.time()-self.time),0) if (np.round((time.time()-self.time),2) == 0 and self.c == 0): # os.system("gnome-terminal -e 'bash -c \"cvlc --fullscreen --loop ~/Documents/eeg_hmi/dataset/black.jpg &; exec bash\"'") # os.system("cvlc --fullscreen --loop ~/Documents/eeg_hmi/dataset/black.jpg &") subprocess.Popen("cvlc --fullscreen --loop ~/Documents/eeg_hmi/dataset/black.jpg &", shell=True) if ((np.round((time.time()-self.time),0) == self.init_time+self.step)and self.c == 1): # os.system("gnome-terminal -e 'bash -c \"cvlc --fullscreen "+self.path+"/"+str(self.count)+".mp4 &; exec bash\"'") # os.system("cvlc --fullscreen "+self.path+"/"+str(self.count)+".mp4 &") subprocess.Popen("cvlc --fullscreen "+self.path+"/"+str(self.count)+".mp4 &", shell=True) if ((np.round((time.time()-self.time),0) == (self.init_time+self.clip_time)+self.step) and self.c == 2): os.system("cvlc --fullscreen --loop ~/Documents/eeg_hmi/dataset/SAM.png &") if ((np.round((time.time()-self.time),0) == (self.init_time+self.clip_time+self.questions_time)+self.step)and self.c == 3): os.system("cvlc --fullscreen --loop ~/Documents/eeg_hmi/dataset/black.jpg &") if ((np.round((time.time()-self.time),0) == (self.init_time+self.clip_time+self.questions_time+self.rest_time)+self.step)and self.c == 4): if (self.count < self.num_clips): self.count+=1 self.step = self.step + (self.init_time+self.clip_time+self.questions_time+self.rest_time) else: os.system("pkill -f vlc &") emotiv.stop() #stop experiment except Exception: emotiv.stop() time.sleep(0.001)
def GetDataO(tm): fs = 128.0 #Frecuencia de muestreo N = fs * tm #Numero de muestras ct = 0 #Contador dt = [] #Vector de datos with Emotiv(display_output=False, verbose=True) as headset: while ct < N: packet = headset.dequeue() if packet is not None: # print packet.sensors # print "########################" dic = {} for key, value in packet.sensors.iteritems(): value = packet.sensors[key]['value'] quality = packet.sensors[key]['quality'] dic[key] = (value, quality) dt.append(dic) ct += 1 time.sleep(0.007) ldic = dt dicx = ldic[0].copy() for key, value in dicx.iteritems(): dicx[key] = [] for i in ldic: for key, value in i.iteritems(): value = i[key][0] quality = i[key][1] dicx[key].append((quality, value)) pass return dicx
def evt_main(): global is_running ring_buf = np.zeros(x.size) headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while is_running: packet = headset.dequeue() print packet.gyro_x, packet.gyro_y ring_buf[pos] = packet.sensors["O1"]["value"] pos = (pos + 1) % ring_buf.size if pos % 4 == 0: yield np.concatenate( (ring_buf[pos:ring_buf.size:1], ring_buf[0:pos:1])) gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
def emoPollingWorker(sharedObject): global running with Emotiv(display_output=True, verbose=False) as headset: while True: packet = headset.dequeue() if packet is not None: sharedObject["sensors"] = copy.deepCopy(packet.sensors) time.sleep(0.001)
def _thread_reading_online(self): """ Helper function for reading online data. To be used as a thread, putting data to queue. """ online_data = dict( zip(self.channel_list, [[] for i in range(len(self.channel_list))])) counter = 0 headset = Emotiv(display_output=False, serial_number=self.serial_number, write_values=False) # epoc_channels = [k[1] for k in enumerate(self.headset.sensors)] try: start_time = time.time() while True: packet = headset.dequeue() if packet is not None: for ch in self.channel_list: quality = packet.sensors[ch]['quality'] data = packet.sensors[ch]['value'] online_data[ch].append((data * 0.51) / 1000.) # in mV counter += 1 if counter >= self.buffer_size: ratio = self.sampling_rate // self.buffer_size # assert ((time.time() - start_time) % (1./ratio)) < 0.075 # assert sampling rate # print((time.time() - start_time) % (1./ratio)) # if not ((time.time() - start_time) % 1) < 0.05: # print("WARNING: sampling rate is low!") self.online_data_queue.put( [online_data, headset.battery]) online_data = dict( zip(self.channel_list, [[] for i in range(len(self.channel_list))])) counter = 0 except KeyboardInterrupt: print("stopping...") self.stop()
def epoc_publish_channels(): # Setup ROS publishers. signal_publishers = { channel: rospy.Publisher('epoc/signal/%s' % channel, UInt32) for channel in channels} quality_publishers = { channel: rospy.Publisher('epoc/quality/%s' % channel, UInt32) for channel in channels} # Open a connection to the Emotiv EPOC. headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(1) # Initialize ROS node+publisher. rospy.init_node('epoc_publish') # Start the publishing loop. rospy.loginfo('Starting publishing loop...') published_count = 0 try: while not rospy.is_shutdown(): # Get the next packet from the EPOC. packet = headset.dequeue() # Publish the the EEG channels and accelerometer values. for channel in channels: signal = UInt32(packet.sensors[channel]['value']) quality = UInt32(packet.sensors[channel]['quality']) signal_publishers[channel].publish(signal) quality_publishers[channel].publish(quality) # Update and print information count. published_count += 1 print('\rPublished: %d' % published_count, end='') gevent.sleep(0) except rospy.ROSInterruptException: headset.close()
def evt_main(): global is_running ring_buf = np.zeros(x.size) ring_buf2 = np.zeros(x.size) headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while is_running: packet = headset.dequeue() print packet.gyro_x, packet.gyro_y ring_buf[pos] = packet.sensors["O1"]["value"] ring_buf2[pos] = packet.sensors["O2"]["value"] pos = (pos + 1) % ring_buf.size if pos % 4 == 0: yield np.concatenate((ring_buf[pos:ring_buf.size:1], ring_buf[0:pos:1])), np.concatenate((ring_buf2[pos:ring_buf.size:1], ring_buf2[0:pos:1])) gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
def main_process(self): """ Get realtime EEG data from Emotiv EPOC, process all data (FFT, feature extraction, and classification), and predict the emotion. Input: - Output: Class of emotion between 1 to 5 according to Russel's Circumplex Model. """ headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) threads = [] eeg_realtime = np.zeros((number_of_channel, number_of_realtime_eeg), dtype=np.double) counter = 0 init = True try: #Looping to get realtime EEG data from Emotiv EPOC while True: packet = headset.dequeue() #Get initial EEG data for all channels if init: for i in range(number_of_channel): eeg_realtime[i, counter] = packet.sensors[ channel_names[i]]['value'] else: new_data = [ packet.sensors[channel_names[i]]['value'] for i in range(number_of_channel) ] eeg_realtime = np.insert(eeg_realtime, number_of_realtime_eeg, new_data, axis=1) eeg_realtime = np.delete(eeg_realtime, 0, axis=1) #If EEG data have been recorded in ... seconds, then process data to predict emotion if counter == (sampling_rate - 1) or counter == (number_of_realtime_eeg - 1): t = threading.Thread(target=rte.process_all_data, args=(eeg_realtime, )) threads.append(t) t.start() init = False counter = 0 gevent.sleep(0) counter += 1 except KeyboardInterrupt: headset.close() finally: headset.close()
def __init__(self, parent=None): self.headset = Emotiv() self.electrodePairing = { \ "AF3": {'pair': "AF4", 'order': 1}, "AF4": {'pair': "AF3", 'order': 0}, "F3": {'pair': "F4", 'order': 1}, "F4": {'pair': "F3", 'order': 0}, "F7": {'pair': "F8", 'order': 1}, "F8": {'pair': "F7", 'order': 0}, "FC5": {'pair': "FC6", 'order': 1}, "FC6": {'pair': "FC5", 'order': 0}, "T7": {'pair': "T8", 'order': 1}, "T8": {'pair': "T7", 'order': 0}, "P7": {'pair': "P8", 'order': 1}, "P8": {'pair': "P7", 'order': 0}, "O1": {'pair': "O2", 'order': 1}, "O2": {'pair': "O1", 'order': 0}, } self.timer = pg.QtCore.QTimer() self.recording = False self.parser = PacketParser() self.header_text = "Timestamp,F3 Value,F3 Quality,FC5 Value,FC5 Quality,F7 Value,F7 Quality,T7 Value,T7 Quality,P7 Value,P7 Quality,O1 Value,O1 Quality,O2 Value,O2 Quality,P8 Value,P8 Quality,T8 Value,T8 Quality,F8 Value,F8 Quality,AF4 Value,AF4 Quality,FC6 Value,FC6 Quality,F4 Value,F4 Quality,AF3 Value,AF3 Quality,X Value,Y Value,Z Value"
def __init__(self, connect_new_device=True, cache=True, cache_length=200, is_research=True, **kwargs): self.current_y = 22 self.previous_y = 22 self.speed_y = 22 self.cache = cache self.t_last_window = time.time() self.t = [] if self.cache: self.cache_data = dict() self.cache_decoder = np.zeros((emotiv_decoder.OUTPUT_DIM, 1)) for ch in CHANNELS: self.cache_data[ch] = [0] self.cache_length = cache_length if connect_new_device: self.emotiv = Emotiv(display_output=False, is_research=is_research) else: self.emotiv = kwargs['emotiv'] self.load_calibration()
def main(): with Emotiv(display_output=False, verbose=False, write=False, force_epoc_mode=True, is_research=True) as headset: while headset.running: try: packet = headset.dequeue() if packet is not None: sendToMatlab(packet) time.sleep(0.001) except Exception: clientsocket.close() headset.stop()
def main(): pub = rospy.Publisher('emotiv_raw', Data, queue_size=1000) rospy.init_node('emotiv_node') rate = rospy.Rate(128) msg = Data() with Emotiv(display_output=False, verbose=False, write=False, force_epoc_mode=True, is_research=True) as headset: while not rospy.is_shutdown(): try: packet = headset.dequeue() if packet is not None: updateMsg(packet, msg) pub.publish(msg) rate.sleep() except rospy.ROSInterruptException: headset.stop()
def __init__(self, channels, gheight): """ Creates pygame window and graph drawing workers for each sensor. """ pygame.init() self.screen = pygame.display.set_mode(resolution) self.graphers = [] self.record_packets = [] self.fullscreen = False self.recording = False self.updated = False self.middle_x, self.middle_y = resolution[0]/2, resolution[1]/2 for i, name in enumerate(channels): self.graphers.append(Grapher(self.screen, gheight, name, i)) self.emotiv = Emotiv(display_output=False) gevent.spawn(self.emotiv.setup) gevent.sleep(0)
def evt_main(): global is_running ring_buf = np.zeros(x.size) headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while is_running: packet = headset.dequeue() yield packet gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
def getDataO(self, tm): fs = 128.0 #Frecuencia de muestreo N = fs * tm #Numero de muestras ct = 0 #Contador dt = [] #Vector de datos with Emotiv(display_output=False, verbose=True) as headset: while ct < N: packet = headset.dequeue() if packet is not None: # print packet.sensors # print "########################" dic = {} for key, value in packet.sensors.iteritems(): value = packet.sensors[key]['value'] quality = packet.sensors[key]['quality'] dic[key] = (value, quality) dt.append(dic) ct += 1 time.sleep(0.007) return dt
class ThreadReaderEmotiv(Thread): def __init__(self, input): threading.Thread.__init__(self) self.headset = Emotiv() self.f3 = input['F3'] self.f4 = input['F4'] self.af3 = input['AF3'] self.af4 = input['AF4'] def run(self): self.headset = Emotiv() gevent.spawn(self.headset.setup) gevent.sleep(0) print("Serial Number: %s" % self.headset.serial_number) while True: packet = self.headset.dequeue() self.f3.insert(packet.sensors['F3']['value']) self.f4.insert(packet.sensors['F4']['value']) self.af3.insert(packet.sensors['AF3']['value']) self.af4.insert(packet.sensors['AF4']['value']) gevent.sleep(0)
def collect_raw_thread(): """ collect raw data from another thread""" sensor_names = ["T7", "T8", "P7", "P8", "O1", "O2"] with Emotiv(display_output=True, write=True, write_decrypted=True, verbose=True, output_path="data") as headset: O2_array = [] while True: packet = headset.dequeue() sensor_vals = [] if packet is not None: for i in sensor_names: sensor_vals.append(dict(packet.sensors)[i]['value']) O2_array.append(sensor_vals[5]) socketio.sleep(0.0078) if len(O2_array) % 1024 == 0: Fourier_Thread(O2_array[-1024:]) arr = sensor_vals socketio.emit('array_response', { 'data': 'Server generated event', 'data': O2_array }, namespace='/test') socketio.emit('raw_response', { 'data': 'Server generated event', 'raw_array': arr }, namespace='/test')
def main_process(self): """ Get realtime EEG data from Emotiv EPOC, process all data (FFT, feature extraction, and classification), and predict the emotion. Input: - Output: Class of emotion between 1 to 5 according to Russel's Circumplex Model. """ headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) threads = [] eeg_realtime = np.zeros((number_of_channel,number_of_realtime_eeg),dtype=np.double) counter=0 init=True try: #Looping to get realtime EEG data from Emotiv EPOC while True: packet = headset.dequeue() #Get initial EEG data for all channels if init: for i in range(number_of_channel):eeg_realtime[i,counter]=packet.sensors[channel_names[i]]['value'] else: new_data=[packet.sensors[channel_names[i]]['value'] for i in range(number_of_channel)] eeg_realtime=np.insert(eeg_realtime,number_of_realtime_eeg,new_data,axis=1) eeg_realtime=np.delete(eeg_realtime,0,axis=1) #If EEG data have been recorded in ... seconds, then process data to predict emotion if counter == (sampling_rate-1) or counter == (number_of_realtime_eeg-1): t = threading.Thread(target=rte.process_all_data, args=(eeg_realtime,)) threads.append(t) t.start() init=False counter=0 gevent.sleep(0) counter += 1 except KeyboardInterrupt: headset.close() finally: headset.close()
def evt_main(ring_buf): global is_running headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while is_running: packet = headset.dequeue() print packet.gyro_x, packet.gyro_y ring_buf[pos] = packet.sensors["FC5"]["value"] if pos % 4 == 0: yield ring_buf pos = (pos + 1) % ring_buf.size gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
def packets(): global is_running ring_buf = np.zeros(x.size) headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while is_running: packet = headset.dequeue() data = {key: (value["value"], value["quality"]) for (key, value) in packet.sensors.items()} yield data gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
def evt_main(ring_buf): headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) pos = 0 try: while True: packet = headset.dequeue() print packet.gyro_x, packet.gyro_y ring_buf[pos] = packet.gyro_x if pos % 4 == 0: yield ring_buf pos = (pos + 1) % 1024 gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: is_running = False headset.close()
from emokit.emotiv import Emotiv if __name__ == "__main__": with Emotiv() as headset: while True: packet = headset.dequeue() if packet is not None: print("Gyro - X:{x_position} Y:{y_position}".format(x_position=packet.sensors['X']['value'],y_position=packet.sensors['Y']['value']))
def main(debug=False): global gheight pygame.init() screen = pygame.display.set_mode((1600, 900)) graphers = [] recordings = [] recording = False record_packets = [] updated = False curX, curY = 400, 300 for name in 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' '): graphers.append(Grapher(screen, name, len(graphers))) fullscreen = False emotiv = Emotiv(displayOutput=False) gevent.spawn(emotiv.setup) gevent.sleep(1) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: emotiv.close() return if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_ESCAPE): emotiv.close() return elif (event.key == pygame.K_f): if fullscreen: screen = pygame.display.set_mode((1600, 900)) fullscreen = False else: screen = pygame.display.set_mode((1600,900), FULLSCREEN, 16) fullscreen = True elif (event.key == pygame.K_r): if not recording: record_packets = [] recording = True else: recording = False recordings.append(list(record_packets)) record_packets = None packetsInQueue = 0 try: while packetsInQueue < 8: packet = emotiv.dequeue() print(packet.sensors) if abs(packet.gyroX) > 1: curX = max(0, min(curX, 1600)) curX -= packet.gyroX if abs(packet.gyroY) > 1: curY += packet.gyroY curY = max(0, min(curY, 900)) map(lambda x: x.update(packet), graphers) if recording: record_packets.append(packet) updated = True packetsInQueue += 1 except Exception, e: print e if updated: screen.fill((75, 75, 75)) map(lambda x: x.draw(), graphers) pygame.draw.rect(screen, (255, 255, 255), (curX - 5, curY - 5, 10, 10), 0) pygame.display.flip() updated = False gevent.sleep(0)
# This is an example of popping a packet from the Emotiv class's packet queue # and printing the gyro x and y values to the console. from emokit.emotiv import Emotiv import gevent if __name__ == "__main__": headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) try: while True: packet = headset.dequeue() print packet.gyro_x, packet.gyro_y gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: headset.close()
def getAlphaPower(buff, Ts = 1/128): N = len(buff) freq = np.fft.fftfreq(N,Ts) Power = np.abs(np.fft(buff))**2 spectrum = zip(freq,Power) alphalist = [] for (f,S) in spectrum: if f>=8 and f<=12: alphalist.append(S) alpha = np.mean(alphalist) return alpha if __name__ == "__main__": headset = Emotiv() routine = gevent.spawn(headset.setup) gevent.sleep(0) try: while True: buffin = [] for i in xrange(128): packet = headset.dequeue() buffin.append(packet.sensors['F3']['value']) #print packet.gyro_x, packet.gyro_y, packet.battery gevent.sleep(0) alpha = getAlphaPower(buffin) print alpha except KeyboardInterrupt: headset.running = False headset.close()
self.httpd = self.server_class(self.server_address, self.handler_class) print time.asctime(), "Server Starts - %s:%s" % self.server_address while self.run_server: try: self.httpd.handle_request() except (KeyboardInterrupt, SystemExit): self.stop() raise print time.asctime(), "Server Stops - %s:%s" % self.server_address self.httpd.server_close(); if __name__ == "__main__": emotiv = Emotiv(display_output=False) server = HttpEEGDataProvider() try: print "starting server and emotiv" t = threading.Thread(target=server.run) t.start() emotiv.setup() print "closing server and emotiv" emotiv.close() server.stop() except (KeyboardInterrupt, SystemExit) as e: print e.getMessage() emotiv.close() server.stop()
def main(): """ Creates pygame window and graph drawing workers for each sensor. """ global gheight pygame.init() screen = pygame.display.set_mode((1280, 800)) graphers = [] recordings = [] recording = False record_packets = [] updated = False cursor_x, cursor_y = 400, 300 #for name in 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' '): for name in 'AF4 P8 F4 T8 O2'.split(' '): graphers.append(Grapher(screen, name, len(graphers))) fullscreen = False emotiv = Emotiv(display_output=True) gevent.spawn(emotiv.setup) gevent.sleep(0) while emotiv.running: for event in pygame.event.get(): if event.type == pygame.QUIT: emotiv.close() return if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: emotiv.close() return elif event.key == pygame.K_f: if fullscreen: screen = pygame.display.set_mode((1280, 800)) fullscreen = False else: screen = pygame.display.set_mode((1280, 800), FULLSCREEN, 16) fullscreen = True elif event.key == pygame.K_r: if not recording: record_packets = [] recording = True else: recording = False recordings.append(list(record_packets)) record_packets = None packets_in_queue = 0 try: while packets_in_queue < 8: packet = emotiv.dequeue() if abs(packet.gyro_x) > 1: cursor_x = max(0, min(cursor_x, 1280)) cursor_x -= packet.gyro_x if abs(packet.gyro_y) > 1: cursor_y += packet.gyro_y cursor_y = max(0, min(cursor_y, 800)) map(lambda x: x.update(packet), graphers) if recording: record_packets.append(packet) updated = True packets_in_queue += 1 except Exception, ex: print ex if updated: screen.fill((75, 75, 75)) map(lambda x: x.draw(), graphers) pygame.draw.rect(screen, (255, 255, 255), (cursor_x - 5, cursor_y - 5, 10, 10), 0) pygame.display.flip() updated = False gevent.sleep(0)
height = screen.height cursor_x, cursor_y = width / 2, height / 2 while True: updated = False packet = headset.dequeue() if abs(packet.gyro_x) > 1: cursor_x -= packet.gyro_x updated = True if abs(packet.gyro_y) > 1: cursor_y += packet.gyro_y updated = True cursor_x = max(0, min(cursor_x, width)) cursor_y = max(0, min(cursor_y, height)) if updated: screen.move_mouse(cursor_x, cursor_y) gevent.sleep(0) headset = None if __name__ == "__main__": try: headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) main() finally: if headset: headset.close()
if(args.nogui): guifeature = False sensornames = 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' ') if guifeature: # building the node connection display pygame.init() surface = pygame.display.set_mode((640, 480), 0, 32) pygame.display.set_caption('Emotiv Epoc Callibration Test') background = pygame.image.load(os.path.join('images','sensormap.png')) surface.blit(background, (0,0)) pygame.display.flip() print "Initializing controller..." emotiv = Emotiv(displayOutput=False) gevent.spawn(emotiv.setup) gevent.sleep(1) print "Controller initialized." initOSCClient(args.ip, args.port) print "Starting client." # run forever try: running = True while running: if guifeature: for event in pygame.event.get(): if event.type == QUIT:
curX, curY = width / 2, height / 2 while True: updated = False packet = emotiv.dequeue() if abs(packet.gyroX) > 1: curX -= packet.gyroX updated = True if abs(packet.gyroY) > 1: curY += packet.gyroY updated = True curX = max(0, min(curX, width)) curY = max(0, min(curY, height)) if updated: screen.move_mouse(curX, curY) gevent.sleep(0) emotiv = None if __name__ == "__main__": try: emotiv = Emotiv() gevent.spawn(emotiv.setup) gevent.sleep(1) main(*sys.argv[1:]) finally: if emotiv: emotiv.close()
class EEGRenderer(): def __init__(self, channels, gheight): """ Creates pygame window and graph drawing workers for each sensor. """ pygame.init() self.screen = pygame.display.set_mode(resolution) self.graphers = [] self.record_packets = [] self.fullscreen = False self.recording = False self.updated = False self.middle_x, self.middle_y = resolution[0]/2, resolution[1]/2 for i, name in enumerate(channels): self.graphers.append(Grapher(self.screen, gheight, name, i)) self.emotiv = Emotiv(display_output=False) gevent.spawn(self.emotiv.setup) gevent.sleep(0) def handleEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.emotiv.close() return if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.emotiv.close() return elif event.key == pygame.K_f: if self.fullscreen: self.screen = pygame.display.set_mode(resolution) self.fullscreen = False else: self.screen = pygame.display.set_mode(resolution, FULLSCREEN, 16) self.fullscreen = True elif event.key == pygame.K_r: if not self.recording: self.record_packets = [] self.recording = True else: self.recording = False self.recordings.append(list(self.record_packets)) self.record_packets = None def update(self, cursor_x, cursor_y): if self.updated: self.screen.fill((75, 75, 75)) map(lambda x:x.draw(), self.graphers) pygame.draw.rect(self.screen, (255, 0, 255), [cursor_x, cursor_y, 5, 5], 5) pygame.display.flip() self.updated = False def main(self): while self.emotiv.running: self.handleEvents() packets_in_queue = 0 try: cursor_x, cursor_y = self.middle_x, self.middle_y while packets_in_queue < 8: packet = self.emotiv.dequeue() if abs(packet.gyro_x) > 1: cursor_x += packet.gyro_x-GYRO_DEFAULT if abs(packet.gyro_y) > 1: cursor_y += packet.gyro_y-GYRO_DEFAULT map(lambda x: x.update(packet), self.graphers) if self.recording: self.record_packets.append(packet) self.updated = True packets_in_queue += 1 cursor_x = self.middle_x + cursor_x / packets_in_queue cursor_y = self.middle_y + cursor_y / packets_in_queue except (Exception, KeyboardInterrupt) as e: raise e self.update(cursor_x, cursor_y) gevent.sleep(0)