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; \
54 Internal function to close usb device pointer.
55 Sets ftdi->usb_dev to NULL.
58 \param ftdi pointer to ftdi_context
60 \retval zero if all is fine, otherwise error code from usb_close()
62 static int ftdi_usb_close_internal (struct ftdi_context *ftdi)
68 ret = usb_close (ftdi->usb_dev);
76 Initializes a ftdi_context.
78 \param ftdi pointer to ftdi_context
81 \retval -1: couldn't allocate read buffer
83 \remark This should be called before all functions
85 int ftdi_init(struct ftdi_context *ftdi)
90 ftdi->usb_read_timeout = 5000;
91 ftdi->usb_write_timeout = 5000;
93 ftdi->type = TYPE_BM; /* chip type */
95 ftdi->bitbang_enabled = 0;
97 ftdi->readbuffer = NULL;
98 ftdi->readbuffer_offset = 0;
99 ftdi->readbuffer_remaining = 0;
100 ftdi->writebuffer_chunksize = 4096;
106 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
108 ftdi->error_str = NULL;
110 #ifdef LIBFTDI_LINUX_ASYNC_MODE
111 ftdi->async_usb_buffer_size=10;
112 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
113 ftdi_error_return(-1, "out of memory for async usb buffer");
115 /* initialize async usb buffer with unused-marker */
116 for (i=0; i < ftdi->async_usb_buffer_size; i++)
117 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
119 ftdi->async_usb_buffer_size=0;
120 ftdi->async_usb_buffer = NULL;
123 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
125 /* All fine. Now allocate the readbuffer */
126 return ftdi_read_data_set_chunksize(ftdi, 4096);
130 Allocate and initialize a new ftdi_context
132 \return a pointer to a new ftdi_context, or NULL on failure
134 struct ftdi_context *ftdi_new(void)
136 struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
143 if (ftdi_init(ftdi) != 0)
153 Open selected channels on a chip, otherwise use first channel.
155 \param ftdi pointer to ftdi_context
156 \param interface Interface to use for FT2232C/2232H/4232H chips.
159 \retval -1: unknown interface
161 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
167 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
171 ftdi->index = INTERFACE_B;
177 ftdi->index = INTERFACE_C;
183 ftdi->index = INTERFACE_D;
188 ftdi_error_return(-1, "Unknown interface");
194 Deinitializes a ftdi_context.
196 \param ftdi pointer to ftdi_context
198 void ftdi_deinit(struct ftdi_context *ftdi)
200 ftdi_usb_close_internal (ftdi);
202 if (ftdi->async_usb_buffer != NULL)
204 free(ftdi->async_usb_buffer);
205 ftdi->async_usb_buffer = NULL;
208 if (ftdi->readbuffer != NULL)
210 free(ftdi->readbuffer);
211 ftdi->readbuffer = NULL;
216 Deinitialize and free an ftdi_context.
218 \param ftdi pointer to ftdi_context
220 void ftdi_free(struct ftdi_context *ftdi)
227 Use an already open libusb device.
229 \param ftdi pointer to ftdi_context
230 \param usb libusb usb_dev_handle to use
232 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
239 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
240 needs to be deallocated by ftdi_list_free() after use.
242 \param ftdi pointer to ftdi_context
243 \param devlist Pointer where to store list of found devices
244 \param vendor Vendor ID to search for
245 \param product Product ID to search for
247 \retval >0: number of devices found
248 \retval -1: usb_find_busses() failed
249 \retval -2: usb_find_devices() failed
250 \retval -3: out of memory
252 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
254 struct ftdi_device_list **curdev;
256 struct usb_device *dev;
260 if (usb_find_busses() < 0)
261 ftdi_error_return(-1, "usb_find_busses() failed");
262 if (usb_find_devices() < 0)
263 ftdi_error_return(-2, "usb_find_devices() failed");
267 for (bus = usb_get_busses(); bus; bus = bus->next)
269 for (dev = bus->devices; dev; dev = dev->next)
271 if (dev->descriptor.idVendor == vendor
272 && dev->descriptor.idProduct == product)
274 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
276 ftdi_error_return(-3, "out of memory");
278 (*curdev)->next = NULL;
279 (*curdev)->dev = dev;
281 curdev = &(*curdev)->next;
291 Frees a usb device list.
293 \param devlist USB device list created by ftdi_usb_find_all()
295 void ftdi_list_free(struct ftdi_device_list **devlist)
297 struct ftdi_device_list *curdev, *next;
299 for (curdev = *devlist; curdev != NULL;)
310 Frees a usb device list.
312 \param devlist USB device list created by ftdi_usb_find_all()
314 void ftdi_list_free2(struct ftdi_device_list *devlist)
316 ftdi_list_free(&devlist);
320 Return device ID strings from the usb device.
322 The parameters manufacturer, description and serial may be NULL
323 or pointer to buffers to store the fetched strings.
325 \note Use this function only in combination with ftdi_usb_find_all()
326 as it closes the internal "usb_dev" after use.
328 \param ftdi pointer to ftdi_context
329 \param dev libusb usb_dev to use
330 \param manufacturer Store manufacturer string here if not NULL
331 \param mnf_len Buffer size of manufacturer string
332 \param description Store product description string here if not NULL
333 \param desc_len Buffer size of product description string
334 \param serial Store serial string here if not NULL
335 \param serial_len Buffer size of serial string
338 \retval -1: wrong arguments
339 \retval -4: unable to open device
340 \retval -7: get product manufacturer failed
341 \retval -8: get product description failed
342 \retval -9: get serial number failed
343 \retval -10: unable to close device
345 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
346 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
348 if ((ftdi==NULL) || (dev==NULL))
351 if (!(ftdi->usb_dev = usb_open(dev)))
352 ftdi_error_return(-4, usb_strerror());
354 if (manufacturer != NULL)
356 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
358 ftdi_usb_close_internal (ftdi);
359 ftdi_error_return(-7, usb_strerror());
363 if (description != NULL)
365 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
367 ftdi_usb_close_internal (ftdi);
368 ftdi_error_return(-8, usb_strerror());
374 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
376 ftdi_usb_close_internal (ftdi);
377 ftdi_error_return(-9, usb_strerror());
381 if (ftdi_usb_close_internal (ftdi) != 0)
382 ftdi_error_return(-10, usb_strerror());
388 Opens a ftdi device given by a usb_device.
390 \param ftdi pointer to ftdi_context
391 \param dev libusb usb_dev to use
394 \retval -3: unable to config device
395 \retval -4: unable to open device
396 \retval -5: unable to claim device
397 \retval -6: reset failed
398 \retval -7: set baudrate failed
400 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
402 int detach_errno = 0;
404 if (!(ftdi->usb_dev = usb_open(dev)))
405 ftdi_error_return(-4, "usb_open() failed");
407 #ifdef LIBUSB_HAS_GET_DRIVER_NP
408 // Try to detach ftdi_sio kernel module.
409 // Returns ENODATA if driver is not loaded.
411 // The return code is kept in a separate variable and only parsed
412 // if usb_set_configuration() or usb_claim_interface() fails as the
413 // detach operation might be denied and everything still works fine.
414 // Likely scenario is a static ftdi_sio kernel module.
415 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
416 detach_errno = errno;
420 // set configuration (needed especially for windows)
421 // tolerate EBUSY: one device with one configuration, but two interfaces
422 // and libftdi sessions to both interfaces (e.g. FT2232)
424 if (dev->descriptor.bNumConfigurations > 0)
426 // libusb-win32 on Windows 64 can return a null pointer for a valid device
428 config_val = dev->config[0].bConfigurationValue;
430 if (usb_set_configuration(ftdi->usb_dev, config_val) &&
433 ftdi_usb_close_internal (ftdi);
434 if (detach_errno == EPERM)
436 ftdi_error_return(-8, "inappropriate permissions on device!");
440 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
446 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
448 ftdi_usb_close_internal (ftdi);
449 if (detach_errno == EPERM)
451 ftdi_error_return(-8, "inappropriate permissions on device!");
455 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
459 if (ftdi_usb_reset (ftdi) != 0)
461 ftdi_usb_close_internal (ftdi);
462 ftdi_error_return(-6, "ftdi_usb_reset failed");
465 // Try to guess chip type
466 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
467 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
468 && dev->descriptor.iSerialNumber == 0))
469 ftdi->type = TYPE_BM;
470 else if (dev->descriptor.bcdDevice == 0x200)
471 ftdi->type = TYPE_AM;
472 else if (dev->descriptor.bcdDevice == 0x500)
473 ftdi->type = TYPE_2232C;
474 else if (dev->descriptor.bcdDevice == 0x600)
476 else if (dev->descriptor.bcdDevice == 0x700)
477 ftdi->type = TYPE_2232H;
478 else if (dev->descriptor.bcdDevice == 0x800)
479 ftdi->type = TYPE_4232H;
481 // Set default interface on dual/quad type chips
488 ftdi->index = INTERFACE_A;
494 if (ftdi_set_baudrate (ftdi, 9600) != 0)
496 ftdi_usb_close_internal (ftdi);
497 ftdi_error_return(-7, "set baudrate failed");
500 ftdi_error_return(0, "all fine");
504 Opens the first device with a given vendor and product ids.
506 \param ftdi pointer to ftdi_context
507 \param vendor Vendor ID
508 \param product Product ID
510 \retval same as ftdi_usb_open_desc()
512 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
514 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
518 Opens the first device with a given, vendor id, product id,
519 description and serial.
521 \param ftdi pointer to ftdi_context
522 \param vendor Vendor ID
523 \param product Product ID
524 \param description Description to search for. Use NULL if not needed.
525 \param serial Serial to search for. Use NULL if not needed.
528 \retval -1: usb_find_busses() failed
529 \retval -2: usb_find_devices() failed
530 \retval -3: usb device not found
531 \retval -4: unable to open device
532 \retval -5: unable to claim device
533 \retval -6: reset failed
534 \retval -7: set baudrate failed
535 \retval -8: get product description failed
536 \retval -9: get serial number failed
537 \retval -10: unable to close device
539 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
540 const char* description, const char* serial)
543 struct usb_device *dev;
548 if (usb_find_busses() < 0)
549 ftdi_error_return(-1, "usb_find_busses() failed");
550 if (usb_find_devices() < 0)
551 ftdi_error_return(-2, "usb_find_devices() failed");
553 for (bus = usb_get_busses(); bus; bus = bus->next)
555 for (dev = bus->devices; dev; dev = dev->next)
557 if (dev->descriptor.idVendor == vendor
558 && dev->descriptor.idProduct == product)
560 if (!(ftdi->usb_dev = usb_open(dev)))
561 ftdi_error_return(-4, "usb_open() failed");
563 if (description != NULL)
565 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
567 ftdi_usb_close_internal (ftdi);
568 ftdi_error_return(-8, "unable to fetch product description");
570 if (strncmp(string, description, sizeof(string)) != 0)
572 if (ftdi_usb_close_internal (ftdi) != 0)
573 ftdi_error_return(-10, "unable to close device");
579 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
581 ftdi_usb_close_internal (ftdi);
582 ftdi_error_return(-9, "unable to fetch serial number");
584 if (strncmp(string, serial, sizeof(string)) != 0)
586 if (ftdi_usb_close_internal (ftdi) != 0)
587 ftdi_error_return(-10, "unable to close device");
592 if (ftdi_usb_close_internal (ftdi) != 0)
593 ftdi_error_return(-10, "unable to close device");
595 return ftdi_usb_open_dev(ftdi, dev);
601 ftdi_error_return(-3, "device not found");
605 Resets the ftdi device.
607 \param ftdi pointer to ftdi_context
610 \retval -1: FTDI reset failed
612 int ftdi_usb_reset(struct ftdi_context *ftdi)
614 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
615 SIO_RESET_REQUEST, SIO_RESET_SIO,
616 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
617 ftdi_error_return(-1,"FTDI reset failed");
619 // Invalidate data in the readbuffer
620 ftdi->readbuffer_offset = 0;
621 ftdi->readbuffer_remaining = 0;
627 Clears the read buffer on the chip and the internal read buffer.
629 \param ftdi pointer to ftdi_context
632 \retval -1: read buffer purge failed
634 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
636 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
637 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
638 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
639 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
641 // Invalidate data in the readbuffer
642 ftdi->readbuffer_offset = 0;
643 ftdi->readbuffer_remaining = 0;
649 Clears the write buffer on the chip.
651 \param ftdi pointer to ftdi_context
654 \retval -1: write buffer purge failed
656 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
658 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
659 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
660 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
661 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
667 Clears the buffers on the chip and the internal read buffer.
669 \param ftdi pointer to ftdi_context
672 \retval -1: read buffer purge failed
673 \retval -2: write buffer purge failed
675 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
679 result = ftdi_usb_purge_rx_buffer(ftdi);
683 result = ftdi_usb_purge_tx_buffer(ftdi);
693 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
695 \param ftdi pointer to ftdi_context
698 \retval -1: usb_release failed
699 \retval -2: usb_close failed
701 int ftdi_usb_close(struct ftdi_context *ftdi)
705 #ifdef LIBFTDI_LINUX_ASYNC_MODE
706 /* try to release some kernel resources */
707 ftdi_async_complete(ftdi,1);
710 if (ftdi->usb_dev != NULL)
711 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
714 if (ftdi_usb_close_internal (ftdi) != 0)
721 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
722 Function is only used internally
725 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
726 unsigned short *value, unsigned short *index)
728 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
729 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
730 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
731 int divisor, best_divisor, best_baud, best_baud_diff;
732 unsigned long encoded_divisor;
741 divisor = 24000000 / baudrate;
743 if (ftdi->type == TYPE_AM)
745 // Round down to supported fraction (AM only)
746 divisor -= am_adjust_dn[divisor & 7];
749 // Try this divisor and the one above it (because division rounds down)
753 for (i = 0; i < 2; i++)
755 int try_divisor = divisor + i;
759 // Round up to supported divisor value
760 if (try_divisor <= 8)
762 // Round up to minimum supported divisor
765 else if (ftdi->type != TYPE_AM && try_divisor < 12)
767 // BM doesn't support divisors 9 through 11 inclusive
770 else if (divisor < 16)
772 // AM doesn't support divisors 9 through 15 inclusive
777 if (ftdi->type == TYPE_AM)
779 // Round up to supported fraction (AM only)
780 try_divisor += am_adjust_up[try_divisor & 7];
781 if (try_divisor > 0x1FFF8)
783 // Round down to maximum supported divisor value (for AM)
784 try_divisor = 0x1FFF8;
789 if (try_divisor > 0x1FFFF)
791 // Round down to maximum supported divisor value (for BM)
792 try_divisor = 0x1FFFF;
796 // Get estimated baud rate (to nearest integer)
797 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
798 // Get absolute difference from requested baud rate
799 if (baud_estimate < baudrate)
801 baud_diff = baudrate - baud_estimate;
805 baud_diff = baud_estimate - baudrate;
807 if (i == 0 || baud_diff < best_baud_diff)
809 // Closest to requested baud rate so far
810 best_divisor = try_divisor;
811 best_baud = baud_estimate;
812 best_baud_diff = baud_diff;
815 // Spot on! No point trying
820 // Encode the best divisor value
821 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
822 // Deal with special cases for encoded value
823 if (encoded_divisor == 1)
825 encoded_divisor = 0; // 3000000 baud
827 else if (encoded_divisor == 0x4001)
829 encoded_divisor = 1; // 2000000 baud (BM only)
831 // Split into "value" and "index" values
832 *value = (unsigned short)(encoded_divisor & 0xFFFF);
833 if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
835 *index = (unsigned short)(encoded_divisor >> 8);
837 *index |= ftdi->index;
840 *index = (unsigned short)(encoded_divisor >> 16);
842 // Return the nearest baud rate
847 Sets the chip baud rate
849 \param ftdi pointer to ftdi_context
850 \param baudrate baud rate to set
853 \retval -1: invalid baudrate
854 \retval -2: setting baudrate failed
856 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
858 unsigned short value, index;
861 if (ftdi->bitbang_enabled)
863 baudrate = baudrate*4;
866 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
867 if (actual_baudrate <= 0)
868 ftdi_error_return (-1, "Silly baudrate <= 0.");
870 // Check within tolerance (about 5%)
871 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
872 || ((actual_baudrate < baudrate)
873 ? (actual_baudrate * 21 < baudrate * 20)
874 : (baudrate * 21 < actual_baudrate * 20)))
875 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
877 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
878 SIO_SET_BAUDRATE_REQUEST, value,
879 index, NULL, 0, ftdi->usb_write_timeout) != 0)
880 ftdi_error_return (-2, "Setting new baudrate failed");
882 ftdi->baudrate = baudrate;
887 Set (RS232) line characteristics.
888 The break type can only be set via ftdi_set_line_property2()
889 and defaults to "off".
891 \param ftdi pointer to ftdi_context
892 \param bits Number of bits
893 \param sbit Number of stop bits
894 \param parity Parity mode
897 \retval -1: Setting line property failed
899 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
900 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
902 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
906 Set (RS232) line characteristics
908 \param ftdi pointer to ftdi_context
909 \param bits Number of bits
910 \param sbit Number of stop bits
911 \param parity Parity mode
912 \param break_type Break type
915 \retval -1: Setting line property failed
917 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
918 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
919 enum ftdi_break_type break_type)
921 unsigned short value = bits;
926 value |= (0x00 << 8);
929 value |= (0x01 << 8);
932 value |= (0x02 << 8);
935 value |= (0x03 << 8);
938 value |= (0x04 << 8);
945 value |= (0x00 << 11);
948 value |= (0x01 << 11);
951 value |= (0x02 << 11);
958 value |= (0x00 << 14);
961 value |= (0x01 << 14);
965 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
966 SIO_SET_DATA_REQUEST, value,
967 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
968 ftdi_error_return (-1, "Setting new line property failed");
974 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
976 \param ftdi pointer to ftdi_context
977 \param buf Buffer with the data
978 \param size Size of the buffer
980 \retval <0: error code from usb_bulk_write()
981 \retval >0: number of bytes written
983 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
987 int total_written = 0;
989 while (offset < size)
991 int write_size = ftdi->writebuffer_chunksize;
993 if (offset+write_size > size)
994 write_size = size-offset;
996 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
998 ftdi_error_return(ret, "usb bulk write failed");
1000 total_written += ret;
1001 offset += write_size;
1004 return total_written;
1007 #ifdef LIBFTDI_LINUX_ASYNC_MODE
1008 #ifdef USB_CLASS_PTP
1009 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
1011 /* this is strongly dependent on libusb using the same struct layout. If libusb
1012 changes in some later version this may break horribly (this is for libusb 0.1.12) */
1013 struct usb_dev_handle
1016 // some other stuff coming here we don't need
1020 Check for pending async urbs
1023 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
1025 struct usbdevfs_urb *urb;
1029 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1031 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1032 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
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
1045 \param timeout_msec max milliseconds to wait
1049 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
1052 struct usbdevfs_urb *urb=NULL;
1058 FD_SET(ftdi->usb_dev->fd, &writefds);
1060 /* init timeout only once, select writes time left after call */
1061 tv.tv_sec = timeout_msec / 1000;
1062 tv.tv_usec = (timeout_msec % 1000) * 1000;
1066 while (_usb_get_async_urbs_pending(ftdi)
1067 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1070 if (keep_going && !wait_for_more)
1072 /* don't wait if repeating only for keep_going */
1077 /* wait for timeout msec or something written ready */
1078 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1081 if (ret == 0 && urb != NULL)
1083 /* got a free urb, mark it */
1084 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1086 /* try to get more urbs that are ready now, but don't wait anymore */
1092 /* no more urbs waiting */
1100 Wait until one or more async URBs are completed by the kernel and mark their
1101 positions in the async-buffer as unused.
1103 \param ftdi pointer to ftdi_context
1104 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1106 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1108 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1112 Stupid libusb does not offer async writes nor does it allow
1113 access to its fd - so we need some hacks here.
1116 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1118 struct usbdevfs_urb *urb;
1119 int bytesdone = 0, requested;
1120 int ret, cleanup_count;
1125 /* find a free urb buffer we can use */
1127 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1129 if (i==ftdi->async_usb_buffer_size)
1131 /* wait until some buffers are free */
1132 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1135 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1137 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1138 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1139 break; /* found a free urb position */
1144 /* no free urb position found */
1148 requested = size - bytesdone;
1149 if (requested > 4096)
1152 memset(urb,0,sizeof(urb));
1154 urb->type = USBDEVFS_URB_TYPE_BULK;
1157 urb->buffer = bytes + bytesdone;
1158 urb->buffer_length = requested;
1160 urb->actual_length = 0;
1161 urb->number_of_packets = 0;
1162 urb->usercontext = 0;
1166 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1168 while (ret < 0 && errno == EINTR);
1170 return ret; /* the caller can read errno to get more info */
1172 bytesdone += requested;
1174 while (bytesdone < size);
1179 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1180 Does not wait for completion of the transfer nor does it make sure that
1181 the transfer was successful.
1183 This function could be extended to use signals and callbacks to inform the
1184 caller of completion or error - but this is not done yet, volunteers welcome.
1186 Works around libusb and directly accesses functions only available on Linux.
1187 Only available if compiled with --with-async-mode.
1189 \param ftdi pointer to ftdi_context
1190 \param buf Buffer with the data
1191 \param size Size of the buffer
1193 \retval <0: error code from usb_bulk_write()
1194 \retval >0: number of bytes written
1196 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1200 int total_written = 0;
1202 while (offset < size)
1204 int write_size = ftdi->writebuffer_chunksize;
1206 if (offset+write_size > size)
1207 write_size = size-offset;
1209 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1211 ftdi_error_return(ret, "usb bulk write async failed");
1213 total_written += ret;
1214 offset += write_size;
1217 return total_written;
1219 #endif // LIBFTDI_LINUX_ASYNC_MODE
1222 Configure write buffer chunk size.
1225 \param ftdi pointer to ftdi_context
1226 \param chunksize Chunk size
1230 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1232 ftdi->writebuffer_chunksize = chunksize;
1237 Get write buffer chunk size.
1239 \param ftdi pointer to ftdi_context
1240 \param chunksize Pointer to store chunk size in
1244 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1246 *chunksize = ftdi->writebuffer_chunksize;
1251 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1253 Automatically strips the two modem status bytes transfered during every read.
1255 \param ftdi pointer to ftdi_context
1256 \param buf Buffer to store data in
1257 \param size Size of the buffer
1259 \retval <0: error code from usb_bulk_read()
1260 \retval 0: no data was available
1261 \retval >0: number of bytes read
1263 \remark This function is not useful in bitbang mode.
1264 Use ftdi_read_pins() to get the current state of the pins.
1266 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1268 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1271 // New hi-speed devices from FTDI use a packet size of 512 bytes
1272 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1277 // everything we want is still in the readbuffer?
1278 if (size <= ftdi->readbuffer_remaining)
1280 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1283 ftdi->readbuffer_remaining -= size;
1284 ftdi->readbuffer_offset += size;
1286 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1290 // something still in the readbuffer, but not enough to satisfy 'size'?
1291 if (ftdi->readbuffer_remaining != 0)
1293 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1296 offset += ftdi->readbuffer_remaining;
1298 // do the actual USB read
1299 while (offset < size && ret > 0)
1301 ftdi->readbuffer_remaining = 0;
1302 ftdi->readbuffer_offset = 0;
1303 /* returns how much received */
1304 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1306 ftdi_error_return(ret, "usb bulk read failed");
1310 // skip FTDI status bytes.
1311 // Maybe stored in the future to enable modem use
1312 num_of_chunks = ret / packet_size;
1313 chunk_remains = ret % packet_size;
1314 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1316 ftdi->readbuffer_offset += 2;
1319 if (ret > packet_size - 2)
1321 for (i = 1; i < num_of_chunks; i++)
1322 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1323 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1325 if (chunk_remains > 2)
1327 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1328 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1330 ret -= 2*num_of_chunks;
1333 ret -= 2*(num_of_chunks-1)+chunk_remains;
1338 // no more data to read?
1343 // data still fits in buf?
1344 if (offset+ret <= size)
1346 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1347 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1350 /* Did we read exactly the right amount of bytes? */
1352 //printf("read_data exact rem %d offset %d\n",
1353 //ftdi->readbuffer_remaining, offset);
1358 // only copy part of the data or size <= readbuffer_chunksize
1359 int part_size = size-offset;
1360 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1362 ftdi->readbuffer_offset += part_size;
1363 ftdi->readbuffer_remaining = ret-part_size;
1364 offset += part_size;
1366 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1367 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1378 Configure read buffer chunk size.
1381 Automatically reallocates the buffer.
1383 \param ftdi pointer to ftdi_context
1384 \param chunksize Chunk size
1388 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1390 unsigned char *new_buf;
1392 // Invalidate all remaining data
1393 ftdi->readbuffer_offset = 0;
1394 ftdi->readbuffer_remaining = 0;
1396 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1397 ftdi_error_return(-1, "out of memory for readbuffer");
1399 ftdi->readbuffer = new_buf;
1400 ftdi->readbuffer_chunksize = chunksize;
1406 Get read buffer chunk size.
1408 \param ftdi pointer to ftdi_context
1409 \param chunksize Pointer to store chunk size in
1413 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1415 *chunksize = ftdi->readbuffer_chunksize;
1421 Enable bitbang mode.
1423 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1425 \param ftdi pointer to ftdi_context
1426 \param bitmask Bitmask to configure lines.
1427 HIGH/ON value configures a line as output.
1430 \retval -1: can't enable bitbang mode
1432 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1434 unsigned short usb_val;
1436 usb_val = bitmask; // low byte: bitmask
1437 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1438 usb_val |= (ftdi->bitbang_mode << 8);
1440 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1441 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1442 NULL, 0, ftdi->usb_write_timeout) != 0)
1443 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1445 ftdi->bitbang_enabled = 1;
1450 Disable bitbang mode.
1452 \param ftdi pointer to ftdi_context
1455 \retval -1: can't disable bitbang mode
1457 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1459 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)
1460 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1462 ftdi->bitbang_enabled = 0;
1467 Enable advanced bitbang mode for FT2232C chips.
1469 \param ftdi pointer to ftdi_context
1470 \param bitmask Bitmask to configure lines.
1471 HIGH/ON value configures a line as output.
1472 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1475 \retval -1: can't enable bitbang mode
1477 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1479 unsigned short usb_val;
1481 usb_val = bitmask; // low byte: bitmask
1482 usb_val |= (mode << 8);
1483 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)
1484 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1486 ftdi->bitbang_mode = mode;
1487 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1492 Directly read pin state. Useful for bitbang mode.
1494 \param ftdi pointer to ftdi_context
1495 \param pins Pointer to store pins into
1498 \retval -1: read pins failed
1500 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1502 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)
1503 ftdi_error_return(-1, "read pins failed");
1511 The FTDI chip keeps data in the internal buffer for a specific
1512 amount of time if the buffer is not full yet to decrease
1513 load on the usb bus.
1515 \param ftdi pointer to ftdi_context
1516 \param latency Value between 1 and 255
1519 \retval -1: latency out of range
1520 \retval -2: unable to set latency timer
1522 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1524 unsigned short usb_val;
1527 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1530 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)
1531 ftdi_error_return(-2, "unable to set latency timer");
1539 \param ftdi pointer to ftdi_context
1540 \param latency Pointer to store latency value in
1543 \retval -1: unable to get latency timer
1545 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1547 unsigned short usb_val;
1548 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)
1549 ftdi_error_return(-1, "reading latency timer failed");
1551 *latency = (unsigned char)usb_val;
1556 Poll modem status information
1558 This function allows the retrieve the two status bytes of the device.
1559 The device sends these bytes also as a header for each read access
1560 where they are discarded by ftdi_read_data(). The chip generates
1561 the two stripped status bytes in the absence of data every 40 ms.
1563 Layout of the first byte:
1564 - B0..B3 - must be 0
1565 - B4 Clear to send (CTS)
1568 - B5 Data set ready (DTS)
1571 - B6 Ring indicator (RI)
1574 - B7 Receive line signal detect (RLSD)
1578 Layout of the second byte:
1579 - B0 Data ready (DR)
1580 - B1 Overrun error (OE)
1581 - B2 Parity error (PE)
1582 - B3 Framing error (FE)
1583 - B4 Break interrupt (BI)
1584 - B5 Transmitter holding register (THRE)
1585 - B6 Transmitter empty (TEMT)
1586 - B7 Error in RCVR FIFO
1588 \param ftdi pointer to ftdi_context
1589 \param status Pointer to store status information in. Must be two bytes.
1592 \retval -1: unable to retrieve status information
1594 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1598 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)
1599 ftdi_error_return(-1, "getting modem status failed");
1601 *status = (usb_val[1] << 8) | usb_val[0];
1607 Set flowcontrol for ftdi chip
1609 \param ftdi pointer to ftdi_context
1610 \param flowctrl flow control to use. should be
1611 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1614 \retval -1: set flow control failed
1616 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1618 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1619 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1620 NULL, 0, ftdi->usb_write_timeout) != 0)
1621 ftdi_error_return(-1, "set flow control failed");
1629 \param ftdi pointer to ftdi_context
1630 \param state state to set line to (1 or 0)
1633 \retval -1: set dtr failed
1635 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1637 unsigned short usb_val;
1640 usb_val = SIO_SET_DTR_HIGH;
1642 usb_val = SIO_SET_DTR_LOW;
1644 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1645 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1646 NULL, 0, ftdi->usb_write_timeout) != 0)
1647 ftdi_error_return(-1, "set dtr failed");
1655 \param ftdi pointer to ftdi_context
1656 \param state state to set line to (1 or 0)
1659 \retval -1 set rts failed
1661 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1663 unsigned short usb_val;
1666 usb_val = SIO_SET_RTS_HIGH;
1668 usb_val = SIO_SET_RTS_LOW;
1670 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1671 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1672 NULL, 0, ftdi->usb_write_timeout) != 0)
1673 ftdi_error_return(-1, "set of rts failed");
1679 Set dtr and rts line in one pass
1681 \param ftdi pointer to ftdi_context
1682 \param dtr DTR state to set line to (1 or 0)
1683 \param rts RTS state to set line to (1 or 0)
1686 \retval -1 set dtr/rts failed
1688 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1690 unsigned short usb_val;
1693 usb_val = SIO_SET_DTR_HIGH;
1695 usb_val = SIO_SET_DTR_LOW;
1698 usb_val |= SIO_SET_RTS_HIGH;
1700 usb_val |= SIO_SET_RTS_LOW;
1702 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1703 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1704 NULL, 0, ftdi->usb_write_timeout) != 0)
1705 ftdi_error_return(-1, "set of rts/dtr failed");
1711 Set the special event character
1713 \param ftdi pointer to ftdi_context
1714 \param eventch Event character
1715 \param enable 0 to disable the event character, non-zero otherwise
1718 \retval -1: unable to set event character
1720 int ftdi_set_event_char(struct ftdi_context *ftdi,
1721 unsigned char eventch, unsigned char enable)
1723 unsigned short usb_val;
1729 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)
1730 ftdi_error_return(-1, "setting event character failed");
1738 \param ftdi pointer to ftdi_context
1739 \param errorch Error character
1740 \param enable 0 to disable the error character, non-zero otherwise
1743 \retval -1: unable to set error character
1745 int ftdi_set_error_char(struct ftdi_context *ftdi,
1746 unsigned char errorch, unsigned char enable)
1748 unsigned short usb_val;
1754 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)
1755 ftdi_error_return(-1, "setting error character failed");
1763 \param ftdi pointer to ftdi_context
1764 \param eeprom Pointer to ftdi_eeprom
1768 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1770 ftdi->eeprom_size=size;
1775 Init eeprom with default values.
1777 \param eeprom Pointer to ftdi_eeprom
1779 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1781 eeprom->vendor_id = 0x0403;
1782 eeprom->product_id = 0x6001;
1784 eeprom->self_powered = 1;
1785 eeprom->remote_wakeup = 1;
1786 eeprom->BM_type_chip = 1;
1788 eeprom->in_is_isochronous = 0;
1789 eeprom->out_is_isochronous = 0;
1790 eeprom->suspend_pull_downs = 0;
1792 eeprom->use_serial = 0;
1793 eeprom->change_usb_version = 0;
1794 eeprom->usb_version = 0x0200;
1795 eeprom->max_power = 0;
1797 eeprom->manufacturer = NULL;
1798 eeprom->product = NULL;
1799 eeprom->serial = NULL;
1801 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1805 Build binary output from ftdi_eeprom structure.
1806 Output is suitable for ftdi_write_eeprom().
1808 \param eeprom Pointer to ftdi_eeprom
1809 \param output Buffer of 128 bytes to store eeprom image to
1811 \retval >0: used eeprom size
1812 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1814 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1817 unsigned short checksum, value;
1818 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1821 if (eeprom->manufacturer != NULL)
1822 manufacturer_size = strlen(eeprom->manufacturer);
1823 if (eeprom->product != NULL)
1824 product_size = strlen(eeprom->product);
1825 if (eeprom->serial != NULL)
1826 serial_size = strlen(eeprom->serial);
1828 size_check = eeprom->size;
1829 size_check -= 28; // 28 are always in use (fixed)
1831 // Top half of a 256byte eeprom is used just for strings and checksum
1832 // it seems that the FTDI chip will not read these strings from the lower half
1833 // Each string starts with two bytes; offset and type (0x03 for string)
1834 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1835 if (eeprom->size>=256)size_check = 120;
1836 size_check -= manufacturer_size*2;
1837 size_check -= product_size*2;
1838 size_check -= serial_size*2;
1840 // eeprom size exceeded?
1845 memset (output, 0, eeprom->size);
1847 // Addr 00: Stay 00 00
1848 // Addr 02: Vendor ID
1849 output[0x02] = eeprom->vendor_id;
1850 output[0x03] = eeprom->vendor_id >> 8;
1852 // Addr 04: Product ID
1853 output[0x04] = eeprom->product_id;
1854 output[0x05] = eeprom->product_id >> 8;
1856 // Addr 06: Device release number (0400h for BM features)
1857 output[0x06] = 0x00;
1859 if (eeprom->BM_type_chip == 1)
1860 output[0x07] = 0x04;
1862 output[0x07] = 0x02;
1864 // Addr 08: Config descriptor
1866 // Bit 6: 1 if this device is self powered, 0 if bus powered
1867 // Bit 5: 1 if this device uses remote wakeup
1868 // Bit 4: 1 if this device is battery powered
1870 if (eeprom->self_powered == 1)
1872 if (eeprom->remote_wakeup == 1)
1876 // Addr 09: Max power consumption: max power = value * 2 mA
1877 output[0x09] = eeprom->max_power;
1879 // Addr 0A: Chip configuration
1880 // Bit 7: 0 - reserved
1881 // Bit 6: 0 - reserved
1882 // Bit 5: 0 - reserved
1883 // Bit 4: 1 - Change USB version
1884 // Bit 3: 1 - Use the serial number string
1885 // Bit 2: 1 - Enable suspend pull downs for lower power
1886 // Bit 1: 1 - Out EndPoint is Isochronous
1887 // Bit 0: 1 - In EndPoint is Isochronous
1890 if (eeprom->in_is_isochronous == 1)
1892 if (eeprom->out_is_isochronous == 1)
1894 if (eeprom->suspend_pull_downs == 1)
1896 if (eeprom->use_serial == 1)
1898 if (eeprom->change_usb_version == 1)
1902 // Addr 0B: reserved
1903 output[0x0B] = 0x00;
1905 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1906 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1907 if (eeprom->change_usb_version == 1)
1909 output[0x0C] = eeprom->usb_version;
1910 output[0x0D] = eeprom->usb_version >> 8;
1914 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1915 // Addr 0F: Length of manufacturer string
1916 output[0x0F] = manufacturer_size*2 + 2;
1918 // Addr 10: Offset of the product string + 0x80, calculated later
1919 // Addr 11: Length of product string
1920 output[0x11] = product_size*2 + 2;
1922 // Addr 12: Offset of the serial string + 0x80, calculated later
1923 // Addr 13: Length of serial string
1924 output[0x13] = serial_size*2 + 2;
1928 if (eeprom->size>=256) i = 0x80;
1931 // Output manufacturer
1932 output[0x0E] = i | 0x80; // calculate offset
1933 output[i++] = manufacturer_size*2 + 2;
1934 output[i++] = 0x03; // type: string
1935 for (j = 0; j < manufacturer_size; j++)
1937 output[i] = eeprom->manufacturer[j], i++;
1938 output[i] = 0x00, i++;
1941 // Output product name
1942 output[0x10] = i | 0x80; // calculate offset
1943 output[i] = product_size*2 + 2, i++;
1944 output[i] = 0x03, i++;
1945 for (j = 0; j < product_size; j++)
1947 output[i] = eeprom->product[j], i++;
1948 output[i] = 0x00, i++;
1952 output[0x12] = i | 0x80; // calculate offset
1953 output[i] = serial_size*2 + 2, i++;
1954 output[i] = 0x03, i++;
1955 for (j = 0; j < serial_size; j++)
1957 output[i] = eeprom->serial[j], i++;
1958 output[i] = 0x00, i++;
1961 // calculate checksum
1964 for (i = 0; i < eeprom->size/2-1; i++)
1966 value = output[i*2];
1967 value += output[(i*2)+1] << 8;
1969 checksum = value^checksum;
1970 checksum = (checksum << 1) | (checksum >> 15);
1973 output[eeprom->size-2] = checksum;
1974 output[eeprom->size-1] = checksum >> 8;
1980 Decode binary EEPROM image into an ftdi_eeprom structure.
1982 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1983 \param buf Buffer of \a size bytes of raw eeprom data
1984 \param size size size of eeprom data in bytes
1987 \retval -1: something went wrong
1989 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
1990 FIXME: Strings are malloc'ed here and should be freed somewhere
1992 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
1995 unsigned short checksum, eeprom_checksum, value;
1996 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1998 int eeprom_size = 128;
2000 size_check = eeprom->size;
2001 size_check -= 28; // 28 are always in use (fixed)
2003 // Top half of a 256byte eeprom is used just for strings and checksum
2004 // it seems that the FTDI chip will not read these strings from the lower half
2005 // Each string starts with two bytes; offset and type (0x03 for string)
2006 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
2007 if (eeprom->size>=256)size_check = 120;
2008 size_check -= manufacturer_size*2;
2009 size_check -= product_size*2;
2010 size_check -= serial_size*2;
2012 // eeprom size exceeded?
2017 // empty eeprom struct
2018 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2020 // Addr 00: Stay 00 00
2022 // Addr 02: Vendor ID
2023 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2025 // Addr 04: Product ID
2026 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2028 value = buf[0x06] + (buf[0x07]<<8);
2032 eeprom->BM_type_chip = 1;
2035 eeprom->BM_type_chip = 0;
2037 default: // Unknown device
2038 eeprom->BM_type_chip = 0;
2042 // Addr 08: Config descriptor
2044 // Bit 6: 1 if this device is self powered, 0 if bus powered
2045 // Bit 5: 1 if this device uses remote wakeup
2046 // Bit 4: 1 if this device is battery powered
2048 if (j&0x40) eeprom->self_powered = 1;
2049 if (j&0x20) eeprom->remote_wakeup = 1;
2051 // Addr 09: Max power consumption: max power = value * 2 mA
2052 eeprom->max_power = buf[0x09];
2054 // Addr 0A: Chip configuration
2055 // Bit 7: 0 - reserved
2056 // Bit 6: 0 - reserved
2057 // Bit 5: 0 - reserved
2058 // Bit 4: 1 - Change USB version
2059 // Bit 3: 1 - Use the serial number string
2060 // Bit 2: 1 - Enable suspend pull downs for lower power
2061 // Bit 1: 1 - Out EndPoint is Isochronous
2062 // Bit 0: 1 - In EndPoint is Isochronous
2065 if (j&0x01) eeprom->in_is_isochronous = 1;
2066 if (j&0x02) eeprom->out_is_isochronous = 1;
2067 if (j&0x04) eeprom->suspend_pull_downs = 1;
2068 if (j&0x08) eeprom->use_serial = 1;
2069 if (j&0x10) eeprom->change_usb_version = 1;
2071 // Addr 0B: reserved
2073 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2074 // Addr 0D: USB version high byte when 0x0A bit 4 is set
2075 if (eeprom->change_usb_version == 1)
2077 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2080 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2081 // Addr 0F: Length of manufacturer string
2082 manufacturer_size = buf[0x0F]/2;
2083 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2084 else eeprom->manufacturer = NULL;
2086 // Addr 10: Offset of the product string + 0x80, calculated later
2087 // Addr 11: Length of product string
2088 product_size = buf[0x11]/2;
2089 if (product_size > 0) eeprom->product = malloc(product_size);
2090 else eeprom->product = NULL;
2092 // Addr 12: Offset of the serial string + 0x80, calculated later
2093 // Addr 13: Length of serial string
2094 serial_size = buf[0x13]/2;
2095 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2096 else eeprom->serial = NULL;
2098 // Decode manufacturer
2099 i = buf[0x0E] & 0x7f; // offset
2100 for (j=0;j<manufacturer_size-1;j++)
2102 eeprom->manufacturer[j] = buf[2*j+i+2];
2104 eeprom->manufacturer[j] = '\0';
2106 // Decode product name
2107 i = buf[0x10] & 0x7f; // offset
2108 for (j=0;j<product_size-1;j++)
2110 eeprom->product[j] = buf[2*j+i+2];
2112 eeprom->product[j] = '\0';
2115 i = buf[0x12] & 0x7f; // offset
2116 for (j=0;j<serial_size-1;j++)
2118 eeprom->serial[j] = buf[2*j+i+2];
2120 eeprom->serial[j] = '\0';
2125 for (i = 0; i < eeprom_size/2-1; i++)
2128 value += buf[(i*2)+1] << 8;
2130 checksum = value^checksum;
2131 checksum = (checksum << 1) | (checksum >> 15);
2134 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2136 if (eeprom_checksum != checksum)
2138 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2146 Read eeprom location
2148 \param ftdi pointer to ftdi_context
2149 \param eeprom_addr Address of eeprom location to be read
2150 \param eeprom_val Pointer to store read eeprom location
2153 \retval -1: read failed
2155 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2157 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
2158 ftdi_error_return(-1, "reading eeprom failed");
2166 \param ftdi pointer to ftdi_context
2167 \param eeprom Pointer to store eeprom into
2170 \retval -1: read failed
2172 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2176 for (i = 0; i < ftdi->eeprom_size/2; i++)
2178 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)
2179 ftdi_error_return(-1, "reading eeprom failed");
2186 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2187 Function is only used internally
2190 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2192 return ((value & 1) << 1) |
2193 ((value & 2) << 5) |
2194 ((value & 4) >> 2) |
2195 ((value & 8) << 4) |
2196 ((value & 16) >> 1) |
2197 ((value & 32) >> 1) |
2198 ((value & 64) >> 4) |
2199 ((value & 128) >> 2);
2203 Read the FTDIChip-ID from R-type devices
2205 \param ftdi pointer to ftdi_context
2206 \param chipid Pointer to store FTDIChip-ID
2209 \retval -1: read failed
2211 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2213 unsigned int a = 0, b = 0;
2215 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)
2217 a = a << 8 | a >> 8;
2218 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)
2220 b = b << 8 | b >> 8;
2221 a = (a << 16) | (b & 0xFFFF);
2222 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2223 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2224 *chipid = a ^ 0xa5f0f7d1;
2229 ftdi_error_return(-1, "read of FTDIChip-ID failed");
2233 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2234 Call this function then do a write then call again to see if size changes, if so write again.
2236 \param ftdi pointer to ftdi_context
2237 \param eeprom Pointer to store eeprom into
2238 \param maxsize the size of the buffer to read into
2240 \retval size of eeprom
2242 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2244 int i=0,j,minsize=32;
2249 for (j = 0; i < maxsize/2 && j<size; j++)
2251 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2252 SIO_READ_EEPROM_REQUEST, 0, i,
2253 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2254 ftdi_error_return(-1, "reading eeprom failed");
2259 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2265 Write eeprom location
2267 \param ftdi pointer to ftdi_context
2268 \param eeprom_addr Address of eeprom location to be written
2269 \param eeprom_val Value to be written
2272 \retval -1: read failed
2274 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
2276 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2277 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
2278 NULL, 0, ftdi->usb_write_timeout) != 0)
2279 ftdi_error_return(-1, "unable to write eeprom");
2287 \param ftdi pointer to ftdi_context
2288 \param eeprom Pointer to read eeprom from
2291 \retval -1: read failed
2293 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2295 unsigned short usb_val, status;
2298 /* These commands were traced while running MProg */
2299 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2301 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2303 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2306 for (i = 0; i < ftdi->eeprom_size/2; i++)
2308 usb_val = eeprom[i*2];
2309 usb_val += eeprom[(i*2)+1] << 8;
2310 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2311 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2312 NULL, 0, ftdi->usb_write_timeout) != 0)
2313 ftdi_error_return(-1, "unable to write eeprom");
2322 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2324 \param ftdi pointer to ftdi_context
2327 \retval -1: erase failed
2329 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2331 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2332 ftdi_error_return(-1, "unable to erase eeprom");
2338 Get string representation for last error code
2340 \param ftdi pointer to ftdi_context
2342 \retval Pointer to error string
2344 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2346 return ftdi->error_str;
2349 /* @} end of doxygen libftdi group */