Esempio n. 1
0
 def open(self):
     self.handle = ljm.openS(self.device, self.connection, self.identifier)
     # ==== Writing initial config ====
     reg, types, values = [], [], []
     for c in self.in_chan_list + self.out_chan_list:
         # Turn (name,val) tuples to (addr,type,val)
         for i, t in enumerate(c.get('write_at_open', [])):
             if len(t) == 2:
                 c['write_at_open'][i] = ljm.nameToAddress(t[0]) + (t[1], )
         # Write everything we need
         for r, t, v in c.get('write_at_open', []):
             reg.append(r)
             types.append(t)
             values.append(v)
     if reg:
         ljm.eWriteAddresses(self.handle, len(reg), reg, types, values)
     # ==== Recap of the addresses to read/write ====
     self.read_addresses = [c['to_read'] for c in self.in_chan_list]
     self.read_types = [c['dtype'] for c in self.in_chan_list]
     self.write_addresses = [c['to_write'] for c in self.out_chan_list]
     self.write_types = [c['dtype'] for c in self.out_chan_list]
     self.last_values = [None] * len(self.write_addresses)
     # ==== Measuring zero to add to the offset (if asked to) ====
     if any([c.get("make_zero", False) for c in self.in_chan_list]):
         print("[Labjack] Please wait during offset evaluation...")
         off = self.eval_offset()
         names, values = [], []
         for i, c in enumerate(self.in_chan_list):
             if 'make_zero' in c and c['make_zero']:
                 names.append(c['name'] + '_EF_CONFIG_E')
                 values.append(c['offset'] + off[i])
         ljm.eWriteNames(self.handle, len(names), names, values)
Esempio n. 2
0
 def __init__(self, **kwargs):
     InOut.__init__(self)
     for arg, default in [
         ('device', 'ANY'),  # Model (T7, DIGIT,...)
         ('connection', 'ANY'),  # Connection (USB,ETHERNET,...)
         ('identifier', 'ANY'),  # Identifier (serial n°, ip,..)
         ('channels', [{
             'name': 'AIN0'
         }]),
         ('scan_rate', 100000),
         ('scan_per_read', 10000),
         ('resolution', 1)
     ]:
         setattr(self, arg, kwargs.pop(arg, default))
     assert len(
         kwargs) == 0, "T7_streamer got unsupported arg(s)" + str(kwargs)
     default = {'gain': 1, 'offset': 0, 'make_zero': False, 'range': 10}
     if len(self.channels) * self.scan_rate > 100000:
         self.scan_rate = 100000 / len(self.channels)
         print(
             "[Labjack] Warning! scan_rate is too high! Sample rate cannot "
             "exceed 100kS/s, lowering samplerate to", self.scan_rate,
             "samples/s")
     self.chan_list = []
     for d in self.channels:
         if isinstance(d, str):
             d = {'name': d}
         for k in ['gain', 'offset', 'make_zero', 'range']:
             if k not in d:
                 d[k] = default[k]
         if 'to_write' not in d:
             d['to_write'] = []
         d['to_write'].append(("_RANGE", d['range']))
         d['to_read'] = ljm.nameToAddress(d['name'])[0]
         self.chan_list.append(d)
 def __init__(self, **kwargs):
   InOut.__init__(self)
   for arg, default in [
                        ('device', 'ANY'), # Model (T7, DIGIT,...)
                        ('connection', 'ANY'), # Connection (USB,ETHERNET,...)
                        ('identifier', 'ANY'), # Identifier (serial n°, ip,..)
                        ('channels', [{'name':'AIN0'}]),
                        ('scan_rate',100000),
                        ('scan_per_read',10000),
                        ('resolution',1)
                        ]:
     setattr(self,arg,kwargs.pop(arg,default))
   assert len(kwargs) == 0, "T7_streamer got unsupported arg(s)" + str(kwargs)
   default = {'gain':1,'offset':0,'make_zero':False, 'range':10}
   if len(self.channels)*self.scan_rate > 100000:
     self.scan_rate = 100000/len(self.channels)
     print("[Labjack] Warning! scan_rate is too high! Sample rate cannot "\
         "exceed 100kS/s, lowering samplerate to",self.scan_rate,"samples/s")
   self.chan_list = []
   for d in self.channels:
     if isinstance(d,str):
       d = {'name':d}
     for k in ['gain','offset','make_zero','range']:
       if not k in d:
         d[k] = default[k]
     if not 'to_write' in d:
       d['to_write'] = []
     d['to_write'].append(("_RANGE",d['range']))
     d['to_read'] = ljm.nameToAddress(d['name'])[0]
     self.chan_list.append(d)
 def open(self):
   self.handle = ljm.openS(self.device,self.connection,self.identifier)
   # ==== Writing initial config ====
   reg,types,values = [],[],[]
   for c in self.in_chan_list+self.out_chan_list:
     # Turn (name,val) tuples to (addr,type,val)
     for i,t in enumerate(c.get('write_at_open',[])):
       if len(t) == 2:
         c['write_at_open'][i] = ljm.nameToAddress(t[0])+(t[1],)
     # Write everything we need
     for r,t,v in c.get('write_at_open',[]):
       reg.append(r)
       types.append(t)
       values.append(v)
   if reg:
     ljm.eWriteAddresses(self.handle,len(reg),reg,types,values)
   # ==== Recap of the addresses to read/write ====
   self.read_addresses = [c['to_read'] for c in self.in_chan_list]
   self.read_types = [c['dtype'] for c in self.in_chan_list]
   self.write_addresses = [c['to_write'] for c in self.out_chan_list]
   self.write_types = [c['dtype'] for c in self.out_chan_list]
   self.last_values = [None]*len(self.write_addresses)
   # ==== Measuring zero to add to the offset (if asked to) ====
   if any([c.get("make_zero",False) for c in self.in_chan_list]):
     print("[Labjack] Please wait during offset evaluation...")
     off = self.eval_offset()
     names,values = [],[]
     for i,c in enumerate(self.in_chan_list):
       if 'make_zero' in c and c['make_zero']:
         names.append(c['name']+'_EF_CONFIG_E')
         values.append(c['offset']+off[i])
     ljm.eWriteNames(self.handle,len(names),names,values)
