示例#1
0
    def __init__(self):
        deva = ftdi.Device(interface_select=ftdi.INTERFACE_A)
        deva.ftdi_fn.ftdi_set_bitmode(0x00, 0x00)  # reset
        deva.close()

        self.dev = ftdi.Device(interface_select=ftdi.INTERFACE_B)
        self.dev.ftdi_fn.ftdi_set_bitmode(0x00, 0x00)  # reset
        self.dev.ftdi_fn.ftdi_set_bitmode(0x03, 0x02)  # MPSSE mode
        self.set_spi_clock(500e3)
示例#2
0
    def test_read_timeout(self):
        # on Linux, there is a strange bug that sets the timeout to zero.
        # However, after sleep, with the FTDI device still plugged in *and
        # used at least once*, the timeout kicks in and the effective
        # timeout will be the 16 ms promised by a timeout inside the FTDI
        # chip.
        #
        # Test that the timeout is 16 ms, not less.  We expect to not see
        # data, so the PMT voltages must be zero!

        try:
            device = pylibftdi.Device()
        except pylibftdi.FtdiError:
            self.skipTest("Device not found")

        # Explicitly set latency timer. Apparently, that's possible, and it
        # fixes the issue. Thanks @tomkooij!
        device.ftdi_fn.ftdi_set_latency_timer(16)
        device.flush()
        t = []
        for i in range(10):
            t0 = time.time()
            device.read(62)
            t.append(time.time() - t0)
        mean_t = sum(t) / len(t)
        self.assertAlmostEqual(mean_t, 16e-3, delta=2e-3)
示例#3
0
    def __init__(self, serial_number=None, label=None):
        """Constructor
        
        Args:
            serial_number (str): S/N of the device
            label (str): optional name of the device
        """

        super(Controller, self).__init__()
   
        dev = pylibftdi.Device(mode='b', device_id=serial_number)
        dev.baudrate = 115200
    
        def _checked_c(ret):
            if not ret == 0:
                raise Exception(dev.ftdi_fn.ftdi_get_error_string())
    
        _checked_c(dev.ftdi_fn.ftdi_set_line_property(8, # number of bits
                                                      1, # number of stop bits
                                                      0  # no parity
                                                      ))
        time.sleep(50.0/1000)
        dev.flush(pylibftdi.FLUSH_BOTH)
        time.sleep(50.0/1000)

        # skipping reset part since it looks like pylibftdi does it already

        # this is pulled from ftdi.h
        SIO_RTS_CTS_HS = (0x1 << 8)
        _checked_c(dev.ftdi_fn.ftdi_setflowctrl(SIO_RTS_CTS_HS))
        _checked_c(dev.ftdi_fn.ftdi_setrts(1))

        self.serial_number = serial_number
        self.label         = label
        self._device       = dev

        # some conservative limits
        self.max_velocity     = 0.3     # mm/s
        self.max_acceleration = 0.3     # mm/s/s

        # these define how encode count translates into position, velocity
        # and acceleration. e.g. 1 mm is equal to 1 * self.position_scale
        # these are set to None on purpose - you should never use this class
        # as is.
        self.position_scale     = None
        self.velocity_scale     = None
        self.acceleration_scale = None

        # defines the linear, i.e. distance, range of the controller
        # unit is in mm
        self.linear_range = (0,10)

        # whether or not sofware limit in position is applied
        self.soft_limits = True

        # the message queue are messages that are sent asynchronously. For
        # example if we performed a move, and are waiting for move completed
        # message, any other message received in the mean time are place in the
        # queue.
        self.message_queue = []
示例#4
0
    def open(self):
        """Open device.

        Raises :class:`DeviceNotFoundError` if the device cannot be found.
        Raises :class:`DeviceError` if the device cannot be opened.

        """
        if self._device is None:
            try:
                logger.info("Initialising Ftdi device {} {}".format(self._device_description, self._device_index))
                self._device = pylibftdi.Device(self._device_description,
                    interface_select=self._interface_select, device_index=self._device_index)
            except pylibftdi.FtdiError as exc:
                if "(-3)" in str(exc):
                    raise DeviceNotFoundError(str(exc))
                else:
                    raise DeviceError(str(exc))
            else:
                # force default latency timer of 16 ms
                # on some systems, this reverts to 0 ms if not set explicitly
                self._device.ftdi_fn.ftdi_set_latency_timer(16)

                self.closed = False
                self.flush()
        else:
            return
