def acquire_cb(self, state): #print("acq callback") #print(state) if (self.action_acq.get_active()): # This is commented because it seems that comedi_cancel() # clears stale data in the fd and card? #data = os.read(self.fd, BUF_SIZE) #print("LEN DATA: %d" % len(data)) # Start comedi command ret = c.comedi_command(self.dev, self.cmd) if (ret != 0): self.warn_dialog("PCI-6033E cannot collect data! Error: %d" % ret) print(c.comedi_strerror(c.comedi_errno())) return(False) #self.timer_id = GObject.timeout_add(100, self.my_timer) # Make these timeouts configurable... self.plotter_id = GObject.timeout_add(250, self.update_plots) self.plot_id = GObject.timeout_add(500, self.num_data_timer) self.timer_id = GObject.timeout_add(20, self.pci_6033e_get_data) #self.plot_timer.start() self.action_acq.set_label("Halt") else: self.action_acq.set_label("Acquire") if (self.timer_id): if (c.comedi_cancel(self.dev, SUBDEVICE) < 0): print("failed to cancel comedi command...") GObject.source_remove(self.timer_id) if (self.plot_id): GObject.source_remove(self.plot_id) if (self.plotter_id): GObject.source_remove(self.plotter_id) #self.plot_timer.stop() # Empty stale data self.data_buf = ""
def streamer(device,subdevice,chans,comedi_range,shared_array): ''' read the channels defined in chans, on the device/subdevice, and streams the values in the shared_array. The shared_array has a lock, to avoid reading and writing at the same time and it's process-proof. device: '/dev/comedi0' subdevice : 0=in, 1=out chans : [0,1,2,3,4....] : BE AWARE the reading is done crescendo, no matter the order given here. It means that [0,1,2] and [2,0,1] will both have [0,1,2] as result, but you can ask for [0,1,5]. comedi_range: same size as chans, with the proper range for each chan. If unknown, try [0,0,0,....]. shared_array: same size as chans, must be defined before with multiprocess.Array: shared_array= Array('f', np.arange(len(chans))) ''' dev=c.comedi_open(device) if not dev: raise "Error openning Comedi device" fd = c.comedi_fileno(dev) #get a file-descriptor for use later BUFSZ = 10000 #buffer size freq=8000# acquisition frequency: if too high, set frequency to maximum. nchans = len(chans) #number of channels aref =[c.AREF_GROUND]*nchans mylist = c.chanlist(nchans) #create a chanlist of length nchans maxdata=[0]*(nchans) range_ds=[0]*(nchans) for index in range(nchans): #pack the channel, gain and reference information into the chanlist object mylist[index]=c.cr_pack(chans[index], comedi_range[index], aref[index]) maxdata[index]=c.comedi_get_maxdata(dev,subdevice,chans[index]) range_ds[index]=c.comedi_get_range(dev,subdevice,chans[index],comedi_range[index]) cmd = c.comedi_cmd_struct() period = int(1.0e9/freq) # in nanoseconds ret = c.comedi_get_cmd_generic_timed(dev,subdevice,cmd,nchans,period) if ret: raise "Error comedi_get_cmd_generic failed" cmd.chanlist = mylist # adjust for our particular context cmd.chanlist_len = nchans cmd.scan_end_arg = nchans cmd.stop_arg=0 cmd.stop_src=c.TRIG_NONE t0 = time.time() j=0 ret = c.comedi_command(dev,cmd) if ret !=0: raise "comedi_command failed..." #Lines below are for initializing the format, depending on the comedi-card. data = os.read(fd,BUFSZ) # read buffer and returns binary data data_length=len(data) #print maxdata #print data_length if maxdata[0]<=65536: # case for usb-dux-D n = data_length/2 # 2 bytes per 'H' format = `n`+'H' elif maxdata[0]>65536: #case for usb-dux-sigma n = data_length/4 # 2 bytes per 'H' format = `n`+'I' #print struct.unpack(format,data) # init is over, start acquisition and stream last_t=time.time() try: while True: #t_now=time.time() #while (t_now-last_t)<(1./frequency): #t_now=time.time() ##print t_now-last_t #last_t=t_now data = os.read(fd,BUFSZ) # read buffer and returns binary data #print len(data), data_length if len(data)==data_length: datastr = struct.unpack(format,data) # convert binary data to digital value if len(datastr)==nchans: #if data not corrupted for some reason #shared_array.acquire() for i in range(nchans): shared_array[i]=c.comedi_to_phys((datastr[i]),range_ds[i],maxdata[i]) #print datastr #shared_array.release() #j+=1 #print j #print "Frequency= ",(j/(time.time()-t0)) #print np.transpose(shared_array[:]) except (KeyboardInterrupt): c.comedi_cancel(dev,subdevice) ret = c.comedi_close(dev) if ret !=0: raise "comedi_close failed..."
ret = c.comedi_command(dev,cmd) if ret<0: raise "error executing comedi_command" while flag: print 'buffer offset', c.comedi_get_buffer_offset(device, subdevice) print ' buffer contents', c.comedi_get_buffer_contents(device, subdevice) front += c.comedi_get_buffer_contents(dev,subdevice) print "front = ", front if front > time_limit: flag = 0 t1 = time.time() # reached "secs" seconds c.comedi_cancel(device, subdevice) c.comedi_poll(device, subdevice) c.comedi_close(dev) break if (front<back): t1 = time.time() # reached "secs" seconds print "front<back" print "ERROR comedi_get_buffer_contents" c.comedi_cancel(device, subdevice) c.comedi_poll(device, subdevice) break if (front==back): print 'sleep' #~ time.sleep(.001) time.sleep(pause)
def stop(aichIC, aichEC, aichFR, dt, xunits, yunitsIC, yunitsEC, gainIC, gainEC, fn, ftmpIC, fntmpIC, ftmpEC, fntmpEC, ftmpFR, fntmpFR, entmp, s, connic, connec, connfr, plot_sample, databstr_old): # Close device: ret = c.comedi_cancel(aichIC.dev, aichIC.subdev) # time stamp for last sample s.send(np.array([time.time(),], dtype=np.float64).tostring()) if ret != 0: comedi_errcheck() # Empty buffer: # ret = c.comedi_poll(aich.dev, aich.subdev) # if ret < 0: # comedi_errcheck() read_buffer(aichIC, aichEC, aichFR, gainIC, gainEC, connic, connec, connfr, plot_sample, ftmpIC, ftmpEC, ftmpFR, databstr_old) ftmpIC.close() ftmpEC.close() ftmpFR.close() # Scale temporary file: sys.stdout.write("NICOMEDI: Saving to file: Reading temp file...\n") sys.stdout.flush() ftmpIC = open(fntmpIC, 'rb') ftmpEC = open(fntmpEC, 'rb') ftmpFR = open(fntmpFR, 'rb') databstrIC = ftmpIC.read() databstrEC = ftmpEC.read() databstrFR = ftmpFR.read() sys.stdout.write("NICOMEDI: Saving to file: Processing data...\n") sys.stdout.flush() datalistIC = np.fromstring(databstrIC, np.float32) datalistEC = np.fromstring(databstrEC, np.float32) frames = np.fromstring(databstrFR, np.int8) # Write to hdf5: sys.stdout.write("NICOMEDI: Saving to file: Converting to hdf5...\n") sys.stdout.flush() chlist = [stfio.Channel([stfio.Section(np.array(datalistIC, dtype=np.float)),]), stfio.Channel([stfio.Section(np.array(datalistEC, dtype=np.float)),])] chlist[0].yunits = yunitsIC chlist[1].yunits = yunitsEC rec = stfio.Recording(chlist) rec.dt = dt # set sampling interval rec.xunits = xunits # set time units sys.stdout.write("NICOMEDI: Saving to file: Writing hdf5 to %s..." % fn) sys.stdout.flush() if sys.version_info >= (3,): rec.write(fn) else: rec.write(fn.encode('latin-1')) sys.stdout.write("done\n") sys.stdout.flush() # Write frame transition times if frames[0] != 0: sys.stdout.write("NICOMEDI: Warning: first frame isn't 0\n") edges = find_edges(frames) etmp = open(entmp, 'wb') etmp.write(edges.astype(np.int32).tostring()) etmp.close() # Close and delete temp file: ftmpIC.close() ftmpEC.close() ftmpFR.close() # Do not remove temp files, CSH 2013-10-11 # os.remove(fntmpIC) # os.remove(fntmpEC) # os.remove(fntmpFR) sys.stdout.write("\nNICOMEDI: Stopping acquisition, read %d samples\n" \ % len(datalistIC)) sys.stdout.flush() sys.stdout.write("NICOMEDI: Synchronizing in background\n") locald = os.path.dirname(fn) netd = os.path.dirname(locald.replace(settings.local_data_dir, settings.net_data_dir_mnt)) + '/' if not os.path.exists(netd): args = ["/usr/local/bin/sync_rackstation.sh"] else: netd = os.path.dirname(locald.replace(settings.local_data_dir, settings.net_data_dir)) + """/'""" args = ["/usr/bin/rsync", "-a", locald, netd] subprocess.Popen(args)
def close(self): c.comedi_cancel(self.device, self.subdevice) ret = c.comedi_close(self.device) if ret != 0: print('Comedi.close failed')
def streamer(device, subdevice, chans, comedi_range, shared_array): ''' read the channels defined in chans, on the device/subdevice, and streams the values in the shared_array. The shared_array has a lock, to avoid reading and writing at the same time and it's process-proof. device: '/dev/comedi0' subdevice : 0=in, 1=out chans : [0,1,2,3,4....] : BE AWARE the reading is done crescendo, no matter the order given here. It means that [0,1,2] and [2,0,1] will both have [0,1,2] as result, but you can ask for [0,1,5]. comedi_range: same size as chans, with the proper range for each chan. If unknown, try [0,0,0,....]. shared_array: same size as chans, must be defined before with multiprocess.Array: shared_array= Array('f', np.arange(len(chans))) ''' dev = c.comedi_open(device) if not dev: raise "Error openning Comedi device" fd = c.comedi_fileno(dev) #get a file-descriptor for use later BUFSZ = 10000 #buffer size freq = 8000 # acquisition frequency: if too high, set frequency to maximum. nchans = len(chans) #number of channels aref = [c.AREF_GROUND] * nchans mylist = c.chanlist(nchans) #create a chanlist of length nchans maxdata = [0] * (nchans) range_ds = [0] * (nchans) for index in range( nchans ): #pack the channel, gain and reference information into the chanlist object mylist[index] = c.cr_pack(chans[index], comedi_range[index], aref[index]) maxdata[index] = c.comedi_get_maxdata(dev, subdevice, chans[index]) range_ds[index] = c.comedi_get_range(dev, subdevice, chans[index], comedi_range[index]) cmd = c.comedi_cmd_struct() period = int(1.0e9 / freq) # in nanoseconds ret = c.comedi_get_cmd_generic_timed(dev, subdevice, cmd, nchans, period) if ret: raise "Error comedi_get_cmd_generic failed" cmd.chanlist = mylist # adjust for our particular context cmd.chanlist_len = nchans cmd.scan_end_arg = nchans cmd.stop_arg = 0 cmd.stop_src = c.TRIG_NONE t0 = time.time() j = 0 ret = c.comedi_command(dev, cmd) if ret != 0: raise "comedi_command failed..." #Lines below are for initializing the format, depending on the comedi-card. data = os.read(fd, BUFSZ) # read buffer and returns binary data data_length = len(data) #print maxdata #print data_length if maxdata[0] <= 65536: # case for usb-dux-D n = data_length / 2 # 2 bytes per 'H' format = ` n ` + 'H' elif maxdata[0] > 65536: #case for usb-dux-sigma n = data_length / 4 # 2 bytes per 'H' format = ` n ` + 'I' #print struct.unpack(format,data) # init is over, start acquisition and stream last_t = time.time() try: while True: #t_now=time.time() #while (t_now-last_t)<(1./frequency): #t_now=time.time() ##print t_now-last_t #last_t=t_now data = os.read(fd, BUFSZ) # read buffer and returns binary data #print len(data), data_length if len(data) == data_length: datastr = struct.unpack( format, data) # convert binary data to digital value if len(datastr ) == nchans: #if data not corrupted for some reason #shared_array.acquire() for i in range(nchans): shared_array[i] = c.comedi_to_phys( (datastr[i]), range_ds[i], maxdata[i]) #print datastr #shared_array.release() #j+=1 #print j #print "Frequency= ",(j/(time.time()-t0)) #print np.transpose(shared_array[:]) except (KeyboardInterrupt): c.comedi_cancel(dev, subdevice) ret = c.comedi_close(dev) if ret != 0: raise "comedi_close failed..."
def close(self): """Close the device.""" c.comedi_cancel(self.device,self.subdevice) ret = c.comedi_close(self.device) if ret !=0: raise Exception('comedi_close failed...') #def _stream(self): #''' #[Deprecated] #Read the channels defined in chans, on the device/subdevice, #and streams the values in the shared_array. #''' #fd = c.comedi_fileno(self.device) # get a file-descriptor #self.BUFSZ = 10000 # buffer size #self.freq=8000 # acquisition frequency #nchans = len(self.channels) # number of channels #self.shared_array= Array('f',np.arange(nchans)) #self.aref =[c.AREF_GROUND]*nchans #mylist = c.chanlist(nchans) # create a chanlist of length nchans #maxdata=[0]*(nchans) #range_ds=[0]*(nchans) #for index in range(nchans): # pack informations into the chanlist #mylist[index]=c.cr_pack(self.channels[index], #self.range_num[index], self.aref[index]) #maxdata[index]=c.comedi_get_maxdata(self.device, #self.subdevice,self.channels[index]) #range_ds[index]=c.comedi_get_range(self.device, #self.subdevice,self.channels[index], #self.range_num[index]) #cmd = c.comedi_cmd_struct() #period = int(1.0e9/self.freq) # in nanoseconds #ret = c.comedi_get_cmd_generic_timed(self.device,self.subdevice, #cmd,nchans,period) #if ret: raise Exception("Error comedi_get_cmd_generic failed") #cmd.chanlist = mylist # adjust for our particular context #cmd.chanlist_len = nchans #cmd.scan_end_arg = nchans #cmd.stop_arg=0 #cmd.stop_src=c.TRIG_NONE #ret = c.comedi_command(self.device,cmd) #if ret !=0: raise Exception("comedi_command failed...") ##Lines below are for initializing the format, depending on the comedi-card. #data = os.read(fd,self.BUFSZ) # read buffer and returns binary data #data_length=len(data) #if maxdata[0]<=65536: # case for usb-dux-D #n = data_length/2 # 2 bytes per 'H' #format = `n`+'H' #elif maxdata[0]>65536: #case for usb-dux-sigma #n = data_length/4 # 2 bytes per 'H' #format = `n`+'I' ## init is over, start acquisition and stream ##last_t=time.time() #try: #while True: #data = os.read(fd,self.BUFSZ) # read buffer and returns binary #if len(data)==data_length: #datastr = struct.unpack(format,data) #if len(datastr)==nchans: #if data not corrupted #for i in range(nchans): #self.shared_array[i]=c.comedi_to_phys((datastr[i]), #range_ds[i],maxdata[i]) #except Exception as e: #print "error in comediSensor : ", e #self.close() #raise
def stop(aichIC, aichEC, aichFR, dt, xunits, yunitsIC, yunitsEC, gainIC, gainEC, fn, ftmpIC, fntmpIC, ftmpEC, fntmpEC, ftmpFR, fntmpFR, entmp, s, connic, connec, connfr, plot_sample, databstr_old): # Close device: ret = c.comedi_cancel(aichIC.dev, aichIC.subdev) # time stamp for last sample s.send(np.array([ time.time(), ], dtype=np.float64).tostring()) if ret != 0: comedi_errcheck() # Empty buffer: # ret = c.comedi_poll(aich.dev, aich.subdev) # if ret < 0: # comedi_errcheck() read_buffer(aichIC, aichEC, aichFR, gainIC, gainEC, connic, connec, connfr, plot_sample, ftmpIC, ftmpEC, ftmpFR, databstr_old) ftmpIC.close() ftmpEC.close() ftmpFR.close() # Scale temporary file: sys.stdout.write("NICOMEDI: Saving to file: Reading temp file...\n") sys.stdout.flush() ftmpIC = open(fntmpIC, 'rb') ftmpEC = open(fntmpEC, 'rb') ftmpFR = open(fntmpFR, 'rb') databstrIC = ftmpIC.read() databstrEC = ftmpEC.read() databstrFR = ftmpFR.read() sys.stdout.write("NICOMEDI: Saving to file: Processing data...\n") sys.stdout.flush() datalistIC = np.fromstring(databstrIC, np.float32) datalistEC = np.fromstring(databstrEC, np.float32) frames = np.fromstring(databstrFR, np.int8) # Write to hdf5: sys.stdout.write("NICOMEDI: Saving to file: Converting to hdf5...\n") sys.stdout.flush() chlist = [ stfio.Channel([ stfio.Section(np.array(datalistIC, dtype=np.float)), ]), stfio.Channel([ stfio.Section(np.array(datalistEC, dtype=np.float)), ]) ] chlist[0].yunits = yunitsIC chlist[1].yunits = yunitsEC rec = stfio.Recording(chlist) rec.dt = dt # set sampling interval rec.xunits = xunits # set time units sys.stdout.write("NICOMEDI: Saving to file: Writing hdf5 to %s..." % fn) sys.stdout.flush() if sys.version_info >= (3, ): rec.write(fn) else: rec.write(fn.encode('latin-1')) sys.stdout.write("done\n") sys.stdout.flush() # Write frame transition times if frames[0] != 0: sys.stdout.write("NICOMEDI: Warning: first frame isn't 0\n") edges = find_edges(frames) etmp = open(entmp, 'wb') etmp.write(edges.astype(np.int32).tostring()) etmp.close() # Close and delete temp file: ftmpIC.close() ftmpEC.close() ftmpFR.close() # Do not remove temp files, CSH 2013-10-11 # os.remove(fntmpIC) # os.remove(fntmpEC) # os.remove(fntmpFR) sys.stdout.write("\nNICOMEDI: Stopping acquisition, read %d samples\n" \ % len(datalistIC)) sys.stdout.flush() sys.stdout.write("NICOMEDI: Synchronizing in background\n") locald = os.path.dirname(fn) netd = os.path.dirname( locald.replace(settings.local_data_dir, settings.net_data_dir_mnt)) + '/' if not os.path.exists(netd): args = ["/usr/local/bin/sync_rackstation.sh"] else: netd = os.path.dirname( locald.replace(settings.local_data_dir, settings.net_data_dir)) + """/'""" args = ["/usr/bin/rsync", "-a", locald, netd] subprocess.Popen(args)
def comedi_reset(self): #self.collect_data_stop() ret = c.comedi_cancel(self.dev,self.subdevice) if ret!=0: self.logger.error("Error executing comedi reset") return -1