Beispiel #1
0
 def __init__(self, vid=FT232H_VID, pid=FT232H_PID):
     """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).
     """
     # 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)
     # Open USB connection for specified VID and PID.
     self._check(ftdi.usb_open, vid, pid)
     # 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
	def __init__(self, vid=FT232H_VID, pid=FT232H_PID):
		"""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).
		"""
		# 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)
		# Open USB connection for specified VID and PID.
		self._check(ftdi.usb_open, vid, pid)
		# 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
Beispiel #3
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 serial is not None:
                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)
Beispiel #4
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 serial is not None:
                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)
Beispiel #5
0
	def __init__(self):
		self.ftdic = ftdi1.new()
		print "usb_open ret = ", ftdi1.usb_open(self.ftdic, 0x0403, 0x8c81)
		print "set_bitmode ret = ", ftdi1.set_bitmode(self.ftdic, 0x00, ftdi1.BITMODE_RESET)		# Reset port to normal operation
		print "set_baudrate ret = ", ftdi1.set_baudrate(self.ftdic, 115200)		# 115200 baud
		print "setflowctrl ret = ", ftdi1.setflowctrl(self.ftdic, ftdi1.SIO_DISABLE_FLOW_CTRL)
		print "setdtr ret = ", ftdi1.setdtr(self.ftdic, 1)
		print "setrts ret = ", ftdi1.setrts(self.ftdic, 1)
 def open_comms(self):
     self.ftdic = ftdi.new()
     ret = ftdi.usb_open(self.ftdic, self.idVendor, self.idProduct)
     print ret
     ret = ftdi.usb_purge_buffers(self.ftdic)
     print ret
     ret = ftdi.set_bitmode(self.ftdic, 0xFF, ftdi.BITMODE_BITBANG)
     print ret
Beispiel #7
0
def openDevice(vendor, product, lowByteValue, lowByteDirection):
    context = ftdi1.new()
    assert context
    try:
        _ftdi1_check(context, ftdi1.usb_open, vendor, product)
        return Mpsse(context, lowByteValue, lowByteDirection)
    except:
        ftdi1.free(context)
        raise
Beispiel #8
0
def openDevice(vendor, product, lowByteValue, lowByteDirection):
	context = ftdi1.new()
	assert context
	try:
		_ftdi1_check(context, ftdi1.usb_open, vendor, product)
		return Mpsse(context, lowByteValue, lowByteDirection)
	except:
		ftdi1.free(context)
		raise
Beispiel #9
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
Beispiel #10
0
 def __init__(self, VID=0x0403, PID=0x6010, _debug_out=None):
     """Open USB connection and initialize FTDI context."""
     context = ftdi.new()
     if not (ftdi.usb_open(context, VID, PID) == 0):
         ftdi.free(context)
         self.ftdic = None
         raise IOError('could not open USB connection!')
     ftdi.set_bitmode(context, 0, ftdi.BITMODE_SYNCFF)
     self.ftdic = context
     self._debug_ftdi = False
     self._debug_out = _debug_out
     self._debug_lock = threading.Lock()
