Exemple #1
0
def imagecapture_part(xb, yb, xe, ye, nx, ny, n):
    dev = comedi.comedi_open("/dev/comedi0")
    outsubdevice = 1
    insubdevice = 0
    xchannel = 0
    ychannel = 1
    inchannel = 0
    analogref = comedi.AREF_GROUND
    arange =  0

    image = numpy.zeros((nx,ny), float)
	
    for y in range(ny, 0, -1):
        y = y-1
        write_data = int(  (float(y)/(ny-1) *(ye-yb) + yb ) * 65535)
        msg = comedi.comedi_data_write(dev, outsubdevice, ychannel, arange, analogref, write_data)
        for x in range(0, nx):
#            print "( " + str(x) + ", " + str(y) + ")" 
            write_data = int(  (float(x)/(nx-1) * (xe-xb) + xb ) * 65535)
            msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
            pixel = 0.0
            for i in range(0, n):
                result = comedi.comedi_data_read(dev,insubdevice,inchannel,arange,analogref)
                pixel = pixel + float(result[1])
            pixel = pixel/n
#            print pixel,
            msg=result[0]
            image[x][y] = pixel
        print
		
    comedi.comedi_close(dev)
    return image
Exemple #2
0
    def measure(self,arange,aref,num_scans):
        device = _comedi.comedi_open(comedidev)
        if not device:
             raise Exception('error opening Comedi device {}'.format(
                comedidev))
        setup_read_insn = SetupReadInsn(
            subdevice=subdevice, channel=channel,
            aref=aref, range=arange, n_scan=num_scans)

        insns = setup_insns(
            device, [setup_gtod_insn, setup_read_insn, setup_gtod_insn])
        ret = _comedi.comedi_do_insnlist(device, insns)
        if ret != insns.n_insns:
            raise Exception('error running instructions ({})'.format(ret))
            ret = _comedi.comedi_close(device)
            if ret != 0:
                raise Exception('error closing Comedi device')

        array = _comedi.insn_array.frompointer(insns.insns)
        t1 = get_time_of_day(array[0])
        t2 = get_time_of_day(array[2])
        data = _comedi.lsampl_array.frompointer(array[1].data)
        vals = []
        for i in range(array[1].n):
            vals.append(data[i])
        #sig=str((sum(vals) / float(len(vals))))
        sig=float(median(vals))
        free_insns(insns)
        ret = _comedi.comedi_close(device)
        return(sig)
Exemple #3
0
def getimage(nx, ny, n):
	dev = comedi.comedi_open("/dev/comedi0")
	outsubdevice = 1
	insubdevice = 0
	xchannel = 0
	ychannel = 1
	inchannel = 0
	analogref = comedi.AREF_GROUND
	arange =  0
	
	image = numpy.zeros((nx,ny), float)
	
	for y in range(0, ny):
		write_data = int(  (float(y)/(ny-1) ) * 65535)	
		msg = comedi.comedi_data_write(dev, outsubdevice, ychannel, arange, analogref, write_data)
		for x in range(0, nx):
			write_data = int(  (float(x)/(nx-1) ) * 65535)
			msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
			pixel = 0.0
			for i in range(0, n):
				result = comedi.comedi_data_read(dev,insubdevice,inchannel,arange,analogref)
				pixel = pixel + float(result[1])
			pixel = pixel/n
#			print pixel,
			msg=result[0]
			image[x][y] = pixel
#		print
		
	comedi.comedi_close(dev)
	return pixel
Exemple #4
0
def setx(voltage):
    dev = comedi.comedi_open("/dev/comedi0")
    outsubdevice = 1
    insubdevice = 0
    xchannel = 0
    ychannel = 1
    inchannel = 0
    analogref = comedi.AREF_GROUND
    arange =  0
    write_data = int(  (float(voltage)+10)/20*65535)
    msg = comedi.comedi_data_write(dev, outsubdevice, xchannel, arange, analogref, write_data)
    comedi.comedi_close(dev)
Exemple #5
0
def diowrite(subdevice, channel, data):
	dev = comedi.comedi_open("/dev/comedi0")
	ret1 = comedi.comedi_dio_config(dev, subdevice, channel, comedi.COMEDI_OUTPUT)

	if ret1 == 1:
		pass
	else:
		print "initialisation failed"
		
	ret=comedi.comedi_dio_write(dev, subdevice, channel, data)

	if ret == 1:
		pass
	else:
		print "setting failed"
	comedi.comedi_close(dev)
