Beispiel #1
0
 def __init__(self, out_queue):
     Thread.__init__(self)
     self.out_queue = out_queue
     self.headset = mindwave.Headset('/dev/tty.MindWave', 'C61A')
     self.headset.connect()
     self._stop = False
     time.sleep(2)
Beispiel #2
0
def main():
    headset = mindwave.Headset('/dev/rfcomm0')
    time.sleep(2)
    headset.connect()
    
    while True:
        # poor_signal, attention, meditation, blink, raw_value, status
        attention = headset.attention
        print "Attention: ", attention
def bacadata():
	headset = mindwave.Headset('COM4', '1425')
	time.sleep(1)

	headset.connect()
	print "Connecting..."

	headset.status != 'connected':
	time.sleep(1)
		headset.status == 'standby':
		headset.connect()
		print "Retrying connect..."
 def __init__(self, foldername):
     self.foldername = foldername
     time.sleep(2)
     #pygame.init()
     self.headset = mindwave.Headset('/dev/ttyUSB0','ee69')
     #pygame.display.set_mode((100,100))
     self.headset.connect()
     print "Connecting..."
     
     while self.headset.status != 'connected':
         time.sleep(0.5)
         if self.headset.status == 'standby':
             self.headset.connect()
         print "Retrying connect..."
     print "Connected."
Beispiel #5
0
def bacadataloop():
	headset = mindwave.Headset('COM4', '1425')
	time.sleep(1)

	headset.connect()
	print "Connecting..."

	while headset.status != 'connected':
		time.sleep(1)
		if headset.status == 'standby':
			headset.connect()
			print "Retrying connect..."
	print "Connected."

	while True:
		print headset.raw_value
		time.sleep(1)
Beispiel #6
0
def recordRaw():
    headset = mindwave.Headset('/dev/tty.MindWaveMobile-SerialPo', '625f')
    time.sleep(initial_sleep)
    dateTimeString = datetime.now().strftime("%m_%d_%Y__%H_%M_%S")
    headset.connect()
    signal = []
    start_time = time.time()
    while True:
        v = headset.raw_value
        time.sleep(0.001)
        print(v, headset.poor_signal, headset.blink)
        signal.append(v)
        if time.time() > start_time + 30:
            break

    f = open('signal' + dateTimeString + '.txt', 'w')
    f.write(str(signal))
    f.write("start time:" + str(start_time))
    f.close()
Beispiel #7
0
  def monitor(self):
    if self.running:
      if self.h:
        self.h.serial_close()
      self.running = False
    else:
      self.running = True
      self.h = None
      import serial
      try:
        device = self.deviceComboBox.currentText()
        self.h = mindwave.Headset("{0}".format(device))
      except serial.serialutil.SerialException, e:
        print "{0}".format(e)
        QtGui.QMessageBox.information(self.MainWindow, 'Couldn\'t find the headset', 'Headset not found. Did you pair and connect to serial device {0}?'.format(device), QtGui.QMessageBox.Ok)

      if self.h:
        self.h.raw_wave_handlers.append(self.raw_wave_handler)
      else:
        self.running = False
    def run(self):
        print("Connecting")
        headset = mindwave.Headset('/dev/tty.MindWaveMobile-SerialPo')
        time.sleep(2)
        print("Connected!")

        try:
            while (headset.poor_signal > 5):
                print(
                    "Headset signal noisy %d. Adjust the headset and the earclip."
                    % (headset.poor_signal))
                time.sleep(0.1)

            print("Writing output to LSL stream")
            stime = time.time()
            prevTime = 0
            while True:
                cycle_start_time = time.time()
                if headset.poor_signal > 5:
                    print(
                        "Headset signal noisy %d. Adjust the headset and the earclip."
                        % (headset.poor_signal))
                    self.__eeg_outlet.push_sample(np.array([0, 0, 0, 0]))
                else:
                    self.__eeg_outlet.push_sample(
                        np.array([
                            headset.raw_value, headset.attention,
                            headset.meditation, headset.blink
                        ]))

                timeDiff = int(time.time() - stime)
                if (timeDiff != prevTime):
                    print("seconds elapsed: " + str(timeDiff))
                    prevTime = timeDiff

                time.sleep((1 / (self.__Fs)) -
                           (time.time() - cycle_start_time + 0.0005))

        finally:
            print("Closing!")
            headset.stop()