示例#5
0
 def __init__(self):
     self.device = ftdi.Device(mode='t', interface_select=ftdi.INTERFACE_B)
     self.device.open()
     self.lo = MAX2871()
     self.source = MAX2871()
     self.current_switches = None
     self.current_att = None
示例#6
0
    def reset(self, enter_bsl=False):
        del self.s

        # Create a bitbang device to do the secret handshake
        ctl = pylibftdi.BitBangDevice()

        if enter_bsl:
            # RTS (0x04) is TEST, CTS (0x08) is RST
            ctl.direction = 0x0C  # Drive pins
            ctl.port = 0x00  # Drive all low
            ctl.port = 0x04  # Set TEST
            ctl.port = 0x00  # Clear
            ctl.port = 0x04  # Set TEST
            ctl.port = 0x0C  # "Release" RST
            ctl.port = 0x08  # "Release" TEST
            ctl.direction = 0x00  # Release pins
        else:
            ctl.direction = 0x0C  # Drive pins
            ctl.port = 0x00  # Drive all low
            ctl.port = 0x04  # "Release" RST
            ctl.port = 0x0C  # "Release" TEST
            ctl.direction = 0x00  # Release pins

        del ctl

        # Create a simple serial port device for the BSL.
        # N.B the even parity bit!
        self.s = pylibftdi.Device()
        if enter_bsl:
            # 8 bits, even parity, 1 stop bit
            self.s.ftdi_fn.ftdi_set_line_property(8, 0, 2)
        else:
            self.s.ftdi_fn.ftdi_set_line_property(8, 0, 0)
        self.s.baudrate = 9600
        self.s.flush()
示例#7
0
    def __init__(self, speed, mode, interface=None, **kwargs):
        self.speed = speed
        self.mode = mode

        self.dev = pylibftdi.Device(interface_select=interface, **kwargs)

        self._open()
示例#8
0
 def __init__(self, baud):
     import pylibftdi
     try:
         handle = pylibftdi.Device()
         handle.baudrate = baud
         super(PyFTDIDriver, self).__init__(handle)
     except pylibftdi.FtdiError:
         raise
示例#9
0
def init():
    s = ftdi.Device(interface_select=PORT)
    s.baudrate = BAUD
    print(s.baudrate)
    # if e == -1:
    # 	print("Failed to set baudrate")
    s.ftdi_fn.ftdi_set_latency_timer(1)
    s.ftdi_fn.ftdi_set_line_property(8, 1, 0)
    return s
示例#10
0
文件: com.py 项目: ISIR-MAP/multicom
 def run(self):
     import pylibftdi
     try:
         self.dev = pylibftdi.Device()#pylint: disable=W0201
         self.dev.baudrate = 230400
     except pylibftdi._base.FtdiError:
         print('haptic device not found')
     writing = Thread(target=self.write, args=("Thread-write",))
     writing.start()
     lecturing = Thread(target=self.lecture, args=("Thread-read",))
     lecturing.start()
示例#11
0
def ftdi_open(board_id, channel):
    """opens FTDI device function depending of the current OS"""
    if OS == 'Linux':
        return pylibftdi.Device(device_index=board_id, interface_select=channel + 1)
    elif OS == 'Windows':
        dev_list = ftdi.listDevices()
        if channel:
            i2c_channel = next(ind for ind, dev in enumerate(dev_list) if chr(dev[-1]) == 'B')
            return ftdi.open(i2c_channel)
        else:
            gpio_channel = next(ind for ind, dev in enumerate(dev_list) if chr(dev[-1]) == 'A')
            return ftdi.open(gpio_channel)
示例#12
0
    def __init__(self):
        SYNCFF = 0x40
        SIO_RTS_CTS_HS = (0x1 << 8)
        self.device = ftdi.Device(mode='b', interface_select=ftdi.INTERFACE_A)
        self.device.open()
        self.device.ftdi_fn.ftdi_set_bitmode(0xff, SYNCFF)
        self.device.ftdi_fn.ftdi_read_data_set_chunksize(0x10000)
        self.device.ftdi_fn.ftdi_write_data_set_chunksize(0x10000)
        self.device.ftdi_fn.ftdi_setflowctrl(SIO_RTS_CTS_HS)
        self.device.flush()

        self.pll = ADF4158()
        self.fclk = 40e6
        self.fpd_freq = self.fclk / 2