Exemple #6
0
def timedbeamunblank(delay):
    dev = comedi.comedi_open("/dev/comedi0")

    subdevice = 2
    channel = 0
    data = 0
    ret1 = comedi.comedi_dio_config(dev, subdevice, channel, comedi.COMEDI_OUTPUT)

    if ret1 == 1:
        pass
    else:
        print "initialisation failed"

    start_time = datetime.datetime.now()   
    ret=comedi.comedi_dio_write(dev, subdevice, channel, data)
    blanked_time = datetime.datetime.now()
    
    if ret == 1:
        pass
    else:
        print "setting failed"

    time.sleep(delay)
        
    data = 1
    ret=comedi.comedi_dio_write(dev, subdevice, channel, data)
    end_time = datetime.datetime.now()

    print "blanked_time =", blanked_time  - start_time
    print "end_time =", end_time  - start_time
    
    if ret == 1:
        pass
    else:
        print "setting failed"

    comedi.comedi_close(dev)
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)
        continue
Exemple #8
0
 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..."
Exemple #10
0
    if (front == back):
        time.sleep(.01)
        continue
    DATA = array.array("H")  # reset array to empty
    ## 	nbytes = front - back
    ## 	chunk_limit = (nbytes / size) * size # count for "size" sized chunks
    ## 	remainder = nbytes%size # bytes left after chunk_limit chunks done
    ## 	for i in range(0,chunk_limit,size):
    ## 		DATA.fromstring(map.read(size)) # read chunks
    ## 	for i in range(0,remainder,2):
    ## 		DATA.fromstring(map.read(2)) # read remaining bytes
    map.seek(back % size)
    for i in range(back, front, 2):
        DATA.fromstring(map.read(2))
        if map.tell() == size:
            map.seek(0)
    DATA.tofile(of)  # append data to log file
    ## 	time.sleep(.01)
    ret = c.comedi_mark_buffer_read(dev, subdevice, front - back)
    if ret < 0:
        raise Exception("error comedi_mark_buffer_read")
    back = front
print("bytes read = ", front)
c.comedi_close(dev)
if ret < 0:
    raise Exception("ERROR executing comedi_close")
of.flush()
of.close()

print("Elapsed time = %d seconds" % (t1 - t0))
Exemple #11
0
	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
Exemple #12
0
def shutdown(aich):
    ret = c.comedi_close(aich.dev)
    if ret != 0:
        comedi_errcheck()
Exemple #13
0
while True:
    startTime = time.time()
    ret, rdata = c.comedi_data_read(comediDevice, inputSubdev, channel, theRange, aref)

    voltage = c.comedi_to_phys(rdata, inputRange, inputMaxdata); 
    #print "Voltage: %f" % voltage

    x1 = voltage
    x2 = x1*voltage
    x3 = x2*voltage
    x4 = x3*voltage
    x5 = x4*voltage

    dist = -14.153*x5+110.18*x4-339.89*x3+538.13*x2-479.23*x1+243.35
    #print "Distance: %f" % dist

    if dist > 50:
        wdata = outputMaxdata/2 + 1000
    else:
        wdata = outputMaxdata/2


    #print 'Writing %d to the motor' % wdata
    c.comedi_data_write(comediDevice, outputSubdev, channel, theRange, aref, wdata)
    print time.time() - startTime

    #time.sleep(1)

print "Closing %s" % str(comediDevice)
c.comedi_close(comediDevice)
 def __del__(self):
     self.logger.info("Deleting Myself")
     self.collect_data_stop()
     self.map.close()
     c.comedi_close(self.dev)
Exemple #15
0
while (1):
	#ret = c.comedi_poll(dev,subdevice)
	#print("poll ret = ", ret)
	data = os.read(fd,BUFSZ)
	#print("len(data) = ", len(data))
	if len(data)==0:
		break
	n = len(data)/2 # 2 bytes per 'H'
	format = repr(n)+'H'
	#print("format = ", format)
	#bytes = struct.calcsize(format)
	#print("bytes = ", bytes)
	#nbytes = c.comedi_get_buffer_contents(dev,subdevice)
	#print("n = ", n, " nbytes = ", nbytes)
	datastr = datastr + struct.unpack(format,data)

t1 = time.time()
print("start time : ", t0)
print("end time : ", t1)
print("time : ", t1 - t0, " seconds")

count = 0
while count < len(datastr):
	for i in range(4):
		print("%d\t" % datastr[count+i])
	print("\n")
	count = count + 4
	
ret = c.comedi_close(dev)
if ret !=0: raise Exception("comedi_close failed...")
Exemple #16
0
 def close(self):
     s = comedi.comedi_close(self.device)
     if s < 0:
         raise InterfaceError('could not close comedi device %s(%s)' % (self.device_name, self.device))
Exemple #17
0
 def close(self):
     """close the output."""
     # c.comedi_cancel(self.device,self.subdevice)
     ret = c.comedi_close(self.device)
     if ret != 0:
         raise Exception("comedi_close failed...")