Beispiel #9
0
def MainThread():
    while True:

        def on_raw(headset, raw):
            queue.put(raw)
            #print queue.get()
            data = []
            data.append(raw)
            path = "relaxy.csv"
            printraw(data, path)

        def printraw(data, path):
            with open(path, 'a') as f:
                writer = csv.writer(f)
                for i in data:
                    writer.writerow(data)

        headset = mindwave.Headset('/dev/ttyUSB0')
        time.sleep(1)

        headset.connect()
        print("Connecting")

        while headset.status != 'connected':
            time.sleep(0.5)
            if headset.status == 'standby':
                headset.connect()
                print("Retrying")
        try:
            print("connected")

            headset.raw_value_handlers.append(on_raw)
            time.sleep(1200)
            headset.disconnect()
        except KeyboardInterrupt:
            headset.disconnect()
        except:
            headset.disconnect()
            print("Unknown Error")
            raise
Beispiel #10
0
    def monitor(self):
        """
    start/stop button pressed
    """
        print "monitor"
        if self.running:
            self.connected = "Not connected"
            self.signal_quality = "unknown signal quality"
            for i, mo in enumerate(self.midiOut):
                bytemsg = self.notequeue.clear_notes(i)
                for msg in bytemsg:
                    self.midiOut[i].send_message(msg)
            if self.h:
                self.h.serial_close()
            self.running = False
        else:
            self.connected = "Connected"
            self.signal_quality = "unknown signal quality"
            self.running = True
            self.h = None
            import serial
            try:
                device = self.deviceComboBox.currentText()
                self.h = mindwave.Headset("{0}".format(device))
            except serial.serialutil.SerialException, e:
                print "{0}".format(e)
                QtGui.QMessageBox.information(
                    self.MainWindow, 'Couldn\'t find the headset',
                    'Headset not found. Did you pair and connect to serial device {0}?'
                    .format(device), QtGui.QMessageBox.Ok)

            if self.h:
                self.h.raw_wave_handlers.append(self.raw_wave_handler)
                self.h.meditation_handlers.append(self.handle_meditation_event)
                self.h.attention_handlers.append(self.handle_attention_event)
                self.h.poor_signal_handlers.append(self.handle_poor_signal)
                self.h.good_signal_handlers.append(self.handle_good_signal)
            else:
                self.running = False
Beispiel #11
0
def graphAnalysis():
    """This function is used to both receive and depict the data into a graph."""
    then = time.time()
    now = time.time()

    plt.axis([-2000, 2000, 0, 50])
    plt.ion()

    # Connect the path and the mindwave's serial number
    neuroSet = mindwave.Headset('COM5', 'CC0E')
    time.sleep(2)

    # Connect the mindwave
    neuroSet.connect()
    print("Currently Pairing Your Headset.")

    while mindwave.status != "Paired!":
        time.sleep(2)
        if mindwave.status == "Standing by.":
            mindwave.connect()
            print("Retrying.")

    print("Paired!")

    # Put data into graph format using matplotlib
    x = True
    while x == True:
        # time.sleep(.5)
        print("Attention: %s" % (neuroSet.attention))
        now = time.time()
        duration = now - then
        duration_sec = duration % 60
        x = str(neuroSet.attention)
        y = str(duration_sec)
        plt.plot(x, y)
        plt.pause(1)

    while True:
        plt.pause(1)
Beispiel #12
0
def train(mode):
    if mode == "raw":
        # Connect headset
        headset = mindwave.Headset('/dev/rfcomm0')
        time.sleep(2)
        headset.connect()
    else:
        manus = Manus()

    X = np.zeros((TRAIN_SAMPLE, HISTORY))
    Y = np.zeros(TRAIN_SAMPLE)
    print "Acquiring True condition..."
    for i in range(TRAIN_SAMPLE / 2):
        for k in range(HISTORY):
            if mode == "raw":
                X[i, k] = headset.attention
            else:
                X[i, k] = manus.simulate()
        if i % 10 == 0:
            print i
    Y[:TRAIN_SAMPLE / 2 - 1] = 1

    print "Acquiring False condition..."
    for i in range(TRAIN_SAMPLE / 2):
        for k in range(HISTORY):
            if mode == "raw":
                X[i + TRAIN_SAMPLE / 2, k] = headset.attention
            else:
                X[i + TRAIN_SAMPLE / 2, k] = manus.simulate()
        if i % 10 == 0:
            print i
    Y[TRAIN_SAMPLE / 2:] = 0

    print "Start training."
    lin_clf = LinearSVC()
    lin_clf.fit(X, Y)
    print "Training finished."
    pickle.dump(lin_clf, open(MODEL_FILENAME, 'wb'))