示例#13
0
    def open(self):
        if (self.port == None):
            print "opening first available ftdi device..."
        else:
            print "opening ftdi device with serial %s" % self.port

        try:
            self._ftdi_dev = pylibftdi.Device(
                device_id=self.port,
                mode='t',
                interface_select=pylibftdi.INTERFACE_B)
        except:
            raise

        self._reconfigurePort()
        self._isOpen = True
示例#14
0
def ftdi_open(board_id, channel, desc=None):
    """opens FTDI device function depending of the current OS"""
    if OS == 'Linux':
        return pylibftdi.Device(device_index=board_id,
                                interface_select=channel + 1)
    elif OS == 'Windows':
        add = desc.get('location')
        dev_list = ftdi.listDevices()
        dev_channel = None
        for i, d in enumerate(dev_list):
            if d != b'':
                if chr(d[-1]) == chr(ord('A') + channel):
                    tmp_dev = ftdi.getDeviceInfoDetail(i)
                    if tmp_dev.get('location') == add + channel:
                        dev_channel = tmp_dev.get('index')
            else:
                pass
        return ftdi.open(dev_channel)
    def test_read_timeout(self):
        # on Linux, there is a strange bug that sets the timeout to zero.
        # However, after sleep, with the FTDI device still plugged in *and
        # used at least once*, the timeout kicks in and the effective
        # timeout will be the 16 ms promised by a timeout inside the FTDI
        # chip.
        #
        # Test that the timeout is 16 ms, not less.  We expect to not see
        # data, so the PMT voltages must be zero!

        device = pylibftdi.Device(DESCRIPTION)
        device.flush()
        t = []
        for i in range(10):
            t0 = time.time()
            device.read(62)
            t.append(time.time() - t0)
        mean_t = sum(t) / len(t)
        self.assertAlmostEqual(mean_t, 16e-3, delta=2e-3)
示例#16
0
def main():
    """
  Write the NEW_VID and NEW_PID to any detected FTDI device's eeprom.
  """
    ftdi_dev = pylibftdi.Device(mode='t')

    # read eeprom contents then parse
    ftdi_dev.ftdi_fn.ftdi_read_eeprom()
    ftdi_dev.ftdi_fn.ftdi_eeprom_decode()

    # use library abstraction to get old vid/pid (rather than from the eeprom buffer)
    old_vid = c_int()
    ftdi_dev.ftdi_fn.ftdi_get_eeprom_value(VENDOR_ID_FIELD, byref(old_vid))
    old_pid = c_int()
    ftdi_dev.ftdi_fn.ftdi_get_eeprom_value(PRODUCT_ID_FIELD, byref(old_pid))

    # set new values
    ftdi_dev.ftdi_fn.ftdi_set_eeprom_value(VENDOR_ID_FIELD, NEW_VID)
    ftdi_dev.ftdi_fn.ftdi_set_eeprom_value(PRODUCT_ID_FIELD, NEW_PID)

    # rebuilt the eeprom image to write
    ftdi_dev.ftdi_fn.ftdi_eeprom_build()
    ftdi_dev.ftdi_fn.ftdi_write_eeprom()

    # read back to verify
    ftdi_dev.ftdi_fn.ftdi_read_eeprom()
    ftdi_dev.ftdi_fn.ftdi_eeprom_decode()

    new_vid = c_int()
    ftdi_dev.ftdi_fn.ftdi_get_eeprom_value(VENDOR_ID_FIELD, byref(new_vid))
    new_pid = c_int()
    ftdi_dev.ftdi_fn.ftdi_get_eeprom_value(PRODUCT_ID_FIELD, byref(new_pid))

    print "vid: 0x%x -> 0x%x" % (old_vid.value, new_vid.value)
    print "pid: 0x%x -> 0x%x" % (old_pid.value, new_pid.value)

    if (new_vid.value == NEW_VID and new_pid.value == NEW_PID):
        print "done"
        exit(0)
    else:
        print "could not verify new values!"
        exit(-1)
