Beispiel #1
0
 def test_dual_if_reset(self):
     """Demonstrate how to connect to an hotplugged FTDI device, i.e.
        an FTDI device that is connected after the initial attempt to
        enumerate it on the USB bus."""
     url1 = environ.get('FTDI_DEVICE', 'ftdi:///1')
     ftdi1 = Ftdi()
     ftdi1.open_from_url(url1)
     count = ftdi1.device_port_count
     if count < 2:
         ftdi1.close()
         raise SkipTest('FTDI device is not a multi-port device')
     next_port = (int(url1[-1]) % count) + 1
     url2 = 'ftdi:///%d' % next_port
     ftdi2 = Ftdi()
     self.assertTrue(ftdi1.is_connected, 'Unable to connect to FTDI')
     ftdi2.open_from_url(url2)
     # use latenty setting to set/test configuration is preserved
     ftdi2.set_latency_timer(128)
     # should be the same value
     self.assertEqual(ftdi2.get_latency_timer(), 128)
     self.assertTrue(ftdi2.is_connected, 'Unable to connect to FTDI')
     ftdi1.close()
     self.assertFalse(ftdi1.is_connected, 'Unable to close connection')
     # closing first connection should not alter second interface
     self.assertEqual(ftdi2.get_latency_timer(), 128)
     ftdi1.open_from_url(url1)
     self.assertTrue(ftdi1.is_connected, 'Unable to connect to FTDI')
     # a FTDI reset should not alter settings...
     ftdi1.reset(False)
     self.assertEqual(ftdi2.get_latency_timer(), 128)
     # ... however performing a USB reset through any interface should alter
     # any previous settings made to all interfaces
     ftdi1.reset(True)
     self.assertNotEqual(ftdi2.get_latency_timer(), 128)
Beispiel #2
0
 def test_multiple_interface(self):
     # the following calls used to create issues (several interfaces from
     # the same device). The test expects an FTDI 2232H here
     ftdi1 = Ftdi()
     ftdi1.open(vendor=0x403, product=0x6010, interface=1)
     ftdi2 = Ftdi()
     ftdi2.open(vendor=0x403, product=0x6010, interface=2)
     for _ in range(5):
         print("If#1: ", hex(ftdi1.poll_modem_status()))
         print("If#2: ", ftdi2.modem_status())
         sleep(0.500)
     ftdi1.close()
     ftdi2.close()
Beispiel #3
0
 def test_multiple_interface(self):
     # the following calls used to create issues (several interfaces from
     # the same device)
     ftdi1 = Ftdi()
     ftdi1.open(interface=1)
     ftdi2 = Ftdi()
     ftdi2.open(interface=2)
     import time
     for x in range(5):
         print "If#1: ", hex(ftdi1.poll_modem_status())
         print "If#2: ", ftdi2.modem_status()
         time.sleep(0.500)
     ftdi1.close()
     ftdi2.close()
Beispiel #4
0
    def open(self, baud=None):
        if self.b_ftdi_obj:
            if baud is not None:
                self.ser.set_baudrate(baud)
            return self.isopen

        if self.ser is not None:
            if self.isopen: self.close()

        if self.ser is None:
            self.ser = Ftdi()

        self.isopen = False
        try:
            self.ser.open(vendor=self.VENDOR_ID,
                          product=self.pid,
                          interface=self.devno)
            self.isopen = True
        except:
            pass

        if baud is None:
            baud = self.self.BAUD_DEFAULT

        self.ser.set_baudrate(baud)

        return self.isopen
