Ejemplo n.º 1
0
    def find_all():
        """Find all connected FTDI devices.

        :returns: list of (manufacturer, description, serial#) tuples.

        """
        return pylibftdi.Driver().list_devices()
Ejemplo n.º 2
0
    def inner():
        import sys
        args = sys.argv

        if len(args) > 1:
            serial = args[1]
        else:
            serial = None

        if serial:
            func(serial)
            return 0
        else:
            print('Looking for APT controllers')
            drv = pylibftdi.Driver()
            controllers = drv.list_devices()

            if controllers:
                for con in controllers:
                    print('Found %s %s S/N: %s' % con)
                    func(con[2])
                    print('')

                return 0
            else:
                print(
                    '\tNo APT controllers found. Maybe you need to specify a PID'
                )
                return 1
Ejemplo n.º 3
0
def main(args):
  print 'Looking for APT controllers'
  drv = pylibftdi.Driver()

  st = time.time()
  controllers = drv.list_devices()
  print '\tlist_devices:',time.time()-st

  if controllers:
    for con in controllers:
      print 'Found %s %s S/N: %s'%con
      st = time.time()
      with pyAPT.MTS50(serial_number=con[2]) as con:
        print '\topen:',time.time()-st
        st = time.time()
        status = con.status()
        print '\tstatus:',time.time()-st

        print '\tController status:'
        print '\t\tPosition: %.2fmm'%(status.position)
        print '\t\tVelocity: %.2fmm'%(status.velocity)
        print '\t\tStatus:',status.flag_strings()

      return 0
  else:
    print '\tNo APT controllers found. Maybe you need to specify a PID'
    return 1
Ejemplo n.º 4
0
def main(args):
  if len(args)<3:
    print(__doc__)
    return 1

  acc = float(args[1])
  max_vel = float(args[2])

  if len(args)>3:
    serial = args[3]
  else:
    serial = None

  if serial:
    set_vel_params(serial, acc, max_vel)
    return 0
  else:
    print('Looking for APT controllers')
    drv = pylibftdi.Driver()
    controllers = drv.list_devices()

    if controllers:
      for con in controllers:
        print('Found %s %s S/N: %s'%con)
        set_vel_params(con[2], acc, max_vel)

      return 0
    else:
      print('\tNo APT controllers found. Maybe you need to specify a PID')
      return 1
Ejemplo n.º 5
0
 def init_fpga_list(self):
     new_list = pylibftdi.Driver().list_devices()
     self.fpga_list = []
     for n_id, name in enumerate(new_list):
         if name[1] == "DLP-FPGA":
             self.fpga_list.append(lib_fpga.Fpga(device_index=n_id))
     print "found " + str(len(self.fpga_list)) + " FPGAs connected"
Ejemplo n.º 6
0
 def __init__(self):
     drv = pylibftdi.Driver()
     controllers = drv.list_devices()
     if controllers:
         controllers = drv.list_devices()
         self.info = controllers[0]
         self.serial = self.info[2]
         self.controller = pyAPT.MTS50(serial_number=self.serial)
     else:
         print('No controllers found')
Ejemplo n.º 7
0
def main():
    # Print as imported USB_PID_LIST
    print "Imported USB_PID_LIST:", map(hex, pylibftdi.USB_PID_LIST)

    # Append new USB PID number to the USB_PID_LIST
    pylibftdi.USB_PID_LIST.append(0x6015)

    # Print updated USB_PID_LIST
    print "Updated USB_PID_LIST:", map(hex, pylibftdi.USB_PID_LIST)
    print pylibftdi.Driver().list_devices()

    for device in get_ftdi_device_list():
        print "Devices:", (device)
Ejemplo n.º 8
0
def get_ftdi_device_list():
    """
    return a list of lines, each a colon-separated
    vendor:product:serial summary of detected devices
    """
    dev_list = []
    for device in pylibftdi.Driver().list_devices():
        # list_devices returns bytes rather than strings
        dev_info = map(lambda x: x.decode('latin1'), device)
        # device must always be this triple
        vendor, product, serial = dev_info
        dev_list.append("%s:%s:%s" % (vendor, product, serial))
    return dev_list
Ejemplo n.º 9
0
    def _get_ftdi_device_list(self):
        """
        return a list of lines, each a colon-separated
        vendor:product:serial summary of detected devices
        """
        dev_list = []
        for device in ftdi.Driver().list_devices():
            # list_devices returns bytes rather than strings
            dev_info = map(lambda x: x.decode('latin1'), device)
            # device must always be this triple
            vendor, product, serial = dev_info

            # We used to return a whole ton of stuff
            # dev_list.append("%s:%s:%s" % (vendor, product, serial))

            # Now just return the serial number
            dev_list.append(serial)
        return dev_list
