def main(): rospy.init_node('mindwave') pub = rospy.Publisher('neuro', MindwaveValues, queue_size=100) rate = rospy.Rate(100) mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): while not rospy.is_shutdown(): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (dataPoint.__class__ is MeditationDataPoint): print(dataPoint.__class__) print(dataPoint) dic = dataPoint.__dict__ meditation = dic['meditationValue'] print(meditation) if (dataPoint.__class__ is AttentionDataPoint): print(dataPoint.__class__) print(dataPoint) dic = dataPoint.__dict__ attention = dic['attentionValue'] print(attention) send_values = MindwaveValues() send_values.meditation = meditation send_values.attention = attention pub.publish(send_values) rate.sleep() else: print( textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
def main(): configureLogger("WSO2IOT_RPiStats") UtilsThread() SubscribeToMQTTQueue( ) # connects and subscribes to an MQTT Queue that receives MQTT commands from the server mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): counter = 0 signalInfo = [0] * 11 while (True): try: dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): if (dataPoint.__class__ is EEGPowersDataPoint): signalInfo[2] = float(str(dataPoint.delta)), signalInfo[3] = dataPoint.theta, signalInfo[4] = dataPoint.lowAlpha, signalInfo[5] = dataPoint.highAlpha, signalInfo[6] = dataPoint.lowBeta, signalInfo[7] = dataPoint.highBeta, signalInfo[8] = dataPoint.lowGamma, signalInfo[9] = dataPoint.midGamma if (dataPoint.__class__ is AttentionDataPoint): signalInfo[0] = float(str(dataPoint).split(":")[1]) # TODO send command to virtual fire alarm after checking AttentionDataPointor or signalInfo[0] try: if (dataPoint.__class__ is PoorSignalLevelDataPoint): signalInfo[1] = float(str(dataPoint).split(":")[1]) except ValueError: print "200 - NO CONTACT TO SKIN" signalInfo[1] = 200 pass if (dataPoint.__class__ is MeditationDataPoint): # TODO send command to virtual fire alarm after checking MeditationDataPoint or signalInfo[10] signalInfo[10] = float(str(dataPoint).split(":")[1]) counter = counter + 1 if (counter == 4): counter = 0 currentTime = calendar.timegm(time.gmtime()) PUSH_DATA_BRAIN_WAVE_INFO = iotUtils.BRAIN_WAVE_INFO.format( currentTime, signalInfo[0], signalInfo[1], signalInfo[10], float(signalInfo[2][0]), float(signalInfo[3][0]), float(signalInfo[4][0]), float(signalInfo[5][0]), float(signalInfo[6][0]), float(signalInfo[7][0]), float(signalInfo[8][0]), float(signalInfo[8][0])) print '~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Devic-eData ~~~~~~~~~~~~~~~~~~~~~~~~~' print('PUBLISHED DATA: ' + PUSH_DATA_BRAIN_WAVE_INFO) print('PUBLISHED TOPIC: ' + mqttConnector.TOPIC_TO_PUBLISH_BRAIN_WAVE_INFO) mqttConnector.publish(PUSH_DATA_BRAIN_WAVE_INFO) except AssertionError: print('An error occurred while reading brain signal') pass else: print( textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
def mindwaveArray(self): output = { "delta": deque(maxlen=30), "theta": deque(maxlen=30), "lowAlpha": deque(maxlen=30), "highAlpha": deque(maxlen=30), "lowBeta": deque(maxlen=30), "highBeta": deque(maxlen=30), "lowGamma": deque(maxlen=30), "midGamma": deque(maxlen=30), } while not thread_stop_event.isSet(): mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if mindwaveDataPointReader.isConnected(): while True: dataPoint = mindwaveDataPointReader.readNextDataPoint() if dataPoint.__class__ is EEGPowersDataPoint: newData = dataPoint.__dict__ for k, v in newData.items(): if k in output.keys(): output[k].appendleft(v) prepData = copy.deepcopy(output) for k, v in prepData.items(): prepData[k] = list(v) socketio.emit( "newnumber", {"output": json.dumps(prepData)}, namespace="/test", ) else: output = "Could not connect to the Mindwave Mobile device, retrying ..." socketio.emit("newnumber", {"output": output}, namespace="/test") sleep(self.delay)
import time import bluetooth from mindwavemobile.MindwaveDataPoints import RawDataPoint from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader import textwrap if __name__ == '__main__': mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): while(True): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): print dataPoint else: print(textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
z = np.random.rand(100) li1, = ax.plot(x, y, color="b", linewidth=2.0) li2, = ax.plot(x, z, color="g") # draw and show it fig.canvas.draw() plt.show(block=False) # threshold value threshold = 100 mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() b = generate_bot() if (mindwaveDataPointReader.isConnected()): while (True): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): print dataPoint # print(dataPoint.__class__) if dataPoint.__class__.__name__ == "AttentionDataPoint": # print(dataPoint.__class__) if dataPoint.attentionValue > threshol: print('Threshold exceeed!') time.sleep(0.2) ## Wait move_forward(b, 100, 100) else: move_forward(b, 0, 0) y[:-10] = y[10:]
class SensorMSG(): def __init__(self, EEG=True, IMU=True, HEART=True): self.EEG_addr = EEG_addr self.EEG_queue = queue.Queue(maxsize=EEG_QUEUE_MAXSIZE) self.HEART_queue = queue.Queue(maxsize=HEART_QUEUE_MAXSIZE) self.IMU_queue = queue.Queue(maxsize=IMU_QUEUE_MAXSIZE) if (logmode): self.log_file = open("logfile.log", "a") self.log_file.write( dt.datetime.now().strftime("%m/%d/%Y, %H:%M:%S\n")) '''Enable sensors to work''' self.EEG_enable = EEG self.HEART_enable = HEART self.IMU_enable = IMU '''connection status''' self.EEG_status = False self.HEART_status = False self.IMU_status = False '''control execuion flags''' self.EEG_running = 0 self.HEART_running = 0 self.IMU_running = 0 self.SENDER_running = 0 '''last time update sensor''' self.EEG_t_last = dt.datetime.now() self.HEART_t_last = dt.datetime.now() self.IMU_t_last = dt.datetime.now() if (EEG): self.connect_EEG(self.EEG_addr) if (IMU): self.connect_IMU() if (HEART): self.connect_HEART() def print_log(self, str): print(str) self.log_file.write(dt.datetime.now().strftime("%H:%M:%S: ") + str + "\n") def connect_EEG(self, addr): self.print_log("[+] Try to connect") self.mindwaveDataPointReader = MindwaveDataPointReader(addr) while True: try: self.mindwaveDataPointReader.start() time.sleep(2) if (self.mindwaveDataPointReader.isConnected()): self.print_log("[+] Connected") self.EEG_status = True return self.EEG_status except: self.print_log("[-] Fail Connection") time.sleep(2) self.print_log("[+] retry...") def get_EEG(self): if (self.EEG_status): self.print_log("[+] getting EEG values: Status: " + str(self.EEG_status) + " Running: " + str(self.EEG_running)) dict = { 'Meditation': 0, 'Attention': 0, 'delta': '0', 'theta': '0', 'lowAlpha': '0', 'highAlpha': '0', 'lowBeta': '0', "highBeta": '0', 'lowGamma': '0', 'midGamma': '0', 'PoorSignalLevel': 0 } self.med_value = 0 self.at_value = 0 self.signal = 0 while (self.EEG_running): dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if (dataPoint.__class__ is dp.PoorSignalLevelDataPoint): poorSignalLevel = dataPoint.dict() dict.update(poorSignalLevel) elif (dataPoint.__class__ is dp.AttentionDataPoint): attention = dataPoint.dict() dict.update(attention) elif (dataPoint.__class__ is dp.MeditationDataPoint): meditation = dataPoint.dict() dict.update(meditation) elif (dataPoint.__class__ is dp.EEGPowersDataPoint): eegPowers = dataPoint.dict() dict.update(eegPowers) if (('delta' in dict) and ('PoorSignalLevel' in dict) and ('Meditation' in dict) and ('Attention' in dict)): if (not self.med_value == dict.get('Meditation') or not self.at_value == dict.get('Attention') or not self.signal == dict.get('PoorSignalLevel')): print(dict) self.med_value = int(dict.get('Meditation')) self.at_value = int(dict.get('Attention')) self.signal = int(dict.get('PoorSignalLevel')) self.EEG_queue.put( [self.med_value, self.at_value, self.signal]) self.EEG_t_last = dt.datetime.now() if (self.EEG_running == -1): print("EEG_paused") time.sleep(.5) def start_EEG(self): if (not self.EEG_status): self.print_log('[-] EEG sensor not connected') else: self.EEG_running = 1 threading.Thread(target=self.get_EEG, args=()).start() def pause_EEG(self): self.print_log("[+] Pause EEG") self.EEG_running = -1 def continue_EEG(self): self.print_log("[+] Continue EEG") self.EEG_running = 1 def stop_EEG(self): self.print_log("[+] Stop EEG") self.EEG_running = 0 def connect_IMU(self): self.IMU_status = True if (not debug_mock): mpu9250 = FaBo9Axis_MPU9250.MPU9250() self.print_log("[+]MPU9250 conected") else: self.print_log("[!]MPU9250 mocking mode") def get_IMU(self): while (self.IMU_running): if (self.IMU_running == 1): if (not debug_mock): self.accel = mpu9250.readAccel() self.gyro = mpu9250.readGyro() self.mag = mpu9250.readMagnet() else: self.accel = { 'x': randrange(-2, 2), 'y': randrange(-2, 2), 'z': randrange(-2, 2) } self.gyro = { 'x': randrange(-180, 180, 5), 'y': randrange(-180, 180, 5), 'z': randrange(-180, 180, 5) } self.mag = { 'x': randrange(-180, 180, 5), 'y': randrange(-180, 180, 5), 'z': randrange(-180, 180, 5) } self.IMU_queue.put([ self.accel['x'], self.accel['y'], self.accel['z'], self.gyro['x'], self.gyro['y'], self.gyro['z'], self.mag['x'], self.mag['y'], self.mag['z'] ]) time.sleep(0.2) elif (self.IMU_running == -1): print("IMU_paused") time.sleep(.5) def start_IMU(self): if (not self.IMU_status): self.print_log('[-] IMU sensor not connected') else: self.IMU_running = 1 threading.Thread(target=self.get_IMU, args=()).start() def pause_IMU(self): self.print_log("[+] Pause IMU") self.IMU_running = -1 def continue_IMU(self): self.print_log("[+] Continue IMU") self.IMU_running = 1 def stop_IMU(self): self.print_log("[+] Stop IMU") self.IMU_running = 0 def connect_HEART(self): self.HEART_status = True if (not debug_mock): self.heart_sensor = max30102.MAX30102() self.print_log("[+]MAX30102 conected") else: self.print_log("[!]MPU9250 mocking mode") def display_heartrate(beat, bpm, avg_bpm): pass def start_OSC_sender(self): self.client = udp_client.SimpleUDPClient(IP, PORT) self.SENDER_running = 1 while (self.SENDER_running): if (self.EEG_enable == 1 and not self.EEG_queue.empty()): self.print_log("send_EEG") self.client.send_message("/EEG", self.EEG_queue.get()) if (self.IMU_enable == 1 and not self.IMU_queue.empty()): self.print_log("send_IMU") print(self.IMU_queue.get()) self.client.send_message("/IMU", self.IMU_queue.get()) def stop_OSC_sender(self): self.SENDER_running = 0 pass def end_file(self): if (logmode): self.log_file.close()
def main(): #Default setting macaddr = "" spi_ch = 0 sensor_ch = 0 pNNx = 50 npNN = 30 nBPM = 10 #Load configuration file try: settingFile = open("setting.txt", "r") print('Fond setting file') tmp = settingFile.readlines() settingFile.close() for line in tmp: line = line.strip() if line[0] == '#' or line[0] == '': continue else: cmd = line.split(':') if cmd[0].lower() == 'macaddr': macaddr = cmd[1].strip() elif cmd[0].lower() == 'spi-ch': spi_ch = int(cmd[1].strip()) elif cmd[0].lower() == 'pulse-ch': sensor_ch = int(cmd[1].strip()) elif cmd[0].lower() == 'pnnx': pNNx = int(cmd[1].strip()) elif cmd[0].lower() == 'n-pnnx': npNN = int(cmd[1].strip()) elif cmd[0].lower() == 'n-bpm': nBPM = int(cmd[1].strip()) else: print('Unknown setting', cmd[0]) except: print('File not found, use default setting') newFlag = BOOL(False) global threadRun IBI = PULSEIBI(size=npNN, pNNx=pNNx) queue = QUEUE() rawpulse = RAWPULSE(length=3, diff=-0.002) rawpulse_size = rawpulse.size() ThreadStarted = 0 raw_emotion = np.zeros( (8) ) #[happy,excite,surprise,strain,sad,ennui,calm,sleep] -> 'pleasure','excite','arouse','distress','misery','depress','sleep','content' percent_emotion = [0] * 8 percent_min_emotion = [0] * 8 #Prepare for multiprocessing, plot graph global ctype_threadRun ctype_percent_emotion = multiprocessing.Array('d', [0] * 8) ctype_oneMinEmo = multiprocessing.Array('d', [0] * 8) ctype_rawpulse = multiprocessing.Array('i', [0] * rawpulse_size) ctype_rawpulse_label = multiprocessing.Array('d', rawpulse.label()) bpm = IBI.BPM() if bpm is None: ctype_bpm = multiprocessing.Value('i', 0) else: ctype_bpm = multiprocessing.Value('i', bpm) multi_cond = multiprocessing.Condition() bv_condition = threading.Condition() #Try to connect to the predefined device print("Main program is started on PID", os.getpid()) try: pl = threading.Thread(target=pulse.pulsePNN, name="Pulse sensor reader", args=(spi_ch, sensor_ch, threadRun, IBI, rawpulse)) pl.daemon = True pl.start() ThreadStarted = 1 print("Reading pulse sensor thread is started") except: e = sys.exc_info()[0] print("Can not start the pulse sensor reader thread", e) threadRun.stop() ctype_threadRun.value = 0 return try: pt = multiprocessing.Process(target=plotGraph, name="Graph plotter", args=(ctype_threadRun, multi_cond, ctype_percent_emotion, ctype_oneMinEmo, ctype_rawpulse, ctype_rawpulse_label, ctype_bpm)) pt.daemon = True pt.start() ThreadStarted = 2 print("Plotting process is started") #Tflag = True except: e = sys.exc_info()[0] print("Can not start the plotting process", e) threadRun.stop() ctype_threadRun.value = 0 return if macaddr != '': mindwaveDataPointReader = MindwaveDataPointReader("20:68:9D:3F:4F:88") mindwaveDataPointReader.start() if (not mindwaveDataPointReader.isConnected()): print("Find another device...") mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() else: print("Searching for device") mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): print('Connected to', mindwaveDataPointReader.mac()) try: mv = threading.Thread(target=getSignal, name="mind wave reader", args=(mindwaveDataPointReader, bv_condition, threadRun, newFlag, queue, IBI)) mv.daemon = True mv.start() ThreadStarted = 3 print("Reading mind wave thread is started!") #Tflag = True except: e = sys.exc_info()[0] print("Can not start the mind wave reader thread", e) threadRun.stop() ctype_threadRun.value = 0 return #while threadRun.status(): start = datetime.now() oneMinEmo = CIR_ARRAY(60) this_emotion = np.empty((8)) while threadRun: #Critical section with bv_condition: #bv_condition.acquire() while not newFlag: bv_condition.wait() if not threadRun: break #print queue.getAll() qData = queue.getAll() #[poorSignal,meditaton,attention,BPM,pNN50] now = datetime.now() newFlag.false() #print('QLEN:',len(qData)) #print ('\n\tC-RELE') #bv_condition.release() #End of Critical section #The computation unit starts here! updateFlag = False for data in qData: if data[4] is not None and data[0] < 50: arousal = data[1] - data[ 2] #Equivalent to kakusei in Tanaka's work updateFlag = True if data[4] < 0.3: pleasure = -100 * (data[4] / 0.3) else: pleasure = 100 * (data[4] - 0.3) / 0.7 angle = math.degrees(math.atan2(arousal, pleasure)) if angle < 0: angle += 360 elif angle >= 360: angle -= 360 if angle < 0 or angle > 360: print( 'Unexpected error on angle, stopping for 10 seconds' ) time.sleep(10) # OLD 'happy','excite','surprise','strain','sad','ennui','calm','sleep' # NEW 'pleasure','excite','arouse','distress','misery','depress','sleep','content' #emotion classification this_emotion[:] = 0 ''' if angle < 45: #angle between 0 - 44 raw_emotion[0] += 1 raw_emotion[1] += 1 this_emotion[0] += 1 this_emotion[1] += 1 elif angle < 90: #angle between 45 - 89 raw_emotion[2] += 1 raw_emotion[1] += 1 this_emotion[2] += 1 this_emotion[1] += 1 elif angle < 135: #angle between 90 - 134 raw_emotion[2] += 1 raw_emotion[3] += 1 this_emotion[2] += 1 this_emotion[3] += 1 elif angle < 180: #angle between 135 - 179 raw_emotion[4] += 1 raw_emotion[3] += 1 this_emotion[4] += 1 this_emotion[3] += 1 elif angle < 225: #angle between 180 - 224 raw_emotion[4] += 1 raw_emotion[5] += 1 this_emotion[4] += 1 this_emotion[5] += 1 elif angle < 270: #angle between 225 - 269 raw_emotion[7] += 1 raw_emotion[5] += 1 this_emotion[7] += 1 this_emotion[5] += 1 elif angle < 315: #angle between 270 - 314 raw_emotion[7] += 1 raw_emotion[6] += 1 this_emotion[7] += 1 this_emotion[6] += 1 else: #angle between 315 - 359 raw_emotion[0] += 1 raw_emotion[6] += 1 this_emotion[0] += 1 this_emotion[6] += 1 ''' if angle < 45: #pleasure - excite #angle between 0 - 44 emotionB = angle / 45.0 emotionA = 1 - emotionB raw_emotion[0] += emotionA raw_emotion[1] += emotionB this_emotion[0] += emotionA this_emotion[1] += emotionB elif angle < 90: #excite - arouse #angle between 45 - 89 emotionB = (angle - 45.0) / 45.0 emotionA = 1 - emotionB raw_emotion[1] += emotionA raw_emotion[2] += emotionB this_emotion[1] += emotionA this_emotion[2] += emotionB elif angle < 135: #arouse - distress #angle between 90 - 134 emotionB = (angle - 90.0) / 45.0 emotionA = 1 - emotionB raw_emotion[2] += emotionA raw_emotion[3] += emotionB this_emotion[2] += emotionA this_emotion[3] += emotionB elif angle < 180: #distress - misery #angle between 135 - 179 emotionB = (angle - 135.0) / 45.0 emotionA = 1 - emotionB raw_emotion[3] += emotionA raw_emotion[4] += emotionB this_emotion[3] += emotionA this_emotion[4] += emotionB elif angle < 225: #misery - depress #angle between 180 - 224 emotionB = (angle - 180.0) / 45.0 emotionA = 1 - emotionB raw_emotion[4] += emotionA raw_emotion[5] += emotionB this_emotion[4] += emotionA this_emotion[5] += emotionB elif angle < 270: #depress - sleep #angle between 225 - 269 emotionB = (angle - 225.0) / 45.0 emotionA = 1 - emotionB raw_emotion[5] += emotionA raw_emotion[6] += emotionB this_emotion[5] += emotionA this_emotion[6] += emotionB elif angle < 315: #sleep - content #angle between 270 - 314 emotionB = (angle - 270.0) / 45.0 emotionA = 1 - emotionB raw_emotion[6] += emotionA raw_emotion[7] += emotionB this_emotion[6] += emotionA this_emotion[7] += emotionB else: #content - pleasure #angle between 315 - 360 emotionB = (angle - 315.0) / 45.0 emotionA = 1 - emotionB raw_emotion[7] += emotionA raw_emotion[0] += emotionB this_emotion[7] += emotionA this_emotion[0] += emotionB print('emotion: ', raw_emotion, round(data[4], 2), angle) oneMinEmo.put(this_emotion) else: oneMinEmo.put([0, 0, 0, 0, 0, 0, 0, 0]) #Updating the graph if updateFlag: #Calculate the graph raw_sum = raw_emotion.sum() if raw_sum != 0: percent_emotion[:] = raw_emotion * (100 / raw_emotion.sum()) else: percent_emotion[:] = [0] * 8 #Calculate the one min graph oneMin = oneMinEmo.get() oneMin_raw = np.array([sum(x) for x in zip(*oneMin)]) oneMin_sum = sum(oneMin_raw) if oneMin_sum != 0: factor = 100.0 / oneMin_sum percent_min_emotion[:] = oneMin_raw * (100.0 / oneMin_sum) else: percent_min_emotion[:] = [0] * 8 with multi_cond: ctype_percent_emotion[:] = percent_emotion ctype_oneMinEmo[:] = percent_min_emotion ctype_rawpulse[:] = rawpulse.get() bpm = IBI.BPM(nBPM) if bpm is None: ctype_bpm.value = 0 else: ctype_bpm.value = int(round(bpm)) multi_cond.notify() with multi_cond: multi_cond.notify() mindwaveDataPointReader.close() if ThreadStarted == 1: if pl.is_alive(): pl.join(5) print("1 Child thread are successfully closed") elif ThreadStarted == 2: if pl.is_alive(): pl.join(5) if pt.is_alive(): pt.join(5) print("2 Child thread are successfully closed") elif ThreadStarted == 3: if pl.is_alive(): pl.join(5) if mv.is_alive(): mv.join(5) if pt.is_alive(): pt.join(10) print("3 Child thread are successfully closed") sys.exit(0)
import time from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader as reader from mindwavemobile.MindwaveDataPoints import * if __name__ == '__main__': data_list = [] temp = 0 med = 0 att = 0 f = open("data.txt", 'w') reader = reader() reader.start() if (reader.isConnected()): while True: data = reader.readNextDataPoint() if (data.__class__ is MeditationDataPoint): med = data.meditationValue temp = time.time() elif(data.__class__ is AttentionDataPoint): att = data.attentionValue unit = [temp, med, att] data_list.append(unit) print(unit) f.write(str(unit) + '\n') f.flush() f.close() else: print("device disconnected")