Beispiel #13
0
    def headsetConnect(self, donglePortName):
        try:
            if not self.headset or not self.headset.is_open():
                self.headset = mindwave.Headset(donglePortName, config.MINDSET_ID)

                self.headset.attention_handlers.append(self.getAttentionHandler)

            logger.info('Connect to the Mindwave headset')
            if self.headset.status != 'connected':
                if self.headset.status == 'standby':
                    self.headsetStatus = Statuses.DISCONNECTED

                if self.headsetStatus != Statuses.CONNECTING:
                    self.headsetStatus = Statuses.CONNECTING
                    self.headset.connect(config.MINDSET_ID)
            else:
                logger.info('Mindwave headset connected')
                self.headsetStatus = Statuses.CONNECTED
        except Exception as err:
            logger.error(err)
            self.headset.disconnect()
            self.headsetStatus = Statuses.DISCONNECTED
            pass
        return
import time
import mindwave, time
import pyqtgraph as pg
import numpy as np
import mindwave, time
then = time.time()

headset = mindwave.Headset('COM10', 'CC0E')
time.sleep(2)

headset.connect()
print "Connecting..."

while headset.status != 'connected':
    time.sleep(0.5)
    if headset.status == 'standby':
        headset.connect()
        print "Retrying connect..."
print "Connected."



x = np.arange(100)
y = np.arange(100)
x[0] = 0.0000
y[0] = 0.0000

pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pw = pg.plot()
while True:
Beispiel #15
0
import mindwave, time

headset = mindwave.Headset('COM4', '1425')
time.sleep(1)

headset.connect()
print "Connecting..."

while headset.status != 'connected':
    time.sleep(1)
    if headset.status == 'standby':
        headset.connect()
        print "Retrying connect..."
print "Connected."

while True:
    print headset.raw_value
    time.sleep(1)

def on_raw(headset, raw):
    if headset.poor_signal == 0:
        if raw > 400 and headset.listener.initial == 0:
            headset.listener.initial = mindwave.datetime.datetime.now()
        elif raw < -90 and headset.listener.timer(
        ) > 20 and headset.listener.timer() < 300:
            on_blink(headset)
            headset.listener.initial = 0
        elif headset.listener.timer() > 500:
            headset.listener.initial = 0


if __name__ == '__main__':
    headset = mindwave.Headset('/dev/ttyUSB0')
    time.sleep(2)

    headset.connect()
    print "Connecting"

    while headset.status != 'connected':
        time.sleep(0.5)
        if headset.status == 'standby':
            headset.connect()
            print "Retrying"
    try:
        print "connected"
        headset.blink_handlers.append(on_blink)
        headset.raw_value_handlers.append(on_raw)
        headset.raw_value_handlers.append(send_poor)