Ejemplo n.º 10
0
    def scan(self, override_params=None, quiet=False):
        self.port = None
        if override_params is not None: self.params = override_params

        # Check device is present on the bus.
        if 'bcdDevice' in self.params.keys():
            usbCoreDev = usb.core.find(idVendor=self.params['vid'],idProduct=self.params['pid'],\
                             bcdDevice=self.params['bcdDevice'])
        else:
            usbCoreDev = usb.core.find(idVendor=self.params['vid'],
                                       idProduct=self.params['pid'])

        if usbCoreDev is None:
            raise pyLabDataLoggerIOError("USB Device %s not found" %
                                         self.params['name'])

        # Parse driver parameters
        self.bus = usbCoreDev.bus
        self.adds = usbCoreDev.address

        # Find the matching pyAPT device seen on the USB tree, ensure it exists
        try:
            cprint('\tLooking for APT controllers', 'green')
            drv = pylibftdi.Driver()
            controllers = drv.list_devices()
        except:
            raise RuntimeError(
                "Error loading FTDI drivers. You may need superuser priveliges."
            )

        if self.serial_number is None:
            for controller in controllers:
                cprint(controller, 'magenta')
                con = pyAPT.Controller(serial_number=controller[2])
                print('\t', con.info())
                if fmatch(con, self.bus, self.adds):
                    self.serial_number = controller[2]

        if self.serial_number is None:
            cprint("Could not open port to device.", 'red', attrs=['bold'])
        else:
            self.activate(quiet=quiet)
        return
Ejemplo n.º 11
0
def ftdi_info():
    """
    Return (ordered) dictionary contianing pylibftdi environment info

    Designed for display purposes only; keys and value types may vary.
    """
    info = OrderedDict()
    d = pylibftdi.Driver()
    info['pylibftdi version'] = pylibftdi.__VERSION__
    try:
        info['libftdi version'] = d.libftdi_version()
        info['libftdi library name'] = d._load_library('libftdi')._name
    except pylibftdi.LibraryMissingError:
        info['libftdi library'] = "Missing"
    try:
        info['libusb version'] = d.libusb_version()
        info['libusb library name'] = d._load_library('libusb')._name
    except pylibftdi.LibraryMissingError:
        info['libusb library'] = "Missing"
    info['Python version'] = platform.python_version()
    info['OS platform'] = platform.platform()
    return info
Ejemplo n.º 12
0
def main(args):
  print 'Looking for APT controllers'
  drv = pylibftdi.Driver()
  controllers = drv.list_devices()

  if len(args)>1:
    serial = args[1]
  else:
    serial = None

  if serial:
    controllers = filter(lambda x:x[2] == serial, controllers)

  if controllers:
    for con in controllers:
      print 'Found %s %s S/N: %s'%con
      with pyAPT.MTS50(serial_number=con[2]) as con:
        print '\tPosition (mm) = %.2f [enc:%d]'%(con.position(), con.position(raw=True))

      return 0
  else:
    print '\tNo APT controllers found. Maybe you need to specify a PID'
    return 1
Ejemplo n.º 13
0
    def __init__(self, conf, cbs=None, rpc_target=None):
        super(Controller, self).__init__()
        self.config = conf
        self.cbs = cbs
        self.status_poll = conf['status_poll']
        self.controllers = {}

        if True:
            # Get info of all axes, create a controller for each
            drv = pylibftdi.Driver()
            controllers = drv.list_devices()
            rpc_target.register(
                self.describe,
                "{}.thorlabs.describe".format(rpc_target.namespace))
            for controller in controllers:
                id = controller[2].decode('latin-1')
                self.controllers[id] = MotorController(
                    {
                        "serial_number": id,
                        "label": None
                    },
                    cbs=self.cbs,
                    rpc_target=rpc_target)
            self.config['controllers'] = self.generate_config()
Ejemplo n.º 14
0
    def __init__(self,hwser=None):
      # add Thorlabs devices to USB_PID_LIST -> in the __init__.py script
      #pylibftdi.USB_PID_LIST.append(0xfaf0)

      # Get list of connected devices
      devList = pylibftdi.Driver().list_devices()
      # Find out how many serial devices are connected to the USB bus
      numDevices = len(devList)
