示例#1
0
def TE_HIGH_ACC_RAW(handle,AIN_names):
    
    numAddresses = len(AIN_names)
    aScanList = ljm.namesToAddresses(numAddresses, AIN_names)[0]
    scanRate = 10000
    scansPerRead = scanRate

    aNames = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
              "STREAM_RESOLUTION_INDEX"]
    aValues = [ljm.constants.GND, 10.0, 0, 0] #single-ended, +/-10V, 0 (default),
                                              #0 (default)
    ljm.eWriteNames(handle, len(aNames), aNames, aValues)
    
    # Configure and start stream
    scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate)
    
    ret = ljm.eStreamRead(handle)
    
    acc_high_z_val = ret[0]
    
#    acc_high_z_val=[data[i]for i in range(0,len(data),1)]
#    ACC_LOW_Y_value=[data[i]for i in range(1,len(data),3)]
#    ACC_LOW_Z_value=[data[i]for i in range(2,len(data),3)]
    ljm.eStreamStop(handle)
    return acc_high_z_val
示例#2
0
def mainloop_reading(handle,scanres,readnum,readsize,wvfrmres,fq,verbosity,compar):
	'''
	Mainloop used for reading values and calculating the distance between two peaks. Could yield the values as they are calculating.

	handle variable is the labjack object
	scanres normaly equals to scanres from eStreamStart method
	channels gives out the number of channels that need to be read by the function
	readnum is the the number of time the while function will be read.
	'''
	count = 0
	if compar == True:
		data = np.empty(scanres*(readnum-1))
	while True:
		read = ljm.eStreamRead(handle)
		if compar == True:
			if count > 0:data[(count-1)*(scanres):count*scanres] = read[0][0:scanres]

		#Peak detection
		if count>0:
		 	dataaverage =  np.array([np.mean([(read[0][0:scanres])[y + (x*127/wvfrmres)] for x in range((readsize*wvfrmres) -1)]) for y in range(127/wvfrmres)]) 
		 	peakind = peak_detect_periodic(dataaverage,fq,scanrate)
			if len(peakind[0])==2:
				print('Ratio: {0}'.format((peakind[0][1]-peakind[0][0])*(wvfrmres*2)/127.0))
			else:
				if args.verbosity >0:print('NaN because of {0} spike(s) detected'.format(len(peakind[0])))
		if verbosity > 0:
			print('DeviceBufferStatus: {0}  LJMBufferStatus:{1}'.format(read[1],read[2]))
		count += 1
		if count >= readnum:
			if verbosity > 0 : print("Number of read obtained:{0}".format(count))
			break
		time.sleep(1/float(scanres * scanrate/127))
	if compar == True:
		return data
