def openDevice(quiet=QUIET_OPEN):
    """Open a device.

    This is defined in one place as a quick way to configure which device is
    opened for all of the scripts in the SD directory.
    """
    # Open first found LabJack
    handle = ljm.openS("ANY", "ANY",
                       "ANY")  # Any device, Any connection, Any identifier
    #handle = ljm.openS("T7", "ANY", "ANY")  # T7 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)

    if not quiet:
        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]))

    if info[0] == ljm.constants.dtT4:
        print("The T4 does not support an SD card.")
        print("Exiting now.")
        exit()

    return handle
 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)
Exemple #3
0
    def init_labjack_task(self, session, params=None):
        """
        task to initialize labjack module
        """

        if self.initialized:
            return True, "Already initialized module"

        with self.lock.acquire_timeout(0, job='init') as acquired:
            if not acquired:
                self.log.warn("Could not start init because "
                              "{} is already running".format(self.lock.job))
                return False, "Could not acquire lock."

            session.set_status('starting')
            # Connect with the labjack
            self.handle = ljm.openS("ANY", "ANY", self.ip_address)
            info = ljm.getHandleInfo(self.handle)
            self.log.info(
                "\nOpened LabJack of type: %i, Connection type: %i,\n"
                "Serial number: %i, IP address: %s, Port: %i" %
                (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4]))

        session.add_message("Labjack initialized")

        self.initialized = True

        # Start data acquisition if requested in site-config
        auto_acquire = params.get('auto_acquire', False)
        if auto_acquire:
            self.agent.start('acq')

        return True, 'LabJack module initialized.'
Exemple #4
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)
Exemple #5
0
    def connect(self):
        try:
            self.handle = ljm.openS(self.params['device'],
                                    self.params['connection'],
                                    self.params['devid'])
            info = ljm.getHandleInfo(self.handle)

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

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

            return 1

        except Exception as e:
            log.error('Failed to connect to LabJack (%s): %s.' %
                      (self.params['devid'], e))
Exemple #6
0
def find_LJ():
    # Look for LabJack
    lookforLJ = True
    while lookforLJ:
        # Try to find LabJack
        try:
            handle = ljm.openS(
                'T7', 'ANY',
                'ANY')  # T7 device, Any connection, Any identifier
            info = ljm.getHandleInfo(handle)  # LabJack Info
            print('Connected to LabJack')
            return (handle, info)
            ljm.closeAll
            lookforLJ = False

        # If LabJack isn't found
        except:
            print('Not finding a LabJack Connection... \n')
            while True:
                LJ_response = input('Would you like to try again? (y/n) \n')
                if LJ_response == 'y':
                    break
                elif LJ_response == 'n':
                    sys.exit()
                    lookforLJ = False
                else:
                    print(
                        'Invalid response. Please enter y for yes or n for no\n'
                    )
