def launch_acquisition(msg): global isAcquiring isAcquiring = 1 macAddress = msg['payload']['macAddress'] # This example will collect data for 5 sec. running_time = 9 batteryThreshold = 30 acqChannels = [0, 1, 2, 3, 4, 5] samplingRate = 1000 nSamples = 10 digitalOutput = [1, 1] # Connect to BITalino device = BITalino(macAddress) # Set battery threshold device.battery(batteryThreshold) # Read BITalino version print(device.version()) # ON/OFF device.trigger([1, 1]) device.trigger([0, 0]) # Start Acquisition device.start(samplingRate, acqChannels) start = time.time() end = time.time() while (end - start) < running_time and isAcquiring == 1: # Read samples data = device.read(nSamples) print(data) msg['payload']['val'] = data.tolist() end = time.time() # Stop acquisition device.stop() # Close connection device.close() isAcquiring = 0 return ("success")
except: print "Error: cannot connect to BITalino" exit() # Read BITalino version print(device.version()) # Set battery threshold device.battery(batterythreshold) # Start Acquisition device.start(fsample, channels) # Turn BITalino led on digitalOutput = [1,1] device.trigger(digitalOutput) startfeedback = time.time(); countfeedback = 0; print "STARTING STREAM" while True: # measure the time that it takes start = time.time(); # read the selected channels from the dat = device.read(blocksize) # it starts with 5 extra channels, the first is the sample number (running from 0 to 15), the next 4 seem to be binary dat = dat[:,5:] # write the data to the output buffer
class bitalino_device(object): def __init__(self, macAddress, batteryThreshold, samplingRate, nSamples): self.macAddress = macAddress self.batteryThreshold = batteryThreshold self.acqChannels = [0, 1, 2, 3, 4, 5] self.samplingRate = samplingRate self.nSamples = nSamples self.status = 0 self.ledOn = [1, 0] self.ledOff = [0, 1] self.attSensors = "this" self.file = "" self.threshold = 5 self.noise = [1, 1, 1, 1, 1, 1] self.prevData = [0, 0, 0, 0, 0, 0] def connect(self): try: self.connection = BITalino(self.macAddress) self.status = 1 except: print('failed to connect') def state(self): return self.connection.state() def start(self): self.connection.start(self.samplingRate, self.acqChannels) def start_read(self): return self.connection.read(self.nSamples) def stop(self): self.connection.stop() def led_on(self): self.connection.trigger(self.ledOn) def led_off(self): self.connection.trigger(self.ledOff) def create_file(self, current_directory): print('in create file') new_file = bitFile(self.macAddress, self.acqChannels, self.samplingRate, self.attSensors) self.file = new_file.createFile(current_directory) def update_sensors(self, sensorValues): self.attSensors = sensorValues def get_sensor_value(self): print(str(self.attSensors)) def matToString(self, matrix): """ :param matrix: The matrix to be turned into string Returns a string of a matrix row by row, without brackets or commas """ r, c = matrix.shape string = "" for row in range(0, r): string = string + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + "\t" for col in range(1, c): string = string + str(int(matrix[row, col])) + "\t" string += "\n" return string def openFile(self): open(self.file, "w") def checkNoiseArray(self, channels): for i in range(6): if (int(channels[i]) - int(self.prevData[i]) < self.threshold): self.noise[i] = 0 else: self.noise[i] = 1 self.prevData = channels #print(self.noise) def checkNoise(self, data): data = self.matToString(data) #print(data) channels_list = data.split('\n') for channels in channels_list: channel = channels.split('\t') if len(channel) > 1: self.checkNoiseArray(channel[5:11]) #for channel in channels[2:]: # print(channel) def write(self, string_sample): self.file.write(string_sample) def closeFile(self): self.file.close()
except: print("Error: cannot connect to BITalino") exit() # Read BITalino version print((device.version())) # Set battery threshold device.battery(batterythreshold) # Start Acquisition device.start(fsample, channels) # Turn BITalino led on digitalOutput = [1,1] device.trigger(digitalOutput) startfeedback = time.time() countfeedback = 0 print("STARTING STREAM") while True: # measure the time that it takes start = time.time(); # read the selected channels from the bitalino dat = device.read(blocksize) # it starts with 5 extra channels, the first is the sample number (running from 0 to 15), the next 4 seem to be binary dat = dat[:,5:] # write the data to the output buffer
def _start(): """Start the module This uses the global variables from setup and adds a set of global variables """ global parser, args, config, r, response, patch, name global monitor, debug, device, fsample, blocksize, channels, batterythreshold, nchans, startfeedback, countfeedback, ft_host, ft_port, ft_output, datatype, digitalOutput # this can be used to show parameters that have changed monitor = EEGsynth.monitor(name=name, debug=patch.getint("general", "debug")) # get the options from the configuration file debug = patch.getint("general", "debug") device = patch.getstring("bitalino", "device") fsample = patch.getfloat("bitalino", "fsample", default=1000) blocksize = patch.getint("bitalino", "blocksize", default=10) channels = patch.getint("bitalino", "channels", multiple=True) # these should be one-offset batterythreshold = patch.getint("bitalino", "batterythreshold", default=30) # switch from one-offset to zero-offset nchans = len(channels) for i in range(nchans): channels[i] -= 1 monitor.info("fsample = " + str(fsample)) monitor.info("channels = " + str(channels)) monitor.info("nchans = " + str(nchans)) monitor.info("blocksize = " + str(blocksize)) try: ft_host = patch.getstring("fieldtrip", "hostname") ft_port = patch.getint("fieldtrip", "port") monitor.success("Trying to connect to buffer on %s:%i ..." % (ft_host, ft_port)) ft_output = FieldTrip.Client() ft_output.connect(ft_host, ft_port) monitor.success("Connected to output FieldTrip buffer") except: raise RuntimeError("cannot connect to output FieldTrip buffer") datatype = FieldTrip.DATATYPE_FLOAT32 ft_output.putHeader(nchans, float(fsample), datatype) try: # Connect to BITalino device = BITalino(device) monitor.success((device.version())) except: raise RuntimeError("cannot connect to BITalino") # Set battery threshold device.battery(batterythreshold) # Start Acquisition device.start(fsample, channels) # Turn BITalino led on digitalOutput = [1, 1] device.trigger(digitalOutput) startfeedback = time.time() countfeedback = 0 # there should not be any local variables in this function, they should all be global if len(locals()): print("LOCALS: " + ", ".join(locals().keys()))
def main(): # OS Specific Initializations clearCmd = "cls||clear" if platform.system() == 'Windows': clearCmd = "cls" print("Using Windows default console size 80x24") columns = 80 rows = 24 else: clearCmd = "clear" rows, columns = os.popen('stty size', 'r').read().split() print("Connecting to BITalino...") # Set MAC Address with argument defaultMACAddress = "20:16:12:21:98:56" if len(sys.argv) == 2: macAddress = sys.argv[1] print("Using address: " + macAddress) elif len(sys.argv) > 1: print("Please input only 1 argument, which is the address of the BITalino device.") print("Running without argument will use default MAC Address = " + defaultMACAddress) print("Exiting...") exit() else: macAddress = defaultMACAddress print("Using default MAC address: " + macAddress) # Setting other attributes batteryThreshold = 30 acqChannels = [0,1] samplingRate = 100 nSamples = 20 digitalOutput = [1,1] # Connect to BITalino device = BITalino(macAddress) # Set battery threshold device.battery(batteryThreshold) # Read BITalino version os.system(clearCmd) print("Device Version:" + device.version()) # Start Acquisition device.start(samplingRate, acqChannels) # Take baseline measurement p1Base = [] p2Base = [] start = time.time() end = time.time() samplingTime = 15 print("Sampling for baseline...") while (end - start) < samplingTime: # Sampling for baseline baseSample = device.read(nSamples) p1Base.append(numpy.mean(baseSample[:,5])) p2Base.append(numpy.mean(baseSample[:,6])) end = time.time() p1B = numpy.mean(p1Base) p2B = numpy.mean(p2Base) print("\n") p1P = "Player 1 Baseline: " + str(p1B) print(p1P) p2P = "Player 2 Baseline: " + str(p2B) print(p2P) print("\n\n\n\n\n\n") print("Are you ready for the game? Type 'No' to exit".center(int(columns)," ")) response = sys.stdin.readline().rstrip() if response == "No": sys.exit() print("\n") print("Starting Game...".center(int(columns), " ")) time.sleep(5) # Start Game os.system(clearCmd) gameRunning = True player1Progress = 28 while gameRunning: # While not reaching runningTime, read samples rawData = device.read(nSamples) portA1 = rawData[:,5] #print "Port A1: ", portA1 valueA1 = numpy.mean(portA1 - p1B) #print "Value A1: ", valueA1 #print "" portA2 = rawData[:,6] #print "Port A2: ", portA2 valueA2 = numpy.mean(portA2 - p2B) #print "Value A2: ", valueA2 #print "\n" if (valueA2 - valueA1) > 10: player1Progress-=1 elif (valueA2 - valueA1) > 20: plater1Progress-=2 elif (valueA1 - valueA2) > 10: player1Progress+=1 elif (valueA1 - valueA2) > 20: player1Progress+=2 print("\n\n") print("Player 1 Reading:".center(int(columns)," ")) print("\n") print(str(valueA1).center(int(columns)," ")) print("\n\n\n") print("*****************************I*****************************".center(int(columns)," ")) progress = "P1 *" + ' '*player1Progress + 'O' + ' '*(56-player1Progress) + '* P2' print(progress.center(int(columns)," ")) print("*****************************I*****************************".center(int(columns)," ")) print("\n\n\n") print("Player 2 Reading:".center(int(columns)," ")) print("\n") print(str(valueA2).center(int(columns)," ")) time.sleep(0.2) os.system(clearCmd) if player1Progress == 0: print("\n\n\n\n\n") print("Player 1 has won".center(int(columns)," ")) gameRunning = False elif player1Progress == 56: print("\n\n\n\n\n") print("Player 2 has won".center(int(columns)," ")) gameRunning = False # Turn BITalino LED on device.trigger(digitalOutput) # Stop acquisition device.stop() # Close connection device.close()
class BITalinoProcess(Process): """ BITalino acquisition process. """ def __init__(self, outQueue, goFlag, acqFlag, mac=None, channels=[0], step=100, SamplingRate=1000, timeout=5, bitCls=None): # run parent __init__ super(BITalinoProcess, self).__init__() # synchronization inputs self.queue = outQueue self.go = goFlag self.acq = acqFlag # BITalino settings self.mac = mac self.channels = channels self.step = step self.SamplingRate = int(SamplingRate) if bitCls is None: self.device = BITalino() else: self.device = bitCls() # trigger stuff c1, c2 = Pipe() self._outerPipe = c1 self._innerPipe = c2 self._trigout = 2 * self.step / float(self.SamplingRate) # timeout self.timeout = timeout @classmethod def instaStart(cls, *args, **kwargs): # do some class method magic here to instantiate and start the process outQueue = Queue() goFlag = Event() goFlag.set() acqFlag = Event() p = cls(outQueue, goFlag, acqFlag, *args, **kwargs) p.start() return p, outQueue, goFlag, acqFlag def _checkTrigger(self): # check if there is a trigger to act on if self._innerPipe.poll(): data = self._innerPipe.recv() try: mask = data['Mask'] except KeyError: # report failure self._innerPipe.send({'Ack': False}) else: # trigger self.device.trigger(mask) # report success self._innerPipe.send({'Ack': True}) def trigger(self, data=[0, 0, 0, 0]): # act on digital outputs if not self.acq.is_set(): return False # send mask self._outerPipe.send({'Mask': data}) # wait for ack if self._outerPipe.poll(self._trigout): out = self._outerPipe.recv() return out['Ack'] else: return False def connect(self): # connect to BITalino if self.device.open(self.mac, self.SamplingRate): time.sleep(1.5) print "successful" return True else: print "failed" return False def setup(self): # setup bitalino print "connecting to %s: " % self.mac while self.go.is_set(): if self.connect(): return True time.sleep(1.5) return False def on_start(self): # run immediately after acquisition starts pass def exit(self): # exit process self.acq.clear() self.go.clear() def processData(self, data): # process received data # send data self.queue.put(data) def on_stop(self): # run immediately before acquisition stops pass def run(self): # main loop # connect to device, proceed if successful if self.setup(): while self.go.is_set(): # wait for acquisition flag print "Waiting" self.acq.wait(timeout=self.timeout) if self.acq.is_set(): # start acquisition self.device.start(self.channels) # time.sleep(1) print "acquiring" self.on_start() while self.acq.is_set(): # read data data = self.device.read(self.step) # process data self.processData(data) # check trigger self._checkTrigger() # clean up self.on_stop() self.queue.put('') # stop acquisition self.device.stop() # print "blocked" print "acquisition stopped" # disconnect device self.device.close() print "disconnected"