Esempio n. 5
0
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]
    ljm.eWriteName(handle, "STREAM_TRIGGER_INDEX", address);

    # Clear any previous settings on triggerName's Extended Feature registers
    ljm.eWriteName(handle, "%s_EF_ENABLE" % triggerName, 0);

    # 5 enables a rising or falling edge to trigger stream
    ljm.eWriteName(handle, "%s_EF_INDEX" % triggerName, 5);

    # Enable
    ljm.eWriteName(handle, "%s_EF_ENABLE" % triggerName, 1);
Esempio n. 6
0
handle = ljm.openS("ANY", "ANY", "ANY")
# handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "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 Stream Out
OUT_NAMES = ["FIO_STATE", "DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT2_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT2_ENABLE", 1)

# Write values to the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT2_LOOP_SIZE", 8)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 111)
Esempio n. 7
0
def convert_name_to_int_type(name):
    return ljm.nameToAddress(name)[1]
Esempio n. 8
0
def convert_name_to_address(name):
    return ljm.nameToAddress(name)[0]
Esempio n. 9
0
def generador_Frecuecia(f1, f2, f3, f4, nombre):

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

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

    # Open first found LabJack

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Close handle
    ljm.close(handle)
    print("Termino")
Esempio n. 10
0
def convert_name_to_int_type(name):
    return ljm.nameToAddress(name)[1]
Esempio n. 11
0
def convert_name_to_address(name):
    return ljm.nameToAddress(name)[0]
                   "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]

