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 read_data(self): try: a = Emotiv() self.current_session_raw = a.setupWin() # a.device.close() self.get_raw_id() return True except Exception as err: print "Error reading raw data! " for t in err.args: print t return False
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 save_data(salidaDatos, q_marcas): emo = EM.Emotiv(True, False, (1, 1)) emo.connect() emo.setup() emo.setBufferSizeInSecs(5.0) emo.enableForUser(0) emo.setEdfOutput(salidaDatos) emo.startWriting() emo.start() salida = False while not salida: if not q_marcas.empty(): marca = q_marcas.get() if marca == 42: salida = True print "Antes de mandar ", marca, time.time() emo.mark(0, marca) print "Desp de mandar ", marca, time.time() time.sleep(2) emo.stop() emo.disconnect()
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 emotiv(self): headset = Emotiv() gevent.spawn(headset.setup) print("Serial Number: %s" % headset.serial_number) self.num_blocks = len(self.content) cont_seconds = 0 temp_t = 0 tag = self.content[0][1] #Se define el escritor de las lecturas en el archivo CSV writer = csv.writer(open(self.filename, 'w'), delimiter=',', quotechar='"', lineterminator='\n') row = ["Audio"] row.append("Time") row.append("Exact Time") for sensor in self.sensors: row.append(sensor) row.append(sensor + "_Quality") row.append("Emotion") row.append("Selected Emotion") writer.writerow(row) try: t0 = time.time() time_block = 300 index_actual = 0 while True: t = int(time.time() - t0) if temp_t != t: cont_seconds += 1 if cont_seconds >= time_block: cont_seconds = 0 index_actual += 1 #self.player.next_source() if cont_seconds >= 300: time_block = 15 if t > 720: headset.close() self.player.pause() break if t < 180: tag = 'NON-RELAX' elif (t >= 180): tag = self.emotions[index_actual] row = [self.content[index_actual][0].split('.')[0]] row.append(str(t)) row.append(time.time()) try: for sensor in self.sensors: row.append(str(headset.sensors[sensor]['value'])) row.append(str(headset.sensors[sensor]['quality'])) except: print "Sensor incorrecto" headset.close() row.append(tag) row.append(self.selectedEmotion) if self.selectedEmotion != '': self.selectedEmotion = '' # Se exporta a csv writer.writerow(row) #print row temp_t = t gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: headset.close()
def main(outfile='eegout.csv', debug=False): global gheight pygame.init() screen = pygame.display.set_mode((800, 450)) graphers = [] recordings = [] recording = False record_packets = [] updated = False curX, curY = 400, 300 pause = False features = 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' ') for name in features: graphers.append(Grapher(screen, name, len(graphers))) fullscreen = False emotiv = Emotiv(displayOutput=False) gevent.spawn(emotiv.setup) gevent.sleep(1) labels = 'down up'.split(' ') classifier = RandomizedTrees(labels) testsize = 0 train = 0 csvfile = open(outfile, 'wb') csvwriter = csv.writer(csvfile, delimiter = ',') # first row = attribute names csvwriter.writerow(features); # for displaying testing instructions font = pygame.font.Font(None, 36) text = 'next: ' + labels[train / 2] 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((800, 450)) fullscreen = False else: # Don't actually do full-screen. You might be unable to # undo... screen = pygame.display.set_mode((1600,900)) 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 elif (event.key == pygame.K_RETURN): train = train + 1 # print the next concept to train if train < 2 * len(labels): if train % 2 == 0: text = 'next: ' + labels[train / 2] else: text = 'current: ' + labels[train / 2] else: text = '' elif (event.key == pygame.K_p): pause = not pause packetsInQueue = 0 try: while packetsInQueue < 8: packet = emotiv.dequeue() # update cursor position based on gyros # 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)) sensors = packet.sensors csvrow = [] for i in range(len(features)): csvrow.append(sensors[features[i]]['value']) print csvrow csvwriter.writerow(csvrow); if train == 0: print 'doing nothing' elif train < 2 * len(labels): if train % 2 == 1: classifier.AddTrainExample(csvrow, labels[train / 2]) testsize = testsize + 1 print labels[train / 2] elif train == 2 * len(labels): classifier.Train() train = train + 1 else: (label, score) = classifier.Classify(csvrow) print "label:" print label print "classification score:" print score # Update cursor (top left if (0, 0)): # Suggested pairings: # right hand up = right # left hand up = left # both hands up = up # rest up = down if pause == False: if label == 'right': curX += 1 x, y = screen.get_size() if curX > x: curX = x elif label == 'left': curX -= 1 if curX < 0: curX = 0 elif label == 'down': curY += 1 x, y = screen.get_size() if curY > y: curY = y elif label == 'up': curY -= 1 if curY < 0: curY = 0 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) # r for 'to render' rtext = font.render(text, 1, (0, 255, 0)) screen.blit(rtext, (0, 0)) pygame.display.flip() updated = False gevent.sleep(0)
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()
def start(self, sequence=None, time_block=7, filename='data.csv'): self.time_block = time_block self.filename = filename #Se define el objeto EMOTIV, utilizando la libreria EMOKIT headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) print("Serial Number: %s" % headset.serial_number) if sequence is not None: self.sequence = sequence self.num_blocks = len(self.sequence) i = 0 cont_block = 0 cont_seconds = 0 temp_t = 0 tag = self.sequence[0] #Se define el escritor de las lecturas en el archivo CSV writer = csv.writer(open(self.filename, 'w'), delimiter='\t', quotechar='"') try: t0 = time.time() while True: t = int(time.time() - t0) #t = int(time.time()) if temp_t != t: cont_seconds += 1 if cont_seconds > self.time_block: cont_seconds = 0 cont_block += 1 if cont_block == self.num_blocks: headset.close() break else: tag = self.sequence[cont_block] # Se obtiene el paquete de datos, utilizando EMOKIT packet = headset.dequeue() #print packet.sensors # Se construye la informacion a guardar row = [ str(t), "F3:" + str(packet.sensors['F3']['quality']) + "," + str(packet.sensors['F3']['value']), "F4:" + str(packet.sensors['F4']['quality']) + "," + str(packet.sensors['F4']['value']), "AF3:" + str(packet.sensors['AF3']['quality']) + "," + str(packet.sensors['AF3']['value']), "AF4:" + str(packet.sensors['AF4']['quality']) + "," + str(packet.sensors['AF4']['value']), "O1:" + str(packet.sensors['O1']['quality']) + "," + str(packet.sensors['O1']['value']), "O2:" + str(packet.sensors['O2']['quality']) + "," + str(packet.sensors['O2']['value']), tag ] # Se exporta a csv writer.writerow(row) print row temp_t = t gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: headset.close() i += 1
def main(): """ Creates pygame window and graph drawing workers for each sensor. """ global gheight pygame.init() screen = pygame.display.set_mode((800, 600)) 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(' '): 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((800, 600)) fullscreen = False else: screen = pygame.display.set_mode((800, 600), 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, 800)) cursor_x -= packet.gyro_x if abs(packet.gyro_y) > 1: cursor_y += packet.gyro_y cursor_y = max(0, min(cursor_y, 600)) 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)
def main(): """ Creates pygame window and graph drawing workers for each sensor. """ global gheight pygame.init() screen = pygame.display.set_mode((800, 600)) 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(" "): 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((800, 600)) fullscreen = False else: screen = pygame.display.set_mode((800, 600), 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, 800)) cursor_x -= packet.gyro_x if abs(packet.gyro_y) > 1: cursor_y += packet.gyro_y cursor_y = max(0, min(cursor_y, 600)) 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)
def start(self, sequence=None, sensors=None, time_block=7): self.time_block = time_block #Se define el objeto EMOTIV, utilizando la libreria EMOKIT headset = Emotiv() gevent.spawn(headset.setup) print("Serial Number: %s" % headset.serial_number) if sequence is not None: self.sequence = sequence self.num_blocks = len(self.sequence) i = 0 cont_block = 0 cont_seconds = 0 temp_t = 0 tag = self.sequence[0] #Se define el escritor de las lecturas en el archivo CSV # writer = csv.writer(open(self.filename, 'w'), delimiter=',', quotechar='"', lineterminator='\n') #windows writer = csv.writer(open(self.filename, 'w'), delimiter=',', quotechar='"') #linux try: row = ["Time"] for sensor in sensors: row.append(sensor) row.append(sensor + "_Quality") row.append("Tag") writer.writerow(row) t0 = time.time() while True: t = int(time.time() - t0) if temp_t != t: cont_seconds += 1 if cont_seconds > self.time_block: cont_seconds = 0 cont_block += 1 if cont_block == self.num_blocks: headset.close() break else: tag = self.sequence[cont_block] # Se construye la informacion a guardar row = [str(t)] try: for sensor in sensors: row.append(str(headset.sensors[sensor]['value'])) row.append(str(headset.sensors[sensor]['quality'])) except: print "Sensor incorrecto" headset.close() row.append(tag) # Se exporta a csv writer.writerow(row) print row temp_t = t gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: headset.close() i += 1
updated = False for packet in headset: print 'received', packet.gyroX, packet.gyroY updated = True if abs(packet.gyroX) > 1: curX -= packet.gyroX - 1 if abs(packet.gyroY) > 1: curY += packet.gyroY curX = max(0, min(curX, width)) curY = max(0, min(curY, height)) if updated: screen.move_mouse(curX, curY) time.sleep(1.0 / 60) headset = None try: logger = logging.getLogger('emotiv') logger.setLevel(logging.INFO) log_handler = logging.StreamHandler() logger.addHandler(log_handler) headset = Emotiv() main(*sys.argv[1:]) finally: pass
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() 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)
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() 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)
updated = False for packet in emotiv.dequeue(): updated = True if abs(packet.gyroX) > 1: curX -= packet.gyroX - 1 if abs(packet.gyroY) > 1: curY += packet.gyroY curX = max(0, min(curX, width)) curY = max(0, min(curY, height)) if updated: screen.move_mouse(curX, curY) time.sleep(1.0 / 60) emotiv = None try: logger = logging.getLogger('emotiv') logger.setLevel(logging.INFO) log_handler = logging.StreamHandler() logger.addHandler(log_handler) emotiv = Emotiv() main(*sys.argv[1:]) finally: if emotiv: emotiv.close()
return string.join(current_string,"") if __name__ == "__main__": folder = os.path.dirname(os.path.abspath(__file__))+'\\data\\' name = "" filename = datetime.now().strftime('%H%M%S') + "_" + name + "_" + str(maxtime) + ".csv" output = 0 FreqFlicker = 10 t = 1 # panjang waktu sinyal reference (sekond) fs = 128 # frekuensi sampling #pygame.time.set_timer(USEREVENT + 1,6000) # Timer Interrupt headset = Emotiv() gevent.spawn(headset.setup) gevent.sleep(0) for val in avail_state : rect = Rectangle(env.getRectFreq(val), (env.getRectPos(val)[0],env.getRectPos(val)[1]), env.getRectIMG(val), val) rect.start() background = Background() # menjalankan init() Class Background background.start() rectangle2 = Rectangle2(10) # menjalankan init() Class Background rectangle2.start() winsinc,Ref,t1,t2 = getdata(t,fs) # Pengondisian Sinyal data winsinc2 = bool(max(winsinc)) # print winsinc
def emotiv(self): headset = Emotiv() gevent.spawn(headset.setup) print("Serial Number: %s" % headset.serial_number) self.num_blocks = len(self.content) cont_block = 0 cont_seconds = 0 temp_t = 0 tag = self.content[0][1] #Se define el escritor de las lecturas en el archivo CSV writer = csv.writer(open(self.filename, 'w'), delimiter=',', quotechar='"', lineterminator='\n') row = ["Image/Color"] row.append("Time") row.append("Exact Time") for sensor in self.sensors: row.append(sensor) row.append(sensor + "_Quality") row.append("Emotion") row.append("Selected Emotion") writer.writerow(row) try: t0 = time.time() tnow = time.time() while True: t = int(time.time() - t0) if temp_t != t: cont_seconds += 1 if cont_seconds > self.time_block: cont_seconds = 0 cont_block += 1 if cont_block == self.num_blocks: headset.close() break else: tag = self.content[cont_block][1] #display images if cont_block >= self.contColors: self.time_block = 5 self.panel1.configure( image=self.images[cont_block - self.contColors]) print "Display: " + str(cont_block - self.contColors) self.display = self.images[cont_block - self.contColors] self.panel1.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES) else: color = Color(self.content[cont_block - 1][0]) colors = list( color.range_to( Color(self.content[cont_block][0]), self.difColorSize)) now = time.time() for color in colors: self.root.configure(background=color) #self.root.configure(background=self.content[cont_block][0]) row = [self.content[cont_block][0]] row.append(str(t)) row.append(time.time()) try: for sensor in self.sensors: row.append(str(headset.sensors[sensor]['value'])) row.append(str(headset.sensors[sensor]['quality'])) except: print "Sensor incorrecto" headset.close() row.append(tag) row.append(self.selectedEmotion) if self.selectedEmotion != '': self.selectedEmotion = '' # Se exporta a csv writer.writerow(row) #print row temp_t = t gevent.sleep(0) except KeyboardInterrupt: headset.close() finally: headset.close()
curY += packet.gyroY curX = max(0, min(curX, 800)) curY = max(0, min(curY, 600)) map(lambda x: x.update(packet), graphers) 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() time.sleep(1.0 / 60) emotiv = None try: logger = logging.getLogger('emotiv') logger.setLevel(logging.INFO) log_handler = logging.StreamHandler() logger.addHandler(log_handler) emotiv = Emotiv() gheight = 600 / 14 hgheight = gheight >> 1 main(*sys.argv[1:]) finally: pass