Beispiel #5
0
 def __init__(self):
     self._ftdi = Ftdi()
     self.log = getLogger('pyftdi.i2c')
     self._slaves = {}
     self._frequency = 0.0
     self._direction = I2cController.SCL_BIT | I2cController.SDA_O_BIT
     self._immediate = (Ftdi.SEND_IMMEDIATE, )
     self._idle = (Ftdi.SET_BITS_LOW, self.IDLE, self._direction)
     data_low = (Ftdi.SET_BITS_LOW, self.IDLE & ~self.SDA_O_BIT,
                 self._direction)
     clock_low_data_low = (Ftdi.SET_BITS_LOW,
                           self.IDLE & ~(self.SDA_O_BIT | self.SCL_BIT),
                           self._direction)
     self._clock_low_data_high = (Ftdi.SET_BITS_LOW,
                                  self.IDLE & ~self.SCL_BIT,
                                  self._direction)
     self._read_bit = (Ftdi.READ_BITS_PVE_MSB, 0)
     self._read_byte = (Ftdi.READ_BYTES_PVE_MSB, 0, 0)
     self._write_byte = (Ftdi.WRITE_BYTES_NVE_MSB, 0, 0)
     self._nack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.HIGH)
     self._ack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.LOW)
     self._start = data_low * 4 + clock_low_data_low * 4
     self._stop = clock_low_data_low * 4 + data_low * 4 + self._idle * 4
     self._tristate = None
     self._tx_size = 1
     self._rx_size = 1
Beispiel #6
0
    def __init__(self, ftdi_pid='232r', serial_num=None, laser_pin=PIN_CTS):
        """Inits LaserPointer object.

        Initializes a LaserPointer object by constructing an Ftdi object and opening the desired
        FTDI device. Configures the FTDI device to bitbang mode.

        Args:
            ftdi_pid: Product ID string for the FTDI device.
            serial_num: String containing the serial number of the FTDI device. If None, any
                serial number will be accepted.
            laser_pin: Integer bit mask with a single bit set corresponding to the pin on the FTDI
                device that controls the laser pointer.
        """
        self.laser_pin = laser_pin

        self.ftdi = Ftdi()

        self.ftdi.open_bitbang(
            vendor=Ftdi.VENDOR_IDS['ftdi'],
            product=Ftdi.PRODUCT_IDS[Ftdi.FTDI_VENDOR][ftdi_pid],
            serial=serial_num,        # serial number of FT232RQ in the laser FTDI cable
            latency=Ftdi.LATENCY_MAX, # 255ms; reduce if necessary (at cost of higher CPU usage)
        )

        # set laser_pin as output, all others as inputs
        self.ftdi.set_bitmode(self.laser_pin, Ftdi.BitMode.BITBANG)
        assert self.ftdi.bitbang_enabled

        # make sure laser is disabled by default
        self.set(False)
Beispiel #7
0
 def test_close_on_disconnect(self):
     """Validate close after disconnect."""
     log = logging.getLogger('pyftdi.tests.ftdi')
     url = environ.get('FTDI_DEVICE', 'ftdi:///1')
     ftdi = Ftdi()
     ftdi.open_from_url(url)
     self.assertTrue(ftdi.is_connected, 'Unable to connect to FTDI')
     print('Please disconnect FTDI device')
     while ftdi.is_connected:
         try:
             ftdi.poll_modem_status()
         except FtdiError:
             break
         sleep(0.1)
     ftdi.close()
     print('Please reconnect FTDI device')
     while True:
         UsbTools.flush_cache()
         try:
             ftdi.open_from_url(url)
         except (FtdiError, UsbToolsError):
             log.debug('FTDI device not detected')
             sleep(0.1)
         except ValueError:
             log.warning('FTDI device not initialized')
             ftdi.close()
             sleep(0.1)
         else:
             log.info('FTDI device detected')
             break
     ftdi.poll_modem_status()
     ftdi.close()
