Beispiel #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
Beispiel #2
0
    def connect(self):
        try:
            self.handle = ljm.openS(self.params['device'],
                                    self.params['connection'],
                                    self.params['devid'])
            info = ljm.getHandleInfo(self.handle)

            self.deviceType = info[0]
            assert self.deviceType in [ljm.constants.dtT7, ljm.constants.dtT4]
            if self.deviceType == ljm.constants.dtT7:
                self._command('AIN_ALL_RANGE', self.params['arange'])
            self._command('AIN_ALL_NEGATIVE_CH', ljm.constants.GND)
            log.info('Connected to LabJack (%i).' % (info[2]))
            self.clock = 80e6  # internal clock frequency

            try:
                ''' Stop streaming if currently running '''
                ljm.eStreamStop(self.handle)
            except:
                pass

            return 1

        except Exception as e:
            log.error('Failed to connect to LabJack (%s): %s.' %
                      (self.params['devid'], e))
Beispiel #3
0
	def close(self):
		"""Close the device."""
		try:
			ljm.eStreamStop(self.handle)
		except ljm.LJMError: #if no streamer open
			pass
		finally:
			ljm.close(self.handle)
			print ("LabJack device closed")
def signal_handler(signal, frame):
    global handle
    print("\nStop Stream")
    ljm.eStreamStop(handle)

    # Close handle
    ljm.close(handle)
    print('You pressed Ctrl+C!')
    sys.exit(0)
Beispiel #5
0
 def close_streamer(self):
   """
   Special method called if streamer is open.
   """
   if self.verbose:
     while not self.queue.empty():
       self.queue.get_nowait()
     self.queue.put("stop")
   ljm.eStreamStop(self.handle)
Beispiel #6
0
def prepare_for_exit(handle, stop_stream=True):
    if stop_stream:
        print("\nStopping Stream")
        try:
            ljm.eStreamStop(handle)
        except ljm.LJMError as exception:
            if exception.errorString != "STREAM_NOT_RUNNING":
                raise

    ljm.close(handle)
Beispiel #7
0
    def StreamStop(self):
        if self.__streaming:
            self.__streaming = False
            ljm.eStreamStop(self.handle)
            self.__stream_completion = self.__stream_callback(
                self.handle, None)
        else:
            self.__stream_completion = False

        return self.__stream_completion
Beispiel #8
0
def prepare_for_exit(handle, stop_stream=True):
    if stop_stream:
        print("\nStopping Stream")
        try:
            ljm.eStreamStop(handle)
        except ljm.LJMError as exception:
            if exception.errorString != "STREAM_NOT_RUNNING":
                raise

    ljm.close(handle)
Beispiel #9
0
 def prepare_stream(self):
     try:
         ''' Stop streaming if currently running '''
         ljm.eStreamStop(self.handle)
     except:
         pass
     self.aScanList = []
     aNames = [
         'STREAM_SETTLING_US', 'STREAM_RESOLUTION_INDEX',
         'STREAM_CLOCK_SOURCE'
     ]
     aValues = [0, 0, 0]
     self._write_array(aNames, aValues)
Beispiel #10
0
    def stream_out(self, channels, data, scanRate, loop=0):
        ''' Streams data at a given scan rate.

            Args:
                channels (list): Output channels to stream on, e.g. ['DAC0', 'DAC1']
                data (array): Data to stream out. For streaming on multiple channels, use column 0 for DAC0 and column 1 for DAC1.
                scanRate (float): desired output rate in scans/s
                loop (int): number of values from the end of the buffer to loop after finishing stream
        '''

        try:
            ''' Stop streaming if currently running '''
            ljm.eStreamStop(self.handle)
        except:
            pass
        n = np.ceil(np.log10(2 * (1 + len(data))) / np.log10(2))
        buffer_size = 2**n
        for i in range(len(channels)):
            aNames = [
                "STREAM_OUT%i_TARGET" % i,
                "STREAM_OUT%i_BUFFER_SIZE" % i,
                "STREAM_OUT%i_ENABLE" % i
            ]
            ch = channels[i]
            if ch == 'FIO_STATE':
                target = 2500
            else:
                target = 1000 + 2 * ch
            aValues = [target, buffer_size, 1]
            self._write_array(aNames, aValues)
            if ch == 'FIO_STATE':
                target = ['STREAM_OUT%i_BUFFER_U16' % i] * len(data)
            else:
                target = ['STREAM_OUT%i_BUFFER_F32' % i] * len(data)
            try:
                target_array = data[:, i]
            except IndexError:
                target_array = data
            ljm.eWriteNames(self.handle, len(target_array), target,
                            list(target_array))
            aNames = [
                "STREAM_OUT%i_LOOP_SIZE" % i,
                "STREAM_OUT%i_SET_LOOP" % i
            ]
            aValues = [loop * len(data), 1]
            self._write_array(aNames, aValues)
            self.aScanList.append(4800 + i)

        scanRate = ljm.eStreamStart(self.handle, 1, len(self.aScanList),
                                    self.aScanList, scanRate)