Exemple #18
0
        raise Exception('error opening Comedi device {}'.format(args.filename))

    setup_read_insn = SetupReadInsn(subdevice=args.subdevice,
                                    channel=args.channel,
                                    aref=args.aref,
                                    range=args.range,
                                    n_scan=args.num_scans)

    insns = setup_insns(device,
                        [setup_gtod_insn, setup_read_insn, setup_gtod_insn])

    ret = _comedi.comedi_do_insnlist(device, insns)
    if ret != insns.n_insns:
        raise Exception('error running instructions ({})'.format(ret))

    ret = _comedi.comedi_close(device)
    if ret != 0:
        raise Exception('error closing Comedi device {} ({})'.format(
            args.filename, ret))

    array = _comedi.insn_array.frompointer(insns.insns)
    t1 = get_time_of_day(array[0])
    t2 = get_time_of_day(array[2])
    print('initial time: {}'.format(t1))
    print('final time:   {}'.format(t2))
    print('difference:   {}'.format(t2 - t1))
    print('data:')
    data = _comedi.lsampl_array.frompointer(array[1].data)
    for i in range(array[1].n):
        print(data[i])
Exemple #19
0
    print "Cannot load comedi module, please install python-libcomedi"

def SetComediDevice():
    if os.path.isfile("/proc/comedi"):
        device = "/dev/comedi0"
        try:
            dev = comedi.comedi_open(device)
            global insubdevice
            insubdevice = comedi.comedi_get_read_subdevice(dev)
        #    print "subdevice for input = " + str(insubdevice)
            global outsubdevice
            outsubdevice = comedi.comedi_get_write_subdevice(dev)
        #    print "subdevice for output = " + str(outsubdevice)

            return "/dev/comedi0"
        except:
            print "cannot open /dev/comedi0, permissions?"
    else:
        return ""

device = SetComediDevice()
print "DAQ device is " + device 
print "subdevice for input = " + str(insubdevice)
print "subdevice for output = " + str(outsubdevice)

#