Beispiel #8
0
 def test_enumerate(self):
     """Check simple enumeration of two similar FTDI device."""
     ftdi = Ftdi()
     temp_stdout = StringIO()
     with redirect_stdout(temp_stdout):
         self.assertRaises(SystemExit, ftdi.open_from_url, 'ftdi:///?')
     lines = [l.strip() for l in temp_stdout.getvalue().split('\n')]
     lines.pop(0)  # "Available interfaces"
     while lines and not lines[-1]:
         lines.pop()
     self.assertEqual(len(lines), 10)
     for line in lines:
         self.assertTrue(line.startswith('ftdi://'))
         # skip description, i.e. consider URL only
         url = line.split(' ')[0]
         urlparts = urlsplit(url)
         self.assertEqual(urlparts.scheme, 'ftdi')
         parts = urlparts.netloc.split(':')
         if parts[1] == '4232':
             # def file contains no serial number, so expect bus:addr syntax
             self.assertEqual(len(parts), 4)
             self.assertRegex(parts[2], r'^\d$')
             self.assertRegex(parts[3], r'^\d$')
         else:
             # other devices are assigned a serial number
             self.assertEqual(len(parts), 3)
             self.assertTrue(parts[2].startswith('FT'))
         self.assertRegex(urlparts.path, r'^/\d$')
Beispiel #9
0
 def createdevpinout(self,ftdidevicename,devtype="",devorder=-1):
  global PINOUT
  startpoint = len(Settings.Pinout)
  try:
   fi = Ftdi()
   fi = fi.create_from_url(ftdidevicename)
   gpionum = fi.port_width
   lismpsse = fi.has_mpsse
   lportindex = fi.port_index
   fi.close()
  except Exception as e:
   gpionum = 0
  if gpionum>0:
   for g in range(0,gpionum):
    pname = get_ftdi_pinnames(g,lportindex,lismpsse)
    if devorder>-1:
     try:
      pname[2] = pname[2].replace("SPI-","SPI"+str(devorder)+"-")
      pname[3] = pname[3].replace("I2C-","I2C"+str(devorder)+"-")
     except:
      pass
    pindet = {"ID": int(startpoint+g),
"BCM":int(startpoint+g),
"realpin":int(g),
"name":pname,
"canchange":1,
"altfunc": 0,
"startupstate":-1,
"actualstate":-1,
"ftdevice":ftdidevicename,
"ftdevtype":devtype
}
    Settings.Pinout.append(pindet)
    pindet = None
Beispiel #10
0
 def __init__(self, trst=False, frequency=3.0E6, usb_read_timeout=5000, usb_write_timeout=5000, debug=False):
     """
     trst uses the nTRST optional JTAG line to hard-reset the TAP
       controller
     """
     self._ftdi = Ftdi()
     self._lock = Lock()
     self._ftdi.timeouts = (usb_read_timeout, usb_write_timeout)
     self._trst = trst
     self._frequency = frequency
     self._ftdi_opened = False
     self._immediate = bytes((Ftdi.SEND_IMMEDIATE,))
     self.direction = (JtagController.TCK_BIT |
                       JtagController.TDI_BIT |
                       JtagController.TMS_BIT |
                       (self._trst and JtagController.TRST_BIT or 0))
     # all JTAG outputs are low - Additionally, setting this upper
     # bits as outputs and then having a specific initial value
     # gets the PYNQ-Z1 board working
     self.direction |= 0x90
     self.initialout = 0xe0  
     #@@@#self.initialout = self.direction
     self._last = None  # Last deferred TDO bit
     self._write_buff = array('B')
     self._debug = debug
Beispiel #11
0
 def __init__(self, silent_clock=False, cs_count=4, turbo=True):
     self._ftdi = Ftdi()
     self._cs_bits = (((SpiController.CS_BIT << cs_count) - 1)
                      & ~(SpiController.CS_BIT - 1))
     self._ports = [None] * cs_count
     self._direction = (self._cs_bits | SpiController.DO_BIT
                        | SpiController.SCK_BIT)
     self._turbo = turbo
     self._cs_high = Array('B')
     if self._turbo:
         if silent_clock:
             # Set SCLK as input to avoid emitting clock beats
             self._cs_high.extend([
                 Ftdi.SET_BITS_LOW, self._cs_bits,
                 self._direction & ~SpiController.SCK_BIT
             ])
         # /CS to SCLK delay, use 8 clock cycles as a HW tempo
         self._cs_high.extend([Ftdi.WRITE_BITS_TMS_NVE, 8 - 1, 0xff])
     # Restore idle state
     self._cs_high.extend(
         [Ftdi.SET_BITS_LOW, self._cs_bits, self._direction])
     if not self._turbo:
         self._cs_high.append(Ftdi.SEND_IMMEDIATE)
     self._immediate = Array('B', [Ftdi.SEND_IMMEDIATE])
     self._frequency = 0.0