Beispiel #17
0
def main():
    num_lights = None
    if len(sys.argv) != 2:
        print(
            "\nDiscovery will go much faster if you provide the number of lights on your LAN:"
        )
        print("  python {} <number of lights on LAN>\n".format(sys.argv[0]))
    else:
        num_lights = int(sys.argv[1])

    # instantiate LifxLAN client, num_lights may be None (unknown).
    # In fact, you don't need to provide LifxLAN with the number of bulbs at all.
    # lifx = LifxLAN() works just as well. Knowing the number of bulbs in advance
    # simply makes initial bulb discovery faster.
    lifx = LifxLAN(num_lights)

    # test power control
    print("Discovering lights...")
    original_powers = lifx.get_power_all_lights()
    original_colors = lifx.get_color_all_lights()

    half_period_ms = 2500
    duration_mins = 20
    duration_secs = duration_mins * 60
    print("Breathing...")

    #inititalize lcd display
    lcd_init()
    #GPIO.setup(23,GPIO.OUT)
    #GPIO.setup(12,GPIO.OUT)
    #GPIO.output(12,GPIO.HIGH)
    #GPIO.output(23,GPIO.HIGH)

    GPIO.setup(17, GPIO.OUT)
    #connect headset to Rpi
    headset = mindwave.Headset('/dev/ttyUSB0', 'DB00')
    time.sleep(2)

    headset.connect()
    print "Connecting..."

    while headset.status != 'connected':
        time.sleep(0.5)
        if headset.status == 'standby':
            headset.connect()
            print "Retrying connect..."
    print "Connected."
    time.sleep(1)
    # dims bulb completely at beginning
    # brightness in range [0 - 65535]
    # set_color is [Hue, Saturation, Brightness, Kelvin], duration in ms
    for bulb in original_colors:
        color = original_colors[bulb]
        dim = list(copy(color))
        dim[2] = 65000
        dim[0] = 62000
        #print "changing bulb to %s" % dim[2]
        bulb.set_color(dim, half_period_ms, rapid=True)
    lightswitch = False
    previous = []

    #no idea what this is for lol
    # p = False

    prevAvg = 0
    count = 0
    while True:
        #This is for meditation
        time.sleep(1)
        #Take user input for number of readings per output
        avgSize = 4
        while True:
            question = "Average Size: " + str(avgSize)
            print question
            text = raw_input("Average Size = ")
            if text == "end":
                break
            avgSize = int(text)

        time.sleep(1)
        while True:
            if count < avgSize - 1:
                count += 1
                previous.append(headset.meditation)
                #for x in range(len(previous)):
                #   print previous[x]
            else:
                #p = False
                previous.append(headset.meditation)
                #for x in range(len(previous)):
                #    print previous[x]
                k = 0
                sum = 0
                while k < avgSize:
                    sum += previous[k]
                    k += 1
                Avg = sum / len(previous)
                #print original_colors
                # max brightness of bulb goes from 0 to 65535 based on reverse of Avg. So closer to max meditation means dimmer bulb.
                # brightness in range [0 - 65535]
                # set_color is [Hue, Saturation, Brightness, Kelvin], duration in ms
                for bulb in original_colors:
                    color = original_colors[bulb]
                    dim = list(copy(color))
                    #dim[2] = 655*(100-Avg)
                    dim[0] = 62000 - 200 * Avg
                    #bulb.set_color(dim, 0, rapid=True)
                    #print "changing bulb to %s" % dim[2]
                    bulb.set_color(dim, half_period_ms, rapid=True)
                #time.sleep(half_period_ms/1000.0)
                previous = []
                count = 0
                print "Meditation: %s changing bulb to %s" % (Avg, dim[0])
                #switch light state if avg is more than 50 and prev is less than 50
                if Avg >= 50 and prevAvg < 50:
                    if lightswitch == False:
                        GPIO.output(17, GPIO.HIGH)
                        lightswitch = True
                    else:
                        GPIO.output(17, GPIO.LOW)
                        lightswitch = False
                prevAvg = Avg
            time.sleep(1)
Beispiel #18
0
import mindwave, time
from pprint import pprint

headset = mindwave.Headset('/dev/ttyUSB0', '1F5D')
time.sleep(2)

headset.connect()
print "Connecting..."

while headset.status != 'connected':
    time.sleep(0.5)
    if headset.status == 'standby':
        headset.connect()
        print "Retrying connect..."
print "Connected."

while True:
    time.sleep(.5)
    print "Raw value: %s, Attention: %s, Meditation: %s" % (
        headset.raw_value, headset.attention, headset.meditation)
    pprint(headset.waves)
Beispiel #19
0
import threading
import mindwave
import cv2
import time
import os
LOW_THRESHOLD_OPENCV = 2
# Anything 2 and under is considered not paying attention
LOW_THRESHOLD_MINDWAVE = 75
# Anything below 75 is considered not paying attention
STRICT_MODE = False
# False is basically (LOW_THRESHOLD_OPENCV OR LOW_THRESHOLD_MINDWAVE) and True is (LOW_THRESHOLD_OPENCV AND LOW_THRESHOLD_MINDWAVE)
try:
	headset = mindwave.Headset("/dev/rfcomm0")
	headset.connect()
except:
	pass
eye_detect_list = []

def get_rolling_average():
	print eye_detect_list
	if len(eye_detect_list) < 10:
		for i in range(10-len(eye_detect_list)):
			print("Inserting data for rolling average...")
			eye_detect_list.insert(0,3)
	return sum(eye_detect_list) / float(len(eye_detect_list))

def get_headset_attention():
	try:
		val = headset.attention
	except:
		val = 0
