def __find_bitalino(macAddress, device_name, general_event, specific_event): """Loop to find and connect to the bitalino device by macAddress.""" # Connection Loop print('Looking for bitalino...' '-- NAME: {} -- ADDR: {}').format(device_name, macAddress) while True: try: # Check for event interruption if (specific_event.is_set() or general_event.is_set()): raise ValueError('Closing the acquisition.') device = bt.BITalino(macAddress, timeout=1) # connect to BITalino print('Running!' '-- NAME: {} -- ADDR: {}').format(device_name, macAddress) break except ValueError as e: print('{}' '-- NAME: {} -- ADDR: {}').format(e, device_name, macAddress) return None except Exception as e: print('{}' '-- NAME: {} -- ADDR: {}').format(e, device_name, macAddress) pass return device
def __init__(self, nFrames=256, fvz=1000): self.macAddress = "20:18:06:13:21:59" self.fvz = fvz self.nframes = nFrames self.device = None self.emg_record_current_frame = [] self.emg_full_record = [] self.device = bitalino.BITalino(self.macAddress) self.startTime = 0
def read_data_bitalino(macAddress, samplingFreq, running_time): print("") print("BITalino Data Collection") print("") print("Searching for devices...") acqChannels = [0, 1, 2, 3, 4, 5] # Acquisition Channels ([0-5]) weight = 57 device = bitalino.BITalino(macAddress) print("") print("Device " + str(macAddress) + " connected.") print("") device.start(samplingFreq, acqChannels) print("Starting acquisition.") print("") start = time.time() end = time.time() while (end - start) < running_time: # Read samples dataAcquired = device.read(samplingFreq) # Acc transfer function: ACC(g) = ((ADC - Cmin)/(Cmax - Cmin))*2-1 max_acc = max(dataAcquired[:, 5]) min_acc = min(dataAcquired[:, 5]) fill_AccData = abs(((dataAcquired[:, 5] - min_acc) / (max_acc - min_acc)) * 2 - 1) # BITalino channel 1 # HR and SpO2 sat transfer function: 0.25*ADC-0.8 #fill_HR_oxy = 0.25*dataAcquired[:,6]-0.8 # BITalino channel 2 #fill_SpO2_oxy = 0.25*dataAcquired[:,7]-0.8 # BITalino channel 3 # Mean values Acc_mean = numpy.mean(fill_AccData) #HR_oxy_mean = numpy.mean(fill_HR_oxy) #SpO2_oxy_mean = numpy.mean(fill_SpO2_oxy) # CSV Format dt = datetime.today() with open('EE_Bitalino_Dataset.csv', 'a') as file: writer = csv.writer(file) writer.writerow([ int(dt.timestamp()), "Ricardo", weight, "Rest", round(Acc_mean, 5) #, #round(HR_oxy_mean,2), #round(SpO2_oxy_mean,2) ]) end = time.time() device.stop() # Stop acquisition device.close() # Close connection print("Connection closed.")
def main(mac_addr, measuring_time): device = bitalino.BITalino(mac_addr) device.start(SamplingRate=1000, analogChannels=[0, 1, 2, 3]) start = time.time() end = time.time() filename = datetime.datetime.now().strftime('%Y%m%d-%H-%M-%S-cal.csv') with open(filename, 'ab') as file: while end - start < measuring_time: np.savetxt(file, device.read(10), delimiter=',', fmt='%d') end = time.time()
def ConnectBitalino(macAddress, batThresh=30, frequency=100): acqChannels = [0,1,2,3] digitalOutput = [0,0,0,0] global device device = bitalino.BITalino(macAddress) device.battery(batThresh) print colored("Connected to : %s"%(device.version()), "green") device.start(frequency, acqChannels)
def __init__(self, parent=None, macAddress='00:00:00:00:00:00', Fs=100, acq=[0, 1]): super(BitalinoMeasurement, self).__init__(parent) self.__Fs = None self.__analog_ch = None self.__mac_address = macAddress self.set_bitalino_sampling_rate(Fs) self.set_acq_analog_channels(acq) self.device = bitalino.BITalino(self.__mac_address)
def __init__(self, mac_address, timeout=None): """Constructor connects with BITalino device through bluetooth :param mac_address: MAC Address of the BITalino device :param timeout: defines a timeout for the connection """ th_id = get_ident() SharedResources.logger.info( "{th_id}: Connecting to BITalino with MAC {mac_address}".format( th_id=th_id, mac_address=mac_address)) self._bitalino = bitalino.BITalino(mac_address, timeout) SharedResources()
def read_function(): global device global contador global nStop zeros = [float(0.0)] * 21 while True: if not type(device) == bitalino.BITalino: try: print "Chega aqui 1 " device = bitalino.BITalino(macAddress) print "Chega aqui 2 " contador = 0 except Exception as e: print e device = "" contador += 1 if contador == nStop: stopDevice() return else: try: if not device.started: print "here 1 " device.start(samplingRate, acqChannels) print "here 2" #data = json.dumps(device.read(nSamples).tolist()) data = device.read(nSamples) for i in range(0, nSamples, 5): send_osc("/0/raw", zeros) send_osc("/0/bitalino", data[i, :].astype('float')) except Exception as e: print e device = "" contador += 1 if contador == nStop: stopDevice() return
def __init__(self, macAddress='98:D3:31:80:48:08', samplingRate=1000, channels=[0, 1, 2, 3, 4, 5]): self.board = BT.BITalino(macAddress) # Sampling Rate (Hz) self.dT = 1.0 / float(samplingRate) self.samplingRate = samplingRate # Number of samples acquired before transmission is made # This is a parameter, it influences the board to PC delay # and the power consumption of the board self.nSamp = 200 # Initialize the board self.channels = channels
def BITalino_source(): BITalino_macAddr = None for d in devices: if os.path.exists(d): BITalino_macAddr = d if not BITalino_macAddr: print "ERROR: DEVICE NOT FOUND" print "list of possible devices:" print "\n".join(devices) print print "May be you want to run:" print "$ sudo rfcomm connect rfcomm0" exit(1) # setting up BITalino device = bitalino.BITalino() if not device.open(BITalino_macAddr, BITalino_SamplingRate): print "Error opening BITalino" print "addr: {} , sampling rate: {}".format(BITalino_macAddr, BITalino_SamplingRate) exit() # print "Device version:" # print device.version() # first yield is conf yield dict(sampling_rate=BITalino_SamplingRate) # Start Acquisition in all Analog Channels device.start() labels = [ "Digital/D0", "Digital/D1", "Digital/D2", "Digital/D3", "Analog/A0", "Analog/A2", "Analog/A3", "Analog/A4", "Analog/A5" ] # led ON # device.trigger([0,0,0,1]) while True: data = device.read(BITalino_nSamples) for n in range(data.shape[1]): for signal, label in enumerate(labels): yield label, data[signal][n]
def BITalino_handler(mac_addr, ch_mask, srate, labels): #labels = ["'nSeq'", "'I1'", "'I2'", "'O1'", "'O2'", "'A1'", "'A2'", "'A3'", "'A4'", "'A5'", "'A6'"] ch_mask = numpy.array(ch_mask) - 1 global connection global stateWS try: print(mac_addr) device = bitalino.BITalino(mac_addr) print(ch_mask) print(srate) device.start(srate, ch_mask) cols = numpy.arange(len(ch_mask) + 5) print cols while stateWS: print "GFGFGFGFG" data = device.read(250) res = "{" for i in cols: idx = i if (i > 4): idx = ch_mask[i - 5] + 5 res += '"' + labels[idx] + '":' + tostring(data[:, i]) + ',' res = res[:-1] + "}" if connection: if len(cl) > 0: [con.write_message(res) for con in cl] print "SSS" else: [con.write_message(res) for con in cl] print "ASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS" stopDevice(device) stateWS = False done = True stopIOLoop() except KeyboardInterrupt: print "Closing Program" os._exit(0) except Exception: traceback.print_exc() os._exit(0)
def main(): #setting up OSC osc = OSC.OSCClient() osc.connect(simuladorAddr) #setting up BITalino device = bitalino.BITalino() if not device.open(macAddr, SamplingRate): print "Error opening BITalino" print "addr: {} , sampling rate: {}".format(macAddr, SamplingRate) exit() #print "Device version:" #print device.version() #Start Acquisition in Analog Channels 0 and 3 device.start([2]) #led ON # device.trigger([0,0,0,1]) try: while True: data = device.read(nSamples) tosend = list(data[5] / 1024) #do something with data ? msg = OSC.OSCMessage("/ECG") msg += tosend try: osc.send(msg) except OSC.OSCClientError: pass except KeyboardInterrupt: pass finally: device.stop() device.close()
for i in range(5, 10): json_data[sensors[i]] = data[i] return json.dumps(json_data, cls=NumPyArangeEncoder) def post_to_server(json): requests.post(post_route, json, headers={'content-type': 'application/json'}) def closedevice(): print "exiting cleanly" device.close() atexit.register(closedevice) device = bitalino.BITalino() device.open(macAddress="/dev/tty.bitalino-DevB", SamplingRate=100) print 'opened device' device.start() print 'started acquisiton' reads = 0 while True: print "reading", reads data = device.read(100) post_to_server(jsonify_arrays(data)) reads += 1
import time import numpy as np from threading import * import select # import argparse # from pythonosc import osc_message_builder # from pythonosc import udp_client from OSC import OSCClient, OSCMessage # .... Bitalino Setup .... SamplingRate = 1000 nSample=10 device = bitalino.BITalino("/dev/tty.bitalino-DevB")#/dev/tty.BITalino-58-82-DevB") #device = bitalino.BITalino("20:15:10:26:62:92") device.start(SamplingRate) # ........ # .... Sockets Setup.... # parser = argparse.ArgumentParser() # parser.add_argument("--ip", default="127.0.0.1", help="The ip of the OSC server") # parser.add_argument("--port", type=int, default=5204, help="The port the OSC server is listening on") # args = parser.parse_args() # # processing = udp_client.SimpleUDPClient(args.ip, args.port) processing = OSCClient() processing.connect( ("127.0.0.1", 5204) )
def read_function(protocolType, macAddress, nSamples, samplingRate, acqChannels, nStop, labels, send_address): global stateOSC global stateOpenSignals if protocolType == "OSC" or protocolType == "OPENSIGNALS": c = OSC.OSCClient() c.connect(send_address) if protocolType == "OSC": addr = "/" + macAddress + "/" zeros = [float(0.0)] * 21 counter = 0 device = "" global done print macAddress while stateOSC or stateOpenSignals: if done: print "Closing OSC protocol!" stopDevice(device) return if not type(device) == bitalino.BITalino: try: device = bitalino.BITalino(macAddress) print "Connected to a device with the macAddress : " + str( macAddress) except Exception as e: print "Try number " + str(counter + 1) + " : " + str(e) counter += 1 if counter == nStop: print "Number of tries reached, something went wrong!" stopDevice(device) return else: try: if not device.started: print type(samplingRate) acqChannels[:] = [x - 1 for x in acqChannels] print type(acqChannels) device.start(samplingRate, acqChannels) textFile = createTextFile() data = device.read(nSamples) numpy.savetxt(textFile, data, fmt='%d', delimiter=' ', newline='\n') if sum(digitalIO) != 0: idx = numpy.ones(len(digitalIO)) * -1 for i in numpy.arange(len(digitalIO)): if (digitalIO[i] == 1): aux = numpy.where(data[:, i + 1] == 0) print aux if len(aux[0]) > 0: idx[i] = aux[0] if idx[i] >= 0: digitalIO[i] -= 1 print idx idx.sort() if idx[-1] >= 0: data = data[idx[-1]:, :] if sum(digitalIO) != 0: continue if protocolType == "OPENSIGNALS": for i in range(0, nSamples, 5): send_osc(c, "/0/raw", zeros) send_osc(c, "/0/bitalino", data[i, :].astype('float')) elif protocolType == "OSC": cols = numpy.arange(len(acqChannels) + 5) for i in cols: #idx = i #if (i>4): idx=acqChannels[i-5]+5 idx = (acqChannels[i - 5] + 5 if (i > 4) else i) send_osc(c, addr + labels[idx], data[:, i]) except Exception as e: print "Try number " + str(counter + 1) + " : " + str(e) counter += 1 if counter == nStop: stopDevice(device) stateOSC = False stateOpenSignals = False textFile.close() done = True print "Number of tries reached, something went wrong!" return stopDevice(device) done = True print "OSC Closed"
import matplotlib.pyplot as plt from threading import Thread from statsmodels.nonparametric.smoothers_lowess import lowess import peakutils.peak import math num_buzz_trig = 20 threshold = 0 trialData = [] trial = True # Mac OS # macAddress = "/dev/tty.BITalino-XX-XX-DevB" # Windows macAddress = "20:17:09:18:58:60" device = bitalino.BITalino(macAddress) #generate breaks randomly between the different buzzer pulses def generatePauses(number): fib = range(number) nums = [] for num in fib: #nums.append(random.uniform(2, 5)) -> a little more stressful test! nums.append(random.uniform(3, 6)) return nums def dataAcquisition(): global trial global trialData
import bitalino import numpy import time macAddress1 = "20:17:09:18:58:62" test = bitalino.BITalino(macAddress1) time.sleep(1) srate = 1000 nframes = 100 resp_threshold = 500 acc_threshold = 580 alarm = 0 alarm_played = 0 test.start(srate, [1, 3]) print("START") try: while True: data = test.read(nframes) if numpy.mean(data[:, 1]) < 1: break r = data[:, 5] y = data[:, 6] resp_sm = numpy.mean(r) acc_sm = numpy.mean(y) if resp_sm > resp_threshold and acc_sm > acc_threshold:
mixer.music.play() else: mixer.music.load('fast.mp3') mixer.music.play() print 'CARDIMAX - Robótica Médica \nAna Rita Lopes | Inês Cruz | Joana Dias\n' # BITalino iniciação mac = '98:D3:31:B2:13:94' samp_rate = 100 #Hz seconds_aqc = 10 #seconds of aquisition nSamples = seconds_aqc * samp_rate analogChannels = [0] bit = bitalino.BITalino(mac) version = bit.version() print bit.version() print 'Starting acquisition...\nCTRL+C to stop.\n' bit.start(samp_rate, analogChannels) x = np.linspace(0, seconds_aqc, nSamples) cutOff = 3 #cutoff frequency in Hz loop_var = 1 n_ant = -1 global mixer mixer.init() try: