Example #1
0
def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):
    """Return a list of all FT232H device serial numbers connected to the
    machine.  You can use these serial numbers to open a specific FT232H device
    by passing it to the FT232H initializer's serial parameter.
    """
    try:
        # Create a libftdi context.
        ctx = None
        ctx = ftdi.new()
        # Enumerate FTDI devices.
        device_list = None
        count, device_list = ftdi.usb_find_all(ctx, vid, pid)
        if count < 0:
            raise RuntimeError(
                'ftdi_usb_find_all returned error {0}: {1}'.format(
                    count, ftdi.get_error_string(self._ctx)))
        # Walk through list of devices and assemble list of serial numbers.
        devices = []
        while device_list is not None:
            # Get USB device strings and add serial to list of devices.
            ret, manufacturer, description, serial = ftdi.usb_get_strings(
                ctx, device_list.dev, 256, 256, 256)
            if ret < 0:
                raise RuntimeError(
                    'ftdi_usb_get_strings returned error {0}: {1}'.format(
                        ret, ftdi.get_error_string(self._ctx)))
            devices.append(serial)
            device_list = device_list.next
        return devices
    finally:
        # Make sure to clean up list and context when done.
        if device_list is not None:
            ftdi.list_free(device_list)
        if ctx is not None:
            ftdi.free(ctx)
def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):
    """Return a list of all FT232H device serial numbers connected to the
    machine.  You can use these serial numbers to open a specific FT232H device
    by passing it to the FT232H initializer's serial parameter.
    """
    try:
        # Create a libftdi context.
        ctx = None
        ctx = ftdi.new()
        # Enumerate FTDI devices.
        device_list = None
        count, device_list = ftdi.usb_find_all(ctx, vid, pid)
        if count < 0:
            raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(
                count, ftdi.get_error_string(self._ctx)))
        # Walk through list of devices and assemble list of serial numbers.
        devices = []
        while device_list is not None:
            # Get USB device strings and add serial to list of devices.
            ret, manufacturer, description, serial = ftdi.usb_get_strings(
                ctx, device_list.dev, 256, 256, 256)
            if ret < 0:
                raise RuntimeError('ftdi_usb_get_strings returned error {0}: {1}'.format(
                    ret, ftdi.get_error_string(self._ctx)))
            devices.append(serial)
            device_list = device_list.next
        return devices
    finally:
        # Make sure to clean up list and context when done.
        if device_list is not None:
            ftdi.list_free(device_list)
        if ctx is not None:
            ftdi.free(ctx)
Example #3
0
def write(ftdic, data):
    tc = ftdi1.write_data_submit(ftdic, str(bytearray(data)), len(data))
    if not tc:
        raise Exception('FTDI write error')
    ret = ftdi1.transfer_data_done(tc)
    if ret < 0:
        raise Exception(ftdi1.get_error_string(ftdic))
Example #4
0
    def _write(self, string):
        """Helper function to call write_data on the provided FTDI device and
        verify it succeeds.
        """
        # Get modem status. Useful to enable for debugging.
        #ret, status = ftdi.poll_modem_status(self._ctx)
        #if ret == 0:
        #	logger.debug('Modem status {0:02X}'.format(status))
        #else:
        #	logger.debug('Modem status error {0}'.format(ret))
        length = len(string)

        try:
            ret = ftdi.write_data(self._ctx, string)
            #compatible with libFtdi 1.3
        except TypeError:
            global FT232HPrintedOnce
            if (FT232HPrintedOnce == 0):
                print 'WARNING: Using ftdi.write_data function compatible with libFtdi 1.2'
                FT232HPrintedOnce = 1
            ret = ftdi.write_data(self._ctx, string,
                                  length)  #compatible with libFtdi 1.2
        # Log the string that was written in a python hex string format using a very
        # ugly one-liner list comprehension for brevity.
        #logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
        if ret < 0:
            raise RuntimeError(
                'ftdi_write_data failed with error {0}: {1}'.format(
                    ret, ftdi.get_error_string(self._ctx)))
        if ret != length:
            raise RuntimeError(
                'ftdi_write_data expected to write {0} bytes but actually wrote {1}!'
                .format(length, ret))
Example #5
0
def _ftdi1_check(context, function, *args):
    if function == ftdi1.write_data:
        writeData, writeCount = args
    result = function(context, *args)
    if result < 0:
        error_string = ftdi1.get_error_string(context)
        raise EnvironmentError(error_string)
    return result
Example #6
0
def _ftdi1_check(context, function, *args):
	if function == ftdi1.write_data:
		writeData, writeCount = args
	result = function(context, *args)
	if result < 0:
		error_string = ftdi1.get_error_string(context)
		raise EnvironmentError(error_string)
	return result
 def _check(self, command, *args):
     """Helper function to call the provided command on the FTDI device and
     verify the response matches the expected value.
     """
     ret = command(self._ctx, *args)
     logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))
     if ret != 0:
         raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(
             command.__name__, ret, ftdi.get_error_string(self._ctx)))
Example #8
0
def read(ftdic, length):
    data = '\0' * length
    tc = ftdi1.read_data_submit(ftdic, data, length)
    if not tc:
        raise Exception('FTDI read error')
    ret = ftdi1.transfer_data_done(tc)
    if ret < 0:
        raise Exception(ftdi1.get_error_string(ftdic))
    return list(bytearray(data))
Example #9
0
def ftwrite(string):
    length = len(string)
    ret = ftdi.write_data(ctx, string, length)
    if ret < 0:
        raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(
            ret, ftdi.get_error_string(self._ctx)))
    if ret != length:
        raise RuntimeError(
            'ftdi_write_data expected to write {0} bytes but actually wrote {1}!'
            .format(length, ret))
Example #10
0
 def _check(self, command, *args):
     """Helper function to call the provided command on the FTDI device and
     verify the response matches the expected value.
     """
     ret = command(self._ctx, *args)
     logger.debug('Called ftdi_{0} and got response {1}.'.format(
         command.__name__, ret))
     if ret != 0:
         raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(
             command.__name__, ret, ftdi.get_error_string(self._ctx)))
Example #11
0
	def __del__(self):


		# close usb
		ret = ftdi1.usb_close(self.ftdic)
		if ret < 0:
			print('unable to close ftdi device: %d (%s)' % (ret, ftdi1.get_error_string(self.ftdic)))
		    

		print ('device closed')
		ftdi1.free(self.ftdic)
Example #12
0
 def _check(self, command, *args):
     """
     Helper function to call the provided command on the FTDI device and
     verify the response matches the expected value.
     """
     ret = command(self._bus, *args)
     self._log.debug('Called {0} with result code {1}.'.format(
         command.__name__, ret))
     if ret != 0:
         raise RuntimeError('Calling {0} failed with error {1}: {2}'.format(
             command.__name__, ret, ftdi.get_error_string(self._bus)))
Example #13
0
    def id(self):  # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
        """Return a unique id for the detected chip, if any."""
        # There are some times we want to trick the platform detection
        # say if a raspberry pi doesn't have the right ID, or for testing
        try:
            return os.environ['BLINKA_FORCECHIP']
        except KeyError:  # no forced chip, continue with testing!
            pass

        # Special case, if we have an environment var set, we could use FT232H
        try:
            if os.environ['BLINKA_FT232H']:
                # we can't have ftdi1 as a dependency cause its wierd
                # to install, sigh.
                import ftdi1 as ftdi  # pylint: disable=import-error
                try:
                    ctx = None
                    ctx = ftdi.new()  # Create a libftdi context.
                    # Enumerate FTDI devices.
                    count, _ = ftdi.usb_find_all(ctx, 0, 0)
                    if count < 0:
                        raise RuntimeError(
                            'ftdi_usb_find_all returned error %d : %s' % count,
                            ftdi.get_error_string(self._ctx))
                    if count == 0:
                        raise RuntimeError('BLINKA_FT232H environment variable' + \
                                           'set, but no FT232H device found')
                finally:
                    # Make sure to clean up list and context when done.
                    if ctx is not None:
                        ftdi.free(ctx)
            return FT232H
        except KeyError:  # no FT232H environment var
            pass

        platform = sys.platform
        if platform == "linux" or platform == "linux2":
            return self._linux_id()
        if platform == "esp8266":
            return ESP8266
        if platform == "samd21":
            return SAMD21
        if platform == "pyboard":
            return STM32
        # nothing found!
        return None
