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 __init__(self, device_type, connection_type, serial_number, mp_q): self.valid = False self.mp_q = mp_q self.monitor_points = { 'drive_state': 0, # 0 = off, 1 = up, 2 = down 'brake': 0, # 0 = off, 1 = on 'plus_limit': 0, 'minus_limit': 0, 'ant_el': 0.0, 'foc_temp': -273.15, 'rf_a_power': -100.0, 'rf_b_power': -100.0, 'laser_a_current': 0.0, 'laser_b_current': 0.0, 'laser_a_opt_power': 0.0, 'laser_b_opt_power': 0.0, 'psu_a_volt': 0.0, 'psu_b_volt': 0.0, 'box_temp': -273.15 } # Open a LabJack try: self.lj_handle = ljm.open(device_type, connection_type, serial_number) except ljm.LJMError: self.valid = False return # To be replaced with a raise exception? self.valid = True print("Hello from analog backend")
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 __init__(self, log_msg_q, mp_q, simulate=False): log_msg_q.put((log.INFO, MODULE, "Searching for LabJack T7's")) # Set up arrays to hold device information for discovered LabJack devices self.num_found = 0 self.num_ant = 0 self.num_abe = 0 self.ants = {} self.abes = {} self.stop_time = 0.0 self.move_time = 0.0 if simulate: a_device_types = [] a_connection_types = [] a_serial_numbers = [] a_ip_addresses = [] self.num_found = NUM_SIM for i in range(NUM_SIM): a_device_types.append(ljm.constants.dtT7) a_connection_types.append(ljm.constants.ctETHERNET) a_serial_numbers.append("-2") a_ip_addresses.append("192.168.1.{}".format(i)) else: try: (self.num_found, a_device_types, a_connection_types, a_serial_numbers, a_ip_addresses) =\ ljm.listAll(ljm.constants.dtT7, ljm.constants.ctTCP) except ljm.LJMError as e: log_msg_q.put( (log.FATAL, MODULE, "Error searching for LabJack devices. LJMError: {}". format(e))) raise ljm.LJMError if self.num_found > 0: sim_ant_num = 1 for i in range(self.num_found): lj_handle = None try: lj_handle = ljm.open(a_device_types[i], a_connection_types[i], a_serial_numbers[i]) except ljm.LJMError: self.num_found -= self.num_found if self.num_found <= 0: return if simulate: (lj_type, lj_location) = (ANT_TYPE, sim_ant_num) sim_ant_num += 1 else: (lj_type, lj_location) = self._get_type_and_location(lj_handle) if lj_type == ANT_TYPE: self.ants[lj_location] = DsaAntLabjack( lj_handle, lj_location, log_msg_q, mp_q) self.num_ant += 1 elif lj_type == ABE_TYPE: self.abes[lj_location] = DsaAbeLabjack( lj_handle, lj_location, log_msg_q, mp_q) self.num_abe += 1
def __init__(self): # Open first found LabJack self.handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") #self.handle = ljm.openS("ANY", "ANY", "ANY") self.info = ljm.getHandleInfo(self.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" % \ (self.info[0], self.info[1], self.info[2], ljm.numberToIP(self.info[3]), self.info[4], self.info[5])) self.configure()
def openLJMDevice(deviceType, connectionType, identifier): try: handle = ljm.open(deviceType, connectionType, identifier) except ljm.LJMError: print("Error calling ljm.open(" + "deviceType=" + str(deviceType) + ", " + "connectionType=" + str(connectionType) + ", " + "identifier=" + identifier + ")") raise return handle
def open_ljm_device(device_type, connection_type, identifier): try: handle = ljm.open(device_type, connection_type, identifier) except ljm.LJMError: print( "Error calling ljm.open(" + \ "device_type=" + str(device_type) + ", " + \ "connection_type=" + str(connection_type) + ", " + \ "identifier=" + identifier + ")" ) raise return handle
def openPorts(): """Open all the ports including the labjack and the powersupplies""" # open the powersupply serial ports xCoil.supply.openPort() yCoil.supply.openPort() #zCoil.supply.openPort() print('opened all three powersupplies') # open the labjack serial port handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") # print the labjack info 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])) return (handle) # return the handle so e can close it later
def Init(): # Open first found LabJack handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") #handle = ljm.openS("ANY", "ANY", "ANY") #A2D setup 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])) # Setup and call eWriteNames to configure AINs on the LabJack. numFrames = 3 names = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "AIN_ALL_RESOLUTION_INDEX"] aValues = [199, 10, 1] ljm.eWriteNames(handle, numFrames, names, aValues) #return handle, Info return handle
def ld_connect(dt, ct): """ function used to detect LabJack device(s) using specific protocol(s) dt: device type DEVICE and ANY allowed ct: connection type CT values and ANY allowed return: list of connection to devices and list of connection information in case of loosing connection for trying to restore the connection to de device >>> dev = ld_connect(ANY, ANY) #it will connect to any labjack devices using any protocols >>> dev = ld_connect(DEVICE_T7, CT[3]) #it will connect to labjack t7 devices using tcp protocols >>> dev = ld_connect(DEVICE_T7, ANY) #it will connect to labjack t7 devices using any protocols >>> dev = ld_connect(DEVICE_T7, CT[2]) #it will connect to labjack t7 devices using only wifi >>> dev = ld_connect(DEVICE_T7, CT[1]) #it will connect to labjack t7 devices using only ethernet >>> dev = ld_connect(DEVICE_T7, CT[0]) #it will connect to labjack t7 devices using only usb """ connection_info = [] handle = [] labjack_devices = ljm.listAllS(dt, ct) for index in range(labjack_devices[CD_INDEX]): try: handle.append( ljm.open( labjack_devices[DT_INDEX][index], labjack_devices[CT_INDEX][index], labjack_devices[SN_INDEX][index] ) ) connection_info.append( [ labjack_devices[DT_INDEX][index], labjack_devices[CT_INDEX][index], labjack_devices[SN_INDEX][index] ] ) except ljm.ljm.LJMError as LjmError: print( LjmError._errorString + ": Unable to connect to device " + str( [ labjack_devices[DT_INDEX][index], labjack_devices[CT_INDEX][index], labjack_devices[SN_INDEX][index] ] ) ) return handle, connection_info
def labjackInitialize(): ''' All the code to initialize the connection to the labjack. Searches for the first Labjack that is connected, initializes the connection, and returns a handle for communication ''' # Open first found LabJack # Eventually we will have multiple labjacks open, so fix this handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") info = ljm.getHandleInfo(handle) print("\nOpened 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])) return handle
def run(self): """ main algorithm threads used to reconnect to devices after losing it connection """ for i in range(self.reconnection_attempt): time.sleep(self.second) try: handle = ljm.open(self.connection_info[0], self.connection_info[1], self.connection_info[2]) if handle > 0: Globals.handles.append(handle) Globals.information.append(self.connection_info) print("\nDevice " + str(self.connection_info) + " successfully reconnected.\n") return 0 except ljm.ljm.LJMError as LjmError: self.error = LjmError._errorString print("\nUnable to reconnect to device " + str(self.connection_info) + " Error: " + LjmError._errorString + ". Removed permanently\n") return -1
""" Demonstrates how to use the labjack.ljm.eReadName (LJM_eReadName) function. """ from labjack import ljm # 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])) # Setup and call eReadName to read a value from the LabJack. name = "SERIAL_NUMBER" result = ljm.eReadName(handle, name) print("\neReadName result: ") print(" Name - %s, value : %f" % (name, result)) # Close handle ljm.close(handle)
from labjack import ljm from datetime import datetime import timeit import functools def eNamesIteration(handle, numFrames, names, aWrites, aNumValues, aValues, results): # Function for timit.Timer. Performs a eNames call to do LabJack operations. # Takes eNames parameters and a list for results which will be filled. del results[:] r = ljm.eNames(handle, numFrames, names, aWrites, aNumValues, aValues) results.extend(r) # 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])) numIterations = 1000 # Number of iterations to perform in the loop # Analog input settings numAIN = 1 # Number of analog inputs to read rangeAIN = 10.0 resolutionAIN = 1
from labjack import ljm import time import sys import numpy as np from datetime import datetime #from oct2py import octave #import matplotlib.pyplot as plt from scipy.signal import find_peaks_cwt import scipy.fftpack as ft import peakutils file = open("times.txt", "w") t0 = time.time() #from peakdetect import peakdetect handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctETHERNET, "192.168.254.100") t1 = time.time() TopenEthernet = t0 - t1 OFFSET = 0.131 MULTIPLICITY = 1400 ANS = [0, 0, 0, 0] DIGITAL = ["FIO1", "FIO4", "FIO2", "FIO0"] def seleccionador(x): ljm.eWriteName(handle, DIGITAL[x], 1) def silenciador(x, peak):
def open_handle(self): self.handle=ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
def __init__(self, etcd_endpoint: list, sim=False): """Discover Model T7 LabJack devices on network and return their information Searches on the network for any LabJack T7 devices, and queries them for their DHCP-assigned IP address. The devices are queried for their hardware identifier (DIP switch on to the LabJack interface board) to determine if they are for an antenna (ant) or analog back-end box (BEB), as well as the associated number. For the antennas, this is the antenna number. Each BEB device is associated with multiple antennas. Args: etcd_endpoint (:obj:'list' of 'str'): A list with the etcd IP address and port number sim (bool): Indicates if simulated (True) or real (False) data Raises: ljm.LJMError: An error occurred accessing the LabJack drivers. """ # Get the name of this for logging purposes. my_class = str(self.__class__) self.class_name = (my_class[my_class.find('.') + 1:my_class.find("'>'") - 1]) # Set up logging. self.logger = logging.getLogger(Conf.LOGGER + '.' + __name__) # Set class name for logging. CustomFormatter.log_msg_fmt['class'] = self.class_name self.logger.info("Searching for LabJack T7's") # Set up arrays to hold device information for discovered LabJack devices. self.num_ant = 0 self.num_beb = 0 self.ants = {} self.bebs = {} if sim: a_connection_types, a_device_types, a_serial_numbers = self._creat_sim_devices( ) else: a_device_types, a_connection_types, a_serial_numbers = self._find_devices( ) if self.num_found > 0: sim_ant_num = 1 sim_beb_num = 1 for i in range(self.num_found): lj_handle = None try: lj_handle = ljm.open(a_device_types[i], a_connection_types[i], a_serial_numbers[i]) except ljm.LJMError: self.num_found -= self.num_found if self.num_found <= 0: return if sim: if i % 2 == 0: (lj_type, lj_location) = (Constants.ANT_TYPE, sim_ant_num) sim_ant_num += 1 else: (lj_type, lj_location) = (Constants.BEB_TYPE, sim_beb_num) sim_beb_num += 10 else: (lj_type, lj_location) = self._get_type_and_location(lj_handle) if lj_type == Constants.ANT_TYPE: self.ants[lj_location] = DsaAntLabJack( lj_handle, lj_location, etcd_endpoint, sim) self.num_ant += 1 print("Antenna {} found".format(lj_location)) elif lj_type == Constants.BEB_TYPE: self.bebs[lj_location] = DsaBebLabJack( lj_handle, lj_location, etcd_endpoint) self.num_beb += 1 print("Analog backend {} found".format(lj_location))
def open_handle(identifier='ANY'): """ Function used only to open handle. For better exception behavior handling. """ handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY,identifier) return handle
#dependencies="00a" __author__ = 'chet' # # $Id$ # import gumtools as gt import serial from labjack import ljm from time import sleep ser = serial.Serial(port='COM7', baudrate=115200, timeout=1) if not gt.login(ser): gt.fail(ser) #open the labjack with the specified serial # on any available connection lj = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "470010285") gpios = [] #iterate over all GPIOs for i in xrange(8): gpios.append(True) #just to save copiable code, loop over I/O 0 or 1 for val in xrange(2): #VERY IMPORTANT always reset LJ to low out to avoid driving LJ and Gumstix simultaneously DIO = "FIO%i" % i ljm.eWriteName(lj, DIO, 0) #configure GPIO to output ser.write('echo out > /gpio/boardio%i/direction\r' % (i + 1)) sleep(1) ser.write('echo %i > /gpio/boardio%i/value\r' % (val, i + 1)) sleep(1) #read value on LJ
#dependencies="00a" __author__ = 'chet' # # $Id$ # import gumtools as gt import serial from labjack import ljm from time import sleep ser = serial.Serial(port='COM7', baudrate=115200, timeout=1) if not gt.login(ser): gt.fail(ser) #open the labjack with the specified serial # on any available connection lj = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "470010285") gpios = [] #iterate over all GPIOs for i in xrange(8): gpios.append(True) #just to save copiable code, loop over I/O 0 or 1 for val in xrange(2): #VERY IMPORTANT always reset LJ to low out to avoid driving LJ and Gumstix simultaneously DIO = "FIO%i" % i ljm.eWriteName(lj, DIO, 0) #configure GPIO to output ser.write('echo out > /gpio/boardio%i/direction\r' % (i+1)) sleep(1) ser.write('echo %i > /gpio/boardio%i/value\r' % (val, i+1)) sleep(1) #read value on LJ