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;
403 if (!(ftdi->usb_dev = usb_open(dev)))
404 ftdi_error_return(-4, "usb_open() failed");
406 #ifdef LIBUSB_HAS_GET_DRIVER_NP
407 // Try to detach ftdi_sio kernel module.
408 // Returns ENODATA if driver is not loaded.
410 // The return code is kept in a separate variable and only parsed
411 // if usb_set_configuration() or usb_claim_interface() fails as the
412 // detach operation might be denied and everything still works fine.
413 // Likely scenario is a static ftdi_sio kernel module.
414 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
415 detach_errno = errno;
419 // set configuration (needed especially for windows)
420 // tolerate EBUSY: one device with one configuration, but two interfaces
421 // and libftdi sessions to both interfaces (e.g. FT2232)
422 if (dev->descriptor.bNumConfigurations > 0 &&
423 usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
426 ftdi_usb_close_internal (ftdi);
427 if (detach_errno == EPERM)
429 ftdi_error_return(-8, "inappropriate permissions on device!");
433 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
438 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
440 ftdi_usb_close_internal (ftdi);
441 if (detach_errno == EPERM)
443 ftdi_error_return(-8, "inappropriate permissions on device!");
447 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
451 if (ftdi_usb_reset (ftdi) != 0)
453 ftdi_usb_close_internal (ftdi);
454 ftdi_error_return(-6, "ftdi_usb_reset failed");
457 // Try to guess chip type
458 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
459 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
460 && dev->descriptor.iSerialNumber == 0))
461 ftdi->type = TYPE_BM;
462 else if (dev->descriptor.bcdDevice == 0x200)
463 ftdi->type = TYPE_AM;
464 else if (dev->descriptor.bcdDevice == 0x500)
465 ftdi->type = TYPE_2232C;
466 else if (dev->descriptor.bcdDevice == 0x600)
468 else if (dev->descriptor.bcdDevice == 0x700)
469 ftdi->type = TYPE_2232H;
470 else if (dev->descriptor.bcdDevice == 0x800)
471 ftdi->type = TYPE_4232H;
473 // Set default interface on dual/quad type chips
480 ftdi->index = INTERFACE_A;
486 if (ftdi_set_baudrate (ftdi, 9600) != 0)
488 ftdi_usb_close_internal (ftdi);
489 ftdi_error_return(-7, "set baudrate failed");
492 ftdi_error_return(0, "all fine");
496 Opens the first device with a given vendor and product ids.
498 \param ftdi pointer to ftdi_context
499 \param vendor Vendor ID
500 \param product Product ID
502 \retval same as ftdi_usb_open_desc()
504 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
506 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
510 Opens the first device with a given, vendor id, product id,
511 description and serial.
513 \param ftdi pointer to ftdi_context
514 \param vendor Vendor ID
515 \param product Product ID
516 \param description Description to search for. Use NULL if not needed.
517 \param serial Serial to search for. Use NULL if not needed.
520 \retval -1: usb_find_busses() failed
521 \retval -2: usb_find_devices() failed
522 \retval -3: usb device not found
523 \retval -4: unable to open device
524 \retval -5: unable to claim device
525 \retval -6: reset failed
526 \retval -7: set baudrate failed
527 \retval -8: get product description failed
528 \retval -9: get serial number failed
529 \retval -10: unable to close device
531 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
532 const char* description, const char* serial)
535 struct usb_device *dev;
540 if (usb_find_busses() < 0)
541 ftdi_error_return(-1, "usb_find_busses() failed");
542 if (usb_find_devices() < 0)
543 ftdi_error_return(-2, "usb_find_devices() failed");
545 for (bus = usb_get_busses(); bus; bus = bus->next)
547 for (dev = bus->devices; dev; dev = dev->next)
549 if (dev->descriptor.idVendor == vendor
550 && dev->descriptor.idProduct == product)
552 if (!(ftdi->usb_dev = usb_open(dev)))
553 ftdi_error_return(-4, "usb_open() failed");
555 if (description != NULL)
557 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
559 ftdi_usb_close_internal (ftdi);
560 ftdi_error_return(-8, "unable to fetch product description");
562 if (strncmp(string, description, sizeof(string)) != 0)
564 if (ftdi_usb_close_internal (ftdi) != 0)
565 ftdi_error_return(-10, "unable to close device");
571 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
573 ftdi_usb_close_internal (ftdi);
574 ftdi_error_return(-9, "unable to fetch serial number");
576 if (strncmp(string, serial, sizeof(string)) != 0)
578 if (ftdi_usb_close_internal (ftdi) != 0)
579 ftdi_error_return(-10, "unable to close device");
584 if (ftdi_usb_close_internal (ftdi) != 0)
585 ftdi_error_return(-10, "unable to close device");
587 return ftdi_usb_open_dev(ftdi, dev);
593 ftdi_error_return(-3, "device not found");
597 Resets the ftdi device.
599 \param ftdi pointer to ftdi_context
602 \retval -1: FTDI reset failed
604 int ftdi_usb_reset(struct ftdi_context *ftdi)
606 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
607 SIO_RESET_REQUEST, SIO_RESET_SIO,
608 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
609 ftdi_error_return(-1,"FTDI reset failed");
611 // Invalidate data in the readbuffer
612 ftdi->readbuffer_offset = 0;
613 ftdi->readbuffer_remaining = 0;
619 Clears the read buffer on the chip and the internal read buffer.
621 \param ftdi pointer to ftdi_context
624 \retval -1: read buffer purge failed
626 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
628 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
629 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
630 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
631 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
633 // Invalidate data in the readbuffer
634 ftdi->readbuffer_offset = 0;
635 ftdi->readbuffer_remaining = 0;
641 Clears the write buffer on the chip.
643 \param ftdi pointer to ftdi_context
646 \retval -1: write buffer purge failed
648 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
650 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
651 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
652 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
653 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
659 Clears the buffers on the chip and the internal read buffer.
661 \param ftdi pointer to ftdi_context
664 \retval -1: read buffer purge failed
665 \retval -2: write buffer purge failed
667 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
671 result = ftdi_usb_purge_rx_buffer(ftdi);
675 result = ftdi_usb_purge_tx_buffer(ftdi);
685 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
687 \param ftdi pointer to ftdi_context
690 \retval -1: usb_release failed
691 \retval -2: usb_close failed
693 int ftdi_usb_close(struct ftdi_context *ftdi)
697 #ifdef LIBFTDI_LINUX_ASYNC_MODE
698 /* try to release some kernel resources */
699 ftdi_async_complete(ftdi,1);
702 if (ftdi->usb_dev != NULL)
703 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
706 if (ftdi_usb_close_internal (ftdi) != 0)
713 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
714 Function is only used internally
717 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
718 unsigned short *value, unsigned short *index)
720 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
721 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
722 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
723 int divisor, best_divisor, best_baud, best_baud_diff;
724 unsigned long encoded_divisor;
733 divisor = 24000000 / baudrate;
735 if (ftdi->type == TYPE_AM)
737 // Round down to supported fraction (AM only)
738 divisor -= am_adjust_dn[divisor & 7];
741 // Try this divisor and the one above it (because division rounds down)
745 for (i = 0; i < 2; i++)
747 int try_divisor = divisor + i;
751 // Round up to supported divisor value
752 if (try_divisor <= 8)
754 // Round up to minimum supported divisor
757 else if (ftdi->type != TYPE_AM && try_divisor < 12)
759 // BM doesn't support divisors 9 through 11 inclusive
762 else if (divisor < 16)
764 // AM doesn't support divisors 9 through 15 inclusive
769 if (ftdi->type == TYPE_AM)
771 // Round up to supported fraction (AM only)
772 try_divisor += am_adjust_up[try_divisor & 7];
773 if (try_divisor > 0x1FFF8)
775 // Round down to maximum supported divisor value (for AM)
776 try_divisor = 0x1FFF8;
781 if (try_divisor > 0x1FFFF)
783 // Round down to maximum supported divisor value (for BM)
784 try_divisor = 0x1FFFF;
788 // Get estimated baud rate (to nearest integer)
789 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
790 // Get absolute difference from requested baud rate
791 if (baud_estimate < baudrate)
793 baud_diff = baudrate - baud_estimate;
797 baud_diff = baud_estimate - baudrate;
799 if (i == 0 || baud_diff < best_baud_diff)
801 // Closest to requested baud rate so far
802 best_divisor = try_divisor;
803 best_baud = baud_estimate;
804 best_baud_diff = baud_diff;
807 // Spot on! No point trying
812 // Encode the best divisor value
813 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
814 // Deal with special cases for encoded value
815 if (encoded_divisor == 1)
817 encoded_divisor = 0; // 3000000 baud
819 else if (encoded_divisor == 0x4001)
821 encoded_divisor = 1; // 2000000 baud (BM only)
823 // Split into "value" and "index" values
824 *value = (unsigned short)(encoded_divisor & 0xFFFF);
825 if (ftdi->type == TYPE_2232C)
827 *index = (unsigned short)(encoded_divisor >> 8);
829 *index |= ftdi->index;
832 *index = (unsigned short)(encoded_divisor >> 16);
834 // Return the nearest baud rate
839 Sets the chip baud rate
841 \param ftdi pointer to ftdi_context
842 \param baudrate baud rate to set
845 \retval -1: invalid baudrate
846 \retval -2: setting baudrate failed
848 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
850 unsigned short value, index;
853 if (ftdi->bitbang_enabled)
855 baudrate = baudrate*4;
858 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
859 if (actual_baudrate <= 0)
860 ftdi_error_return (-1, "Silly baudrate <= 0.");
862 // Check within tolerance (about 5%)
863 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
864 || ((actual_baudrate < baudrate)
865 ? (actual_baudrate * 21 < baudrate * 20)
866 : (baudrate * 21 < actual_baudrate * 20)))
867 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
869 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
870 SIO_SET_BAUDRATE_REQUEST, value,
871 index, NULL, 0, ftdi->usb_write_timeout) != 0)
872 ftdi_error_return (-2, "Setting new baudrate failed");
874 ftdi->baudrate = baudrate;
879 Set (RS232) line characteristics.
880 The break type can only be set via ftdi_set_line_property2()
881 and defaults to "off".
883 \param ftdi pointer to ftdi_context
884 \param bits Number of bits
885 \param sbit Number of stop bits
886 \param parity Parity mode
889 \retval -1: Setting line property failed
891 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
892 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
894 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
898 Set (RS232) line characteristics
900 \param ftdi pointer to ftdi_context
901 \param bits Number of bits
902 \param sbit Number of stop bits
903 \param parity Parity mode
904 \param break_type Break type
907 \retval -1: Setting line property failed
909 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
910 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
911 enum ftdi_break_type break_type)
913 unsigned short value = bits;
918 value |= (0x00 << 8);
921 value |= (0x01 << 8);
924 value |= (0x02 << 8);
927 value |= (0x03 << 8);
930 value |= (0x04 << 8);
937 value |= (0x00 << 11);
940 value |= (0x01 << 11);
943 value |= (0x02 << 11);
950 value |= (0x00 << 14);
953 value |= (0x01 << 14);
957 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
958 SIO_SET_DATA_REQUEST, value,
959 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
960 ftdi_error_return (-1, "Setting new line property failed");
966 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
968 \param ftdi pointer to ftdi_context
969 \param buf Buffer with the data
970 \param size Size of the buffer
972 \retval <0: error code from usb_bulk_write()
973 \retval >0: number of bytes written
975 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
979 int total_written = 0;
981 while (offset < size)
983 int write_size = ftdi->writebuffer_chunksize;
985 if (offset+write_size > size)
986 write_size = size-offset;
988 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
990 ftdi_error_return(ret, "usb bulk write failed");
992 total_written += ret;
993 offset += write_size;
996 return total_written;
999 #ifdef LIBFTDI_LINUX_ASYNC_MODE
1000 #ifdef USB_CLASS_PTP
1001 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
1003 /* this is strongly dependent on libusb using the same struct layout. If libusb
1004 changes in some later version this may break horribly (this is for libusb 0.1.12) */
1005 struct usb_dev_handle
1008 // some other stuff coming here we don't need
1012 Check for pending async urbs
1015 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
1017 struct usbdevfs_urb *urb;
1021 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1023 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1024 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
1032 Wait until one or more async URBs are completed by the kernel and mark their
1033 positions in the async-buffer as unused
1035 \param ftdi pointer to ftdi_context
1036 \param wait_for_more if != 0 wait for more than one write to complete
1037 \param timeout_msec max milliseconds to wait
1041 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
1044 struct usbdevfs_urb *urb=NULL;
1050 FD_SET(ftdi->usb_dev->fd, &writefds);
1052 /* init timeout only once, select writes time left after call */
1053 tv.tv_sec = timeout_msec / 1000;
1054 tv.tv_usec = (timeout_msec % 1000) * 1000;
1058 while (_usb_get_async_urbs_pending(ftdi)
1059 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1062 if (keep_going && !wait_for_more)
1064 /* don't wait if repeating only for keep_going */
1069 /* wait for timeout msec or something written ready */
1070 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1073 if (ret == 0 && urb != NULL)
1075 /* got a free urb, mark it */
1076 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1078 /* try to get more urbs that are ready now, but don't wait anymore */
1084 /* no more urbs waiting */
1092 Wait until one or more async URBs are completed by the kernel and mark their
1093 positions in the async-buffer as unused.
1095 \param ftdi pointer to ftdi_context
1096 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1098 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1100 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1104 Stupid libusb does not offer async writes nor does it allow
1105 access to its fd - so we need some hacks here.
1108 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1110 struct usbdevfs_urb *urb;
1111 int bytesdone = 0, requested;
1112 int ret, cleanup_count;
1117 /* find a free urb buffer we can use */
1119 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1121 if (i==ftdi->async_usb_buffer_size)
1123 /* wait until some buffers are free */
1124 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1127 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1129 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1130 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1131 break; /* found a free urb position */
1136 /* no free urb position found */
1140 requested = size - bytesdone;
1141 if (requested > 4096)
1144 memset(urb,0,sizeof(urb));
1146 urb->type = USBDEVFS_URB_TYPE_BULK;
1149 urb->buffer = bytes + bytesdone;
1150 urb->buffer_length = requested;
1152 urb->actual_length = 0;
1153 urb->number_of_packets = 0;
1154 urb->usercontext = 0;
1158 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1160 while (ret < 0 && errno == EINTR);
1162 return ret; /* the caller can read errno to get more info */
1164 bytesdone += requested;
1166 while (bytesdone < size);
1171 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1172 Does not wait for completion of the transfer nor does it make sure that
1173 the transfer was successful.
1175 This function could be extended to use signals and callbacks to inform the
1176 caller of completion or error - but this is not done yet, volunteers welcome.
1178 Works around libusb and directly accesses functions only available on Linux.
1179 Only available if compiled with --with-async-mode.
1181 \param ftdi pointer to ftdi_context
1182 \param buf Buffer with the data
1183 \param size Size of the buffer
1185 \retval <0: error code from usb_bulk_write()
1186 \retval >0: number of bytes written
1188 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1192 int total_written = 0;
1194 while (offset < size)
1196 int write_size = ftdi->writebuffer_chunksize;
1198 if (offset+write_size > size)
1199 write_size = size-offset;
1201 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1203 ftdi_error_return(ret, "usb bulk write async failed");
1205 total_written += ret;
1206 offset += write_size;
1209 return total_written;
1211 #endif // LIBFTDI_LINUX_ASYNC_MODE
1214 Configure write buffer chunk size.
1217 \param ftdi pointer to ftdi_context
1218 \param chunksize Chunk size
1222 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1224 ftdi->writebuffer_chunksize = chunksize;
1229 Get write buffer chunk size.
1231 \param ftdi pointer to ftdi_context
1232 \param chunksize Pointer to store chunk size in
1236 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1238 *chunksize = ftdi->writebuffer_chunksize;
1243 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1245 Automatically strips the two modem status bytes transfered during every read.
1247 \param ftdi pointer to ftdi_context
1248 \param buf Buffer to store data in
1249 \param size Size of the buffer
1251 \retval <0: error code from usb_bulk_read()
1252 \retval 0: no data was available
1253 \retval >0: number of bytes read
1255 \remark This function is not useful in bitbang mode.
1256 Use ftdi_read_pins() to get the current state of the pins.
1258 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1260 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1263 // New hi-speed devices from FTDI use a packet size of 512 bytes
1264 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1269 // everything we want is still in the readbuffer?
1270 if (size <= ftdi->readbuffer_remaining)
1272 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1275 ftdi->readbuffer_remaining -= size;
1276 ftdi->readbuffer_offset += size;
1278 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1282 // something still in the readbuffer, but not enough to satisfy 'size'?
1283 if (ftdi->readbuffer_remaining != 0)
1285 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1288 offset += ftdi->readbuffer_remaining;
1290 // do the actual USB read
1291 while (offset < size && ret > 0)
1293 ftdi->readbuffer_remaining = 0;
1294 ftdi->readbuffer_offset = 0;
1295 /* returns how much received */
1296 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1298 ftdi_error_return(ret, "usb bulk read failed");
1302 // skip FTDI status bytes.
1303 // Maybe stored in the future to enable modem use
1304 num_of_chunks = ret / packet_size;
1305 chunk_remains = ret % packet_size;
1306 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1308 ftdi->readbuffer_offset += 2;
1311 if (ret > packet_size - 2)
1313 for (i = 1; i < num_of_chunks; i++)
1314 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1315 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1317 if (chunk_remains > 2)
1319 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1320 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1322 ret -= 2*num_of_chunks;
1325 ret -= 2*(num_of_chunks-1)+chunk_remains;
1330 // no more data to read?
1335 // data still fits in buf?
1336 if (offset+ret <= size)
1338 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1339 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1342 /* Did we read exactly the right amount of bytes? */
1344 //printf("read_data exact rem %d offset %d\n",
1345 //ftdi->readbuffer_remaining, offset);
1350 // only copy part of the data or size <= readbuffer_chunksize
1351 int part_size = size-offset;
1352 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1354 ftdi->readbuffer_offset += part_size;
1355 ftdi->readbuffer_remaining = ret-part_size;
1356 offset += part_size;
1358 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1359 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1370 Configure read buffer chunk size.
1373 Automatically reallocates the buffer.
1375 \param ftdi pointer to ftdi_context
1376 \param chunksize Chunk size
1380 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1382 unsigned char *new_buf;
1384 // Invalidate all remaining data
1385 ftdi->readbuffer_offset = 0;
1386 ftdi->readbuffer_remaining = 0;
1388 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1389 ftdi_error_return(-1, "out of memory for readbuffer");
1391 ftdi->readbuffer = new_buf;
1392 ftdi->readbuffer_chunksize = chunksize;
1398 Get read buffer chunk size.
1400 \param ftdi pointer to ftdi_context
1401 \param chunksize Pointer to store chunk size in
1405 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1407 *chunksize = ftdi->readbuffer_chunksize;
1413 Enable bitbang mode.
1415 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1417 \param ftdi pointer to ftdi_context
1418 \param bitmask Bitmask to configure lines.
1419 HIGH/ON value configures a line as output.
1422 \retval -1: can't enable bitbang mode
1424 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1426 unsigned short usb_val;
1428 usb_val = bitmask; // low byte: bitmask
1429 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1430 usb_val |= (ftdi->bitbang_mode << 8);
1432 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1433 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1434 NULL, 0, ftdi->usb_write_timeout) != 0)
1435 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1437 ftdi->bitbang_enabled = 1;
1442 Disable bitbang mode.
1444 \param ftdi pointer to ftdi_context
1447 \retval -1: can't disable bitbang mode
1449 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1451 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)
1452 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1454 ftdi->bitbang_enabled = 0;
1459 Enable advanced bitbang mode for FT2232C chips.
1461 \param ftdi pointer to ftdi_context
1462 \param bitmask Bitmask to configure lines.
1463 HIGH/ON value configures a line as output.
1464 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1467 \retval -1: can't enable bitbang mode
1469 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1471 unsigned short usb_val;
1473 usb_val = bitmask; // low byte: bitmask
1474 usb_val |= (mode << 8);
1475 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)
1476 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1478 ftdi->bitbang_mode = mode;
1479 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1484 Directly read pin state. Useful for bitbang mode.
1486 \param ftdi pointer to ftdi_context
1487 \param pins Pointer to store pins into
1490 \retval -1: read pins failed
1492 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1494 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)
1495 ftdi_error_return(-1, "read pins failed");
1503 The FTDI chip keeps data in the internal buffer for a specific
1504 amount of time if the buffer is not full yet to decrease
1505 load on the usb bus.
1507 \param ftdi pointer to ftdi_context
1508 \param latency Value between 1 and 255
1511 \retval -1: latency out of range
1512 \retval -2: unable to set latency timer
1514 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1516 unsigned short usb_val;
1519 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1522 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)
1523 ftdi_error_return(-2, "unable to set latency timer");
1531 \param ftdi pointer to ftdi_context
1532 \param latency Pointer to store latency value in
1535 \retval -1: unable to get latency timer
1537 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1539 unsigned short usb_val;
1540 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)
1541 ftdi_error_return(-1, "reading latency timer failed");
1543 *latency = (unsigned char)usb_val;
1548 Poll modem status information
1550 This function allows the retrieve the two status bytes of the device.
1551 The device sends these bytes also as a header for each read access
1552 where they are discarded by ftdi_read_data(). The chip generates
1553 the two stripped status bytes in the absence of data every 40 ms.
1555 Layout of the first byte:
1556 - B0..B3 - must be 0
1557 - B4 Clear to send (CTS)
1560 - B5 Data set ready (DTS)
1563 - B6 Ring indicator (RI)
1566 - B7 Receive line signal detect (RLSD)
1570 Layout of the second byte:
1571 - B0 Data ready (DR)
1572 - B1 Overrun error (OE)
1573 - B2 Parity error (PE)
1574 - B3 Framing error (FE)
1575 - B4 Break interrupt (BI)
1576 - B5 Transmitter holding register (THRE)
1577 - B6 Transmitter empty (TEMT)
1578 - B7 Error in RCVR FIFO
1580 \param ftdi pointer to ftdi_context
1581 \param status Pointer to store status information in. Must be two bytes.
1584 \retval -1: unable to retrieve status information
1586 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1590 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)
1591 ftdi_error_return(-1, "getting modem status failed");
1593 *status = (usb_val[1] << 8) | usb_val[0];
1599 Set flowcontrol for ftdi chip
1601 \param ftdi pointer to ftdi_context
1602 \param flowctrl flow control to use. should be
1603 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1606 \retval -1: set flow control failed
1608 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1610 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1611 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1612 NULL, 0, ftdi->usb_write_timeout) != 0)
1613 ftdi_error_return(-1, "set flow control failed");
1621 \param ftdi pointer to ftdi_context
1622 \param state state to set line to (1 or 0)
1625 \retval -1: set dtr failed
1627 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1629 unsigned short usb_val;
1632 usb_val = SIO_SET_DTR_HIGH;
1634 usb_val = SIO_SET_DTR_LOW;
1636 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1637 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1638 NULL, 0, ftdi->usb_write_timeout) != 0)
1639 ftdi_error_return(-1, "set dtr failed");
1647 \param ftdi pointer to ftdi_context
1648 \param state state to set line to (1 or 0)
1651 \retval -1 set rts failed
1653 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1655 unsigned short usb_val;
1658 usb_val = SIO_SET_RTS_HIGH;
1660 usb_val = SIO_SET_RTS_LOW;
1662 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1663 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1664 NULL, 0, ftdi->usb_write_timeout) != 0)
1665 ftdi_error_return(-1, "set of rts failed");
1671 Set dtr and rts line in one pass
1673 \param ftdi pointer to ftdi_context
1674 \param dtr DTR state to set line to (1 or 0)
1675 \param rts RTS state to set line to (1 or 0)
1678 \retval -1 set dtr/rts failed
1680 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1682 unsigned short usb_val;
1685 usb_val = SIO_SET_DTR_HIGH;
1687 usb_val = SIO_SET_DTR_LOW;
1690 usb_val |= SIO_SET_RTS_HIGH;
1692 usb_val |= SIO_SET_RTS_LOW;
1694 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1695 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1696 NULL, 0, ftdi->usb_write_timeout) != 0)
1697 ftdi_error_return(-1, "set of rts/dtr failed");
1703 Set the special event character
1705 \param ftdi pointer to ftdi_context
1706 \param eventch Event character
1707 \param enable 0 to disable the event character, non-zero otherwise
1710 \retval -1: unable to set event character
1712 int ftdi_set_event_char(struct ftdi_context *ftdi,
1713 unsigned char eventch, unsigned char enable)
1715 unsigned short usb_val;
1721 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)
1722 ftdi_error_return(-1, "setting event character failed");
1730 \param ftdi pointer to ftdi_context
1731 \param errorch Error character
1732 \param enable 0 to disable the error character, non-zero otherwise
1735 \retval -1: unable to set error character
1737 int ftdi_set_error_char(struct ftdi_context *ftdi,
1738 unsigned char errorch, unsigned char enable)
1740 unsigned short usb_val;
1746 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)
1747 ftdi_error_return(-1, "setting error character failed");
1755 \param ftdi pointer to ftdi_context
1756 \param eeprom Pointer to ftdi_eeprom
1760 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1762 ftdi->eeprom_size=size;
1767 Init eeprom with default values.
1769 \param eeprom Pointer to ftdi_eeprom
1771 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1773 eeprom->vendor_id = 0x0403;
1774 eeprom->product_id = 0x6001;
1776 eeprom->self_powered = 1;
1777 eeprom->remote_wakeup = 1;
1778 eeprom->BM_type_chip = 1;
1780 eeprom->in_is_isochronous = 0;
1781 eeprom->out_is_isochronous = 0;
1782 eeprom->suspend_pull_downs = 0;
1784 eeprom->use_serial = 0;
1785 eeprom->change_usb_version = 0;
1786 eeprom->usb_version = 0x0200;
1787 eeprom->max_power = 0;
1789 eeprom->manufacturer = NULL;
1790 eeprom->product = NULL;
1791 eeprom->serial = NULL;
1793 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1797 Build binary output from ftdi_eeprom structure.
1798 Output is suitable for ftdi_write_eeprom().
1800 \param eeprom Pointer to ftdi_eeprom
1801 \param output Buffer of 128 bytes to store eeprom image to
1803 \retval >0: used eeprom size
1804 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1806 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1809 unsigned short checksum, value;
1810 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1813 if (eeprom->manufacturer != NULL)
1814 manufacturer_size = strlen(eeprom->manufacturer);
1815 if (eeprom->product != NULL)
1816 product_size = strlen(eeprom->product);
1817 if (eeprom->serial != NULL)
1818 serial_size = strlen(eeprom->serial);
1820 size_check = eeprom->size;
1821 size_check -= 28; // 28 are always in use (fixed)
1823 // Top half of a 256byte eeprom is used just for strings and checksum
1824 // it seems that the FTDI chip will not read these strings from the lower half
1825 // Each string starts with two bytes; offset and type (0x03 for string)
1826 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1827 if (eeprom->size>=256)size_check = 120;
1828 size_check -= manufacturer_size*2;
1829 size_check -= product_size*2;
1830 size_check -= serial_size*2;
1832 // eeprom size exceeded?
1837 memset (output, 0, eeprom->size);
1839 // Addr 00: Stay 00 00
1840 // Addr 02: Vendor ID
1841 output[0x02] = eeprom->vendor_id;
1842 output[0x03] = eeprom->vendor_id >> 8;
1844 // Addr 04: Product ID
1845 output[0x04] = eeprom->product_id;
1846 output[0x05] = eeprom->product_id >> 8;
1848 // Addr 06: Device release number (0400h for BM features)
1849 output[0x06] = 0x00;
1851 if (eeprom->BM_type_chip == 1)
1852 output[0x07] = 0x04;
1854 output[0x07] = 0x02;
1856 // Addr 08: Config descriptor
1858 // Bit 6: 1 if this device is self powered, 0 if bus powered
1859 // Bit 5: 1 if this device uses remote wakeup
1860 // Bit 4: 1 if this device is battery powered
1862 if (eeprom->self_powered == 1)
1864 if (eeprom->remote_wakeup == 1)
1868 // Addr 09: Max power consumption: max power = value * 2 mA
1869 output[0x09] = eeprom->max_power;
1871 // Addr 0A: Chip configuration
1872 // Bit 7: 0 - reserved
1873 // Bit 6: 0 - reserved
1874 // Bit 5: 0 - reserved
1875 // Bit 4: 1 - Change USB version
1876 // Bit 3: 1 - Use the serial number string
1877 // Bit 2: 1 - Enable suspend pull downs for lower power
1878 // Bit 1: 1 - Out EndPoint is Isochronous
1879 // Bit 0: 1 - In EndPoint is Isochronous
1882 if (eeprom->in_is_isochronous == 1)
1884 if (eeprom->out_is_isochronous == 1)
1886 if (eeprom->suspend_pull_downs == 1)
1888 if (eeprom->use_serial == 1)
1890 if (eeprom->change_usb_version == 1)
1894 // Addr 0B: reserved
1895 output[0x0B] = 0x00;
1897 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1898 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1899 if (eeprom->change_usb_version == 1)
1901 output[0x0C] = eeprom->usb_version;
1902 output[0x0D] = eeprom->usb_version >> 8;
1906 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1907 // Addr 0F: Length of manufacturer string
1908 output[0x0F] = manufacturer_size*2 + 2;
1910 // Addr 10: Offset of the product string + 0x80, calculated later
1911 // Addr 11: Length of product string
1912 output[0x11] = product_size*2 + 2;
1914 // Addr 12: Offset of the serial string + 0x80, calculated later
1915 // Addr 13: Length of serial string
1916 output[0x13] = serial_size*2 + 2;
1920 if (eeprom->size>=256) i = 0x80;
1923 // Output manufacturer
1924 output[0x0E] = i | 0x80; // calculate offset
1925 output[i++] = manufacturer_size*2 + 2;
1926 output[i++] = 0x03; // type: string
1927 for (j = 0; j < manufacturer_size; j++)
1929 output[i] = eeprom->manufacturer[j], i++;
1930 output[i] = 0x00, i++;
1933 // Output product name
1934 output[0x10] = i | 0x80; // calculate offset
1935 output[i] = product_size*2 + 2, i++;
1936 output[i] = 0x03, i++;
1937 for (j = 0; j < product_size; j++)
1939 output[i] = eeprom->product[j], i++;
1940 output[i] = 0x00, i++;
1944 output[0x12] = i | 0x80; // calculate offset
1945 output[i] = serial_size*2 + 2, i++;
1946 output[i] = 0x03, i++;
1947 for (j = 0; j < serial_size; j++)
1949 output[i] = eeprom->serial[j], i++;
1950 output[i] = 0x00, i++;
1953 // calculate checksum
1956 for (i = 0; i < eeprom->size/2-1; i++)
1958 value = output[i*2];
1959 value += output[(i*2)+1] << 8;
1961 checksum = value^checksum;
1962 checksum = (checksum << 1) | (checksum >> 15);
1965 output[eeprom->size-2] = checksum;
1966 output[eeprom->size-1] = checksum >> 8;
1972 Decode binary EEPROM image into an ftdi_eeprom structure.
1974 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1975 \param buf Buffer of \a size bytes of raw eeprom data
1976 \param size size size of eeprom data in bytes
1979 \retval -1: something went wrong
1981 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
1982 FIXME: Strings are malloc'ed here and should be freed somewhere
1984 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
1987 unsigned short checksum, eeprom_checksum, value;
1988 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1990 int eeprom_size = 128;
1992 size_check = eeprom->size;
1993 size_check -= 28; // 28 are always in use (fixed)
1995 // Top half of a 256byte eeprom is used just for strings and checksum
1996 // it seems that the FTDI chip will not read these strings from the lower half
1997 // Each string starts with two bytes; offset and type (0x03 for string)
1998 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1999 if (eeprom->size>=256)size_check = 120;
2000 size_check -= manufacturer_size*2;
2001 size_check -= product_size*2;
2002 size_check -= serial_size*2;
2004 // eeprom size exceeded?
2009 // empty eeprom struct
2010 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2012 // Addr 00: Stay 00 00
2014 // Addr 02: Vendor ID
2015 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2017 // Addr 04: Product ID
2018 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2020 value = buf[0x06] + (buf[0x07]<<8);
2024 eeprom->BM_type_chip = 1;
2027 eeprom->BM_type_chip = 0;
2029 default: // Unknown device
2030 eeprom->BM_type_chip = 0;
2034 // Addr 08: Config descriptor
2036 // Bit 6: 1 if this device is self powered, 0 if bus powered
2037 // Bit 5: 1 if this device uses remote wakeup
2038 // Bit 4: 1 if this device is battery powered
2040 if (j&0x40) eeprom->self_powered = 1;
2041 if (j&0x20) eeprom->remote_wakeup = 1;
2043 // Addr 09: Max power consumption: max power = value * 2 mA
2044 eeprom->max_power = buf[0x09];
2046 // Addr 0A: Chip configuration
2047 // Bit 7: 0 - reserved
2048 // Bit 6: 0 - reserved
2049 // Bit 5: 0 - reserved
2050 // Bit 4: 1 - Change USB version
2051 // Bit 3: 1 - Use the serial number string
2052 // Bit 2: 1 - Enable suspend pull downs for lower power
2053 // Bit 1: 1 - Out EndPoint is Isochronous
2054 // Bit 0: 1 - In EndPoint is Isochronous
2057 if (j&0x01) eeprom->in_is_isochronous = 1;
2058 if (j&0x02) eeprom->out_is_isochronous = 1;
2059 if (j&0x04) eeprom->suspend_pull_downs = 1;
2060 if (j&0x08) eeprom->use_serial = 1;
2061 if (j&0x10) eeprom->change_usb_version = 1;
2063 // Addr 0B: reserved
2065 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2066 // Addr 0D: USB version high byte when 0x0A bit 4 is set
2067 if (eeprom->change_usb_version == 1)
2069 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2072 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2073 // Addr 0F: Length of manufacturer string
2074 manufacturer_size = buf[0x0F]/2;
2075 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2076 else eeprom->manufacturer = NULL;
2078 // Addr 10: Offset of the product string + 0x80, calculated later
2079 // Addr 11: Length of product string
2080 product_size = buf[0x11]/2;
2081 if (product_size > 0) eeprom->product = malloc(product_size);
2082 else eeprom->product = NULL;
2084 // Addr 12: Offset of the serial string + 0x80, calculated later
2085 // Addr 13: Length of serial string
2086 serial_size = buf[0x13]/2;
2087 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2088 else eeprom->serial = NULL;
2090 // Decode manufacturer
2091 i = buf[0x0E] & 0x7f; // offset
2092 for (j=0;j<manufacturer_size-1;j++)
2094 eeprom->manufacturer[j] = buf[2*j+i+2];
2096 eeprom->manufacturer[j] = '\0';
2098 // Decode product name
2099 i = buf[0x10] & 0x7f; // offset
2100 for (j=0;j<product_size-1;j++)
2102 eeprom->product[j] = buf[2*j+i+2];
2104 eeprom->product[j] = '\0';
2107 i = buf[0x12] & 0x7f; // offset
2108 for (j=0;j<serial_size-1;j++)
2110 eeprom->serial[j] = buf[2*j+i+2];
2112 eeprom->serial[j] = '\0';
2117 for (i = 0; i < eeprom_size/2-1; i++)
2120 value += buf[(i*2)+1] << 8;
2122 checksum = value^checksum;
2123 checksum = (checksum << 1) | (checksum >> 15);
2126 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2128 if (eeprom_checksum != checksum)
2130 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2138 Read eeprom location
2140 \param ftdi pointer to ftdi_context
2141 \param eeprom_addr Address of eeprom location to be read
2142 \param eeprom_val Pointer to store read eeprom location
2145 \retval -1: read failed
2147 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2149 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)
2150 ftdi_error_return(-1, "reading eeprom failed");
2158 \param ftdi pointer to ftdi_context
2159 \param eeprom Pointer to store eeprom into
2162 \retval -1: read failed
2164 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2168 for (i = 0; i < ftdi->eeprom_size/2; i++)
2170 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)
2171 ftdi_error_return(-1, "reading eeprom failed");
2178 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2179 Function is only used internally
2182 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2184 return ((value & 1) << 1) |
2185 ((value & 2) << 5) |
2186 ((value & 4) >> 2) |
2187 ((value & 8) << 4) |
2188 ((value & 16) >> 1) |
2189 ((value & 32) >> 1) |
2190 ((value & 64) >> 4) |
2191 ((value & 128) >> 2);
2195 Read the FTDIChip-ID from R-type devices
2197 \param ftdi pointer to ftdi_context
2198 \param chipid Pointer to store FTDIChip-ID
2201 \retval -1: read failed
2203 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2205 unsigned int a = 0, b = 0;
2207 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)
2209 a = a << 8 | a >> 8;
2210 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)
2212 b = b << 8 | b >> 8;
2213 a = (a << 16) | (b & 0xFFFF);
2214 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2215 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2216 *chipid = a ^ 0xa5f0f7d1;
2221 ftdi_error_return(-1, "read of FTDIChip-ID failed");
2225 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2226 Call this function then do a write then call again to see if size changes, if so write again.
2228 \param ftdi pointer to ftdi_context
2229 \param eeprom Pointer to store eeprom into
2230 \param maxsize the size of the buffer to read into
2232 \retval size of eeprom
2234 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2236 int i=0,j,minsize=32;
2241 for (j = 0; i < maxsize/2 && j<size; j++)
2243 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2244 SIO_READ_EEPROM_REQUEST, 0, i,
2245 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2246 ftdi_error_return(-1, "reading eeprom failed");
2251 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2257 Write eeprom location
2259 \param ftdi pointer to ftdi_context
2260 \param eeprom_addr Address of eeprom location to be written
2261 \param eeprom_val Value to be written
2264 \retval -1: read failed
2266 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
2268 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2269 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
2270 NULL, 0, ftdi->usb_write_timeout) != 0)
2271 ftdi_error_return(-1, "unable to write eeprom");
2279 \param ftdi pointer to ftdi_context
2280 \param eeprom Pointer to read eeprom from
2283 \retval -1: read failed
2285 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2287 unsigned short usb_val, status;
2290 /* These commands were traced while running MProg */
2291 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2293 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2295 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2298 for (i = 0; i < ftdi->eeprom_size/2; i++)
2300 usb_val = eeprom[i*2];
2301 usb_val += eeprom[(i*2)+1] << 8;
2302 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2303 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2304 NULL, 0, ftdi->usb_write_timeout) != 0)
2305 ftdi_error_return(-1, "unable to write eeprom");
2314 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2316 \param ftdi pointer to ftdi_context
2319 \retval -1: erase failed
2321 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2323 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2324 ftdi_error_return(-1, "unable to erase eeprom");
2330 Get string representation for last error code
2332 \param ftdi pointer to ftdi_context
2334 \retval Pointer to error string
2336 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2338 return ftdi->error_str;
2341 /* @} end of doxygen libftdi group */