Esempio n. 1
0
def start_data_collection(serial_port, num_seconds=-1):
    headset_obj = NP.NeuroPy(serial_port, 9600, log=False)

    headset_obj.setCallBack("attention", generic_callback)
    headset_obj.setCallBack("meditation", generic_callback)
    headset_obj.setCallBack("rawValue", generic_callback)
    headset_obj.setCallBack("delta", generic_callback)
    headset_obj.setCallBack("theta", generic_callback)
    headset_obj.setCallBack("lowAlpha", generic_callback)
    headset_obj.setCallBack("highAlpha", generic_callback)
    headset_obj.setCallBack("lowBeta", generic_callback)
    headset_obj.setCallBack("highBeta", generic_callback)
    headset_obj.setCallBack("lowGamma", generic_callback)
    headset_obj.setCallBack("midGamma", generic_callback)
    headset_obj.setCallBack("poorSignal", generic_callback)
    headset_obj.setCallBack("blinkStrength", generic_callback)

    headset_obj.start()
    if num_seconds != -1:
        time.sleep(num_seconds)
        headset_obj.stop()

    if num_seconds != -1:
        time.sleep(num_seconds)
        headset_obj.stop()
Esempio n. 2
0
 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()
Esempio n. 3
0
def startBCI():
    object1=NeuroPy("COM6") 
    #set call back:
    object1.setCallBack("attention",attention_callback)
    
    #start method
    object1.start()
    return None
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()
Esempio n. 5
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()
Esempio n. 6
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()
Esempio n. 7
0
# -*- coding: utf-8 -*-
from NeuroPy import NeuroPy
from time import sleep
import threading
from api_service import *

neuropy = NeuroPy("COM4")  # type: NeuroPy
#neuropy = NeuroPy("/dev/rfcomm0",57600)  # type: NeuroPy


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)
    return 0


def meditation_callback(meditation_value):
    """this function will be called everytime NeuroPy has a new value for attention"""
    print("Value of meditation is: ", meditation_value)
    return 1


def rawValue_callback(rawValue_value):
    """this function will be called everytime NeuroPy has a new value for attention"""
    # print ("Value of rawValue is: ", rawValue_value)
    return 2


def delta_callback(delta_value):
    """this function will be called everytime NeuroPy has a new value for attention"""
    print("Value of delta is: ", delta_value)
Esempio n. 8
0
from NeuroPy import NeuroPy
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation

neuropy = NeuroPy("COM3")  # Specify COM Port
neuropy.start()

fig = plt.figure()
t = 0

meditation = []

x_time = []

print("=============================")


def animate(i):
    global t
    global meditation

    if t == 300:  # preset: 300(sec)

        con = input("Continue (Y/N)? ")

        if con == 'N':
            with open('BrainWave/BrainWave.csv', 'w') as w:
                meditation = str(meditation)
                meditation = meditation.split()
                for i in range(len(meditation)):
'''
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)
Esempio n. 10
0
    rowdata.append(hset.rawValue)
    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)
Esempio n. 11
0
from NeuroPy import NeuroPy
import time
import socket
import sys

eyesOption = ['eyes_open', 'eyes_closed']
alphaOption = ['lowAlpha', 'highAlpha']

object1 = NeuroPy("COM3")  #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
'''


#for each callback, store value into textfile
def highalpha_callback(highAlpha_value):
    print "Value of highAlpha is ", highAlpha_value

    file_name = str(eyesOption[0]) + '-' + str(alphaOption[1])
    with open(file_name, 'a') as f:
        f.write(str(highAlpha_value) + '\n')


def lowalpha_callback(lowAlpha_value):
    print "Value of lowAlpha is ", lowAlpha_value
Esempio n. 12
0
from NeuroPy import NeuroPy
from time import sleep
import csv
from subprocess import call
import sys
poorcnter = 0
val = 0
cnter = 0
qwe = 0
arr = [0.000] * 2048
object1 = NeuroPy("COM28")


# with open('dataset5.csv', 'wb') as f:
# writer = csv.writer(f)
def attention_callback(attention_value):
    global poorcnter
    if (poorcnter == 0):
        if (object1.poorSignal != 0):
            poorcnter = 1
            print("started taking data")
    else:
        if (object1.attention >= 15 and object1.meditation >= 15
                and object1.poorSignal == 0 and attention_value < 30000):
            global cnter
            cnter += 1
            for i in range(len(arr) - 1):
                arr[i] = arr[i + 1]
            arr[2047] = attention_value
            if (cnter == 2048):
                global qwe
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()
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
Esempio n. 15
0
import csv
from subprocess import call
import sys
import time
ts = time.strftime("%I%M%S")
val = 0
val2 = 0
val3 = 0
cnter = 0
cnter2 = 0
cnter3 = 0
qwe = 0
arr = [0.000] * 512
arr2 = [0.000] * 1024
arr3 = [0.000] * 2048
object1 = NeuroPy("COM5")
# with open('dataset5.csv', 'wb') as f:
# writer = csv.writer(f)