Example #14
0
	def _write(self, string):
		"""Helper function to call write_data on the provided FTDI device and
		verify it succeeds.
		"""
		# Get modem status. Useful to enable for debugging.
		#ret, status = ftdi.poll_modem_status(self._ctx)
		#if ret == 0:
		#	logger.debug('Modem status {0:02X}'.format(status))
		#else:
		#	logger.debug('Modem status error {0}'.format(ret))
		length = len(string)
		ret = ftdi.write_data(self._ctx, string, length)
		# Log the string that was written in a python hex string format using a very
		# ugly one-liner list comprehension for brevity.
		#logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
		if ret < 0:
			raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))
		if ret != length:
			raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))
Example #15
0
 def call(self, function, *fargs):
     """Call a libftdi function and log its output."""
     values = None
     log.debug("calling ftdi_%s with args: (context, %s)",
               function.__name__, list(fargs))
     ret = function(self.context, *fargs)
     log.debug("got return value(s): %s", ret)
     if isinstance(ret, (list, tuple)) and len(ret) > 1:
         values = ret[1:]
         if isinstance(values, (list, tuple)) and len(values) == 1:
             values = values[0]
         ret = ret[0]
     else:
         # just return the return code
         values = ret
     if ret < 0:
         raise FtdiException("{} failed: {:d} ({})".format(
             function.__name__, ret, ftdi.get_error_string(self.context)))
     else:
         log.debug("returning: %s", values)
         return values
Example #16
0
 def _write(self, string):
     """
     Helper function to call write_data on the provided FTDI device and
     verify it succeeds.
     """
     # Get modem status. Useful to enable for debugging.
     # ret, status = ftdi.poll_modem_status(self._bus)
     # if ret == 0:
     #   logger.debug('Modem status {0:02X}'.format(status))
     # else:
     #   logger.debug('Modem status error {0}'.format(ret))
     length = len(string)
     ret = ftdi.write_data(self._bus, string, length)
     # Log the string that was written in a python hex string format using
     # a very ugly one-liner list comprehension for brevity.
     # logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
     if ret < 0:
         raise RuntimeError(
             'ftdi_write_data failed with error {0}: {1}'.format(
                 ret, ftdi.get_error_string(self._bus)))
     if ret != length:
         raise RuntimeError(
             'ftdi_write_data expected to write {0} bytes but actually wrote {1}!'
             .format(length, ret))
Example #17
0
  if value == ftdi.CBUSH_VBUS_SENSE:
    return 'VBUS_SENSE'
  return 'UNKNOWN'

# Surround the program with a try ... except clause.
try:

  # Allocate and inialize an ftdi context.
  ftdic = ftdi.new()
  if ftdic == 0:
    raise ErrorMsg('ftdi.new() failed')

  # List all the FT230X devices.
  nDevices, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6015)
  if nDevices < 0:
    raise ErrorMsg('ftdi.usb_find_all error = %s' % ftdi.get_error_string(ftdic));
  elif nDevices == 0:
    raise ErrorMsg('No FT230X devices found');
  elif nDevices != 1:
    raise ErrorMsg('More than one FT230X device found');

  # Display the identified single FT230X device.
  ret, manufacturer, description, serial = ftdi.usb_get_strings(ftdic, devlist.dev)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_get_strings error = %s' % ftdi.get_error_string(ftdic))
  print 'manufacturer="%s" description="%s" serial="%s"' % (manufacturer, description, serial)

  # Open the identified single FT230X device.
  ret = ftdi.usb_open_desc(ftdic, 0x0403, 0x6015, description, serial);
  if ret < 0:
    raise ErrorMsg('ftdi.usb_open_desc error = %s' % ftdi.get_error_string(ftdic))
Example #18
0
    return 'UNKNOWN'


# Surround the program with a try ... except clause.
try:

    # Allocate and inialize an ftdi context.
    ftdic = ftdi.new()
    if ftdic == 0:
        raise ErrorMsg('ftdi.new() failed')

    # List all the FT230X devices.
    nDevices, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6015)
    if nDevices < 0:
        raise ErrorMsg('ftdi.usb_find_all error = %s' %
                       ftdi.get_error_string(ftdic))
    elif nDevices == 0:
        raise ErrorMsg('No FT230X devices found')
    elif nDevices != 1:
        raise ErrorMsg('More than one FT230X device found')

    # Display the identified single FT230X device.
    ret, manufacturer, description, serial = ftdi.usb_get_strings(
        ftdic, devlist.dev)
    if ret < 0:
        raise ErrorMsg('ftdi.usb_get_strings error = %s' %
                       ftdi.get_error_string(ftdic))
    print 'manufacturer="%s" description="%s" serial="%s"' % (
        manufacturer, description, serial)

    # Open the identified single FT230X device.