Beispiel #12
0
 def test_eeprom_read(self):
     """Check full read sequence."""
     ftdi = Ftdi()
     ftdi.open_from_url('ftdi:///1')
     data = ftdi.read_eeprom()
     self.assertEqual(len(data), 0x400)
     ftdi.close()
Beispiel #13
0
    def test_input_gpio(self):
        """Simple test to demonstrate input bit-banging on CBUS.

           You need a CBUS-capable FTDI (FT232R/FT232H/FT230X/FT231X), whose
           EEPROM has been configured to support GPIOs on CBUS0 and CBUS3.

           Hard-wiring is required to run this test:
           * CBUS0 (input) should be connected to RTS (output)
           * CBUS3 (input) should be connected to DTR (output)
        """
        ftdi = Ftdi()
        ftdi.open_from_url(self.url)
        # sanity check: device should support CBUS feature
        self.assertEqual(ftdi.has_cbus, True)
        eeprom = FtdiEeprom()
        eeprom.connect(ftdi)
        # sanity check: device should have been configured for CBUS GPIOs
        self.assertEqual(eeprom.cbus_mask & 0b1001, 0b1001)
        # configure CBUS0 and CBUS3 as input
        ftdi.set_cbus_direction(0b1001, 0b0000)
        # no output pin available
        self.assertRaises(FtdiError, ftdi.set_cbus_gpio, 0)
        for cycle in range(40):
            rts = bool(cycle & 0x1)
            dtr = bool(cycle & 0x2)
            ftdi.set_rts(rts)
            ftdi.set_dtr(dtr)
            # need to inverse logical level as RS232 uses negative logic
            cbus = ~ftdi.get_cbus_gpio()
            sig = (cbus & 0x1) | ((cbus & 0x8) >> 2)
            value = cycle & 0x3
            self.assertEqual(value, sig)
Beispiel #14
0
 def setUpClass(cls):
     FtdiTestCase.setUpClass()
     if VirtLoader:
         cls.loader = VirtLoader()
         with open('pyftdi/tests/resources/ft2232h.yaml', 'rb') as yfp:
             cls.loader.load(yfp)
         vftdi = cls.loader.get_virtual_ftdi(1, 1)
         vport1 = vftdi.get_port(1)
         vport2 = vftdi.get_port(2)
         # create virtual connections as real HW
         in_pins = [vport1[pos] for pos in range(16)]
         out_pins = [vport2[pos] for pos in range(16)]
         for in_pin, out_pin in zip(in_pins, out_pins):
             out_pin.connect_to(in_pin)
         # prevent from using the tracer twice (Ftdi & VirtualFtdi)
         cls.debug_mpsse = False
     else:
         cls.debug_mpsse = cls.debug
     url = environ.get('FTDI_DEVICE', 'ftdi:///1')
     ftdi = Ftdi()
     ftdi.open_from_url(url)
     count = ftdi.device_port_count
     width = ftdi.port_width
     ftdi.close()
     if count < 2:
         raise SkipTest('FTDI device is not a multi-port device')
     if width < 2:
         raise SkipTest('FTDI device does not support wide ports')
     url = url[:-1]
     cls.urls = [f'{url}1', f'{url}2']