def attention_callback(attention_value):
    if (object1.attention >= 10 and object1.meditation >= 10
            and object1.poorSignal == 0 and attention_value < 30000):
        global cnter
        global cnter2
        global cnter3
        cnter += 1
        cnter2 += 1
        cnter3 += 1
        for i in range(len(arr) - 1):
            arr[i] = arr[i + 1]
 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()
# Connect to Mindwave to computer first
# Call neuropy.start() to get data.
# Neuropy.stop() to stop
from NeuroPy import NeuroPy
import numpy as np
import matplotlib.pyplot as plt
import mindwave, time

neuropy = NeuroPy()
neuropy.start()

then = time.time()
now = time.time()

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

#connects the path(usb) and the specific serial number of your mindwave
headset = mindwave.Headset('COM5', 'CC0E')
time.sleep(2)

#connecting the mindwave
headset.connect()
print("Pairing...")

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

def predict(model, scl, inpt):
    inpt = inpt.reshape(1, -1)
    inpt = scl.transform(inpt)
    inpt = torch.FloatTensor(inpt)
    out = model(inpt)
    y_test_pred = torch.sigmoid(out)
    y_pred_tag = torch.round(y_test_pred)

    return y_pred_tag.item()


model, scaler = load_model('model_no_jump_hist40.pth',
                           'scaler_no_jump_hist40.scl')
neuropy = mp.NeuroPy(port='COM4')
results = Attrdict()


def set_callback(neuropy, name, print_result=False, function=None):
    def default_function(value):
        results[name] = value
        if print_result:
            print(name, value)

    results[name] = 0
    selected_function = function if function else default_function
    neuropy.setCallBack(name, selected_function)