def main():
    try:
        luaScript = """-- Use USER_RAM0_U16 (register 46180) to determine which control loop to run
                    local ramval = 0
                    MB.W(46180, 0, ramval)
                    local loop0 = 0
                    local loop1 = 1
                    local loop2 = 2

                    -- Setup an interval to control loop execution speed. Update every second
                    LJ.IntervalConfig(0,1000)
                    while true do
                      if LJ.CheckInterval(0) then
                        ramval = MB.R(46180, 0)

                        if ramval == loop0 then
                          print("using loop0")
                        end

                        if ramval == loop1 then
                          print("using loop1")
                        end

                        if ramval == loop2 then
                          print("using loop2")
                        end

                      end
                    end"""
        # Open first found LabJack
        handle = ljm.openS("ANY", "ANY",
                           "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]))

        loadLuaScript(handle, luaScript)
        print("LUA_RUN %d" % ljm.eReadName(handle, "LUA_RUN"))
        print("LUA_DEBUG_NUM_BYTES: %d" %
              ljm.eReadName(handle, "LUA_DEBUG_NUM_BYTES"))
        readLuaInfo(handle)
        # Close handle
        ljm.close(handle)
    except ljm.LJMError:
        ljm.eWriteName(handle, "LUA_RUN", 0)
        # Close handle
        ljm.close(handle)
        raise
    except Exception:
        ljm.eWriteName(handle, "LUA_RUN", 0)
        # Close handle
        ljm.close(handle)
        raise
    def Open(self, serial_number, model="ANY", connection="ANY"):
        with self.lock:
            # sn_in_use = { <serial number> : 'device': <device instance>, 'use': <count> }
            if serial_number in self.sn_in_use:
                # Already in use, return handle and don't re-open
                self.sn_in_use[serial_number]['use'] += 1

            else:

                # Not in use, so open it and put into sn_in_use table
                try:
                    handle = ljm.openS(str(model), str(connection),
                                       str(serial_number))

                except Exception as e:
                    print("openS returned '%s'" % str(e))
                    raise LabJackException(e.message,
                                           code=LJD_LABJACK_NOT_FOUND)

                device = LabJackDevice(self, handle, 0, connection,
                                       str(serial_number))

                device.SetChannelList(self.GetChannelList(str(model)))

                self.sn_in_use[serial_number] = {'device': device, 'use': 1}

            return self.sn_in_use[serial_number]['device']
Exemple #9
0
 def open(self):
     self.handle = ljm.openS(self.device, self.connection, self.identifier)
     names, values = [], []
     for c in self.chan_list:
         if "to_write" in c:
             for n, v in c['to_write']:
                 names.append(c['name'] + n)
                 values.append(v)
     #names.append("STREAM_NUM_ADDRESSES");values.append(len(self.channels))
     names.append("STREAM_SCANRATE_HZ")
     values.append(self.scan_rate)
     names.append("STREAM_RESOLUTION_INDEX")
     values.append(self.resolution)
     ljm.eWriteNames(self.handle, len(names), names, values)
     scan_rate = ljm.eReadName(self.handle, "STREAM_SCANRATE_HZ")
     if scan_rate != self.scan_rate:
         print("[Labjack] Actual scan_rate:", scan_rate, "instead of",
               self.scan_rate)
         self.scan_rate = scan_rate
     if any([c.get("make_zero", False) for c in self.chan_list]):
         print("[Labjack] Please wait during offset evaluation...")
         off = self.eval_offset()
         names, values = [], []
         for i, c in enumerate(self.chan_list):
             if 'make_zero' in c and c['make_zero']:
                 c['offset'] += c['gain'] * off[i]
     self.n = 0  # Number of data points (to rebuild time)
 def connect(self):
     try:
         self.handle = ljm.openS(self.deviceType, self.connectionType,
                                 self.identifier)
     except ljm.LJMError as e:
         self.handle = None
         raise UnknownDeviceError(self.deviceType, self.connectionType,
                                  self.identifier, e)
def get_labjack_value(idx):
    # Open first found LabJack
    handle = ljm.openS("ANY", "ANY", "ANY")
    print("\neFetching results for the station: {}".format(idx))
    results = (abs(ljm.eReadName(handle, idx)) / 0.1) * 9

    print("\neReadNames results: {}".format(results))

    return json.dumps(results)
Exemple #12
0
def connect_to_LJ():
    handle = ljm.openS("T7", "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]))
    return handle
Exemple #13
0
 def __init__(self, debug=True):
     self.handle = ljm.openS("ANY", "ANY", "ANY")
     info = ljm.getHandleInfo(self.handle)
     if debug:
         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]))
Exemple #14
0
 def labJackSetUp(self):
     global handle
     handle = ljm.openS("T7", "ANY",
                        "ANY")  # T7 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]))
Exemple #15
0
        def __new__(cls, *args):

            try:
                from labjack import ljm
                handle = ljm.openS("ANY", "ANY", "ANY")
                ljm.close(handle)
                return STORMDAQ(*args)

            except:
                return mockers.MockDAQ()
Exemple #16
0
    def start(self, cmd=None):
        super().start(cmd)
        print('Starting LabJackT7Device')

        try:
            self.lj = ljm.openS(deviceType=self.device_type,
                                connectionType=self.conection_type,
                                identifier=self.identifier)
        except ljm.LJMError as e:
            print(f'could not connect to labjack: {e}')
            self.lj = None