Beispiel #15
0
    def test_output_gpio(self):
        """Simple test to demonstrate ouput bit-banging on CBUS.

           You need a CBUS-capable FTDI (FT232R/FT232H/FT230X/FT231X), whose
           EEPROM has been configured to support GPIOs on CBUS0 and CBUS3.

           Hard-wiring is required to run this test:
           * CBUS0 (output) should be connected to CTS (input)
           * CBUS3 (output) should be connected to DSR (input)
        """
        ftdi = Ftdi()
        ftdi.open_from_url(self.url)
        # sanity check: device should support CBUS feature
        self.assertEqual(ftdi.has_cbus, True)
        eeprom = FtdiEeprom()
        eeprom.connect(ftdi)
        # sanity check: device should have been configured for CBUS GPIOs
        self.assertEqual(eeprom.cbus_mask & 0b1001, 0b1001)
        # configure CBUS0 and CBUS3 as output
        ftdi.set_cbus_direction(0b1001, 0b1001)
        # no input pin available
        self.assertRaises(FtdiError, ftdi.get_cbus_gpio)
        for cycle in range(40):
            value = cycle & 0x3
            # CBUS0 and CBUS3
            cbus = ((value & 0x2) << 2) | value & 0x1
            # for now, need a digital/logic analyzer to validate output
            ftdi.set_cbus_gpio(cbus)
            # CBUS0 is connected to CTS, CBUS3 to DSR
            # need to inverse logical level as RS232 uses negative logic
            sig = int(not ftdi.get_cts()) | (int(not ftdi.get_dsr()) << 1)
            self.assertEqual(value, sig)
Beispiel #16
0
 def setUpClass(cls):
     FtdiTestCase.setUpClass()
     if VirtLoader:
         cls.loader = VirtLoader()
         with open('pyftdi/tests/resources/ft232r.yaml', 'rb') as yfp:
             cls.loader.load(yfp)
         vftdi = cls.loader.get_virtual_ftdi(1, 1)
         vport = vftdi.get_port(1)
         # create virtual connections as real HW
         in_pins = [vport[pos] for pos in range(4)]
         out_pins = [vport[pos] for pos in range(4, 8)]
         for in_pin, out_pin in zip(in_pins, out_pins):
             out_pin.connect_to(in_pin)
     if cls.url == 'ftdi:///1':
         # assumes that if not specific device is used, and a multiport
         # device is connected, there is no loopback wires between pins of
         # the same port. This hack allows to run the same test with a
         # FT232H, then a FT2232H for ex, to that with two test sessions
         # the whole test set is run. If a specific device is selected
         # assume the HW always match the expected configuration.
         ftdi = Ftdi()
         ftdi.open_from_url(cls.url)
         count = ftdi.device_port_count
         ftdi.close()
         cls.skip_loopback = count > 1
     else:
         cls.skip_loopback = False
Beispiel #17
0
 def test(self):
     ftdi = Ftdi()
     ftdi.open_from_url(URL)
     for baudrate in self.BAUDRATES:
         actual, _, _ = ftdi._convert_baudrate(baudrate)
         ratio = baudrate / actual
         self.assertTrue(0.97 <= ratio <= 1.03, "Invalid baudrate")
Beispiel #18
0
 def setUpClass(cls):
     FtdiTestCase.setUpClass()
     if VirtLoader:
         cls.loader = VirtLoader()
         with open('pyftdi/tests/resources/ft2232h.yaml', 'rb') as yfp:
             cls.loader.load(yfp)
         vftdi = cls.loader.get_virtual_ftdi(1, 1)
         vport1 = vftdi.get_port(1)
         vport2 = vftdi.get_port(2)
         # create virtual connections as real HW
         in_pins = [vport1[pos] for pos in range(8)]
         out_pins = [vport2[pos] for pos in range(8)]
         for in_pin, out_pin in zip(in_pins, out_pins):
             out_pin.connect_to(in_pin)
     ftdi = Ftdi()
     ftdi.open_from_url(cls.url)
     count = ftdi.device_port_count
     pos = ftdi.port_index
     ftdi.close()
     if pos != 1:
         raise ValueError("FTDI interface should be the device's first")
     if count < 2:
         raise SkipTest('FTDI device is not a multi-port device')
     url = cls.url[:-1]
     cls.urls = [f'{url}1', f'{url}2']
