Esempio n. 1
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()
Esempio n. 2
0
    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
Esempio n. 3
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
Esempio n. 4
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()
Esempio n. 7
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()
Esempio n. 8
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 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()
Esempio n. 11
0
    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()
Esempio n. 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()
Esempio n. 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()
Esempio n. 14
0
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)
Esempio n. 15
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()
Esempio n. 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()
Esempio n. 17
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()
Esempio n. 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
Esempio n. 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)
Esempio n. 20
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)
Esempio n. 21
0
    mOscMessage = OSCMessage()

    headset = Emotiv(serial_number="SN201405232628GM",
                     vendor_id=8609,
                     product_id=1)
    gevent.spawn(headset.setup)
    gevent.sleep(0)

    chanHist = [[0 for x in range(0)] for x in range(6)]
    N = 128  #We always take 128 chunks so we get to slighly above 60hz
    T = 1.0 / (N * 1
               )  # We know that the emotive delivers 128 samples persecond
    count = 0
    try:
        while True:
            packet = headset.dequeue()
            cCount = 0
            for k, v in packet.sensors.iteritems():
                if ((k in SENSOR_LIST) and ('value' in v)
                        and ('quality' in v)):
                    chanHist[cCount].append(v['value'])
                    cCount += 1
                    mOscMessage.clear("/emokit/" + k + "/")
                    mOscMessage.append(v['value'])
                    mOscMessage.append(v['quality'])
                    mOscClient.send(mOscMessage)
            count += 1
            if count >= N:
                for i in range(0, len(chanHist)):
                    output = [1 for x in range(8)]
                    norm = [1 for x in range(8)]
Esempio n. 22
0
class EmokitController:
    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 load_calibration(self):
        self.calibrated = False
        try:
            self.bounds = pickle.load(open('data/CALIBRATION_BOUNDS.pkl',
                                           'rb'))
            self.calibrated = True
        except:
            print('No calibration profile found (data/CALIBRATION_BOUNDS.pkl)')

    def establish_connection(self):
        while True:
            self.stream_data()
            key = self.decode()
            if key != 1:
                time.sleep(0.01)
            else:
                break
        print('Connection established.')

    def decode(self):
        data = np.array([
            self.cache_data[ch][-emotiv_decoder.WINDOW_SIZE:]
            for ch in emotiv_decoder.CHANNELS
        ],
                        dtype='float')
        if (np.size(data, 1) == emotiv_decoder.WINDOW_SIZE):
            if self.calibrated:
                for i, ch in enumerate(emotiv_decoder.CHANNELS):
                    data[i, :] = (
                        data[i, :] -
                        (self.bounds['max'][ch] + self.bounds['min'][ch]) /
                        2) / (self.bounds['max'][ch] - self.bounds['min'][ch])
            key = emotiv_decoder.decode(data)

            #print(self.cache_data)
            if (np.size(self.cache_decoder, 1) >= self.cache_length):
                self.cache_decoder[:, :-1] = self.cache_decoder[:, 1:]
                self.cache_decoder[:, -1] = key
            else:
                self.cache_decoder = np.hstack(
                    [self.cache_decoder,
                     key.reshape(np.size(key), 1)])
            return (key)
        else:
            return (0)

    def stream_and_decode(self):
        self.stream_data()
        if (time.time() - self.t_last_window) >= emotiv_decoder.WINDOW_SHIFT:
            key = self.decode()
            self.t_last_window = time.time()

    def post_pygame_event(self):
        self.stream_data()
        if (time.time() - self.t_last_window) >= emotiv_decoder.WINDOW_SHIFT:
            key = self.decode()
            self.t_last_window = time.time()
            if (key == 1):
                pygame.event.post(
                    pygame.event.Event(pygame.KEYDOWN, {
                        'key': K_UP,
                        'unicode': None
                    }))
            elif (key == 2):
                pygame.event.post(
                    pygame.event.Event(pygame.KEYDOWN, {
                        'key': K_DOWN,
                        'unicode': None
                    }))
            elif (key == 3):
                pygame.event.post(
                    pygame.event.Event(pygame.KEYDOWN, {
                        'key': K_LEFT,
                        'unicode': None
                    }))
            elif (key == 4):
                pygame.event.post(
                    pygame.event.Event(pygame.KEYDOWN, {
                        'key': K_RIGHT,
                        'unicode': None
                    }))

    def get_cache_data(self):
        return (self.cache_data)

    def get_cache_decoder(self):
        return (self.cache_decoder)

    def get_cache_decoder_last(self):
        return (self.cache_decoder[-1])

    def stream_data(self):
        record_sensors = dict()

        for ch in CHANNELS:
            record_sensors[ch] = []
        while (self.emotiv.running):
            try:
                packet = self.emotiv.dequeue()
                if packet is not None:
                    if type(packet) == EmotivPacket:
                        for ch in CHANNELS:
                            record_sensors[ch] = packet.sensors[ch].copy()
            except Exception as ex:
                print("EmotivRender DequeuePlotError ",
                      sys.exc_info()[0],
                      sys.exc_info()[1],
                      sys.exc_info()[2], " : ", ex)
            if self.cache:
                for ch in CHANNELS:
                    if (len(self.cache_data[ch]) >= self.cache_length):
                        self.cache_data[ch].pop(0)
                    if (record_sensors[ch] != []):
                        self.cache_data[ch].append(record_sensors[ch]['value'])
                    else:
                        # Not correctly controlling for shifting series for lost packet
                        self.cache_data[ch].append(self.cache_data[ch][-1])
                if (len(self.t) > self.cache_length):
                    self.t.pop(0)
                self.t.append(time.time())

            return (record_sensors)

    def record_session(self, t, name=None):
        self.establish_connection()
        data = dict()
        for ch in CHANNELS:
            data[ch] = []
        for i in range(t):
            data_point = self.stream_data().copy()
            for ch in CHANNELS:
                if (data_point[ch] != []):
                    data[ch].append(data_point[ch]['value'])
            time.sleep(0.01)

        if (name is not None):
            import pickle
            pickle.dump(data, open(name, 'wb'))
        else:
            return (data)
