def main(): ''' Data streamer from OpenBCI to the Dual Brains Visualization Launch either with a BCI connected to a usb port: $: python data_buffer.py --serial-port /dev/tty.usbserial-DQ007RRX Or using a pre-recorded test file: $: python data_buffer.py --test-file ../aaron_test_data/Filtered_Data/RAW_eeg_data_only_FILTERED.txt ''' if len(sys.argv) is not 3: sys.exit('Usage: %s (--serial-port OR --test-file) /path/to/resource' % sys.argv[0]) option = sys.argv[1] path = sys.argv[2] print 'Starting UDP server' global udp udp = udp_server.UDPServer() db = Data_Buffer() if option in '--serial-port': board = bci.OpenBCIBoard(port=path, send=db) board.start_streaming(db.buffer) if option in '--test-file': playback(db, path)
def read_samples(): # USB dongle settings port = "COM3" baud = 115200 # connect to board board = bci.OpenBCIBoard(port=port, baud=baud, filter_data=False) board.start_streaming(process_sample)
def __init__(self, ip='localhost', port=12345, address="/openbci"): # connection infos self.ip = ip self.port = port self.address = address self.client = OSCClient() self.client.connect((self.ip, self.port)) self.board = bci.OpenBCIBoard()
def acquisition_proc(eeg_sig): def plotData(sample): eeg_sig.put(sample.channel_data[0]) print(sample.channel_data[0]) if __name__ == '__main__': port = '/dev/ttyUSB0' # baud = 115200 board = bci.OpenBCIBoard(port=port) board.start_streaming(plotData)
def __init__(self): # Initialize node rospy.init_node('publish_measurements', anonymous=False) # Get ros parameters #port = rospy.get_param("~port") #baud = rospy.get_param('~baud') #filter_data = rospy.get_param('~filter_data') #scaled_output = rospy.get_param('~scaled_output') #daisy = rospy.get_param('~daisy_module') #log = rospy.get_param('~log') #timeout = rospy.get_param('~timeout') # port = '/dev/ttyUSB0' baud = 115200 filter_data = 'True' scaled_output = 'True' daisy = 'True' log = 'True' timeout = 'None' try: timeout = float(timeout) except ValueError: timeout = None # Initialize OpenBCI board self.board = bci.OpenBCIBoard(port=port, baud=baud, filter_data=filter_data, scaled_output=scaled_output, daisy=daisy, log=log, timeout=timeout) print(self.board.getSampleRate()) # Set ros parameters rospy.set_param('eeg_channel_count', self.board.getNbEEGChannels()) rospy.set_param('aux_channel_count', self.board.getNbAUXChannels()) rospy.set_param('sampling_rate', self.board.getSampleRate()) # Setup EEG data publisher and message self.pub_EEG = rospy.Publisher('eeg_channels', BCIuVolts, queue_size=1) self.msg_EEG = BCIuVolts() # Setup AUX data publisher and messsage self.pub_AUX = rospy.Publisher('eeg_aux', Imu, queue_size=1) self.msg_AUX = Imu() self.msg_AUX.header.seq = 0 self.msg_AUX.header.stamp = None self.msg_AUX.header.frame_id = "" self.msg_AUX.orientation_covariance[0] = -1 # No orientation self.msg_AUX.angular_velocity_covariance[0] = -1 # No angular velocity self.msg_AUX.linear_acceleration_covariance = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # No accel covariance
def initialize_board(self): self.board = bci.OpenBCIBoard() time.sleep(1) #turn off all channels except Channel 1 self.board.ser.write(b'2') self.board.ser.write(b'3') self.board.ser.write(b'4') self.board.ser.write(b'5') self.board.ser.write(b'6') self.board.ser.write(b'7') self.board.ser.write(b'8')
def __init__(self,daisy=False): parser = argparse.ArgumentParser(description="OpenBCI 'user'") parser.add_argument('-p', '--port', help="Port to connect to OpenBCI Dongle " + "( ex /dev/ttyUSB0 or /dev/tty.usbserial-* )") parser.add_argument('-d', action="store_true", help="Enable Daisy Module " + "-d") args = parser.parse_args() port = args.port print ("\n-------INSTANTIATING BOARD-------") self.board = bci.OpenBCIBoard(port, daisy=args.d) self.eeg_channels = self.board.getNbEEGChannels() self.aux_channels = self.board.getNbAUXChannels() self.sample_rate = self.board.getSampleRate() print('{} EEG channels and {} AUX channels at {} Hz'.format(self.eeg_channels, self.aux_channels,self.sample_rate))
def board(lock,i): lock.acquire() Logger = CSVLogger() board = bci.OpenBCIBoard(port="COM3", filter_data=False, scaled_output=True, log=True, aux=False) import threading print(board.streaming) boardThread = threading.Thread(target=board.start_streaming, args=(Logger.logger, -1)) boardThread.start() print(board.streaming) x = True while x: if board.streaming: lock.release() x = False
def __init__(self): super(MainWin.DataThread, self).__init__() #Connect the board object to the port; the port name may vary with device, so we just have to hardcode it self.board = bci.OpenBCIBoard(port='/dev/tty.usbserial-DB00MHTW', filter_data=True, daisy=False) #Check the status of the device print (self.board.getNbEEGChannels(), "EEG channels and", self.board.getNbAUXChannels(), "AUX channels at", self.board.getSampleRate(), "Hz.") #Don't worry about why this is in a loop; was using it for testing for i in range(0, 1): self.board.set_channel7() sleep(10) #sentinel flag for running the thread self.running = True #initialize the data matrix to empty self.data = np.empty(shape=(8, 0))
def __init__(self): self.board = bci.OpenBCIBoard(port="/dev/ttyS0") self.eeg_channels = self.board.getNbEEGChannels() self.aux_channels = self.board.getNbAUXChannels() self.sample_rate = self.board.getSampleRate() self.save = False self.graphppg = [] self.graphecg = [] self.ecg = [] self.ppg = [] self.ecg30 = [] self.ppg30 = [] #setting channel 6 beg = 'x6000000X' #setting default and reseting board s = 'sv' s = s + 'd' #writing data to board s = s + 'F' for c in s: if sys.hexversion > 0x03000000: self.board.ser.write(bytes(c, 'utf-8')) else: self.board.ser.write(bytes(c)) time.sleep(0.100) #writing channel six data to board time.sleep(0.100) # for dat in beg: for x in beg: if sys.hexversion > 0x03000000: self.board.ser.write(bytes(x, 'utf-8')) else: self.board.ser.write(bytes(x)) time.sleep(0.100) self.ecg = [] self.ppg = [] self.ecgT = [] self.ppgT = []
def proc_print(e, pid): pid.put(os.getpid()) def writeData(sample): with open(csv_filename, 'at') as f: save = csv.writer(f) save.writerow(sample.channel_data) # save.writerow([sample.id] + sample.channel_data) if stop_stream.is_set(): board.disconnect() # print "----------------" # print("%f" %(sample.id)) # print sample.channel_data[0] # print sample.aux_data # print "----------------" if __name__ == '__main__': port = '/dev/ttyUSB0' # baud = 115200 board = bci.OpenBCIBoard(port=port) board.start_streaming(writeData)
def stream_data_from_OpenBCI(data_queue, t_queue, experiment_queue, experiment_type, t_init, n_data_created, all_data, all_t, all_experiment_val): port = '/dev/ttyUSB0' # if using Linux # (if encounter error: [Errno 13] could not open port /dev/ttyUSB0: Permission denied => see: https://askubuntu.com/questions/58119/changing-permissions-on-serial-port then restart your computer # port = 'COM3' # if using Windows # port = '/dev/tty.OpenBCI-DN008VTF' # If using MAC? logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG) logging.info('---------LOG START-------------') board = bci.OpenBCIBoard(port=port, scaled_output=False, log=True) print("Board Instantiated") sleep(5) OpenBCI_sampler = SampleDataFromOPENBCI(board, data_queue, experiment_queue, experiment_type, t_queue, t_init, n_data_created, all_data, all_t, all_experiment_val) OpenBCI_sampler.start() return board
def __init__(self, **kwargs): super(OpenBCI, self).__init__(**kwargs) self.name = 'source:bciboard' # self.config['port'] = kwargs.get('port', "/dev/tty.usbserial-DN0093NU") # self.config['channels'] = kwargs.get('channels', [0,1,2,3,4,5,6,7]) # self.config['timeout'] = kwargs.get('timeout', -1) # initialise the bci self.bci = bci.OpenBCIBoard(port=self.config['port']) # register callback to disconnect the bci on quit atexit.register(self._boardEndCallback) time.sleep(1) # init channels self._reset_channels() time.sleep(1) # Start streaming from device in a daemonised thread self.bciboard_thread = threading.Thread( target=self.bci.start_streaming, args=[self._on_sample, self._boardEndCallback]) #, # self._boardTimeoutCallback, # self.config['timeout']]) self.bciboard_thread.daemon = True
# append some meta-data info.desc().append_child_value("manufacturer", "OpenBCI") channels = info.desc().append_child("channels") for c in ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]: channels.append_child("channel").append_child_value( "name", c).append_child_value("unit", "microvolts").append_child_value("type", "EEG") # next make an outlet; we set the transmission chunk size to 32 samples and the outgoing buffer size to 360 seconds (max.) outlet = StreamOutlet(info, 32, 360) port = '/dev/tty.usbserial-DN0093AG' baud = 115200 board = bci.OpenBCIBoard(port=port, baud=baud) def sendData(sample): # get 8 channel sample from OpenBCI Board; this is converted into a pylsl.vectorf (the data type that is expected by push_sample) mysample = sample.channel_data # get a time stamp in seconds from OpenBCI hardware stamp = sample.getTime() # now send it, will wait for board to send next packet. outlet.push_sample(mysample, stamp) print((mysample, stamp)) # debug print("now sending data...") board.startStreaming(sendData)
if args.info: plugin = manager.getPluginByName(args.info) if plugin == None: # eg: if an import fail inside a plugin, yapsy skip it print "Error: [", args.info, "] not found or could not be loaded. Check name and requirements." else: print plugin.description plugin.plugin_object.show_help() exit() print "\n------------SETTINGS-------------" print "Notch filtering:", args.filtering print "\n-------INSTANTIATING BOARD-------" board = bci.OpenBCIBoard(port=args.port, daisy=args.daisy, filter_data=args.filtering) # Info about effective number of channels and sampling rate if board.daisy: print "Force daisy mode:", else: print "No daisy:", print board.getNbEEGChannels(), "EEG channels and", board.getNbAUXChannels( ), "AUX channels at", board.getSampleRate(), "Hz." print "\n------------PLUGINS--------------" # Loop round the plugins and print their names. print "Found plugins:", for plugin in manager.getAllPlugins(): print "[", plugin.name, "]",
def dataCatcher(): global board baud = 115200 logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG) logging.info('---------LOG START-------------') if numCh >= 9: for i in range(10): if os.name == 'nt': #print("Connecting to Windows serial port") port = "COM" + str(i) elif os.name == 'posix': #print("Connecting to Linux Serial port") port = "/dev/ttyS" + str(i) try: board = bci.OpenBCIBoard(port=port, scaled_output=True, log=True, filter_data=False, daisy=True) break except Exception: pass else: for i in range(10): if os.name == 'nt': #print("Connecting to Windows serial port") port = "COM" + str(i) elif os.name == 'posix': #print("Connecting to Linux serial port") port = "/dev/ttyUSB" + str(i) #port = '/dev/tty.OpenBCI-DN008VTF' #port = '/dev/tty.OpenBCI-DN0096XA' try: board = bci.OpenBCIBoard(port=port, scaled_output=True, log=True, filter_data=False, daisy=False) break except Exception: print("Could not connect to this port") pass if board != None: print("Board Instantiated") board.ser.write('v') #tme.sleep(10) if not board.streaming: board.ser.write(b'b') board.streaming = True print("Samplerate: %0.2fHz" % board.getSampleRate()) glb.fs = board.getSampleRate() glb.b, glb.a = filterlib.designfilter(filtertype="notch", Q=20) board.start_streaming(printData) else: print("Board initialization failed, exit and reconnect dongle")
class UDPServer(object): def __init__(self, ip, port, json): self.ip = ip self.port = port self.json = json print "Selecting raw UDP streaming. IP: ", self.ip, ", port: ", str( self.port) self.server = socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM) def send_data(self, data): self.server.sendto(data, (self.ip, self.port)) def handle_sample(self, sample): if self.json: # Just send channel data. self.send_data(json.dumps(sample.channel_data)) else: # Pack up and send the whole OpenBCISample object. self.send_data(pickle.dumps(sample)) args = parser.parse_args() obci = open_bci.OpenBCIBoard(args.serial, int(args.baud)) if args.filter_data: obci.filter_data = True sock_server = UDPServer(args.host, int(args.port), args.json) obci.start_streaming(sock_server.handle_sample)
import threading # Constants START_TIME = time.strftime('%m-%d-%Y_%H-%M-%S') COM_PORT = 'COM3' SAMPLE_RATE = bci.SAMPLE_RATE EXPERIMENT_TIME = 5 * 60 # in seconds WINDOW_LENGTH = 250 PREDICTION_WINDOW_LENGTH = 5 CHANGE_THRESHOLD = 0.93 TESTING_PROP = 0.2 # proportion of data to test classifiers over FFT_FREQ = np.fft.rfftfreq(WINDOW_LENGTH, d=1.0/SAMPLE_RATE) PLOT_FREQ = 3 # Globals board = bci.OpenBCIBoard(port=COM_PORT) eyes_closed = 0 window = collections.deque(maxlen=WINDOW_LENGTH) prediction_window = collections.deque(maxlen=PREDICTION_WINDOW_LENGTH) readings = [] feature_vectors = [] labels = [] current_state = 0 plotting = False def calc_feature_vector(): fft = np.fft.rfft(window) feature_vector = [] for i in range(len(fft)): if FFT_FREQ[i] >= 8 and FFT_FREQ[i] <= 13: feature_vector.append(abs(fft[i]) ** 0.5)
from scipy import signal import matplotlib.pyplot as plt from numpy.random import randn #import tkinter mutex = Lock() #Helmetsetup port = 'COM6' baud = 115200 logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG) logging.info('---------LOG START-------------') board = bci.OpenBCIBoard(port=port, scaled_output=True, log=True, filter_data=False) print("Board Instantiated") board.ser.write('v') #tme.sleep(10) if not board.streaming: board.ser.write(b'b') board.streaming = True print("Samplerate: %0.2fHz" % board.getSampleRate()) #Graph setup app = QtGui.QApplication([]) p = pg.plot() nPlots = 6
import sys; sys.path.append('..') # help python find open_bci_v3.py relative to scripts folder import open_bci_v3 as bci import os def printData(sample): #os.system('clear') print "----------------" # print("%f" %(sample.id)) print sample.channel_data[0] # print sample.aux_data print "----------------" if __name__ == '__main__': port = '/dev/ttyUSB0' baud = 115200 board = bci.OpenBCIBoard(port=port) board.start_streaming(printData)
if args.log: print("Logging Enabled: " + str(args.log)) logging.basicConfig(filename="OBCI.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG) logging.getLogger('yapsy').setLevel(logging.DEBUG) logging.info('---------LOG START-------------') logging.info(args) else: print("user.py: Logging Disabled.") print("\n-------INSTANTIATING BOARD-------") print("About to open board") board = bci.OpenBCIBoard(port=args.port, daisy=args.daisy, filter_data=args.filtering, scaled_output=True, log=args.log, aux=args.aux) # Info about effective number of channels and sampling rate print("Got this far") #This does not happen t2 if board.daisy: print("Force daisy mode:") else: print("No daisy:") print(board.getNbEEGChannels(), "EEG channels and", board.getNbAUXChannels(), "AUX channels at", board.getSampleRate(), "Hz.") print("\n------------PLUGINS--------------") # Loop round the plugins and print their names. print("Found plugins:")
def __init__(self): # Initialize node rospy.init_node('publish_measurements', anonymous=False) # Get ros parameters #port = rospy.get_param("~port") #baud = rospy.get_param('~baud') #filter_data = rospy.get_param('~filter_data') #scaled_output = rospy.get_param('~scaled_output') #daisy = rospy.get_param('~daisy_module') #log = rospy.get_param('~log') #timeout = rospy.get_param('~timeout') # port = '/dev/ttyUSB0' baud = 115200 filter_data = True scaled_output = True daisy = False log = True timeout = 'None' try: timeout = float(timeout) except ValueError: timeout = None # Initialize OpenBCI board self.board = bci.OpenBCIBoard(port=port, baud=baud, filter_data=filter_data, scaled_output=scaled_output, daisy=daisy, log=log, timeout=timeout) self.f = open( '/home/siddarthkaki/new_ws/src/openbci/src/data_main.txt', 'w') #thumb - 1, index - 2, middle - 3, ring - 4, pinky - 5 #self.f.write(str('time, chan1, chan2, chan3, chan4, chan5, chan6, chan7, chan8, label')+'\n') self.f.write(str('time, chan7, label') + '\n') self.f2 = open('/home/siddarthkaki/new_ws/src/openbci/src/label.txt', 'w') self.f2.write(str('time, label') + '\n') self.run_time = 0 self.run = 0 # Set ros parameters rospy.set_param('eeg_channel_count', self.board.getNbEEGChannels()) rospy.set_param('aux_channel_count', self.board.getNbAUXChannels()) rospy.set_param('sampling_rate', self.board.getSampleRate()) # Setup EEG data publisher and message self.pub_EEG = rospy.Publisher('eeg_channels', BCIuVolts, queue_size=1) self.msg_EEG = BCIuVolts() # Setup AUX data publisher and messsage self.pub_AUX = rospy.Publisher('eeg_aux', Imu, queue_size=1) self.msg_AUX = Imu() self.msg_AUX.header.seq = 0 self.msg_AUX.header.stamp = None self.msg_AUX.header.frame_id = "" self.msg_AUX.orientation_covariance[0] = -1 # No orientation self.msg_AUX.angular_velocity_covariance[0] = -1 # No angular velocity self.msg_AUX.linear_acceleration_covariance = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # No accel covariance
""" if True: import sys sys.path.insert(0,'C:/Users/Glenn/Documents/GitHub/NGHack-Pacman/glenn') import main1 main1.go() ##cd C:\Python27\ ##python -m serial.tools.list_ports """ if True: import sys sys.path.insert(0,'C:/Users/Glenn/Documents/GitHub/NGHack-Pacman/glenn') import pygame, open_bci_v3 as bci board = bci.OpenBCIBoard() board.print_register_settings() f = open('C:/Users/Glenn/Documents/GitHub/NGHack-Pacman/glenn/live_raw.txt','w') n = 0 def handle_sample(sample): global n, f if n>=20000: return raw = [] for channel in range(8): signal = sample.channel_data[channel] raw.append(signal) f.write(str(raw)) f.write('\n') n+=1
import open_bci_v3 as bci import os def printData(sample): #os.system('clear') print "----------------" print("%f" % (sample.id)) print sample.channel_data print sample.aux_data print "----------------" if __name__ == '__main__': port = '/dev/ttyUSB0' baud = 115200 board = bci.OpenBCIBoard(port=port, is_simulator=True) board.start_streaming(printData)
# socketio.run(app) # ======= global latest_string, bciboard, bciboard_stopsignal global sock_server, osc_server bciboard_stopsignal = False baud = 115200 available_ports = bci.serial_ports() print "Sees the following port options: " + str(available_ports) print "It is currently strongly advised to specify the port in code" port = available_ports[1] bciboard = bci.OpenBCIBoard(port=port, is_simulator=False) latest_string = "none yet" args = { "host": HOST_IP, "port": '8888', "json": True, } print args sock_server = UDPServer(args["host"], int(args["port"]), args["json"]) osc_server = OSCServer(args["host"], 12345) #set_boardstreaming(True) #Run the http server #app.run(host= HOST_IP)
### Test program for Cyton import sys; sys.path.append('..') # help python find open_bci_v3.py relative to scripts folder import open_bci_v3 as bci import os import logging import time def handle_sample(sample): print(sample.channel_data) board = bci.OpenBCIBoard(port='COM7') board.print_register_settings() board.start_streaming(handle_sample)
print " interpolation: ", interpol_values print " current sample: ", sample.channel_data # send to clients interpolated sample #leftover_duplications = 0 server.broadcast_values(interpol_values) nb_samples_out = nb_samples_out + 1 # send to clients current sample server.broadcast_values(sample.channel_data) nb_samples_out = nb_samples_out + 1 # save current values for possible interpolation last_values = list(sample.channel_data) if __name__ == '__main__': # init server #server = streamer_tcp_server.StreamerTCPServer(ip=SERVER_IP, port=SERVER_PORT, nb_channels=NB_CHANNELS) server = streamer_tcp_server.StreamerTCPServer(ip=SERVER_IP, port=SERVER_PORT) # init board #port = '/dev/ttyUSB1' port = 'COM7' baud = 115200 monit = Monitor() # daemonize theard to terminate it altogether with the main when time will come monit.daemon = True monit.start() board = bci.OpenBCIBoard(port=port, baud=baud, filter_data=False) board.startStreaming(streamData)
# first create a new stream info (here we set the name to OpenBCI, the content-type to EEG, 8 channels, 250 Hz, and float-valued data) # The last value would be the serial number of the device or some other more or less locally unique identifier for the stream as far as available (you could also omit it but interrupted connections wouldn't auto-recover). info = StreamInfo('OpenBCI_32', 'EEG', 8, 250, 'float32', 'usbserial-DN0093AG') # append some meta-data info.desc().append_child_value("manufacturer", "OpenBCI") channels = info.desc().append_child("channels") for c in ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]: channels.append_child("channel").append_child_value( "name", c).append_child_value("unit", "microvolts").append_child_value( "type", "EEG") # next make an outlet; we set the transmission chunk size to 32 samples and the outgoing buffer size to 360 seconds (max.) outlet = StreamOutlet(info, 32, 360) print "Established LSL outlet." except: print "Count not create LSL outlet." print "User serial interface enabled..." print "Connecting to ", args.port board = bci.OpenBCIBoard(port=args.port, baud=args.baud) try: print("Beginning data transmission.") board.startStreaming(sendData) except: print("A problem occured when transmitting data.")
'..') # help python find open_bci_v3.py relative to scripts folder import open_bci_v3 as bci import os import logging import time def printData(sample): #os.system('clear') print "----------------" print("%f" % (sample.id)) print sample.channel_data print sample.aux_data print "----------------" if __name__ == '__main__': port = '/dev/tty.OpenBCI-DN008VTF' #port = '/dev/tty.OpenBCI-DN0096XA' baud = 115200 logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG) logging.info('---------LOG START-------------') board = bci.OpenBCIBoard(port=port, scaled_output=False, log=True) print("Board Instantiated") board.ser.write('v') time.sleep(10) #board.start_streaming(printData) board.print_bytes_in()
# baud rate is not currently used parser.add_argument('-b', '--baud', default=115200, type=int, help="Baud rate (not currently used)") parser.add_argument('-c', '--cvs', action="store_true", help="write cvs data") args = parser.parse_args() if args.cvs: fun = csv_collect.csv_collect(); else: fun = printData; print "User serial interface enabled..." print "Connecting to ", args.port board = bci.OpenBCIBoard(port=args.port) print "View command map at http://docs.openbci.com." print "Type start to run. Type exit to exit." #Start by restoring default settings s = 'd' while(s != "exit"): #Send char and wait for registers to set if("help" in s): print "View command map at: http://docs.openbci.com/software/01-OpenBCI_SDK.\nFor user interface, read README or view https://github.com/OpenBCI/OpenBCI_Python" elif(s == "/start"): board.startStreaming(fun); elif('test' in s): test = int(s[string.find(s,"test")+4:]) board.test_signal(test);