def main():
    num_lights = None
    if len(sys.argv) != 2:
        print("\nDiscovery will go much faster if you provide the number of lights on your LAN:")
        print("  python {} <number of lights on LAN>\n".format(sys.argv[0]))
    else:
        num_lights = int(sys.argv[1])

    # instantiate LifxLAN client, num_lights may be None (unknown).
    # In fact, you don't need to provide LifxLAN with the number of bulbs at all.
    # lifx = LifxLAN() works just as well. Knowing the number of bulbs in advance
    # simply makes initial bulb discovery faster.
    lifx = LifxLAN(num_lights)

    # test power control
    print("Discovering lights...")
    original_powers = lifx.get_power_all_lights()
    original_colors = lifx.get_color_all_lights()

    half_period_ms = 2500
    duration_mins = 20
    duration_secs = duration_mins*60
    print("Breathing...")
    
    #inititalize lcd display
    lcd_init()
    #GPIO.setup(23,GPIO.OUT)
    #GPIO.setup(12,GPIO.OUT)
    #GPIO.output(12,GPIO.HIGH)
    #GPIO.output(23,GPIO.HIGH)


    GPIO.setup(17,GPIO.OUT)
    #connect headset to Rpi
    headset = mindwave.Headset('/dev/ttyUSB0', 'DB00')
    time.sleep(2)

    headset.connect()
    print "Connecting..."

    while headset.status != 'connected':
        time.sleep(0.5)
        if headset.status == 'standby':
            headset.connect()
            print "Retrying connect..."
    print "Connected."
    time.sleep(1)
    # dims bulb completely at beginning
    # brightness in range [0 - 65535]
    # set_color is [Hue, Saturation, Brightness, Kelvin], duration in ms
    for bulb in original_colors:
        color = original_colors[bulb]
        dim = list(copy(color))
        dim[2] = 65000
        dim[0]=62000
        #print "changing bulb to %s" % dim[2]
        bulb.set_color(dim, half_period_ms, rapid=True)    
    previous = 0   
    #selecting options from menu  
    arr = ['Attention', 'Meditation', 'Blink']
    i = 0
    j = 1
    lcd_byte(LCD_LINE_1, LCD_CMD)
    lcd_string('Select option',2)
    lcd_byte(LCD_LINE_2, LCD_CMD)
    lcd_string('Press any Button' ,2)
    while GPIO.input(14)==GPIO.LOW and GPIO.input(15)==GPIO.LOW:
        pass
    time.sleep(1)
    lcd_byte(LCD_LINE_1, LCD_CMD)
    lcd_string("-->" + arr[i],2)
    lcd_byte(LCD_LINE_2, LCD_CMD)
    lcd_string(arr[j],2)
    while True:
        #print "Attention: %s, Meditation: %s, previous: %s" % (headset.attention, headset.meditation,previous)
        #scroll through options on the menu
        if GPIO.input(15)== GPIO.HIGH:
            print('Scrolling--------')
            
            i = (i+1)%3
            j = (j+1)%3
            lcd_byte(LCD_LINE_1, LCD_CMD)
            lcd_string("-->" + arr[i],2)
            lcd_byte(LCD_LINE_2, LCD_CMD)
            lcd_string(arr[j],2)
            while GPIO.input(15)== GPIO.HIGH:
                pass
    ##      lcd.GPIO.cleanup()
        #select option
        if GPIO.input(14)== GPIO.HIGH:
            
            selected = arr[i]
            print ("Selected " + selected)
            lightswitch = False
            previous = []
            p = False
            prevAvg=0
            count = 0
            #if attention is selected
            if i==0:
                time.sleep(1)
                lcd_byte(LCD_LINE_2, LCD_CMD)
                lcd_string("Type end to Cont",2)
                #Take user input for number of readings per output
                avgSize =4
                while True:
                    lcd_byte(LCD_LINE_1, LCD_CMD)
                    question = "Average Size: "+str(avgSize)
                    lcd_string(question,2)
                    text = raw_input("Average Size = ")
                    if text == "end":
                        break
                    avgSize = int(text)
                    
                    
                    

                lcd_byte(LCD_LINE_1, LCD_CMD)
                lcd_string("Sel. Attention ",2)
                time.sleep(1)
                while True:                    
                    if GPIO.input(14)==GPIO.HIGH:
                        break
                    if count < avgSize-1:
                        count+=1
                        previous.append(headset.attention)
                        #for x in range(len(previous)): 
                         #   print previous[x]
                    else:
                        #p = False
                        previous.append(headset.attention)
                        #for x in range(len(previous)): 
                        #    print previous[x]
                        k = 0
                        sum = 0
                        while k < avgSize:
                            sum += previous[k]
                            k+=1
                        Avg = sum/len(previous)
                        previous = []
                        count = 0
                        print "Attention: %s" % Avg
                        #switch light state if avg is more than 50 and prev is less than 50
                        if Avg >= 50 and prevAvg < 50:
                            if lightswitch == False :
                                GPIO.output(17,GPIO.HIGH)
                                lightswitch = True
                            else:
                                GPIO.output(17,GPIO.LOW)
                                lightswitch = False
                        prevAvg = Avg
                        lcd_byte(LCD_LINE_2, LCD_CMD)
                        lcd_string(str(Avg),2)                      
                    time.sleep(1)
            #if meditation is selected
            if i ==1:
                time.sleep(1)                
                lcd_byte(LCD_LINE_2, LCD_CMD)
                lcd_string("Type end to Cont",2)
                #Take user input for number of readings per output
                avgSize =4
                while True:
                    lcd_byte(LCD_LINE_1, LCD_CMD)
                    question = "Average Size: "+str(avgSize)
                    lcd_string(question,2)
                    text = raw_input("Average Size = ")
                    if text == "end":
                        break
                    avgSize = int(text)

                lcd_byte(LCD_LINE_1, LCD_CMD)
                lcd_string("Sel. Meditation ",2)
                time.sleep(1)
                while True:                    
                    if GPIO.input(14)==GPIO.HIGH:
                        break
                    if count < avgSize-1:
                        count+=1
                        previous.append(headset.meditation)
                        #for x in range(len(previous)): 
                         #   print previous[x]
                    else:
                        #p = False
                        previous.append(headset.meditation)
                        #for x in range(len(previous)): 
                        #    print previous[x]
                        k = 0
                        sum = 0
                        while k < avgSize:
                            sum += previous[k]
                            k+=1
                        Avg = sum/len(previous)
                        #print original_colors
                        # max brightness of bulb goes from 0 to 65535 based on reverse of Avg. So closer to max meditation means dimmer bulb.
                        # brightness in range [0 - 65535]
                        # set_color is [Hue, Saturation, Brightness, Kelvin], duration in ms
                        for bulb in original_colors:
                            color = original_colors[bulb]
                            dim = list(copy(color))
                            #dim[2] = 655*(100-Avg)
                            dim[0] = 62000-200*Avg
                            #bulb.set_color(dim, 0, rapid=True)
                            #print "changing bulb to %s" % dim[2]
                            bulb.set_color(dim, half_period_ms, rapid=True)
                        #time.sleep(half_period_ms/1000.0)
                        previous = []
                        count = 0
                        print "Meditation: %s changing bulb to %s" % (Avg,dim[0])
                        #switch light state if avg is more than 50 and prev is less than 50
                        if Avg >= 50 and prevAvg < 50:
                            if lightswitch == False :
                                GPIO.output(17,GPIO.HIGH)
                                lightswitch = True
                            else:
                                GPIO.output(17,GPIO.LOW)
                                lightswitch = False
                        prevAvg = Avg
                        lcd_byte(LCD_LINE_2, LCD_CMD)
                        lcd_string(str(Avg),2)                      
                    time.sleep(1)
            #if blink is selected
            #blink doesnt work yet
            if i == 2:
                print('WORK IN PROGRESS')
            lcd_byte(LCD_LINE_1, LCD_CMD)
            lcd_string("-->" + arr[i],2)
            lcd_byte(LCD_LINE_2, LCD_CMD)
            lcd_string(arr[j],2)
            GPIO.output(17,GPIO.LOW)
            while GPIO.input(14)== GPIO.HIGH:
                pass
        plt.pause(0.0001)

        self.plcounter = self.plcounter + 1

        if self.plcounter > self.rangeval:
            self.plcounter = 0
            self.plotx[:] = []
            self.x[:] = []
            self.y[:] = []
            self.z[:] = []


