def setup_devices(): config = None ljm_devices = {} config_url = SERVER_BASE_URL + CONFIG_PATH + '?rpi_mac=' + get_device_mac() result = requests.get(config_url) if result.status_code == 200: config = result.json()[0] devices = config.get('devices', []) for device in devices: channels = [chnl for chnl in range(device.get('num_channels', 0))] channel_addrs = [] for channel in channels: ain_start = device.get('starting_address', 0) channel_addrs.append(int(ain_start + DATA_BYTE_SIZE * channel)) device_id = device.get('device_id', '') sample_rate = device.get('sample_rate', 0) read_rate = device.get('read_rate', 0) try: ljd = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, device_id) ljm.eStreamStart(ljd, read_rate, len(channel_addrs), channel_addrs, sample_rate) ljm_devices[device_id] = ljd except: pass return (ljm_devices, config)
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 start_stream(self): """ Method to initialize a streaming data. """ try: ljm.eStreamStart(self.handle, self.scans_per_read, self.nb_channels, self.a_scan_list, self.scan_rate_per_channel) except ljm.LJMError as e: print('Error in start_stream:', e) self.close_streamer() raise if self.verbose: thread = Thread(target=self.DialogBox, args=( self.scan_rate_per_channel, self.scans_per_read, self.queue)) thread.start() self.stream_started = True
def stream_out(self, 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 ''' self.stop() n = np.ceil(np.log10(2 * (1 + len(data))) / np.log10(2)) buffer_size = 2**n self._write_dict({ "STREAM_OUT0_TARGET": 2500, "STREAM_OUT0_BUFFER_SIZE": buffer_size, "STREAM_OUT0_ENABLE": 1, "STREAM_OUT0_LOOP_SIZE": loop * len(data), "STREAM_OUT0_SET_LOOP": 1 }) data_register = ['STREAM_OUT0_BUFFER_U16'] * len(data) self._write_array(data_register, list(data)) # self._write_dict({"STREAM_OUT0_LOOP_SIZE": loop*len(data), # "STREAM_OUT0_SET_LOOP": 1 # }) scanRate = ljm.eStreamStart(self.handle, 1, 1, [4800], scanRate)
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 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 ''' self.stop() n = np.ceil(np.log10(2 * (1 + len(data))) / np.log10(2)) buffer_size = 2**n for i in range(len(channels)): self._write_dict({ f'STREAM_OUT{i}_TARGET': 1000 + 2 * channels[i], f'STREAM_OUT{i}_BUFFER_SIZE': buffer_size, f'STREAM_OUT{i}_ENABLE': 1 }) target = ['STREAM_OUT%i_BUFFER_F32' % i] * len(data) self._write_array(target, list(data)) self._write_dict({ f'STREAM_OUT{i}_LOOP_SIZE': loop * len(data), f'STREAM_OUT{i}_SET_LOOP': 1 }) self.aScanList.append(4800 + i) # add stream-out register to scan list scanRate = ljm.eStreamStart(self.handle, 1, len(self.aScanList), self.aScanList, scanRate)
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 _start(self, channels, data, scanRate, loop=0, dtype='F32'): self.stop() n = np.ceil(np.log10(2 * (1 + len(data))) / np.log10(2)) buffer_size = 2**n i = 0 scan_list = [] for ch in channels: self.labjack._write_dict({ f'STREAM_OUT{i}_TARGET': ch, f'STREAM_OUT{i}_BUFFER_SIZE': buffer_size, f'STREAM_OUT{i}_ENABLE': 1 }) target = ['STREAM_OUT%i_BUFFER_%s' % (i, dtype)] * len(data) self.labjack._write_array(target, list(data)) self.labjack._write_dict({ f'STREAM_OUT{i}_LOOP_SIZE': loop * len(data), f'STREAM_OUT{i}_SET_LOOP': 1 }) scan_list.append(4800 + i) i += 1 scanRate = ljm.eStreamStart(self.labjack.handle, 1, len(scan_list), scan_list, scanRate)
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)
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
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)
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 start_stream(self): ljm.eStreamStart(self.handle, self.scan_per_read, len(self.chan_list), [c['to_read'] for c in self.chan_list], self.scan_rate) self.stream_t0 = time()
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", 1000) ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 2048) ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1) size = 1 val = np.arange(2.5, 5, 2.5 / (size * 128)) #Writing the waveform onto the labjack ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", size * 127) for x in range(4): ljm.eWriteNameArray(handle, "STREAM_OUT0_BUFFER_F32", 127, val[x * 128:(x + 1) * 127]) ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1) ljm.eStreamStart(handle, size * 127, 2, [4800, 0], 150) for x in range(2): read = ljm.eStreamRead(handle) data = np.append(data, read[0][0:size * 127]) print x ljm.eStreamStop(handle) print("Stream finished") theospace = np.linspace(size * 127, 2 * size * 127, size * 127) slope = ((2.5 * theospace) / (size * 127)) space = np.linspace(2.5, 5, size * 127) print('Voltage max: {0}'.format(data.max())) data = np.convolve(data, signal.gaussian(size * 127, 10), 'same')[(size * 127) - 1:(2 * size * 127) - 1]
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) # 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 while i <= MAX_REQUESTS: ret = ljm.eStreamRead(handle) data = ret[0] scans = len(data)/numAddresses totScans += scans
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)
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 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)
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)
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
def start_stream(self): ljm.eStreamStart(self.handle,self.scan_per_read,len(self.chan_list), [c['to_read'] for c in self.chan_list],self.scan_rate) self.stream_t0 = time()
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) 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.
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)):
handle = ljm.openS("T7","ETHERNET","470010370") except ljm.LJMError: print('Could not open labjack \n Program is terminated') sys.exit() try: if args.nocalib == False: val = initialise_sinus(args.wvfrmres,args.amp, args.offset) else: val = initialise_sinus(args.wvfrmres,args.amp,offset_calibration(handle)) initialise_streamout(handle,val) #Start streaming. 4800 is Stream-Out. 0 is Stream-In if args.verbosity > 0: print("Streaming initiated") ljm.eStreamStart(handle,scanres,2,[4800,0],scanrate) data = mainloop_reading(handle,scanres,args.readnum,args.readsize,args.wvfrmres,args.fq,args.verbosity,args.compar) #Error catching except ljm.LJMError: print("LJM Error break") except Exception: print("System error break") print(traceback.format_exc()) sys.exit() except KeyboardInterrupt: if args.verbosity > 0 : print("\n User called break") try: ljm.eStreamStop(handle) if args.verbosity > 0: print("Streaming finished")
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")
# 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", "AIN0_RANGE", "AIN1_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX" ] aValues = [ljm.constants.GND, 10.0, 10.0, 0, 0] # Write the analog inputs' negative channels (when applicable), ranges, # stream settling time and stream resolution configuration. numFrames = len(aNames) ljm.eWriteNames(handle, numFrames, 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.
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)
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 }
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 __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)
# +/-10 V, stream settling is 0 (default) and stream resolution index # is 0 (default). aNames = ["AIN_ALL_NEGATIVE_CH", "AIN0_RANGE", "AIN1_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] aValues = [ljm.constants.GND, 10.0, 10.0, 0, 0] # Write the analog inputs' negative channels, ranges, stream settling time # and stream resolution configuration. numFrames = len(aNames) ljm.eWriteNames(handle, numFrames, aNames, aValues) configure_device_for_triggered_stream(handle, TRIGGER_NAME) configure_ljm_for_triggered_stream() # 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)
#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)