Beispiel #19
0
 def __init__(self):
     self._ftdi = Ftdi()
     self._lock = Lock()
     self.log = getLogger('pyftdi.i2c')
     self._gpio_port = None
     self._gpio_dir = 0
     self._gpio_low = 0
     self._gpio_mask = 0
     self._i2c_mask = 0
     self._wide_port = False
     self._slaves = {}
     self._retry_count = self.RETRY_COUNT
     self._frequency = 0.0
     self._immediate = (Ftdi.SEND_IMMEDIATE, )
     self._read_bit = (Ftdi.READ_BITS_PVE_MSB, 0)
     self._read_byte = (Ftdi.READ_BYTES_PVE_MSB, 0, 0)
     self._write_byte = (Ftdi.WRITE_BYTES_NVE_MSB, 0, 0)
     self._nack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.HIGH)
     self._ack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.LOW)
     self._ck_delay = 1
     self._tristate = None
     self._tx_size = 1
     self._rx_size = 1
     self._ck_hd_sta = 0
     self._ck_su_sto = 0
     self._ck_idle = 0
Beispiel #20
0
 def __init__(self):
     self._ftdi = Ftdi()
     self.log = getLogger('pyftdi.i2c')
     self._slaves = {}
     self._retry_count = self.RETRY_COUNT
     self._frequency = 0.0
     self._direction = self.SCL_BIT | self.SDA_O_BIT
     self._immediate = (Ftdi.SEND_IMMEDIATE, )
     self._idle = (Ftdi.SET_BITS_LOW, self.IDLE, self._direction)
     self._data_lo = (Ftdi.SET_BITS_LOW, self.IDLE & ~self.SDA_O_BIT,
                      self._direction)
     self._clk_lo_data_lo = (Ftdi.SET_BITS_LOW,
                             self.IDLE & ~(self.SDA_O_BIT | self.SCL_BIT),
                             self._direction)
     self._clk_lo_data_hi = (Ftdi.SET_BITS_LOW, self.IDLE & ~self.SCL_BIT,
                             self._direction)
     self._read_bit = (Ftdi.READ_BITS_PVE_MSB, 0)
     self._read_byte = (Ftdi.READ_BYTES_PVE_MSB, 0, 0)
     self._write_byte = (Ftdi.WRITE_BYTES_NVE_MSB, 0, 0)
     self._nack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.HIGH)
     self._ack = (Ftdi.WRITE_BITS_NVE_MSB, 0, self.LOW)
     self._start = None
     self._stop = None
     self._ck_delay = 1
     self._tristate = None
     self._tx_size = 1
     self._rx_size = 1
