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
def StreamStart(self, channels=None, scans_per_read=24, scan_rate=1.0, callback=None): if self.__streaming: raise LabJackException("Streaming in progress", LJD_STREAMING_IN_PROGRESS) if callback is None: raise LabJackException("Streaming requires callback", LJD_STREAMING_REQUIRES_CALLBACK) if channels is None: raise LabJackException("Streaming requires one or more channels", LJD_STREAMING_REQUIRES_CHANNELS) addresses = ljm.namesToAddresses(len(channels), channels)[0] self.__streaming = True self.__stream_callback = callback rc = ljm.eStreamStart(self.handle, scans_per_read, len(addresses), addresses, scan_rate) ljm.setStreamCallback(self.handle, self.__stream_thread_callback) return rc
def new(self): """Initialise the device and create the handle""" self.handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") if self.mode=="streamer": #self.channels = ["AIN0", "AIN1", "AIN2", "AIN3"] #Scan list names to stream numAddresses = len(self.channels) aScanList = ljm.namesToAddresses(numAddresses, self.channels)[0] aName_prefix=["AIN_ALL_NEGATIVE_CH","STREAM_SETTLING_US","STREAM_RESOLUTION_INDEX"] suffixes = ["_RANGE"] aNames = aName_prefix+[chan+s for chan in self.channels for s in suffixes] temp_values=[[self.chan_range[chan]] for chan,a in enumerate(self.channels)] aValues = [ljm.constants.GND, 0, self.resolution]+[item for sublist in temp_values for item in sublist] #print aValues #print "----------------------" #print aNames ljm.eWriteNames(self.handle, len(aNames), aNames, aValues) # Configure and start stream scanRate = ljm.eStreamStart(self.handle, self.scansPerRead, numAddresses, aScanList, self.scanRate) elif self.mode=="single": numAddresses = len(self.channels) #suffixes = ["_EF_INDEX","_NEGATIVE_CH", "_RANGE", "_RESOLUTION_INDEX", "_EF_CONFIG_D", "_EF_CONFIG_E"] # conf for automatic gain/offset suffixes = ["_NEGATIVE_CH", "_RANGE", "_RESOLUTION_INDEX"] aNames = [chan+s for chan in self.channels for s in suffixes] #aValues = [[1,ljm.constants.GND, self.chan_range[chan],0,self.gain[chan],self.offset[chan]] for chan,a in enumerate(self.channels)] aValues = [[ljm.constants.GND, self.chan_range[chan],self.resolution] for chan,_ in enumerate(self.channels)] aValues=[item for sublist in aValues for item in sublist] #flatten #print aValues #print "----------------------" #print aNames ljm.eWriteNames(self.handle, len(aNames), aNames, aValues) else: raise Exception("Invalid mode, please select 'single' or 'streamer'")
def AIn_start(self, channels, scan_rate): self.stop() scan_list = ljm.namesToAddresses(len(channels), channels)[0] scans_per_read = int(scan_rate / 2) ljm.eStreamStart(self.labjack.handle, scans_per_read, len(channels), scan_list, scan_rate)
def __init__(self, handles, data, rate, io_name, request_num, scan_rate): super(Thread, self).__init__() self.syncStream = stream.Stream(handles, rate) self.handles = handles self.data = data self.io_name = io_name self.request_num = request_num self.scan_rate = scan_rate self.io_addr = ljm.namesToAddresses(len(io_name), io_name)[0]
def open_streamer(self): self.a_scan_list = \ ljm.namesToAddresses(self.nb_channels, self.channels)[0] if self.verbose: self.queue = Queue() a_names = ["AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] a_values = [int(self.chan_range[0]), 0, int(self.resolution[0])] ljm.eWriteNames(self.handle, len(a_names), a_names, a_values) self.stream_started = False
def prepare_streamburst(self, channel, max_samples=2**13 - 1, trigger=None): ''' Sets up the LabJack for burst input streaming on a target channel. ''' self.prepare_stream() self.prepare_stream_trigger(trigger) self.aScanList.extend(ljm.namesToAddresses( 1, ['AIN%i' % channel])[0]) # Scan list addresses for streamBurst ''' Prepare buffer ''' n = np.ceil(np.log10(2 * (1 + max_samples)) / np.log10(2)) buffer_size = 2**n self._command('STREAM_BUFFER_SIZE_BYTES', buffer_size) self.stream_mode = 'in-triggered'
def convert_names_to_addresses(names, length_limit=None): """Convert a list of names to a list of addresses using LJM. @para names: Names to be converted to addresses. @type names: iterable over str @para length_limit: Limit the number of names to read from the name array also limit the size of the returned addresses. @type length_limit: int @return: The given names converted to addresses. @rtype: iterable over str """ length = len(names) if length_limit: length = length_limit addresses_and_types = ljm.namesToAddresses(length, names) # ljm.namesToAddresses returns a tuple of a list of addresses and a list of # types. The list of addresses is indexed at 0 of that tuple. return addresses_and_types[0]
def main(): scanRate = 1000 scansPerRead = int(scanRate / 2) # Number of seconds to stream out waveforms runTime = 5 # The desired stream channels # Up to 4 out-streams can be ran at once scanListNames = ["STREAM_OUT0"] scanList = ljm.namesToAddresses(len(scanListNames), scanListNames)[0] # Only stream out to DAC0 targetAddr = 1000 # Stream out index can only be a number between 0-3 streamOutIndex = 0 samplesToWrite = 512 # Make an arbitrary waveform that increases voltage linearly from 0-2.5V writeData = [] for i in range(samplesToWrite): sample = 2.5*i/samplesToWrite writeData.append(sample) print("Beginning...\n") handle = openLJMDevice(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") printDeviceInfo(handle) try : print("\nInitializing stream out... \n") ljm.periodicStreamOut(handle, streamOutIndex, targetAddr, scanRate, len(writeData), writeData) actualScanRate = ljm.eStreamStart(handle, scansPerRead, len(scanList), scanList, scanRate) print("Stream started with scan rate of %f Hz\n Running for %d seconds\n" % (scanRate, runTime)) sleep(runTime) except ljm.LJMError: ljm_stream_util.prepareForExit(handle) raise except Exception: ljm_stream_util.prepareForExit(handle) raise ljm_stream_util.prepareForExit(handle)
def prepare_stream_out(self, trigger=None, channels=[]): ''' Prepares an output stream. Args: trigger (int): if not None, set an FIO channel to trigger on Note: The maximum buffer size of the LabJack T7 is 2^15=32768 bytes, so up to 2^14=16384 samples can be held. At the default stream rate of 100 kS/s, this corresponds to 163.84 ms of data. If we want to stream for longer than that, we need to repeatedly write half a buffer's worth of data each time the buffer is half full. ''' for channel in channels: self.aScanList.extend(ljm.namesToAddresses(1, [channel])[0]) self.prepare_stream() self.prepare_stream_trigger(trigger) if trigger is not None: self.stream_mode = 'out-triggered' else: self.stream_mode = 'out'
NUMBER_OF_AINS = 16 # Open first found LabJack handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") #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])) # 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] scanRate = 1000 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)
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.'
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 }
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 4.0) # 4.0 V ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 5.0) # 5.0 V ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1) print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS"))) # Stream Configuration POS_IN_NAMES = ["AIN0", "AIN1"] NUM_IN_CHANNELS = len(POS_IN_NAMES) TOTAL_NUM_CHANNELS = NUM_IN_CHANNELS + NUM_OUT_CHANNELS # Add positive channels to scan list aScanList = ljm.namesToAddresses(NUM_IN_CHANNELS, POS_IN_NAMES)[0] scanRate = 2000 scansPerRead = 60 # 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: # When streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution.
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)
ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_F32", 4.0) # 4.0 V ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_F32", 5.0) # 5.0 V ljm.eWriteName(handle, "STREAM_OUT1_SET_LOOP", 1) print("STREAM_OUT1_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT1_BUFFER_STATUS"))) # Stream Configuration POS_IN_NAMES = ["AIN0"] NUM_IN_CHANNELS = len(POS_IN_NAMES) TOTAL_NUM_CHANNELS = NUM_IN_CHANNELS + NUM_OUT_CHANNELS # Add positive channels to scan list aScanList = ljm.namesToAddresses(NUM_IN_CHANNELS, POS_IN_NAMES)[0] scanRate = 20 scansPerRead = 60 # Add the stream out token 4800 to the end aScanList.extend([4800]) 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)
#handle = ljm.openS("T7", "ANY", "ANY") # T7 device, Any connection, Any identifier #handle = ljm.openS("T4", "ANY", "ANY") # T4 device, Any connection, Any identifier #handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") # Any device, Any connection, Any identifier 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])) deviceType = info[0] # Stream Configuration si.aScanListNames = ["AIN0", "FIO_STATE", "SYSTEM_TIMER_20HZ", "STREAM_DATA_CAPTURE_16"] # Scan list names to stream si.numAddresses = len(si.aScanListNames) si.aScanList = ljm.namesToAddresses(si.numAddresses, si.aScanListNames)[0] si.scanRate = 2000 si.scansPerRead = int(si.scanRate / 2) si.streamLengthMS = 10000 si.done = False si.aDataSize - si.numAddresses * si.scansPerRead si.handle = handle try: # When streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time # and resolution. if deviceType == ljm.constants.dtT4: # LabJack T4 configuration
"ANY") # Any device, Any connection, Any identifier #handle = ljm.openS("T7", "ANY", "ANY") # T7 device, Any connection, Any identifier #handle = ljm.openS("T4", "ANY", "ANY") # T4 device, Any connection, Any identifier #handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") # Any device, Any connection, Any identifier 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])) deviceType = info[0] # Stream Configuration aScanListNames = ["AIN0", "AIN1"] # Scan list names to stream numAddresses = len(aScanListNames) aScanList = ljm.namesToAddresses( numAddresses, aScanListNames)[0] # Scan list addresses for streamBurst scanRate = 10000 # Scans per second numScans = 20000 # Number of scans to perform try: # When streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. if deviceType == ljm.constants.dtT4: # LabJack T4 configuration # AIN0 and AIN1 ranges are +/-10 V, stream settling is 0 (default) and # stream resolution index is 0 (default). aNames = [ "AIN0_RANGE", "AIN1_RANGE", "STREAM_SETTLING_US",
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")
aNames.append("DIO_STATE") aWrites.append(ljm.constants.WRITE) aNumValues.append(1) aValues.append(0) # output-low if writeDACs is True: # Add analog output writes (DAC0-1) for i in range(2): numFrames += 1 aNames.append("DAC%i" % i) aWrites.append(ljm.constants.WRITE) aNumValues.append(1) aValues.append(0.0) # 0.0 V # Make lists of addresses and data types for eAddresses. aAddresses, aTypes = ljm.namesToAddresses(numFrames, aNames) print("\nTest frames:") for i in range(numFrames): if aWrites[i] == ljm.constants.READ: wrStr = "READ" else: wrStr = "WRITE" print(" %s %s (%s)" % (wrStr, aNames[i], aAddresses[i])) print("\nBeginning %i iterations..." % numIterations) # Initialize time variables maxMS = 0 minMS = 0 totalMS = 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)
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
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])) deviceType = info[0] if deviceType == ljm.constants.dtT4: print("\nThe LabJack T4 does not support triggered stream.") sys.exit() # Stream Configuration aScanListNames = ["AIN0", "AIN1"] # Scan list names to stream numAddresses = len(aScanListNames) aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0] scanRate = 1000 scansPerRead = int(scanRate / 2) TRIGGER_NAME = "DIO0" def configure_device_for_triggered_stream(handle, triggerName): """Configure the device to wait for a trigger before beginning stream. @para handle: The device handle @type handle: int @para triggerName: The name of the channel that will trigger stream to start @type triggerName: str """ address = ljm.nameToAddress(triggerName)[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)):