Exemple #17
0
    def __init__(self, device='ANY', connection='ANY', devid='ANY'):
        try:
            self.handle = ljm.openS(device, connection, devid)
            info = ljm.getHandleInfo(self.handle)

            self.deviceType = info[0]
            assert self.deviceType in [ljm.constants.dtT7, ljm.constants.dtT4]

            print('Connected to LabJack (%i).' % (info[2]))
        except Exception as e:
            print('Failed to connect to LabJack (%s): %s.' % (devid, e))
Exemple #18
0
    def connectLabjack(self):
        self.labjackHandle = ljm.openS("T7", "ANY", "ANY")
        info = ljm.getHandleInfo(self.labjackHandle)
        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]))

        ljm.eWriteName(self.labjackHandle, "AIN_ALL_RANGE", 10.0)
        ljm.eWriteName(self.labjackHandle, "AIN_ALL_RESOLUTION_INDEX", 8)
Exemple #19
0
def load_labjack(device_spec):
    """Load labjack to bind to.

    @param device_spec: Information about the device to open. Should be dict
        with keys deviceType, connectionType, and identifier that correspond
        to the same parameters in the ljm open call.
    @type device_spec: dict
    @return: LabJack device that will be bound to.
    @rtype: LJM handle
    """
    return ljm.openS(device_spec['deviceType'], device_spec['connectionType'],
                     device_spec['identifier'])
Exemple #20
0
    def controllerInit(self):
        '''
        initalize the controller
        '''
        i = 0
        msg = ''

        self.controller = ljm.openS('T7', 'USB', '470013817')
        self.loadWiring()
        msg = self.checkRelayPower()
        i = 4  # If everything worked out break the while loop
        self.configureTemperatureInputs()
        return msg
Exemple #21
0
def load_labjack(device_spec):
    """Load labjack to bind to.

    @param device_spec: Information about the device to open. Should be dict
        with keys deviceType, connectionType, and identifier that correspond
        to the same parameters in the ljm open call.
    @type device_spec: dict
    @return: LabJack device that will be bound to.
    @rtype: LJM handle
    """
    return ljm.openS(
        device_spec['deviceType'],
        device_spec['connectionType'],
        device_spec['identifier']
    )
Exemple #22
0
    def __init__(self):
        """
        Creates a connection with a T7 labjack connected in any port.
        Also creates some constants to be used later
        """

        self.handle = ljm.openS(
            "T7", "Any", "ANY")  #Connects with a T7 labjack in "ANY" port
        self.info = ljm.getHandleInfo(self.handle)

        #Constant, they save space
        self.WRITE = ljm.constants.WRITE
        self.READ = ljm.constants.READ
        self.FLOAT32 = ljm.constants.FLOAT32  #Currently the only one used
        self.UINT16 = ljm.constants.UINT16
        self.UINT32 = ljm.constants.UINT32
Exemple #23
0
    def connect(self):
        """ Function used for connecting to labjack with parameters specified in Parameters class.

        :return: True if connection successful, False if connection error occurred
        """

        # check if already connected
        if self.connection_state:
            if Parameters.DEBUG:
                print(
                    "Function labjack_connection.connect: already connected!")
            return True
        # if not, try to connect
        else:
            # open Labjack connection with given parameters
            try:
                self.connection_handle = ljm.openS(
                    "ANY", Parameters.LABJACK_CONNECTION,
                    Parameters.LABJACK_SERIAL_NUMBER)
            except (ValueError, LJMError):
                if Parameters.DEBUG:
                    print("Couldn't connect to labjack! (part 1)")
                self.connection_state = False
                return False

            # check for success
            if self.connection_handle > 0:
                if Parameters.DEBUG:
                    info = ljm.getHandleInfo(self.connection_handle)
                    print(
                        "Function labjack_connection.connect: connection successful!"
                    )
                    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]))
                self.connection_state = True
                return True
            # connection not successful
            else:
                if Parameters.DEBUG:
                    print("Couldn't connect to labjack! (part 2)")
                    print("Connection handle is: ", self.connection_handle)
                self.connection_state = False
                return False
Exemple #24
0
 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]))
     print('Labjack Class initialization 1')
     self.configure()
     print('Labjack Class initialization 2')
     self.servo_position = 1500.0 # in PWM value units
     self.airspeed = 0.0
     self.flap_servo_neutral = 1580.
     self.motor_servo_neutral = 1620.
     print('Labjack Class Servo Configuration')
     self.configure_servo()