dev = comedi.comedi_open(device)
comedi.comedi_set_global_oor_behavior(comedi.COMEDI_OOR_NUMBER)
comedi.comedi_close(dev)
Exemple #20
0
def main():
    # Find comedi analog device number
    try:
        with open(COMEDI_PROC_F) as f:
            #print(f)
            for line in f.readlines():
                m_analog = re.match(PCI_6033E_PATTERN, line)
                m_digital = re.match(PCI_DIO_32HS_PATTERN, line)
                if m_analog:
                    print(m_analog.group())
                    dev_number = m_analog.groups()[0]
                    analog_dev_fname = "/dev/comedi" + dev_number
                if m_digital:
                    print(m_digital.group())
                    dev_number = m_digital.groups()[0]
                    digital_dev_fname = "/dev/comedi" + dev_number
    except IOError:
        print("Could not find file: %s" % COMEDI_PROC_F)

    if (f):
        f.close()

    if (analog_dev_fname):
        analog_dev = c.comedi_open(analog_dev_fname)
        if not(analog_dev):
            print("Unable to open analog comedi device...")
        
        ret = c.comedi_lock(analog_dev, 0)
        if (ret < 0):
            print("Could not lock comedi device")

        ret = c.comedi_get_max_buffer_size(analog_dev, 0)
        if (ret > 0):
            print("analog max buffer size: %i" % ret)
        else:
            print("Failed to get analog dev max buffer size...")

        ret = c.comedi_set_max_buffer_size(analog_dev, 0, MAX_BUFFER_SIZE)
        if (ret > 0):
            print("analog dev new buffer size: %i" % ret)
        else:
            print("Failed to analog dev set max buffer size...")

        c.comedi_close(analog_dev)


    if (digital_dev_fname):
        digital_dev = c.comedi_open(digital_dev_fname)
        if not(digital_dev):
            print("Unable to open digital comedi device...")
        
        ret = c.comedi_lock(digital_dev, 0)
        if (ret < 0):
            print("Could not lock digital comedi device")

        ret = c.comedi_get_max_buffer_size(digital_dev, 0)
        if (ret > 0):
            print("analog max buffer size: %i" % ret)
        else:
            print("Failed to get digital dev max buffer size...")

        ret = c.comedi_set_max_buffer_size(digital_dev, 0, MAX_BUFFER_SIZE)
        if (ret > 0):
            print("digital dev new buffer size: %i" % ret)
        else:
            print("Failed to digital dev set max buffer size...")

        c.comedi_close(digital_dev)
    def pci_6033e_init(self, dev_name):
        self.dev = c.comedi_open(dev_name)
        if not(self.dev):
            self.warn_dialog("Unable to open device: " + dev_name)
            return(-1)

        ret = c.comedi_lock(self.dev, SUBDEVICE)
        if (ret < 0):
            self.warn_dialog("Could not lock comedi device")
            return(-1)

        # get a file-descriptor for use later
        self.fd = c.comedi_fileno(self.dev)
        if (self.fd <= 0): 
            self.warn_dialog("Error obtaining Comedi device file descriptor")
            c.comedi_close(self.dev)
            return(-1)

        # Channel range (0-5V)
        if (c.comedi_range_is_chan_specific(self.dev, SUBDEVICE) != 0):
            self.warn_dialog("Comedi range is channel specific!")
            c.comedi_close(self.dev)
            return(-1)

        self.comedi_range = c.comedi_get_range(self.dev, SUBDEVICE, 0, CHAN_RANGE)
        self.comedi_maxdata = c.comedi_get_maxdata(self.dev, SUBDEVICE, 0)

        board_name = c.comedi_get_board_name(self.dev)
        if (board_name != "pci-6033e"):
            print("Opened wrong device!")
        
        # Prepare channels, gains, refs
        self.comedi_num_chans = NUM_CHANNELS
        chans = range(self.comedi_num_chans)
        gains = [0]*self.comedi_num_chans
        aref = [c.AREF_GROUND]*self.comedi_num_chans

        chan_list = c.chanlist(self.comedi_num_chans)

        # Configure all the channels!
        for i in range(self.comedi_num_chans):
            chan_list[i] = c.cr_pack(chans[i], gains[i], aref[i])

        # The comedi command
        self.cmd = c.comedi_cmd_struct()

        # 1.0e9 because this number is in nanoseconds for some reason
        period = int(1.0e9/float(SCAN_FREQ))

        # Init cmd
        ret = c.comedi_get_cmd_generic_timed(self.dev, SUBDEVICE, self.cmd, self.comedi_num_chans, period)
        if (ret):
            self.warn_dialog("Could not initiate command")
            c.comedi_close(self.dev)
            return(-1)

        # Populate command 
        self.cmd.chanlist = chan_list
        self.cmd.chanlist_len = self.comedi_num_chans
        self.cmd.scan_end_arg = self.comedi_num_chans
        self.cmd.stop_src = c.TRIG_NONE
        self.cmd.stop_arg = 0

        print("real timing: %d ns" % self.cmd.convert_arg)
        print("Real scan freq: %d Hz" % (1.0/(float(self.cmd.convert_arg)*32.0*1.0e-9)))
        #print("period: %d ns" % period)
    
        print_cmd(self.cmd)

        # Test command out.
        ret = c.comedi_command_test(self.dev, self.cmd)
        if (ret < 0):
            self.warn_dialog("Comedi command test failed!")
            c.comedi_close(self.dev)
            return(-1)

        print("Command test passed")

        return(0)
Exemple #22
0
 def close(self):
     s = comedi.comedi_close(self.device)
     if s < 0:
         raise InterfaceError('could not close comedi device %s(%s)' %
                              (self.device_name, self.device))
 def on_destroy(self, widget):
     if (self.dev):
         c.comedi_close(self.dev)
         print("Comedi device closed...")
     Gtk.main_quit()
Exemple #24
0
def shutdown(aich):
    ret = c.comedi_close(aich.dev)
    if ret != 0:
        comedi_errcheck()
Exemple #25
0
 def __del__(self):
     comedi.comedi_close(self.dev)
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..."
            _, zero_phydata = biases[chan_i][range_i]

            pbs[chan_i][range_i].set_value(phydata -
                                           zero_phydata)  #['value'] = data
            #print("[%.3f,%.3f] Raw %d  --> voltage %f" %(ranges[rn].min,ranges[rn].max,data,phydata))

    # This is the observed reading in each channel
    channels = [
        captured[ch][SELECTED_RANGE][1] for ch, _ in enumerate(CHANNELS)
    ]
    #bias     = [ biases[ch][SELECTED_RANGE][1]   for ch,_ in enumerate(CHANNELS) ] # this is the channel bias, not the G-value-bias (if you know what I mean...)

    # Now we compute the G0-G5 using the totally awkward combination
    gs = channels_to_g(channels)

    # Let's plot the Gs!
    for i, (greading, gb) in enumerate(zip(gs, gbias)):
        Glabels[i].set_value(greading - gb)

    forces = compute_forces(gs, gbias)
    for (forc, fl) in zip(forces, force_labels):
        fl.set_value(forc)

    dumpf.write(" ".join([str(x) for x in channels]) + "\n")

dumpf.close()

ret = c.comedi_close(dev)
if ret < 0:
    raise Exception("ERROR executing comedi_close")