Esempio n. 23
0
# run forever
try:
    running = True
    while running:

        if guifeature:
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                    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:
Esempio n. 24
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)
Esempio n. 25
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()
Esempio n. 26
0
class Record:
    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 setPlotGraphBySensor(self, sensor):
        self.plots.setVisible(False)
        self.altPlots.setVisible(True)

        if self.electrodePairing[sensor]["order"]:
            self.altPlots.restartSensors( [ sensor, self.electrodePairing[sensor]["pair"]] )
        else:
            self.altPlots.restartSensors([ self.electrodePairing[sensor]["pair"], sensor ])

        self.returnToGraphs.setVisible(True)

    def update(self):
        packet = self.headset.dequeue()
        if packet != None:
            self.plots.updater(packet)
        self.headsetState.updateHeadsetStatus(packet)

        if self.recording:
            row = self.parser.fromPacketToCSV( packet )
            self.output_file.write(row + "\n")

    def setRecordTab(self):
        self.setLeftSidedBox()
        self.setCenterBox()

        # Main grid layout
        self.gridLayout = QGridLayout()
        self.gridLayout.addLayout( self.leftBox, 0, 0)
        self.gridLayout.addLayout( self.centerBox, 0, 1)

        self.gridLayout.setColumnStretch(0, 1)
        self.gridLayout.setColumnStretch(1, 3)

        return self.gridLayout

    def setLeftSidedBox(self):
        # Left sided box for controls
        self.leftBox = QFormLayout()

        self.recordButton = QPushButton("Record")
        self.recordButton.setEnabled(False)
        self.recordButton.clicked.connect(self.startRecord)

        self.stopButton = QPushButton("Stop")
        self.stopButton.setEnabled(False)
        self.stopButton.clicked.connect(self.stopRecord)

        self.recordButtons = QGridLayout()
        self.recordButtons.addWidget( self.recordButton, 0, 0)
        self.recordButtons.addWidget( self.stopButton, 0, 1)
        self.leftBox.addRow(QLabel("Recording controls"))
        self.leftBox.addRow(self.recordButtons)

        self.route = QLineEdit()
        self.route.setReadOnly(True)
        self.examine = QPushButton("Examine")
        self.examine.clicked.connect(self.getFilename)
        folderButtons = QGridLayout()
        folderButtons.addWidget(self.route, 0, 0)
        folderButtons.addWidget(self.examine, 0, 1)
        self.leftBox.addRow(QLabel("Save folder"))
        self.leftBox.addRow(folderButtons)

        # Sensors status
        self.leftBox.addRow(QLabel("Sensor status"))
        self.headsetState = HeadStatusWidget(self.setPlotGraphBySensor)
        self.leftBox.addRow(self.headsetState)
        self.headsetState.updateHeadsetStatus(None)

    def setCenterBox(self):
        # Center sided box for signals
        self.centerBox = QFormLayout()

        self.centerBox.addRow(QLabel("Signal status"))

        self.returnToGraphs = QPushButton("Return")
        self.returnToGraphs.setVisible(False)
        self.returnToGraphs.clicked.connect(self.returnToGraphics)
        self.centerBox.addRow(self.returnToGraphs)

        self.plots = PlottingWidget()
        self.centerBox.addRow(self.plots)

        self.altPlots = PlottingWidget([])
        self.centerBox.addRow(self.altPlots)
        self.altPlots.setVisible(False)

    def returnToGraphics(self):
        self.altPlots.setVisible(False)
        self.returnToGraphs.setVisible(False)
        self.plots.setVisible(True)

    def getFilename(self):
        filename = QFileDialog.getExistingDirectory(self.examine, "Open Directory",
                                         "/home",
                                         QFileDialog.ShowDirsOnly
                                         | QFileDialog.DontResolveSymlinks);
        self.fileRoute = filename
        self.route.setText(self.fileRoute)

        self.recordButton.setEnabled(True)

    def startRecord(self):
        self.stopButton.setEnabled(True)
        self.recordButton.setEnabled(False)

        self.recording = True
        self.file_name += datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H-%M-%S') + ".csv"
        self.output_file = open(self.file_name, 'w')
        self.output_file.write(self.header_text + "\n")

    def stopRecord(self):
        self.output_file.close()