Exemple #25
0
    def __init__(self):
        self._labjack = ljm.openS("T7", "USB", "ANY")

        self._serial_number = ljm.eReadName(self._labjack, 'SERIAL_NUMBER')

        # Start making the GUI to display when this sensor is selected
        self._widget = BaseWidget()

        # Label to show the serial number of the Labjack
        self._widget.serial_number = ControlLabel()
        self._widget.serial_number.value = str(int(self._serial_number))

        # Number input to get the threshold for an 'on' signal
        # for frequency calculations
        self._widget.threshold = ControlNumber(label="Threshold",
                                               default=0.1,
                                               minimum=0,
                                               maximum=float('inf'),
                                               decimals=5)
    def Connect(self):
        self.animate()  #plot once connected.

        try:
            self.handle = ljm.openS("T7", "ANY", "ANY")
            # T7 device, Any connection, Any identifier
        except ljm.LJMError:
            self.ErrorText =\
                "LJM error while connecting - check if device is connected"
            self.UpdateErrorText()
            return
        self.IsConnected = True
        info = ljm.getHandleInfo(self.handle)
        self.DeviceType = info[0]
        self.ConnectionType = info[1]
        self.SerialNumber = info[2]
        self.IPaddress = ljm.numberToIP(info[3])
        self.Port = info[4]
        self.MaxBytesPerMB = info[5]
        self.UpdateInfo()
Exemple #27
0
def retrieve_analogvalues():
    # Open first found LabJack
    handle = ljm.openS("ANY", "ANY", "ANY")

    # Call eReadName to read the serial number from the LabJack.
    name = "SERIAL_NUMBER"
    result = ljm.eReadName(handle, name)

    print("\neReadName result: ")
    print("    %s = %f" % (name, result))
    numFrames = 4
    # names = ["SERIAL_NUMBER", "PRODUCT_ID", "FIRMWARE_VERSION"]
    names = ['AIN0', 'AIN1', 'AIN2', 'AIN3']
    results = ljm.eReadNames(handle, numFrames, names)

    print("\neReadNames results: ")
    for i in range(numFrames):
        print("Measured Power of - %s, value : %f" %
              (names[i], (abs(results[i]) / 0.1) * 9))

    return results
Exemple #28
0
    def __init__(self, device='ANY', connection='ANY', devid='ANY'):
        try:
            self.handle = ljm.openS(device, connection, devid)
            info = ljm.getHandleInfo(self.handle)

            self.deviceType = info[0]
            assert self.deviceType in [ljm.constants.dtT7, ljm.constants.dtT4]

            print('Connected to LabJack (%i).' % (info[2]))
        except Exception as e:
            print('Failed to connect to LabJack (%s): %s.' % (devid, e))

        ## load submodules
        self.analog = Analog(self)
        self.digital = Digital(self)
        self.temperature = Temperature(self)
        self.pwm = PWM(self)
        self.spi = SPI(self)
        self.i2c = I2C(self)
        self.stream = Stream(self)
        self.waveform = WaveformGenerator(self)
        self.pattern = PatternGenerator(self)
        self.adc_stream = ADCStream(self)
 def open(self):
   self.handle = ljm.openS(self.device,self.connection,self.identifier)
   names,values = [],[]
   for c in self.chan_list:
     if "to_write" in c:
       for n,v in c['to_write']:
         names.append(c['name']+n)
         values.append(v)
   #names.append("STREAM_NUM_ADDRESSES");values.append(len(self.channels))
   names.append("STREAM_SCANRATE_HZ");values.append(self.scan_rate)
   names.append("STREAM_RESOLUTION_INDEX");values.append(self.resolution)
   ljm.eWriteNames(self.handle,len(names),names,values)
   scan_rate = ljm.eReadName(self.handle,"STREAM_SCANRATE_HZ")
   if scan_rate != self.scan_rate:
     print("[Labjack] Actual scan_rate:",scan_rate,"instead of",self.scan_rate)
     self.scan_rate = scan_rate
   if any([c.get("make_zero",False) for c in self.chan_list]):
     print("[Labjack] Please wait during offset evaluation...")
     off = self.eval_offset()
     names,values = [],[]
     for i,c in enumerate(self.chan_list):
       if 'make_zero' in c and c['make_zero']:
         c['offset'] += c['gain']*off[i]
   self.n = 0 # Number of data points (to rebuild time)