#        # Check each device to see if either the serial number matches (if given) or the description string is recognized as valid for the class type
      numMatchingDevices=0
      for dev in range(numDevices):
        detail = devList[dev]
        if hwser!=None and detail[2]!="" and int(detail[2])==hwser:
          # Get the first device which matches the serial number if given
          numMatchingDevices+=1
          self.device=device=pylibftdi.Device(mode='b',device_id=detail[2].decode())
          break
        elif hwser==None and (detail[1].decode() in self.deviceDescriptionStrings()):
          # Get the first device which is valid for the given class if no hwser
          numMatchingDevices+=1
          if numMatchingDevices==1:
            self.device=device=pylibftdi.Device(mode='b',device_id=detail[2].decode())
          elif dev==numDevices-1 and numMatchingDevices==0:
             # Raise an exception if no devices were found
             if hwser!=None:
                 errorStr="Hardware serial number " + str(hwser) + " was not found" 
             else:
                 errorStr="No devices found matching class name " + type(self).__name__ + ". Expand the definition of CLASS_STRING_MAPPING if necessary"
             raise DeviceNotFoundError(errorStr)
      # Print a warning message if no serial given and multiple devices were found which matched the class type
      if numMatchingDevices>1 and hwser==None: 
          print(str(numMatchingDevices)+" devices found matching " + type(self).__name__ + "; the first device was opened")
      # Inititalize the device according to FTD2xx and APT requirements
      device.baudrate = 115200

      # Return exception if there is an error in ftdi function
      def _checked_c(ret):
        if not ret == 0:
          raise Exception(device.ftdi_fn.ftdi_get_error_string())

      _checked_c(device.ftdi_fn.ftdi_set_line_property( 8,  # number of bits
                                                        1,  # number of stop bits
                                                        0   # no parity
                                                        ))
      self.delay()
      device.flush(pylibftdi.FLUSH_BOTH)
      self.delay()

      # Skip the reset part

      # From ftdi.h
      SIO_RTS_CTS_HS = (0x1 << 8)
      _checked_c(device.ftdi_fn.ftdi_setflowctrl(SIO_RTS_CTS_HS))
      _checked_c(device.ftdi_fn.ftdi_setrts(1))

      # Check first 2 digits of serial number to see if it's normal type or card/slot type, and build self.channelAddresses as list of (chanID,destAddress) tuples
      self.channelAddresses=[]
      if device.device_id[0:2] in c.BAY_TYPE_SERIAL_PREFIXES:
        # Get the device info
        serNum,model,hwtype,firmwareVer,notes,hwVer,modState,numCh=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO,destID=c.RACK_CONTROLLER_ID)[-1]
        # Check each bay to see if it's enabled and also request hardware info
        for bay in range(numCh):
          bayId=c.ALL_BAYS[bay]
          self.writeMessage(c.MGMSG_HW_NO_FLASH_PROGRAMMING,destID=bayId)
          if self.BayUsed(bay):
            bayInfo=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO,destID=bayId)[-1]
            self.channelAddresses.append((c.CHANNEL_1,bayId))
      else:
        # Otherwise just build a list of the channel numbers
        self.writeMessage(c.MGMSG_HW_NO_FLASH_PROGRAMMING,destID=c.GENERIC_USB_ID)
        try:
          serNum,model,hwtype,firmwareVer,notes,hwVer,modState,numCh=self.query(c.MGMSG_HW_REQ_INFO,c.MGMSG_HW_GET_INFO,waitTime=c.INIT_QUERY_TIMEOUT)[-1]
        except:
          print('Device not responding, trying manual initialization')
          numCh = 1
          model = b'TCD001\x00\x00'
          serNum = 00000000
          notes = b'APT DC Motor Controller'
        for channel in range(numCh):
          self.channelAddresses.append((c.ALL_CHANNELS[channel],c.GENERIC_USB_ID))  
      for channel in range(len(self.channelAddresses)):
        self.writeMessage(c.MGMSG_MOD_SET_CHANENABLESTATE,1,c.CHAN_ENABLE_STATE_ENABLED,c.RACK_CONTROLLER_ID)            
        self.EnableHWChannel(channel)
      # Set the controller type
      #print(model)
      #input()
      self.controllerType=model.split(b'\x00',1)[0].decode()
      # Print a message saying we've connected to the device successfuly
      print("Connected to %s device with serial number %d. Notes about device: %s"%(model.split(b'\x00',1)[0].decode(),serNum,notes.split(b'\x00',1)[0].decode()))
 def setUp(self):
     self.driver = pylibftdi.Driver()
     self.devices = self.driver.list_devices()
import unittest
import time

import pylibftdi

MANUFACTURER = 'FTDI'
DESCRIPTION = 'USB <-> Serial'
SERIAL_NUM = ''
MUONLAB_ID = (MANUFACTURER, DESCRIPTION, SERIAL_NUM)

hardware_is_present = lambda: MUONLAB_ID in \
    pylibftdi.Driver().list_devices()


class ListDevicesTest(unittest.TestCase):
    def setUp(self):
        self.driver = pylibftdi.Driver()
        self.devices = self.driver.list_devices()

    def test_list_devices_returns_list(self):
        self.assertIsInstance(self.devices, list)

    @unittest.expectedFailure
    def test_find_muonlab_in_devices_list(self):
        self.assertIn(MUONLAB_ID, self.devices)


@unittest.skipIf(not hardware_is_present(),
                 "Hardware is not detected, skipping tests.")
class OpenDeviceTest(unittest.TestCase):
    def test_open_device(self):