示例#17
0
    def __init__(self, serial_num, obj, refresh=0, baudrate=115200):
        # Name and type of the connection peer
        self.name = ''
        self.type = ''

        self.object = obj
        self.baudrate = baudrate
        self.serial_num = serial_num
        self.devpath = ''

        if refresh > 0:
            self._refresh = refresh

        self.device = pylibftdi.Device(mode='b',
                                       device_id=self.serial_num,
                                       lazy_open=True)
        self.device._baudrate = self.baudrate

        self._updateTimer = LoopingCall(self.update)
        self._updateTimer.start(self._refresh)
        self._readTimer = LoopingCall(self.read)
        self._readTimer.start(self._refresh / 10)

        # the following will start a small daemon to monitor the connection and call ConnectionMade and ConnectionLost
        # pyftdi doesn't seem to support this so this pyudev daemon is necessary

        context = Context()
        # find out whether device is already connected and if that is the case open ftdi connection
        for device in context.list_devices(subsystem='usb'):
            if device.get('ID_SERIAL_SHORT') == self.serial_num:
                for ch in device.children:
                    if 'tty' not in ch.get('DEVPATH'):
                        self.devpath = ch.get('DEVPATH')
                        self.ConnectionMade()

        cm = Monitor.from_netlink(context)
        cm.filter_by(subsystem='usb')
        observer = MonitorObserver(cm,
                                   callback=self.ConnectionMCallBack,
                                   name='monitor-observer')
        observer.start()
示例#18
0
 def _initialize_serial_com(self):
     '''Initialize the low-level serial com connection'''
     self.resolved_port = self._resolve_port_name()
     self.port_type = self._resolve_port_type()
     if self.port_type == 'pyserial':
         self._ready_port = self._ready_port_pyserial
         import serial
         self.serial_com = serial.Serial(self.resolved_port,
                                         baudrate=self.baudrate,
                                         timeout=self.timeout)
     elif self.port_type == 'pylibftdi':
         self._ready_port = self._ready_port_pylibftdi
         import pylibftdi
         self.serial_com = pylibftdi.Device(self.resolved_port)
     elif self.port_type == 'test':
         self._ready_port = self._ready_port_test
         import test.test_larpix as test_lib
         self.serial_com = test_lib.FakeSerialPort()
     else:
         raise ValueError('Port type must be either pyserial, pylibftdi, or test')
     return
示例#19
0
def burn(firmware_file):
    f = pylibftdi.Device("HiSPARC III Master", interface_select=1)

    # Select MPSSE mode (0x02)
    # Direction is not used here, it doesn't seem to work.
    # We'll set the direction explicitly later.
    f.ftdi_fn.ftdi_set_bitmode(0, 0x02)

    # Set clock frequency to 30 MHz (0x0000)
    write(f, [TCK_DIVISOR, 0, 0])
    # Disable divide clock frequency by 5
    write(f, [DISABLE_CLK_DIV5])

    # bits 0 and 1 are output that is, bits TCK/SK and TDI/DO, clock and
    # data
    write(f, [SET_BITS_LOW, 0, 0b11])

    print_high_bits(f)
    # pull nCONFIG (low byte bit 0) low
    write(f, [SET_BITS_HIGH, 0, 1])
    print_high_bits(f)
    # pull nCONFIG (low byte bit 0) high
    write(f, [SET_BITS_HIGH, 1, 1])
    print_high_bits(f)

    BUFSIZE = 64 * 1024

    with open(os.path.expanduser(firmware_file), 'rb') as file:
        while True:
            xbuf = file.read(BUFSIZE)
            if not xbuf:
                break

            LENGTH = len(xbuf) - 1
            LENGTH_L = LENGTH & 0xff
            LENGTH_H = LENGTH >> 8 & 0xff
            write(f, [WRITE_BYTES_PVE_LSB, LENGTH_L, LENGTH_H])
            write(f, xbuf)

    print_high_bits(f)
