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 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)
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", " "))
class RunMWM(threading.Thread): def __init__(self): #self._target = target #self._args = args self.isRunning = True threading.Thread.__init__(self) self._eegpower = deque() self.mindwaveDataPointReader=None #def run(self): # self._target(*self._args) def connectMWM(self, target_address): """ make the MWM connection """ print "Connecting to MWM...", try: self.mindwaveDataPointReader = MindwaveDataPointReader(target_address) self.mindwaveDataPointReader.start() # connect to the mindwave mobile headset except IOError as e: print e print "Couldn't connect to MWM device. Check address? Is it turned on?"; raise e print " connected" def run(self): """ run a while loop to capture data and push it into a queue """ while(self.isRunning): dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if dataPoint.__class__ is PoorSignalLevelDataPoint: count=0 if not dataPoint.headSetHasContactToSkin(): #chek the first one, and if no contact, loop until dies count+=1 dataPoint = mindwaveDataPointReader.readNextDataPoint() print "waiting for signal quality" while(not dataPoint.headSetHasContactToSkin() or count>10000): count+=1 dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if count>10000: print "No contact, quitting" raise ValueError("no EEG contact") else: print "Contact detected" elif (dataPoint.__class__ is EEGPowersDataPoint): eegpower = np.log(dataPoint.asList()) / np.log(float(dataPoint.maxint)) data = {'brain':eegpower, 'timestamp': time.time()} with lock: eegpower_buffer.append(data) #append to global queue print "alphaH {0} --> {1:1.4f} at {2}".format(dataPoint.highAlpha, data['brain'][3], data['timestamp']) print "\n" mindwaveDataPointReader.close() print "Closed MWM session."
def read(queue, mwm_pipeend, display_freq, episode_duration): #used for data acquisition timing counter = 0 record_times = [] #mwm collects data at approximately 512 Hz. Can vary though. That's why we need the trim. trim_size = (episode_duration - .4) * 508 print("episode_duration:", episode_duration) episode_data = [] #creates a new mindwave mobile object mwm_reader = MindwaveDataPointReader() mwm_reader.start() #finds the start signal while True: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("Start sequence received, signaling animation...") #once the start command is received from the mwm, the start signal is sent through the pipe to the animation process mwm_pipeend.send([True]) break epi_type = mwm_pipeend.recv()[0] print("\tCommencing data acquisition at", time.time()) #for as long as the episode is happening, read data from mwm. For some reason, mwm closes too late. Need early stopping #that's why I subtract .4 seconds from the end_time here end_time = (time.time() + episode_duration - .4) - .1 while time.time() < end_time: data_point = mwm_reader.readNextDataPoint() if (data_point.__class__ is RawDataPoint): episode_data.append(data_point._readRawValue()) if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 240): l = np.average(np.diff(record_times)) print("\t\tmwm:", 1 / l, "Hz") record_times = [] counter = 0 print("\tClosing mwm stream at", time.time()) #get the episode type from the environment # print("trimming ", len(episode_data) - int(trim_size), "readings") # trim the episode data so it's always a constant length print("trimming:", len(episode_data) - trim_size) episode_data = episode_data[:int(trim_size)] episode_data_df = pd.DataFrame().append([episode_data]) episode_data_df['episode_type'] = np.array([epi_type]) #close and delete mwm mwm_reader.end() del mwm_reader #when the episode is finished, the data gathered by the recorder device is accessed and placed in the queue so the parent process can obtain it queue.put(episode_data_df)
class BrainWaveSource(Source): def __init__(self): Source.__init__(self, self.get_dict().next) self.logger = logging.getLogger('bws') self.mindwaveDataPointReader = MindwaveDataPointReader() self.mindwaveDataPointReader.start() self.finished = False self.initialized = False self.started = False def get_dict(self): "Synchronous (!) method to get the next set of brainwave measurements from the sensor" while True: builder = MeasurementBuilder() self.logger.debug('have builder') self.finished = False while not self.finished: datapoint = self.mindwaveDataPointReader.readNextDataPoint() self.logger.debug('datapoint read') builder.add_measurement(datapoint) self.logger.debug('measurement added') if builder.is_finished(): self.logger.debug('finished building') measurement = builder.get_dict() self.finished = True if not self.initialized: self.logger.debug("Not yet initialized") if not measurement['meta']['noise'] == 25: self.initialized = True else: yield measurement def select(self, selector): return Transformer([self], {self.getName(): 'd'}, lambda d: d and d[selector]) def start(self): self.started = True parent = self def internal(): while parent.started: if parent.finished: parent.push() time.sleep(1) else: time.sleep(0.1) self.t = Thread(target=internal) self.t.daemon = True self.t.start() def stop(self): self.started = False
def read(queue): global results mwm_reader = MindwaveDataPointReader() mwm_reader.start() recorder = rcrdr.Recorder(episode_duration=episode_duration, mwm_reader=mwm_reader) time_out_time = time.time() + 10 while time.time() < time_out_time: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("start sequence received, commencing episode...") break recorder.record_one_episode(1, time.time()) print(recorder.get_episode_data()) queue.put(recorder.get_episode_data())
def attempt_connect(eeg_addr): # print('EEG Address in Attempt Connect: {}'.format(eeg_addr)) connect = False # Create Mindwave objects eeg_obj = MindwaveDataPointReader(eeg_addr) # Attempt connection to EEG Object try: eeg_obj.start() except IOError as e: pass # print('EEG Not Connected: {}'.format(eeg_addr)) else: connect = True print('EEG Connected: {}'.format(eeg_addr)) # return eeg_obj return eeg_obj, connect
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] index = 0 try: while(True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append((time.time(),data)) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append((time.time(),data)) index+=1 print index except KeyboardInterrupt: pass fmt = 'ddddddddd' dataFormat = [] file_ = open(sys.argv[1], 'wb') file_.write(fmt.ljust(25,' ')) for i in xrange(len(eeg_datapoints)): timestamp = attention_datapoints[i][0] attention = attention_datapoints[i][1] delta = eeg_datapoints[i][1].delta theta = eeg_datapoints[i][1].theta lowalpha = eeg_datapoints[i][1].lowAlpha highalpha = eeg_datapoints[i][1].highAlpha lowbeta = eeg_datapoints[i][1].lowBeta highbeta = eeg_datapoints[i][1].highBeta lowgamma = eeg_datapoints[i][1].lowGamma midgamma = eeg_datapoints[i][1].midGamma s = struct.pack(fmt,timestamp, delta, theta, lowalpha, highalpha, lowbeta, highbeta, lowgamma, midgamma) file_.write(s) file_.close()
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] index = 0 try: while (True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append((time.time(), data)) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append((time.time(), data)) index += 1 print index except KeyboardInterrupt: pass fmt = 'ddddddddd' dataFormat = [] file_ = open(sys.argv[1], 'wb') file_.write(fmt.ljust(25, ' ')) for i in xrange(len(eeg_datapoints)): timestamp = attention_datapoints[i][0] attention = attention_datapoints[i][1] delta = eeg_datapoints[i][1].delta theta = eeg_datapoints[i][1].theta lowalpha = eeg_datapoints[i][1].lowAlpha highalpha = eeg_datapoints[i][1].highAlpha lowbeta = eeg_datapoints[i][1].lowBeta highbeta = eeg_datapoints[i][1].highBeta lowgamma = eeg_datapoints[i][1].lowGamma midgamma = eeg_datapoints[i][1].midGamma s = struct.pack(fmt, timestamp, delta, theta, lowalpha, highalpha, lowbeta, highbeta, lowgamma, midgamma) file_.write(s) file_.close()
def read(queue, mwm_pipeend, display_freq, episode_duration, num_episodes): #num_episodes counter = 0 record_times = [] current_episode = 0 trim_size = (episode_duration - .4) * 508 - 20 trial_data_df = pd.DataFrame() # creates a new mindwave mobile object mwm_reader = MindwaveDataPointReader() mwm_reader.start() # finds the start signal while True: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("Start sequence received.") break start_time = time.time() #idles for 3 seconds to jump past annoying start spike while (time.time() < start_time + 12): mwm_reader.readNextDataPoint() if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 512): l = np.average(np.diff(record_times)) print("\t\tmwm idling") record_times = [] counter = 0 # once the start command is received from the mwm, the start signal is sent through the pipe to the animation process mwm_pipeend.send(["start_trial"]) print("Startup spike passed. Trial begins.\n") while (current_episode < num_episodes): counter = 0 record_times = [] #used for data acquisition timing episode_data = [] episode_reading_times = [] epi_type = mwm_pipeend.recv()[0] mwm_reader.clearBuffer() # mwm_reader.clearBufferV2() mwm_pipeend.send(["buffer_cleared"]) #for as long as the episode is happening, read data from mwm. For some reason, mwm closes too late. Need early stopping #that's why I subtract .4 seconds from the end_time here end_time = (time.time() + episode_duration - .4) - .15 print("\tCommencing data acquisition at", time.time()) #record data for length of episode while time.time() < end_time: data_point = mwm_reader.readNextDataPoint() if (data_point.__class__ is RawDataPoint): episode_data.append(data_point._readRawValue()) episode_reading_times.append(time.time()) if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 240): l = np.average(np.diff(record_times)) print("\t\tmwm:", int(1 / l), "Hz") record_times = [] counter = 0 print("\tEnding data acquisition at", time.time()) correct_index = 1024 #this value represents the index at which Pacman initially moves #receives the time at which pacman makes his move from the environment action_time = mwm_pipeend.recv()[0] #finds the index closest in time to pacman's move time action_index = episode_reading_times.index( min(episode_reading_times, key=lambda x: abs(x - action_time))) #adds dummy data to front of episode_data or removes offset number of readings so that the critical points are aligned offset = action_index - correct_index if (offset < 0): dummy = [0] * abs(offset) episode_data = dummy + episode_data elif (offset > 0): episode_data = episode_data[offset:] to_trim = int(len(episode_data) - trim_size) print("\t\ttrimming:", to_trim, "readings") episode_data = episode_data[:int(trim_size)] episode_data_df = pd.DataFrame().append([episode_data]) episode_data_df['episode_type'] = np.array([epi_type]) episode_data_df['episode_num'] = np.array([current_episode]) episode_data_df['action_index'] = np.array([action_index]) episode_data_df['trimmed_data'] = np.array([to_trim]) episode_data_df['win'] = np.array([epi_type in [0, 3]]) print("\tpredicting...") prediction = predict(episode_data_df) mwm_pipeend.send(prediction) print("prediction sent") #predict if episode data df is corrupt if (action_index < 950 or action_index > 1100): episode_data_df['is_corrupt'] = np.array([1]) elif (to_trim > 100 or to_trim < 0): episode_data_df['is_corrupt'] = np.array([1]) else: episode_data_df['is_corrupt'] = np.array([0]) # append to trial data df trial_data_df = pd.concat([trial_data_df, episode_data_df]) print("Episode finished. \n\n") #idle until animation sends finished animation signal # while(not mwm_pipeend.recv()): # mwm_reader.readNextDataPoint() # if (display_freq): # current_time = time.time() # record_times.append(current_time) # counter += 1 # if (counter == 240): # l = np.average(np.diff(record_times)) # print("\t\tmwm:", 1 / l, "Hz") # record_times = [] # counter = 0 current_episode += 1 #close and delete mwm mwm_reader.end() del mwm_reader #when the episode is finished, the data gathered by the recorder device is accessed and placed in the queue so the parent process can obtain it queue.put(trial_data_df)
# some X and Y data x = np.arange(100) y = np.random.rand(100) 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)
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")
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] try: while (True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append(data) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append(data) except KeyboardInterrupt: pass # plot data print len(eeg_datapoints) print len(attention_datapoints) attention_datapoint_vals = [ point.attentionValue for point in attention_datapoints ] # will the following give us a good speed increase over using list comprehensions? # or will the readability be better? delta_points = [] theta_points = [] lowAlpha_points = [] highAlpha_points = [] lowBeta_points = [] highBeta_points = [] lowGamma_points = [] midGamma_points = [] for datapoint in eeg_datapoints: # print(datapoint) delta_points.append(datapoint.delta) theta_points.append(datapoint.theta) lowAlpha_points.append(datapoint.lowAlpha) highAlpha_points.append(datapoint.highAlpha) lowBeta_points.append(datapoint.lowBeta) highBeta_points.append(datapoint.highBeta) lowGamma_points.append(datapoint.lowGamma) midGamma_points.append(datapoint.midGamma) # two plots will make the data look more presentable since the scales # of the data vary widely (maybe even more, like a plot per greek letter # or something) # plot the EEG components (scale: 0 - large) pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(delta_points)) for i in delta_points], label="Delta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(theta_points)) for i in theta_points], label="Theta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowAlpha_points)) for i in lowAlpha_points], label="Low-Alpha") pl.plot( range(len(eeg_datapoints)), [float(i) / float(sum(highAlpha_points)) for i in highAlpha_points], label="High-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowBeta_points)) for i in lowBeta_points], label="Low-Beta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(highBeta_points)) for i in highBeta_points], label="High-Beta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowGamma_points)) for i in lowGamma_points], label="Low-Gamma") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(midGamma_points)) for i in midGamma_points], label="Mid-Gamma") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') # pl.yscale('log') pl.show() # plot the attention reading (scale: 1- 1001) pl.plot(range(len(attention_datapoints)), attention_datapoint_vals, label="Attention") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') pl.show()
def init(): global mindwaveDataPointReader mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start()
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)
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] try: while(True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append(data) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append(data) except KeyboardInterrupt: pass # plot data print len(eeg_datapoints) print len(attention_datapoints) attention_datapoint_vals = [point.attentionValue for point in attention_datapoints] # will the following give us a good speed increase over using list comprehensions? # or will the readability be better? delta_points = [] theta_points = [] lowAlpha_points = [] highAlpha_points = [] lowBeta_points = [] highBeta_points = [] lowGamma_points = [] midGamma_points = [] for datapoint in eeg_datapoints: # print(datapoint) delta_points.append(datapoint.delta) theta_points.append(datapoint.theta) lowAlpha_points.append(datapoint.lowAlpha) highAlpha_points.append(datapoint.highAlpha) lowBeta_points.append(datapoint.lowBeta) highBeta_points.append(datapoint.highBeta) lowGamma_points.append(datapoint.lowGamma) midGamma_points.append(datapoint.midGamma) # two plots will make the data look more presentable since the scales # of the data vary widely (maybe even more, like a plot per greek letter # or something) # plot the EEG components (scale: 0 - large) pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(delta_points)) for i in delta_points], label="Delta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(theta_points)) for i in theta_points], label="Theta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowAlpha_points)) for i in lowAlpha_points], label="Low-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highAlpha_points)) for i in highAlpha_points], label="High-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowBeta_points)) for i in lowBeta_points], label="Low-Beta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highBeta_points)) for i in highBeta_points], label="High-Beta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowGamma_points)) for i in lowGamma_points], label="Low-Gamma") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(midGamma_points)) for i in midGamma_points], label="Mid-Gamma") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') # pl.yscale('log') pl.show() # plot the attention reading (scale: 1- 1001) pl.plot(range(len(attention_datapoints)), attention_datapoint_vals, label="Attention") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') pl.show()
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", " "))
print "Player 1" target_address = '/dev/tty.MindWaveMobile-DevA' elif playername == 'player2_val': target_address = '/dev/tty.MindWaveMobile-DevA-2' #target_address = "/dev/tty.MindWaveMobile-DevA" if not target_address: raise IOError("No valid serial port address") #return print "Serial port address: " + target_address print "Running " + playername print "Connecting to MWM...", try: mindwaveDataPointReader = MindwaveDataPointReader(target_address) mindwaveDataPointReader.start() # connect to the mindwave mobile headset except IOError as e: print e print "Couldn't connect to MWM device. Check address? Is it turned on?"; raise e #return print " connected" # datastream = collections.deque; rawdatastream = deque() attentiondata = deque() meditationdata = deque() bwdata = deque() # Delta (0.5 - 2.75Hz), theta (3.5 - 6.75Hz), low-alpha (7.5 - 9.25Hz), # high-alpha (10 - 11.75Hz), low-beta (13 - 16.75Hz), high-beta (18 - 29.75Hz),