import mindwave, time

# Hardcoded serial number of my Mindwave device.
headset = mindwave.Headset()

time.sleep(2)

plotter = Plotter(500, -500, 500)

attention = 0
meditation = 0
eeg = 0

# def on_raw( headset, rawvalue):
#     time.sleep(.01)
#     print "Count %d :Raw value: %s, Attention: %s, Meditation: %s" % (headset.count, headset.raw_value, headset.attention, headset.meditation)
#     (eeg, attention, meditation) = (headset.raw_value, headset.count, headset.meditation)
#     plotter.plotdata( [eeg, attention, meditation])
#
Beispiel #22
0
import mindwave
import time
import matplotlib.pyplot as plt

headset = mindwave.Headset('/dev/tty.MindWaveMobile-SerialPo', '625f')
time.sleep(2)

headset.connect()
signal = []

start_time = time.time()
while True:
    v = headset.raw_value
    time.sleep(0.001)
    print(v)
    signal.append(v)
    if time.time() > start_time + 30:
        break

plt.plot(signal)
plt.show()
f = open('signal.txt', 'w')
f.write(str(signal))
f.close()
Beispiel #23
0
            med_array.append(headset.meditation)
            att_array.append(headset.attention)
    med = np.mean(med_array)
    att = np.mean(att_array)
    mood = (att - med) / 200.0 + 0.50
    return mood