Beispiel #11
0
    def __init__(self,
                 vid=FT4232H_VID,
                 pid=FT4232H_PID,
                 serial=None,
                 iface=ftdi.INTERFACE_B,
                 useMPSSE=True):
        """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)

        ftdi.set_interface(self._ctx, iface)

        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))
        # 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.

        ftdi.set_interface(self._ctx, iface)

        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
Beispiel #12
0
def main():
    """Main program"""
    restart = True
    ftdic = ftdi.new()
    serial = None

    if len(sys.argv) > 1:                                                                                                                   
        serial = sys.argv[1]

    ret = ftdi.usb_open_desc(ftdic, 0x0403, 0x6001, None, serial)
    if ret < 0:
        print("ftdi.usb_open(): %d" % ret, file=sys.stderr)
        sys.exit(1)

    ret = ftdi.read_eeprom(ftdic)
    if ret < 0:
        print("ftdi.read_eeprom(): %d" % ret, file=sys.stderr)
        sys.exit(1)

    ret = ftdi.eeprom_decode(ftdic, True)
    if ret < 0:
        print("ftdi.eeprom_decode(): %d" % ret, file=sys.stderr)
        sys.exit(1)
    print()

    set_eeprom_value(ftdic, ftdi.CBUS_FUNCTION_0, ftdi.CBUS_TXLED)
    set_eeprom_value(ftdic, ftdi.CBUS_FUNCTION_1, ftdi.CBUS_RXLED)
    set_eeprom_value(ftdic, ftdi.CBUS_FUNCTION_2, ftdi.CBUS_IOMODE)
    set_eeprom_value(ftdic, ftdi.CBUS_FUNCTION_3, ftdi.CBUS_IOMODE)

    ret = ftdi.eeprom_build(ftdic);
    if ret < 0:
        print("ftdi.eeprom_build(): %d" % ret, file=sys.stderr)
        sys.exit(1)

    print("New EEPROM settings:")
    ret = ftdi.eeprom_decode(ftdic, True)
    if ret < 0:
        print("ftdi.eeprom_decode(): %d" % ret, file=sys.stderr)
        sys.exit(1)

    ret = ftdi.write_eeprom(ftdic);
    if ret < 0:
        print("ftdi.write_eeprom(): %d" % ret, file=sys.stderr)
        sys.exit(1)

    ftdi.free(ftdic)
Beispiel #13
0
    def __init__(self, pin, debug=DEBUG, overdrive=OVERDRIVE, pullup=None):
        self._rmmod()
        self._dbg = debug
        self._ctx = ftdi.new()
        self._level = 0x0000
        self._direction = 0x0000
        self._buffer = False
        self._output = None
        self._debug(1, "1Wire: Init")
        self._max_buffer = 0
        self._overdrive = overdrive
        self._od = False
        self._rc = False
        self._gpiol1 = 5

        # Set the pin to use
        self.pin = pin
        self.pullup = pullup

        # Set up delay timers (clock frequencies)
        self._reset_clocks(False)

        # Two ways to delay. dump a byte to tms, or pulse the clock for n
        # bits. A 1 bit pulse seems to take the same as time as a 8bit
        # dump to TMS? Default is to pulse the clock.
        self.tms_dump = '\x4a\x01\xff'  # Dump 8 bits to TMS
        self.pb = '\x8e\x01'  # Pulse clock (1 bits)
        self.delay = self.pb

        # MPSSE Command to read GPIO
        self.read_gpio = '\x81\x83'

        # If we have a pullup pin, set it to low by default, this pin controls
        # switching on a strong_pullup if the device needs extra power. It is
        # activated when pullup_and_check() is called.
        # set_pin() always sets our GPIO flags for our GPIO pin too, so that gets
        # done here regardless of having an addition pullup control pin.
        if self.pullup is not None:
            self.set_pin(self.pullup, False, False)
        else:
            self.set_pin(self.pin, False, True)
        self.write_gpio_state()

        # Create the context for FTDI
        if self._ctx == 0:
            raise Exception("Failed to open FTDI")
        atexit.register(self.close)
Beispiel #14
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
Beispiel #15
0
def switch(mode):
    global c
    c = ftdi.new()
    # TODO(benjaminfair): error checking
    ftdi.usb_open_desc(c, 0x0403, 0x6001, None, os.environ.get("FTDI_SERIAL"))
    ftdi.set_bitmode(c, 0xFF, ftdi.BITMODE_BITBANG)
    atexit.register(ftdi.free, c)

    disable()

    if mode == 'run':
        set(SWITCH)
    elif mode == 'debug':
        clear(SWITCH)
    elif mode == 'disable':
        return

    enable()
def main():
    """Main program"""
    context = ftdi.new()

    version_info = ftdi.get_library_version()
    print("[FTDI version] major: %d, minor: %d, micro: %d" \
               ", version_str: %s, snapshot_str: %s" %
               (version_info.major, version_info.minor, version_info.micro,
               version_info.version_str, version_info.snapshot_str))

    # try to open an ftdi 0x6010 or 0x6001
    ret = ftdi.usb_open(context, UM232H_B_VID, UM232H_B_PID)
    if ret < 0:
        ret = ftdi.usb_open(context, UM232H_B_VID, UM232H_B_PID)
        
    print("ftdi.usb_open(): %d" % ret)
    print("ftdi.set_baudrate(): %d" % ftdi.set_baudrate(context, 9600))

    ftdi.free(context)
Beispiel #17
0
def main():
    """Main program"""
    context = ftdi.new()

    version_info = ftdi.get_library_version()
    print("[FTDI version] major: %d, minor: %d, micro: %d" \
               ", version_str: %s, snapshot_str: %s" %
               (version_info.major, version_info.minor, version_info.micro,
               version_info.version_str, version_info.snapshot_str))

    # try to open an ftdi 0x6010 or 0x6001
    ret = ftdi.usb_open(context, 0x0403, 0x6010)
    if ret < 0:
        ret = ftdi.usb_open(context, 0x0403, 0x6001)

    print("ftdi.usb_open(): %d" % ret)
    print("ftdi.set_baudrate(): %d" % ftdi.set_baudrate(context, 9600))

    ftdi.free(context)
Beispiel #18
0
 def __init__(self, *args, **kwargs):
     """
     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.
     """
     self._serial = kwargs.get('serial', None)
     # Initialize FTDI device connection.
     self._bus = ftdi.new()
     if self._bus == 0:
         raise RuntimeError('ftdi_new failed! Is libftdi1 installed?')
     # Register handler to close and cleanup FTDI context on program exit.
     atexit.register(self.close)
     super(Ft232hGpioInterface, self).__init__(*args, **kwargs)
     if self._serial is None:
         # Open USB connection for specified VID and PID if no serial is
         # specified.
         self._check(ftdi.usb_open, self.FT232H_VID, self.FT232H_PID)
     else:
         # Open USB connection for VID, PID, serial.
         self._check(
             ftdi.usb_open_string,
             's:{0}:{1}:{2}'.format(self.FT232H_VID, self.FT232H_PID,
                                    self._serial))
     # Reset device.
     self._check(ftdi.usb_reset)
     # Disable flow control. 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
     self._log.info("Started interface {0}.".format(self))
Beispiel #19
0
def bruteforce_connection_props():
    for bits in [ftdi.BITS_8]:  #[ftdi.BITS_7, ftdi.BITS_8]:
        for sbit in [ftdi.STOP_BIT_1, ftdi.STOP_BIT_15, ftdi.STOP_BIT_2]:
            for parity in [
                    ftdi.NONE, ftdi.ODD, ftdi.EVEN, ftdi.MARK, ftdi.SPACE
            ]:
                for break_ in [ftdi.BREAK_ON]:  #, ftdi.BREAK_OFF]:
                    print(bits, sbit, parity, break_)
                    ctx = ftdi.new()
                    ret = ftdi.usb_open(ctx, 0x0760, 0x0002)
                    assert ret == 0
                    ret = ftdi.set_baudrate(ctx, 38400)
                    assert ret == 0, 'baudrate error'

                    ftdi.set_line_property2(ctx, bits, sbit, parity, break_)

                    send_msg_led(ctx, 2, 0x49, True)

                    input('waiting')

                    ftdi.free(ctx)
Beispiel #20
0
	def __init__(self, num_pixels, num_rows):
		# Create a libftdi context.
		ctx = None
		ctx = ftdi.new()
		# Define USB vendor and product ID
		vid = 0x0403
		pid = 0x6014
		# Enumerate FTDI devices.
		self.serial = None
		device_list = None
		count, device_list = ftdi.usb_find_all(ctx, vid, pid)
		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)
			print 'return: {0}, manufacturer: {1}, description: {2}, serial: |{3}|'.format(ret,manufacturer,description,serial)
			if 'FTDI' in manufacturer and 'Serial' in description and 'FT' in serial:
				self.serial = serial
			device_list = device_list.next
		# 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)	
		
		# Create an FT232H object.
		self.ft232h = FT232H.FT232H(serial=self.serial)
		# Create an FT232H object.
		self.ft232h = FT232H.FT232H()
		# Create a SPI interface for the FT232H object.  Set the SPI bus to 6mhz.
		self.spi    = FT232H.SPI(self.ft232h, max_speed_hz=SPI_BAUD)
		# Create a pixel data buffer and lookup table.
		self.buffer = bytearray(num_pixels*BYTES_PER_PIXEL*3)
		self.lookup = self.build_byte_lookup()
		#print self.lookup
		self.set_brightness(MAX_INTENSITY/2) #set brightness to 25% by default
		self.num_pixels	= num_pixels
		self.rows 		= num_rows
		self.cols 		= num_pixels/num_rows
Beispiel #21
0
def main():
    ctx = ftdi.new()

    ret = ftdi.usb_open(ctx, 0x0760, 0x0002)
    assert ret == 0, 'ftdi.usb_open error: {}'.format(ret)

    ret = ftdi.set_baudrate(ctx, 38400)
    assert ret == 0, 'baudrate error'

    try:
        code.interact(local={
            'ctx': ctx,
            'ftdi': ftdi,
            'read_continuously': read_continuously,
            'parse_continuously': parse_continuously,
            'send_msg_slider': send_msg_slider,
            'send_msg_led': send_msg_led,
            'bruteforce_properties': bruteforce_properties,
        },
                      banner='ftdi & ctx imported',
                      exitmsg='cleaning up!')
    finally:
        ftdi.free(ctx)
        print('done')
Beispiel #22
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))
     # 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
Complete program to demonstrate the usage
of the swig generated python wrapper

You need to build and install the wrapper first"""

