Example #1
0
    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
Example #2
0
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()
Example #3
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()
            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 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 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 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()
Example #8
0
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 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()
Example #10
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 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()
Example #12
0
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()
Example #13
0
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()
Example #14
0
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()
Example #15
0
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()
Example #16
0
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()
Example #17
0
class Analizer():
    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 analize(self, signals, sensors, bufferlength, frecs):
        #logging.debug("Analize")
        nSamples = bufferlength
        sampleRate = 128.  #this is the epoc rate
        t = arange(nSamples) / sampleRate
        cutoff_hz = 40
        nyq_rate = sampleRate / 2.
        numtaps = 29
        fir_coeff = firwin(numtaps, cutoff_hz / nyq_rate)
        results = {}
        #sensors = 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' ')
        for name in sensors:
            #print signals[name]
            filtered_signal = lfilter(fir_coeff, 5.0, signals[name])
            warmup = numtaps - 1
            #print filtered_signal
            # The phase delay of the filtered signal
            delay = (warmup / 2) / sampleRate
            #print(len(signals[name]))
            #print "\n"

            fres, espect = periodogram(filtered_signal[warmup:][5:],
                                       sampleRate)

            #print max frec
            maxFrec = True
            if maxFrec:
                mespect = max(espect[5:])
                i = 0
                while espect[5:][i] != mespect:
                    i += 1
                #print "max frec=",fres[5:][i]
                results['Max' + name] = fres[5:][i]

            frecs.sort()
            results[name] = []
            for x in frecs:
                flow = x - 1
                fhight = x + 1
                i = 0
                while fres[i] < flow:
                    i += 1
                debugflist = filter(lambda x: x >= flow and x <= fhight, fres)
                debugAlist = espect[i:i + len(debugflist)]
                #print debugflist,"\n",debugAlist
                frecAvg = sum(debugAlist) / len(debugAlist)
                results[name].append(frecAvg)
                pass

            if False:
                figure(1)
                plot(t, signals[name])
                plot(t - delay, filtered_signal, 'r')
                plot(t[warmup:] - delay,
                     filtered_signal[warmup:],
                     'g',
                     linewidth=4)
                grid(True)

                figure(2)
                plot(fres, espect)

                show()
                pass

            pass

        results["avg"] = []
        for i in range(len(frecs)):
            fi = map(lambda n: results[n][i], sensors)
            results["avg"].append(sum(fi) / len(fi))
        #print results
        return results
        pass

    def analizeProccess(self):

        headset = self.headset
        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,
                                               self.frecs)
                    #print self.signal
                    for name in sensors:
                        packets[name] = packets[name][64:]
                        pass
                    pass
            gevent.sleep(0)
        pass

    def close(self):
        self.headset.close()
        pass
Example #18
0
    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()

                # 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']), 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
Example #19
0
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)
Example #20
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)
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())
Example #22
0
                    break
            if not running:
                break

        # get sensor values from headset
        packet = emotiv.dequeue()
        processPacket(packet)
        for i in range(len(sensornames)):
            updateQuality(i, packet.sensors[sensornames[i]]['quality'])
        if guifeature:
            pygame.display.flip()
        gevent.sleep(0)
    print "Terminating client."
    if guifeature:
        pygame.quit()
    emotiv.close()
    closeOSC()
    sys.exit()

# cleanly exit the client
except KeyboardInterrupt:
    print "Terminating client."
    if guifeature:
        pygame.quit()
    emotiv.close()
    closeOSC()
    sys.exit()
finally:
    print "Terminating client."
    if guifeature:
        pygame.quit()
Example #23
0
        height = screen.height

        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()
Example #24
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()
Example #25
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()
                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)
Example #26
0
                        elif round(freq[j]) > 0.5 and round(freq[j]) < 80:
                            norm[7] += 1
                            output[7] += yf[j]
                        j = j + 1
                        if norm[0] != 0 and norm[1] != 0 and norm[
                                2] != 0 and norm[3] != 0 and norm[
                                    4] != 0 and norm[5] != 0 and norm[
                                        6] != 0 and norm[7] != 0:
                            mOscMessage.clear("/brainWaves/" +
                                              SENSOR_LIST.split(' ')[i] + "/")
                            mOscMessage.append(output[0] / norm[0])
                            mOscMessage.append(output[1] / norm[1])
                            mOscMessage.append(output[2] / norm[2])
                            mOscMessage.append(output[3] / norm[3])
                            mOscMessage.append(output[4] / norm[4])
                            mOscMessage.append(output[5] / norm[5])
                            mOscMessage.append(output[6] / norm[6])
                            mOscMessage.append(output[7] / norm[7])
                            mOscClient.send(mOscMessage)
                            #Here we create and send an oscMessage
                        # print str(output[0]/norm[0])+"\t"+str(output[1]/norm[1])+"\t"+str(output[2]/norm[2])+"\t"+str(output[3]/norm[3])
                count = 0  #After the analysis we recet our counter
                chanHist = [[0 for x in range(0)]
                            for x in range(6)]  #and the channel history
            cCount = 0
            gevent.sleep(0)
    except KeyboardInterrupt:
        headset.close()
    finally:
        headset.close()
Example #27
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)
Example #28
0
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)