Ejemplo n.º 1
0
def mindWave(duration):
	mind = NeuroPy("/dev/tty.MindWaveMobile-DevA", 57600)
	mind.start()
	cur_time = time()
	while time() < cur_time + duration:
		cur.execute("INSERT INTO Waves VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (time(), mind.delta, mind.theta, mind.lowAlpha, mind.highAlpha, mind.lowBeta, mind.highBeta, mind.lowGamma, mind.midGamma, mind.attention, mind.meditation))
		sleep(0.5)
Ejemplo n.º 2
0
def startBCI():
    object1=NeuroPy("COM6") 
    #set call back:
    object1.setCallBack("attention",attention_callback)
    
    #start method
    object1.start()
    return None
Ejemplo n.º 3
0
def main():
    neuropy = NeuroPy("/dev/rfcomm0") #instantiate NeuroPy class

    neuropy.start() #start thread
    start_time = 0 
    blinked = False #if blink is detected
    last_blink_time = 0
    double_blink = False
    triple_blink = False
    i = 100
    j = 100

    try:
        while i < 20000:
            i = i + 1 
            value = neuropy.rawValue #gets the raw brain activity level
            print value, "   ", i 
            
            if value > 100: #if the raw level gets above 200, which indicates a spike, start the clock
                start_time = time.clock()
                #print value
            if start_time:
                if value <  -100: #if the spike in brain activity is over
                    total_time = time.clock() - start_time #how long the spike was
                    start_time = 0
                    if 0.01 < total_time < 0.050: #if the spike was a certain length
                        if last_blink_time and time.clock() - last_blink_time < .6: #if the blink occured right after the previous blink
                            if double_blink:
                                triple_blink = True
                            else :
                                double_blink = True
                        last_blink_time = time.clock() #reset the clock
                        i+=1
                        blinked = True
            if blinked and time.clock()-last_blink_time > .61: #if a certain amount of time has passed since the last blink
                if triple_blink:
                    print "Triple blink detected .......... turning left"
                    motor.forward_left()
                    time.sleep(3)
                    motor.forward()
                    break
                
                elif double_blink:
                    print "Double blink detected ........... turning right"
                    motor.forward_right()
                    time.sleep(3)
                    motor.forward()
                    break
                    
                double_blink = blinked = triple_blink = False
        time.sleep(2)
        return
    finally:
        neuropy.stop()
Ejemplo n.º 4
0
def main():
    print("hallo hallo")

    object1 = NeuroPy("/dev/rfcomm0")

    object1.setCallBack("attention", attention_callback)

    object1.start()

    while True:
        if (object1.meditation > 70):
            object1.stop()
Ejemplo n.º 5
0
class Nsky():
    def __init__(self):
        self.value = 0
        self.counter = 0
        self.skip_value = 0
        self.data_array = [0.000] * 1024
        self.neuro_object = NeuroPy("COM15")
        self.caller()

    def attention_callback(self, attention_value):
        if (self.neuro_object.attention >= 15
                and self.neuro_object.meditation >= 15
                and self.neuro_object.poorSignal == 0):
            self.counter += 1
            for i in range(len(self.data_array) - 1):
                self.data_array[i] = self.data_array[i + 1]
            self.data_array[1023] = attention_value
            if (self.counter == 1024):
                if (self.skip_value == 0):
                    self.skip_value = 1
                    self.value = input(
                        "(0 for left and 1 for right and 2 for ntg)")
                    self.counter = 0
                    if self.value == 3:
                        self.neuro_object.stop()
                    return None
                with open('traindata.csv', 'ab') as datafile:
                    writer = csv.writer(datafile)
                    writer.writerow([
                        self.neuro_object.attention,
                        self.neuro_object.meditation,
                        self.neuro_object.poorSignal, self.data_array,
                        self.value
                    ])
                self.value = input(
                    "(0 for left and 1 for right and 2 for ntg)")
                self.counter = 0
        return None

    def caller(self):
        #set call back:
        self.neuro_object.setCallBack("rawValue", self.attention_callback)
        #call start method
        self.value = input("(0 for left and 1 for right and 2 for ntg)")
        self.neuro_object.start()

        while True:
            if (
                    self.neuro_object.meditation > 100
            ):  #another way of accessing data provided by headset (1st being call backs)
                print("geda meditationg too much")
Ejemplo n.º 6
0
def collect(port, user_id):
    """Collect attention and meditation values from NeuroSky headset & store to database"""

    print "You have reached the beginning of this function!"
    port = str(port)
    headset_data = NeuroPy("/dev/cu.MindWaveMobile-DevA-" + port, 57600)

    headset_data.start()
    current_time = time.time()
    start_time = time.time()
    elapsed_time = current_time + 30 # Collect data from headset for an elapsed time of a minute.
    
    new_session = Session(utc=datetime.datetime.utcnow(), user_id=user_id)

    # TODO: figure out how to get current_user
    # current_user.sessions.append(new_session)
    # db.session.add(current_user)
    # db.session.add(new_session)
    # db.session.commit()
    print new_session.id

    # Add session to database first.
    # In the while loop, save attention and meditation data to database.
    while current_time < elapsed_time:
        attention = headset_data.attention
        # print attention
        current_time = time.time()
        # print current_time, elapsed_time
        meditation = headset_data.meditation
        
        new_state = State(utc=datetime.datetime.utcnow(), attention=attention, meditation=meditation, session_id=new_session.id)
        # db.session.add(new_state)
        # db.session.commit()
        new_session.states.append(new_state)
        time.sleep(3) # Collect data every 3 seconds.

    new_session.generate_high_score()
    db.session.add(new_session)
    db.session.commit()
    # headset_data.stop()
    # print attention
    return
Ejemplo n.º 7
0
from NeuroPy import NeuroPy
import serial

try:
    neuro = NeuroPy("COM3", 57600)
    neuro.start()
    print ("Neuropy found on COM5")
except:
    print "Not found"

value = 0

while True:
    value = neuro.rawValue
    print value
Ejemplo n.º 8
0
'''def attention_callback(attention_value):
    "this function will be called everytime NeuroPy has a new value for attention"
    print "Value of attention is",attention_value
    #do other stuff (fire a rocket), based on the obtained value of attention_value
    #do some more stuff
    return None'''

#set call back:
#object1.setCallBack("attention",attention_callback)


#call start method
#values = []
#average = 0
object1.start() #initializes the MindWave headset
start_time = 0
i = 0
blinked = False
last_blink_time = 0
double_blink = False
triple_blink = False
quadruple_blink = False
quintuple_blink = False
degrees = False
shouldMove = 1
code_message_sent = False
servos = ['BASE','BOTTOM BARS','MIDDLE BARS','TOP BARS','GRIPPER']
current_servo = 0
code = [] #the binary code that will be determined based on single and double blinks
Ejemplo n.º 9
0
# Responsável pela conexão com o MindWave
from NeuroPy import NeuroPy

# Responsável pelo controle do Mouse
from mouse import MindMouse

# Responsável pela detecção do Teclado
from pynput import keyboard

# CONFIGURAÇÃO INICIAL #
neuro = NeuroPy("COM6")  #Inicializando o MindWave
neuro.start()
'''Exemplos de inicialização:
#windows: object1=NeuroPy("COM6",57600)
#linux: object1=NeuroPy("/dev/rfcomm0",57600)'''

print('Digite uma velocidade de 5 a 15 (5 mais lento e 15 mais rápido):')
velocidade = input()  #Definindo a velocidado do mouse
mouseVirtual = MindMouse(int(velocidade))  #Iniciando objeto mouse

# CÓDIGO TEMPORARIO
'''
Objetivo:
    Enquanto não estou fazendo uso do equipamento MindWave, para fazer
    os testes de manuseio do mouse, estou usando teclas:
    u - Cima
    j - Baixo
    h - Esquerda
    k - Direita
    l - um mouse click direito
    o - um mouse click esquerdo
Ejemplo n.º 10
0
def attention_level(attention_value):
    neuropy.setCallBack("attention",attention_level)
    av = attention_value
    print "\nAttention level = ", attention_value
    if attention_value > 50:	#check if attention is above threshold
        print "Moving forward"
        motor.forward()	#forward motion of wheelchair
        time.sleep(1)
        ultrasonic.ultra()	#check for obbstacle distance
        
    else :
        print("Stopped                  Low Attention")
        motor.stop()
    return 

/*
*
* Function Name: 	main
* Input: 			-
* Output: 			-
* Logic: 			neuropy object used to create multiple threads by neuropy.start()
* Example Call:		run.main()
*
*/

if __name__=='__main__':
    neuropy.setCallBack("attention",attention_level)
    neuropy.start()
    
Ejemplo n.º 11
0
def blinkstrength_callback(blinkstrength_value):
    print "Value of blinkstrength is", blinkstrength_value
    return None
'''

#set recording timer in minutes
nmin = 1

#set call back:
#object1.setCallBack("attention",attention_callback)
#object1.setCallBack("blinkStrength",blinkstrength_callback)
object1.setCallBack("highAlpha", highalpha_callback)
object1.setCallBack("lowAlpha", lowalpha_callback)

#call start method
object1.start()

#define an INET, STREAMing socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#define IP address and match port with EEGServer port
server_address = (SERVER_ADDRESS, 2222)
print >> sys.stderr, 'connecting to %s port %s' % server_address
#socket connect requires IP address and also port number
sock.connect(server_address)

t_end = time.time() + 60 * (nmin)
print('start recording')

while time.time() < t_end:
    #keep running until t_end
    data = str(object1.highAlpha) + '\r\n'
Ejemplo n.º 12
0
from NeuroPy import NeuroPy
from time import sleep
from time import time
import csv

neuropy = NeuroPy("/dev/rfcomm1") 

neuropy.start()
sleep(3)


with open('_jamanna blink.csv', 'w') as csvfile:
    fieldnames = ['attention', 'delta', 'meditation', 'rawValue', 'theta', 
    'lowAlpha', 'highAlpha', 'lowBeta', 'highBeta', 'lowGamma', 'midGamma', 'poorSignal', 'blinkStrength' ,'label']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    i = time()
    j = time()
    print "Action 1 = truth"
    while(j-i<140):
    	writer.writerow({'attention': neuropy.attention, 'delta': neuropy.delta, 
    		'meditation': neuropy.meditation, 'rawValue': neuropy.rawValue, 
    		'theta': neuropy.theta, 'lowAlpha': neuropy.lowAlpha, 'highAlpha': neuropy.highAlpha, 
    		'lowBeta': neuropy.lowBeta, 'highBeta': neuropy.highBeta, 
    		'lowGamma' : neuropy.lowGamma, 'midGamma' : neuropy.midGamma, 
    		'poorSignal' : neuropy.poorSignal, 'blinkStrength': neuropy.blinkStrength, 'label': '1'})
        sleep(0.1)
        j = time()
    
csvfile.close()
neuropy.stop()
Ejemplo n.º 13
0
from NeuroPy import NeuroPy
object1=NeuroPy("/dev/rfcomm0") #If port not given 57600 is automatically assumed
                        #object1=NeuroPy("/dev/rfcomm0") for linux
def attention_callback(attention_value):
    "this function will be called everytime NeuroPy has a new value for attention"
    print ("Value of attention is",attention_value)
    #do other stuff (fire a rocket), based on the obtained value of attention_value
    #do some more stuff
    return None

def blink_callback(blink_value):
    "this function will be called everytime NeuroPy has a new value for blink"
    print ("Value of blinks is",blink_value)
    #do other stuff (fire a rocket), based on the obtained value of attention_value
    #do some more stuff
    return None

#set call back:
object1.setCallBack("attention",attention_callback)
object1.setCallBack("blink", blink_callback)

#set call back:
object1.setCallBack("meditation",attention_callback)

#call start method
object1.start()

while True:
    if(object1.meditation>70): #another way of accessing data provided by headset (1st being call backs)
        object1.stop()         #if meditation level reaches above 70, stop fetching data from the headset
Ejemplo n.º 14
0
'''
attention, meditation, rawValue, delta, theta, lowAlpha, highAlpha, lowBeta, highBeta, lowGamma, midGamma, poorSignal, blinkStrength 

$ pip install pyserial
$ pip install NeuroPy
$ pip install pyosc
'''

from NeuroPy import NeuroPy
import OSC
import time

neuroPy = NeuroPy("/dev/rfcomm0", 57600)
neuroPy.start()

oscClient = OSC.OSCClient()
oscClient.connect(('127.0.0.1', 57120))

while True:
    attention = neuroPy.attention
    meditation = neuroPy.meditation

    oscMsg = OSC.OSCMessage()
    oscMsg.setAddress("/neuro")
    oscMsg.append([attention, meditation])

    oscClient.send(oscMsg)

    print "attention: " + str(attention) + " - " + "meditation: " + str(
        meditation)
Ejemplo n.º 15
0
from NeuroPy import NeuroPy
#import winsound 		 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from pyo import *
s = Server().boot()

npo=NeuroPy('/dev/rfcomm0',57600)

npo.start()
def npacb(sigval):
    print sigval
    return None

#npo.setCallBack("rawValue",npacb)
npo.setCallBack("attention",npacb)

freqeeg = 512

def crtfrearray(feeg):
    eegcoll = []
    cnteeg=0
    while cnteeg<feeg:
        eegcoll.append(npo.rawValue)
        cnteeg+=1
    freqs = np.fft.fftfreq(len(eegcoll))
    idx=np.argmax(np.abs(np.array(eegcoll))**2)
    freq=freqs[idx]
    freqhz=abs(freq*freqeeg)
    if freqhz>40 and freqhz<freqeeg:
Ejemplo n.º 16
0
__dir__ = os.path.dirname(os.path.realpath(__file__))

devices = {
    'OS X': '/dev/cu.MindWaveMobile-DevA'
}

headset = NeuroPy('/dev/cu.MindWaveMobile-DevA')


def cb(name):
    def a_cb(value):
        print(name, value)
    return a_cb

#call start method
headset.start()

#set call back:
for attr in ('attention', 'delta', 'highAlpha', 'highBeta', 'lowAlpha', 'lowBeta', 'lowGamma', 'meditation', 'midGamma', 'theta'):
    headset.setCallBack(attr, cb(attr))

mp3 = mp3play.load('../6.mp3')
mp3.play()

# while True:
#     sleep(5)
#     print('Instant meditation:', headset.meditation)
#     if headset.meditation > 90:
#         headset.stop()

Ejemplo n.º 17
0
class BrainWindow(QWidget):
    def __init__(self,
                 parent=None,
                 sensorNUmber=0
                 ):  #sensorNUmber - rfcomm port number - 0 for rfcomm0 etc
        super(BrainWindow, self).__init__(parent)

        self.sensorNUmber = sensorNUmber
        self.setWindowTitle(u"Mindwave " + str(self.sensorNUmber + 1))

        layout = QGridLayout()
        layout.addWidget(QLabel("Value"), 0, 1)
        layout.addWidget(QLabel("Min"), 0, 2)
        layout.addWidget(QLabel("Max"), 0, 3)
        layout.addWidget(QLabel("Relative"), 0, 4)

        layout.addWidget(QLabel("Attention:"), 1, 0)
        layout.addWidget(QLabel("Poor signal:"), 1, 2)
        layout.addWidget(QLabel("Low beta"), 2, 0)
        layout.addWidget(QLabel("High beta"), 3, 0)
        layout.addWidget(QLabel("Low gamma"), 4, 0)
        layout.addWidget(QLabel("Mid gamma"), 5, 0)
        layout.addWidget(QLabel("Raw data:"), 6, 0)

        self.attentionLabel = QLabel()
        layout.addWidget(self.attentionLabel, 1, 1)

        self.poorSignalLabel = QLabel()
        layout.addWidget(self.poorSignalLabel, 1, 3)

        self.lBetaLabel = QLabel()
        self.lBetaMinLabel = QLabel()
        self.lBetaMaxLabel = QLabel()
        self.lBetaRelLabel = QLabel()
        layout.addWidget(self.lBetaLabel, 2, 1)
        layout.addWidget(self.lBetaMinLabel, 2, 2)
        layout.addWidget(self.lBetaMaxLabel, 2, 3)
        layout.addWidget(self.lBetaRelLabel, 2, 4)

        self.hBetaLabel = QLabel()
        self.hBetaMinLabel = QLabel()
        self.hBetaMaxLabel = QLabel()
        self.hBetaRelLabel = QLabel()
        layout.addWidget(self.hBetaLabel, 3, 1)
        layout.addWidget(self.hBetaMinLabel, 3, 2)
        layout.addWidget(self.hBetaMaxLabel, 3, 3)
        layout.addWidget(self.hBetaRelLabel, 3, 4)

        self.lGammaLabel = QLabel()
        self.lGammaMinLabel = QLabel()
        self.lGammaMaxLabel = QLabel()
        self.lGammaRelLabel = QLabel()
        layout.addWidget(self.lGammaLabel, 4, 1)
        layout.addWidget(self.lGammaMinLabel, 4, 2)
        layout.addWidget(self.lGammaMaxLabel, 4, 3)
        layout.addWidget(self.lGammaRelLabel, 4, 4)

        self.mGammaLabel = QLabel()
        self.mGammaMinLabel = QLabel()
        self.mGammaMaxLabel = QLabel()
        self.mGammaRelLabel = QLabel()
        layout.addWidget(self.mGammaLabel, 5, 1)
        layout.addWidget(self.mGammaMinLabel, 5, 2)
        layout.addWidget(self.mGammaMaxLabel, 5, 3)
        layout.addWidget(self.mGammaRelLabel, 5, 4)

        #stop
        stopButton = QPushButton("Stop")
        stopButton.clicked.connect(self.stop)
        layout.addWidget(stopButton, 7, 0)

        self.setLayout(layout)

        self.headSet = NeuroPy("/dev/rfcomm" + str(sensorNUmber), 57600)
        self.headSet.setCallBack("attention", self.attention_callback)
        self.headSet.setCallBack("lowBeta", self.lowBeta_callback)
        self.headSet.setCallBack("highBeta", self.highBeta_callback)
        self.headSet.setCallBack("lowGamma", self.lowGamma_callback)
        self.headSet.setCallBack("midGamma", self.midGamma_callback)
        self.headSet.setCallBack("rawValue", self.rawValue_callback)
        self.headSet.setCallBack("poorSignal", self.poorSignal_callback)
        self.headSet.start()

        self.highLimit = 100000  # ignore occasional  higher values from EEG data
        self.lowLimit = 100

        self.lBetamin = 10000
        self.lBetamax = 0.1
        self.lBetarelative = 0
        self.hBetamin = 10000
        self.hBetamax = 0.1
        self.hBetarelative = 0
        self.lGammamin = 10000
        self.lGammamax = 0.1
        self.lGammarelative = 0
        self.mGammamin = 10000
        self.mGammamax = 0.1
        self.mGammarelative = 0

    def __del__(self):
        self.stop()

    def stop(self):
        self.headSet.stop()
        #self.perf.Stop()
        #self.perf.Join()
        #self.cs.Stop()

    #TEMPORARY -delete later

    def lowBeta_callback(self, value):
        #print "Low beta: ", value
        if (value > self.highLimit or
                value < self.lowLimit):  # don't handle occasional high values
            return
        self.lBetaLabel.setText(str(value))
        if (value < self.lBetamin and value != 0):
            self.lBetamin = value
            self.lBetaMinLabel.setText(str(value))
        if (value > self.lBetamax):
            self.lBetamax = value
            self.lBetaMaxLabel.setText(str(value))
        self.lBetarelative = float(value - self.lBetamin) / (self.lBetamax -
                                                             self.lBetamin + 1)
        self.lBetaRelLabel.setText(str(self.lBetarelative))
        sendUdpMessage("sensor,lb" + str(self.sensorNUmber + 1) + "," +
                       str(self.lBetarelative))

        #self.cs.SetChannel("lowBetaRelative",self.lBetarelative)
        return None

    def highBeta_callback(self, value):
        #print "high beta: ", value
        if (value > self.highLimit or
                value < self.lowLimit):  # don't handle occasional high values
            return
        self.hBetaLabel.setText(str(value))
        if (value < self.hBetamin and value != 0):
            self.hBetamin = value
            self.hBetaMinLabel.setText(str(value))
        if (value > self.hBetamax):
            self.hBetamax = value
            self.hBetaMaxLabel.setText(str(value))
        self.hBetarelative = float(value - self.hBetamin) / (self.hBetamax -
                                                             self.hBetamin + 1)
        self.hBetaRelLabel.setText(str(self.hBetarelative))
        sendUdpMessage("sensor,hb" + str(self.sensorNUmber + 1) + "," +
                       str(self.hBetarelative))
        #self.cs.SetChannel("highBetaRelative",self.hBetarelative)
        return None

    def lowGamma_callback(self, value):
        #print "Low gamma: ", value
        if (value > self.highLimit or
                value < self.lowLimit):  # don't handle occasional high values
            return
        self.lGammaLabel.setText(str(value))
        if (value < self.lGammamin and value != 0):
            self.lGammamin = value
            self.lGammaMinLabel.setText(str(value))
        if (value > self.lGammamax):
            self.lGammamax = value
            self.lGammaMaxLabel.setText(str(value))
        self.lGammarelative = float(value - self.lGammamin) / (
            self.lGammamax - self.lGammamin + 1)
        self.lGammaRelLabel.setText(str(self.lGammarelative))
        #self.cs.SetChannel("lowBetaRelative",self.lGammarelative)
        return None

    def midGamma_callback(self, value):
        #print "mid gamma: ", value
        if (value > self.highLimit or
                value < self.lowLimit):  # don't handle occasional high values
            return
        self.mGammaLabel.setText(str(value))
        if (value < self.mGammamin and value != 0):
            self.mGammamin = value
            self.mGammaMinLabel.setText(str(value))
        if (value > self.mGammamax):
            self.mGammamax = value
            self.mGammaMaxLabel.setText(str(value))
        self.mGammarelative = float(value - self.mGammamin) / (
            self.mGammamax - self.mGammamin + 1)
        self.mGammaRelLabel.setText(str(self.mGammarelative))
        #self.cs.SetChannel("midmGammaRelative",self.mGammarelative)
        return None

    def attention_callback(self, value):
        #print "Attention: ",value
        self.attentionLabel.setText(str(value))
        sendUdpMessage("sensor,attention" + str(self.sensorNUmber + 1) + "," +
                       str(float(value) / 100))
        #self.cs.SetChannel("attention",value)
        return None

    def rawValue_callback(self, value):
        #this is very fast don't print this
        #print "rawValue: ", value
        #self.cs.SetChannel("rawValue",value)
        if (abs(value) < 1000):
            sendUdpMessage("sensor,raw" + str(self.sensorNUmber + 1) + "," +
                           str(value))
        return None

    def poorSignal_callback(self, value):
        print "headset: ", self.sensorNUmber, "poor signal: ", value
        self.poorSignalLabel.setText(str(value))
Ejemplo n.º 18
0
serport = FindSerialDevice("Select the Serial port: ")
ser = serial.Serial(serport, 9600, timeout=1)
mindwaveport = FindSerialDevice("Select the Mindwave port: ")
bluetooth_baund_rate = input(
    'bluetooth baund rate (default: 57600) >') or 57600
mindwave = NeuroPy(mindwaveport, bluetooth_baund_rate)
jsonlist = []
jsonlist1 = []
list = []

if ser.is_open:
    ser.flushOutput()
    ser.flushInput()
    try:
        mindwave.start()

        while 1:
            ser.flushOutput()
            now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            response = ser.readline().decode().strip()
            low_alpha = mindwave.low_alpha
            high_alpha = mindwave.high_alpha
            low_beta = mindwave.low_beta
            high_beta = mindwave.high_beta
            meditation = mindwave.meditation
            if response:
                jsonlist.append(response)
                if len(jsonlist) == 2:
                    z = {jsonlist[0]: jsonlist[1]}
                    jsonlist1.append(z)
Ejemplo n.º 19
0
from NeuroPy import NeuroPy
#import winsound
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from pyo import *
s = Server().boot()

npo = NeuroPy('/dev/rfcomm0', 57600)

npo.start()


def npacb(sigval):
    print sigval
    return None


#npo.setCallBack("rawValue",npacb)
npo.setCallBack("attention", npacb)

freqeeg = 512


def crtfrearray(feeg):
    eegcoll = []
    cnteeg = 0
    while cnteeg < feeg:
        eegcoll.append(npo.rawValue)
        cnteeg += 1
    freqs = np.fft.fftfreq(len(eegcoll))
Ejemplo n.º 20
0
class BrainWindow(QWidget):
	def __init__(self, parent=None, sensorNUmber=0): #sensorNUmber - rfcomm port number - 0 for rfcomm0 etc
		super(BrainWindow, self).__init__(parent)
		
		self.sensorNUmber = sensorNUmber
		self.setWindowTitle(u"Mindwave"+str(self.sensorNUmber))
		
		layout = QGridLayout()
		layout.addWidget(QLabel("Value"),0,1)
		layout.addWidget(QLabel("Min"),0,2)
		layout.addWidget(QLabel("Max"),0,3)
		layout.addWidget(QLabel("Relative"),0,4)
		
		layout.addWidget(QLabel("Attention:"),1,0)
		layout.addWidget(QLabel("Poor signal:"),1,2)
		layout.addWidget(QLabel("Low beta"),2,0)
		layout.addWidget(QLabel("High beta"),3,0)
		layout.addWidget(QLabel("Low gamma"),4,0)
		layout.addWidget(QLabel("Mid gamma"),5,0)
		layout.addWidget(QLabel("Raw data:"),6,0)
		
		self.attentionLabel = QLabel()
		layout.addWidget(self.attentionLabel,1,1)
		
		self.poorSignalLabel = QLabel()
		layout.addWidget(self.poorSignalLabel,1,3)
		
		self.lBetaLabel = QLabel()
		self.lBetaMinLabel = QLabel()
		self.lBetaMaxLabel = QLabel()
		self.lBetaRelLabel = QLabel()
		layout.addWidget(self.lBetaLabel,2,1)
		layout.addWidget(self.lBetaMinLabel,2,2)
		layout.addWidget(self.lBetaMaxLabel,2,3)
		layout.addWidget(self.lBetaRelLabel,2,4)
		
		self.hBetaLabel = QLabel()
		self.hBetaMinLabel = QLabel()
		self.hBetaMaxLabel = QLabel()
		self.hBetaRelLabel = QLabel()
		layout.addWidget(self.hBetaLabel,3,1)
		layout.addWidget(self.hBetaMinLabel,3,2)
		layout.addWidget(self.hBetaMaxLabel,3,3)
		layout.addWidget(self.hBetaRelLabel,3,4)
		
		self.lGammaLabel = QLabel()
		self.lGammaMinLabel = QLabel()
		self.lGammaMaxLabel = QLabel()
		self.lGammaRelLabel = QLabel()
		layout.addWidget(self.lGammaLabel,4,1)
		layout.addWidget(self.lGammaMinLabel,4,2)
		layout.addWidget(self.lGammaMaxLabel,4,3)
		layout.addWidget(self.lGammaRelLabel,4,4)
		
		self.mGammaLabel = QLabel()
		self.mGammaMinLabel = QLabel()
		self.mGammaMaxLabel = QLabel()
		self.mGammaRelLabel = QLabel()
		layout.addWidget(self.mGammaLabel,5,1)
		layout.addWidget(self.mGammaMinLabel,5,2)
		layout.addWidget(self.mGammaMaxLabel,5,3)
		layout.addWidget(self.mGammaRelLabel,5,4)
		
		
		
		
		#stop
		stopButton = QPushButton("Stop")
		stopButton.clicked.connect(self.stop)
		layout.addWidget(stopButton,7,0)
		
		self.setLayout(layout)
		
		
		self.headSet = NeuroPy("/dev/rfcomm"+str(sensorNUmber),57600)
		self.headSet.setCallBack("attention",self.attention_callback)
		self.headSet.setCallBack("lowBeta",self.lowBeta_callback)
		self.headSet.setCallBack("highBeta",self.highBeta_callback)
		self.headSet.setCallBack("lowGamma",self.lowGamma_callback)
		self.headSet.setCallBack("midGamma",self.midGamma_callback)
		self.headSet.setCallBack("rawValue",self.rawValue_callback)
		self.headSet.setCallBack("poorSignal",self.poorSignal_callback)
		self.headSet.start()
		
		self.highLimit = 100000 # ignore occasional  higher values from EEG data
		self.lowLimit = 100
		
		self.lBetamin = 10000
		self.lBetamax = 0.1
		self.lBetarelative = 0
		self.hBetamin = 10000
		self.hBetamax = 0.1
		self.hBetarelative = 0
		self.lGammamin = 10000
		self.lGammamax = 0.1
		self.lGammarelative = 0
		self.mGammamin = 10000
		self.mGammamax = 0.1
		self.mGammarelative = 0
		
		
		
	def __del__(self):
		self.stop()
	
	def stop(self):
		self.headSet.stop()
		#self.perf.Stop()
		#self.perf.Join()
		#self.cs.Stop()
	
	#TEMPORARY -delete later
	
		
	
	def lowBeta_callback(self, value):
		#print "Low beta: ", value
		if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values
			return
		self.lBetaLabel.setText(str(value))
		if (value<self.lBetamin and value!=0):
			self.lBetamin = value
			self.lBetaMinLabel.setText(str(value))
		if (value>self.lBetamax):
			self.lBetamax = value
			self.lBetaMaxLabel.setText(str(value))
		self.lBetarelative = float(value-self.lBetamin)/(self.lBetamax-self.lBetamin+1)
		self.lBetaRelLabel.setText(str(self.lBetarelative))
		sendUdpMessage("sensor,lb"+str(self.sensorNUmber+1)+","+str(self.lBetarelative))

		#self.cs.SetChannel("lowBetaRelative",self.lBetarelative)		
		return None
	
	def highBeta_callback(self, value):
		#print "high beta: ", value
		if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values
			return
		self.hBetaLabel.setText(str(value))
		if (value<self.hBetamin and value!=0):
			self.hBetamin = value
			self.hBetaMinLabel.setText(str(value))
		if (value>self.hBetamax):
			self.hBetamax = value
			self.hBetaMaxLabel.setText(str(value))
		self.hBetarelative = float(value-self.hBetamin)/(self.hBetamax-self.hBetamin+1)
		self.hBetaRelLabel.setText(str(self.hBetarelative))
		sendUdpMessage("sensor,hb"+str(self.sensorNUmber+1)+","+str(self.hBetarelative))
		#self.cs.SetChannel("highBetaRelative",self.hBetarelative)		
		return None
	
	def lowGamma_callback(self, value):
		#print "Low gamma: ", value
		if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values
			return
		self.lGammaLabel.setText(str(value))
		if (value<self.lGammamin and value!=0):
			self.lGammamin = value
			self.lGammaMinLabel.setText(str(value))
		if (value>self.lGammamax):
			self.lGammamax = value
			self.lGammaMaxLabel.setText(str(value))
		self.lGammarelative = float(value-self.lGammamin)/(self.lGammamax-self.lGammamin+1)
		self.lGammaRelLabel.setText(str(self.lGammarelative))
		#self.cs.SetChannel("lowBetaRelative",self.lGammarelative)		
		return None
	
	def midGamma_callback(self, value):
		#print "mid gamma: ", value
		if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values
			return
		self.mGammaLabel.setText(str(value))
		if (value<self.mGammamin and value!=0):
			self.mGammamin = value
			self.mGammaMinLabel.setText(str(value))
		if (value>self.mGammamax):
			self.mGammamax = value
			self.mGammaMaxLabel.setText(str(value))
		self.mGammarelative = float(value-self.mGammamin)/(self.mGammamax-self.mGammamin+1)
		self.mGammaRelLabel.setText(str(self.mGammarelative))
		#self.cs.SetChannel("midmGammaRelative",self.mGammarelative)		
		return None
	
	def attention_callback(self, value):
		#print "Attention: ",value
		self.attentionLabel.setText(str(value))
		sendUdpMessage("sensor,attention"+str(self.sensorNUmber+1)+","+str(float(value)/100))
		#self.cs.SetChannel("attention",value)
		return None
	
	def rawValue_callback(self, value):
		#this is very fast don't print this 
		#print "rawValue: ", value
		#self.cs.SetChannel("rawValue",value)
		if (abs(value)<1000):
			sendUdpMessage("sensor,raw"+str(self.sensorNUmber+1)+","+str(value))
		return None
	
	def poorSignal_callback(self,value):
		print "headset: ",self.sensorNUmber,"poor signal: ",value
		self.poorSignalLabel.setText(str(value))
Ejemplo n.º 21
0
#code to obtain data

from NeuroPy import NeuroPy
import time

datafile = open("testdata.txt", "w+")

object = NeuroPy("COM11", 57600)
#Start communication
object.start()

f = 200  #set sampling frequency
t = 2  #set sampling time
N = f * 2  #no of sample points

datafile.write('%d\n' % f)
datafile.write('%d\n' % N)

i = 0

while i < N:

    datafile.write('%d\n' % object.rawValue)
    time.sleep(1 / f)
    i = i + 1

datafile.close()
Ejemplo n.º 22
0
from NeuroPy import NeuroPy
import threading


def stoppa(a):
    a.stop()
    a.save()


#Rilassamento 438 secs a 1min
#Musica metal 200 secs da 25sec
#Logica 200 da 0
#Memoria 200 da 0

person_name = input('Nome dell\'utente: ')
task_name = input('Nome del task: ')
task_duration = input('Durata del task(sec):')

record = NeuroPy("COM3",
                 person_name=person_name,
                 task_name=task_name,
                 task_duration=task_duration)
threading.Timer(int(task_duration), stoppa, [record]).start()
record.start()
class MindwaveTracker:
    com = "COM16"

    time_last_notified = time.clock()
    MAX_ZERO_VALUES_BEFORE_WARNING = 10
    attention_value = 0
    meditation_value = 0
    poorSignal = 0
    blinkStrength = 0
    index = 0
    aantal_avg = 0
    interval = 0
    teller_duration_iteration_sec = 0.0
    datetime_from = datetime.datetime.today()
    teller_zero_values = 0
    mindwave_instance = None

    def __init__(self, aantal_avg, interval, com_port_mindwave):
        self.aantal_avg = aantal_avg
        self.interval = interval
        self.com = com_port_mindwave
        self.mindwave_instance = NeuroPy(self.com)
        self.mindwave_instance.start()

    def notify(self):
        time_now = time.clock()
        duration_iteration_sec = time_now - self.time_last_notified
        self.time_last_notified = time.clock()
        self.teller_duration_iteration_sec += duration_iteration_sec
        if self.teller_duration_iteration_sec >= self.interval:
            self.teller_duration_iteration_sec = 0.0
            self.record_measurement()

    def record_measurement(self):
        print str(
            str('attention: ' + str(self.mindwave_instance.attention)) + '\t' +
            str('meditation: ' + str(self.mindwave_instance.meditation)))
        if (self.index == self.aantal_avg):
            print str('avg attention: ' +
                      str(float(self.attention_value / self.aantal_avg)))
            average_attention = float(
                self.attention_value / self.aantal_avg) / 100
            average_meditation = float(
                self.meditation_value / self.aantal_avg) / 100
            average_poorSignal = float(self.poorSignal / self.aantal_avg)
            average_blinkStrength = float(self.blinkStrength / self.aantal_avg)
            datetime_to = datetime.datetime.today()
            DAMindwave_SQLite.insert_row_mindwave(
                self.datetime_from, datetime_to, average_attention,
                average_meditation, average_poorSignal, average_blinkStrength)

            self.attention_value = self.mindwave_instance.attention
            self.meditation_value = self.mindwave_instance.meditation
            self.poorSignal = self.mindwave_instance.poorSignal
            self.blinkStrength = self.mindwave_instance.blinkStrength

            self.index = 1
            self.datetime_from = datetime.datetime.today()

        else:
            if self.mindwave_instance.attention != 0 and self.mindwave_instance.meditation != 0:
                self.attention_value += self.mindwave_instance.attention
                self.meditation_value += self.mindwave_instance.meditation
                self.poorSignal += self.mindwave_instance.poorSignal
                self.blinkStrength += self.mindwave_instance.blinkStrength

                self.index += 1
            else:
                self.teller_zero_values += 1
                if self.teller_zero_values == self.MAX_ZERO_VALUES_BEFORE_WARNING:
                    tkMessageBox.showinfo(
                        title="Warning",
                        message=
                        "The attention and meditation values are 0 for a long time. Possible problem with the device"
                    )
                    self.teller_zero_values = 0

    def stop_device(self):
        try:
            self.mindwave_instance.stop()
        except Exception, e:
            raise Exception(e)
Ejemplo n.º 24
0
    rowdata.append(hset.attention)
    rowdata.append(hset.meditation)
    rowdata.append(hset.delta)
    rowdata.append(hset.theta)
    rowdata.append(hset.lowAlpha)
    rowdata.append(hset.highAlpha)
    rowdata.append(hset.lowBeta)
    rowdata.append(hset.highBeta)
    rowdata.append(hset.lowGamma)
    rowdata.append(hset.midGamma)
    queue.append(rowdata)


# NeuroSky Setup
hset = NeuroPy('COM4')
hset.start()
time.sleep(8)
print('Ready...')

results = []
queue = []
while True:

    # Terminating data collection
    if keyboard.is_pressed('q'):
        print('Quitting - Results outputted to output.csv')
        #storing into csv
        with open("output.csv", "wb") as f:
            writer = csv.writer(f)
            writer.writerows(results)
        break
import serial
import time
from NeuroPy import NeuroPy

ser = serial.Serial(port='COM5', baudrate=9600)
#set the Arduino port connection
object1 = NeuroPy("COM4", 57600)  #set the MindWave headset portconnection
#change ports if needed
object1.start()  #start reading from the MindWave headset
#t_end = time.time() + 60 * 1 to define time for the while-loop if needed

print 'Are you ready to break a spoon bitch !!!'
a = input('Shall we continue sucker ?')
#request a keyboard input, which is '' to continue with the script
#this is done to allow time for the servo to go to the initial position

try:
    while True:

        if object1.attention > 40:
            #this statement tells the arduino to start moving the motor if
            #attention level is over 40 (attention level varies 0-100)
            ser.write('5')
            time.sleep(0.5)
            #0.5s time delay to make consistent and smooth movement of the motor
            print object1.attention
        else:
            #this statement tells the arduino to stop moving the motor if
            # attention level is bellow the threshold
            time.sleep(0.5)
            # another time delay for consistency
Ejemplo n.º 26
0
from win32api import GetSystemMetrics
import pytweening
import time
import win32gui


def map(x, oFrom, oTo, nFrom, nTo):
    return x * ((nTo - nFrom) / (oTo - oFrom))
    pass


print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))