if __name__ == '__main__':
    global sp
    global user_config
    global med
    global att
    global mood
    global headset
    headset = mindwave.Headset(port + sys.argv[1], '625f')
    headset.autoconnect()
    headset.connect()
    med = 0
    att = 0
    mood = 0.5
    mood_old = 0
    load_config()
    token = util.prompt_for_user_token(
        user_config['username'],
        scope=
        'user-follow-read,user-top-read,user-modify-playback-state,user-read-playback-state,streaming,app-remote-control,playlist-modify-private,playlist-modify-public',
        client_id=user_config['client_id'],
        client_secret=user_config['client_secret'],
        redirect_uri=user_config['redirect_uri'])
    spotify_auth = spotipy.Spotify(auth=token)
Beispiel #24
0
import mindwave
import time

headset = mindwave.Headset('/dev/tty.MindWave','625f')
time.sleep(2)
headset.autoconnect()

#headset.connect()
print "Connecting.."

while (headset.status) != 'connected':
    print headset.status
    time.sleep(0.5)
    if headset.status == 'standby':
        headset.autoconnect()
        print "Retrying connect..."

print "Connected."

while True:
    print "Attention: %s, Meditation: %s" % (headset.attention, headset.meditation)
    time.sleep(2)
Beispiel #25
0
import mindwave, time
import os

port = "/dev/null"
mid = "1425"
rate = 0.001953125
namafile = "hasilnya.csv"
runfile = "run"

open(runfile, 'a').close()

headset = mindwave.Headset(port, mid)

headset.connect()
print("Connecting")

while headset.status != "connected":
    time.sleep(0.5)
    if headset.status == "standby":
        headset.connect()
        print("Retrying connect...")
print("Connected.")

f = open(namafile, 'a+')

while True:
    if os.path.exists(runfile) != True:
        f.close()
        break
    try:
        while True:
Beispiel #26
0
import mindwave, time

#headset = mindwave.Headset('/dev/tty.MindWaveMobile-DevA','ef47')
headset = mindwave.Headset('COM4')
time.sleep(2)

while True:
    time.sleep(.5)
    print ("Raw value: %s, Attention: %s, Meditation: %s" % (headset.raw_value, headset.attention, headset.meditation))
    
Beispiel #27
0
    currentTimestamp = None
    currentRawValue = None
    currentAttention = None

    trial_index = 0  # the first trial in the permutation

    data = {'timestamp': [], 'raw_value': [], 'attention': []}
    sampled_data = {
        'timestamp': [],
        'raw_value': [],
        'attention': [],
        'label': []
    }

    print("Connecting...")
    headset = mindwave.Headset(
        '/dev/tty.MindWaveMobile-SerialPo')  # mac version
    print("Connected!")

    try:
        while (headset.poor_signal > 5):
            print(
                "Headset signal noisy %d. Adjust the headset and the earclip."
                % (headset.poor_signal))
            time.sleep(0.1)

        print("Writing %d seconds output to %s" % (secondsToSample, filename))
        stime = time.time()
        trial_stime = time.time()
        headset.raw_value_handlers.append(on_raw)
        prevTime = 0
        while ((time.time() - stime) < secondsToSample):