示例#20
0
    def __init__(self, portNum=2):

        #Now set up the real ports
        self.port = ftdi.Device('USB-COM485 Plus2', interface_select=portNum)
        self.port.ftdi_fn.ftdi_set_latency_timer(1)
        # self.port.setTimeouts(3,3)
        # self.port.setUSBParameters(64)
        self.port.baudrate = 5000000
        self.reset()
        self.port.ftdi_fn.ftdi_usb_reset()
        print(self.port)

        self.num_errors = 0
        self.send_flag = False
        self.counter = 0
        self.counter2 = 0

        self.commands = {
            0x12: self.sendPackage,  #Data request
            0x10: self.setSendFlag,  #Start data transfer
            0x11: self.setSendFlag,  #Stop data transfer
            0xE1: self.deac_transducer,
            0xE2: self.deac_transducer,
            0xE3: self.deac_transducer,
            0xE4: self.deac_transducer,
            0xE5: self.deac_transducer,
            0xE6: self.deac_transducer,
            0xF0: self.reset,  #Full sensor reset
            0xF1: self.reset_transducer,
            0xF2: self.reset_transducer,
            0xF3: self.reset_transducer,
            0xF4: self.reset_transducer,
            0xF5: self.reset_transducer,
            0xF6: self.reset_transducer,
            0xFA: self.reset_imu,
            0xFB: self.reset_dac
        }

        self.crc8_table = crc.calculate_CRC8_table()
        self.crc32_table = crc.calculate_CRC32_table()
    def startFTDI(self, BAUD, HZ, PORT):
        #Open connection to port
        self.s = ftdi.Device(device_id='FT0NG8XX', interface_select=PORT)
        self.s.baudrate = BAUD
        self.s.ftdi_fn.ftdi_set_latency_timer(1)
        self.s.ftdi_fn.ftdi_set_line_property(8, 1, 0)

        #Generate byte message with sample rate
        hz = toHex(HZ)

        while not len(hz) == 4:
            hz = '0' + hz
            b = b'' + toStr([0x10, int(hz[:2], 16), int(hz[2:], 16)])

    #Start timing, write, and read
        self.startt = time.time()
        self.s.write(b)
        print('Started transmission')
        sys.stdout.flush()
        self.recState.data = 'Go'
        self.statPublisher.publish(self.recState)
        self.recState.data = 'Stop'
示例#22
0
    def __init__(self, serial_number=None):
        super(Connection, self).__init__()

        # this takes up to 2-3s:
        dev = pylibftdi.Device(mode='b', device_id=serial_number)
        dev.baudrate = 115200

        def _checked_c(ret):
            if not ret == 0:
                raise Exception(dev.ftdi_fn.ftdi_get_error_string())

        _checked_c(
            dev.ftdi_fn.ftdi_set_line_property(
                8,  # number of bits
                1,  # number of stop bits
                0  # no parity
            ))
        time.sleep(50.0 / 1000)

        dev.flush(pylibftdi.FLUSH_BOTH)

        time.sleep(50.0 / 1000)

        # skipping reset part since it looks like pylibftdi does it already

        # this is pulled from ftdi.h
        SIO_RTS_CTS_HS = (0x1 << 8)
        _checked_c(dev.ftdi_fn.ftdi_setflowctrl(SIO_RTS_CTS_HS))

        _checked_c(dev.ftdi_fn.ftdi_setrts(1))

        # the message queue are messages that are sent asynchronously. For example
        # if we performed a move, and are waiting for move completed message,
        # any other message received in the mean time are place in the queue.
        self.message_queue = []

        self.serial_number = serial_number
        self._device = dev
示例#23
0
    def __init__(self, ADC, encoding='latin1'):
        """Set up the FTDI object that represents the FPGA.

        :param ADC: ADC object (see ADC module)
        :param encoding: Encoding of the text data coming from the FTDI object
        """
        SYNCFF = 0x40
        SIO_RTS_CTS_HS = (0x1 << 8)
        #self.device = ftdi.Device(mode='t', interface_select=ftdi.INTERFACE_A, encoding=encoding)
        self.device = ftdi.Device(mode='b',
                                  interface_select=ftdi.INTERFACE_A,
                                  encoding=encoding)
        #self.device.open()  # Not needed if not lazy open
        self.device.ftdi_fn.ftdi_set_bitmode(0xff, SYNCFF)
        self.device.ftdi_fn.ftdi_read_data_set_chunksize(0x10000)
        self.device.ftdi_fn.ftdi_write_data_set_chunksize(0x10000)
        self.device.ftdi_fn.ftdi_setflowctrl(SIO_RTS_CTS_HS)
        self.device.flush()
        print("[INFO] FTDI baudrate:", self.device.baudrate)

        self.pll = ADC  # ADC and PLL are on the same clock
        self.fclk = 40e6  # [Hz] Clock frequency
        self.fpd_freq = self.fclk / 2