ob = NeuroPy("COM6")
ob.start()
count = 0
flag = 1
lastAttention = 0
while (True):
    # print(ob.attention, "blink",ob.blinkStrength)
    # pi.moveTo(map(ob.attention+1, 1, 100, 1, GetSystemMetrics(0)),
    #           map(ob.meditation+1, 1, 100, 1, GetSystemMetrics(1)), pytweening.easeInQuad(0.75))
    # pi.moveTo(map(ob.highBeta+1, 1, 100, 1, GetSystemMetrics(0)),
    #   100, pytweening.easeInQuad(0.75))
    # print(ob.blinkStrength)
    # time.sleep(0.1)
    # print("alpha ",ob.highAlpha," ",ob.lowAlpha," Beta ",ob.highBeta," ",ob.lowBeta)
    flags, hcursor, (x, y) = win32gui.GetCursorInfo()
    if (ob.attention == 0):
        print(ob.attention)
Ejemplo n.º 27
0
class SpaceInvaders(object):
    def __init__(self):
        # It seems, in Linux buffersize=512 is not enough, use 4096 to prevent:
        #   ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
        mixer.pre_init(44100, -16, 1, 4096)
        init()
        self.clock = time.Clock()
        self.caption = display.set_caption('Space Invaders')
        self.screen = SCREEN
        self.background = image.load(IMAGE_PATH + 'background.jpg').convert()
        self.mainScreen = True
        self.mathScreen = False
        self.levelScreen = False
        self.startGame = False
        self.gameOver = False

        # Initial values for attention and meditation thresholds
        self.attPractice = list()
        self.medPractice = list()
        self.attThreshold = 0
        self.medThreshold = 0
        self.attHigh = True
        self.medHigh = True

        # Counter for enemy starting position (increased each new round)
        self.enemyPosition = ENEMY_DEFAULT_POSITION
        self.titleText = Text(FONT, 50, 'Space Invaders', WHITE, 164, 155)
        self.titleText2 = Text(FONT, 25, 'Press any key to continue', WHITE,
                               201, 225)
        self.gameOverText = Text(FONT, 50, 'Game Over', WHITE, 250, 270)
        self.nextRoundText = Text(FONT, 50, 'Next Round', WHITE, 240, 270)
        self.enemy1Text = Text(FONT, 25, '   =   10 pts', GREEN, 368, 270)
        self.enemy2Text = Text(FONT, 25, '   =  20 pts', BLUE, 368, 320)
        self.enemy3Text = Text(FONT, 25, '   =  30 pts', PURPLE, 368, 370)
        self.enemy4Text = Text(FONT, 25, '   =  ?????', RED, 368, 420)
        self.scoreText = Text(FONT, 20, 'Score', WHITE, 5, 5)
        self.livesText = Text(FONT, 20, 'Lives ', WHITE, 640, 5)

        # For math practice use
        self.titleMath = Text(FONT, 40, 'practice before game!', WHITE, 130,
                              70)
        self.titleMath2 = Text(FONT, 25, 'press any key to next question',
                               WHITE, 160, 120)
        self.attMath = Text(FONT, 25, 'Attention  :', GREEN, 280, 450)
        self.medMath = Text(FONT, 25, 'Meditation:', GREEN, 280, 500)

        # For level screen use
        self.titleLevel = Text(FONT, 40, 'select game level', WHITE, 170, 70)
        self.titleLevel2 = Text(FONT, 20,
                                'enter number between 1 and 6 and return',
                                WHITE, 150, 120)
        self.attThText = Text(FONT, 25, 'Attention Threshold :', RED, 200, 450)
        self.medThText = Text(FONT, 25, 'Meditation Threshold :', RED, 200,
                              500)
        self.intList = [K_1, K_2, K_3, K_4, K_5, K_6]
        self.level = 0
        self.levelSet = False

        # Display attention value on screen
        self.attentionText = Text(FONT, 20, 'Attention', WHITE, 180, 5)
        self.meditationText = Text(FONT, 20, 'Meditation', WHITE, 395, 5)

        # Life symbols
        self.life1 = Life(715, 3)
        self.life2 = Life(742, 3)
        self.life3 = Life(769, 3)
        self.livesGroup = sprite.Group(self.life1, self.life2, self.life3)

        # Neuropy object to extract brainwave value
        self.neuropy = NeuroPy(PORT1, PORT2)
        self.neuropy.start()

    def main(self):
        while True:
            # Main title screen
            if self.mainScreen:
                self.screen.blit(self.background, (0, 0))
                self.titleText.draw(self.screen)
                self.titleText2.draw(self.screen)
                self.enemy1Text.draw(self.screen)
                self.enemy2Text.draw(self.screen)
                self.enemy3Text.draw(self.screen)
                self.enemy4Text.draw(self.screen)
                self.create_main_menu()

                # Keyboard input handling
                for e in event.get():
                    if self.should_exit(e):  #QUIT or escape key to quit
                        sys.exit()
                    if e.type == KEYUP:
                        self.numQuestions = 5
                        self.make_math_problem()
                        self.numQuestions -= 1
                        self.numQueStr = str(
                            self.numQuestions) + " more question"
                        self.mathScreen = True
                        self.mainScreen = False

            # Practice Math Screen
            elif self.mathScreen:
                self.screen.blit(self.background, (0, 0))
                self.titleMath.draw(self.screen)
                self.titleMath2.draw(self.screen)
                self.attMath.draw(self.screen)
                self.medMath.draw(self.screen)
                self.problemText = Text(FONT, 50, self.problem, WHITE, 230,
                                        280)
                self.problemText.draw(self.screen)
                self.numQuestionText = Text(FONT, 25, self.numQueStr, RED, 270,
                                            150)
                self.numQuestionText.draw(self.screen)

                # Neuropy values
                self.attMathValue = Text(FONT, 25, str(self.neuropy.attention),
                                         GREEN, 480, 450)
                self.medMathValue = Text(FONT, 25,
                                         str(self.neuropy.meditation), GREEN,
                                         480, 500)
                self.attMathValue.draw(self.screen)
                self.medMathValue.draw(self.screen)

                # add non-zero value of attention and meditation
                if self.neuropy.attention > 0:
                    self.attPractice.append(self.neuropy.attention)
                if self.neuropy.meditation > 0:
                    self.medPractice.append(self.neuropy.meditation)

                # Keyboard input handling
                for e in event.get():
                    if self.should_exit(e):
                        sys.exit()
                    if e.type == KEYUP:
                        if self.numQuestions > 0:
                            self.make_math_problem()
                            self.numQuestions -= 1
                            if self.numQuestions == 0:
                                self.numQueStr = "last question"
                            else:
                                self.numQueStr = str(
                                    self.numQuestions) + " more question"
                        else:
                            self.attThreshold = int(
                                sum(self.attPractice) / len(self.attPractice))
                            self.medThreshold = int(
                                sum(self.medPractice) / len(self.medPractice))
                            self.attPractice = list()
                            self.medPractice = list()
                            self.attThVal = Text(FONT, 25,
                                                 str(self.attThreshold), WHITE,
                                                 580, 450)
                            self.medThVal = Text(FONT, 25,
                                                 str(self.medThreshold), WHITE,
                                                 580, 500)
                            self.levelScreen = True
                            self.mathScreen = False

            elif self.levelScreen:
                self.screen.blit(self.background, (0, 0))
                self.titleLevel.draw(self.screen)
                self.titleLevel2.draw(self.screen)
                self.attThText.draw(self.screen)
                self.medThText.draw(self.screen)
                self.attThVal.draw(self.screen)
                self.medThVal.draw(self.screen)
                if self.levelSet:
                    self.levelText.draw(self.screen)
                for e in event.get():
                    if self.should_exit(e):
                        sys.exit()
                    if e.type == KEYUP:
                        if self.levelSet and e.key == K_RETURN:  # Start Game
                            self.allBlockers = sprite.Group(
                                self.make_blockers(0), self.make_blockers(1),
                                self.make_blockers(2), self.make_blockers(3))
                            self.livesGroup.add(self.life1, self.life2,
                                                self.life3)
                            self.reset(0)
                            self.startGame = True
                            self.levelScreen = False
                        elif not self.levelSet and e.key in self.intList:
                            # input number = number of enermy bullets
                            self.level = e.key - 48  # extract the key number
                            levelStr = "level " + str(self.level)
                            self.levelText = Text(FONT, 70, levelStr, GREEN,
                                                  240, 250)
                            self.levelSet = True

            elif self.startGame:  # Game Plaing screen
                # When winning game and going to next round
                if not self.enemies and not self.explosionsGroup:
                    currentTime = time.get_ticks()
                    if currentTime - self.gameTimer < 3000:
                        self.screen.blit(self.background, (0, 0))
                        self.scoreText2 = Text(FONT, 20, str(self.score),
                                               GREEN, 85, 5)
                        self.scoreText.draw(self.screen)
                        self.scoreText2.draw(self.screen)
                        self.nextRoundText.draw(self.screen)
                        self.livesText.draw(self.screen)
                        self.livesGroup.update()
                        self.check_input()
                    if currentTime - self.gameTimer > 3000:
                        self.enemyPosition += ENEMY_MOVE_DOWN
                        self.reset(self.score)
                        self.gameTimer += 3000
                # While playing actual game
                else:
                    currentTime = time.get_ticks()
                    self.play_main_music(currentTime)
                    self.screen.blit(self.background, (0, 0))
                    self.allBlockers.update(self.screen)
                    self.scoreText2 = Text(FONT, 20, str(self.score), GREEN,
                                           85, 5)
                    self.scoreText.draw(self.screen)
                    self.scoreText2.draw(self.screen)

                    # Check if att and med are above threshold value
                    self.attHigh = True if self.neuropy.attention >= self.attThreshold else False
                    self.medHigh = True if self.neuropy.meditation <= self.medThreshold else False

                    # Draw neuropy text and value
                    attColor = GREEN
                    medColor = GREEN
                    if self.attHigh:
                        attColor = RED
                    if self.medHigh:
                        medColor = RED
                    self.attentionText2 = Text(FONT, 20,
                                               str(self.neuropy.attention),
                                               attColor, 320, 5)
                    self.meditationText2 = Text(FONT, 20,
                                                str(self.neuropy.meditation),
                                                medColor, 545, 5)
                    self.attentionText2.draw(self.screen)
                    self.meditationText2.draw(self.screen)
                    self.attentionText.draw(self.screen)
                    self.meditationText.draw(self.screen)

                    # Check some conditions
                    self.livesText.draw(self.screen)
                    self.check_input()
                    self.enemies.update(currentTime)
                    self.allSprites.update(self.keys, currentTime)
                    self.explosionsGroup.update(currentTime)
                    self.check_collisions()
                    self.create_new_ship(self.makeNewShip, currentTime)
                    self.make_enemies_shoot()
            # When losing game
            elif self.gameOver:
                currentTime = time.get_ticks()
                # Reset enemy starting position
                self.enemyPosition = ENEMY_DEFAULT_POSITION
                self.create_game_over(currentTime)

            display.update()
            self.clock.tick(60)

    def make_math_problem(self):
        num1 = str(random.randint(1, 99))
        num2 = str(random.randint(1, 99))
        symbol = ' + ' if random.randint(0, 1) == 0 else ' - '
        self.problem = num1 + symbol + num2 + ' = ???'

    def make_enemies_shoot(self):
        if (time.get_ticks() - self.timer) > 700 and self.enemies:
            if self.medHigh:
                for i in range(self.level):
                    enemy = self.enemies.random_bottom()
                    self.enemyBullets.add(
                        Bullet(enemy.rect.x + 14, enemy.rect.y + 20, 1, 5,
                               'enemylaser', 'center'))
                    self.allSprites.add(self.enemyBullets)
            else:
                enemy = self.enemies.random_bottom()
                self.enemyBullets.add(
                    Bullet(enemy.rect.x + 14, enemy.rect.y + 20, 1, 5,
                           'enemylaser', 'center'))
                self.allSprites.add(self.enemyBullets)
            self.timer = time.get_ticks()

    def check_input(self):
        self.keys = key.get_pressed()
        for e in event.get():
            if self.should_exit(e):
                sys.exit()
            if e.type == KEYDOWN:
                if e.key == K_SPACE:
                    if len(self.bullets) == 0 and self.shipAlive:
                        # Special shoot when attention is high
                        if self.attHigh:
                            for i in range(5):
                                speed = 15 - i
                                bullet = Bullet(self.player.rect.x + 23,
                                                self.player.rect.y + 5, -1,
                                                speed, 'laser', 'center')
                                self.bullets.add(bullet)
                            self.allSprites.add(self.bullets)
                            self.sounds['shoot2'].play()
                        # Normal shoot
                        else:
                            bullet = Bullet(self.player.rect.x + 23,
                                            self.player.rect.y + 5, -1, 15,
                                            'laser', 'center')
                            self.bullets.add(bullet)
                            self.allSprites.add(self.bullets)
                            self.sounds['shoot'].play()

    def reset(self, score):
        self.player = Ship()
        self.playerGroup = sprite.Group(self.player)
        self.explosionsGroup = sprite.Group()
        self.bullets = sprite.Group()
        self.mysteryShip = Mystery()
        self.mysteryGroup = sprite.Group(self.mysteryShip)
        self.enemyBullets = sprite.Group()
        self.make_enemies()
        self.allSprites = sprite.Group(self.player, self.enemies,
                                       self.livesGroup, self.mysteryShip)
        self.keys = key.get_pressed()

        self.timer = time.get_ticks()
        self.noteTimer = time.get_ticks()
        self.shipTimer = time.get_ticks()
        self.score = score
        self.create_audio()
        self.makeNewShip = False
        self.shipAlive = True

    def make_blockers(self, number):
        blockerGroup = sprite.Group()
        for row in range(4):
            for column in range(9):
                blocker = Blocker(10, GREEN, row, column)
                blocker.rect.x = 50 + (200 * number) + (column * blocker.width)
                blocker.rect.y = BLOCKERS_POSITION + (row * blocker.height)
                blockerGroup.add(blocker)
        return blockerGroup

    def create_audio(self):
        self.sounds = {}
        for sound_name in [
                'shoot', 'shoot2', 'invaderkilled', 'mysterykilled',
                'shipexplosion'
        ]:
            self.sounds[sound_name] = mixer.Sound(SOUND_PATH +
                                                  '{}.wav'.format(sound_name))
            self.sounds[sound_name].set_volume(0.2)

        self.musicNotes = [
            mixer.Sound(SOUND_PATH + '{}.wav'.format(i)) for i in range(4)
        ]
        for sound in self.musicNotes:
            sound.set_volume(0.5)

        self.noteIndex = 0

    def play_main_music(self, currentTime):
        if currentTime - self.noteTimer > self.enemies.moveTime:
            self.note = self.musicNotes[self.noteIndex]
            if self.noteIndex < 3:
                self.noteIndex += 1
            else:
                self.noteIndex = 0

            self.note.play()
            self.noteTimer += self.enemies.moveTime

    @staticmethod
    def should_exit(evt):
        # type: (pygame.event.EventType) -> bool
        return evt.type == QUIT or (evt.type == KEYUP and evt.key == K_ESCAPE)

    def make_enemies(self):
        enemies = EnemiesGroup(10, 5)
        for row in range(5):
            for column in range(10):
                enemy = Enemy(row, column)
                enemy.rect.x = 157 + (column * 50)
                enemy.rect.y = self.enemyPosition + (row * 45)
                enemies.add(enemy)

        self.enemies = enemies

    def calculate_score(self, row):
        scores = {
            0: 30,
            1: 20,
            2: 20,
            3: 10,
            4: 10,
            5: choice([50, 100, 150, 300])
        }

        score = scores[row]
        self.score += score
        return score

    def create_main_menu(self):
        self.enemy1 = IMAGES['enemy3_1']
        self.enemy1 = transform.scale(self.enemy1, (40, 40))
        self.enemy2 = IMAGES['enemy2_2']
        self.enemy2 = transform.scale(self.enemy2, (40, 40))
        self.enemy3 = IMAGES['enemy1_2']
        self.enemy3 = transform.scale(self.enemy3, (40, 40))
        self.enemy4 = IMAGES['mystery']
        self.enemy4 = transform.scale(self.enemy4, (80, 40))
        self.screen.blit(self.enemy1, (318, 270))
        self.screen.blit(self.enemy2, (318, 320))
        self.screen.blit(self.enemy3, (318, 370))
        self.screen.blit(self.enemy4, (299, 420))

    def check_collisions(self):
        sprite.groupcollide(self.bullets, self.enemyBullets, True, True)

        for enemy in sprite.groupcollide(self.enemies, self.bullets, True,
                                         True).keys():
            self.sounds['invaderkilled'].play()
            self.calculate_score(enemy.row)
            EnemyExplosion(enemy, self.explosionsGroup)
            self.gameTimer = time.get_ticks()

        for mystery in sprite.groupcollide(self.mysteryGroup, self.bullets,
                                           True, True).keys():
            mystery.mysteryEntered.stop()
            self.sounds['mysterykilled'].play()
            score = self.calculate_score(mystery.row)
            MysteryExplosion(mystery, score, self.explosionsGroup)
            newShip = Mystery()
            self.allSprites.add(newShip)
            self.mysteryGroup.add(newShip)

        for player in sprite.groupcollide(self.playerGroup, self.enemyBullets,
                                          True, True).keys():
            if self.life3.alive():
                self.life3.kill()
            elif self.life2.alive():
                self.life2.kill()
            elif self.life1.alive():
                self.life1.kill()
            else:
                self.gameOver = True
                self.startGame = False
            self.sounds['shipexplosion'].play()
            ShipExplosion(player, self.explosionsGroup)
            self.makeNewShip = True
            self.shipTimer = time.get_ticks()
            self.shipAlive = False

        if self.enemies.bottom >= 540:
            sprite.groupcollide(self.enemies, self.playerGroup, True, True)
            if not self.player.alive() or self.enemies.bottom >= 600:
                self.gameOver = True
                self.startGame = False

        sprite.groupcollide(self.bullets, self.allBlockers, True, True)
        sprite.groupcollide(self.enemyBullets, self.allBlockers, True, True)
        if self.enemies.bottom >= BLOCKERS_POSITION:
            sprite.groupcollide(self.enemies, self.allBlockers, False, True)

    def create_new_ship(self, createShip, currentTime):
        if createShip and (currentTime - self.shipTimer > 900):
            self.player = Ship()
            self.allSprites.add(self.player)
            self.playerGroup.add(self.player)
            self.makeNewShip = False
            self.shipAlive = True

    def create_game_over(self, currentTime):
        self.screen.blit(self.background, (0, 0))
        passed = currentTime - self.timer
        if passed < 750:
            self.gameOverText.draw(self.screen)
        elif 750 < passed < 1500:
            self.screen.blit(self.background, (0, 0))
        elif 1500 < passed < 2250:
            self.gameOverText.draw(self.screen)
        elif 2250 < passed < 2750:
            self.screen.blit(self.background, (0, 0))
        elif passed > 3000:
            self.mainScreen = True

        for e in event.get():
            if self.should_exit(e):
                sys.exit()