Beispiel #21
0
    def __init__(self, name, serial=None, port='A', baudrate=115200):
        '''
            discover and initialize Tunnel_DAC hardware
            
            Input:
                serial - serial number of the FTDI converter
                channel - 2 character channel id the DAC is connected to;
                    the first byte identifies the channel (A..D for current devices)
                    the second byte identifies the bit within that channel (0..7)
                numdacs - number of DACs daisy-chained on that line
                delay - communications delay assumed between PC and the USB converter
        '''
        logging.info(__name__ + ': Initializing instrument Tunnel_DAC')
        Instrument.__init__(self, name, tags=['physical'])

        self._conn = Ftdi()
        # VIDs and PIDs of converters used
        vps = [
            (0x0403, 0x6011),  # FTDI UM4232H 4ch
            (0x0403, 0x6014)  # FTDI UM232H 1ch
        ]
        # explicitly clear device cache of UsbTools
        #UsbTools.USBDEVICES = []
        # find all devices and obtain serial numbers
        devs = self._conn.find_all(vps)
        # filter list by serial number if provided
        if (serial != None):
            devs = [dev for dev in devs if dev[2] == serial]
        if (len(devs) == 0):
            logging.error(__name__ + ': failed to find matching FTDI devices.')
        elif (len(devs) > 1):
            logging.error(
                __name__ +
                ': more than one converter found and no serial number given.')
            logging.info(__name__ + ': available devices are: %s.' %
                         str([dev[2] for dev in devs]))
        vid, pid, self._serial, ports, description = devs[0]
        self._ports = [chr(ord('A') + i) for i in range(ports)]

        # open device
        (self._port, bit) = self._parse_channel_string(port)
        self._conn.open(vid,
                        pid,
                        interface=ord(self._port) - ord('A') + 1,
                        serial=self._serial)
        logging.info(__name__ +
                     ': using converter with serial #%s' % self._serial)
        self._conn.set_bitmode(0xFF, Ftdi.BITMODE_BITBANG)
        self._set_baudrate(baudrate)

        # provide user interface
        self.add_parameter('port',
                           type=types.StringType,
                           flags=Instrument.FLAG_GET)
        #self.add_parameter('aliases', type=types.DictType, flags=Instrument.FLAG_GETSET)
        self.add_function('digital_out')
        self.add_function('digital_stream')
        self.add_function('set_aliases')
        self.add_function('get_aliases')
Beispiel #22
0
    def __init__(self, deviceid):
        """

        :rtype: object
        """
        # self.input = queue.Queue(20)
        self.packetCallback = None
        self.errorCallback = None

        self._commandLock = Lock()
        self._packetReadEvent = Event()
        self._startedEvent = Event()
        self._stoppedEvent = Event()
        self._run = True
        self.device_id = deviceid
        self._ftdi = Ftdi()
        self.numScanners = 0
        self.numRelays = 0
        self.relaystatus = {}
        self.version = "0.00"
        self.model = "unknown"
        self._unlockTimeouts = {}

        self._parserState = ParserState.BEGIN
        self._firstChar = ' '
        self._body = bytearray()

        # self.ftdi.open(vendor=0x0403,product=0x6001, serial=self.device)
        self._ftdi.open_from_url(self.device_id)
        self._ftdi.set_baudrate(57600)

        self._backgroundThread = Thread(target=self.background)
        self._backgroundThread.start()
        self._otherThread = Thread(target=self.lock_watch_loop)
        self._otherThread.start()

        if not self._startedEvent.wait(3.0):
            raise RuntimeError("Unable to startup board!")
        else:
            logger.log(logging.DEBUG, "Started up, disabling echo")
            self.send_command('e', '0')

            def get_device_info(fc, b, me):
                if fc == 'I':
                    info = {i.split(':')[0]: i.split(':')[1] for i in b.split(',')}
                    self.model = info['m']
                    self.version = info['v']
                    self.numRelays = int(info['r'])
                    self.numScanners = int(info['s'])
                    for a in range(self.numRelays):
                        self._unlockTimeouts[a] = []
                        self.relaystatus[a] = False

            self.packetCallback = get_device_info
            logger.info("calling getting device info")
            self.send_command('i', '')
            logger.info("done interrogating")

            self.packetCallback = None
Beispiel #23
0
 def __init__(self, debug=False):
     self.blaster = Ftdi()
     self.virtual = True
     self.blaster.LATENCY_MIN = 1
     self.blaster.open(0x09FB, 0x6001)
     self.blaster.write_data_set_chunksize(1)
     self._last = None  # Last deferred TDO bit
     self.debug = debug
Beispiel #24
0
 def setUpClass(cls):
     FtdiTestCase.setUpClass()
     if VirtLoader:
         cls.loader = VirtLoader()
         with open(cls.TEST_CONFIG_FILENAME, 'rb') as yfp:
             cls.loader.load(yfp)
     if cls.url == 'ftdi:///1':
         ftdi = Ftdi()
         ftdi.open_from_url(cls.url)
         count = ftdi.device_port_count
         ftdi.close()