UM232H_B_VID = 0x0403
UM232H_B_PID = 0x6014

# initialize
ftdic = ftdi.new()
if ftdic == 0:
    print( 'new failed: %d', ret )
    os._exit( 1 )

# try to list ftdi devices 0x6010 or 0x6001
ret, devlist = ftdi.usb_find_all( ftdic, UM232H_B_VID, UM232H_B_PID )
if ret <= 0:
    ret, devlist = ftdi.usb_find_all( ftdic, 0x0403, 0x6001)

if ret < 0:
    print( 'ftdi_usb_find_all failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
    os._exit( 1 )
print( 'Number of FTDI devices found: %d\n' % ret )
curnode = devlist
i = 0
while( curnode != None ):
    ret, manufacturer, description, serial = ftdi.usb_get_strings( ftdic, curnode.dev )
    if ret < 0:
        print( 'ftdi_usb_get_strings failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
        os._exit( 1 )
    print( 'Device #%d: manufacturer="%s" description="%s" serial="%s"\n' % ( i, manufacturer, description, serial ) )
    curnode = curnode.next
    i += 1

# open usb
ret = ftdi.usb_open( ftdic, UM232H_B_VID, UM232H_B_PID  )
Example #20
0
print ('version: %s\n' % ftdi.__version__)

# initialize
ftdic = ftdi.new()
if ftdic == 0:
    print('new failed: %d' % ret)
    os._exit(1)

# try to list ftdi devices 0x6010 or 0x6001
ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6010)
if ret <= 0:
    ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6001)

if ret < 0:
    print('ftdi_usb_find_all failed: %d (%s)' %
          (ret, ftdi.get_error_string(ftdic)))
    os._exit(1)
print('devices: %d' % ret)
curnode = devlist
i = 0
while(curnode != None):
    ret, manufacturer, description, serial = ftdi.usb_get_strings(
        ftdic, curnode.dev)
    if ret < 0:
        print('ftdi_usb_get_strings failed: %d (%s)' %
              (ret, ftdi.get_error_string(ftdic)))
        os._exit(1)
    print('#%d: manufacturer="%s" description="%s" serial="%s"\n' %
          (i, manufacturer, description, serial))
    curnode = curnode.next
    i += 1
Example #21
0
  if value == ftdi.CBUSX_VBUS_SENSE:
    return 'VBUS_SENSE'
  return 'UNKNOWN'

# Surround the program with a try ... except clause.
try:

  # Allocate and inialize an ftdi context.
  ftdic = ftdi.new()
  if ftdic == 0:
    raise ErrorMsg('ftdi.new() failed')

  # List all the FT230X devices.
  nDevices, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6015)
  if nDevices < 0:
    raise ErrorMsg('ftdi.usb_find_all error = %s' % ftdi.get_error_string(ftdic))
  elif nDevices == 0:
    raise ErrorMsg('No FT230X devices found')
  elif nDevices != 1:
    raise ErrorMsg('More than one FT230X device found')

  # Display the identified single FT230X device.
  ret, manufacturer, description, serial = ftdi.usb_get_strings(ftdic, devlist.dev)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_get_strings error = %s' % ftdi.get_error_string(ftdic))
  print 'manufacturer="%s" description="%s" serial="%s"' % (manufacturer, description, serial)

  # Open the identified single FT230X device.
  ret = ftdi.usb_open_desc(ftdic, 0x0403, 0x6015, description, serial)
  if ret < 0:
    raise ErrorMsg('ftdi.usb_open_desc error = %s' % ftdi.get_error_string(ftdic))
UM232H_B_PID = 0x6014

# initialize
ftdic = ftdi.new()
if ftdic == 0:
    print('new failed: %d', ret)
    os._exit(1)

# try to list ftdi devices 0x6010 or 0x6001
ret, devlist = ftdi.usb_find_all(ftdic, UM232H_B_VID, UM232H_B_PID)
if ret <= 0:
    ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6001)

if ret < 0:
    print('ftdi_usb_find_all failed: %d (%s)' %
          (ret, ftdi.get_error_string(ftdic)))
    os._exit(1)