Beispiel #11
0
 def __exit__(self, *exc):
     try:
         eStreamStop(self.handle)
     except ljm.LJMError as exception:
         if exception.errorString != "STREAM_NOT_RUNNING":
             raise
     if (self.running_ramp) and (self.ramp_thread != None):
         self.ramp_thread.stop()
     if (self.hv1 != 0) or (self.hv2 != 0):
         self.SetHV1(0)
         self.SetHV2(0)
         time.sleep(5)
     self.SetPolarity("POS", "NEG")
     self.HV1Enable(False)
     self.HV2Enable(False)
     ljm.close(self.handle)
Beispiel #12
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 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
Beispiel #14
0
 def stop(self):
     ''' Stop streaming if currently running '''
     try:
         ljm.eStreamStop(self.labjack.handle)
     except:
         pass
Beispiel #15
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")
Beispiel #16
0
    def __init__(self, time_offset, IP_address, sampling, channels):
        self.hv1_enable = 0
        self.hv2_enable = 0
        self.hv1 = 0
        self.hv2 = 0
        self.polarity1 = "POS"
        self.polarity2 = "NEG"
        self.running_ramp = False
        self.ramp_thread = None
        self.handle = openS("T7", "ETHERNET", IP_address)
        self.HV1Enable()
        self.HV2Enable()
        self.SetLJTickVoltage("TDAC0", 0)
        self.SetLJTickVoltage("TDAC1", 0)
        try:
            eStreamStop(self.handle)
        except ljm.LJMError as exception:
            if exception.errorString != "STREAM_NOT_RUNNING":
                raise

        self.time_offset = time_offset

        try:
            self.verification_string = str(getHandleInfo(self.handle)[0])
        except:
            self.verification_string = "False"

        # Ensure triggered stream is disabled.
        eWriteName(self.handle, "STREAM_TRIGGER_INDEX", 0)

        # Enabling internally-clocked stream.
        eWriteName(self.handle, "STREAM_CLOCK_SOURCE", 0)

        # Configure the analog input negative channels, ranges, stream settling
        # times and stream resolution index.
        aNames = [
            "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [constants.GND, 10.0, 0,
                   0]  # single-ended, +/-10V, 0 (default), 0 (default)
        eWriteNames(self.handle, len(aNames), aNames, aValues)

        # start acquisition
        self.active_channels = []
        self.active_channel_names = []
        for ch in [0, 1, 2, 3, 4, 5]:
            if bool(int(channels[0][ch].get())):
                self.active_channel_names.append(channels[1][ch].get())
                self.active_channels.append("AIN{0}".format(ch))
        self.num_addresses = len(self.active_channels)
        self.scan_list = namesToAddresses(self.num_addresses,
                                          self.active_channels)[0]
        self.scans_rate = int(sampling["scans_rate"].get())
        self.scans_per_read = int(sampling["scans_per_read"].get())

        self.new_attributes = [
            ("column_names", ", ".join(self.active_channel_names)),
            ("units", ", ".join(["V"] * len(self.active_channels))),
            ("sampling", "{0} [S/s]".format(self.scans_rate))
        ]

        # shape and type of the array of returned data
        self.shape = (self.num_addresses, )
        self.dtype = 'f'

        self.scan_rate = eStreamStart(self.handle, self.scans_per_read,
                                      self.num_addresses, self.scan_list,
                                      self.scans_rate)
Beispiel #17
0
 def stop_stream(self):
     ljm.eStreamStop(self.handle)
 def stop_stream(self):
   ljm.eStreamStop(self.handle)
Beispiel #19
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
Beispiel #20
0
            for k in range(0, NUM_IN_CHANNELS):
                ainStr += "%s: %0.5f, " % (POS_IN_NAMES[k], data[j * NUM_IN_CHANNELS + k])
            print("  %s" % (ainStr))
        print(
            "  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = "
            "%i" % (curSkip / NUM_IN_CHANNELS, ret[1], ret[2])
        )
        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 * NUM_IN_CHANNELS / tt))
    print("Skipped scans = %0.0f" % (totSkip / NUM_IN_CHANNELS))
except ljm.LJMError:
    ljme = sys.exc_info()[1]
    print(ljme)
except Exception:
    e = sys.exc_info()[1]
    print(e)

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

# Close handle
ljm.close(handle)
Beispiel #21
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.'
Beispiel #22
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
        }
Beispiel #23
0
                raise err

    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))
except ljm.LJMError:
    ljme = sys.exc_info()[1]
    print(ljme)
except Exception:
    e = sys.exc_info()[1]
    print(e)

try:
    print("\nStop Stream")
    ljm.eStreamStop(handle)
except ljm.LJMError:
    ljme = sys.exc_info()[1]
    print(ljme)
except Exception:
    e = sys.exc_info()[1]
    print(e)

# Close handle
ljm.close(handle)
Beispiel #24
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)