is_pressed_manually = False
Esempio n. 19
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()
Esempio n. 20
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))
Esempio n. 21
0
class MyWin(QtWidgets.QMainWindow):
    started = False
    ncolors = 256
    colors_by_att = False
    MindWave_obj = NeuroPy("COM3")
    cam = cv2.VideoCapture()
    pwidth, pheight = 0, 0
    pil_img = Image.init()
    pixmap = QtGui.QPixmap

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Color levels | PyQt | OpenCV | NeuroSky MindWave")
        self.setGeometry(400, 100, 1241, 820)
        self.ui.pushButton_3.clicked.connect(self.Ext)
        self.ui.pushButton_4.clicked.connect(self.loadImage)
        self.ui.pushButton_5.clicked.connect(self.saveImage)
        self.ui.horizontalSlider.setValue(self.ncolors)
        self.ui.horizontalSlider.valueChanged.connect(self.colorsChanged)
        self.ui.checkBox.stateChanged.connect(self.colorsModeChanged)
        self.ui.checkBox_2.stateChanged.connect(self.cameraModeChanged)
        self.pwidth = self.ui.label.width()
        self.pheight = self.ui.label.height()
        self.pil_img = Image.open("eye.jpg")
        self.pixmap = QtGui.QPixmap.fromImage(
            self.pilImgToQImg_resized(self.pil_img))
        self.ui.label.setPixmap(self.pixmap)
        if not self.MindWave_obj.threadRun:
            try:
                self.MindWave_obj.start()
                self.statusBar().showMessage(" === MindWave connected! === ")
            except:
                self.statusBar().showMessage(
                    " === Connection to MindWave failed! === ")

    def pilImgToQImg_resized(self, pilimg):
        """	convert Pillow Image to QImage and resize choosen image to window area """
        ocvimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
        dim = (self.pwidth, self.pheight)
        resized = cv2.resize(ocvimg, dim, interpolation=cv2.INTER_AREA)
        self.pil_img = Image.fromarray(cv2.cvtColor(resized,
                                                    cv2.COLOR_BGR2RGB))
        return QtGui.QImage(resized, resized.shape[1], resized.shape[0],
                            resized.shape[1] * 3,
                            QtGui.QImage.Format_RGB888).rgbSwapped()

    def saveImage(self):
        """ save current transformation of image to file """
        fileName, _ = QFileDialog.getSaveFileName(
            self, "QFileDialog.getSaveeFileName()", "",
            "Image Files (*.jpg *.png *.bmp)")
        if fileName:
            self.pixmap.save(fileName)

    def loadImage(self):
        """ load image from file """
        fileName, _ = QFileDialog.getOpenFileName(
            self, "QFileDialog.getOpenFileName()", "",
            "Image Files (*.jpg *.png *.bmp)")
        if fileName:
            self.pil_img = Image.open(fileName)
            self.pixmap = QtGui.QPixmap.fromImage(
                self.pilImgToQImg_resized(self.pil_img))
            self.ui.label.setPixmap(self.pixmap)

    def cameraModeChanged(self):
        """	turn on / off camera input """
        if not self.cam.isOpened():
            self.cam.open(0)
            self.started = True
        else:
            self.started = False
            self.cam.release()

    def colorsModeChanged(self):
        """ turn on / off color levels dependency on attention level (obtained from EEG device) """
        self.colors_by_att = not self.colors_by_att

    def colorsChanged(self):
        """ processing change of color levels """
        self.ncolors = self.ui.horizontalSlider.value()
        self.ui.progressBar.setValue(self.MindWave_obj.attention)
        self.ui.label_3.setText("COLOR LEVELS: " + str(self.ncolors))
        if not self.started:
            t_pil_img = self.pil_img.convert(
                'P', palette=Image.ADAPTIVE,
                colors=self.ncolors).convert('RGB')
            im = t_pil_img.convert("RGBA")
            data = im.tobytes("raw", "RGBA")
            qim = QtGui.QImage(data, im.size[0], im.size[1],
                               QtGui.QImage.Format_RGBA8888)
            self.pixmap = QtGui.QPixmap.fromImage(qim)
            self.ui.label.setPixmap(self.pixmap)

    def update_flow(self):
        """ update attention value and processing camera input for transformation """
        self.ui.progressBar.setValue(self.MindWave_obj.attention)
        if self.started:
            ret, frame = self.cam.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            t_pil_img = Image.fromarray(frame)
            t_pil_img = t_pil_img.convert('P',
                                          palette=Image.ADAPTIVE,
                                          colors=self.ncolors).convert('RGB')
            im = t_pil_img.convert("RGBA")
            data = im.tobytes("raw", "RGBA")
            qim = QtGui.QImage(data, im.size[0], im.size[1],
                               QtGui.QImage.Format_RGBA8888)
            self.pixmap = QtGui.QPixmap.fromImage(qim).scaled(
                self.pwidth, self.pheight, QtCore.Qt.IgnoreAspectRatio)
            self.ui.label.setPixmap(self.pixmap)

        if self.MindWave_obj.attention > 0:
            if self.colors_by_att:
                self.ncolors = self.MindWave_obj.attention
                self.ui.horizontalSlider.setValue(self.ncolors)

    def Ext(self):
        """ exit the application """
        sys.exit()
Esempio n. 22
0
from NeuroPy import NeuroPy
from time import sleep
import serial

neuropy = NeuroPy(port='/dev/tty.MindWaveMobile-SerialPo') 

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
    return None

neuropy.setCallBack("attention", attention_callback)

# neuropy.__srl = serial.Serial(
#                    '/dev/tty.MindWaveMobile-SerialPo', 57600)

#neuropy.__srl.flushInput()

neuropy.start()

print('Sleeping for 10 seconds')

sleep(10)

try:
    while True:
        sleep(1)
finally:
    neuropy.stop()