print('Number of FTDI devices found: %d\n' % ret)
curnode = devlist
i = 0
while (curnode != None):
    ret, manufacturer, description, serial = ftdi.usb_get_strings(
        ftdic, curnode.dev)
    if ret < 0:
        print('ftdi_usb_get_strings failed: %d (%s)' %
              (ret, ftdi.get_error_string(ftdic)))
        os._exit(1)
    print('Device #%d: manufacturer="%s" description="%s" serial="%s"\n' %
          (i, manufacturer, description, serial))
    curnode = curnode.next
    i += 1
Example #23
0
 def __init__(self, vid=FT232H_VID, pid=FT232H_PID, serial=None):
     """Create a FT232H object.  Will search for the first available FT232H
     device with the specified USB vendor ID and product ID (defaults to
     FT232H default VID & PID).  Can also specify an optional serial number
     string to open an explicit FT232H device given its serial number.  See
     the FT232H.enumerate_device_serials() function to see how to list all
     connected device serial numbers.
     """
     # Initialize FTDI device connection.
     self._ctx = ftdi.new()
     if self._ctx == 0:
         raise RuntimeError('ftdi_new failed! Is libftdi1 installed?')
     # Register handler to close and cleanup FTDI context on program exit.
     atexit.register(self.close)
     if serial is None:
         # Open USB connection for specified VID and PID if no serial is specified.
         self._check(ftdi.usb_open, vid, pid)
     else:
         # Open USB connection for VID, PID, serial.
         ##self._check(ftdi.usb_open_string, 's:{0}:{1}:{2}'.format(vid, pid, serial))
         
         finaldev = None
         device_list = None
         count, device_list = ftdi.usb_find_all(self._ctx, vid, pid)
         if count < 0:
             raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))
         # Walk through list of devices and assemble list of serial numbers.
         devices = []
         while device_list is not None:
             # Get USB device strings and add serial to list of devices.
             ret, manufacturer, description, serialtest = ftdi.usb_get_strings(self._ctx, device_list.dev, 256, 256, 256)
             if serialtest == serial:
                 finaldev = device_list.dev
             device_list = device_list.next
         if finaldev is None:
             raise RuntimeError('Could not find correct device')
         self._check(ftdi.usb_open_dev, finaldev)
             #
             
     # Reset device.
     self._check(ftdi.usb_reset)
     # Disable flow control. Commented out because it is unclear if this is necessary.
     #self._check(ftdi.setflowctrl, ftdi.SIO_DISABLE_FLOW_CTRL)
     # Change read & write buffers to maximum size, 65535 bytes.
     self._check(ftdi.read_data_set_chunksize, 65535)
     self._check(ftdi.write_data_set_chunksize, 65535)
     # Clear pending read data & write buffers.
     self._check(ftdi.usb_purge_buffers)
     # Enable MPSSE and syncronize communication with device.
     self._mpsse_enable()
     self._mpsse_sync()
     # Initialize all GPIO as inputs.
     self._write('\x80\x00\x00\x82\x00\x00')
     self._direction = 0x0000
     self._level = 0x0000
Example #24
0
BAUD = 400000         # 400kHz, 2xNyquist for 100kHz I2C

FT232H_VID = 0x0403   # Default FTDI FT232H vendor ID
FT232H_PID = 0x6014   # Default FTDI FT232H product ID


# Initialize new context
ftdictx = ftdi.new()
if ftdictx == 0:
    print( 'failed to create new context: %d', ret )
    os._exit( 1 )

# Try to list FT232H devices
ret, devlist = ftdi.usb_find_all( ftdictx, FT232H_VID, FT232H_PID )
if ret < 0:
    print( 'ftdi_usb_find_all failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdictx ) ) )
    os._exit( 1 )

print( 'Number of FTDI devices found: %d\n' % ret )
curnode = devlist
#i = 0
#while( curnode != None ):
#    ret, manufacturer, description, serial = ftdi.usb_get_strings( ftdictx, curnode.dev )
#    if ret < 0:
#        print( 'ftdi_usb_get_strings failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdictx ) ) )
#        os._exit( 1 )
#    print( 'Device #%d: manufacturer="%s" description="%s" serial="%s"\n' % ( i, manufacturer, description, serial ) )
#    curnode = curnode.next
#    i += 1

# Open USB to the first FT232H