示例#24
0
    def __init__(self,
                 port=DEFAULT_PORT,
                 baud=DEFAULT_BAUD,
                 use_ftdi=False,
                 print_unhandled=False):
        self.print_unhandled = print_unhandled
        self.unhandled_bytes = 0
        self.callbacks = {}
        self.global_callbacks = []
        if use_ftdi:
            import pylibftdi
            self.ser = pylibftdi.Device()
            self.ser.baudrate = baud
        else:
            import serial
            try:
                self.ser = serial.Serial(port, baud, timeout=1)
            except serial.SerialException:
                print
                print "Serial device '%s' not found" % port
                print
                print "The following serial devices were detected:"
                print
                for p in list_ports():
                    p_name, p_desc, _ = p
                    if p_desc == p_name:
                        print "\t%s" % p_name
                    else:
                        print "\t%s (%s)" % (p_name, p_desc)
                sys.exit(1)

        # Delay then flush the buffer to make sure the receive buffer starts empty.
        time.sleep(0.5)
        self.ser.flush()

        self.lt = ListenerThread(self, print_unhandled)
        self.lt.start()
    def __init__(self, path, baud=3000000, portNum=1, rate=1500):
        self.num_errors = 0

        self.crc8_table = crc.calculate_CRC8_table()
        self.crc32_table = crc.calculate_CRC32_table()

        self.garbage_response = {
            'differential': [0, 0, 0, 0, 0, 0],
            'differential_raw': [0, 0, 0, 0, 0, 0],
            'sum': [0, 0, 0, 0, 0, 0],
            'sum_raw': [0, 0, 0, 0, 0, 0],
            'imu': [0, 0, 0, 0],
            'quaternion': [0, 0, 0, 0],
            'saturated': [0, 0, 0, 0, 0, 0],
            'temperature': 0,
            'report_id': 'NA'
        }

        self.baud = baud
        self.conti_read_flag = False
        self.report_ids = {
            0x01: 'Accelerometer',
            0x02: 'Gyroscope',
            0x04: 'Linear Acceleration',
            0x05: 'Rotation Vector',
            0x08: 'Game Rotation Vector'
        }

        #Find calibration matrix
        self.calMatrix = np.eye(6)
        self.filename = path + '/src/calibration.cal'
        self.get_cal_matrix()

        ###Initialize serial port
        try:
            self.port = ftdi.Device('USB-COM485 Plus2',
                                    interface_select=portNum)
        except ftdi.FtdiError:
            rospy.logerr('Failed to open port. Quitting...')
            sys.exit(0)
        self.port.ftdi_fn.ftdi_set_latency_timer(1)
        self.port.ftdi_fn.ftdi_set_line_property(8, 1, 0)
        self.port.baudrate = self.baud
        self.portNum = portNum
        rospy.loginfo('Opened port ' + str(self.portNum))

        self.reset()  #reset transmit and receive buffers

        self.ab = {
            2.5: (0x5DC000, 2.7304),
            5: (0x5DC000, 2.7304),
            10: (0x5DC000, 2.7304),
            15: (0x3E8000, 1.8202),
            25: (0x4B0000, 2.1843),
            30: (0x3E8000, 1.8202),
            50: (0x4B0000, 2.1843),
            60: (0x3E8000, 1.8202),
            100: (0x4B0000, 2.1843),
            500: (0x3C0000, 1.7474),
            1000: (0x3C0000, 1.7474),
            2000: (0x3C0000, 1.7474),
            3750: (0x400000, 1.8639),
            7500: (0x400000, 1.8639),
            15000: (0x400000, 1.8639),
            30000: (0x400000, 1.8639)
        }

        self.inBuf = [False] * 6
        self.adsGain = [1] * 6
        self.adsRate = [30e3] * 6
        self.vref = 2.5
        self.OFC = [1] * 6
        self.FSC = [1] * 6

        ###Set up ROS
        self.sampleRate = rate
        self.rate = rospy.Rate(self.sampleRate)

        #queue_size limits the number of queued messages if a subscriber is reading too slowly
        #Create publisher to write continuous data to topic using custom message type
        self.force_data_pub = rospy.Publisher('force_data' + str(portNum),
                                              SensorOutput,
                                              queue_size=1)
        #Listen to user commands and interrupt action to carry out the command
        self.user_cmds = rospy.Service('user_command' + str(portNum), ByteSrv,
                                       self.send_byte)
        #Listen to user commands to dstart or stop continuous data transfer
        self.run_flag = rospy.Subscriber('continuous_data_flag' + str(portNum),
                                         FlagMsg, self.changeFlag)
        #Service for reading and parsing one measurement
        self.measure_srv = rospy.Service('poll' + str(portNum),
                                         SensorOutputRequest, self.poll)
        #Publisher for IMU Calibration
        self.imu_cal_pub = rospy.Publisher('imu_calibration' + str(portNum),
                                           KeyValue,
                                           queue_size=1)

        #Let all the topics start properly
        rospy.sleep(1)
        self.times = []
        count = 0
        ##Run loop - do this forever in the background
        while not rospy.is_shutdown():
            self.rate.sleep()

            if self.conti_read_flag == 1:  #Continuous data transfer
                #Wait for initialization bit and matching crc-4
                if self.wait_for_packet(verbose=False):
                    parsed = self.found_init_byte()
                    try:
                        if parsed != None:
                            self.force_data_pub.publish(parsed)
                            count += 1
                        else:
                            rospy.logwarn('Error parsing data')
                    except rospy.ROSSerializationException:
                        rospy.logwarn(
                            "Error publishing. Serialization Exception caught. Continuing..."
                        )

            elif self.conti_read_flag == 0 and count != 0:  #Data transmission has just been stopped
                rospy.loginfo('Stopping Continuous Data Transfer...')
                self.port.write(
                    b'\x11\x00\x00\xC9'
                )  #11 is the byte command, C9 is the matching crc8
                self.purge()
                rospy.sleep(0.25)
                timeout = 0
                count = 0
                while self.readBytes(1) != []:
                    self.port.write(b'\x11\x00\x00\xC9')
                    self.purge()
                    rospy.sleep(0.25)
                    timeout += 1
                    if timeout == 100:
                        rospy.logwarn(
                            'Failed to stop transmission. Please try again')
                        break

            elif self.conti_read_flag == 2:  #Calibrate IMU
                self.calibrate_imu
        self.port.close()
        self.measure_srv.shutdown('Finished')
        self.user_cmds.shutdown('Finished')