Beispiel #28
0
def main():
    lcd_init()
    GPIO.setup(17,GPIO.OUT)
    headset = mindwave.Headset('/dev/ttyUSB0', 'DB00')
    time.sleep(2)

    headset.connect()
    print "Connecting..."

    while headset.status != 'connected':
        time.sleep(0.5)
        if headset.status == 'standby':
            headset.connect()
            print "Retrying connect..."
    print "Connected."
    time.sleep(1)
        
    previous = 0   
      
    arr = ['Attention', 'Meditation', 'Blink']
    i = 0
    j = 1
    lcd_byte(LCD_LINE_1, LCD_CMD)
    lcd_string('Select option',2)
    lcd_byte(LCD_LINE_2, LCD_CMD)
    lcd_string('Press any Button' ,2)
    while GPIO.input(14)==GPIO.LOW and GPIO.input(15)==GPIO.LOW:
        pass
    time.sleep(1)
    lcd_byte(LCD_LINE_1, LCD_CMD)
    lcd_string("-->" + arr[i],2)
    lcd_byte(LCD_LINE_2, LCD_CMD)
    lcd_string(arr[j],2)
    while True:
        #print "Attention: %s, Meditation: %s, previous: %s" % (headset.attention, headset.meditation,previous)
        if GPIO.input(15)== GPIO.HIGH:
            print('Scrolling--------')
            
            i = (i+1)%3
            j = (j+1)%3
            lcd_byte(LCD_LINE_1, LCD_CMD)
            lcd_string("-->" + arr[i],2)
            lcd_byte(LCD_LINE_2, LCD_CMD)
            lcd_string(arr[j],2)
            while GPIO.input(15)== GPIO.HIGH:
                pass
    ##      lcd.GPIO.cleanup()
              
        if GPIO.input(14)== GPIO.HIGH:
            
            selected = arr[i]
            print ("Selected " + selected)
            lightswitch = False
            previous = 0
            p = False
            prevAvg=0
            if i==0:
                lcd_byte(LCD_LINE_1, LCD_CMD)
                lcd_string("Sel. Attention ",2)
                time.sleep(1)
                while True:                    
                    if GPIO.input(14)==GPIO.HIGH:
                        break
                    if p == False:
                        p = True
                        previous = headset.attention
                    else:
                        p = False
                        Avg = (headset.attention+previous)/2
                        print "Attention: %s" % Avg
                        if Avg >= 50 and prevAvg < 50:
                            if lightswitch == False :
                                GPIO.output(17,GPIO.HIGH)
                                lightswitch = True
                            else:
                                GPIO.output(17,GPIO.LOW)
                                lightswitch = False
                        prevAvg = Avg
                        lcd_byte(LCD_LINE_2, LCD_CMD)
                        lcd_string(str(Avg),2)                      
                    time.sleep(1)
            if i ==1:
                lcd_byte(LCD_LINE_1, LCD_CMD)
                lcd_string("Sel. Meditation",2)
                time.sleep(1)
                while True:                    
                    if GPIO.input(14)==GPIO.HIGH:
                        break
                    if p == False:
                        p = True
                        previous = headset.attention
                    else:
                        p = False
                        Avg = (headset.attention+previous)/2
                        print "Meditation: %s" % Avg
                        if Avg >= 50 and prevAvg < 50:
                            if lightswitch == False :
                                GPIO.output(17,GPIO.HIGH)
                                lightswitch = True
                            else:
                                GPIO.output(17,GPIO.LOW)
                                lightswitch = False
                        prevAvg = Avg
                        lcd_byte(LCD_LINE_2, LCD_CMD)
                        lcd_string(str(Avg),2)                      
                    time.sleep(1)    
            if i == 2:
                print('WORK IN PROGRESS')
            lcd_byte(LCD_LINE_1, LCD_CMD)
            lcd_string("-->" + arr[i],2)
            lcd_byte(LCD_LINE_2, LCD_CMD)
            lcd_string(arr[j],2)
            GPIO.output(17,GPIO.LOW)
            while GPIO.input(14)== GPIO.HIGH:
                pass
Beispiel #29
0
#!/usr/bin/python
import mindwave
import time
import datetime

#create a tsv file_name of YMD of today's date
time_stamp = time.time()
file_name = datetime.datetime.fromtimestamp(time_stamp).strftime(
    '%Y-%m-%d') + '.tsv'
f = open(file_name, 'a')

#connect the mindwave
headset = mindwave.Headset('/dev/tty.MindWaveMobile-DevA', '771C')
headset.disconnect()  #clear any previous activity
headset.connect()

while 1:
    #getting the data
    meditation_data = headset.meditation
    attention_data = headset.attention

    #printing data to screen
    print("attention average :   {0}".format(meditation_data))
    print("meditation average:   {0}\r\n".format(attention_data))

    #create raw and formatted timestamp
    time_stamp = time.time()
    date_stamp = datetime.datetime.fromtimestamp(time_stamp).strftime(
        '%Y-%m-%d %H:%M:%S')

    #writing data and timestamp to tab-separated-value file
import mindwave, time

headset = mindwave.Headset('/dev/ttyUSB3', '1E5F')
time.sleep(2)

headset.connect()
print "Connecting..."

while headset.status != 'connected':
    time.sleep(0.5)
    if headset.status == 'standby':
        headset.connect()
        print "Retrying connect..."
print "Connected."

while True:
    time.sleep(.5)
    print "Attention: %s, Meditation: %s" % (headset.attention,
                                             headset.meditation)