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()
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 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;
155 ftdi_error_return(-1, "Unknown interface");
161 Deinitializes a ftdi_context.
163 \param ftdi pointer to ftdi_context
165 void ftdi_deinit(struct ftdi_context *ftdi)
167 if (ftdi->async_usb_buffer != NULL)
169 free(ftdi->async_usb_buffer);
170 ftdi->async_usb_buffer = NULL;
173 if (ftdi->readbuffer != NULL)
175 free(ftdi->readbuffer);
176 ftdi->readbuffer = NULL;
181 Deinitialize and free an ftdi_context.
183 \param ftdi pointer to ftdi_context
185 void ftdi_free(struct ftdi_context *ftdi)
192 Use an already open libusb device.
194 \param ftdi pointer to ftdi_context
195 \param usb libusb usb_dev_handle to use
197 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
204 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
205 needs to be deallocated by ftdi_list_free() after use.
207 \param ftdi pointer to ftdi_context
208 \param devlist Pointer where to store list of found devices
209 \param vendor Vendor ID to search for
210 \param product Product ID to search for
212 \retval >0: number of devices found
213 \retval -1: usb_find_busses() failed
214 \retval -2: usb_find_devices() failed
215 \retval -3: out of memory
217 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
219 struct ftdi_device_list **curdev;
221 struct usb_device *dev;
225 if (usb_find_busses() < 0)
226 ftdi_error_return(-1, "usb_find_busses() failed");
227 if (usb_find_devices() < 0)
228 ftdi_error_return(-2, "usb_find_devices() failed");
232 for (bus = usb_get_busses(); bus; bus = bus->next)
234 for (dev = bus->devices; dev; dev = dev->next)
236 if (dev->descriptor.idVendor == vendor
237 && dev->descriptor.idProduct == product)
239 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
241 ftdi_error_return(-3, "out of memory");
243 (*curdev)->next = NULL;
244 (*curdev)->dev = dev;
246 curdev = &(*curdev)->next;
256 Frees a usb device list.
258 \param devlist USB device list created by ftdi_usb_find_all()
260 void ftdi_list_free(struct ftdi_device_list **devlist)
262 struct ftdi_device_list *curdev, *next;
264 for (curdev = *devlist; curdev != NULL;)
275 Frees a usb device list.
277 \param devlist USB device list created by ftdi_usb_find_all()
279 void ftdi_list_free2(struct ftdi_device_list *devlist)
281 ftdi_list_free(&devlist);
285 Return device ID strings from the usb device.
287 The parameters manufacturer, description and serial may be NULL
288 or pointer to buffers to store the fetched strings.
290 \note Use this function only in combination with ftdi_usb_find_all()
291 as it closes the internal "usb_dev" after use.
293 \param ftdi pointer to ftdi_context
294 \param dev libusb usb_dev to use
295 \param manufacturer Store manufacturer string here if not NULL
296 \param mnf_len Buffer size of manufacturer string
297 \param description Store product description string here if not NULL
298 \param desc_len Buffer size of product description string
299 \param serial Store serial string here if not NULL
300 \param serial_len Buffer size of serial string
303 \retval -1: wrong arguments
304 \retval -4: unable to open device
305 \retval -7: get product manufacturer failed
306 \retval -8: get product description failed
307 \retval -9: get serial number failed
308 \retval -10: unable to close device
310 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
311 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
313 if ((ftdi==NULL) || (dev==NULL))
316 if (!(ftdi->usb_dev = usb_open(dev)))
317 ftdi_error_return(-4, usb_strerror());
319 if (manufacturer != NULL)
321 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
323 usb_close (ftdi->usb_dev);
324 ftdi_error_return(-7, usb_strerror());
328 if (description != NULL)
330 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
332 usb_close (ftdi->usb_dev);
333 ftdi_error_return(-8, usb_strerror());
339 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
341 usb_close (ftdi->usb_dev);
342 ftdi_error_return(-9, usb_strerror());
346 if (usb_close (ftdi->usb_dev) != 0)
347 ftdi_error_return(-10, usb_strerror());
353 Opens a ftdi device given by a usb_device.
355 \param ftdi pointer to ftdi_context
356 \param dev libusb usb_dev to use
359 \retval -3: unable to config device
360 \retval -4: unable to open device
361 \retval -5: unable to claim device
362 \retval -6: reset failed
363 \retval -7: set baudrate failed
365 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
367 int detach_errno = 0;
368 if (!(ftdi->usb_dev = usb_open(dev)))
369 ftdi_error_return(-4, "usb_open() failed");
371 #ifdef LIBUSB_HAS_GET_DRIVER_NP
372 // Try to detach ftdi_sio kernel module.
373 // Returns ENODATA if driver is not loaded.
375 // The return code is kept in a separate variable and only parsed
376 // if usb_set_configuration() or usb_claim_interface() fails as the
377 // detach operation might be denied and everything still works fine.
378 // Likely scenario is a static ftdi_sio kernel module.
379 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
380 detach_errno = errno;
383 // set configuration (needed especially for windows)
384 // tolerate EBUSY: one device with one configuration, but two interfaces
385 // and libftdi sessions to both interfaces (e.g. FT2232)
386 if (dev->descriptor.bNumConfigurations > 0 &&
387 usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
390 usb_close (ftdi->usb_dev);
391 if (detach_errno == EPERM)
393 ftdi_error_return(-8, "inappropriate permissions on device!");
397 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
401 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
403 usb_close (ftdi->usb_dev);
404 if (detach_errno == EPERM)
406 ftdi_error_return(-8, "inappropriate permissions on device!");
410 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
414 if (ftdi_usb_reset (ftdi) != 0)
416 usb_close (ftdi->usb_dev);
417 ftdi_error_return(-6, "ftdi_usb_reset failed");
420 if (ftdi_set_baudrate (ftdi, 9600) != 0)
422 usb_close (ftdi->usb_dev);
423 ftdi_error_return(-7, "set baudrate failed");
426 // Try to guess chip type
427 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
428 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
429 && dev->descriptor.iSerialNumber == 0))
430 ftdi->type = TYPE_BM;
431 else if (dev->descriptor.bcdDevice == 0x200)
432 ftdi->type = TYPE_AM;
433 else if (dev->descriptor.bcdDevice == 0x500)
435 ftdi->type = TYPE_2232C;
437 ftdi->index = INTERFACE_A;
439 else if (dev->descriptor.bcdDevice == 0x600)
441 else if (dev->descriptor.bcdDevice == 0x700)
442 ftdi->type = TYPE_2232H;
443 else if (dev->descriptor.bcdDevice == 0x800)
444 ftdi->type = TYPE_4232H;
446 ftdi_error_return(0, "all fine");
450 Opens the first device with a given vendor and product ids.
452 \param ftdi pointer to ftdi_context
453 \param vendor Vendor ID
454 \param product Product ID
456 \retval same as ftdi_usb_open_desc()
458 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
460 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
464 Opens the first device with a given, vendor id, product id,
465 description and serial.
467 \param ftdi pointer to ftdi_context
468 \param vendor Vendor ID
469 \param product Product ID
470 \param description Description to search for. Use NULL if not needed.
471 \param serial Serial to search for. Use NULL if not needed.
474 \retval -1: usb_find_busses() failed
475 \retval -2: usb_find_devices() failed
476 \retval -3: usb device not found
477 \retval -4: unable to open device
478 \retval -5: unable to claim device
479 \retval -6: reset failed
480 \retval -7: set baudrate failed
481 \retval -8: get product description failed
482 \retval -9: get serial number failed
483 \retval -10: unable to close device
485 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
486 const char* description, const char* serial)
489 struct usb_device *dev;
494 if (usb_find_busses() < 0)
495 ftdi_error_return(-1, "usb_find_busses() failed");
496 if (usb_find_devices() < 0)
497 ftdi_error_return(-2, "usb_find_devices() failed");
499 for (bus = usb_get_busses(); bus; bus = bus->next)
501 for (dev = bus->devices; dev; dev = dev->next)
503 if (dev->descriptor.idVendor == vendor
504 && dev->descriptor.idProduct == product)
506 if (!(ftdi->usb_dev = usb_open(dev)))
507 ftdi_error_return(-4, "usb_open() failed");
509 if (description != NULL)
511 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
513 usb_close (ftdi->usb_dev);
514 ftdi_error_return(-8, "unable to fetch product description");
516 if (strncmp(string, description, sizeof(string)) != 0)
518 if (usb_close (ftdi->usb_dev) != 0)
519 ftdi_error_return(-10, "unable to close device");
525 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
527 usb_close (ftdi->usb_dev);
528 ftdi_error_return(-9, "unable to fetch serial number");
530 if (strncmp(string, serial, sizeof(string)) != 0)
532 if (usb_close (ftdi->usb_dev) != 0)
533 ftdi_error_return(-10, "unable to close device");
538 if (usb_close (ftdi->usb_dev) != 0)
539 ftdi_error_return(-10, "unable to close device");
541 return ftdi_usb_open_dev(ftdi, dev);
547 ftdi_error_return(-3, "device not found");
551 Resets the ftdi device.
553 \param ftdi pointer to ftdi_context
556 \retval -1: FTDI reset failed
558 int ftdi_usb_reset(struct ftdi_context *ftdi)
560 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
561 SIO_RESET_REQUEST, SIO_RESET_SIO,
562 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
563 ftdi_error_return(-1,"FTDI reset failed");
565 // Invalidate data in the readbuffer
566 ftdi->readbuffer_offset = 0;
567 ftdi->readbuffer_remaining = 0;
573 Clears the read buffer on the chip and the internal read buffer.
575 \param ftdi pointer to ftdi_context
578 \retval -1: read buffer purge failed
580 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
582 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
583 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
584 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
585 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
587 // Invalidate data in the readbuffer
588 ftdi->readbuffer_offset = 0;
589 ftdi->readbuffer_remaining = 0;
595 Clears the write buffer on the chip.
597 \param ftdi pointer to ftdi_context
600 \retval -1: write buffer purge failed
602 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
604 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
605 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
606 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
607 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
613 Clears the buffers on the chip and the internal read buffer.
615 \param ftdi pointer to ftdi_context
618 \retval -1: read buffer purge failed
619 \retval -2: write buffer purge failed
621 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
625 result = ftdi_usb_purge_rx_buffer(ftdi);
629 result = ftdi_usb_purge_tx_buffer(ftdi);
637 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
639 \param ftdi pointer to ftdi_context
642 \retval -1: usb_release failed
643 \retval -2: usb_close failed
645 int ftdi_usb_close(struct ftdi_context *ftdi)
649 #ifdef LIBFTDI_LINUX_ASYNC_MODE
650 /* try to release some kernel resources */
651 ftdi_async_complete(ftdi,1);
654 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
657 if (usb_close (ftdi->usb_dev) != 0)
664 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
665 Function is only used internally
668 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
669 unsigned short *value, unsigned short *index)
671 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
672 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
673 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
674 int divisor, best_divisor, best_baud, best_baud_diff;
675 unsigned long encoded_divisor;
684 divisor = 24000000 / baudrate;
686 if (ftdi->type == TYPE_AM)
688 // Round down to supported fraction (AM only)
689 divisor -= am_adjust_dn[divisor & 7];
692 // Try this divisor and the one above it (because division rounds down)
696 for (i = 0; i < 2; i++)
698 int try_divisor = divisor + i;
702 // Round up to supported divisor value
703 if (try_divisor <= 8)
705 // Round up to minimum supported divisor
708 else if (ftdi->type != TYPE_AM && try_divisor < 12)
710 // BM doesn't support divisors 9 through 11 inclusive
713 else if (divisor < 16)
715 // AM doesn't support divisors 9 through 15 inclusive
720 if (ftdi->type == TYPE_AM)
722 // Round up to supported fraction (AM only)
723 try_divisor += am_adjust_up[try_divisor & 7];
724 if (try_divisor > 0x1FFF8)
726 // Round down to maximum supported divisor value (for AM)
727 try_divisor = 0x1FFF8;
732 if (try_divisor > 0x1FFFF)
734 // Round down to maximum supported divisor value (for BM)
735 try_divisor = 0x1FFFF;
739 // Get estimated baud rate (to nearest integer)
740 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
741 // Get absolute difference from requested baud rate
742 if (baud_estimate < baudrate)
744 baud_diff = baudrate - baud_estimate;
748 baud_diff = baud_estimate - baudrate;
750 if (i == 0 || baud_diff < best_baud_diff)
752 // Closest to requested baud rate so far
753 best_divisor = try_divisor;
754 best_baud = baud_estimate;
755 best_baud_diff = baud_diff;
758 // Spot on! No point trying
763 // Encode the best divisor value
764 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
765 // Deal with special cases for encoded value
766 if (encoded_divisor == 1)
768 encoded_divisor = 0; // 3000000 baud
770 else if (encoded_divisor == 0x4001)
772 encoded_divisor = 1; // 2000000 baud (BM only)
774 // Split into "value" and "index" values
775 *value = (unsigned short)(encoded_divisor & 0xFFFF);
776 if (ftdi->type == TYPE_2232C)
778 *index = (unsigned short)(encoded_divisor >> 8);
780 *index |= ftdi->index;
783 *index = (unsigned short)(encoded_divisor >> 16);
785 // Return the nearest baud rate
790 Sets the chip baud rate
792 \param ftdi pointer to ftdi_context
793 \param baudrate baud rate to set
796 \retval -1: invalid baudrate
797 \retval -2: setting baudrate failed
799 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
801 unsigned short value, index;
804 if (ftdi->bitbang_enabled)
806 baudrate = baudrate*4;
809 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
810 if (actual_baudrate <= 0)
811 ftdi_error_return (-1, "Silly baudrate <= 0.");
813 // Check within tolerance (about 5%)
814 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
815 || ((actual_baudrate < baudrate)
816 ? (actual_baudrate * 21 < baudrate * 20)
817 : (baudrate * 21 < actual_baudrate * 20)))
818 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
820 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
821 SIO_SET_BAUDRATE_REQUEST, value,
822 index, NULL, 0, ftdi->usb_write_timeout) != 0)
823 ftdi_error_return (-2, "Setting new baudrate failed");
825 ftdi->baudrate = baudrate;
830 Set (RS232) line characteristics.
831 The break type can only be set via ftdi_set_line_property2()
832 and defaults to "off".
834 \param ftdi pointer to ftdi_context
835 \param bits Number of bits
836 \param sbit Number of stop bits
837 \param parity Parity mode
840 \retval -1: Setting line property failed
842 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
843 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
845 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
849 Set (RS232) line characteristics
851 \param ftdi pointer to ftdi_context
852 \param bits Number of bits
853 \param sbit Number of stop bits
854 \param parity Parity mode
855 \param break_type Break type
858 \retval -1: Setting line property failed
860 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
861 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
862 enum ftdi_break_type break_type)
864 unsigned short value = bits;
869 value |= (0x00 << 8);
872 value |= (0x01 << 8);
875 value |= (0x02 << 8);
878 value |= (0x03 << 8);
881 value |= (0x04 << 8);
888 value |= (0x00 << 11);
891 value |= (0x01 << 11);
894 value |= (0x02 << 11);
901 value |= (0x00 << 14);
904 value |= (0x01 << 14);
908 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
909 SIO_SET_DATA_REQUEST, value,
910 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
911 ftdi_error_return (-1, "Setting new line property failed");
917 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
919 \param ftdi pointer to ftdi_context
920 \param buf Buffer with the data
921 \param size Size of the buffer
923 \retval <0: error code from usb_bulk_write()
924 \retval >0: number of bytes written
926 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
930 int total_written = 0;
932 while (offset < size)
934 int write_size = ftdi->writebuffer_chunksize;
936 if (offset+write_size > size)
937 write_size = size-offset;
939 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
941 ftdi_error_return(ret, "usb bulk write failed");
943 total_written += ret;
944 offset += write_size;
947 return total_written;
950 #ifdef LIBFTDI_LINUX_ASYNC_MODE
951 /* this is strongly dependent on libusb using the same struct layout. If libusb
952 changes in some later version this may break horribly (this is for libusb 0.1.12) */
953 struct usb_dev_handle
956 // some other stuff coming here we don't need
960 Check for pending async urbs
963 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
965 struct usbdevfs_urb *urb;
969 for (i=0; i < ftdi->async_usb_buffer_size; i++)
971 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
972 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
980 Wait until one or more async URBs are completed by the kernel and mark their
981 positions in the async-buffer as unused
983 \param ftdi pointer to ftdi_context
984 \param wait_for_more if != 0 wait for more than one write to complete
985 \param timeout_msec max milliseconds to wait
989 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
992 struct usbdevfs_urb *urb=NULL;
998 FD_SET(ftdi->usb_dev->fd, &writefds);
1000 /* init timeout only once, select writes time left after call */
1001 tv.tv_sec = timeout_msec / 1000;
1002 tv.tv_usec = (timeout_msec % 1000) * 1000;
1006 while (_usb_get_async_urbs_pending(ftdi)
1007 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1010 if (keep_going && !wait_for_more)
1012 /* don't wait if repeating only for keep_going */
1017 /* wait for timeout msec or something written ready */
1018 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1021 if (ret == 0 && urb != NULL)
1023 /* got a free urb, mark it */
1024 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1026 /* try to get more urbs that are ready now, but don't wait anymore */
1032 /* no more urbs waiting */
1040 Wait until one or more async URBs are completed by the kernel and mark their
1041 positions in the async-buffer as unused.
1043 \param ftdi pointer to ftdi_context
1044 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1046 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1048 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1052 Stupid libusb does not offer async writes nor does it allow
1053 access to its fd - so we need some hacks here.
1056 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1058 struct usbdevfs_urb *urb;
1059 int bytesdone = 0, requested;
1060 int ret, cleanup_count;
1065 /* find a free urb buffer we can use */
1067 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1069 if (i==ftdi->async_usb_buffer_size)
1071 /* wait until some buffers are free */
1072 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1075 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1077 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1078 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1079 break; /* found a free urb position */
1084 /* no free urb position found */
1088 requested = size - bytesdone;
1089 if (requested > 4096)
1092 memset(urb,0,sizeof(urb));
1094 urb->type = USBDEVFS_URB_TYPE_BULK;
1097 urb->buffer = bytes + bytesdone;
1098 urb->buffer_length = requested;
1100 urb->actual_length = 0;
1101 urb->number_of_packets = 0;
1102 urb->usercontext = 0;
1106 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1108 while (ret < 0 && errno == EINTR);
1110 return ret; /* the caller can read errno to get more info */
1112 bytesdone += requested;
1114 while (bytesdone < size);
1119 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1120 Does not wait for completion of the transfer nor does it make sure that
1121 the transfer was successful.
1123 This function could be extended to use signals and callbacks to inform the
1124 caller of completion or error - but this is not done yet, volunteers welcome.
1126 Works around libusb and directly accesses functions only available on Linux.
1127 Only available if compiled with --with-async-mode.
1129 \param ftdi pointer to ftdi_context
1130 \param buf Buffer with the data
1131 \param size Size of the buffer
1133 \retval <0: error code from usb_bulk_write()
1134 \retval >0: number of bytes written
1136 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1140 int total_written = 0;
1142 while (offset < size)
1144 int write_size = ftdi->writebuffer_chunksize;
1146 if (offset+write_size > size)
1147 write_size = size-offset;
1149 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1151 ftdi_error_return(ret, "usb bulk write async failed");
1153 total_written += ret;
1154 offset += write_size;
1157 return total_written;
1159 #endif // LIBFTDI_LINUX_ASYNC_MODE
1162 Configure write buffer chunk size.
1165 \param ftdi pointer to ftdi_context
1166 \param chunksize Chunk size
1170 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1172 ftdi->writebuffer_chunksize = chunksize;
1177 Get write buffer chunk size.
1179 \param ftdi pointer to ftdi_context
1180 \param chunksize Pointer to store chunk size in
1184 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1186 *chunksize = ftdi->writebuffer_chunksize;
1191 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1193 Automatically strips the two modem status bytes transfered during every read.
1195 \param ftdi pointer to ftdi_context
1196 \param buf Buffer to store data in
1197 \param size Size of the buffer
1199 \retval <0: error code from usb_bulk_read()
1200 \retval 0: no data was available
1201 \retval >0: number of bytes read
1203 \remark This function is not useful in bitbang mode.
1204 Use ftdi_read_pins() to get the current state of the pins.
1206 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1208 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1211 // New hi-speed devices from FTDI use a packet size of 512 bytes
1212 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1217 // everything we want is still in the readbuffer?
1218 if (size <= ftdi->readbuffer_remaining)
1220 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1223 ftdi->readbuffer_remaining -= size;
1224 ftdi->readbuffer_offset += size;
1226 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1230 // something still in the readbuffer, but not enough to satisfy 'size'?
1231 if (ftdi->readbuffer_remaining != 0)
1233 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1236 offset += ftdi->readbuffer_remaining;
1238 // do the actual USB read
1239 while (offset < size && ret > 0)
1241 ftdi->readbuffer_remaining = 0;
1242 ftdi->readbuffer_offset = 0;
1243 /* returns how much received */
1244 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1246 ftdi_error_return(ret, "usb bulk read failed");
1250 // skip FTDI status bytes.
1251 // Maybe stored in the future to enable modem use
1252 num_of_chunks = ret / packet_size;
1253 chunk_remains = ret % packet_size;
1254 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1256 ftdi->readbuffer_offset += 2;
1259 if (ret > packet_size - 2)
1261 for (i = 1; i < num_of_chunks; i++)
1262 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1263 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1265 if (chunk_remains > 2)
1267 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1268 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1270 ret -= 2*num_of_chunks;
1273 ret -= 2*(num_of_chunks-1)+chunk_remains;
1278 // no more data to read?
1283 // data still fits in buf?
1284 if (offset+ret <= size)
1286 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1287 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1290 /* Did we read exactly the right amount of bytes? */
1292 //printf("read_data exact rem %d offset %d\n",
1293 //ftdi->readbuffer_remaining, offset);
1298 // only copy part of the data or size <= readbuffer_chunksize
1299 int part_size = size-offset;
1300 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1302 ftdi->readbuffer_offset += part_size;
1303 ftdi->readbuffer_remaining = ret-part_size;
1304 offset += part_size;
1306 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1307 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1318 Configure read buffer chunk size.
1321 Automatically reallocates the buffer.
1323 \param ftdi pointer to ftdi_context
1324 \param chunksize Chunk size
1328 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1330 unsigned char *new_buf;
1332 // Invalidate all remaining data
1333 ftdi->readbuffer_offset = 0;
1334 ftdi->readbuffer_remaining = 0;
1336 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1337 ftdi_error_return(-1, "out of memory for readbuffer");
1339 ftdi->readbuffer = new_buf;
1340 ftdi->readbuffer_chunksize = chunksize;
1346 Get read buffer chunk size.
1348 \param ftdi pointer to ftdi_context
1349 \param chunksize Pointer to store chunk size in
1353 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1355 *chunksize = ftdi->readbuffer_chunksize;
1361 Enable bitbang mode.
1363 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1365 \param ftdi pointer to ftdi_context
1366 \param bitmask Bitmask to configure lines.
1367 HIGH/ON value configures a line as output.
1370 \retval -1: can't enable bitbang mode
1372 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1374 unsigned short usb_val;
1376 usb_val = bitmask; // low byte: bitmask
1377 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1378 usb_val |= (ftdi->bitbang_mode << 8);
1380 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1381 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1382 NULL, 0, ftdi->usb_write_timeout) != 0)
1383 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1385 ftdi->bitbang_enabled = 1;
1390 Disable bitbang mode.
1392 \param ftdi pointer to ftdi_context
1395 \retval -1: can't disable bitbang mode
1397 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1399 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)
1400 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1402 ftdi->bitbang_enabled = 0;
1407 Enable advanced bitbang mode for FT2232C chips.
1409 \param ftdi pointer to ftdi_context
1410 \param bitmask Bitmask to configure lines.
1411 HIGH/ON value configures a line as output.
1412 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1415 \retval -1: can't enable bitbang mode
1417 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1419 unsigned short usb_val;
1421 usb_val = bitmask; // low byte: bitmask
1422 usb_val |= (mode << 8);
1423 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)
1424 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1426 ftdi->bitbang_mode = mode;
1427 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1432 Directly read pin state. Useful for bitbang mode.
1434 \param ftdi pointer to ftdi_context
1435 \param pins Pointer to store pins into
1438 \retval -1: read pins failed
1440 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1442 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)
1443 ftdi_error_return(-1, "read pins failed");
1451 The FTDI chip keeps data in the internal buffer for a specific
1452 amount of time if the buffer is not full yet to decrease
1453 load on the usb bus.
1455 \param ftdi pointer to ftdi_context
1456 \param latency Value between 1 and 255
1459 \retval -1: latency out of range
1460 \retval -2: unable to set latency timer
1462 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1464 unsigned short usb_val;
1467 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1470 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)
1471 ftdi_error_return(-2, "unable to set latency timer");
1479 \param ftdi pointer to ftdi_context
1480 \param latency Pointer to store latency value in
1483 \retval -1: unable to get latency timer
1485 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1487 unsigned short usb_val;
1488 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)
1489 ftdi_error_return(-1, "reading latency timer failed");
1491 *latency = (unsigned char)usb_val;
1496 Poll modem status information
1498 This function allows the retrieve the two status bytes of the device.
1499 The device sends these bytes also as a header for each read access
1500 where they are discarded by ftdi_read_data(). The chip generates
1501 the two stripped status bytes in the absence of data every 40 ms.
1503 Layout of the first byte:
1504 - B0..B3 - must be 0
1505 - B4 Clear to send (CTS)
1508 - B5 Data set ready (DTS)
1511 - B6 Ring indicator (RI)
1514 - B7 Receive line signal detect (RLSD)
1518 Layout of the second byte:
1519 - B0 Data ready (DR)
1520 - B1 Overrun error (OE)
1521 - B2 Parity error (PE)
1522 - B3 Framing error (FE)
1523 - B4 Break interrupt (BI)
1524 - B5 Transmitter holding register (THRE)
1525 - B6 Transmitter empty (TEMT)
1526 - B7 Error in RCVR FIFO
1528 \param ftdi pointer to ftdi_context
1529 \param status Pointer to store status information in. Must be two bytes.
1532 \retval -1: unable to retrieve status information
1534 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1538 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)
1539 ftdi_error_return(-1, "getting modem status failed");
1541 *status = (usb_val[1] << 8) | usb_val[0];
1547 Set flowcontrol for ftdi chip
1549 \param ftdi pointer to ftdi_context
1550 \param flowctrl flow control to use. should be
1551 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1554 \retval -1: set flow control failed
1556 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1558 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1559 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1560 NULL, 0, ftdi->usb_write_timeout) != 0)
1561 ftdi_error_return(-1, "set flow control failed");
1569 \param ftdi pointer to ftdi_context
1570 \param state state to set line to (1 or 0)
1573 \retval -1: set dtr failed
1575 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1577 unsigned short usb_val;
1580 usb_val = SIO_SET_DTR_HIGH;
1582 usb_val = SIO_SET_DTR_LOW;
1584 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1585 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1586 NULL, 0, ftdi->usb_write_timeout) != 0)
1587 ftdi_error_return(-1, "set dtr failed");
1595 \param ftdi pointer to ftdi_context
1596 \param state state to set line to (1 or 0)
1599 \retval -1 set rts failed
1601 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1603 unsigned short usb_val;
1606 usb_val = SIO_SET_RTS_HIGH;
1608 usb_val = SIO_SET_RTS_LOW;
1610 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1611 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1612 NULL, 0, ftdi->usb_write_timeout) != 0)
1613 ftdi_error_return(-1, "set of rts failed");
1619 Set dtr and rts line in one pass
1621 \param ftdi pointer to ftdi_context
1622 \param dtr DTR state to set line to (1 or 0)
1623 \param rts RTS state to set line to (1 or 0)
1626 \retval -1 set dtr/rts failed
1628 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1630 unsigned short usb_val;
1633 usb_val = SIO_SET_DTR_HIGH;
1635 usb_val = SIO_SET_DTR_LOW;
1638 usb_val |= SIO_SET_RTS_HIGH;
1640 usb_val |= SIO_SET_RTS_LOW;
1642 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1643 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1644 NULL, 0, ftdi->usb_write_timeout) != 0)
1645 ftdi_error_return(-1, "set of rts/dtr failed");
1651 Set the special event character
1653 \param ftdi pointer to ftdi_context
1654 \param eventch Event character
1655 \param enable 0 to disable the event character, non-zero otherwise
1658 \retval -1: unable to set event character
1660 int ftdi_set_event_char(struct ftdi_context *ftdi,
1661 unsigned char eventch, unsigned char enable)
1663 unsigned short usb_val;
1669 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)
1670 ftdi_error_return(-1, "setting event character failed");
1678 \param ftdi pointer to ftdi_context
1679 \param errorch Error character
1680 \param enable 0 to disable the error character, non-zero otherwise
1683 \retval -1: unable to set error character
1685 int ftdi_set_error_char(struct ftdi_context *ftdi,
1686 unsigned char errorch, unsigned char enable)
1688 unsigned short usb_val;
1694 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)
1695 ftdi_error_return(-1, "setting error character failed");
1703 \param ftdi pointer to ftdi_context
1704 \param eeprom Pointer to ftdi_eeprom
1708 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1710 ftdi->eeprom_size=size;
1715 Init eeprom with default values.
1717 \param eeprom Pointer to ftdi_eeprom
1719 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1721 eeprom->vendor_id = 0x0403;
1722 eeprom->product_id = 0x6001;
1724 eeprom->self_powered = 1;
1725 eeprom->remote_wakeup = 1;
1726 eeprom->BM_type_chip = 1;
1728 eeprom->in_is_isochronous = 0;
1729 eeprom->out_is_isochronous = 0;
1730 eeprom->suspend_pull_downs = 0;
1732 eeprom->use_serial = 0;
1733 eeprom->change_usb_version = 0;
1734 eeprom->usb_version = 0x0200;
1735 eeprom->max_power = 0;
1737 eeprom->manufacturer = NULL;
1738 eeprom->product = NULL;
1739 eeprom->serial = NULL;
1741 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1745 Build binary output from ftdi_eeprom structure.
1746 Output is suitable for ftdi_write_eeprom().
1748 \param eeprom Pointer to ftdi_eeprom
1749 \param output Buffer of 128 bytes to store eeprom image to
1751 \retval >0: used eeprom size
1752 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1754 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1757 unsigned short checksum, value;
1758 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1761 if (eeprom->manufacturer != NULL)
1762 manufacturer_size = strlen(eeprom->manufacturer);
1763 if (eeprom->product != NULL)
1764 product_size = strlen(eeprom->product);
1765 if (eeprom->serial != NULL)
1766 serial_size = strlen(eeprom->serial);
1768 size_check = eeprom->size;
1769 size_check -= 28; // 28 are always in use (fixed)
1771 // Top half of a 256byte eeprom is used just for strings and checksum
1772 // it seems that the FTDI chip will not read these strings from the lower half
1773 // Each string starts with two bytes; offset and type (0x03 for string)
1774 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1775 if (eeprom->size>=256)size_check = 120;
1776 size_check -= manufacturer_size*2;
1777 size_check -= product_size*2;
1778 size_check -= serial_size*2;
1780 // eeprom size exceeded?
1785 memset (output, 0, eeprom->size);
1787 // Addr 00: Stay 00 00
1788 // Addr 02: Vendor ID
1789 output[0x02] = eeprom->vendor_id;
1790 output[0x03] = eeprom->vendor_id >> 8;
1792 // Addr 04: Product ID
1793 output[0x04] = eeprom->product_id;
1794 output[0x05] = eeprom->product_id >> 8;
1796 // Addr 06: Device release number (0400h for BM features)
1797 output[0x06] = 0x00;
1799 if (eeprom->BM_type_chip == 1)
1800 output[0x07] = 0x04;
1802 output[0x07] = 0x02;
1804 // Addr 08: Config descriptor
1806 // Bit 6: 1 if this device is self powered, 0 if bus powered
1807 // Bit 5: 1 if this device uses remote wakeup
1808 // Bit 4: 1 if this device is battery powered
1810 if (eeprom->self_powered == 1)
1812 if (eeprom->remote_wakeup == 1)
1816 // Addr 09: Max power consumption: max power = value * 2 mA
1817 output[0x09] = eeprom->max_power;
1819 // Addr 0A: Chip configuration
1820 // Bit 7: 0 - reserved
1821 // Bit 6: 0 - reserved
1822 // Bit 5: 0 - reserved
1823 // Bit 4: 1 - Change USB version
1824 // Bit 3: 1 - Use the serial number string
1825 // Bit 2: 1 - Enable suspend pull downs for lower power
1826 // Bit 1: 1 - Out EndPoint is Isochronous
1827 // Bit 0: 1 - In EndPoint is Isochronous
1830 if (eeprom->in_is_isochronous == 1)
1832 if (eeprom->out_is_isochronous == 1)
1834 if (eeprom->suspend_pull_downs == 1)
1836 if (eeprom->use_serial == 1)
1838 if (eeprom->change_usb_version == 1)
1842 // Addr 0B: reserved
1843 output[0x0B] = 0x00;
1845 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1846 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1847 if (eeprom->change_usb_version == 1)
1849 output[0x0C] = eeprom->usb_version;
1850 output[0x0D] = eeprom->usb_version >> 8;
1854 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1855 // Addr 0F: Length of manufacturer string
1856 output[0x0F] = manufacturer_size*2 + 2;
1858 // Addr 10: Offset of the product string + 0x80, calculated later
1859 // Addr 11: Length of product string
1860 output[0x11] = product_size*2 + 2;
1862 // Addr 12: Offset of the serial string + 0x80, calculated later
1863 // Addr 13: Length of serial string
1864 output[0x13] = serial_size*2 + 2;
1868 if (eeprom->size>=256) i = 0x80;
1871 // Output manufacturer
1872 output[0x0E] = i | 0x80; // calculate offset
1873 output[i++] = manufacturer_size*2 + 2;
1874 output[i++] = 0x03; // type: string
1875 for (j = 0; j < manufacturer_size; j++)
1877 output[i] = eeprom->manufacturer[j], i++;
1878 output[i] = 0x00, i++;
1881 // Output product name
1882 output[0x10] = i | 0x80; // calculate offset
1883 output[i] = product_size*2 + 2, i++;
1884 output[i] = 0x03, i++;
1885 for (j = 0; j < product_size; j++)
1887 output[i] = eeprom->product[j], i++;
1888 output[i] = 0x00, i++;
1892 output[0x12] = i | 0x80; // calculate offset
1893 output[i] = serial_size*2 + 2, i++;
1894 output[i] = 0x03, i++;
1895 for (j = 0; j < serial_size; j++)
1897 output[i] = eeprom->serial[j], i++;
1898 output[i] = 0x00, i++;
1901 // calculate checksum
1904 for (i = 0; i < eeprom->size/2-1; i++)
1906 value = output[i*2];
1907 value += output[(i*2)+1] << 8;
1909 checksum = value^checksum;
1910 checksum = (checksum << 1) | (checksum >> 15);
1913 output[eeprom->size-2] = checksum;
1914 output[eeprom->size-1] = checksum >> 8;
1920 Decode binary EEPROM image into an ftdi_eeprom structure.
1922 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1923 \param output Buffer of \a size bytes of raw eeprom data
1924 \param size size size of eeprom data in bytes
1927 \retval -1: something went wrong
1929 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
1930 FIXME: Strings are malloc'ed here and should be freed somewhere
1932 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
1935 unsigned short checksum, eeprom_checksum, value;
1936 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1938 int eeprom_size = 128;
1940 size_check = eeprom->size;
1941 size_check -= 28; // 28 are always in use (fixed)
1943 // Top half of a 256byte eeprom is used just for strings and checksum
1944 // it seems that the FTDI chip will not read these strings from the lower half
1945 // Each string starts with two bytes; offset and type (0x03 for string)
1946 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1947 if (eeprom->size>=256)size_check = 120;
1948 size_check -= manufacturer_size*2;
1949 size_check -= product_size*2;
1950 size_check -= serial_size*2;
1952 // eeprom size exceeded?
1957 // empty eeprom struct
1958 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
1960 // Addr 00: Stay 00 00
1962 // Addr 02: Vendor ID
1963 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
1965 // Addr 04: Product ID
1966 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
1968 value = buf[0x06] + (buf[0x07]<<8);
1972 eeprom->BM_type_chip = 1;
1975 eeprom->BM_type_chip = 0;
1977 default: // Unknown device
1978 eeprom->BM_type_chip = 0;
1982 // Addr 08: Config descriptor
1984 // Bit 6: 1 if this device is self powered, 0 if bus powered
1985 // Bit 5: 1 if this device uses remote wakeup
1986 // Bit 4: 1 if this device is battery powered
1988 if (j&0x40) eeprom->self_powered = 1;
1989 if (j&0x20) eeprom->remote_wakeup = 1;
1991 // Addr 09: Max power consumption: max power = value * 2 mA
1992 eeprom->max_power = buf[0x09];
1994 // Addr 0A: Chip configuration
1995 // Bit 7: 0 - reserved
1996 // Bit 6: 0 - reserved
1997 // Bit 5: 0 - reserved
1998 // Bit 4: 1 - Change USB version
1999 // Bit 3: 1 - Use the serial number string
2000 // Bit 2: 1 - Enable suspend pull downs for lower power
2001 // Bit 1: 1 - Out EndPoint is Isochronous
2002 // Bit 0: 1 - In EndPoint is Isochronous
2005 if (j&0x01) eeprom->in_is_isochronous = 1;
2006 if (j&0x02) eeprom->out_is_isochronous = 1;
2007 if (j&0x04) eeprom->suspend_pull_downs = 1;
2008 if (j&0x08) eeprom->use_serial = 1;
2009 if (j&0x10) eeprom->change_usb_version = 1;
2011 // Addr 0B: reserved
2013 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2014 // Addr 0D: USB version high byte when 0x0A bit 4 is set
2015 if (eeprom->change_usb_version == 1)
2017 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2020 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2021 // Addr 0F: Length of manufacturer string
2022 manufacturer_size = buf[0x0F]/2;
2023 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2024 else eeprom->manufacturer = NULL;
2026 // Addr 10: Offset of the product string + 0x80, calculated later
2027 // Addr 11: Length of product string
2028 product_size = buf[0x11]/2;
2029 if (product_size > 0) eeprom->product = malloc(product_size);
2030 else eeprom->product = NULL;
2032 // Addr 12: Offset of the serial string + 0x80, calculated later
2033 // Addr 13: Length of serial string
2034 serial_size = buf[0x13]/2;
2035 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2036 else eeprom->serial = NULL;
2038 // Decode manufacturer
2039 i = buf[0x0E] & 0x7f; // offset
2040 for (j=0;j<manufacturer_size-1;j++)
2042 eeprom->manufacturer[j] = buf[2*j+i+2];
2044 eeprom->manufacturer[j] = '\0';
2046 // Decode product name
2047 i = buf[0x10] & 0x7f; // offset
2048 for (j=0;j<product_size-1;j++)
2050 eeprom->product[j] = buf[2*j+i+2];
2052 eeprom->product[j] = '\0';
2055 i = buf[0x12] & 0x7f; // offset
2056 for (j=0;j<serial_size-1;j++)
2058 eeprom->serial[j] = buf[2*j+i+2];
2060 eeprom->serial[j] = '\0';
2065 for (i = 0; i < eeprom_size/2-1; i++)
2068 value += buf[(i*2)+1] << 8;
2070 checksum = value^checksum;
2071 checksum = (checksum << 1) | (checksum >> 15);
2074 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2076 if (eeprom_checksum != checksum)
2078 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2088 \param ftdi pointer to ftdi_context
2089 \param eeprom Pointer to store eeprom into
2092 \retval -1: read failed
2094 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2098 for (i = 0; i < ftdi->eeprom_size/2; i++)
2100 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)
2101 ftdi_error_return(-1, "reading eeprom failed");
2108 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2109 Function is only used internally
2112 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2114 return ((value & 1) << 1) |
2115 ((value & 2) << 5) |
2116 ((value & 4) >> 2) |
2117 ((value & 8) << 4) |
2118 ((value & 16) >> 1) |
2119 ((value & 32) >> 1) |
2120 ((value & 64) >> 4) |
2121 ((value & 128) >> 2);
2125 Read the FTDIChip-ID from R-type devices
2127 \param ftdi pointer to ftdi_context
2128 \param chipid Pointer to store FTDIChip-ID
2131 \retval -1: read failed
2133 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2135 unsigned int a = 0, b = 0;
2137 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)
2139 a = a << 8 | a >> 8;
2140 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)
2142 b = b << 8 | b >> 8;
2143 a = (a << 16) | (b & 0xFFFF);
2144 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2145 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2146 *chipid = a ^ 0xa5f0f7d1;
2151 ftdi_error_return(-1, "read of FTDIChip-ID failed");
2155 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2156 Call this function then do a write then call again to see if size changes, if so write again.
2158 \param ftdi pointer to ftdi_context
2159 \param eeprom Pointer to store eeprom into
2160 \param maxsize the size of the buffer to read into
2162 \retval size of eeprom
2164 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2166 int i=0,j,minsize=32;
2171 for (j = 0; i < maxsize/2 && j<size; j++)
2173 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2174 SIO_READ_EEPROM_REQUEST, 0, i,
2175 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2176 ftdi_error_return(-1, "reading eeprom failed");
2181 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2189 \param ftdi pointer to ftdi_context
2190 \param eeprom Pointer to read eeprom from
2193 \retval -1: read failed
2195 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2197 unsigned short usb_val, status;
2200 /* These commands were traced while running MProg */
2201 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2203 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2205 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2208 for (i = 0; i < ftdi->eeprom_size/2; i++)
2210 usb_val = eeprom[i*2];
2211 usb_val += eeprom[(i*2)+1] << 8;
2212 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2213 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2214 NULL, 0, ftdi->usb_write_timeout) != 0)
2215 ftdi_error_return(-1, "unable to write eeprom");
2224 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2226 \param ftdi pointer to ftdi_context
2229 \retval -1: erase failed
2231 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2233 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2234 ftdi_error_return(-1, "unable to erase eeprom");
2240 Get string representation for last error code
2242 \param ftdi pointer to ftdi_context
2244 \retval Pointer to error string
2246 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2248 return ftdi->error_str;
2251 /* @} end of doxygen libftdi group */