Esempio n. 23
0
class neural():
    data2 = pd.read_csv('dataset4.csv',
                        names=['att', 'med', 'poo', 'rawValue', 'label'])
    X_test = data2.rawValue.tolist()
    # plot 4 images as gray scale
    tsts2 = []
    for i in range(len(X_test)):
        temp = literal_eval(X_test[i])
        temp2 = np.array(temp)
        tsts2.append(temp2)
    X_test = np.array(tsts2)
    X_test = X_test.reshape(len(X_test), 1, 8)

    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights("model.h5")
    print("Loaded model from disk")

    # evaluate loaded model on test data
    loaded_model.compile(loss='categorical_crossentropy',
                         optimizer='adam',
                         metrics=['accuracy'])
    sleep(1)
    print("taking input started")
    object1 = NeuroPy("COM11")

    def attention_callback(attention_value):
        win = GraphWin('Face', 200, 150)  # give title and dimensions
        win.yUp()  # make right side up coordinates!

        head = Circle(Point(40, 100), 25)  # set center and radius
        head.setFill("yellow")
        head.draw(win)

        if (object1.attention >= 5 and object1.meditation >= 5):
            print(object1.poorSignal)
            temp = [
                object1.delta, object1.theta, object1.lowAlpha,
                object1.highAlpha, object1.lowBeta, object1.highBeta,
                object1.lowGamma, object1.midGamma
            ]
            #with open('dataset3.csv', 'ab') as f:
            #writer = csv.writer(f)
            #writer.writerow([object1.attention, object1.meditation, object1.poorSignal, temp, 0])
            temp2 = [temp]
            temp2 = np.array(temp2)
            temp2 = temp2.reshape(len(temp2), 1, 8)
            ynew = loaded_model.predict_proba(temp2)
            print("X=%s, Predicted=%s" % (temp2, ynew))
            if (ynew[0][0] > 0.69):
                print("left")
                eye1 = Circle(Point(30, 105), 5)
                eye1.setFill('blue')
                eye1.draw(win)
            if (ynew[0][1] > 0.69):
                print("right")
                eye2 = Line(Point(45, 105), Point(55, 105))  # set endpoints
                eye2.setWidth(3)
                eye2.draw(win)

        return None

    #set call back:
    object1.setCallBack("delta", attention_callback)
    #call start method
    object1.start()

    while True:
        if (
                object1.meditation > 100
        ):  #another way of accessing data provided by headset (1st being call backs)
            print("geda meditationg too much")
            #object1.stop() #if meditation level reaches above 70, stop fetching data from the headset
Esempio n. 24
0
from NeuroPy import NeuroPy
from time import sleep

neuropy = NeuroPy("COM4")
neuropy.start()

while True:
    if neuropy.meditation > 70:  # Access data through object
        neuropy.stop()
    sleep(0.2)  # Don't eat the CPU cycles
Esempio n. 25
0


json_file = open('model4.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model4.h5")
print("Loaded model from disk")
 
# evaluate loaded model on test data
loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
sleep(1)
print("taking input started")
object1=NeuroPy("COM15")
count=0
count0=0
count1=0
val=0
cnter=0
qwe=0
arrdelta=[0.000]*8
arrtheta=[0.000]*8
arrloalpha=[0.000]*8
arrhialpha=[0.000]*8
arrlobeta=[0.000]*8
arrhibeta=[0.000]*8
arrlogamma=[0.000]*8
arrmidgamma=[0.000]*8
def attention_callback(attention_value):
Esempio n. 26
0
from NeuroPy import NeuroPy
from time import sleep
from threading import Timer


def end_reading():
    file_at.close()
    # file_me.close()
    # file_bl.close()
    neuropy.stop()


neuropy = NeuroPy('COM4')
neuropy.start()
t = Timer(10.0, end_reading)
file_at = open('data-bl.txt', 'w')
t.start()

while True:
    file_at.write(str(neuropy.blink))
    file_at.write('\n')
    sleep(0.2)
Esempio n. 27
0
__author__ = "Shivam Shekhar, edited by COGS 189 Group!"

import os
import sys
import pygame
import random
from pygame import *
from time import sleep
from NeuroPy import NeuroPy

neuropy = NeuroPy("COM3")
data = []

pygame.init()

scr_size = (width, height) = (600, 150)
FPS = 60
gravity = 0.6

black = (0, 0, 0)
white = (255, 255, 255)
background_col = (235, 235, 235)

high_score = 0

screen = pygame.display.set_mode(scr_size)
clock = pygame.time.Clock()
pygame.display.set_caption("T-Rex Rush")

jump_sound = pygame.mixer.Sound('sprites/jump.wav')
die_sound = pygame.mixer.Sound('sprites/die.wav')
Esempio n. 28
0
from NeuroPy import NeuroPy
from time import sleep
import csv
from subprocess import call
import sys

val = 0
cnter = 0
qwe = 0
arr = [0.000] * 2048
object1 = NeuroPy("COM22")
# with open('dataset5.csv', 'wb') as f:
# writer = csv.writer(f)


def attention_callback(attention_value):
    if (object1.attention >= 15 and object1.meditation >= 15
            and object1.poorSignal == 0 and attention_value < 30000):
        global cnter
        cnter += 1
        for i in range(len(arr) - 1):
            arr[i] = arr[i + 1]
        arr[2047] = attention_value
        if (cnter == 2048):
            global qwe
            global val
            # if(qwe==0):
            # qwe=1
            # val=input("(0 for red 1 for green 2 for black and 3 for yellow)")
            # cnter=0
            # return None
Esempio n. 29
0
import pyautogui as pi
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):
Esempio n. 30
0
def PostRequest(request_body):
    # 构造服务接口地址
    url = 'http://localhost:{0}/'.format(6000)
    r0 = requests.post(url=url, json=request_body)
    # print(r0.json())


pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

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