import os
import sys
import ftdi1 as ftdi
import time

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
Beispiel #24
0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Tinkering that I did on Fedora 23 using this library:

http://www.intra2net.com/en/developer/libftdi/download/libftdi1-1.2.tar.bz2
'''

import sys
import time
import ftdi1 as ftdi

# My DS_UM232H:
usb_vendor = 0x0403
usb_model = 0x6014

context = ftdi.new()

dev = ftdi.usb_open(context, usb_vendor, usb_model)

if dev < 0:
    print 'Failed to open.  :-('

while True:
    aa, bb = ftdi.read_data(context, 1000)
    if aa != 0:
        # print bb[:aa],
        sys.stdout.write(bb[:aa])
    else:
        time.sleep(0.01)
Beispiel #25
0
import os
import sys

# Import ftdi1 module
import ftdi1 as ftdi

#BAUD, = sys.argv		# command line inputs

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 )
Beispiel #26
0
Complete program to demonstrate the usage
of the swig generated python wrapper

You need to build and install the wrapper first"""

import os
import sys
import ftdi1 as ftdi
import time

# version
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
Beispiel #27
0
#!/usr/bin/python3

import ftdi1
f = ftdi1.new()
ftdi1.usb_open(f, 0x0403, 0x6001)
ftdi1.set_bitmode(f, 1, 0)
ftdi1.write_data(f, bytes([0]))
ftdi1.write_data(f, bytes([1]))
ftdi1.usb_close(f)
Beispiel #28
0
def red(context):
    actuate(context, RED_ON)
    actuate(context, GREEN_OFF)


def green(context):
    # turn on Green light
    actuate(context, GREEN_ON)
    actuate(context, RED_OFF)


def off(context):
    actuate(context, RED_OFF)
    actuate(context, GREEN_OFF)


context = ftd.new()
ftd.usb_open(context, 0x0403, 0x6001)
ftd.set_bitmode(context, 0xff, ftd.BITMODE_BITBANG)
# Everything off --- shouldn't be necessary.
ftd.write_data(context, bytes([0x00]))

if len(sys.argv) == 1:
    off(context)
elif sys.argv[1] == 'red':
    red(context)
elif sys.argv[1] == 'green':
    green(context)
else:
    print("Usage: lavalamps [red|green]")
Beispiel #29
0
BLUE2 = ANSI('\033[1;34m')
BG_BLUE = ANSI('\033[0;44m')
MAGENTA = ANSI('\033[0;35m')
MAGENTA2 = ANSI('\033[1;35m')
CYAN = ANSI('\033[0;36m')
CYAN2 = ANSI('\033[1;36m')
WHITE = ANSI('\033[0;37m')
WHITE2 = ANSI('\033[1;37m')


def BIT(x):
    return 1 << x


# Initialize FTDI device connection.
ctx = ftdi.new()
ftdi.usb_open(ctx, 0x263d, 0x4001)
ftdi.usb_reset(ctx)

# 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.
ftdi.read_data_set_chunksize(ctx, 65535)
ftdi.write_data_set_chunksize(ctx, 65535)

# Clear pending read data & write buffers.
ftdi.usb_purge_buffers(ctx)
# Reset MPSSE
ftdi.set_bitmode(ctx, 0, 0)
# Enable MPSSE
Beispiel #30
0
    if ret < 0:
        raise Exception(ftdi1.get_error_string(ftdic))


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))


ftdic = ftdi1.new()
ftdi1.usb_open_desc_index(ftdic, ftdi_vendor, ftdi_product, None, None, 0)
ftdi1.usb_reset(ftdic)
ftdi1.set_interface(ftdic, ftdi1.INTERFACE_A)
ftdi1.set_bitmode(ftdic, 0, ftdi1.BITMODE_MPSSE)

b = []

# Calculate required clock rate, we bitbang out a clock on the data bit,
# so we need to run at the clock_rate * 2
hz = clock_rate * 2
numerator = 30000000.0
if hz < 1000:
    b += cmd(ftdi1.EN_DIV_5)
    numerator /= 5.0
else:
Beispiel #31
0
 def __init__(self):
     self.context = ftdi.new()
     if self.context == 0:
         raise FtdiException("Could not open FTDI context.")
Beispiel #32
0
    #     # Multiple devices plugged in
    #     if(len(sys.argv) < 3):
    #         print("Multiple devices plugged in. Please specify an index")
    #         os._exit(1)
    #     device = devices[int(sys.argv[2])]
    # else:
    #     # Only one device plugged in
    #     device = devices[0]

    # print(device['path'])
    # ret = ftdi.usb_open(ftdic, 0x0403, 0x6001)
    print(devices)

    ftdics = []
    for device in devices:
        ret = ftdi.new()
        if ret == 0:
            print('new failed: %d' % ret)
            os._exit(1)
        ftdics.append(ret)

    for ftdic, device in zip(ftdics, devices):
        print(device['path'])
        ret = ftdi.usb_open_bus_addr(ftdic, int(device['bus']),
                                     int(device['device']))
        if ret < 0:
            print('unable to open ftdi device: %d (%s)' %
                  (ret, ftdi.get_error_string(ftdic)))
            os._exit(1)

    if (sys.argv[1] == "bootload"):