# Setup Stream Out
OUT_NAMES = ["DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)

# Write values to the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", 6)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 0.0)  # 0.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 1.0)  # 1.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 2.0)  # 2.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 3.0)  # 3.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 4.0)  # 4.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 5.0)  # 5.0 V
Esempio n. 13
0
    def check_chan(self):
        default = {
            'gain': 1,
            'offset': 0,
            'make_zero': False,
            'resolution': 1,
            'range': 10,
            'direction': 1,
            'dtype': ljm.constants.FLOAT32,
            'limits': None
        }
        if not isinstance(self.channels, list):
            self.channels = [self.channels]
        # Let's loop over all the channels to set everything we need
        self.in_chan_list = []
        self.out_chan_list = []
        for d in self.channels:
            if isinstance(d, str):
                d = {'name': d}

            # === Modbus registers ===
            if isinstance(d['name'], int):
                for k in ['direction', 'dtype', 'limits']:
                    if k not in d:
                        d[k] = default[k]
                if d['direction']:
                    d['to_write'] = d['name']
                    d['gain'] = 1
                    d['offset'] = 0
                    self.out_chan_list.append(d)
                else:
                    d['to_read'] = d['name']
                    self.in_chan_list.append(d)

            # === AIN channels ===
            elif d['name'].startswith("AIN"):
                for k in [
                        'gain', 'offset', 'make_zero', 'resolution', 'range'
                ]:
                    if k not in d:
                        d[k] = default[k]
                if 'write_at_open' not in d:
                    d['write_at_open'] = []
                d['write_at_open'].extend(
                    [  # What will be written when opening the chan
                        ljm.nameToAddress(d['name'] + "_RANGE") +
                        (d['range'], ),
                        ljm.nameToAddress(d['name'] + "_RESOLUTION_INDEX") +
                        (d['resolution'], )
                    ])
                if 'thermocouple' in d:
                    therm = {
                        'E': 20,
                        'J': 21,
                        'K': 22,
                        'R': 23,
                        'T': 24,
                        'S': 25,
                        'C': 30
                    }
                    d['write_at_open'].extend([
                        ljm.nameToAddress(d['name'] + "_EF_INDEX") +
                        (therm[d['thermocouple']], ),
                        ljm.nameToAddress(d['name'] + "_EF_CONFIG_A") +
                        (1, ),  # for degrees C
                        ljm.nameToAddress(d['name'] + "_EF_CONFIG_B") +
                        (60052, ),  # CJC config
                        ljm.nameToAddress(d['name'] + "_EF_CONFIG_D") +
                        (1, ),  # CJC config
                        ljm.nameToAddress(d['name'] + "_EF_CONFIG_E") +
                        (0, )  # CJC config
                    ])
                    d['to_read'], d['dtype'] = ljm.nameToAddress(d['name'] +
                                                                 "_EF_READ_A")
                elif d["gain"] == 1 and d['offset'] == 0 and not d['make_zero']:
                    # No gain/offset
                    # We can read directly of the AIN register
                    d['to_read'], d['dtype'] = ljm.nameToAddress(d['name'])
                else:  # With gain and offset: let's use Labjack's built in slope
                    d['write_at_open'].extend([
                        ljm.nameToAddress(d['name']+"_EF_INDEX")+(1,), # for slope
                        ljm.nameToAddress(d['name']+"_EF_CONFIG_D")+(d['gain'],),
                        ljm.nameToAddress(d['name']+"_EF_CONFIG_E")\
                        +(d['offset'] if not d['make_zero'] else 0,),
                    ]) # To configure slope in the device
                    d['to_read'], d['dtype'] = ljm.nameToAddress(d['name'] +
                                                                 "_EF_READ_A")

                self.in_chan_list.append(d)

            # === DAC/TDAC channels ===
            elif "DAC" in d['name']:
                for k in ['gain', 'offset', 'limits']:
                    if k not in d:
                        d[k] = default[k]
                d['to_write'], d['dtype'] = ljm.nameToAddress(d['name'])
                self.out_chan_list.append(d)

            # === FIO/EIO/CIO/MIO channels ===
            elif "IO" in d['name']:
                if "direction" not in d:
                    d["direction"] = default["direction"]
                if d["direction"]:  # 1/True => output, 0/False => input
                    d['gain'] = 1
                    d['offset'] = 0
                    d['limits'] = None
                    d['to_write'], d['dtype'] = ljm.nameToAddress(d['name'])
                    self.out_chan_list.append(d)
                else:
                    d['to_read'], d['dtype'] = ljm.nameToAddress(d['name'])
                    self.in_chan_list.append(d)

            else:
                raise AttributeError("[labjack] Invalid chan name: " +
                                     str(d['name']))

            self.in_chan_dict = {}
            for c in self.in_chan_list:
                self.in_chan_dict[c["name"]] = c
            self.out_chan_dict = {}
            for c in self.out_chan_list:
                self.out_chan_dict[c["name"]] = c
def convertNameToAddress(name):
    return ljm.nameToAddress(name)[0]
def convertNameToIntType(name):
    return ljm.nameToAddress(name)[1]
  def check_chan(self):
    default = {'gain':1,'offset':0,'make_zero':False,'resolution':1,
        'range':10,'direction':1,'dtype':ljm.constants.FLOAT32,'limits':None}
    if not isinstance(self.channels,list):
      self.channels = [self.channels]
    # Let's loop over all the channels to set everything we need
    self.in_chan_list = []
    self.out_chan_list = []
    for d in self.channels:
      if isinstance(d,str):
        d = {'name':d}

      # === Modbus registers ===
      if isinstance(d['name'],int):
        for k in ['direction','dtype','limits']:
          if not k in d:
            d[k] = default[k]
        if d['direction']:
          d['to_write'] = d['name']
          d['gain'] = 1
          d['offset'] = 0
          self.out_chan_list.append(d)
        else:
          d['to_read'] = d['name']
          self.in_chan_list.append(d)

      # === AIN channels ===
      elif d['name'].startswith("AIN"):
        for k in ['gain','offset','make_zero','resolution','range']:
          if not k in d:
            d[k] = default[k]
        if not 'write_at_open' in d:
          d['write_at_open'] = []
        d['write_at_open'].extend([ # What will be written when opening the chan
            ljm.nameToAddress(d['name']+"_RANGE")+(d['range'],),
            ljm.nameToAddress(d['name']+"_RESOLUTION_INDEX")+(d['resolution'],)
            ])
        if 'thermocouple' in d:
          therm = {'E':20,'J':21,'K':22,'R':23,'T':24,'S':25,'C':30}
          d['write_at_open'].extend([
              ljm.nameToAddress(d['name']+"_EF_INDEX")\
                +(therm[d['thermocouple']],),
              ljm.nameToAddress(d['name']+"_EF_CONFIG_A")+(1,), # for degrees C
              ljm.nameToAddress(d['name']+"_EF_CONFIG_B")+(60052,), # CJC config
              ljm.nameToAddress(d['name']+"_EF_CONFIG_D")+(1,), # CJC config
              ljm.nameToAddress(d['name']+"_EF_CONFIG_E")+(0,) # CJC config
            ])
          d['to_read'],d['dtype'] = ljm.nameToAddress(d['name']+"_EF_READ_A")
        elif d["gain"] == 1 and d['offset'] == 0 and not d['make_zero']:
          # No gain/offset
          # We can read directly of the AIN register
          d['to_read'],d['dtype'] = ljm.nameToAddress(d['name'])
        else: # With gain and offset: let's use Labjack's built in slope
          d['write_at_open'].extend([
              ljm.nameToAddress(d['name']+"_EF_INDEX")+(1,), # for slope
              ljm.nameToAddress(d['name']+"_EF_CONFIG_D")+(d['gain'],),
              ljm.nameToAddress(d['name']+"_EF_CONFIG_E")\
                  +(d['offset'] if not d['make_zero'] else 0,),
              ]) # To configure slope in the device
          d['to_read'],d['dtype'] = ljm.nameToAddress(d['name']+"_EF_READ_A")

        self.in_chan_list.append(d)

      # === DAC/TDAC channels ===
      elif "DAC" in d['name']:
        for k in ['gain','offset','limits']:
          if not k in d:
            d[k] = default[k]
        d['to_write'],d['dtype'] = ljm.nameToAddress(d['name'])
        self.out_chan_list.append(d)

      # === FIO/EIO/CIO/MIO channels ===
      elif "IO" in d['name']:
        if not "direction" in d:
          d["direction"] = default["direction"]
        if d["direction"]: # 1/True => output, 0/False => input
          d['gain'] = 1
          d['offset'] = 0
          d['limits'] = None
          d['to_write'],d['dtype'] = ljm.nameToAddress(d['name'])
          self.out_chan_list.append(d)
        else:
          d['to_read'],d['dtype'] = ljm.nameToAddress(d['name'])
          self.in_chan_list.append(d)

      else:
        raise AttributeError("[labjack] Invalid chan name: "+str(d['name']))

      self.in_chan_dict = {}
      for c in self.in_chan_list:
        self.in_chan_dict[c["name"]] = c
      self.out_chan_dict = {}
      for c in self.out_chan_list:
        self.out_chan_dict[c["name"]] = c