示例#3
0
 def get_stream(self):
   a = np.array(ljm.eStreamRead(self.handle)[0])
   r = a.reshape(len(a)//len(self.channels),len(self.channels))
   for i,c in enumerate(self.chan_list):
     r[:,i] = c['gain']*r[:,i]+c['offset']
   t = self.stream_t0+np.arange(self.n,self.n+r.shape[0])/self.scan_rate
   self.n += r.shape[0]
   return [t,r]
示例#4
0
 def ReadValue(self):
     """
     Reads ADC values from the analog inputs set to streaming mode.
     """
     # the structures for reading waveform data into
     data = np.array(eStreamRead(self.handle)[0]).reshape(
         -1, self.num_addresses)
     return data
示例#5
0
def stream_data(q, ljm_devices):
    print("Reading thread has started.")
    try:
        # ljm.eWriteAddress(ljm_device, 1000, ljm.constants.FLOAT32, 2.5)
        remaining_data = {}
        while True:
            #for _ in range(NUM_READS):
            for device_id in ljm_devices:
                print("Reading from {0}...".format(device_id))
                results = ljm.eStreamRead(ljm_devices[device_id])
                read_time = str(datetime.now())
                reading = {
                    "id": str(uuid4()),
                    "rpi_mac": get_device_mac(),
                    "device_id": device_id,
                    "read_time": read_time,
                    "data": results[0]
                }
                remaining_data[device_id] = results[1]
                q.put(reading)

        for device_id in ljm_devices:
            if (remaining_data.get(device_id, 0) > 0):
                print("Reading from {0}...".format(device_id))
                results = ljm.eStreamRead(ljm_devices[device_id])
                read_time = str(datetime.now())
                reading = {
                    "id": str(uuid4()),
                    "rpi_mac": get_device_mac(),
                    "device_id": device_id,
                    "read_time": read_time,
                    "data": results[0]
                }
                q.put(reading)

            ljm.eStreamStop(ljm_devices[device_id])
    except ljm.LJMError as ljmerr:
        print("Error occurred while streaming. Quiting streaming program.")
        print(ljmerr)

    finally:
        for device_id in ljm_devices:
            ljm.close(ljm_devices[device_id])
        global is_reading
        is_reading = False
    def readStreamOn(self, io_name, request_num, scansPerRead):
        """
            Function use for consulting value on the streamer
        :param io_name: input output name to scan
        :param request_num: number of request on the streamer -1 will be an infinite loop
        :param scansPerRead: number of scan per read
        :return:
        """
        i = 0
        request = request_num
        if request_num == -1:
            request = 0
        totScans = 0
        index = 0
        array = []
        totSkip = 0 # Total skipped samples
        for handle in self.handles:
            scanRate = ljm.eStreamStart(handle, scansPerRead, len(io_name), io_name, self.rate)
            array.append([0, 0])
        try:
            while i <= request:
                for handle in self.handles:
                    stream = ljm.eStreamRead(handle)

                    data = stream[0]
                    scans = len(data)/len(io_name)
                    totScans += scans

                    # Count the skipped samples which are indicated by -9999 values. Missed
                    # samples occur after a device's stream buffer overflows and are
                    # reported after auto-recover mode ends.
                    curSkip = data.count(-9999.0)
                    totSkip += curSkip
                    array[handle] = [array[handle][0] + data[0], array[handle][1] + data[1]]
                    if i % self.rate == 0 and i != 0:
                        ainStr = ""
                        for j in range(0, len(io_name)):
                            ainStr += "%s = %0.5f " % (io_name[j], array[handle][j] / self.rate)
                        print(ainStr)
                        array[handle] = [0, 0]
                    """print("\neStreamRead %i" % i)
                    ainStr = ""
                    for j in range(0, len(io_name)):
                        ainStr += "%s = %0.5f " % (io_name[j], data[j])
                    print(ainStr)"""
                    if request_num != -1:
                        i += 1
                    index += 1
                index = 0
        except ljm.LJMError:
            ljm_err = sys.exc_info()[1]
            print(ljm_err)
        except Exception:
            e = sys.exc_info()[1]
            print(e)
示例#7
0
 def get_stream(self):
   """
   Read the device buffer if scan_mode is set.
   """
   if not self.stream_started:
     self.start_stream()
   retrieved_from_buffer = ljm.eStreamRead(self.handle)
   results = retrieved_from_buffer[0]
   timer = time()
   if self.verbose:
     self.queue.put(
       [timer, retrieved_from_buffer[1], retrieved_from_buffer[2]])
   return timer, results
示例#8
0
def myStreamReadCallback(arg):
    global si

    if si.handle != arg:
        printWithLock("myStreamReadCallback - Unexpected argument: %d" % (arg))
        return

    # Check if stream is done so that we don't output the print statement below.
    if si.done:
        return

    string = "\niteration: %3d\n" % si.streamRead
    si.streamRead += 1

    try:
        ret = ljm.eStreamRead(si.handle)
        aData = ret[0]
        deviceScanBacklog = ret[1]
        ljmScanBackLog = ret[2]

        scans = len(aData) / si.numAddresses
        si.totScans += scans

        # Count the skipped samples which are indicated by -9999 values. Missed
        # samples occur after a device's stream buffer overflows and are
        # reported after auto-recover mode ends.
        curSkip = aData.count(-9999.0)
        si.totSkip += curSkip

        string += "  1st scan out of %i: " % scans
        for j in range(0, si.numAddresses):
            string += "%s = %0.5f, " % (si.aScanListNames[j], aData[j])
        string += "\n  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = %i" % \
                (curSkip/si.numAddresses, deviceScanBacklog, ljmScanBackLog)
        printWithLock(string)

    # If LJM has called this callback, the data is valid, but LJM_eStreamRead
    # may return LJME_STREAM_NOT_RUNNING if another thread (such as the Python
    # main thread) has stopped stream.
    except ljm.LJMError as err:
        if err.errorCode == ljm.errorcodes.STREAM_NOT_RUNNING:
            printWithLock("eStreamRead returned LJME_STREAM_NOT_RUNNING.")
        else:
            printWithLock(err)
def offset_calibration(handle, precision=2):
    '''With a linear sweep of every possible tension, the program finds the maximum voltage read'''
    linear = np.arange(2.5, 5, 2.5 / ((4 * 127) + 1))
    initialise_streamout(handle, linear, 4)
    ljm.eStreamStart(handle, (4 * 127), 2, [4800, 0], 150)
    data = np.empty(4 * 127)
    for x in range(precision):
        read = ljm.eStreamRead(handle)
        data = np.append(data, read[0][0:4 * 127])
    ljm.eStreamStop(handle)
    slope = ((2.5 * np.linspace(4 * 127, 2 * 4 * 127, 4 * 127)) / (4 * 127))
    data = np.convolve(data, signal.gaussian(4 * 127, 10),
                       'same')[(4 * 127) - 1:(2 * 4 * 127) - 1]
    peakind = np.array(
        signal.argrelmax(
            np.array([x if x > 0.99 * data.max() else 0 for x in data])))
    if peakind.mean() < len(slope):
        maxVoltage = slope[peakind.mean()]
        print('Maximum found for {0}'.format(maxVoltage))
    else:
        print('No maxima found, 3.75 will be the offset')
        maxVoltage = 3.75
    return maxVoltage
示例#10
0
	def readStream(self):
		"""Read the signal on all pre-definied channels at the same time."""
		try:
			#print "here1"
			ret = ljm.eStreamRead(self.handle)
			#print ret
			data = ret[0]
			#print "stream1", data
			try:
				#print "data : ",data
				#if self.scansPerRead!=1:
					#data=zip(*[iter(data)]*self.scansPerRead)
				curSkip = data.pop(-9999.0) # delete non-valid values
				print "skipped some data!"
			except TypeError : # No corrupted data
				data=[a*b+c for a,b,c in zip(data,self.gain*self.scansPerRead,self.offset*self.scansPerRead)] # apply coefficients
				#ret=OrderedDict(zip(['t(s)'],[time.time()]))
				#ret.update(OrderedDict(zip(self.channels,data)))
				#results=[a*b+c for a,b,c in zip(results,self.gain,self.offset)]
				#ret=OrderedDict(zip(['t(s)'],[time.time()]))
				#ret.update(OrderedDict(zip(channels,results)))
				#data.insert(0,)
				#print "data2 : ",data
				return time.time(),data
		except ljm.LJMError:
			#print "error 1"
			ljme = sys.exc_info()[1]
			print(ljme)
			self.close()
			raise Exception("Error in LabJack Streamer")
		except Exception:
			#print "exception in streamer"
			e = sys.exc_info()[1]
			print(e)
			self.close()
			raise
示例#11
0
 def AIn_read(self):
     return ljm.eStreamRead(self.labjack.handle)
示例#12
0
def generador_Frecuecia(f1, f2, f3, f4, nombre):

    fs = 20000
    # f = 500
    ciclo1 = f1 / 400.0000000
    ciclo1 = np.ceil(ciclo1)
    ciclo2 = f2 / 400.0000000
    ciclo2 = np.ceil(ciclo2)
    duration1 = np.float32(ciclo1 / f1)
    duration2 = np.float32(ciclo2 / f2)
    samples1 = (np.sin(2 * np.pi * np.arange(fs * duration1) * f1 /
                       fs)).astype(np.float32)
    samples1 = 2.0 * samples1 + 2.5
    samples2 = (np.sin(2 * np.pi * np.arange(fs * duration2) * f2 /
                       fs)).astype(np.float32)
    samples2 = 2.0 * samples2 + 2.5
    #plt.plot(samples)
    #plt.show()

    # print(len(samples1))
    # MAX_REQUESTS = 1000  # The number of eStreamRead calls that will be performed.

    # Open first found LabJack

    # handle = ljm.openS("ANY", "ANY", "ANY")

    info = ljm.getHandleInfo(handle)
    print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
          "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
          (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))

    # Desactivacion de parlantes
    t0 = time.time()
    ljm.eWriteName(handle, "FIO1", 0)
    ljm.eWriteName(handle, "FIO4", 0)
    ljm.eWriteName(handle, "FIO2", 0)
    ljm.eWriteName(handle, "FIO0", 0)
    t1 = time.time()
    TDes_parlantes = t0 - t1

    # Setup Stream Out
    OUT_NAMES = ["DAC0", "DAC1"]
    NUM_OUT_CHANNELS = len(OUT_NAMES)
    outAddress1 = ljm.nameToAddress(OUT_NAMES[0])[0]
    outAddress2 = ljm.nameToAddress(OUT_NAMES[0])[1]

    # Allocate memory for the stream-out buffer
    t0 = time.time()
    ljm.eWriteName(handle, "STREAM_OUT0_TARGET", 1000)
    ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 2048)
    ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)
    ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", len(samples1))
    ljm.eWriteName(handle, "STREAM_OUT1_TARGET", 1002)
    ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_SIZE", 2048)
    ljm.eWriteName(handle, "STREAM_OUT1_ENABLE", 1)
    ljm.eWriteName(handle, "STREAM_OUT1_LOOP_SIZE", len(samples2))
    freq1 = 80000000.000000000000000000 / 32
    freq1 = freq1 / f3
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 0)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 1)
    ljm.eWriteName(handle, "DIO3_EF_ENABLE", 0)
    ljm.eWriteName(handle, "DIO3_EF_INDEX", 0)
    ljm.eWriteName(handle, "DIO3_EF_OPTIONS", 1)
    ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1 / 2)
    ljm.eWriteName(handle, "DIO3_EF_ENABLE", 1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1)
    ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1 / 2)

    freq2 = 80000000.000000000000000000 / 32
    freq2 = freq2 / f4
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 0)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 1)
    ljm.eWriteName(handle, "DIO5_EF_ENABLE", 0)
    ljm.eWriteName(handle, "DIO5_EF_INDEX", 0)
    ljm.eWriteName(handle, "DIO5_EF_OPTIONS", 2)
    ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2 / 2)
    ljm.eWriteName(handle, "DIO5_EF_ENABLE", 1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2)
    ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2 / 2)

    for i in range(0, len(samples1)):
        ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", samples1[i])
    for i in range(0, len(samples2)):
        ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_F32", samples2[i])
    t1 = time.time()
    Tallocatememory = t0 - t1
    tm.sleep(1)

    ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1)
    ljm.eWriteName(handle, "STREAM_OUT1_SET_LOOP", 1)
    print("STREAM_OUT0_BUFFER_STATUS = %f" %
          (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS")))
    print("STREAM_OUT0_BUFFER_STATUS = %f" %
          (ljm.eReadName(handle, "STREAM_OUT1_BUFFER_STATUS")))

    # Stream Configuration
    aScanListNames = ["AIN2"]  # Scan list names to stream
    numAddresses = len(aScanListNames)
    aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0]
    scanRate = fs
    scansPerRead = int(scanRate / 1000)

    # Datos de Transformada de FFT
    T = 1.00000 / fs
    x = np.linspace(0.00, scansPerRead * T, scansPerRead)
    xf = np.linspace(0.00, 1.00 / (2.00 * T), scansPerRead / 2)
    # fig, (ax, bx) = plt.subplots(2, 1)

    # plt.ion()
    # Add the scan list outputs to the end of the scan list.
    # STREAM_OUT0 = 4800, STREAM_OUT1 = 4801, etc.
    aScanList.extend([4800])  # STREAM_OUT0
    # If we had more STREAM_OUTs
    aScanList.extend([4801])  # STREAM_OUT1
    # aScanList.extend([4802]) # STREAM_OUT2
    # aScanList.extend([4803]) # STREAM_OUT3

    try:
        # Configure the analog inputs' negative channel, range, settling time and
        # resolution.
        # Note when streaming, negative channels and ranges can be configured for
        # individual analog inputs, but the stream has only one settling time and
        # resolution.
        aNames = [
            "AIN2_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [3, 10.0, 0, 0]  # single-ended, +/-10V, 0 (default),
        # 0 (default)
        ljm.eWriteNames(handle, len(aNames), aNames, aValues)

        i = 1
        j = 0
        print("Empieza")
        t0 = time.time()
        scanRate = ljm.eStreamStart(handle, scansPerRead, 3, aScanList,
                                    scanRate)
        while j < 1:
            i = 1
            k = 0
            h = 0
            print(j)
            while (k < 1000):
                k = k + 1
                ret = ljm.eStreamRead(handle)
            # str=tm.time()
            seleccionador(j)
            # end=tm.time()
            while i:  # i <= M9A;X_REQUESTS:
                # for g in range(0,2):
                ret = ljm.eStreamRead(handle)
                data = ret[0][0:scansPerRead]
                # print("Hola")
                # start2 = datetime.now()
                yf = ft.fft(data)
                yf = 2.0 / scansPerRead * np.abs(yf[:scansPerRead // 2])
                # print("Hola2")
                #(peaks, indexes) = octave.findpeaks(yf, 'DoubleSided', 'MinPeakHeight', 0.04, 'MinPeakDistance', 100, 'MinPeakWidth', 0)
                # indexes = find_peaks_cwt(yf, np.arange(1, 2))
                indexes = peakutils.indexes(yf,
                                            thres=0.01 / max(yf),
                                            min_dist=100)
                print(indexes)
                i = silenciador(j, indexes)
                h = h + 1
                # end2 = datetime()

                # end = datetime.now
                # plt.close()
                # print("\nTotal scans = %i" % (totScans))
                # tt = (end - start).seconds + float((end - start).microseconds) / 1000000
            tt = h * 0.001
            # tt2= end-str
            print("Tiempo 1000Hz = %f seconds" % (tt))
            # print("Tiempo 500Hz = %f seconds" % (tt2))
            ANS[j] = (tt - OFFSET) * MULTIPLICITY
            j = j + 1

        # print("LJM Scan Rate = %f scans/second" % (scanRate))
        # print("Timed Scan Rate = %f scans/second" % (totScans / tt))
        # print("Timed Sample Rate = %f samples/second" % (totScans * numAddresses / tt))
        # print("Skipped scans = %0.0f" % (totSkip / numAddresses))
    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
    except Exception:
        e = sys.exc_info()[1]
        print(e)
    t1 = time.time()
    TstreamStart = t0 - t1

    ljm.eWriteName(handle, "FIO1", 0)
    ljm.eWriteName(handle, "FIO4", 0)
    ljm.eWriteName(handle, "FIO2", 0)
    ljm.eWriteName(handle, "FIO0", 0)
    h = 1
    for dato in ANS:
        print("Distancia %i : %f" % (h, dato))
        h = h + 1
    print("\nStop Stream")
    ljm.eStreamStop(handle)

    # Close handle
    ljm.close(handle)
    print("Termino")
示例#13
0
    output_names = [
        'TIME', 'AIN0', 'AIN1', 'AIN2', 'AIN3', 'AIN4', 'AIN5', 'AIN6', 'AIN7',
        'DIO0', 'DIO1', 'DIO2', 'DIO3'
    ]
    cur_log = "camber" + "_" + str(start.month) + "_" + str(
        start.day) + "_" + str(start.year) + "_" + str(start.hour) + "_" + str(
            start.minute) + "_" + str(start.second) + ".csv"

    with open(cur_log, "w") as f:
        writer = csv.writer(f)
        writer.writerow(output_names)

    while True:
        print("logging")
        streamRead = ljm.eStreamRead(handle)

        data = streamRead[0]
        data = np.reshape(data, (scansPerRead, len(aScanListNames)))

        a = data[:, 0]
        b = data[:, 1]
        ain0 = data[:, 2]
        ain1 = data[:, 3]
        ain2 = data[:, 4]
        ain3 = data[:, 5]
        ain4 = data[:, 6]
        ain5 = data[:, 7]
        ain6 = data[:, 8]
        ain7 = data[:, 9]
def main(initial_scan_rate_hz=INITIAL_SCAN_RATE_HZ,
         in_names=IN_NAMES,
         stream_outs=STREAM_OUTS,
         num_cycles=NUM_CYCLES):
    print("Beginning...")
    handle = open_ljm_device(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
    print_device_info(handle)

    print("Initializing stream out buffers...")
    out_contexts = []
    for stream_out in stream_outs:
        out_context = ljm_stream_util.create_out_context(stream_out)
        ljm_stream_util.initialize_stream_out(handle, out_context)
        out_contexts.append(out_context)

    print("")

    for out_context in out_contexts:
        print_register_value(handle, out_context["names"]["buffer_status"])

    for out_context in out_contexts:
        update_str = "Updating %(stream_out)s buffer whenever " \
            "%(buffer_status)s is greater or equal to " % out_context["names"]
        print(update_str + str(out_context["state_size"]))

    scans_per_read = int(
        min([context["state_size"] for context in out_contexts]))
    buffer_status_names = [
        out["names"]["buffer_status"] for out in out_contexts
    ]
    try:
        scan_list = ljm_stream_util.create_scan_list(in_names=in_names,
                                                     out_contexts=out_contexts)
        print("scan_list: " + str(scan_list))
        print("scans_per_read: " + str(scans_per_read))

        scan_rate = ljm.eStreamStart(handle, scans_per_read, len(scan_list),
                                     scan_list, initial_scan_rate_hz)
        print("\nStream started with a scan rate of %0.0f Hz." % scan_rate)
        print("\nPerforming %i buffer updates." % num_cycles)

        iteration = 0
        total_num_skipped_scans = 0
        while iteration < num_cycles:

            buffer_statuses = [0]
            infinity_preventer = 0
            while max(buffer_statuses) < out_context["state_size"]:
                buffer_statuses = ljm.eReadNames(handle,
                                                 len(buffer_status_names),
                                                 buffer_status_names)
                infinity_preventer = infinity_preventer + 1
                if infinity_preventer > scan_rate:
                    raise ValueError(
                        "Buffer statuses don't appear to be updating:" + \
                        str(buffer_status_names) + str(buffer_statuses)
                    )

            for out_context in out_contexts:
                ljm_stream_util.update_stream_out_buffer(handle, out_context)

            # ljm.eStreamRead will sleep until data has arrived
            stream_read = ljm.eStreamRead(handle)

            num_skipped_scans = ljm_stream_util.process_stream_results(
                iteration,
                stream_read,
                in_names,
                device_threshold=out_context["state_size"],
                ljm_threshold=out_context["state_size"])
            total_num_skipped_scans += num_skipped_scans

            iteration = iteration + 1

    except ljm.LJMError:
        ljm_stream_util.prepare_for_exit(handle)
        raise

    except Exception:
        ljm_stream_util.prepare_for_exit(handle)
        raise

    ljm_stream_util.prepare_for_exit(handle)

    print("Total number of skipped scans: %d" % total_num_skipped_scans)
示例#15
0
 def __stream_thread_callback(self, handle):
     values = ljm.eStreamRead(handle)
     self.__stream_callback(handle, values)
示例#16
0
 def syncStream(self, io_name, request_num, scansPerRead, array):
     """
         Function use for consulting value on the streamer
     :param io_name: input output name to scan
     :param request_num: number of request on the streamer
     :param scansPerRead: number of scan per read
     :return:
     """
     io_addr = ljm.namesToAddresses(len(io_name), io_name)[0]
     i = 0
     index = 0
     arraymed = []
     for handle in self.handles:
         """
             start stream on all devices.
         """
         scanRate = ljm.eStreamStart(handle, scansPerRead, len(io_addr), io_addr, self.rate)
         arraymed.append([])
         for j in range(len(io_name)):
             arraymed[index].append(0)
         index += 1
     index = 0
     try:
         while i <= request_num:
             j = 0
             for handle in self.handles:
                 """
                     append all data into an array of stream.
                     Example:
                     +---------+------+------------------------------+
                     | devices | scan | stream                       |
                     +---------+------+------------------------------+
                     |    0    |   0  | first scan out for a device  |
                     |         +------+------------------------------+
                     |         |   1  | second scan out for a device |
                     |         +------+------------------------------+
                     |         |   2  | third scan out for a device  |
                     |         +------+------------------------------+
                     |         |  ... | ............................ |
                     +---------+------+------------------------------+
                     |   ...   |  ... | ............................ |
                     +---------+------+------------------------------+
                 """
                 stream = ljm.eStreamRead(handle)
                 data = stream[0]
                 array[j].append(data)
                 for j in range(len(io_name)):
                     arraymed[index][j] = arraymed[index][j] + data[j]
                 if i % self.rate == 0 and i != 0:
                     print("\neStreamRead from %i to %i" % (i - self.rate, i))
                     ainStr = ""
                     for j in range(0, len(io_name)):
                         ainStr += "%s = %0.5f " % (io_name[j], arraymed[index][j] / self.rateself.rat * 2)
                     print(ainStr)
                     for j in range(0, len(arraymed[index])):
                         arraymed[index][j] = 0
                 """print("\neStreamRead %i" % i)
                 ainStr = ""
                 for j in range(0, len(io_name)):
                     ainStr += "%s = %0.5f " % (io_name[j], data[j])
                 print(ainStr)"""
                 j += 1
                 index += 1
             index = 0
             i += 1
     except ljm.LJMError:
         ljm_err = sys.exc_info()
         print(ljm.ljm.errorToString(1279))
         print(ljm_err)
     except Exception:
         e = sys.exc_info()
         print(e)
     """for i in range(len(self.handles)):
示例#17
0
def stream_to_file(handle,
                   samples_per_point,
                   points_per_write,
                   sampling_rate,
                   address_names,
                   fname_preamble,
                   temp_scale=50,
                   voltage_offset=0.):
    def signal_handler(signal, frame):
        global stop_scan
        stop_scan = True
        print("Stopping scan (KeyboardInterrupt)")

    signal.signal(signal.SIGINT, signal_handler)
    mean_vector = np.zeros(samples_per_point)
    write_buffer = np.zeros((points_per_write, 2))
    num_addresses = len(address_names)
    aScanList = ljm.namesToAddresses(num_addresses, address_names)[0]
    start = 0
    tot_scans = 0
    tot_skip = 0
    total_points = 0
    try:
        ljm.eWriteName(handle, "STREAM_TRIGGER_INDEX", 0)
        ljm.eWriteName(handle, "STREAM_CLOCK_SOURCE", 0)

        scanRate = ljm.eStreamStart(handle, sampling_rate, num_addresses,
                                    aScanList, sampling_rate)
        print(f"Stream started with {sampling_rate:.1f} Hz sampling rate")

        start = datetime.now()
        means = 0
        points = 0
        stop_scan = False
        while not stop_scan:
            ret = ljm.eStreamRead(handle)
            aData = ret[0]
            tot_scans += len(aData)
            mean_vector[means] = np.mean(aData)
            # Count the skipped samples which are indicated by -9999 values.
            # Missed samples occur after a device's stream buffer overflows and
            # are reported after auto-recover mode ends.
            cur_skip = aData.count(-9999.0)
            tot_skip += cur_skip
            means += 1
            if means == samples_per_point:
                write_buffer[points, :] = [
                    time.time(),
                    volt_to_temp(np.mean(mean_vector), 50., 0.)
                ]
                points += 1
                means = 0
                mean_vector = np.zeros(samples_per_point)
            if points == points_per_write:
                fname = fname_from_time(fname_preamble)
                print(f"writing to file {fname}")
                append_to_file(fname, write_buffer)
                points = 0
                write_buffer = np.zeros((points_per_write, 2))
                total_points += points_per_write

    except ljm.LJMError:
        print(sys.exc_info()[1])
    except Exception:
        print(sys.exc_info()[1])
    finally:
        fname = fname_from_time(fname_preamble)
        print(f"writing to file {fname}")
        append_to_file(fname, write_buffer[np.nonzero(write_buffer[:, 1])])
        total_points += len(np.nonzero(write_buffer))
        end = datetime.now()
        print("\nTotal scans = %i" % (tot_scans))
        print("\nTotal points saved = %i" % (total_points))
        tt = (end - start).seconds + float((end - start).microseconds) / 1e6
        print("Time taken = %f seconds" % (tt))
        print("LJM Scan Rate = %f scans/second" % (scanRate))
        print("Timed Scan Rate = %f scans/second" % (tot_scans / tt))
        print("Timed Sample Rate = %f samples/second" %
              (tot_scans * num_addresses / tt))
        print("Skipped scans = %0.0f" % (tot_skip / num_addresses))
        try:
            print("Stopping stream.")
            ljm.eStreamStop(handle)
        except ljm.LJMError:
            print(sys.exc_info()[1])
        except Exception:
            print(sys.exc_info()[1])
        return {
            'Total scans': tot_scans,
            'Saved points': total_points,
            'Scan time': tt,
            'LJM scan rate': scanRate,
            'Timed scan rate': tot_scans / tt,
            'Timed sample rate': tot_scans * num_addresses / tt,
            'Skipped scans': tot_skip / num_addresses
        }
示例#18
0
def StreamCollection(max_requests=60, scanrate=1000, bKick=True, minSum=-1.0):
    #time will take about max_requests/2 in seconds

    MAX_REQUESTS = max_requests  # The number of eStreamRead calls that will be performed.
    FIRST_AIN_CHANNEL = 0  #AIN0
    NUMBER_OF_AINS = 3  # AIN0: L-R, AIN1: Sum, AIN2: T-B

    rawData = []

    # open the all ports and get the labjack handle
    handle = xyz.openPorts()

    info = ljm.getHandleInfo(handle)
    print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
        "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
        (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))

    # Stream Configuration
    aScanListNames = [
        "AIN%i" % i
        for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS)
    ]  #Scan list names
    print("\nScan List = " + " ".join(aScanListNames))
    numAddresses = len(aScanListNames)
    aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0]
    global scanRate
    scanRate = scanrate

    scansPerRead = int(scanRate / 2)

    try:
        # Configure the analog inputs' negative channel, range, settling time and
        # resolution.
        # Note when streaming, negative channels and ranges can be configured for
        # individual analog inputs, but the stream has only one settling time and
        # resolution.
        aNames = [
            "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [ljm.constants.GND, 10.0, 0,
                   0]  #single-ended, +/-10V, 0 (default),
        #0 (default)
        ljm.eWriteNames(handle, len(aNames), aNames, aValues)

        eventNumber = 0  # keeps track of the event we make a new one each time the user resets the pendulum and hits enter
        input('start?')
        while True:

            if bKick:
                # kick the pendulum to drive it so we can take period data.
                print('Kicking')
                xr, yr, zr = kickUpAndWait(
                    0, 4.5e-6, 0,
                    10)  # kick the field and save the current values.
                #xr,yr,zr = kickUpAndWait(0, 2e-6, 0, 10) # seems like we maight want a bit less kick

            # Configure and start stream
            scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses,
                                        aScanList, scanRate)
            print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

            print("\nPerforming %i stream reads." % MAX_REQUESTS)

            if bKick:
                kickDown(xr, yr,
                         zr)  # put the currents back to where they were
                print('Done Kicking!')

            # then do the stream.
            start = datetime.now()
            totScans = 0
            totSkip = 0  # Total skipped samples

            i = 1  # counter for number of stream requests

            while i <= MAX_REQUESTS:
                ret = ljm.eStreamRead(handle)

                data = ret[0]
                scans = len(data) / numAddresses
                totScans += scans

                # Count the skipped samples which are indicated by -9999 values. Missed
                # samples occur after a device's stream buffer overflows and are
                # reported after auto-recover mode ends.
                curSkip = data.count(-9999.0)
                totSkip += curSkip

                print("\neStreamRead %i" % i)
                ainStr = ""
                for j in range(0, numAddresses):
                    ainStr += "%s = %0.5f " % (aScanListNames[j], data[j])
                print("  1st scan out of %i: %s" % (scans, ainStr))
                print("  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = " \
                      "%i" % (curSkip/numAddresses, ret[1], ret[2]))

                newDataChunk = np.reshape(
                    data, (-1, NUMBER_OF_AINS)
                )  # reshape the data to have each row be a different reading

                if i != 1:  # if we are not on the first run.
                    rawData = np.vstack((rawData, newDataChunk))
                else:
                    rawData = newDataChunk  # this should only run on the first time.
                    #print('FIRST RUN THROUGH')

                #print(rawData,'\n')

                i += 1

            end = datetime.now()

            print("\nTotal scans = %i" % (totScans))
            tt = (end - start).seconds + float(
                (end - start).microseconds) / 1000000
            print("Time taken = %f seconds" % (tt))
            print("LJM Scan Rate = %f scans/second" % (scanRate))
            print("Timed Scan Rate = %f scans/second" % (totScans / tt))
            print("Timed Sample Rate = %f samples/second" %
                  (totScans * numAddresses / tt))
            print("Skipped scans = %0.0f" % (totSkip / numAddresses))

            print("\nStop Stream")
            ljm.eStreamStop(handle)

            print('current querry!')
            # update the powersupply field readings so we can reference them later
            xyz.xCoil.getLargeCoilField()
            xyz.yCoil.getLargeCoilField()
            print('done with current querry!')

            # format data to include field values
            rawDataWithFieldValues = []
            print(rawData)
            first = True
            for j, row in enumerate(
                    rawData
            ):  # setp throuh and append the field values to each datapoint
                if row[1] >= minSum:
                    timestamp = j * (1.0 / scanRate)
                    rowWithFieldValues = np.append(
                        row,
                        np.array([
                            xyz.xCoil.largeCoilField, xyz.yCoil.largeCoilField,
                            timestamp, eventNumber
                        ]))  # for now we aren't using the adustment coils
                    if first:
                        first = False
                        rawDataWithFieldValues = rowWithFieldValues

                    else:  # not on the first loop
                        rawDataWithFieldValues = np.vstack(
                            (rawDataWithFieldValues, rowWithFieldValues))
            print(np.shape(rawDataWithFieldValues))

            # and add it to our master data array
            if eventNumber != 0:
                #print(np.shape(allTheData))
                #print('--------')
                #print(np.shape(rawDataWithFieldValues))
                allTheData = np.vstack((allTheData, rawDataWithFieldValues))
                #print(np.shape(allTheData))
            else:
                allTheData = rawDataWithFieldValues

            print(allTheData)
            print(np.shape(allTheData))

            input(
                "finished with eventNumber %s. Press enter to start a new data run."
                % eventNumber)
            eventNumber += 1  # increment the event number

    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
        #xyz.closePorts(handle)

    except KeyboardInterrupt:  # usefull to have a KeyboardInterrupt when your're debugging

        # save the data to a DataFrame
        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)

    except Exception as e:
        # helpful to close the ports on except when debugging the code.
        # it prevents the devices from thinking they are still conected and refusing the new connecton
        # on the next open ports call.

        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)
        print('closed all the ports\n')

        print(e)  # print the exception
        raise
示例#19
0
def main():
    try:
        openTime = datetime.utcnow()
        daqHandle = ljm.openS("T7", "TCP", "ANY")

        daqInfo = ljm.getHandleInfo(daqHandle)
        print(
            "Opened a LabJack with Device type: %i, Connection type: %i,\n"
            "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i"
            % (daqInfo[0], daqInfo[1], daqInfo[2], ljm.numberToIP(
                daqInfo[3]), daqInfo[4], daqInfo[5]))

        csvWriter, csvFile = generateCSV()
        timeHeader = ["TIME"]
        timeHeader.extend(aScanListNames)
        csvWriter.writerow(timeHeader)
        if (daqInfo[0] == ljm.constants.dtT7):

            # Disable triggered streaming
            ljm.eWriteName(daqHandle, "STREAM_TRIGGER_INDEX", 0)

            # Enabling internally-clocked stream.
            ljm.eWriteName(daqHandle, "STREAM_CLOCK_SOURCE", 0)

            # All negative channels are single-ended, AIN0 and AIN1 ranges are
            # +/-10 V, stream settling is 0 (default) and stream resolution index
            # is 0 (default).
            aNames = [
                "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
                "STREAM_RESOLUTION_INDEX"
            ]
            aValues = [ljm.constants.GND, 10.0, 0, 0]

            ljm.eWriteNames(daqHandle, len(aNames), aNames, aValues)

            # Configure and start stream
            scanStartTime = datetime_to_float(datetime.utcnow())
            lastScanStartTime = scanStartTime
            scanRate = ljm.eStreamStart(daqHandle, scansPerRead, numAddresses,
                                        aScanList, scanRate)
            print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

            totScans = 0
            totSkip = 0  # Total skipped samples

            aScanClockNames = ["SYSTEM_TIMER_20HZ", "CORE_TIMER"]
            startClocks = ljm.eReadNames(daqHandle, len(aScanClockNames),
                                         aScanClockNames)
            start20HzClock = startClocks[0]
            start40MHzClock = startClocks[1]
            count40MHzRollover = 0

            # Stream Configuration
            aScanListNames = ["AIN0", "AIN1", "AIN2",
                              "AIN3"]  # Scan list names to stream
            aScanList = ljm.namesToAddresses(len(numAddresses),
                                             aScanListNames)[0]
            scanRate = 10
            scansPerRead = int(scanRate / 2)

            # while True:
            try:
                ret = ljm.eStreamRead(daqHandle)
                scanStopTime = datetime_to_float(datetime.utcnow())

                aData = ret[0]
                scans = len(aData) / numAddresses
                totScans += scans

                # Count the skipped samples which are indicated by -9999 values. Missed
                # samples occur after a device's stream buffer overflows and are
                # reported after auto-recover mode ends.
                curSkip = aData.count(-9999.0)
                totSkip += curSkip
                ainStr = ""
                for j in range(0, numAddresses):
                    ainStr += "%s = %0.5f, " % (aScanListNames[j], aData[j])
                print("  1st scan out of %i: %s" % (scans, ainStr))
                print(
                    "  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = "
                    "%i" % (curSkip / numAddresses, ret[1], ret[2]))
                timeData = np.linspace(scanStartTime,
                                       scanStopTime,
                                       num=scansPerRead)
                print timeData
                print aData
                scanData = np.array(aData)
                print scanData
                print("Rows/Cols: ", scanData.shape)
                print("Num address: ", numAddresses)
                splitScanData = np.split(scanData, scansPerRead)
                print splitScanData
                print("Rows/Cols: ", splitScanData[0].shape)
                csvWriter.writerows(splitScanData)
                verticalStackedSplitScanData = np.vstack(splitScanData)
                print verticalStackedSplitScanData
                print "Test"
                # csvWriter.writerows(verticalStackedSplitScanData)   #use write rows once separated with numpy array
            except Exception as e:
                raise e
                # break
            except KeyboardInterrupt:  # Extend to save button interrupt
                pass
                # break
            # Close T7 Connection
            try:
                print("\nStop Stream")
                ljm.eStreamStop(daqHandle)
            except ljm.LJMError:
                ljme = sys.exc_info()[1]
                print(ljme)
            except Exception:
                e = sys.exc_info()[1]
                print(e)

    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
    except Exception:
        e = sys.exc_info()[1]
        print(e)

    csvFile.close()
    ljm.close(daqHandle)
示例#20
0
#Paramters for acquisition
scanres = int(args.scantime * int(127))

data = []

#Opening labjack and generating handle object
handle = ljm.openS("T7","ETHERNET","470010370")

#Writing constants for Stream-Out
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE",0)
ljm.eWriteName(handle,"STREAM_OUT0_TARGET",1000)
ljm.eWriteName(handle,"STREAM_OUT0_BUFFER_SIZE",256)
ljm.eWriteName(handle,"STREAM_OUT0_ENABLE",1)

#Writing the waveform onto the labjack
ljm.eWriteName(handle,"STREAM_OUT0_LOOP_SIZE",127)
ljm.eWriteNameArray(handle,"STREAM_OUT0_BUFFER_F32",127,val[0:127])
ljm.eWriteName(handle,"STREAM_OUT0_SET_LOOP",1)

#Start streaming. 4800 is Stream-Out. 0 is Stream-In
ljm.eStreamStart(handle,scanres,2,[4800,2],fqreal*127)

for i in range(args.acqtime):
  read = ljm.eStreamRead(handle)
  data.append(read[0][0:scanres])
  if args.verbosity >0:
    print(ljm.eStreamRead(handle)[1:])

ljm.eStreamStop(handle)
ljm.close(handle)
示例#21
0
def main(initial_scanRate_hz=INITIAL_SCAN_RATE_HZ,
         in_names=IN_NAMES,
         stream_outs=STREAM_OUTS,
         num_cycles=NUM_WRITES):
    print("Beginning...")
    handle = openLJMDevice(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
    printDeviceInfo(handle)

    writeData = []
    for i in range(SAMPLES_TO_WRITE):
        sample = 2.5 * i / SAMPLES_TO_WRITE
        writeData.append(sample)
    scansPerRead = int(initial_scanRate_hz / 2)

    try:
        print("Initializing stream out buffers...")
        for stream_out in stream_outs:
            ljm.initializeAperiodicStreamOut(handle, stream_out["index"],
                                             stream_out["target"],
                                             initial_scanRate_hz)
            # Write some data to the buffer before the stream starts
            ljm.writeAperiodicStreamOut(handle, stream_out["index"],
                                        SAMPLES_TO_WRITE, writeData)
            ljm.writeAperiodicStreamOut(handle, stream_out["index"],
                                        SAMPLES_TO_WRITE, writeData)
        print("")
        scanList = makeScanList(in_names=in_names, stream_outs=stream_outs)
        print("scanList: " + str(scanList))
        print("scansPerRead: " + str(scansPerRead))
        scanRate = ljm.eStreamStart(handle, scansPerRead, len(scanList),
                                    scanList, initial_scanRate_hz)
        start_time = ljm.getHostTick()
        print("\nStream started with a scan rate of %0.0f Hz." % scanRate)
        print("\nPerforming %i buffer updates." % num_cycles)
        iteration = 0
        total_num_skipped_scans = 0
        while iteration < num_cycles:
            for stream_out in stream_outs:
                ljm.writeAperiodicStreamOut(handle, stream_out["index"],
                                            SAMPLES_TO_WRITE, writeData)
            # ljm.eStreamRead will sleep until data has arrived
            stream_read = ljm.eStreamRead(handle)
            num_skipped_scans = ljm_stream_util.processStreamResults(
                iteration, stream_read, in_names)
            total_num_skipped_scans += num_skipped_scans
            iteration = iteration + 1
        # Since scan rate determines how quickly data can be written from the device
        # large chunks of data written at low scan rates can take longer to write
        # out than it takes to call LJM_WriteAperiodicStreamOut and
        # LJM_eStreamRead. some delay may be necessary if it is desired to write out
        # all data then immediately close the stream
        runTime = (ljm.getHostTick() - start_time) / 1000
        # 512 samples * 10 writes = 5120 samples. scan rate = 1000
        # samples/sec, so it should take 5.12 seconds to write all data out
        stream_out_ms = 1000 * SAMPLES_TO_WRITE * (NUM_WRITES + 2) / scanRate
        if (runTime < stream_out_ms):
            sleep((stream_out_ms - runTime) / 1000)

    except ljm.LJMError:
        ljm_stream_util.prepareForExit(handle)
        raise
    except Exception:
        ljm_stream_util.prepareForExit(handle)
        raise

    ljm_stream_util.prepareForExit(handle)
    print("Total number of skipped scans: %d" % total_num_skipped_scans)
示例#22
0
    def start_acq(self, session, params=None):
        """
        Task to start data acquisition.

        Args:
            sampling_frequency (float):
                Sampling frequency for data collection. Defaults to 2.5 Hz

        """
        if params is None:
            params = {}

        # Setup streaming parameters. Data is collected and published in
        # blocks at 1 Hz or the scan rate, whichever is less.
        scan_rate_input = params.get('sampling_frequency',
                                     self.sampling_frequency)
        scans_per_read = max(1, int(scan_rate_input))
        num_chs = len(self.chs)
        ch_addrs = ljm.namesToAddresses(num_chs, self.chs)[0]

        with self.lock.acquire_timeout(0, job='acq') as acquired:
            if not acquired:
                self.log.warn("Could not start acq because "
                              "{} is already running".format(self.lock.job))
                return False, "Could not acquire lock."

            session.set_status('running')
            self.take_data = True

            # Start the data stream. Use the scan rate returned by the stream,
            # which should be the same as the input scan rate.
            try:
                scan_rate = ljm.eStreamStart(self.handle, scans_per_read,
                                             num_chs, ch_addrs,
                                             scan_rate_input)
            except LJMError as e:  # in case the stream is running
                self.log.error(e)
                self.log.error("Stopping previous stream and starting new one")
                ljm.eStreamStop(self.handle)
                scan_rate = ljm.eStreamStart(self.handle, scans_per_read,
                                             num_chs, ch_addrs,
                                             scan_rate_input)
            self.log.info(
                f"\nStream started with a scan rate of {scan_rate} Hz.")

            cur_time = time.time()
            while self.take_data:
                data = {'block_name': 'sens', 'data': {}}

                # Query the labjack
                raw_output = ljm.eStreamRead(self.handle)
                output = raw_output[0]

                # Data comes in form ['AIN0_1', 'AIN1_1', 'AIN0_2', ...]
                for i, ch in enumerate(self.chs):
                    ch_output = output[i::num_chs]
                    data['data'][ch + 'V'] = ch_output

                    # Apply unit conversion function for this channel
                    if ch in self.functions.keys():
                        new_ch_output, units = \
                            self.ljf.unit_conversion(np.array(ch_output),
                                                     self.functions[ch])
                        data['data'][ch + units] = list(new_ch_output)

                # The labjack outputs at exactly the scan rate but doesn't
                # generate timestamps. So create them here.
                timestamps = [
                    cur_time + i / scan_rate for i in range(scans_per_read)
                ]
                cur_time += scans_per_read / scan_rate
                data['timestamps'] = timestamps

                self.agent.publish_to_feed('sensors', data)

                # Publish to the downsampled data feed only the first
                # timestamp and data point for each channel.
                data_downsampled = {
                    'block_name': 'sens',
                    'data': {},
                    'timestamp': timestamps[0]
                }
                for key, value in data['data'].items():
                    data_downsampled['data'][key] = value[0]
                self.agent.publish_to_feed('sensors_downsampled',
                                           data_downsampled)
                session.data = data_downsampled

            # Flush buffer and stop the data stream
            self.agent.feeds['sensors'].flush_buffer()
            self.agent.feeds['sensors_downsampled'].flush_buffer()
            ljm.eStreamStop(self.handle)
            self.log.info("Data stream stopped")

        return True, 'Acquisition exited cleanly.'
示例#23
0
    # 0 (default)
    ljm.eWriteNames(handle, len(aNames), aNames, aValues)

    # Configure and start stream
    print(aScanList[0:TOTAL_NUM_CHANNELS])
    scanRate = ljm.eStreamStart(handle, scansPerRead, TOTAL_NUM_CHANNELS, aScanList, scanRate)
    print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

    print("\nPerforming %i stream reads." % MAX_REQUESTS)
    start = datetime.now()
    totScans = 0
    totSkip = 0  # Total skipped samples

    i = 1
    while i <= MAX_REQUESTS:
        ret = ljm.eStreamRead(handle)

        # Note that the Python eStreamData will return a data list of size
        # scansPerRead*TOTAL_NUM_CHANNELS, but only the first
        # scansPerRead*NUM_IN_CHANNELS samples in the list are valid. Output
        # channels are not included in the eStreamRead's returned data.
        data = ret[0][0 : scansPerRead * NUM_IN_CHANNELS]
        scans = len(data) / NUM_IN_CHANNELS
        totScans += scans

        # Count the skipped samples which are indicated by -9999 values. Missed
        # samples occur after a device's stream buffer overflows and are
        # reported after auto-recover mode ends.
        curSkip = data.count(-9999.0)
        totSkip += curSkip
def main(initialScanRateHz=initialScanRateHz,
         inNames=inNames,
         streamOuts=streamOuts,
         numCycles=numCycles):
    print("Beginning...")
    handle = openLJMDevice(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
    printDeviceInfo(handle)

    print("Initializing stream out buffers...")
    outContexts = []
    for streamOut in streamOuts:
        outContext = ljm_stream_util.createOutContext(streamOut)
        ljm_stream_util.initializeStreamOut(handle, outContext)
        outContexts.append(outContext)

    print("")

    for outContext in outContexts:
        printRegisterValue(handle, outContext["names"]["bufferStatus"])

    for outContext in outContexts:
        updateStr = "Updating %(streamOut)s buffer whenever " \
            "%(bufferStatus)s is greater or equal to " % outContext["names"]
        print(updateStr + str(outContext["stateSize"]))

    scansPerRead = int(min([context["stateSize"] for context in outContexts]))
    bufferStatusNames = [out["names"]["bufferStatus"] for out in outContexts]
    try:
        scanList = ljm_stream_util.createScanList(inNames=inNames,
                                                  outContexts=outContexts)
        print("scanList: " + str(scanList))
        print("scansPerRead: " + str(scansPerRead))

        scanRate = ljm.eStreamStart(handle, scansPerRead, len(scanList),
                                    scanList, initialScanRateHz)
        print("\nStream started with a scan rate of %0.0f Hz." % scanRate)
        print("\nPerforming %i buffer updates." % numCycles)

        iteration = 0
        totalNumSkippedScans = 0
        while iteration < numCycles:
            bufferStatuses = [0]
            infinityPreventer = 0
            while max(bufferStatuses) < outContext["stateSize"]:
                bufferStatuses = ljm.eReadNames(handle, len(bufferStatusNames),
                                                bufferStatusNames)
                infinityPreventer = infinityPreventer + 1
                if infinityPreventer > scanRate:
                    raise ValueError(
                        "Buffer statuses don't appear to be updating:" +
                        str(bufferStatusNames) + str(bufferStatuses))

            for outContext in outContexts:
                ljm_stream_util.updateStreamOutBuffer(handle, outContext)

            # ljm.eStreamRead will sleep until data has arrived
            streamRead = ljm.eStreamRead(handle)

            numSkippedScans = ljm_stream_util.processStreamResults(
                iteration,
                streamRead,
                inNames,
                deviceThreshold=outContext["stateSize"],
                LJMThreshold=outContext["stateSize"])
            totalNumSkippedScans += numSkippedScans

            iteration = iteration + 1
    except ljm.LJMError:
        ljm_stream_util.prepareForExit(handle)
        raise
    except Exception:
        ljm_stream_util.prepareForExit(handle)
        raise

    ljm_stream_util.prepareForExit(handle)

    print("Total number of skipped scans: %d" % totalNumSkippedScans)
示例#25
0
    # Configure and start stream
    scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate)
    print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

    print("\nPerforming %i stream reads." % MAX_REQUESTS)
    start = datetime.now()
    totScans = 0
    totSkip = 0  # Total skipped samples

    i = 1
    ljmScanBacklog = 0
    while i <= MAX_REQUESTS:
        ljm_stream_util.variable_stream_sleep(scansPerRead, scanRate, ljmScanBacklog)

        try:
            ret = ljm.eStreamRead(handle)

            aData = ret[0]
            ljmScanBacklog = ret[2]
            scans = len(aData) / numAddresses
            totScans += scans

            # Count the skipped samples which are indicated by -9999 values. Missed
            # samples occur after a device's stream buffer overflows and are
            # reported after auto-recover mode ends.
            curSkip = aData.count(-9999.0)
            totSkip += curSkip

            print("\neStreamRead %i" % i)
            ainStr = ""
            for j in range(0, numAddresses):
示例#26
0
def main(
    initial_scan_rate_hz=INITIAL_SCAN_RATE_HZ,
    in_names=IN_NAMES,
    stream_outs=STREAM_OUTS,
    num_cycles=NUM_CYCLES
):
    print("Beginning...")
    handle = open_ljm_device(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
    print_device_info(handle)

    print("Initializing stream out buffers...")
    out_contexts = []
    for stream_out in stream_outs:
        out_context = ljm_stream_util.create_out_context(stream_out)
        ljm_stream_util.initialize_stream_out(handle, out_context)
        out_contexts.append(out_context)

    print("")

    for out_context in out_contexts:
        print_register_value(handle, out_context["names"]["buffer_status"])

    for out_context in out_contexts:
        update_str = "Updating %(stream_out)s buffer whenever " \
            "%(buffer_status)s is greater or equal to " % out_context["names"]
        print(update_str + str(out_context["state_size"]))

    scans_per_read = int(min([context["state_size"] for context in out_contexts]))
    buffer_status_names = [out["names"]["buffer_status"] for out in out_contexts]
    try:
        scan_list = ljm_stream_util.create_scan_list(
            in_names=in_names,
            out_contexts=out_contexts
        )
        print("scan_list: " + str(scan_list))
        print("scans_per_read: " + str(scans_per_read))

        scan_rate = ljm.eStreamStart(handle, scans_per_read, len(scan_list),
            scan_list, initial_scan_rate_hz)
        print("\nStream started with a scan rate of %0.0f Hz." % scan_rate)
        print("\nPerforming %i buffer updates." % num_cycles)

        iteration = 0
        total_num_skipped_scans = 0
        while iteration < num_cycles:

            buffer_statuses = [0]
            infinity_preventer = 0
            while max(buffer_statuses) < out_context["state_size"]:
                buffer_statuses = ljm.eReadNames(
                    handle,
                    len(buffer_status_names),
                    buffer_status_names
                )
                infinity_preventer = infinity_preventer + 1
                if infinity_preventer > scan_rate:
                    raise ValueError(
                        "Buffer statuses don't appear to be updating:" + \
                        str(buffer_status_names) + str(buffer_statuses)
                    )

            for out_context in out_contexts:
                ljm_stream_util.update_stream_out_buffer(handle, out_context)

            # ljm.eStreamRead will sleep until data has arrived
            stream_read = ljm.eStreamRead(handle)

            num_skipped_scans = ljm_stream_util.process_stream_results(
                iteration,
                stream_read,
                in_names,
                device_threshold=out_context["state_size"],
                ljm_threshold=out_context["state_size"]
            )
            total_num_skipped_scans += num_skipped_scans

            iteration = iteration + 1

    except ljm.LJMError:
        ljm_stream_util.prepare_for_exit(handle)
        raise

    except Exception:
        ljm_stream_util.prepare_for_exit(handle)
        raise

    ljm_stream_util.prepare_for_exit(handle)

    print("Total number of skipped scans: %d" % total_num_skipped_scans)