Exemple #30
0
from labjack import ljm
import time
import sys
from datetime import datetime

MAX_REQUESTS = 5  # The number of eStreamRead calls that will be performed.

# Open first found LabJack
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
Exemple #31
0
def get_handle():
    return ljm.openS(deviceType="T7",connectionType="USB",identifier ="ANY")
Exemple #32
0
    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   passwd="root",
                                   database="trusur_aqm")
    mycursor = mydb.cursor()
    mycursor.execute("SELECT id FROM aqm_sensor_values WHERE id=1")
    mycursor.fetchall()
    if mycursor.rowcount <= 0:
        mycursor.execute("INSERT INTO aqm_sensor_values (id) VALUES (1)")
        mydb.commit()
    print("[V] Database CONNECTED")
except Exception as e:
    print(e)

try:
    labjack = ljm.openS("ANY", "ANY", "ANY")
    is_labjack = True
    print("[V] Labjack CONNECTED")
except:
    print("    [X] Labjack not connected")

try:
    mycursor.execute(
        "SELECT content FROM aqm_configuration WHERE data = 'com_pm10'")
    rec = mycursor.fetchone()
    for row in rec:
        serial_port = rec[0]

    mycursor.execute(
        "SELECT content FROM aqm_configuration WHERE data = 'baud_pm10'")
    rec = mycursor.fetchone()
viz.addChild('ground_wood.osgb')

################################################################################################################################

# Establish connection with Treadmill Control Panel
HOST = '127.0.0.1' #name of the target computer that runs the treadmill controller
PORT = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

# QTM initialization
QUALISYS_IP = '192.168.252.1'
qualisysOn = False

# Establish connection with LabJack
handle = ljm.openS("T7","USB", "ANY")
#Switch = ljm.openS("T7", "USB", "ANY")

## check if LabJack is communicating with the computer
name = "SERIAL_NUMBER"
result = ljm.eReadName(handle, name)

print("\neReadName result: ")
print("    %s = %f" % (name, result))
ljm.eWriteName(handle,"DAC0",0)
ljm.eWriteName(handle,"DAC1",0)


################################################################################################################################

def updateViewHQ():
"""
Demonstrates I2C communication using the LJM driver. The demonstration uses a
a LJTick-DAC connected to FIO0/FIO1, configures I2C settings, and reads, writes
and reads bytes from/to the EEPROM.

"""

from labjack import ljm
from random import randrange

# Open first found LabJack
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]))

# Configure the I2C communication.
ljm.eWriteName(handle, "I2C_SDA_DIONUM", 1)  # SDA pin number = 1 (FIO1)
ljm.eWriteName(handle, "I2C_SCL_DIONUM", 0)  # SCL pin number = 0 (FIO0)

# Speed throttle is inversely proportional to clock frequency. 0 = max.
ljm.eWriteName(handle, "I2C_SPEED_THROTTLE", 0)  # Speed throttle = 0

# Options bits:
#   bit0: Reset the I2C bus.
#   bit1: Restart w/o stop
#   bit2: Disable clock stretching.
ljm.eWriteName(handle, "I2C_OPTIONS", 0)  # Options = 0
from labjack import ljm
import time
import csv
import numpy as np
from openpyxl import load_workbook

# Input Parameters
yValue = '22' # Input your known x-value (i.e. pressure, weight, temperature, etc.)
avename = 'Calibration_Values' # Existing excel file name where value will be logged
Record_Length = 1000 # Number of data points taken (sample rate = .004s), then averaged, for sensor output
#changechange

ave_filename = avename + '.xlsx'
if __name__ == "__main__":

    handle = ljm.openS("T7", "ANY", "ANY")  # T7 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]))

    # Setup and call eReadName to read from AIN0 on the LabJack.
    sigLocation = "AIN2"

    # List variables
    start = float(time.time())
    t_stamp_act = []
    t_stamp = ['T_Stamp',]
    v_out = ['V_Out',]
Exemple #36
0
    def __init__(self):

        # Open first found LabJack.
        self.handle = ljm.openS("ANY", "ANY", "ANY")
        #handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
        self.setallzero()