Beispiel #25
0
 def test_dump(self):
     """Check EEPROM full content."""
     ftdi = Ftdi()
     ftdi.open_from_url('ftdi:///1')
     self._restore_eeprom(ftdi)
     ref_data = bytes(list(range(256)))
     size = len(ref_data)
     data = ftdi.read_eeprom()
     self.assertEqual(len(data), size)
     self.assertEqual(ref_data, data)
     ftdi.close()
Beispiel #26
0
 def connect(self):
     if self.dev.is_kernel_driver_active(0):
         self.dev.detach_kernel_driver(0)
     
     self._claim_dev()
     
     self._ftdi = Ftdi()
     self._ftdi.open_from_device(self.dev)
     
     self._ftdi.set_bitmode(0xFF, Ftdi.BitMode.RESET)
     self._ftdi.set_bitmode(0xFF, Ftdi.BitMode.SYNCFF)
Beispiel #27
0
 def __init__(self, silent_clock=False, cs_count=4, turbo=True):
     self._ftdi = Ftdi()
     self._lock = Lock()
     self._gpio_port = None
     self._gpio_dir = 0
     self._gpio_low = 0
     self._wide_port = False
     self._cs_count = cs_count
     self._turbo = turbo
     self._immediate = bytes((Ftdi.SEND_IMMEDIATE, ))
     self._frequency = 0.0
     self._clock_phase = False
Beispiel #28
0
    def configure(self, url, direction=0, **kwargs):
        """Open a new interface to the specified FTDI device in bitbang mode.

           :param str url: a FTDI URL selector
           :param int direction: a bitfield specifying the FTDI GPIO direction,
                where high level defines an output, and low level defines an
                input
        """
        for k in ('direction', ):
            if k in kwargs:
                del kwargs[k]
        try:
            ftdi = Ftdi()
            ftdi.open_bitbang_from_url(url, direction=direction, **kwargs)
            self._ftdi = ftdi
        except IOError as ex:
            raise GpioException('Unable to open USB port: %s' % str(ex))
        self._direction = direction

        with self._lock:
            if (self._ftdi.has_wide_port and self._ftdi.has_mpsse):
                # If this device supports the wide 16-bit GPIO port,
                # must open as MPSSE to access the 16-bits. So close
                # ftdi and re-open it as MPSSE.
                try:
                    self._ftdi.close()
                    ftdi = Ftdi()
                    ftdi.open_mpsse_from_url(url,
                                             direction=direction,
                                             **kwargs)
                    self._ftdi = ftdi
                except IOError as ex:
                    raise GpioException('Unable to open USB port: %s' %
                                        str(ex))

            self._wide_port = self._ftdi.has_wide_port

            gpio_width = self._wide_port and 16 or 8
            gpio_mask = (1 << gpio_width) - 1
            self._gpio_mask = gpio_mask
Beispiel #29
0
 def open_from_url(self, url, direction, **kwargs):
     """
     """
     for k in ('direction',):
         if k in kwargs:
             del kwargs[k]
     try:
         ftdi = Ftdi()
         ftdi.open_bitbang_from_url(url, direction=direction, **kwargs)
         self._ftdi = ftdi
     except IOError as e:
         raise GpioException('Unable to open USB port: %s' % str(e))
     self._direction = direction
Beispiel #30
0
 def __init__(self, trst=False, frequency=3.0E6):
     """
     trst uses the nTRST optional JTAG line to hard-reset the TAP
       controller
     """
     self._ftdi = Ftdi()
     self._trst = trst
     self._frequency = frequency
     self.direction = (JtagController.TCK_BIT | JtagController.TDI_BIT
                       | JtagController.TMS_BIT |
                       (self._trst and JtagController.TRST_BIT or 0))
     self._last = None  # Last deferred TDO bit
     self._write_buff = Array('B')