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; \
53 /* internal usb_close wrapper -> sets usb dev handle to NULL */
54 int usb_close_intl (struct ftdi_context *ftdi)
58 if (ftdi->usb_dev != NULL)
60 ret = usb_close (ftdi->usb_dev);
67 Initializes a ftdi_context.
69 \param ftdi pointer to ftdi_context
72 \retval -1: couldn't allocate read buffer
74 \remark This should be called before all functions
76 int ftdi_init(struct ftdi_context *ftdi)
81 ftdi->usb_read_timeout = 5000;
82 ftdi->usb_write_timeout = 5000;
84 ftdi->type = TYPE_BM; /* chip type */
86 ftdi->bitbang_enabled = 0;
88 ftdi->readbuffer = NULL;
89 ftdi->readbuffer_offset = 0;
90 ftdi->readbuffer_remaining = 0;
91 ftdi->writebuffer_chunksize = 4096;
97 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
99 ftdi->error_str = NULL;
101 #ifdef LIBFTDI_LINUX_ASYNC_MODE
102 ftdi->async_usb_buffer_size=10;
103 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
104 ftdi_error_return(-1, "out of memory for async usb buffer");
106 /* initialize async usb buffer with unused-marker */
107 for (i=0; i < ftdi->async_usb_buffer_size; i++)
108 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
110 ftdi->async_usb_buffer_size=0;
111 ftdi->async_usb_buffer = NULL;
114 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
116 /* All fine. Now allocate the readbuffer */
117 return ftdi_read_data_set_chunksize(ftdi, 4096);
121 Allocate and initialize a new ftdi_context
123 \return a pointer to a new ftdi_context, or NULL on failure
125 struct ftdi_context *ftdi_new(void)
127 struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
134 if (ftdi_init(ftdi) != 0)
144 Open selected channels on a chip, otherwise use first channel.
146 \param ftdi pointer to ftdi_context
147 \param interface Interface to use for FT2232C/2232H/4232H chips.
150 \retval -1: unknown interface
152 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
158 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
162 ftdi->index = INTERFACE_B;
168 ftdi->index = INTERFACE_C;
174 ftdi->index = INTERFACE_D;
179 ftdi_error_return(-1, "Unknown interface");
185 Deinitializes a ftdi_context.
187 \param ftdi pointer to ftdi_context
189 void ftdi_deinit(struct ftdi_context *ftdi)
191 usb_close_intl (ftdi);
193 if (ftdi->async_usb_buffer != NULL)
195 free(ftdi->async_usb_buffer);
196 ftdi->async_usb_buffer = NULL;
199 if (ftdi->readbuffer != NULL)
201 free(ftdi->readbuffer);
202 ftdi->readbuffer = NULL;
207 Deinitialize and free an ftdi_context.
209 \param ftdi pointer to ftdi_context
211 void ftdi_free(struct ftdi_context *ftdi)
218 Use an already open libusb device.
220 \param ftdi pointer to ftdi_context
221 \param usb libusb usb_dev_handle to use
223 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
230 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
231 needs to be deallocated by ftdi_list_free() after use.
233 \param ftdi pointer to ftdi_context
234 \param devlist Pointer where to store list of found devices
235 \param vendor Vendor ID to search for
236 \param product Product ID to search for
238 \retval >0: number of devices found
239 \retval -1: usb_find_busses() failed
240 \retval -2: usb_find_devices() failed
241 \retval -3: out of memory
243 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
245 struct ftdi_device_list **curdev;
247 struct usb_device *dev;
251 if (usb_find_busses() < 0)
252 ftdi_error_return(-1, "usb_find_busses() failed");
253 if (usb_find_devices() < 0)
254 ftdi_error_return(-2, "usb_find_devices() failed");
258 for (bus = usb_get_busses(); bus; bus = bus->next)
260 for (dev = bus->devices; dev; dev = dev->next)
262 if (dev->descriptor.idVendor == vendor
263 && dev->descriptor.idProduct == product)
265 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
267 ftdi_error_return(-3, "out of memory");
269 (*curdev)->next = NULL;
270 (*curdev)->dev = dev;
272 curdev = &(*curdev)->next;
282 Frees a usb device list.
284 \param devlist USB device list created by ftdi_usb_find_all()
286 void ftdi_list_free(struct ftdi_device_list **devlist)
288 struct ftdi_device_list *curdev, *next;
290 for (curdev = *devlist; curdev != NULL;)
301 Frees a usb device list.
303 \param devlist USB device list created by ftdi_usb_find_all()
305 void ftdi_list_free2(struct ftdi_device_list *devlist)
307 ftdi_list_free(&devlist);
311 Return device ID strings from the usb device.
313 The parameters manufacturer, description and serial may be NULL
314 or pointer to buffers to store the fetched strings.
316 \note Use this function only in combination with ftdi_usb_find_all()
317 as it closes the internal "usb_dev" after use.
319 \param ftdi pointer to ftdi_context
320 \param dev libusb usb_dev to use
321 \param manufacturer Store manufacturer string here if not NULL
322 \param mnf_len Buffer size of manufacturer string
323 \param description Store product description string here if not NULL
324 \param desc_len Buffer size of product description string
325 \param serial Store serial string here if not NULL
326 \param serial_len Buffer size of serial string
329 \retval -1: wrong arguments
330 \retval -4: unable to open device
331 \retval -7: get product manufacturer failed
332 \retval -8: get product description failed
333 \retval -9: get serial number failed
334 \retval -10: unable to close device
336 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
337 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
339 if ((ftdi==NULL) || (dev==NULL))
342 if (!(ftdi->usb_dev = usb_open(dev)))
343 ftdi_error_return(-4, usb_strerror());
345 if (manufacturer != NULL)
347 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
349 usb_close_intl (ftdi);
350 ftdi_error_return(-7, usb_strerror());
354 if (description != NULL)
356 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
358 usb_close_intl (ftdi);
359 ftdi_error_return(-8, usb_strerror());
365 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
367 usb_close_intl (ftdi);
368 ftdi_error_return(-9, usb_strerror());
372 if (usb_close_intl (ftdi) != 0)
373 ftdi_error_return(-10, usb_strerror());
379 Opens a ftdi device given by a usb_device.
381 \param ftdi pointer to ftdi_context
382 \param dev libusb usb_dev to use
385 \retval -3: unable to config device
386 \retval -4: unable to open device
387 \retval -5: unable to claim device
388 \retval -6: reset failed
389 \retval -7: set baudrate failed
391 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
393 int detach_errno = 0;
394 if (!(ftdi->usb_dev = usb_open(dev)))
395 ftdi_error_return(-4, "usb_open() failed");
397 #ifdef LIBUSB_HAS_GET_DRIVER_NP
398 // Try to detach ftdi_sio kernel module.
399 // Returns ENODATA if driver is not loaded.
401 // The return code is kept in a separate variable and only parsed
402 // if usb_set_configuration() or usb_claim_interface() fails as the
403 // detach operation might be denied and everything still works fine.
404 // Likely scenario is a static ftdi_sio kernel module.
405 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
406 detach_errno = errno;
409 // set configuration (needed especially for windows)
410 // tolerate EBUSY: one device with one configuration, but two interfaces
411 // and libftdi sessions to both interfaces (e.g. FT2232)
412 if (dev->descriptor.bNumConfigurations > 0 &&
413 usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
416 usb_close_intl (ftdi);
417 if (detach_errno == EPERM)
419 ftdi_error_return(-8, "inappropriate permissions on device!");
423 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
427 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
429 usb_close_intl (ftdi);
430 if (detach_errno == EPERM)
432 ftdi_error_return(-8, "inappropriate permissions on device!");
436 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
440 if (ftdi_usb_reset (ftdi) != 0)
442 usb_close_intl (ftdi);
443 ftdi_error_return(-6, "ftdi_usb_reset failed");
446 if (ftdi_set_baudrate (ftdi, 9600) != 0)
448 usb_close_intl (ftdi);
449 ftdi_error_return(-7, "set baudrate failed");
452 // Try to guess chip type
453 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
454 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
455 && dev->descriptor.iSerialNumber == 0))
456 ftdi->type = TYPE_BM;
457 else if (dev->descriptor.bcdDevice == 0x200)
458 ftdi->type = TYPE_AM;
459 else if (dev->descriptor.bcdDevice == 0x500)
460 ftdi->type = TYPE_2232C;
461 else if (dev->descriptor.bcdDevice == 0x600)
463 else if (dev->descriptor.bcdDevice == 0x700)
464 ftdi->type = TYPE_2232H;
465 else if (dev->descriptor.bcdDevice == 0x800)
466 ftdi->type = TYPE_4232H;
468 // Set default interface on dual/quad type chips
475 ftdi->index = INTERFACE_A;
481 ftdi_error_return(0, "all fine");
485 Opens the first device with a given vendor and product ids.
487 \param ftdi pointer to ftdi_context
488 \param vendor Vendor ID
489 \param product Product ID
491 \retval same as ftdi_usb_open_desc()
493 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
495 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
499 Opens the first device with a given, vendor id, product id,
500 description and serial.
502 \param ftdi pointer to ftdi_context
503 \param vendor Vendor ID
504 \param product Product ID
505 \param description Description to search for. Use NULL if not needed.
506 \param serial Serial to search for. Use NULL if not needed.
509 \retval -1: usb_find_busses() failed
510 \retval -2: usb_find_devices() failed
511 \retval -3: usb device not found
512 \retval -4: unable to open device
513 \retval -5: unable to claim device
514 \retval -6: reset failed
515 \retval -7: set baudrate failed
516 \retval -8: get product description failed
517 \retval -9: get serial number failed
518 \retval -10: unable to close device
520 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
521 const char* description, const char* serial)
524 struct usb_device *dev;
529 if (usb_find_busses() < 0)
530 ftdi_error_return(-1, "usb_find_busses() failed");
531 if (usb_find_devices() < 0)
532 ftdi_error_return(-2, "usb_find_devices() failed");
534 for (bus = usb_get_busses(); bus; bus = bus->next)
536 for (dev = bus->devices; dev; dev = dev->next)
538 if (dev->descriptor.idVendor == vendor
539 && dev->descriptor.idProduct == product)
541 if (!(ftdi->usb_dev = usb_open(dev)))
542 ftdi_error_return(-4, "usb_open() failed");
544 if (description != NULL)
546 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
548 usb_close_intl (ftdi);
549 ftdi_error_return(-8, "unable to fetch product description");
551 if (strncmp(string, description, sizeof(string)) != 0)
553 if (usb_close_intl (ftdi) != 0)
554 ftdi_error_return(-10, "unable to close device");
560 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
562 usb_close_intl (ftdi);
563 ftdi_error_return(-9, "unable to fetch serial number");
565 if (strncmp(string, serial, sizeof(string)) != 0)
567 if (usb_close_intl (ftdi) != 0)
568 ftdi_error_return(-10, "unable to close device");
573 if (usb_close_intl (ftdi) != 0)
574 ftdi_error_return(-10, "unable to close device");
576 return ftdi_usb_open_dev(ftdi, dev);
582 ftdi_error_return(-3, "device not found");
586 Resets the ftdi device.
588 \param ftdi pointer to ftdi_context
591 \retval -1: FTDI reset failed
593 int ftdi_usb_reset(struct ftdi_context *ftdi)
595 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
596 SIO_RESET_REQUEST, SIO_RESET_SIO,
597 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
598 ftdi_error_return(-1,"FTDI reset failed");
600 // Invalidate data in the readbuffer
601 ftdi->readbuffer_offset = 0;
602 ftdi->readbuffer_remaining = 0;
608 Clears the read buffer on the chip and the internal read buffer.
610 \param ftdi pointer to ftdi_context
613 \retval -1: read buffer purge failed
615 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
617 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
618 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
619 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
620 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
622 // Invalidate data in the readbuffer
623 ftdi->readbuffer_offset = 0;
624 ftdi->readbuffer_remaining = 0;
630 Clears the write buffer on the chip.
632 \param ftdi pointer to ftdi_context
635 \retval -1: write buffer purge failed
637 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
639 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
640 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
641 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
642 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
648 Clears the buffers on the chip and the internal read buffer.
650 \param ftdi pointer to ftdi_context
653 \retval -1: read buffer purge failed
654 \retval -2: write buffer purge failed
656 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
660 result = ftdi_usb_purge_rx_buffer(ftdi);
664 result = ftdi_usb_purge_tx_buffer(ftdi);
672 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
674 \param ftdi pointer to ftdi_context
677 \retval -1: usb_release failed
678 \retval -2: usb_close failed
680 int ftdi_usb_close(struct ftdi_context *ftdi)
684 #ifdef LIBFTDI_LINUX_ASYNC_MODE
685 /* try to release some kernel resources */
686 ftdi_async_complete(ftdi,1);
689 if (ftdi->usb_dev != NULL)
690 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
693 if (usb_close_intl (ftdi)!= 0)
700 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
701 Function is only used internally
704 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
705 unsigned short *value, unsigned short *index)
707 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
708 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
709 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
710 int divisor, best_divisor, best_baud, best_baud_diff;
711 unsigned long encoded_divisor;
720 divisor = 24000000 / baudrate;
722 if (ftdi->type == TYPE_AM)
724 // Round down to supported fraction (AM only)
725 divisor -= am_adjust_dn[divisor & 7];
728 // Try this divisor and the one above it (because division rounds down)
732 for (i = 0; i < 2; i++)
734 int try_divisor = divisor + i;
738 // Round up to supported divisor value
739 if (try_divisor <= 8)
741 // Round up to minimum supported divisor
744 else if (ftdi->type != TYPE_AM && try_divisor < 12)
746 // BM doesn't support divisors 9 through 11 inclusive
749 else if (divisor < 16)
751 // AM doesn't support divisors 9 through 15 inclusive
756 if (ftdi->type == TYPE_AM)
758 // Round up to supported fraction (AM only)
759 try_divisor += am_adjust_up[try_divisor & 7];
760 if (try_divisor > 0x1FFF8)
762 // Round down to maximum supported divisor value (for AM)
763 try_divisor = 0x1FFF8;
768 if (try_divisor > 0x1FFFF)
770 // Round down to maximum supported divisor value (for BM)
771 try_divisor = 0x1FFFF;
775 // Get estimated baud rate (to nearest integer)
776 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
777 // Get absolute difference from requested baud rate
778 if (baud_estimate < baudrate)
780 baud_diff = baudrate - baud_estimate;
784 baud_diff = baud_estimate - baudrate;
786 if (i == 0 || baud_diff < best_baud_diff)
788 // Closest to requested baud rate so far
789 best_divisor = try_divisor;
790 best_baud = baud_estimate;
791 best_baud_diff = baud_diff;
794 // Spot on! No point trying
799 // Encode the best divisor value
800 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
801 // Deal with special cases for encoded value
802 if (encoded_divisor == 1)
804 encoded_divisor = 0; // 3000000 baud
806 else if (encoded_divisor == 0x4001)
808 encoded_divisor = 1; // 2000000 baud (BM only)
810 // Split into "value" and "index" values
811 *value = (unsigned short)(encoded_divisor & 0xFFFF);
812 if (ftdi->type == TYPE_2232C)
814 *index = (unsigned short)(encoded_divisor >> 8);
816 *index |= ftdi->index;
819 *index = (unsigned short)(encoded_divisor >> 16);
821 // Return the nearest baud rate
826 Sets the chip baud rate
828 \param ftdi pointer to ftdi_context
829 \param baudrate baud rate to set
832 \retval -1: invalid baudrate
833 \retval -2: setting baudrate failed
835 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
837 unsigned short value, index;
840 if (ftdi->bitbang_enabled)
842 baudrate = baudrate*4;
845 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
846 if (actual_baudrate <= 0)
847 ftdi_error_return (-1, "Silly baudrate <= 0.");
849 // Check within tolerance (about 5%)
850 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
851 || ((actual_baudrate < baudrate)
852 ? (actual_baudrate * 21 < baudrate * 20)
853 : (baudrate * 21 < actual_baudrate * 20)))
854 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
856 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
857 SIO_SET_BAUDRATE_REQUEST, value,
858 index, NULL, 0, ftdi->usb_write_timeout) != 0)
859 ftdi_error_return (-2, "Setting new baudrate failed");
861 ftdi->baudrate = baudrate;
866 Set (RS232) line characteristics.
867 The break type can only be set via ftdi_set_line_property2()
868 and defaults to "off".
870 \param ftdi pointer to ftdi_context
871 \param bits Number of bits
872 \param sbit Number of stop bits
873 \param parity Parity mode
876 \retval -1: Setting line property failed
878 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
879 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
881 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
885 Set (RS232) line characteristics
887 \param ftdi pointer to ftdi_context
888 \param bits Number of bits
889 \param sbit Number of stop bits
890 \param parity Parity mode
891 \param break_type Break type
894 \retval -1: Setting line property failed
896 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
897 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
898 enum ftdi_break_type break_type)
900 unsigned short value = bits;
905 value |= (0x00 << 8);
908 value |= (0x01 << 8);
911 value |= (0x02 << 8);
914 value |= (0x03 << 8);
917 value |= (0x04 << 8);
924 value |= (0x00 << 11);
927 value |= (0x01 << 11);
930 value |= (0x02 << 11);
937 value |= (0x00 << 14);
940 value |= (0x01 << 14);
944 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
945 SIO_SET_DATA_REQUEST, value,
946 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
947 ftdi_error_return (-1, "Setting new line property failed");
953 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
955 \param ftdi pointer to ftdi_context
956 \param buf Buffer with the data
957 \param size Size of the buffer
959 \retval <0: error code from usb_bulk_write()
960 \retval >0: number of bytes written
962 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
966 int total_written = 0;
968 while (offset < size)
970 int write_size = ftdi->writebuffer_chunksize;
972 if (offset+write_size > size)
973 write_size = size-offset;
975 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
977 ftdi_error_return(ret, "usb bulk write failed");
979 total_written += ret;
980 offset += write_size;
983 return total_written;
986 #ifdef LIBFTDI_LINUX_ASYNC_MODE
987 /* this is strongly dependent on libusb using the same struct layout. If libusb
988 changes in some later version this may break horribly (this is for libusb 0.1.12) */
989 struct usb_dev_handle
992 // some other stuff coming here we don't need
996 Check for pending async urbs
999 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
1001 struct usbdevfs_urb *urb;
1005 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1007 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1008 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
1016 Wait until one or more async URBs are completed by the kernel and mark their
1017 positions in the async-buffer as unused
1019 \param ftdi pointer to ftdi_context
1020 \param wait_for_more if != 0 wait for more than one write to complete
1021 \param timeout_msec max milliseconds to wait
1025 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
1028 struct usbdevfs_urb *urb=NULL;
1034 FD_SET(ftdi->usb_dev->fd, &writefds);
1036 /* init timeout only once, select writes time left after call */
1037 tv.tv_sec = timeout_msec / 1000;
1038 tv.tv_usec = (timeout_msec % 1000) * 1000;
1042 while (_usb_get_async_urbs_pending(ftdi)
1043 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1046 if (keep_going && !wait_for_more)
1048 /* don't wait if repeating only for keep_going */
1053 /* wait for timeout msec or something written ready */
1054 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1057 if (ret == 0 && urb != NULL)
1059 /* got a free urb, mark it */
1060 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1062 /* try to get more urbs that are ready now, but don't wait anymore */
1068 /* no more urbs waiting */
1076 Wait until one or more async URBs are completed by the kernel and mark their
1077 positions in the async-buffer as unused.
1079 \param ftdi pointer to ftdi_context
1080 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1082 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1084 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1088 Stupid libusb does not offer async writes nor does it allow
1089 access to its fd - so we need some hacks here.
1092 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1094 struct usbdevfs_urb *urb;
1095 int bytesdone = 0, requested;
1096 int ret, cleanup_count;
1101 /* find a free urb buffer we can use */
1103 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1105 if (i==ftdi->async_usb_buffer_size)
1107 /* wait until some buffers are free */
1108 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1111 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1113 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1114 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1115 break; /* found a free urb position */
1120 /* no free urb position found */
1124 requested = size - bytesdone;
1125 if (requested > 4096)
1128 memset(urb,0,sizeof(urb));
1130 urb->type = USBDEVFS_URB_TYPE_BULK;
1133 urb->buffer = bytes + bytesdone;
1134 urb->buffer_length = requested;
1136 urb->actual_length = 0;
1137 urb->number_of_packets = 0;
1138 urb->usercontext = 0;
1142 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1144 while (ret < 0 && errno == EINTR);
1146 return ret; /* the caller can read errno to get more info */
1148 bytesdone += requested;
1150 while (bytesdone < size);
1155 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1156 Does not wait for completion of the transfer nor does it make sure that
1157 the transfer was successful.
1159 This function could be extended to use signals and callbacks to inform the
1160 caller of completion or error - but this is not done yet, volunteers welcome.
1162 Works around libusb and directly accesses functions only available on Linux.
1163 Only available if compiled with --with-async-mode.
1165 \param ftdi pointer to ftdi_context
1166 \param buf Buffer with the data
1167 \param size Size of the buffer
1169 \retval <0: error code from usb_bulk_write()
1170 \retval >0: number of bytes written
1172 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1176 int total_written = 0;
1178 while (offset < size)
1180 int write_size = ftdi->writebuffer_chunksize;
1182 if (offset+write_size > size)
1183 write_size = size-offset;
1185 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1187 ftdi_error_return(ret, "usb bulk write async failed");
1189 total_written += ret;
1190 offset += write_size;
1193 return total_written;
1195 #endif // LIBFTDI_LINUX_ASYNC_MODE
1198 Configure write buffer chunk size.
1201 \param ftdi pointer to ftdi_context
1202 \param chunksize Chunk size
1206 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1208 ftdi->writebuffer_chunksize = chunksize;
1213 Get write buffer chunk size.
1215 \param ftdi pointer to ftdi_context
1216 \param chunksize Pointer to store chunk size in
1220 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1222 *chunksize = ftdi->writebuffer_chunksize;
1227 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1229 Automatically strips the two modem status bytes transfered during every read.
1231 \param ftdi pointer to ftdi_context
1232 \param buf Buffer to store data in
1233 \param size Size of the buffer
1235 \retval <0: error code from usb_bulk_read()
1236 \retval 0: no data was available
1237 \retval >0: number of bytes read
1239 \remark This function is not useful in bitbang mode.
1240 Use ftdi_read_pins() to get the current state of the pins.
1242 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1244 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1247 // New hi-speed devices from FTDI use a packet size of 512 bytes
1248 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1253 // everything we want is still in the readbuffer?
1254 if (size <= ftdi->readbuffer_remaining)
1256 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1259 ftdi->readbuffer_remaining -= size;
1260 ftdi->readbuffer_offset += size;
1262 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1266 // something still in the readbuffer, but not enough to satisfy 'size'?
1267 if (ftdi->readbuffer_remaining != 0)
1269 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1272 offset += ftdi->readbuffer_remaining;
1274 // do the actual USB read
1275 while (offset < size && ret > 0)
1277 ftdi->readbuffer_remaining = 0;
1278 ftdi->readbuffer_offset = 0;
1279 /* returns how much received */
1280 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1282 ftdi_error_return(ret, "usb bulk read failed");
1286 // skip FTDI status bytes.
1287 // Maybe stored in the future to enable modem use
1288 num_of_chunks = ret / packet_size;
1289 chunk_remains = ret % packet_size;
1290 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1292 ftdi->readbuffer_offset += 2;
1295 if (ret > packet_size - 2)
1297 for (i = 1; i < num_of_chunks; i++)
1298 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1299 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1301 if (chunk_remains > 2)
1303 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1304 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1306 ret -= 2*num_of_chunks;
1309 ret -= 2*(num_of_chunks-1)+chunk_remains;
1314 // no more data to read?
1319 // data still fits in buf?
1320 if (offset+ret <= size)
1322 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1323 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1326 /* Did we read exactly the right amount of bytes? */
1328 //printf("read_data exact rem %d offset %d\n",
1329 //ftdi->readbuffer_remaining, offset);
1334 // only copy part of the data or size <= readbuffer_chunksize
1335 int part_size = size-offset;
1336 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1338 ftdi->readbuffer_offset += part_size;
1339 ftdi->readbuffer_remaining = ret-part_size;
1340 offset += part_size;
1342 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1343 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1354 Configure read buffer chunk size.
1357 Automatically reallocates the buffer.
1359 \param ftdi pointer to ftdi_context
1360 \param chunksize Chunk size
1364 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1366 unsigned char *new_buf;
1368 // Invalidate all remaining data
1369 ftdi->readbuffer_offset = 0;
1370 ftdi->readbuffer_remaining = 0;
1372 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1373 ftdi_error_return(-1, "out of memory for readbuffer");
1375 ftdi->readbuffer = new_buf;
1376 ftdi->readbuffer_chunksize = chunksize;
1382 Get read buffer chunk size.
1384 \param ftdi pointer to ftdi_context
1385 \param chunksize Pointer to store chunk size in
1389 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1391 *chunksize = ftdi->readbuffer_chunksize;
1397 Enable bitbang mode.
1399 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1401 \param ftdi pointer to ftdi_context
1402 \param bitmask Bitmask to configure lines.
1403 HIGH/ON value configures a line as output.
1406 \retval -1: can't enable bitbang mode
1408 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1410 unsigned short usb_val;
1412 usb_val = bitmask; // low byte: bitmask
1413 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1414 usb_val |= (ftdi->bitbang_mode << 8);
1416 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1417 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1418 NULL, 0, ftdi->usb_write_timeout) != 0)
1419 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1421 ftdi->bitbang_enabled = 1;
1426 Disable bitbang mode.
1428 \param ftdi pointer to ftdi_context
1431 \retval -1: can't disable bitbang mode
1433 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1435 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)
1436 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1438 ftdi->bitbang_enabled = 0;
1443 Enable advanced bitbang mode for FT2232C chips.
1445 \param ftdi pointer to ftdi_context
1446 \param bitmask Bitmask to configure lines.
1447 HIGH/ON value configures a line as output.
1448 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1451 \retval -1: can't enable bitbang mode
1453 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1455 unsigned short usb_val;
1457 usb_val = bitmask; // low byte: bitmask
1458 usb_val |= (mode << 8);
1459 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)
1460 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1462 ftdi->bitbang_mode = mode;
1463 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1468 Directly read pin state. Useful for bitbang mode.
1470 \param ftdi pointer to ftdi_context
1471 \param pins Pointer to store pins into
1474 \retval -1: read pins failed
1476 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1478 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)
1479 ftdi_error_return(-1, "read pins failed");
1487 The FTDI chip keeps data in the internal buffer for a specific
1488 amount of time if the buffer is not full yet to decrease
1489 load on the usb bus.
1491 \param ftdi pointer to ftdi_context
1492 \param latency Value between 1 and 255
1495 \retval -1: latency out of range
1496 \retval -2: unable to set latency timer
1498 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1500 unsigned short usb_val;
1503 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1506 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)
1507 ftdi_error_return(-2, "unable to set latency timer");
1515 \param ftdi pointer to ftdi_context
1516 \param latency Pointer to store latency value in
1519 \retval -1: unable to get latency timer
1521 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1523 unsigned short usb_val;
1524 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)
1525 ftdi_error_return(-1, "reading latency timer failed");
1527 *latency = (unsigned char)usb_val;
1532 Poll modem status information
1534 This function allows the retrieve the two status bytes of the device.
1535 The device sends these bytes also as a header for each read access
1536 where they are discarded by ftdi_read_data(). The chip generates
1537 the two stripped status bytes in the absence of data every 40 ms.
1539 Layout of the first byte:
1540 - B0..B3 - must be 0
1541 - B4 Clear to send (CTS)
1544 - B5 Data set ready (DTS)
1547 - B6 Ring indicator (RI)
1550 - B7 Receive line signal detect (RLSD)
1554 Layout of the second byte:
1555 - B0 Data ready (DR)
1556 - B1 Overrun error (OE)
1557 - B2 Parity error (PE)
1558 - B3 Framing error (FE)
1559 - B4 Break interrupt (BI)
1560 - B5 Transmitter holding register (THRE)
1561 - B6 Transmitter empty (TEMT)
1562 - B7 Error in RCVR FIFO
1564 \param ftdi pointer to ftdi_context
1565 \param status Pointer to store status information in. Must be two bytes.
1568 \retval -1: unable to retrieve status information
1570 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1574 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)
1575 ftdi_error_return(-1, "getting modem status failed");
1577 *status = (usb_val[1] << 8) | usb_val[0];
1583 Set flowcontrol for ftdi chip
1585 \param ftdi pointer to ftdi_context
1586 \param flowctrl flow control to use. should be
1587 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1590 \retval -1: set flow control failed
1592 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1594 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1595 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1596 NULL, 0, ftdi->usb_write_timeout) != 0)
1597 ftdi_error_return(-1, "set flow control failed");
1605 \param ftdi pointer to ftdi_context
1606 \param state state to set line to (1 or 0)
1609 \retval -1: set dtr failed
1611 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1613 unsigned short usb_val;
1616 usb_val = SIO_SET_DTR_HIGH;
1618 usb_val = SIO_SET_DTR_LOW;
1620 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1621 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1622 NULL, 0, ftdi->usb_write_timeout) != 0)
1623 ftdi_error_return(-1, "set dtr failed");
1631 \param ftdi pointer to ftdi_context
1632 \param state state to set line to (1 or 0)
1635 \retval -1 set rts failed
1637 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1639 unsigned short usb_val;
1642 usb_val = SIO_SET_RTS_HIGH;
1644 usb_val = SIO_SET_RTS_LOW;
1646 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1647 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1648 NULL, 0, ftdi->usb_write_timeout) != 0)
1649 ftdi_error_return(-1, "set of rts failed");
1655 Set dtr and rts line in one pass
1657 \param ftdi pointer to ftdi_context
1658 \param dtr DTR state to set line to (1 or 0)
1659 \param rts RTS state to set line to (1 or 0)
1662 \retval -1 set dtr/rts failed
1664 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1666 unsigned short usb_val;
1669 usb_val = SIO_SET_DTR_HIGH;
1671 usb_val = SIO_SET_DTR_LOW;
1674 usb_val |= SIO_SET_RTS_HIGH;
1676 usb_val |= SIO_SET_RTS_LOW;
1678 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1679 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1680 NULL, 0, ftdi->usb_write_timeout) != 0)
1681 ftdi_error_return(-1, "set of rts/dtr failed");
1687 Set the special event character
1689 \param ftdi pointer to ftdi_context
1690 \param eventch Event character
1691 \param enable 0 to disable the event character, non-zero otherwise
1694 \retval -1: unable to set event character
1696 int ftdi_set_event_char(struct ftdi_context *ftdi,
1697 unsigned char eventch, unsigned char enable)
1699 unsigned short usb_val;
1705 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)
1706 ftdi_error_return(-1, "setting event character failed");
1714 \param ftdi pointer to ftdi_context
1715 \param errorch Error character
1716 \param enable 0 to disable the error character, non-zero otherwise
1719 \retval -1: unable to set error character
1721 int ftdi_set_error_char(struct ftdi_context *ftdi,
1722 unsigned char errorch, unsigned char enable)
1724 unsigned short usb_val;
1730 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)
1731 ftdi_error_return(-1, "setting error character failed");
1739 \param ftdi pointer to ftdi_context
1740 \param eeprom Pointer to ftdi_eeprom
1744 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1746 ftdi->eeprom_size=size;
1751 Init eeprom with default values.
1753 \param eeprom Pointer to ftdi_eeprom
1755 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1757 eeprom->vendor_id = 0x0403;
1758 eeprom->product_id = 0x6001;
1760 eeprom->self_powered = 1;
1761 eeprom->remote_wakeup = 1;
1762 eeprom->BM_type_chip = 1;
1764 eeprom->in_is_isochronous = 0;
1765 eeprom->out_is_isochronous = 0;
1766 eeprom->suspend_pull_downs = 0;
1768 eeprom->use_serial = 0;
1769 eeprom->change_usb_version = 0;
1770 eeprom->usb_version = 0x0200;
1771 eeprom->max_power = 0;
1773 eeprom->manufacturer = NULL;
1774 eeprom->product = NULL;
1775 eeprom->serial = NULL;
1777 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1781 Build binary output from ftdi_eeprom structure.
1782 Output is suitable for ftdi_write_eeprom().
1784 \param eeprom Pointer to ftdi_eeprom
1785 \param output Buffer of 128 bytes to store eeprom image to
1787 \retval >0: used eeprom size
1788 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1790 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1793 unsigned short checksum, value;
1794 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1797 if (eeprom->manufacturer != NULL)
1798 manufacturer_size = strlen(eeprom->manufacturer);
1799 if (eeprom->product != NULL)
1800 product_size = strlen(eeprom->product);
1801 if (eeprom->serial != NULL)
1802 serial_size = strlen(eeprom->serial);
1804 size_check = eeprom->size;
1805 size_check -= 28; // 28 are always in use (fixed)
1807 // Top half of a 256byte eeprom is used just for strings and checksum
1808 // it seems that the FTDI chip will not read these strings from the lower half
1809 // Each string starts with two bytes; offset and type (0x03 for string)
1810 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1811 if (eeprom->size>=256)size_check = 120;
1812 size_check -= manufacturer_size*2;
1813 size_check -= product_size*2;
1814 size_check -= serial_size*2;
1816 // eeprom size exceeded?
1821 memset (output, 0, eeprom->size);
1823 // Addr 00: Stay 00 00
1824 // Addr 02: Vendor ID
1825 output[0x02] = eeprom->vendor_id;
1826 output[0x03] = eeprom->vendor_id >> 8;
1828 // Addr 04: Product ID
1829 output[0x04] = eeprom->product_id;
1830 output[0x05] = eeprom->product_id >> 8;
1832 // Addr 06: Device release number (0400h for BM features)
1833 output[0x06] = 0x00;
1835 if (eeprom->BM_type_chip == 1)
1836 output[0x07] = 0x04;
1838 output[0x07] = 0x02;
1840 // Addr 08: Config descriptor
1842 // Bit 6: 1 if this device is self powered, 0 if bus powered
1843 // Bit 5: 1 if this device uses remote wakeup
1844 // Bit 4: 1 if this device is battery powered
1846 if (eeprom->self_powered == 1)
1848 if (eeprom->remote_wakeup == 1)
1852 // Addr 09: Max power consumption: max power = value * 2 mA
1853 output[0x09] = eeprom->max_power;
1855 // Addr 0A: Chip configuration
1856 // Bit 7: 0 - reserved
1857 // Bit 6: 0 - reserved
1858 // Bit 5: 0 - reserved
1859 // Bit 4: 1 - Change USB version
1860 // Bit 3: 1 - Use the serial number string
1861 // Bit 2: 1 - Enable suspend pull downs for lower power
1862 // Bit 1: 1 - Out EndPoint is Isochronous
1863 // Bit 0: 1 - In EndPoint is Isochronous
1866 if (eeprom->in_is_isochronous == 1)
1868 if (eeprom->out_is_isochronous == 1)
1870 if (eeprom->suspend_pull_downs == 1)
1872 if (eeprom->use_serial == 1)
1874 if (eeprom->change_usb_version == 1)
1878 // Addr 0B: reserved
1879 output[0x0B] = 0x00;
1881 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1882 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1883 if (eeprom->change_usb_version == 1)
1885 output[0x0C] = eeprom->usb_version;
1886 output[0x0D] = eeprom->usb_version >> 8;
1890 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1891 // Addr 0F: Length of manufacturer string
1892 output[0x0F] = manufacturer_size*2 + 2;
1894 // Addr 10: Offset of the product string + 0x80, calculated later
1895 // Addr 11: Length of product string
1896 output[0x11] = product_size*2 + 2;
1898 // Addr 12: Offset of the serial string + 0x80, calculated later
1899 // Addr 13: Length of serial string
1900 output[0x13] = serial_size*2 + 2;
1904 if (eeprom->size>=256) i = 0x80;
1907 // Output manufacturer
1908 output[0x0E] = i | 0x80; // calculate offset
1909 output[i++] = manufacturer_size*2 + 2;
1910 output[i++] = 0x03; // type: string
1911 for (j = 0; j < manufacturer_size; j++)
1913 output[i] = eeprom->manufacturer[j], i++;
1914 output[i] = 0x00, i++;
1917 // Output product name
1918 output[0x10] = i | 0x80; // calculate offset
1919 output[i] = product_size*2 + 2, i++;
1920 output[i] = 0x03, i++;
1921 for (j = 0; j < product_size; j++)
1923 output[i] = eeprom->product[j], i++;
1924 output[i] = 0x00, i++;
1928 output[0x12] = i | 0x80; // calculate offset
1929 output[i] = serial_size*2 + 2, i++;
1930 output[i] = 0x03, i++;
1931 for (j = 0; j < serial_size; j++)
1933 output[i] = eeprom->serial[j], i++;
1934 output[i] = 0x00, i++;
1937 // calculate checksum
1940 for (i = 0; i < eeprom->size/2-1; i++)
1942 value = output[i*2];
1943 value += output[(i*2)+1] << 8;
1945 checksum = value^checksum;
1946 checksum = (checksum << 1) | (checksum >> 15);
1949 output[eeprom->size-2] = checksum;
1950 output[eeprom->size-1] = checksum >> 8;
1956 Decode binary EEPROM image into an ftdi_eeprom structure.
1958 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1959 \param buf Buffer of \a size bytes of raw eeprom data
1960 \param size size size of eeprom data in bytes
1963 \retval -1: something went wrong
1965 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
1966 FIXME: Strings are malloc'ed here and should be freed somewhere
1968 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
1971 unsigned short checksum, eeprom_checksum, value;
1972 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1974 int eeprom_size = 128;
1976 size_check = eeprom->size;
1977 size_check -= 28; // 28 are always in use (fixed)
1979 // Top half of a 256byte eeprom is used just for strings and checksum
1980 // it seems that the FTDI chip will not read these strings from the lower half
1981 // Each string starts with two bytes; offset and type (0x03 for string)
1982 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1983 if (eeprom->size>=256)size_check = 120;
1984 size_check -= manufacturer_size*2;
1985 size_check -= product_size*2;
1986 size_check -= serial_size*2;
1988 // eeprom size exceeded?
1993 // empty eeprom struct
1994 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
1996 // Addr 00: Stay 00 00
1998 // Addr 02: Vendor ID
1999 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2001 // Addr 04: Product ID
2002 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2004 value = buf[0x06] + (buf[0x07]<<8);
2008 eeprom->BM_type_chip = 1;
2011 eeprom->BM_type_chip = 0;
2013 default: // Unknown device
2014 eeprom->BM_type_chip = 0;
2018 // Addr 08: Config descriptor
2020 // Bit 6: 1 if this device is self powered, 0 if bus powered
2021 // Bit 5: 1 if this device uses remote wakeup
2022 // Bit 4: 1 if this device is battery powered
2024 if (j&0x40) eeprom->self_powered = 1;
2025 if (j&0x20) eeprom->remote_wakeup = 1;
2027 // Addr 09: Max power consumption: max power = value * 2 mA
2028 eeprom->max_power = buf[0x09];
2030 // Addr 0A: Chip configuration
2031 // Bit 7: 0 - reserved
2032 // Bit 6: 0 - reserved
2033 // Bit 5: 0 - reserved
2034 // Bit 4: 1 - Change USB version
2035 // Bit 3: 1 - Use the serial number string
2036 // Bit 2: 1 - Enable suspend pull downs for lower power
2037 // Bit 1: 1 - Out EndPoint is Isochronous
2038 // Bit 0: 1 - In EndPoint is Isochronous
2041 if (j&0x01) eeprom->in_is_isochronous = 1;
2042 if (j&0x02) eeprom->out_is_isochronous = 1;
2043 if (j&0x04) eeprom->suspend_pull_downs = 1;
2044 if (j&0x08) eeprom->use_serial = 1;
2045 if (j&0x10) eeprom->change_usb_version = 1;
2047 // Addr 0B: reserved
2049 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2050 // Addr 0D: USB version high byte when 0x0A bit 4 is set
2051 if (eeprom->change_usb_version == 1)
2053 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2056 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2057 // Addr 0F: Length of manufacturer string
2058 manufacturer_size = buf[0x0F]/2;
2059 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2060 else eeprom->manufacturer = NULL;
2062 // Addr 10: Offset of the product string + 0x80, calculated later
2063 // Addr 11: Length of product string
2064 product_size = buf[0x11]/2;
2065 if (product_size > 0) eeprom->product = malloc(product_size);
2066 else eeprom->product = NULL;
2068 // Addr 12: Offset of the serial string + 0x80, calculated later
2069 // Addr 13: Length of serial string
2070 serial_size = buf[0x13]/2;
2071 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2072 else eeprom->serial = NULL;
2074 // Decode manufacturer
2075 i = buf[0x0E] & 0x7f; // offset
2076 for (j=0;j<manufacturer_size-1;j++)
2078 eeprom->manufacturer[j] = buf[2*j+i+2];
2080 eeprom->manufacturer[j] = '\0';
2082 // Decode product name
2083 i = buf[0x10] & 0x7f; // offset
2084 for (j=0;j<product_size-1;j++)
2086 eeprom->product[j] = buf[2*j+i+2];
2088 eeprom->product[j] = '\0';
2091 i = buf[0x12] & 0x7f; // offset
2092 for (j=0;j<serial_size-1;j++)
2094 eeprom->serial[j] = buf[2*j+i+2];
2096 eeprom->serial[j] = '\0';
2101 for (i = 0; i < eeprom_size/2-1; i++)
2104 value += buf[(i*2)+1] << 8;
2106 checksum = value^checksum;
2107 checksum = (checksum << 1) | (checksum >> 15);
2110 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2112 if (eeprom_checksum != checksum)
2114 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2124 \param ftdi pointer to ftdi_context
2125 \param eeprom Pointer to store eeprom into
2128 \retval -1: read failed
2130 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2134 for (i = 0; i < ftdi->eeprom_size/2; i++)
2136 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)
2137 ftdi_error_return(-1, "reading eeprom failed");
2144 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2145 Function is only used internally
2148 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2150 return ((value & 1) << 1) |
2151 ((value & 2) << 5) |
2152 ((value & 4) >> 2) |
2153 ((value & 8) << 4) |
2154 ((value & 16) >> 1) |
2155 ((value & 32) >> 1) |
2156 ((value & 64) >> 4) |
2157 ((value & 128) >> 2);
2161 Read the FTDIChip-ID from R-type devices
2163 \param ftdi pointer to ftdi_context
2164 \param chipid Pointer to store FTDIChip-ID
2167 \retval -1: read failed
2169 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2171 unsigned int a = 0, b = 0;
2173 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)
2175 a = a << 8 | a >> 8;
2176 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)
2178 b = b << 8 | b >> 8;
2179 a = (a << 16) | (b & 0xFFFF);
2180 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2181 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2182 *chipid = a ^ 0xa5f0f7d1;
2187 ftdi_error_return(-1, "read of FTDIChip-ID failed");
2191 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2192 Call this function then do a write then call again to see if size changes, if so write again.
2194 \param ftdi pointer to ftdi_context
2195 \param eeprom Pointer to store eeprom into
2196 \param maxsize the size of the buffer to read into
2198 \retval size of eeprom
2200 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2202 int i=0,j,minsize=32;
2207 for (j = 0; i < maxsize/2 && j<size; j++)
2209 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2210 SIO_READ_EEPROM_REQUEST, 0, i,
2211 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2212 ftdi_error_return(-1, "reading eeprom failed");
2217 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2225 \param ftdi pointer to ftdi_context
2226 \param eeprom Pointer to read eeprom from
2229 \retval -1: read failed
2231 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2233 unsigned short usb_val, status;
2236 /* These commands were traced while running MProg */
2237 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2239 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2241 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2244 for (i = 0; i < ftdi->eeprom_size/2; i++)
2246 usb_val = eeprom[i*2];
2247 usb_val += eeprom[(i*2)+1] << 8;
2248 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2249 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2250 NULL, 0, ftdi->usb_write_timeout) != 0)
2251 ftdi_error_return(-1, "unable to write eeprom");
2260 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2262 \param ftdi pointer to ftdi_context
2265 \retval -1: erase failed
2267 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2269 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2270 ftdi_error_return(-1, "unable to erase eeprom");
2276 Get string representation for last error code
2278 \param ftdi pointer to ftdi_context
2280 \retval Pointer to error string
2282 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2284 return ftdi->error_str;
2287 /* @} end of doxygen libftdi group */