1 /***************************************************************************
5 copyright : (C) 2003-2008 by Intra2net AG
6 email : opensource@intra2net.com
7 ***************************************************************************/
9 /***************************************************************************
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU Lesser General Public License *
13 * version 2.1 as published by the Free Software Foundation; *
15 ***************************************************************************/
18 \mainpage libftdi API documentation
20 Library to talk to FTDI chips. You find the latest versions of libftdi at
21 http://www.intra2net.com/en/developer/libftdi/
23 The library is easy to use. Have a look at this short example:
26 More examples can be found in the "examples" directory.
28 /** \addtogroup libftdi */
38 /* stuff needed for async write */
39 #ifdef LIBFTDI_LINUX_ASYNC_MODE
40 #include <sys/ioctl.h>
42 #include <sys/select.h>
43 #include <sys/types.h>
45 #include <linux/usbdevice_fs.h>
48 #define ftdi_error_return(code, str) do { \
49 ftdi->error_str = str; \
55 Initializes a ftdi_context.
57 \param ftdi pointer to ftdi_context
60 \retval -1: couldn't allocate read buffer
62 \remark This should be called before all functions
64 int ftdi_init(struct ftdi_context *ftdi)
69 ftdi->usb_read_timeout = 5000;
70 ftdi->usb_write_timeout = 5000;
72 ftdi->type = TYPE_BM; /* chip type */
74 ftdi->bitbang_enabled = 0;
76 ftdi->readbuffer = NULL;
77 ftdi->readbuffer_offset = 0;
78 ftdi->readbuffer_remaining = 0;
79 ftdi->writebuffer_chunksize = 4096;
85 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
87 ftdi->error_str = NULL;
89 #ifdef LIBFTDI_LINUX_ASYNC_MODE
90 ftdi->async_usb_buffer_size=10;
91 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
92 ftdi_error_return(-1, "out of memory for async usb buffer");
94 /* initialize async usb buffer with unused-marker */
95 for (i=0; i < ftdi->async_usb_buffer_size; i++)
96 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
98 ftdi->async_usb_buffer_size=0;
99 ftdi->async_usb_buffer = NULL;
102 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
104 /* All fine. Now allocate the readbuffer */
105 return ftdi_read_data_set_chunksize(ftdi, 4096);
109 Allocate and initialize a new ftdi_context
111 \return a pointer to a new ftdi_context, or NULL on failure
113 struct ftdi_context *ftdi_new(void)
115 struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
122 if (ftdi_init(ftdi) != 0)
132 Open selected channels on a chip, otherwise use first channel.
134 \param ftdi pointer to ftdi_context
135 \param interface Interface to use for FT2232C/2232H/4232H chips.
138 \retval -1: unknown interface
140 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
146 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
150 ftdi->index = INTERFACE_B;
156 ftdi->index = INTERFACE_C;
162 ftdi->index = INTERFACE_D;
167 ftdi_error_return(-1, "Unknown interface");
173 Deinitializes a ftdi_context.
175 \param ftdi pointer to ftdi_context
177 void ftdi_deinit(struct ftdi_context *ftdi)
179 if (ftdi->async_usb_buffer != NULL)
181 free(ftdi->async_usb_buffer);
182 ftdi->async_usb_buffer = NULL;
185 if (ftdi->readbuffer != NULL)
187 free(ftdi->readbuffer);
188 ftdi->readbuffer = NULL;
193 Deinitialize and free an ftdi_context.
195 \param ftdi pointer to ftdi_context
197 void ftdi_free(struct ftdi_context *ftdi)
204 Use an already open libusb device.
206 \param ftdi pointer to ftdi_context
207 \param usb libusb usb_dev_handle to use
209 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
216 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
217 needs to be deallocated by ftdi_list_free() after use.
219 \param ftdi pointer to ftdi_context
220 \param devlist Pointer where to store list of found devices
221 \param vendor Vendor ID to search for
222 \param product Product ID to search for
224 \retval >0: number of devices found
225 \retval -1: usb_find_busses() failed
226 \retval -2: usb_find_devices() failed
227 \retval -3: out of memory
229 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
231 struct ftdi_device_list **curdev;
233 struct usb_device *dev;
237 if (usb_find_busses() < 0)
238 ftdi_error_return(-1, "usb_find_busses() failed");
239 if (usb_find_devices() < 0)
240 ftdi_error_return(-2, "usb_find_devices() failed");
244 for (bus = usb_get_busses(); bus; bus = bus->next)
246 for (dev = bus->devices; dev; dev = dev->next)
248 if (dev->descriptor.idVendor == vendor
249 && dev->descriptor.idProduct == product)
251 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
253 ftdi_error_return(-3, "out of memory");
255 (*curdev)->next = NULL;
256 (*curdev)->dev = dev;
258 curdev = &(*curdev)->next;
268 Frees a usb device list.
270 \param devlist USB device list created by ftdi_usb_find_all()
272 void ftdi_list_free(struct ftdi_device_list **devlist)
274 struct ftdi_device_list *curdev, *next;
276 for (curdev = *devlist; curdev != NULL;)
287 Frees a usb device list.
289 \param devlist USB device list created by ftdi_usb_find_all()
291 void ftdi_list_free2(struct ftdi_device_list *devlist)
293 ftdi_list_free(&devlist);
297 Return device ID strings from the usb device.
299 The parameters manufacturer, description and serial may be NULL
300 or pointer to buffers to store the fetched strings.
302 \note Use this function only in combination with ftdi_usb_find_all()
303 as it closes the internal "usb_dev" after use.
305 \param ftdi pointer to ftdi_context
306 \param dev libusb usb_dev to use
307 \param manufacturer Store manufacturer string here if not NULL
308 \param mnf_len Buffer size of manufacturer string
309 \param description Store product description string here if not NULL
310 \param desc_len Buffer size of product description string
311 \param serial Store serial string here if not NULL
312 \param serial_len Buffer size of serial string
315 \retval -1: wrong arguments
316 \retval -4: unable to open device
317 \retval -7: get product manufacturer failed
318 \retval -8: get product description failed
319 \retval -9: get serial number failed
320 \retval -10: unable to close device
322 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
323 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
325 if ((ftdi==NULL) || (dev==NULL))
328 if (!(ftdi->usb_dev = usb_open(dev)))
329 ftdi_error_return(-4, usb_strerror());
331 if (manufacturer != NULL)
333 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
335 usb_close (ftdi->usb_dev);
336 ftdi_error_return(-7, usb_strerror());
340 if (description != NULL)
342 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
344 usb_close (ftdi->usb_dev);
345 ftdi_error_return(-8, usb_strerror());
351 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
353 usb_close (ftdi->usb_dev);
354 ftdi_error_return(-9, usb_strerror());
358 if (usb_close (ftdi->usb_dev) != 0)
359 ftdi_error_return(-10, usb_strerror());
365 Opens a ftdi device given by a usb_device.
367 \param ftdi pointer to ftdi_context
368 \param dev libusb usb_dev to use
371 \retval -3: unable to config device
372 \retval -4: unable to open device
373 \retval -5: unable to claim device
374 \retval -6: reset failed
375 \retval -7: set baudrate failed
377 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
379 int detach_errno = 0;
380 if (!(ftdi->usb_dev = usb_open(dev)))
381 ftdi_error_return(-4, "usb_open() failed");
383 #ifdef LIBUSB_HAS_GET_DRIVER_NP
384 // Try to detach ftdi_sio kernel module.
385 // Returns ENODATA if driver is not loaded.
387 // The return code is kept in a separate variable and only parsed
388 // if usb_set_configuration() or usb_claim_interface() fails as the
389 // detach operation might be denied and everything still works fine.
390 // Likely scenario is a static ftdi_sio kernel module.
391 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
392 detach_errno = errno;
395 // set configuration (needed especially for windows)
396 // tolerate EBUSY: one device with one configuration, but two interfaces
397 // and libftdi sessions to both interfaces (e.g. FT2232)
398 if (dev->descriptor.bNumConfigurations > 0 &&
399 usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
402 usb_close (ftdi->usb_dev);
403 if (detach_errno == EPERM)
405 ftdi_error_return(-8, "inappropriate permissions on device!");
409 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
413 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
415 usb_close (ftdi->usb_dev);
416 if (detach_errno == EPERM)
418 ftdi_error_return(-8, "inappropriate permissions on device!");
422 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
426 if (ftdi_usb_reset (ftdi) != 0)
428 usb_close (ftdi->usb_dev);
429 ftdi_error_return(-6, "ftdi_usb_reset failed");
432 if (ftdi_set_baudrate (ftdi, 9600) != 0)
434 usb_close (ftdi->usb_dev);
435 ftdi_error_return(-7, "set baudrate failed");
438 // Try to guess chip type
439 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
440 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
441 && dev->descriptor.iSerialNumber == 0))
442 ftdi->type = TYPE_BM;
443 else if (dev->descriptor.bcdDevice == 0x200)
444 ftdi->type = TYPE_AM;
445 else if (dev->descriptor.bcdDevice == 0x500)
446 ftdi->type = TYPE_2232C;
447 else if (dev->descriptor.bcdDevice == 0x600)
449 else if (dev->descriptor.bcdDevice == 0x700)
450 ftdi->type = TYPE_2232H;
451 else if (dev->descriptor.bcdDevice == 0x800)
452 ftdi->type = TYPE_4232H;
454 // Set default interface on dual/quad type chips
461 ftdi->index = INTERFACE_A;
467 ftdi_error_return(0, "all fine");
471 Opens the first device with a given vendor and product ids.
473 \param ftdi pointer to ftdi_context
474 \param vendor Vendor ID
475 \param product Product ID
477 \retval same as ftdi_usb_open_desc()
479 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
481 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
485 Opens the first device with a given, vendor id, product id,
486 description and serial.
488 \param ftdi pointer to ftdi_context
489 \param vendor Vendor ID
490 \param product Product ID
491 \param description Description to search for. Use NULL if not needed.
492 \param serial Serial to search for. Use NULL if not needed.
495 \retval -1: usb_find_busses() failed
496 \retval -2: usb_find_devices() failed
497 \retval -3: usb device not found
498 \retval -4: unable to open device
499 \retval -5: unable to claim device
500 \retval -6: reset failed
501 \retval -7: set baudrate failed
502 \retval -8: get product description failed
503 \retval -9: get serial number failed
504 \retval -10: unable to close device
506 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
507 const char* description, const char* serial)
510 struct usb_device *dev;
515 if (usb_find_busses() < 0)
516 ftdi_error_return(-1, "usb_find_busses() failed");
517 if (usb_find_devices() < 0)
518 ftdi_error_return(-2, "usb_find_devices() failed");
520 for (bus = usb_get_busses(); bus; bus = bus->next)
522 for (dev = bus->devices; dev; dev = dev->next)
524 if (dev->descriptor.idVendor == vendor
525 && dev->descriptor.idProduct == product)
527 if (!(ftdi->usb_dev = usb_open(dev)))
528 ftdi_error_return(-4, "usb_open() failed");
530 if (description != NULL)
532 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
534 usb_close (ftdi->usb_dev);
535 ftdi_error_return(-8, "unable to fetch product description");
537 if (strncmp(string, description, sizeof(string)) != 0)
539 if (usb_close (ftdi->usb_dev) != 0)
540 ftdi_error_return(-10, "unable to close device");
546 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
548 usb_close (ftdi->usb_dev);
549 ftdi_error_return(-9, "unable to fetch serial number");
551 if (strncmp(string, serial, sizeof(string)) != 0)
553 if (usb_close (ftdi->usb_dev) != 0)
554 ftdi_error_return(-10, "unable to close device");
559 if (usb_close (ftdi->usb_dev) != 0)
560 ftdi_error_return(-10, "unable to close device");
562 return ftdi_usb_open_dev(ftdi, dev);
568 ftdi_error_return(-3, "device not found");
572 Resets the ftdi device.
574 \param ftdi pointer to ftdi_context
577 \retval -1: FTDI reset failed
579 int ftdi_usb_reset(struct ftdi_context *ftdi)
581 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
582 SIO_RESET_REQUEST, SIO_RESET_SIO,
583 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
584 ftdi_error_return(-1,"FTDI reset failed");
586 // Invalidate data in the readbuffer
587 ftdi->readbuffer_offset = 0;
588 ftdi->readbuffer_remaining = 0;
594 Clears the read buffer on the chip and the internal read buffer.
596 \param ftdi pointer to ftdi_context
599 \retval -1: read buffer purge failed
601 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
603 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
604 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
605 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
606 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
608 // Invalidate data in the readbuffer
609 ftdi->readbuffer_offset = 0;
610 ftdi->readbuffer_remaining = 0;
616 Clears the write buffer on the chip.
618 \param ftdi pointer to ftdi_context
621 \retval -1: write buffer purge failed
623 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
625 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
626 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
627 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
628 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
634 Clears the buffers on the chip and the internal read buffer.
636 \param ftdi pointer to ftdi_context
639 \retval -1: read buffer purge failed
640 \retval -2: write buffer purge failed
642 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
646 result = ftdi_usb_purge_rx_buffer(ftdi);
650 result = ftdi_usb_purge_tx_buffer(ftdi);
658 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
660 \param ftdi pointer to ftdi_context
663 \retval -1: usb_release failed
664 \retval -2: usb_close failed
666 int ftdi_usb_close(struct ftdi_context *ftdi)
670 #ifdef LIBFTDI_LINUX_ASYNC_MODE
671 /* try to release some kernel resources */
672 ftdi_async_complete(ftdi,1);
675 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
678 if (usb_close (ftdi->usb_dev) != 0)
685 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
686 Function is only used internally
689 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
690 unsigned short *value, unsigned short *index)
692 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
693 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
694 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
695 int divisor, best_divisor, best_baud, best_baud_diff;
696 unsigned long encoded_divisor;
705 divisor = 24000000 / baudrate;
707 if (ftdi->type == TYPE_AM)
709 // Round down to supported fraction (AM only)
710 divisor -= am_adjust_dn[divisor & 7];
713 // Try this divisor and the one above it (because division rounds down)
717 for (i = 0; i < 2; i++)
719 int try_divisor = divisor + i;
723 // Round up to supported divisor value
724 if (try_divisor <= 8)
726 // Round up to minimum supported divisor
729 else if (ftdi->type != TYPE_AM && try_divisor < 12)
731 // BM doesn't support divisors 9 through 11 inclusive
734 else if (divisor < 16)
736 // AM doesn't support divisors 9 through 15 inclusive
741 if (ftdi->type == TYPE_AM)
743 // Round up to supported fraction (AM only)
744 try_divisor += am_adjust_up[try_divisor & 7];
745 if (try_divisor > 0x1FFF8)
747 // Round down to maximum supported divisor value (for AM)
748 try_divisor = 0x1FFF8;
753 if (try_divisor > 0x1FFFF)
755 // Round down to maximum supported divisor value (for BM)
756 try_divisor = 0x1FFFF;
760 // Get estimated baud rate (to nearest integer)
761 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
762 // Get absolute difference from requested baud rate
763 if (baud_estimate < baudrate)
765 baud_diff = baudrate - baud_estimate;
769 baud_diff = baud_estimate - baudrate;
771 if (i == 0 || baud_diff < best_baud_diff)
773 // Closest to requested baud rate so far
774 best_divisor = try_divisor;
775 best_baud = baud_estimate;
776 best_baud_diff = baud_diff;
779 // Spot on! No point trying
784 // Encode the best divisor value
785 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
786 // Deal with special cases for encoded value
787 if (encoded_divisor == 1)
789 encoded_divisor = 0; // 3000000 baud
791 else if (encoded_divisor == 0x4001)
793 encoded_divisor = 1; // 2000000 baud (BM only)
795 // Split into "value" and "index" values
796 *value = (unsigned short)(encoded_divisor & 0xFFFF);
797 if (ftdi->type == TYPE_2232C)
799 *index = (unsigned short)(encoded_divisor >> 8);
801 *index |= ftdi->index;
804 *index = (unsigned short)(encoded_divisor >> 16);
806 // Return the nearest baud rate
811 Sets the chip baud rate
813 \param ftdi pointer to ftdi_context
814 \param baudrate baud rate to set
817 \retval -1: invalid baudrate
818 \retval -2: setting baudrate failed
820 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
822 unsigned short value, index;
825 if (ftdi->bitbang_enabled)
827 baudrate = baudrate*4;
830 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
831 if (actual_baudrate <= 0)
832 ftdi_error_return (-1, "Silly baudrate <= 0.");
834 // Check within tolerance (about 5%)
835 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
836 || ((actual_baudrate < baudrate)
837 ? (actual_baudrate * 21 < baudrate * 20)
838 : (baudrate * 21 < actual_baudrate * 20)))
839 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
841 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
842 SIO_SET_BAUDRATE_REQUEST, value,
843 index, NULL, 0, ftdi->usb_write_timeout) != 0)
844 ftdi_error_return (-2, "Setting new baudrate failed");
846 ftdi->baudrate = baudrate;
851 Set (RS232) line characteristics.
852 The break type can only be set via ftdi_set_line_property2()
853 and defaults to "off".
855 \param ftdi pointer to ftdi_context
856 \param bits Number of bits
857 \param sbit Number of stop bits
858 \param parity Parity mode
861 \retval -1: Setting line property failed
863 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
864 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
866 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
870 Set (RS232) line characteristics
872 \param ftdi pointer to ftdi_context
873 \param bits Number of bits
874 \param sbit Number of stop bits
875 \param parity Parity mode
876 \param break_type Break type
879 \retval -1: Setting line property failed
881 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
882 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
883 enum ftdi_break_type break_type)
885 unsigned short value = bits;
890 value |= (0x00 << 8);
893 value |= (0x01 << 8);
896 value |= (0x02 << 8);
899 value |= (0x03 << 8);
902 value |= (0x04 << 8);
909 value |= (0x00 << 11);
912 value |= (0x01 << 11);
915 value |= (0x02 << 11);
922 value |= (0x00 << 14);
925 value |= (0x01 << 14);
929 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
930 SIO_SET_DATA_REQUEST, value,
931 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
932 ftdi_error_return (-1, "Setting new line property failed");
938 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
940 \param ftdi pointer to ftdi_context
941 \param buf Buffer with the data
942 \param size Size of the buffer
944 \retval <0: error code from usb_bulk_write()
945 \retval >0: number of bytes written
947 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
951 int total_written = 0;
953 while (offset < size)
955 int write_size = ftdi->writebuffer_chunksize;
957 if (offset+write_size > size)
958 write_size = size-offset;
960 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
962 ftdi_error_return(ret, "usb bulk write failed");
964 total_written += ret;
965 offset += write_size;
968 return total_written;
971 #ifdef LIBFTDI_LINUX_ASYNC_MODE
972 /* this is strongly dependent on libusb using the same struct layout. If libusb
973 changes in some later version this may break horribly (this is for libusb 0.1.12) */
974 struct usb_dev_handle
977 // some other stuff coming here we don't need
981 Check for pending async urbs
984 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
986 struct usbdevfs_urb *urb;
990 for (i=0; i < ftdi->async_usb_buffer_size; i++)
992 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
993 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
1001 Wait until one or more async URBs are completed by the kernel and mark their
1002 positions in the async-buffer as unused
1004 \param ftdi pointer to ftdi_context
1005 \param wait_for_more if != 0 wait for more than one write to complete
1006 \param timeout_msec max milliseconds to wait
1010 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
1013 struct usbdevfs_urb *urb=NULL;
1019 FD_SET(ftdi->usb_dev->fd, &writefds);
1021 /* init timeout only once, select writes time left after call */
1022 tv.tv_sec = timeout_msec / 1000;
1023 tv.tv_usec = (timeout_msec % 1000) * 1000;
1027 while (_usb_get_async_urbs_pending(ftdi)
1028 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1031 if (keep_going && !wait_for_more)
1033 /* don't wait if repeating only for keep_going */
1038 /* wait for timeout msec or something written ready */
1039 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1042 if (ret == 0 && urb != NULL)
1044 /* got a free urb, mark it */
1045 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1047 /* try to get more urbs that are ready now, but don't wait anymore */
1053 /* no more urbs waiting */
1061 Wait until one or more async URBs are completed by the kernel and mark their
1062 positions in the async-buffer as unused.
1064 \param ftdi pointer to ftdi_context
1065 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1067 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1069 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1073 Stupid libusb does not offer async writes nor does it allow
1074 access to its fd - so we need some hacks here.
1077 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1079 struct usbdevfs_urb *urb;
1080 int bytesdone = 0, requested;
1081 int ret, cleanup_count;
1086 /* find a free urb buffer we can use */
1088 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1090 if (i==ftdi->async_usb_buffer_size)
1092 /* wait until some buffers are free */
1093 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1096 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1098 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1099 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1100 break; /* found a free urb position */
1105 /* no free urb position found */
1109 requested = size - bytesdone;
1110 if (requested > 4096)
1113 memset(urb,0,sizeof(urb));
1115 urb->type = USBDEVFS_URB_TYPE_BULK;
1118 urb->buffer = bytes + bytesdone;
1119 urb->buffer_length = requested;
1121 urb->actual_length = 0;
1122 urb->number_of_packets = 0;
1123 urb->usercontext = 0;
1127 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1129 while (ret < 0 && errno == EINTR);
1131 return ret; /* the caller can read errno to get more info */
1133 bytesdone += requested;
1135 while (bytesdone < size);
1140 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1141 Does not wait for completion of the transfer nor does it make sure that
1142 the transfer was successful.
1144 This function could be extended to use signals and callbacks to inform the
1145 caller of completion or error - but this is not done yet, volunteers welcome.
1147 Works around libusb and directly accesses functions only available on Linux.
1148 Only available if compiled with --with-async-mode.
1150 \param ftdi pointer to ftdi_context
1151 \param buf Buffer with the data
1152 \param size Size of the buffer
1154 \retval <0: error code from usb_bulk_write()
1155 \retval >0: number of bytes written
1157 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1161 int total_written = 0;
1163 while (offset < size)
1165 int write_size = ftdi->writebuffer_chunksize;
1167 if (offset+write_size > size)
1168 write_size = size-offset;
1170 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1172 ftdi_error_return(ret, "usb bulk write async failed");
1174 total_written += ret;
1175 offset += write_size;
1178 return total_written;
1180 #endif // LIBFTDI_LINUX_ASYNC_MODE
1183 Configure write buffer chunk size.
1186 \param ftdi pointer to ftdi_context
1187 \param chunksize Chunk size
1191 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1193 ftdi->writebuffer_chunksize = chunksize;
1198 Get write buffer chunk size.
1200 \param ftdi pointer to ftdi_context
1201 \param chunksize Pointer to store chunk size in
1205 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1207 *chunksize = ftdi->writebuffer_chunksize;
1212 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1214 Automatically strips the two modem status bytes transfered during every read.
1216 \param ftdi pointer to ftdi_context
1217 \param buf Buffer to store data in
1218 \param size Size of the buffer
1220 \retval <0: error code from usb_bulk_read()
1221 \retval 0: no data was available
1222 \retval >0: number of bytes read
1224 \remark This function is not useful in bitbang mode.
1225 Use ftdi_read_pins() to get the current state of the pins.
1227 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1229 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1232 // New hi-speed devices from FTDI use a packet size of 512 bytes
1233 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1238 // everything we want is still in the readbuffer?
1239 if (size <= ftdi->readbuffer_remaining)
1241 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1244 ftdi->readbuffer_remaining -= size;
1245 ftdi->readbuffer_offset += size;
1247 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1251 // something still in the readbuffer, but not enough to satisfy 'size'?
1252 if (ftdi->readbuffer_remaining != 0)
1254 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1257 offset += ftdi->readbuffer_remaining;
1259 // do the actual USB read
1260 while (offset < size && ret > 0)
1262 ftdi->readbuffer_remaining = 0;
1263 ftdi->readbuffer_offset = 0;
1264 /* returns how much received */
1265 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1267 ftdi_error_return(ret, "usb bulk read failed");
1271 // skip FTDI status bytes.
1272 // Maybe stored in the future to enable modem use
1273 num_of_chunks = ret / packet_size;
1274 chunk_remains = ret % packet_size;
1275 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1277 ftdi->readbuffer_offset += 2;
1280 if (ret > packet_size - 2)
1282 for (i = 1; i < num_of_chunks; i++)
1283 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1284 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1286 if (chunk_remains > 2)
1288 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1289 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1291 ret -= 2*num_of_chunks;
1294 ret -= 2*(num_of_chunks-1)+chunk_remains;
1299 // no more data to read?
1304 // data still fits in buf?
1305 if (offset+ret <= size)
1307 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1308 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1311 /* Did we read exactly the right amount of bytes? */
1313 //printf("read_data exact rem %d offset %d\n",
1314 //ftdi->readbuffer_remaining, offset);
1319 // only copy part of the data or size <= readbuffer_chunksize
1320 int part_size = size-offset;
1321 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1323 ftdi->readbuffer_offset += part_size;
1324 ftdi->readbuffer_remaining = ret-part_size;
1325 offset += part_size;
1327 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1328 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1339 Configure read buffer chunk size.
1342 Automatically reallocates the buffer.
1344 \param ftdi pointer to ftdi_context
1345 \param chunksize Chunk size
1349 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1351 unsigned char *new_buf;
1353 // Invalidate all remaining data
1354 ftdi->readbuffer_offset = 0;
1355 ftdi->readbuffer_remaining = 0;
1357 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1358 ftdi_error_return(-1, "out of memory for readbuffer");
1360 ftdi->readbuffer = new_buf;
1361 ftdi->readbuffer_chunksize = chunksize;
1367 Get read buffer chunk size.
1369 \param ftdi pointer to ftdi_context
1370 \param chunksize Pointer to store chunk size in
1374 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1376 *chunksize = ftdi->readbuffer_chunksize;
1382 Enable bitbang mode.
1384 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1386 \param ftdi pointer to ftdi_context
1387 \param bitmask Bitmask to configure lines.
1388 HIGH/ON value configures a line as output.
1391 \retval -1: can't enable bitbang mode
1393 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1395 unsigned short usb_val;
1397 usb_val = bitmask; // low byte: bitmask
1398 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1399 usb_val |= (ftdi->bitbang_mode << 8);
1401 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1402 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1403 NULL, 0, ftdi->usb_write_timeout) != 0)
1404 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1406 ftdi->bitbang_enabled = 1;
1411 Disable bitbang mode.
1413 \param ftdi pointer to ftdi_context
1416 \retval -1: can't disable bitbang mode
1418 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1420 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1421 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1423 ftdi->bitbang_enabled = 0;
1428 Enable advanced bitbang mode for FT2232C chips.
1430 \param ftdi pointer to ftdi_context
1431 \param bitmask Bitmask to configure lines.
1432 HIGH/ON value configures a line as output.
1433 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1436 \retval -1: can't enable bitbang mode
1438 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1440 unsigned short usb_val;
1442 usb_val = bitmask; // low byte: bitmask
1443 usb_val |= (mode << 8);
1444 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1445 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1447 ftdi->bitbang_mode = mode;
1448 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1453 Directly read pin state. Useful for bitbang mode.
1455 \param ftdi pointer to ftdi_context
1456 \param pins Pointer to store pins into
1459 \retval -1: read pins failed
1461 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1463 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
1464 ftdi_error_return(-1, "read pins failed");
1472 The FTDI chip keeps data in the internal buffer for a specific
1473 amount of time if the buffer is not full yet to decrease
1474 load on the usb bus.
1476 \param ftdi pointer to ftdi_context
1477 \param latency Value between 1 and 255
1480 \retval -1: latency out of range
1481 \retval -2: unable to set latency timer
1483 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1485 unsigned short usb_val;
1488 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1491 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1492 ftdi_error_return(-2, "unable to set latency timer");
1500 \param ftdi pointer to ftdi_context
1501 \param latency Pointer to store latency value in
1504 \retval -1: unable to get latency timer
1506 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1508 unsigned short usb_val;
1509 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1510 ftdi_error_return(-1, "reading latency timer failed");
1512 *latency = (unsigned char)usb_val;
1517 Poll modem status information
1519 This function allows the retrieve the two status bytes of the device.
1520 The device sends these bytes also as a header for each read access
1521 where they are discarded by ftdi_read_data(). The chip generates
1522 the two stripped status bytes in the absence of data every 40 ms.
1524 Layout of the first byte:
1525 - B0..B3 - must be 0
1526 - B4 Clear to send (CTS)
1529 - B5 Data set ready (DTS)
1532 - B6 Ring indicator (RI)
1535 - B7 Receive line signal detect (RLSD)
1539 Layout of the second byte:
1540 - B0 Data ready (DR)
1541 - B1 Overrun error (OE)
1542 - B2 Parity error (PE)
1543 - B3 Framing error (FE)
1544 - B4 Break interrupt (BI)
1545 - B5 Transmitter holding register (THRE)
1546 - B6 Transmitter empty (TEMT)
1547 - B7 Error in RCVR FIFO
1549 \param ftdi pointer to ftdi_context
1550 \param status Pointer to store status information in. Must be two bytes.
1553 \retval -1: unable to retrieve status information
1555 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1559 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, usb_val, 2, ftdi->usb_read_timeout) != 2)
1560 ftdi_error_return(-1, "getting modem status failed");
1562 *status = (usb_val[1] << 8) | usb_val[0];
1568 Set flowcontrol for ftdi chip
1570 \param ftdi pointer to ftdi_context
1571 \param flowctrl flow control to use. should be
1572 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1575 \retval -1: set flow control failed
1577 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1579 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1580 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1581 NULL, 0, ftdi->usb_write_timeout) != 0)
1582 ftdi_error_return(-1, "set flow control failed");
1590 \param ftdi pointer to ftdi_context
1591 \param state state to set line to (1 or 0)
1594 \retval -1: set dtr failed
1596 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1598 unsigned short usb_val;
1601 usb_val = SIO_SET_DTR_HIGH;
1603 usb_val = SIO_SET_DTR_LOW;
1605 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1606 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1607 NULL, 0, ftdi->usb_write_timeout) != 0)
1608 ftdi_error_return(-1, "set dtr failed");
1616 \param ftdi pointer to ftdi_context
1617 \param state state to set line to (1 or 0)
1620 \retval -1 set rts failed
1622 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1624 unsigned short usb_val;
1627 usb_val = SIO_SET_RTS_HIGH;
1629 usb_val = SIO_SET_RTS_LOW;
1631 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1632 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1633 NULL, 0, ftdi->usb_write_timeout) != 0)
1634 ftdi_error_return(-1, "set of rts failed");
1640 Set dtr and rts line in one pass
1642 \param ftdi pointer to ftdi_context
1643 \param dtr DTR state to set line to (1 or 0)
1644 \param rts RTS state to set line to (1 or 0)
1647 \retval -1 set dtr/rts failed
1649 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1651 unsigned short usb_val;
1654 usb_val = SIO_SET_DTR_HIGH;
1656 usb_val = SIO_SET_DTR_LOW;
1659 usb_val |= SIO_SET_RTS_HIGH;
1661 usb_val |= SIO_SET_RTS_LOW;
1663 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1664 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1665 NULL, 0, ftdi->usb_write_timeout) != 0)
1666 ftdi_error_return(-1, "set of rts/dtr failed");
1672 Set the special event character
1674 \param ftdi pointer to ftdi_context
1675 \param eventch Event character
1676 \param enable 0 to disable the event character, non-zero otherwise
1679 \retval -1: unable to set event character
1681 int ftdi_set_event_char(struct ftdi_context *ftdi,
1682 unsigned char eventch, unsigned char enable)
1684 unsigned short usb_val;
1690 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1691 ftdi_error_return(-1, "setting event character failed");
1699 \param ftdi pointer to ftdi_context
1700 \param errorch Error character
1701 \param enable 0 to disable the error character, non-zero otherwise
1704 \retval -1: unable to set error character
1706 int ftdi_set_error_char(struct ftdi_context *ftdi,
1707 unsigned char errorch, unsigned char enable)
1709 unsigned short usb_val;
1715 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1716 ftdi_error_return(-1, "setting error character failed");
1724 \param ftdi pointer to ftdi_context
1725 \param eeprom Pointer to ftdi_eeprom
1729 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1731 ftdi->eeprom_size=size;
1736 Init eeprom with default values.
1738 \param eeprom Pointer to ftdi_eeprom
1740 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1742 eeprom->vendor_id = 0x0403;
1743 eeprom->product_id = 0x6001;
1745 eeprom->self_powered = 1;
1746 eeprom->remote_wakeup = 1;
1747 eeprom->BM_type_chip = 1;
1749 eeprom->in_is_isochronous = 0;
1750 eeprom->out_is_isochronous = 0;
1751 eeprom->suspend_pull_downs = 0;
1753 eeprom->use_serial = 0;
1754 eeprom->change_usb_version = 0;
1755 eeprom->usb_version = 0x0200;
1756 eeprom->max_power = 0;
1758 eeprom->manufacturer = NULL;
1759 eeprom->product = NULL;
1760 eeprom->serial = NULL;
1762 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1766 Build binary output from ftdi_eeprom structure.
1767 Output is suitable for ftdi_write_eeprom().
1769 \param eeprom Pointer to ftdi_eeprom
1770 \param output Buffer of 128 bytes to store eeprom image to
1772 \retval >0: used eeprom size
1773 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1775 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1778 unsigned short checksum, value;
1779 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1782 if (eeprom->manufacturer != NULL)
1783 manufacturer_size = strlen(eeprom->manufacturer);
1784 if (eeprom->product != NULL)
1785 product_size = strlen(eeprom->product);
1786 if (eeprom->serial != NULL)
1787 serial_size = strlen(eeprom->serial);
1789 size_check = eeprom->size;
1790 size_check -= 28; // 28 are always in use (fixed)
1792 // Top half of a 256byte eeprom is used just for strings and checksum
1793 // it seems that the FTDI chip will not read these strings from the lower half
1794 // Each string starts with two bytes; offset and type (0x03 for string)
1795 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1796 if (eeprom->size>=256)size_check = 120;
1797 size_check -= manufacturer_size*2;
1798 size_check -= product_size*2;
1799 size_check -= serial_size*2;
1801 // eeprom size exceeded?
1806 memset (output, 0, eeprom->size);
1808 // Addr 00: Stay 00 00
1809 // Addr 02: Vendor ID
1810 output[0x02] = eeprom->vendor_id;
1811 output[0x03] = eeprom->vendor_id >> 8;
1813 // Addr 04: Product ID
1814 output[0x04] = eeprom->product_id;
1815 output[0x05] = eeprom->product_id >> 8;
1817 // Addr 06: Device release number (0400h for BM features)
1818 output[0x06] = 0x00;
1820 if (eeprom->BM_type_chip == 1)
1821 output[0x07] = 0x04;
1823 output[0x07] = 0x02;
1825 // Addr 08: Config descriptor
1827 // Bit 6: 1 if this device is self powered, 0 if bus powered
1828 // Bit 5: 1 if this device uses remote wakeup
1829 // Bit 4: 1 if this device is battery powered
1831 if (eeprom->self_powered == 1)
1833 if (eeprom->remote_wakeup == 1)
1837 // Addr 09: Max power consumption: max power = value * 2 mA
1838 output[0x09] = eeprom->max_power;
1840 // Addr 0A: Chip configuration
1841 // Bit 7: 0 - reserved
1842 // Bit 6: 0 - reserved
1843 // Bit 5: 0 - reserved
1844 // Bit 4: 1 - Change USB version
1845 // Bit 3: 1 - Use the serial number string
1846 // Bit 2: 1 - Enable suspend pull downs for lower power
1847 // Bit 1: 1 - Out EndPoint is Isochronous
1848 // Bit 0: 1 - In EndPoint is Isochronous
1851 if (eeprom->in_is_isochronous == 1)
1853 if (eeprom->out_is_isochronous == 1)
1855 if (eeprom->suspend_pull_downs == 1)
1857 if (eeprom->use_serial == 1)
1859 if (eeprom->change_usb_version == 1)
1863 // Addr 0B: reserved
1864 output[0x0B] = 0x00;
1866 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1867 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1868 if (eeprom->change_usb_version == 1)
1870 output[0x0C] = eeprom->usb_version;
1871 output[0x0D] = eeprom->usb_version >> 8;
1875 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1876 // Addr 0F: Length of manufacturer string
1877 output[0x0F] = manufacturer_size*2 + 2;
1879 // Addr 10: Offset of the product string + 0x80, calculated later
1880 // Addr 11: Length of product string
1881 output[0x11] = product_size*2 + 2;
1883 // Addr 12: Offset of the serial string + 0x80, calculated later
1884 // Addr 13: Length of serial string
1885 output[0x13] = serial_size*2 + 2;
1889 if (eeprom->size>=256) i = 0x80;
1892 // Output manufacturer
1893 output[0x0E] = i | 0x80; // calculate offset
1894 output[i++] = manufacturer_size*2 + 2;
1895 output[i++] = 0x03; // type: string
1896 for (j = 0; j < manufacturer_size; j++)
1898 output[i] = eeprom->manufacturer[j], i++;
1899 output[i] = 0x00, i++;
1902 // Output product name
1903 output[0x10] = i | 0x80; // calculate offset
1904 output[i] = product_size*2 + 2, i++;
1905 output[i] = 0x03, i++;
1906 for (j = 0; j < product_size; j++)
1908 output[i] = eeprom->product[j], i++;
1909 output[i] = 0x00, i++;
1913 output[0x12] = i | 0x80; // calculate offset
1914 output[i] = serial_size*2 + 2, i++;
1915 output[i] = 0x03, i++;
1916 for (j = 0; j < serial_size; j++)
1918 output[i] = eeprom->serial[j], i++;
1919 output[i] = 0x00, i++;
1922 // calculate checksum
1925 for (i = 0; i < eeprom->size/2-1; i++)
1927 value = output[i*2];
1928 value += output[(i*2)+1] << 8;
1930 checksum = value^checksum;
1931 checksum = (checksum << 1) | (checksum >> 15);
1934 output[eeprom->size-2] = checksum;
1935 output[eeprom->size-1] = checksum >> 8;
1941 Decode binary EEPROM image into an ftdi_eeprom structure.
1943 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1944 \param buf Buffer of \a size bytes of raw eeprom data
1945 \param size size size of eeprom data in bytes
1948 \retval -1: something went wrong
1950 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
1951 FIXME: Strings are malloc'ed here and should be freed somewhere
1953 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
1956 unsigned short checksum, eeprom_checksum, value;
1957 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1959 int eeprom_size = 128;
1961 size_check = eeprom->size;
1962 size_check -= 28; // 28 are always in use (fixed)
1964 // Top half of a 256byte eeprom is used just for strings and checksum
1965 // it seems that the FTDI chip will not read these strings from the lower half
1966 // Each string starts with two bytes; offset and type (0x03 for string)
1967 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1968 if (eeprom->size>=256)size_check = 120;
1969 size_check -= manufacturer_size*2;
1970 size_check -= product_size*2;
1971 size_check -= serial_size*2;
1973 // eeprom size exceeded?
1978 // empty eeprom struct
1979 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
1981 // Addr 00: Stay 00 00
1983 // Addr 02: Vendor ID
1984 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
1986 // Addr 04: Product ID
1987 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
1989 value = buf[0x06] + (buf[0x07]<<8);
1993 eeprom->BM_type_chip = 1;
1996 eeprom->BM_type_chip = 0;
1998 default: // Unknown device
1999 eeprom->BM_type_chip = 0;
2003 // Addr 08: Config descriptor
2005 // Bit 6: 1 if this device is self powered, 0 if bus powered
2006 // Bit 5: 1 if this device uses remote wakeup
2007 // Bit 4: 1 if this device is battery powered
2009 if (j&0x40) eeprom->self_powered = 1;
2010 if (j&0x20) eeprom->remote_wakeup = 1;
2012 // Addr 09: Max power consumption: max power = value * 2 mA
2013 eeprom->max_power = buf[0x09];
2015 // Addr 0A: Chip configuration
2016 // Bit 7: 0 - reserved
2017 // Bit 6: 0 - reserved
2018 // Bit 5: 0 - reserved
2019 // Bit 4: 1 - Change USB version
2020 // Bit 3: 1 - Use the serial number string
2021 // Bit 2: 1 - Enable suspend pull downs for lower power
2022 // Bit 1: 1 - Out EndPoint is Isochronous
2023 // Bit 0: 1 - In EndPoint is Isochronous
2026 if (j&0x01) eeprom->in_is_isochronous = 1;
2027 if (j&0x02) eeprom->out_is_isochronous = 1;
2028 if (j&0x04) eeprom->suspend_pull_downs = 1;
2029 if (j&0x08) eeprom->use_serial = 1;
2030 if (j&0x10) eeprom->change_usb_version = 1;
2032 // Addr 0B: reserved
2034 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2035 // Addr 0D: USB version high byte when 0x0A bit 4 is set
2036 if (eeprom->change_usb_version == 1)
2038 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2041 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2042 // Addr 0F: Length of manufacturer string
2043 manufacturer_size = buf[0x0F]/2;
2044 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2045 else eeprom->manufacturer = NULL;
2047 // Addr 10: Offset of the product string + 0x80, calculated later
2048 // Addr 11: Length of product string
2049 product_size = buf[0x11]/2;
2050 if (product_size > 0) eeprom->product = malloc(product_size);
2051 else eeprom->product = NULL;
2053 // Addr 12: Offset of the serial string + 0x80, calculated later
2054 // Addr 13: Length of serial string
2055 serial_size = buf[0x13]/2;
2056 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2057 else eeprom->serial = NULL;
2059 // Decode manufacturer
2060 i = buf[0x0E] & 0x7f; // offset
2061 for (j=0;j<manufacturer_size-1;j++)
2063 eeprom->manufacturer[j] = buf[2*j+i+2];
2065 eeprom->manufacturer[j] = '\0';
2067 // Decode product name
2068 i = buf[0x10] & 0x7f; // offset
2069 for (j=0;j<product_size-1;j++)
2071 eeprom->product[j] = buf[2*j+i+2];
2073 eeprom->product[j] = '\0';
2076 i = buf[0x12] & 0x7f; // offset
2077 for (j=0;j<serial_size-1;j++)
2079 eeprom->serial[j] = buf[2*j+i+2];
2081 eeprom->serial[j] = '\0';
2086 for (i = 0; i < eeprom_size/2-1; i++)
2089 value += buf[(i*2)+1] << 8;
2091 checksum = value^checksum;
2092 checksum = (checksum << 1) | (checksum >> 15);
2095 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2097 if (eeprom_checksum != checksum)
2099 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2109 \param ftdi pointer to ftdi_context
2110 \param eeprom Pointer to store eeprom into
2113 \retval -1: read failed
2115 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2119 for (i = 0; i < ftdi->eeprom_size/2; i++)
2121 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2122 ftdi_error_return(-1, "reading eeprom failed");
2129 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2130 Function is only used internally
2133 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2135 return ((value & 1) << 1) |
2136 ((value & 2) << 5) |
2137 ((value & 4) >> 2) |
2138 ((value & 8) << 4) |
2139 ((value & 16) >> 1) |
2140 ((value & 32) >> 1) |
2141 ((value & 64) >> 4) |
2142 ((value & 128) >> 2);
2146 Read the FTDIChip-ID from R-type devices
2148 \param ftdi pointer to ftdi_context
2149 \param chipid Pointer to store FTDIChip-ID
2152 \retval -1: read failed
2154 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2156 unsigned int a = 0, b = 0;
2158 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
2160 a = a << 8 | a >> 8;
2161 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
2163 b = b << 8 | b >> 8;
2164 a = (a << 16) | (b & 0xFFFF);
2165 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2166 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2167 *chipid = a ^ 0xa5f0f7d1;
2172 ftdi_error_return(-1, "read of FTDIChip-ID failed");
2176 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2177 Call this function then do a write then call again to see if size changes, if so write again.
2179 \param ftdi pointer to ftdi_context
2180 \param eeprom Pointer to store eeprom into
2181 \param maxsize the size of the buffer to read into
2183 \retval size of eeprom
2185 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2187 int i=0,j,minsize=32;
2192 for (j = 0; i < maxsize/2 && j<size; j++)
2194 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2195 SIO_READ_EEPROM_REQUEST, 0, i,
2196 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2197 ftdi_error_return(-1, "reading eeprom failed");
2202 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2210 \param ftdi pointer to ftdi_context
2211 \param eeprom Pointer to read eeprom from
2214 \retval -1: read failed
2216 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2218 unsigned short usb_val, status;
2221 /* These commands were traced while running MProg */
2222 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2224 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2226 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2229 for (i = 0; i < ftdi->eeprom_size/2; i++)
2231 usb_val = eeprom[i*2];
2232 usb_val += eeprom[(i*2)+1] << 8;
2233 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2234 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2235 NULL, 0, ftdi->usb_write_timeout) != 0)
2236 ftdi_error_return(-1, "unable to write eeprom");
2245 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2247 \param ftdi pointer to ftdi_context
2250 \retval -1: erase failed
2252 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2254 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2255 ftdi_error_return(-1, "unable to erase eeprom");
2261 Get string representation for last error code
2263 \param ftdi pointer to ftdi_context
2265 \retval Pointer to error string
2267 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2269 return ftdi->error_str;
2272 /* @} end of doxygen libftdi group */