Esempio n. 27
0
# run forever
try:
    running = True
    while running:

        if guifeature:
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                    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:
Esempio n. 28
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)
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())
Esempio n. 30
0
class EmoGetter(DataGetter):
    _values = []
    _fs = 20
    """Gets data from Emotiv"""
    def __init__(self):
        super(EmoGetter, self).__init__()

        self.headset = Emotiv()

        gevent.spawn(self.headset.setup)
        gevent.sleep(0)

        self.running = True

    def get_all_data(self):
        return _values

    def get_next_data(self):
        packet = self.headset.dequeue()
        if packet is None:
            self.running = False
            return []

        sensors = packet.sensors

        vect_2 = (packet.gyro_y**2 + packet.gyro_x**2)
        is_bad = vect_2 > 2

        values = []

        #if sum(self.gyro_hist[-self.n_usless:]) / len(self.gyro_hist[-self.n_usless:]) - vect_2 > self.n_change:
        #	is_bad = True

        for data_name in DATA_NAMES:
            val = sensors[data_name]['value']
            values.append(val)

        gevent.sleep(0)

        self._values.append(values)

        return (values, False)

    def getN(self, n):
        T = 1 / self._fs

        datas = []

        for i in range(n):
            a = time.time()

            v, g = self.get_next_data()
            datas.append(v)

            b = time.time()
            delta = b - a

            if delta < T:
                time.sleep(T - delta)

        return datas
Esempio n. 31
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)