示例#26
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()))
示例#27
0
文件: vna.py 项目: ahfong2006/vna2
 def __init__(self):
     self.device = ftdi.Device(mode='t', interface_select=ftdi.INTERFACE_B)
     self.device.open()
     self.lo = MAX2871()
     self.source = MAX2871()
sensor = Sensor(calMatrix)

# test all modules are working
cont = True
time.sleep(1)
sample = sensor.poll()
for cmmd in sample.sum:
    if cmmd < 0.5:
        cont = False
        print('Sum Signal too low (' + str(cmmd) + 'V)')

sensor.disconnect()

if cont:
    #Open connection to port
    s = ftdi.Device(interface_select=PORT)
    s.baudrate = BAUD
    s.ftdi_fn.ftdi_set_latency_timer(1)
    s.ftdi_fn.ftdi_set_line_property(8, 1, 0)

    #Generate byte message with sample rate
    hz = toHex(HZ)
    #print(hz)
    while not len(hz) == 4:
        hz = '0' + hz
    b = b'' + toStr([0x10, int(hz[:2], 16), int(hz[2:], 16)])

    #Start timing, write, and read
    startt = time.time()
    s.write(b)
    print('Started transmission')
示例#29
0
 def __init__(self, serial=None):
     self.dev = pylibftdi.Device(device_id=serial)
示例#30
0
 def __init__(self, device_index=0):
     self.device_index = int(device_index)
     self.device = pylibftdi.Device(device_index=device_index,
                                    interface_select=pylibftdi.INTERFACE_B)
     self.device.baudrate = 115200