libftdi  0.20
ftdi.c
Go to the documentation of this file.
00001 /***************************************************************************
00002                           ftdi.c  -  description
00003                              -------------------
00004     begin                : Fri Apr 4 2003
00005     copyright            : (C) 2003-2010 by Intra2net AG
00006     email                : opensource@intra2net.com
00007  ***************************************************************************/
00008 
00009 /***************************************************************************
00010  *                                                                         *
00011  *   This program is free software; you can redistribute it and/or modify  *
00012  *   it under the terms of the GNU Lesser General Public License           *
00013  *   version 2.1 as published by the Free Software Foundation;             *
00014  *                                                                         *
00015  ***************************************************************************/
00016 
00029 /* @{ */
00030 
00031 #include <usb.h>
00032 #include <string.h>
00033 #include <errno.h>
00034 #include <stdio.h>
00035 
00036 #include "ftdi.h"
00037 
00038 /* stuff needed for async write */
00039 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00040 #include <sys/ioctl.h>
00041 #include <sys/select.h>
00042 #include <sys/types.h>
00043 #include <unistd.h>
00044 #include <linux/usbdevice_fs.h>
00045 #endif
00046 
00047 #define ftdi_error_return(code, str) do {  \
00048         if ( ftdi )                        \
00049             ftdi->error_str = str;         \
00050         else                               \
00051             fprintf(stderr, str);          \
00052         return code;                       \
00053    } while(0);
00054 
00055 
00065 static int ftdi_usb_close_internal (struct ftdi_context *ftdi)
00066 {
00067     int ret = 0;
00068 
00069     if (ftdi && ftdi->usb_dev)
00070     {
00071        ret = usb_close (ftdi->usb_dev);
00072        ftdi->usb_dev = NULL;
00073     }
00074 
00075     return ret;
00076 }
00077 
00088 int ftdi_init(struct ftdi_context *ftdi)
00089 {
00090     unsigned int i;
00091 
00092     ftdi->usb_dev = NULL;
00093     ftdi->usb_read_timeout = 5000;
00094     ftdi->usb_write_timeout = 5000;
00095 
00096     ftdi->type = TYPE_BM;    /* chip type */
00097     ftdi->baudrate = -1;
00098     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
00099 
00100     ftdi->readbuffer = NULL;
00101     ftdi->readbuffer_offset = 0;
00102     ftdi->readbuffer_remaining = 0;
00103     ftdi->writebuffer_chunksize = 4096;
00104     ftdi->max_packet_size = 0;
00105 
00106     ftdi->interface = 0;
00107     ftdi->index = 0;
00108     ftdi->in_ep = 0x02;
00109     ftdi->out_ep = 0x81;
00110     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
00111 
00112     ftdi->error_str = NULL;
00113 
00114 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00115     ftdi->async_usb_buffer_size=10;
00116     if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
00117         ftdi_error_return(-1, "out of memory for async usb buffer");
00118 
00119     /* initialize async usb buffer with unused-marker */
00120     for (i=0; i < ftdi->async_usb_buffer_size; i++)
00121         ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
00122 #else
00123     ftdi->async_usb_buffer_size=0;
00124     ftdi->async_usb_buffer = NULL;
00125 #endif
00126 
00127     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
00128 
00129     ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;
00130 
00131     /* All fine. Now allocate the readbuffer */
00132     return ftdi_read_data_set_chunksize(ftdi, 4096);
00133 }
00134 
00140 struct ftdi_context *ftdi_new(void)
00141 {
00142     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
00143 
00144     if (ftdi == NULL)
00145     {
00146         return NULL;
00147     }
00148 
00149     if (ftdi_init(ftdi) != 0)
00150     {
00151         free(ftdi);
00152         return NULL;
00153     }
00154 
00155     return ftdi;
00156 }
00157 
00168 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
00169 {
00170     if (ftdi == NULL)
00171         ftdi_error_return(-2, "USB device unavailable");
00172 
00173     switch (interface)
00174     {
00175         case INTERFACE_ANY:
00176         case INTERFACE_A:
00177             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
00178             break;
00179         case INTERFACE_B:
00180             ftdi->interface = 1;
00181             ftdi->index     = INTERFACE_B;
00182             ftdi->in_ep     = 0x04;
00183             ftdi->out_ep    = 0x83;
00184             break;
00185         case INTERFACE_C:
00186             ftdi->interface = 2;
00187             ftdi->index     = INTERFACE_C;
00188             ftdi->in_ep     = 0x06;
00189             ftdi->out_ep    = 0x85;
00190             break;
00191         case INTERFACE_D:
00192             ftdi->interface = 3;
00193             ftdi->index     = INTERFACE_D;
00194             ftdi->in_ep     = 0x08;
00195             ftdi->out_ep    = 0x87;
00196             break;
00197         default:
00198             ftdi_error_return(-1, "Unknown interface");
00199     }
00200     return 0;
00201 }
00202 
00208 void ftdi_deinit(struct ftdi_context *ftdi)
00209 {
00210     if (ftdi == NULL)
00211         return;
00212 
00213     ftdi_usb_close_internal (ftdi);
00214 
00215     if (ftdi->async_usb_buffer != NULL)
00216     {
00217         free(ftdi->async_usb_buffer);
00218         ftdi->async_usb_buffer = NULL;
00219     }
00220 
00221     if (ftdi->readbuffer != NULL)
00222     {
00223         free(ftdi->readbuffer);
00224         ftdi->readbuffer = NULL;
00225     }
00226 }
00227 
00233 void ftdi_free(struct ftdi_context *ftdi)
00234 {
00235     ftdi_deinit(ftdi);
00236     free(ftdi);
00237 }
00238 
00245 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
00246 {
00247     if (ftdi == NULL)
00248         return;
00249 
00250     ftdi->usb_dev = usb;
00251 }
00252 
00253 
00268 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
00269 {
00270     struct ftdi_device_list **curdev;
00271     struct usb_bus *bus;
00272     struct usb_device *dev;
00273     int count = 0;
00274 
00275     usb_init();
00276     if (usb_find_busses() < 0)
00277         ftdi_error_return(-1, "usb_find_busses() failed");
00278     if (usb_find_devices() < 0)
00279         ftdi_error_return(-2, "usb_find_devices() failed");
00280 
00281     curdev = devlist;
00282     *curdev = NULL;
00283     for (bus = usb_get_busses(); bus; bus = bus->next)
00284     {
00285         for (dev = bus->devices; dev; dev = dev->next)
00286         {
00287             if (dev->descriptor.idVendor == vendor
00288                     && dev->descriptor.idProduct == product)
00289             {
00290                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
00291                 if (!*curdev)
00292                     ftdi_error_return(-3, "out of memory");
00293 
00294                 (*curdev)->next = NULL;
00295                 (*curdev)->dev = dev;
00296 
00297                 curdev = &(*curdev)->next;
00298                 count++;
00299             }
00300         }
00301     }
00302 
00303     return count;
00304 }
00305 
00311 void ftdi_list_free(struct ftdi_device_list **devlist)
00312 {
00313     struct ftdi_device_list *curdev, *next;
00314 
00315     for (curdev = *devlist; curdev != NULL;)
00316     {
00317         next = curdev->next;
00318         free(curdev);
00319         curdev = next;
00320     }
00321 
00322     *devlist = NULL;
00323 }
00324 
00330 void ftdi_list_free2(struct ftdi_device_list *devlist)
00331 {
00332     ftdi_list_free(&devlist);
00333 }
00334 
00361 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
00362                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
00363 {
00364     if ((ftdi==NULL) || (dev==NULL))
00365         return -1;
00366 
00367     if (!(ftdi->usb_dev = usb_open(dev)))
00368         ftdi_error_return(-4, usb_strerror());
00369 
00370     if (manufacturer != NULL)
00371     {
00372         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
00373         {
00374             ftdi_usb_close_internal (ftdi);
00375             ftdi_error_return(-7, usb_strerror());
00376         }
00377     }
00378 
00379     if (description != NULL)
00380     {
00381         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
00382         {
00383             ftdi_usb_close_internal (ftdi);
00384             ftdi_error_return(-8, usb_strerror());
00385         }
00386     }
00387 
00388     if (serial != NULL)
00389     {
00390         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
00391         {
00392             ftdi_usb_close_internal (ftdi);
00393             ftdi_error_return(-9, usb_strerror());
00394         }
00395     }
00396 
00397     if (ftdi_usb_close_internal (ftdi) != 0)
00398         ftdi_error_return(-10, usb_strerror());
00399 
00400     return 0;
00401 }
00402 
00409 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, struct usb_device *dev)
00410 {
00411     unsigned int packet_size;
00412 
00413     // Sanity check
00414     if (ftdi == NULL || dev == NULL)
00415         return 64;
00416 
00417     // Determine maximum packet size. Init with default value.
00418     // New hi-speed devices from FTDI use a packet size of 512 bytes
00419     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
00420     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H)
00421         packet_size = 512;
00422     else
00423         packet_size = 64;
00424 
00425     if (dev->descriptor.bNumConfigurations > 0 && dev->config)
00426     {
00427         struct usb_config_descriptor config = dev->config[0];
00428 
00429         if (ftdi->interface < config.bNumInterfaces)
00430         {
00431             struct usb_interface interface = config.interface[ftdi->interface];
00432             if (interface.num_altsetting > 0)
00433             {
00434                 struct usb_interface_descriptor descriptor = interface.altsetting[0];
00435                 if (descriptor.bNumEndpoints > 0)
00436                 {
00437                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
00438                 }
00439             }
00440         }
00441     }
00442 
00443     return packet_size;
00444 }
00445 
00460 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
00461 {
00462     int detach_errno = 0;
00463     int config_val = 1;
00464 
00465     if (ftdi == NULL)
00466         ftdi_error_return(-8, "ftdi context invalid");
00467 
00468     if (!(ftdi->usb_dev = usb_open(dev)))
00469         ftdi_error_return(-4, "usb_open() failed");
00470 
00471 #ifdef LIBUSB_HAS_GET_DRIVER_NP
00472     // Try to detach ftdi_sio kernel module.
00473     // Returns ENODATA if driver is not loaded.
00474     //
00475     // The return code is kept in a separate variable and only parsed
00476     // if usb_set_configuration() or usb_claim_interface() fails as the
00477     // detach operation might be denied and everything still works fine.
00478     // Likely scenario is a static ftdi_sio kernel module.
00479     if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
00480     {
00481         if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
00482             detach_errno = errno;
00483     }
00484 #endif
00485 
00486 #ifdef __WIN32__
00487     // set configuration (needed especially for windows)
00488     // tolerate EBUSY: one device with one configuration, but two interfaces
00489     //    and libftdi sessions to both interfaces (e.g. FT2232)
00490 
00491     if (dev->descriptor.bNumConfigurations > 0)
00492     {
00493         // libusb-win32 on Windows 64 can return a null pointer for a valid device
00494         if (dev->config)
00495             config_val = dev->config[0].bConfigurationValue;
00496 
00497         if (usb_set_configuration(ftdi->usb_dev, config_val) &&
00498             errno != EBUSY)
00499         {
00500             ftdi_usb_close_internal (ftdi);
00501             if (detach_errno == EPERM)
00502             {
00503                 ftdi_error_return(-8, "inappropriate permissions on device!");
00504             }
00505             else
00506             {
00507                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
00508             }
00509         }
00510     }
00511 #endif
00512 
00513     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
00514     {
00515         ftdi_usb_close_internal (ftdi);
00516         if (detach_errno == EPERM)
00517         {
00518             ftdi_error_return(-8, "inappropriate permissions on device!");
00519         }
00520         else
00521         {
00522             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
00523         }
00524     }
00525 
00526     if (ftdi_usb_reset (ftdi) != 0)
00527     {
00528         ftdi_usb_close_internal (ftdi);
00529         ftdi_error_return(-6, "ftdi_usb_reset failed");
00530     }
00531 
00532     // Try to guess chip type
00533     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
00534     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
00535             && dev->descriptor.iSerialNumber == 0))
00536         ftdi->type = TYPE_BM;
00537     else if (dev->descriptor.bcdDevice == 0x200)
00538         ftdi->type = TYPE_AM;
00539     else if (dev->descriptor.bcdDevice == 0x500)
00540         ftdi->type = TYPE_2232C;
00541     else if (dev->descriptor.bcdDevice == 0x600)
00542         ftdi->type = TYPE_R;
00543     else if (dev->descriptor.bcdDevice == 0x700)
00544         ftdi->type = TYPE_2232H;
00545     else if (dev->descriptor.bcdDevice == 0x800)
00546         ftdi->type = TYPE_4232H;
00547     else if (dev->descriptor.bcdDevice == 0x900)
00548         ftdi->type = TYPE_232H;
00549 
00550     // Set default interface on dual/quad type chips
00551     switch(ftdi->type)
00552     {
00553         case TYPE_2232C:
00554         case TYPE_2232H:
00555         case TYPE_4232H:
00556             if (!ftdi->index)
00557                 ftdi->index = INTERFACE_A;
00558             break;
00559         default:
00560             break;
00561     }
00562 
00563     // Determine maximum packet size
00564     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
00565 
00566     if (ftdi_set_baudrate (ftdi, 9600) != 0)
00567     {
00568         ftdi_usb_close_internal (ftdi);
00569         ftdi_error_return(-7, "set baudrate failed");
00570     }
00571 
00572     ftdi_error_return(0, "all fine");
00573 }
00574 
00584 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
00585 {
00586     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
00587 }
00588 
00611 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
00612                        const char* description, const char* serial)
00613 {
00614     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
00615 }
00616 
00641 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
00642                        const char* description, const char* serial, unsigned int index)
00643 {
00644     struct usb_bus *bus;
00645     struct usb_device *dev;
00646     char string[256];
00647 
00648     usb_init();
00649 
00650     if (usb_find_busses() < 0)
00651         ftdi_error_return(-1, "usb_find_busses() failed");
00652     if (usb_find_devices() < 0)
00653         ftdi_error_return(-2, "usb_find_devices() failed");
00654 
00655     if (ftdi == NULL)
00656         ftdi_error_return(-11, "ftdi context invalid");
00657 
00658     for (bus = usb_get_busses(); bus; bus = bus->next)
00659     {
00660         for (dev = bus->devices; dev; dev = dev->next)
00661         {
00662             if (dev->descriptor.idVendor == vendor
00663                     && dev->descriptor.idProduct == product)
00664             {
00665                 if (!(ftdi->usb_dev = usb_open(dev)))
00666                     ftdi_error_return(-4, "usb_open() failed");
00667 
00668                 if (description != NULL)
00669                 {
00670                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
00671                     {
00672                         ftdi_usb_close_internal (ftdi);
00673                         ftdi_error_return(-8, "unable to fetch product description");
00674                     }
00675                     if (strncmp(string, description, sizeof(string)) != 0)
00676                     {
00677                         if (ftdi_usb_close_internal (ftdi) != 0)
00678                             ftdi_error_return(-10, "unable to close device");
00679                         continue;
00680                     }
00681                 }
00682                 if (serial != NULL)
00683                 {
00684                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
00685                     {
00686                         ftdi_usb_close_internal (ftdi);
00687                         ftdi_error_return(-9, "unable to fetch serial number");
00688                     }
00689                     if (strncmp(string, serial, sizeof(string)) != 0)
00690                     {
00691                         if (ftdi_usb_close_internal (ftdi) != 0)
00692                             ftdi_error_return(-10, "unable to close device");
00693                         continue;
00694                     }
00695                 }
00696 
00697                 if (ftdi_usb_close_internal (ftdi) != 0)
00698                     ftdi_error_return(-10, "unable to close device");
00699 
00700                 if (index > 0)
00701                 {
00702                     index--;
00703                     continue;
00704                 }
00705 
00706                 return ftdi_usb_open_dev(ftdi, dev);
00707             }
00708         }
00709     }
00710 
00711     // device not found
00712     ftdi_error_return(-3, "device not found");
00713 }
00714 
00742 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
00743 {
00744     if (ftdi == NULL)
00745         ftdi_error_return(-12, "ftdi context invalid");
00746 
00747     if (description[0] == 0 || description[1] != ':')
00748         ftdi_error_return(-11, "illegal description format");
00749 
00750     if (description[0] == 'd')
00751     {
00752         struct usb_bus *bus;
00753         struct usb_device *dev;
00754 
00755         usb_init();
00756 
00757         if (usb_find_busses() < 0)
00758             ftdi_error_return(-1, "usb_find_busses() failed");
00759         if (usb_find_devices() < 0)
00760             ftdi_error_return(-2, "usb_find_devices() failed");
00761 
00762         for (bus = usb_get_busses(); bus; bus = bus->next)
00763         {
00764             for (dev = bus->devices; dev; dev = dev->next)
00765             {
00766                 /* XXX: This doesn't handle symlinks/odd paths/etc... */
00767                 const char *desc = description + 2;
00768                 size_t len = strlen(bus->dirname);
00769                 if (strncmp(desc, bus->dirname, len))
00770                     continue;
00771                 desc += len;
00772                 if (desc[0] != '/')
00773                     continue;
00774                 ++desc;
00775                 if (strcmp(desc, dev->filename))
00776                     continue;
00777                 return ftdi_usb_open_dev(ftdi, dev);
00778             }
00779         }
00780 
00781         // device not found
00782         ftdi_error_return(-3, "device not found");
00783     }
00784     else if (description[0] == 'i' || description[0] == 's')
00785     {
00786         unsigned int vendor;
00787         unsigned int product;
00788         unsigned int index=0;
00789         const char *serial=NULL;
00790         const char *startp, *endp;
00791 
00792         errno=0;
00793         startp=description+2;
00794         vendor=strtoul((char*)startp,(char**)&endp,0);
00795         if (*endp != ':' || endp == startp || errno != 0)
00796             ftdi_error_return(-11, "illegal description format");
00797 
00798         startp=endp+1;
00799         product=strtoul((char*)startp,(char**)&endp,0);
00800         if (endp == startp || errno != 0)
00801             ftdi_error_return(-11, "illegal description format");
00802 
00803         if (description[0] == 'i' && *endp != 0)
00804         {
00805             /* optional index field in i-mode */
00806             if (*endp != ':')
00807                 ftdi_error_return(-11, "illegal description format");
00808 
00809             startp=endp+1;
00810             index=strtoul((char*)startp,(char**)&endp,0);
00811             if (*endp != 0 || endp == startp || errno != 0)
00812                 ftdi_error_return(-11, "illegal description format");
00813         }
00814         if (description[0] == 's')
00815         {
00816             if (*endp != ':')
00817                 ftdi_error_return(-11, "illegal description format");
00818 
00819             /* rest of the description is the serial */
00820             serial=endp+1;
00821         }
00822 
00823         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
00824     }
00825     else
00826     {
00827         ftdi_error_return(-11, "illegal description format");
00828     }
00829 }
00830 
00840 int ftdi_usb_reset(struct ftdi_context *ftdi)
00841 {
00842     if (ftdi == NULL || ftdi->usb_dev == NULL)
00843         ftdi_error_return(-2, "USB device unavailable");
00844 
00845     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00846                         SIO_RESET_REQUEST, SIO_RESET_SIO,
00847                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00848         ftdi_error_return(-1,"FTDI reset failed");
00849 
00850     // Invalidate data in the readbuffer
00851     ftdi->readbuffer_offset = 0;
00852     ftdi->readbuffer_remaining = 0;
00853 
00854     return 0;
00855 }
00856 
00866 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
00867 {
00868     if (ftdi == NULL || ftdi->usb_dev == NULL)
00869         ftdi_error_return(-2, "USB device unavailable");
00870 
00871     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00872                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
00873                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00874         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
00875 
00876     // Invalidate data in the readbuffer
00877     ftdi->readbuffer_offset = 0;
00878     ftdi->readbuffer_remaining = 0;
00879 
00880     return 0;
00881 }
00882 
00892 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
00893 {
00894     if (ftdi == NULL || ftdi->usb_dev == NULL)
00895         ftdi_error_return(-2, "USB device unavailable");
00896 
00897     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00898                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
00899                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00900         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
00901 
00902     return 0;
00903 }
00904 
00915 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
00916 {
00917     int result;
00918 
00919     if (ftdi == NULL || ftdi->usb_dev == NULL)
00920         ftdi_error_return(-3, "USB device unavailable");
00921 
00922     result = ftdi_usb_purge_rx_buffer(ftdi);
00923     if (result < 0)
00924         return -1;
00925 
00926     result = ftdi_usb_purge_tx_buffer(ftdi);
00927     if (result < 0)
00928         return -2;
00929 
00930     return 0;
00931 }
00932 
00933 
00934 
00945 int ftdi_usb_close(struct ftdi_context *ftdi)
00946 {
00947     int rtn = 0;
00948 
00949     if (ftdi == NULL)
00950         ftdi_error_return(-3, "ftdi context invalid");
00951 
00952 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00953     /* try to release some kernel resources */
00954     ftdi_async_complete(ftdi,1);
00955 #endif
00956 
00957     if (ftdi->usb_dev != NULL)
00958         if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
00959             rtn = -1;
00960 
00961     if (ftdi_usb_close_internal (ftdi) != 0)
00962         rtn = -2;
00963 
00964     return rtn;
00965 }
00966 
00972 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
00973                                  unsigned short *value, unsigned short *index)
00974 {
00975     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
00976     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
00977     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
00978     int divisor, best_divisor, best_baud, best_baud_diff;
00979     unsigned long encoded_divisor;
00980     int i;
00981 
00982     if (baudrate <= 0)
00983     {
00984         // Return error
00985         return -1;
00986     }
00987 
00988     divisor = 24000000 / baudrate;
00989 
00990     if (ftdi->type == TYPE_AM)
00991     {
00992         // Round down to supported fraction (AM only)
00993         divisor -= am_adjust_dn[divisor & 7];
00994     }
00995 
00996     // Try this divisor and the one above it (because division rounds down)
00997     best_divisor = 0;
00998     best_baud = 0;
00999     best_baud_diff = 0;
01000     for (i = 0; i < 2; i++)
01001     {
01002         int try_divisor = divisor + i;
01003         int baud_estimate;
01004         int baud_diff;
01005 
01006         // Round up to supported divisor value
01007         if (try_divisor <= 8)
01008         {
01009             // Round up to minimum supported divisor
01010             try_divisor = 8;
01011         }
01012         else if (ftdi->type != TYPE_AM && try_divisor < 12)
01013         {
01014             // BM doesn't support divisors 9 through 11 inclusive
01015             try_divisor = 12;
01016         }
01017         else if (divisor < 16)
01018         {
01019             // AM doesn't support divisors 9 through 15 inclusive
01020             try_divisor = 16;
01021         }
01022         else
01023         {
01024             if (ftdi->type == TYPE_AM)
01025             {
01026                 // Round up to supported fraction (AM only)
01027                 try_divisor += am_adjust_up[try_divisor & 7];
01028                 if (try_divisor > 0x1FFF8)
01029                 {
01030                     // Round down to maximum supported divisor value (for AM)
01031                     try_divisor = 0x1FFF8;
01032                 }
01033             }
01034             else
01035             {
01036                 if (try_divisor > 0x1FFFF)
01037                 {
01038                     // Round down to maximum supported divisor value (for BM)
01039                     try_divisor = 0x1FFFF;
01040                 }
01041             }
01042         }
01043         // Get estimated baud rate (to nearest integer)
01044         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
01045         // Get absolute difference from requested baud rate
01046         if (baud_estimate < baudrate)
01047         {
01048             baud_diff = baudrate - baud_estimate;
01049         }
01050         else
01051         {
01052             baud_diff = baud_estimate - baudrate;
01053         }
01054         if (i == 0 || baud_diff < best_baud_diff)
01055         {
01056             // Closest to requested baud rate so far
01057             best_divisor = try_divisor;
01058             best_baud = baud_estimate;
01059             best_baud_diff = baud_diff;
01060             if (baud_diff == 0)
01061             {
01062                 // Spot on! No point trying
01063                 break;
01064             }
01065         }
01066     }
01067     // Encode the best divisor value
01068     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
01069     // Deal with special cases for encoded value
01070     if (encoded_divisor == 1)
01071     {
01072         encoded_divisor = 0;    // 3000000 baud
01073     }
01074     else if (encoded_divisor == 0x4001)
01075     {
01076         encoded_divisor = 1;    // 2000000 baud (BM only)
01077     }
01078     // Split into "value" and "index" values
01079     *value = (unsigned short)(encoded_divisor & 0xFFFF);
01080     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H
01081         || ftdi->type == TYPE_232H)
01082     {
01083         *index = (unsigned short)(encoded_divisor >> 8);
01084         *index &= 0xFF00;
01085         *index |= ftdi->index;
01086     }
01087     else
01088         *index = (unsigned short)(encoded_divisor >> 16);
01089 
01090     // Return the nearest baud rate
01091     return best_baud;
01092 }
01093 
01105 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
01106 {
01107     unsigned short value, index;
01108     int actual_baudrate;
01109 
01110     if (ftdi == NULL || ftdi->usb_dev == NULL)
01111         ftdi_error_return(-3, "USB device unavailable");
01112 
01113     if (ftdi->bitbang_enabled)
01114     {
01115         baudrate = baudrate*4;
01116     }
01117 
01118     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
01119     if (actual_baudrate <= 0)
01120         ftdi_error_return (-1, "Silly baudrate <= 0.");
01121 
01122     // Check within tolerance (about 5%)
01123     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
01124             || ((actual_baudrate < baudrate)
01125                 ? (actual_baudrate * 21 < baudrate * 20)
01126                 : (baudrate * 21 < actual_baudrate * 20)))
01127         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
01128 
01129     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01130                         SIO_SET_BAUDRATE_REQUEST, value,
01131                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
01132         ftdi_error_return (-2, "Setting new baudrate failed");
01133 
01134     ftdi->baudrate = baudrate;
01135     return 0;
01136 }
01137 
01151 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01152                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
01153 {
01154     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
01155 }
01156 
01170 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01171                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
01172                             enum ftdi_break_type break_type)
01173 {
01174     unsigned short value = bits;
01175 
01176     if (ftdi == NULL || ftdi->usb_dev == NULL)
01177         ftdi_error_return(-2, "USB device unavailable");
01178 
01179     switch (parity)
01180     {
01181         case NONE:
01182             value |= (0x00 << 8);
01183             break;
01184         case ODD:
01185             value |= (0x01 << 8);
01186             break;
01187         case EVEN:
01188             value |= (0x02 << 8);
01189             break;
01190         case MARK:
01191             value |= (0x03 << 8);
01192             break;
01193         case SPACE:
01194             value |= (0x04 << 8);
01195             break;
01196     }
01197 
01198     switch (sbit)
01199     {
01200         case STOP_BIT_1:
01201             value |= (0x00 << 11);
01202             break;
01203         case STOP_BIT_15:
01204             value |= (0x01 << 11);
01205             break;
01206         case STOP_BIT_2:
01207             value |= (0x02 << 11);
01208             break;
01209     }
01210 
01211     switch (break_type)
01212     {
01213         case BREAK_OFF:
01214             value |= (0x00 << 14);
01215             break;
01216         case BREAK_ON:
01217             value |= (0x01 << 14);
01218             break;
01219     }
01220 
01221     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01222                         SIO_SET_DATA_REQUEST, value,
01223                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01224         ftdi_error_return (-1, "Setting new line property failed");
01225 
01226     return 0;
01227 }
01228 
01240 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01241 {
01242     int ret;
01243     int offset = 0;
01244     int total_written = 0;
01245 
01246     if (ftdi == NULL || ftdi->usb_dev == NULL)
01247         ftdi_error_return(-666, "USB device unavailable");
01248 
01249     while (offset < size)
01250     {
01251         int write_size = ftdi->writebuffer_chunksize;
01252 
01253         if (offset+write_size > size)
01254             write_size = size-offset;
01255 
01256         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
01257         if (ret < 0)
01258             ftdi_error_return(ret, "usb bulk write failed");
01259 
01260         total_written += ret;
01261         offset += write_size;
01262     }
01263 
01264     return total_written;
01265 }
01266 
01267 #ifdef LIBFTDI_LINUX_ASYNC_MODE
01268 #ifdef USB_CLASS_PTP
01269 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
01270 #endif
01271 /* this is strongly dependent on libusb using the same struct layout. If libusb
01272    changes in some later version this may break horribly (this is for libusb 0.1.12) */
01273 struct usb_dev_handle
01274 {
01275     int fd;
01276     // some other stuff coming here we don't need
01277 };
01278 
01283 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
01284 {
01285     struct usbdevfs_urb *urb;
01286     int pending=0;
01287     unsigned int i;
01288 
01289     for (i=0; i < ftdi->async_usb_buffer_size; i++)
01290     {
01291         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01292         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
01293             pending++;
01294     }
01295 
01296     return pending;
01297 }
01298 
01309 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
01310 {
01311     struct timeval tv;
01312     struct usbdevfs_urb *urb;
01313     int ret;
01314     fd_set writefds;
01315     int keep_going=0;
01316 
01317     FD_ZERO(&writefds);
01318     FD_SET(ftdi->usb_dev->fd, &writefds);
01319 
01320     /* init timeout only once, select writes time left after call */
01321     tv.tv_sec = timeout_msec / 1000;
01322     tv.tv_usec = (timeout_msec % 1000) * 1000;
01323 
01324     do
01325     {
01326         ret = -1;
01327         urb = NULL;
01328 
01329         while (_usb_get_async_urbs_pending(ftdi)
01330                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
01331                 && errno == EAGAIN)
01332         {
01333             if (keep_going && !wait_for_more)
01334             {
01335                 /* don't wait if repeating only for keep_going */
01336                 keep_going=0;
01337                 break;
01338             }
01339 
01340             /* wait for timeout msec or something written ready */
01341             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
01342         }
01343 
01344         if (ret == 0 && urb != NULL)
01345         {
01346             /* got a free urb, mark it */
01347             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
01348 
01349             /* try to get more urbs that are ready now, but don't wait anymore */
01350             keep_going=1;
01351         }
01352         else
01353         {
01354             /* no more urbs waiting */
01355             keep_going=0;
01356         }
01357     }
01358     while (keep_going);
01359 }
01360 
01368 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
01369 {
01370     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
01371 }
01372 
01378 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
01379 {
01380     struct usbdevfs_urb *urb;
01381     int bytesdone = 0, requested;
01382     int ret, cleanup_count;
01383     unsigned int i;
01384 
01385     do
01386     {
01387         /* find a free urb buffer we can use */
01388         i = 0;
01389         urb=NULL;
01390         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
01391         {
01392             if (i==ftdi->async_usb_buffer_size)
01393             {
01394                 /* wait until some buffers are free */
01395                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
01396             }
01397 
01398             for (i=0; i < ftdi->async_usb_buffer_size; i++)
01399             {
01400                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01401                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
01402                     break;  /* found a free urb position */
01403                 urb=NULL;
01404             }
01405         }
01406 
01407         /* no free urb position found */
01408         if (urb==NULL)
01409             return -1;
01410 
01411         requested = size - bytesdone;
01412         if (requested > 4096)
01413             requested = 4096;
01414 
01415         memset(urb,0,sizeof(urb));
01416 
01417         urb->type = USBDEVFS_URB_TYPE_BULK;
01418         urb->endpoint = ep;
01419         urb->flags = 0;
01420         urb->buffer = bytes + bytesdone;
01421         urb->buffer_length = requested;
01422         urb->signr = 0;
01423         urb->actual_length = 0;
01424         urb->number_of_packets = 0;
01425         urb->usercontext = 0;
01426 
01427         do
01428         {
01429             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
01430         }
01431         while (ret < 0 && errno == EINTR);
01432         if (ret < 0)
01433             return ret;       /* the caller can read errno to get more info */
01434 
01435         bytesdone += requested;
01436     }
01437     while (bytesdone < size);
01438     return bytesdone;
01439 }
01440 
01460 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
01461 {
01462     int ret;
01463     int offset = 0;
01464     int total_written = 0;
01465 
01466     if (ftdi == NULL || ftdi->usb_dev == NULL)
01467         ftdi_error_return(-666, "USB device unavailable");
01468 
01469     while (offset < size)
01470     {
01471         int write_size = ftdi->writebuffer_chunksize;
01472 
01473         if (offset+write_size > size)
01474             write_size = size-offset;
01475 
01476         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
01477         if (ret < 0)
01478             ftdi_error_return(ret, "usb bulk write async failed");
01479 
01480         total_written += ret;
01481         offset += write_size;
01482     }
01483 
01484     return total_written;
01485 }
01486 #endif // LIBFTDI_LINUX_ASYNC_MODE
01487 
01498 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01499 {
01500     if (ftdi == NULL)
01501         ftdi_error_return(-1, "ftdi context invalid");
01502 
01503     ftdi->writebuffer_chunksize = chunksize;
01504     return 0;
01505 }
01506 
01516 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01517 {
01518     if (ftdi == NULL)
01519         ftdi_error_return(-1, "ftdi context invalid");
01520 
01521     *chunksize = ftdi->writebuffer_chunksize;
01522     return 0;
01523 }
01524 
01541 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01542 {
01543     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
01544     int packet_size;
01545 
01546     if (ftdi == NULL || ftdi->usb_dev == NULL)
01547         ftdi_error_return(-666, "USB device unavailable");
01548 
01549     packet_size = ftdi->max_packet_size;
01550     // Packet size sanity check (avoid division by zero)
01551     if (packet_size == 0)
01552         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
01553 
01554     // everything we want is still in the readbuffer?
01555     if (size <= ftdi->readbuffer_remaining)
01556     {
01557         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
01558 
01559         // Fix offsets
01560         ftdi->readbuffer_remaining -= size;
01561         ftdi->readbuffer_offset += size;
01562 
01563         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
01564 
01565         return size;
01566     }
01567     // something still in the readbuffer, but not enough to satisfy 'size'?
01568     if (ftdi->readbuffer_remaining != 0)
01569     {
01570         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
01571 
01572         // Fix offset
01573         offset += ftdi->readbuffer_remaining;
01574     }
01575     // do the actual USB read
01576     while (offset < size && ret > 0)
01577     {
01578         ftdi->readbuffer_remaining = 0;
01579         ftdi->readbuffer_offset = 0;
01580         /* returns how much received */
01581         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
01582         if (ret < 0)
01583             ftdi_error_return(ret, "usb bulk read failed");
01584 
01585         if (ret > 2)
01586         {
01587             // skip FTDI status bytes.
01588             // Maybe stored in the future to enable modem use
01589             num_of_chunks = ret / packet_size;
01590             chunk_remains = ret % packet_size;
01591             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
01592 
01593             ftdi->readbuffer_offset += 2;
01594             ret -= 2;
01595 
01596             if (ret > packet_size - 2)
01597             {
01598                 for (i = 1; i < num_of_chunks; i++)
01599                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01600                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01601                              packet_size - 2);
01602                 if (chunk_remains > 2)
01603                 {
01604                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01605                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01606                              chunk_remains-2);
01607                     ret -= 2*num_of_chunks;
01608                 }
01609                 else
01610                     ret -= 2*(num_of_chunks-1)+chunk_remains;
01611             }
01612         }
01613         else if (ret <= 2)
01614         {
01615             // no more data to read?
01616             return offset;
01617         }
01618         if (ret > 0)
01619         {
01620             // data still fits in buf?
01621             if (offset+ret <= size)
01622             {
01623                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
01624                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
01625                 offset += ret;
01626 
01627                 /* Did we read exactly the right amount of bytes? */
01628                 if (offset == size)
01629                     //printf("read_data exact rem %d offset %d\n",
01630                     //ftdi->readbuffer_remaining, offset);
01631                     return offset;
01632             }
01633             else
01634             {
01635                 // only copy part of the data or size <= readbuffer_chunksize
01636                 int part_size = size-offset;
01637                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
01638 
01639                 ftdi->readbuffer_offset += part_size;
01640                 ftdi->readbuffer_remaining = ret-part_size;
01641                 offset += part_size;
01642 
01643                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
01644                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
01645 
01646                 return offset;
01647             }
01648         }
01649     }
01650     // never reached
01651     return -127;
01652 }
01653 
01666 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01667 {
01668     unsigned char *new_buf;
01669 
01670     if (ftdi == NULL)
01671         ftdi_error_return(-1, "ftdi context invalid");
01672 
01673     // Invalidate all remaining data
01674     ftdi->readbuffer_offset = 0;
01675     ftdi->readbuffer_remaining = 0;
01676 
01677     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
01678         ftdi_error_return(-1, "out of memory for readbuffer");
01679 
01680     ftdi->readbuffer = new_buf;
01681     ftdi->readbuffer_chunksize = chunksize;
01682 
01683     return 0;
01684 }
01685 
01695 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01696 {
01697     if (ftdi == NULL)
01698         ftdi_error_return(-1, "FTDI context invalid");
01699 
01700     *chunksize = ftdi->readbuffer_chunksize;
01701     return 0;
01702 }
01703 
01704 
01718 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
01719 {
01720     unsigned short usb_val;
01721 
01722     if (ftdi == NULL || ftdi->usb_dev == NULL)
01723         ftdi_error_return(-2, "USB device unavailable");
01724 
01725     usb_val = bitmask; // low byte: bitmask
01726     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
01727     usb_val |= (ftdi->bitbang_mode << 8);
01728 
01729     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01730                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
01731                         NULL, 0, ftdi->usb_write_timeout) != 0)
01732         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
01733 
01734     ftdi->bitbang_enabled = 1;
01735     return 0;
01736 }
01737 
01747 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
01748 {
01749     if (ftdi == NULL || ftdi->usb_dev == NULL)
01750         ftdi_error_return(-2, "USB device unavailable");
01751 
01752     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)
01753         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
01754 
01755     ftdi->bitbang_enabled = 0;
01756     return 0;
01757 }
01758 
01771 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
01772 {
01773     unsigned short usb_val;
01774 
01775     if (ftdi == NULL || ftdi->usb_dev == NULL)
01776         ftdi_error_return(-2, "USB device unavailable");
01777 
01778     usb_val = bitmask; // low byte: bitmask
01779     usb_val |= (mode << 8);
01780     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)
01781         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps selected mode not supported on your chip?");
01782 
01783     ftdi->bitbang_mode = mode;
01784     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
01785     return 0;
01786 }
01787 
01798 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
01799 {
01800     if (ftdi == NULL || ftdi->usb_dev == NULL)
01801         ftdi_error_return(-2, "USB device unavailable");
01802 
01803     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)
01804         ftdi_error_return(-1, "read pins failed");
01805 
01806     return 0;
01807 }
01808 
01824 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
01825 {
01826     unsigned short usb_val;
01827 
01828     if (latency < 1)
01829         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
01830 
01831     if (ftdi == NULL || ftdi->usb_dev == NULL)
01832         ftdi_error_return(-3, "USB device unavailable");
01833 
01834     usb_val = latency;
01835     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)
01836         ftdi_error_return(-2, "unable to set latency timer");
01837 
01838     return 0;
01839 }
01840 
01851 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
01852 {
01853     unsigned short usb_val;
01854 
01855     if (ftdi == NULL || ftdi->usb_dev == NULL)
01856         ftdi_error_return(-2, "USB device unavailable");
01857 
01858     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)
01859         ftdi_error_return(-1, "reading latency timer failed");
01860 
01861     *latency = (unsigned char)usb_val;
01862     return 0;
01863 }
01864 
01905 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
01906 {
01907     char usb_val[2];
01908 
01909     if (ftdi == NULL || ftdi->usb_dev == NULL)
01910         ftdi_error_return(-2, "USB device unavailable");
01911 
01912     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)
01913         ftdi_error_return(-1, "getting modem status failed");
01914 
01915     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
01916 
01917     return 0;
01918 }
01919 
01931 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
01932 {
01933     if (ftdi == NULL || ftdi->usb_dev == NULL)
01934         ftdi_error_return(-2, "USB device unavailable");
01935 
01936     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01937                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
01938                         NULL, 0, ftdi->usb_write_timeout) != 0)
01939         ftdi_error_return(-1, "set flow control failed");
01940 
01941     return 0;
01942 }
01943 
01954 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
01955 {
01956     unsigned short usb_val;
01957 
01958     if (ftdi == NULL || ftdi->usb_dev == NULL)
01959         ftdi_error_return(-2, "USB device unavailable");
01960 
01961     if (state)
01962         usb_val = SIO_SET_DTR_HIGH;
01963     else
01964         usb_val = SIO_SET_DTR_LOW;
01965 
01966     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01967                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01968                         NULL, 0, ftdi->usb_write_timeout) != 0)
01969         ftdi_error_return(-1, "set dtr failed");
01970 
01971     return 0;
01972 }
01973 
01984 int ftdi_setrts(struct ftdi_context *ftdi, int state)
01985 {
01986     unsigned short usb_val;
01987 
01988     if (ftdi == NULL || ftdi->usb_dev == NULL)
01989         ftdi_error_return(-2, "USB device unavailable");
01990 
01991     if (state)
01992         usb_val = SIO_SET_RTS_HIGH;
01993     else
01994         usb_val = SIO_SET_RTS_LOW;
01995 
01996     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01997                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01998                         NULL, 0, ftdi->usb_write_timeout) != 0)
01999         ftdi_error_return(-1, "set of rts failed");
02000 
02001     return 0;
02002 }
02003 
02015 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
02016 {
02017     unsigned short usb_val;
02018 
02019     if (ftdi == NULL || ftdi->usb_dev == NULL)
02020         ftdi_error_return(-2, "USB device unavailable");
02021 
02022     if (dtr)
02023         usb_val = SIO_SET_DTR_HIGH;
02024     else
02025         usb_val = SIO_SET_DTR_LOW;
02026 
02027     if (rts)
02028         usb_val |= SIO_SET_RTS_HIGH;
02029     else
02030         usb_val |= SIO_SET_RTS_LOW;
02031 
02032     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02033                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
02034                         NULL, 0, ftdi->usb_write_timeout) != 0)
02035         ftdi_error_return(-1, "set of rts/dtr failed");
02036 
02037     return 0;
02038 }
02039 
02051 int ftdi_set_event_char(struct ftdi_context *ftdi,
02052                         unsigned char eventch, unsigned char enable)
02053 {
02054     unsigned short usb_val;
02055 
02056     if (ftdi == NULL || ftdi->usb_dev == NULL)
02057         ftdi_error_return(-2, "USB device unavailable");
02058 
02059     usb_val = eventch;
02060     if (enable)
02061         usb_val |= 1 << 8;
02062 
02063     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)
02064         ftdi_error_return(-1, "setting event character failed");
02065 
02066     return 0;
02067 }
02068 
02080 int ftdi_set_error_char(struct ftdi_context *ftdi,
02081                         unsigned char errorch, unsigned char enable)
02082 {
02083     unsigned short usb_val;
02084 
02085     if (ftdi == NULL || ftdi->usb_dev == NULL)
02086         ftdi_error_return(-2, "USB device unavailable");
02087 
02088     usb_val = errorch;
02089     if (enable)
02090         usb_val |= 1 << 8;
02091 
02092     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)
02093         ftdi_error_return(-1, "setting error character failed");
02094 
02095     return 0;
02096 }
02097 
02106 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
02107 {
02108     if (ftdi == NULL)
02109         return;
02110 
02111     ftdi->eeprom_size=size;
02112     eeprom->size=size;
02113 }
02114 
02120 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
02121 {
02122     int i;
02123 
02124     if (eeprom == NULL)
02125         return;
02126 
02127     eeprom->vendor_id = 0x0403;
02128     eeprom->product_id = 0x6001;
02129 
02130     eeprom->self_powered = 1;
02131     eeprom->remote_wakeup = 1;
02132     eeprom->chip_type = TYPE_BM;
02133 
02134     eeprom->in_is_isochronous = 0;
02135     eeprom->out_is_isochronous = 0;
02136     eeprom->suspend_pull_downs = 0;
02137 
02138     eeprom->use_serial = 0;
02139     eeprom->change_usb_version = 0;
02140     eeprom->usb_version = 0x0200;
02141     eeprom->max_power = 0;
02142 
02143     eeprom->manufacturer = NULL;
02144     eeprom->product = NULL;
02145     eeprom->serial = NULL;
02146     for (i=0; i < 5; i++)
02147     {
02148         eeprom->cbus_function[i] = 0;
02149     }
02150     eeprom->high_current = 0;
02151     eeprom->invert = 0;
02152 
02153     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
02154 }
02155 
02161 void ftdi_eeprom_free(struct ftdi_eeprom *eeprom)
02162 {
02163     if (!eeprom)
02164         return;
02165 
02166     if (eeprom->manufacturer != 0) {
02167         free(eeprom->manufacturer);
02168         eeprom->manufacturer = 0;
02169     }
02170     if (eeprom->product != 0) {
02171         free(eeprom->product);
02172         eeprom->product = 0;
02173     }
02174     if (eeprom->serial != 0) {
02175         free(eeprom->serial);
02176         eeprom->serial = 0;
02177     }
02178 }
02179 
02195 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
02196 {
02197     unsigned char i, j;
02198     unsigned short checksum, value;
02199     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02200     int size_check;
02201     const int cbus_max[5] = {13, 13, 13, 13, 9};
02202 
02203     if (eeprom == NULL)
02204         return -2;
02205 
02206     if (eeprom->manufacturer != NULL)
02207         manufacturer_size = strlen(eeprom->manufacturer);
02208     if (eeprom->product != NULL)
02209         product_size = strlen(eeprom->product);
02210     if (eeprom->serial != NULL)
02211         serial_size = strlen(eeprom->serial);
02212 
02213     // highest allowed cbus value
02214     for (i = 0; i < 5; i++)
02215     {
02216         if ((eeprom->cbus_function[i] > cbus_max[i]) ||
02217             (eeprom->cbus_function[i] && eeprom->chip_type != TYPE_R)) return -3;
02218     }
02219     if (eeprom->chip_type != TYPE_R)
02220     {
02221         if (eeprom->invert) return -4;
02222         if (eeprom->high_current) return -5;
02223     }
02224 
02225     size_check = eeprom->size;
02226     size_check -= 28; // 28 are always in use (fixed)
02227 
02228     // Top half of a 256byte eeprom is used just for strings and checksum
02229     // it seems that the FTDI chip will not read these strings from the lower half
02230     // Each string starts with two bytes; offset and type (0x03 for string)
02231     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02232     if (eeprom->size>=256) size_check = 120;
02233     size_check -= manufacturer_size*2;
02234     size_check -= product_size*2;
02235     size_check -= serial_size*2;
02236 
02237     // eeprom size exceeded?
02238     if (size_check < 0)
02239         return (-1);
02240 
02241     // empty eeprom
02242     memset (output, 0, eeprom->size);
02243 
02244     // Addr 00: High current IO
02245     output[0x00] = eeprom->high_current ? HIGH_CURRENT_DRIVE : 0;
02246     // Addr 01: IN endpoint size (for R type devices, different for FT2232)
02247     if (eeprom->chip_type == TYPE_R) {
02248         output[0x01] = 0x40;
02249     }
02250     // Addr 02: Vendor ID
02251     output[0x02] = eeprom->vendor_id;
02252     output[0x03] = eeprom->vendor_id >> 8;
02253 
02254     // Addr 04: Product ID
02255     output[0x04] = eeprom->product_id;
02256     output[0x05] = eeprom->product_id >> 8;
02257 
02258     // Addr 06: Device release number (0400h for BM features)
02259     output[0x06] = 0x00;
02260     switch (eeprom->chip_type) {
02261         case TYPE_AM:
02262             output[0x07] = 0x02;
02263             break;
02264         case TYPE_BM:
02265             output[0x07] = 0x04;
02266             break;
02267         case TYPE_2232C:
02268             output[0x07] = 0x05;
02269             break;
02270         case TYPE_R:
02271             output[0x07] = 0x06;
02272             break;
02273         case TYPE_2232H:
02274             output[0x07] = 0x07;
02275             break;
02276          case TYPE_4232H:
02277             output[0x07] = 0x08;
02278             break;
02279         case TYPE_232H:
02280             output[0x07] = 0x09;
02281             break;
02282         default:
02283             output[0x07] = 0x00;
02284     }
02285 
02286     // Addr 08: Config descriptor
02287     // Bit 7: always 1
02288     // Bit 6: 1 if this device is self powered, 0 if bus powered
02289     // Bit 5: 1 if this device uses remote wakeup
02290     // Bit 4: 1 if this device is battery powered
02291     j = 0x80;
02292     if (eeprom->self_powered == 1)
02293         j |= 0x40;
02294     if (eeprom->remote_wakeup == 1)
02295         j |= 0x20;
02296     output[0x08] = j;
02297 
02298     // Addr 09: Max power consumption: max power = value * 2 mA
02299     output[0x09] = eeprom->max_power;
02300 
02301     // Addr 0A: Chip configuration
02302     // Bit 7: 0 - reserved
02303     // Bit 6: 0 - reserved
02304     // Bit 5: 0 - reserved
02305     // Bit 4: 1 - Change USB version
02306     // Bit 3: 1 - Use the serial number string
02307     // Bit 2: 1 - Enable suspend pull downs for lower power
02308     // Bit 1: 1 - Out EndPoint is Isochronous
02309     // Bit 0: 1 - In EndPoint is Isochronous
02310     //
02311     j = 0;
02312     if (eeprom->in_is_isochronous == 1)
02313         j = j | 1;
02314     if (eeprom->out_is_isochronous == 1)
02315         j = j | 2;
02316     if (eeprom->suspend_pull_downs == 1)
02317         j = j | 4;
02318     if (eeprom->use_serial == 1)
02319         j = j | 8;
02320     if (eeprom->change_usb_version == 1)
02321         j = j | 16;
02322     output[0x0A] = j;
02323 
02324     // Addr 0B: Invert data lines
02325     output[0x0B] = eeprom->invert & 0xff;
02326 
02327     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02328     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02329     if (eeprom->change_usb_version == 1)
02330     {
02331         output[0x0C] = eeprom->usb_version;
02332         output[0x0D] = eeprom->usb_version >> 8;
02333     }
02334 
02335 
02336     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02337     // Addr 0F: Length of manufacturer string
02338     output[0x0F] = manufacturer_size*2 + 2;
02339 
02340     // Addr 10: Offset of the product string + 0x80, calculated later
02341     // Addr 11: Length of product string
02342     output[0x11] = product_size*2 + 2;
02343 
02344     // Addr 12: Offset of the serial string + 0x80, calculated later
02345     // Addr 13: Length of serial string
02346     output[0x13] = serial_size*2 + 2;
02347 
02348     // Addr 14: CBUS function: CBUS0, CBUS1
02349     // Addr 15: CBUS function: CBUS2, CBUS3
02350     // Addr 16: CBUS function: CBUS5
02351     output[0x14] = eeprom->cbus_function[0] | (eeprom->cbus_function[1] << 4);
02352     output[0x15] = eeprom->cbus_function[2] | (eeprom->cbus_function[3] << 4);
02353     output[0x16] = eeprom->cbus_function[4];
02354     // Addr 17: Unknown
02355 
02356     // Dynamic content
02357     // In images produced by FTDI's FT_Prog for FT232R strings start at 0x18
02358     // Space till 0x18 should be considered as reserved.
02359     if (eeprom->chip_type >= TYPE_R) {
02360         i = 0x18;
02361     } else {
02362         i = 0x14;
02363     }
02364     if (eeprom->size >= 256) i = 0x80;
02365 
02366 
02367     // Output manufacturer
02368     output[0x0E] = i | 0x80;  // calculate offset
02369     output[i++] = manufacturer_size*2 + 2;
02370     output[i++] = 0x03; // type: string
02371     for (j = 0; j < manufacturer_size; j++)
02372     {
02373         output[i] = eeprom->manufacturer[j], i++;
02374         output[i] = 0x00, i++;
02375     }
02376 
02377     // Output product name
02378     output[0x10] = i | 0x80;  // calculate offset
02379     output[i] = product_size*2 + 2, i++;
02380     output[i] = 0x03, i++;
02381     for (j = 0; j < product_size; j++)
02382     {
02383         output[i] = eeprom->product[j], i++;
02384         output[i] = 0x00, i++;
02385     }
02386 
02387     // Output serial
02388     output[0x12] = i | 0x80; // calculate offset
02389     output[i] = serial_size*2 + 2, i++;
02390     output[i] = 0x03, i++;
02391     for (j = 0; j < serial_size; j++)
02392     {
02393         output[i] = eeprom->serial[j], i++;
02394         output[i] = 0x00, i++;
02395     }
02396 
02397     // calculate checksum
02398     checksum = 0xAAAA;
02399 
02400     for (i = 0; i < eeprom->size/2-1; i++)
02401     {
02402         value = output[i*2];
02403         value += output[(i*2)+1] << 8;
02404 
02405         checksum = value^checksum;
02406         checksum = (checksum << 1) | (checksum >> 15);
02407     }
02408 
02409     output[eeprom->size-2] = checksum;
02410     output[eeprom->size-1] = checksum >> 8;
02411 
02412     return size_check;
02413 }
02414 
02428 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
02429 {
02430     unsigned char i, j;
02431     unsigned short checksum, eeprom_checksum, value;
02432     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02433     int size_check;
02434     int eeprom_size = 128;
02435 
02436     if (eeprom == NULL)
02437         return -1;
02438 #if 0
02439     size_check = eeprom->size;
02440     size_check -= 28; // 28 are always in use (fixed)
02441 
02442     // Top half of a 256byte eeprom is used just for strings and checksum
02443     // it seems that the FTDI chip will not read these strings from the lower half
02444     // Each string starts with two bytes; offset and type (0x03 for string)
02445     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02446     if (eeprom->size>=256)size_check = 120;
02447     size_check -= manufacturer_size*2;
02448     size_check -= product_size*2;
02449     size_check -= serial_size*2;
02450 
02451     // eeprom size exceeded?
02452     if (size_check < 0)
02453         return (-1);
02454 #endif
02455 
02456     // empty eeprom struct
02457     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
02458 
02459     // Addr 00: High current IO
02460     eeprom->high_current = (buf[0x02] & HIGH_CURRENT_DRIVE);
02461 
02462     // Addr 02: Vendor ID
02463     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
02464 
02465     // Addr 04: Product ID
02466     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
02467 
02468     value = buf[0x06] + (buf[0x07]<<8);
02469     switch (value)
02470     {
02471         case 0x0900:
02472             eeprom->chip_type = TYPE_232H;
02473             break;
02474         case 0x0800:
02475             eeprom->chip_type = TYPE_4232H;
02476             break;
02477         case 0x0700:
02478             eeprom->chip_type = TYPE_2232H;
02479             break;
02480         case 0x0600:
02481             eeprom->chip_type = TYPE_R;
02482             break;
02483         case 0x0400:
02484             eeprom->chip_type = TYPE_BM;
02485             break;
02486         case 0x0200:
02487             eeprom->chip_type = TYPE_AM;
02488             break;
02489         default: // Unknown device
02490             eeprom->chip_type = 0;
02491             break;
02492     }
02493 
02494     // Addr 08: Config descriptor
02495     // Bit 7: always 1
02496     // Bit 6: 1 if this device is self powered, 0 if bus powered
02497     // Bit 5: 1 if this device uses remote wakeup
02498     // Bit 4: 1 if this device is battery powered
02499     j = buf[0x08];
02500     if (j&0x40) eeprom->self_powered = 1;
02501     if (j&0x20) eeprom->remote_wakeup = 1;
02502 
02503     // Addr 09: Max power consumption: max power = value * 2 mA
02504     eeprom->max_power = buf[0x09];
02505 
02506     // Addr 0A: Chip configuration
02507     // Bit 7: 0 - reserved
02508     // Bit 6: 0 - reserved
02509     // Bit 5: 0 - reserved
02510     // Bit 4: 1 - Change USB version
02511     // Bit 3: 1 - Use the serial number string
02512     // Bit 2: 1 - Enable suspend pull downs for lower power
02513     // Bit 1: 1 - Out EndPoint is Isochronous
02514     // Bit 0: 1 - In EndPoint is Isochronous
02515     //
02516     j = buf[0x0A];
02517     if (j&0x01) eeprom->in_is_isochronous = 1;
02518     if (j&0x02) eeprom->out_is_isochronous = 1;
02519     if (j&0x04) eeprom->suspend_pull_downs = 1;
02520     if (j&0x08) eeprom->use_serial = 1;
02521     if (j&0x10) eeprom->change_usb_version = 1;
02522 
02523     // Addr 0B: Invert data lines
02524     eeprom->invert = buf[0x0B];
02525 
02526     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02527     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02528     if (eeprom->change_usb_version == 1)
02529     {
02530         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
02531     }
02532 
02533     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02534     // Addr 0F: Length of manufacturer string
02535     manufacturer_size = buf[0x0F]/2;
02536     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
02537     else eeprom->manufacturer = NULL;
02538 
02539     // Addr 10: Offset of the product string + 0x80, calculated later
02540     // Addr 11: Length of product string
02541     product_size = buf[0x11]/2;
02542     if (product_size > 0) eeprom->product = malloc(product_size);
02543     else eeprom->product = NULL;
02544 
02545     // Addr 12: Offset of the serial string + 0x80, calculated later
02546     // Addr 13: Length of serial string
02547     serial_size = buf[0x13]/2;
02548     if (serial_size > 0) eeprom->serial = malloc(serial_size);
02549     else eeprom->serial = NULL;
02550 
02551     // Addr 14: CBUS function: CBUS0, CBUS1
02552     // Addr 15: CBUS function: CBUS2, CBUS3
02553     // Addr 16: CBUS function: CBUS5
02554     if (eeprom->chip_type == TYPE_R) {
02555         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
02556         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
02557         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
02558         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
02559         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
02560     } else {
02561         for (j=0; j<5; j++) eeprom->cbus_function[j] = 0;
02562     }
02563 
02564     // Decode manufacturer
02565     i = buf[0x0E] & 0x7f; // offset
02566     for (j=0;j<manufacturer_size-1;j++)
02567     {
02568         eeprom->manufacturer[j] = buf[2*j+i+2];
02569     }
02570     eeprom->manufacturer[j] = '\0';
02571 
02572     // Decode product name
02573     i = buf[0x10] & 0x7f; // offset
02574     for (j=0;j<product_size-1;j++)
02575     {
02576         eeprom->product[j] = buf[2*j+i+2];
02577     }
02578     eeprom->product[j] = '\0';
02579 
02580     // Decode serial
02581     i = buf[0x12] & 0x7f; // offset
02582     for (j=0;j<serial_size-1;j++)
02583     {
02584         eeprom->serial[j] = buf[2*j+i+2];
02585     }
02586     eeprom->serial[j] = '\0';
02587 
02588     // verify checksum
02589     checksum = 0xAAAA;
02590 
02591     for (i = 0; i < eeprom_size/2-1; i++)
02592     {
02593         value = buf[i*2];
02594         value += buf[(i*2)+1] << 8;
02595 
02596         checksum = value^checksum;
02597         checksum = (checksum << 1) | (checksum >> 15);
02598     }
02599 
02600     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
02601 
02602     if (eeprom_checksum != checksum)
02603     {
02604         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
02605         return -1;
02606     }
02607 
02608     return 0;
02609 }
02610 
02622 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
02623 {
02624     if (ftdi == NULL || ftdi->usb_dev == NULL)
02625         ftdi_error_return(-2, "USB device unavailable");
02626 
02627     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)
02628         ftdi_error_return(-1, "reading eeprom failed");
02629 
02630     return 0;
02631 }
02632 
02643 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02644 {
02645     int i;
02646 
02647     if (ftdi == NULL || ftdi->usb_dev == NULL)
02648         ftdi_error_return(-2, "USB device unavailable");
02649 
02650     for (i = 0; i < ftdi->eeprom_size/2; i++)
02651     {
02652         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)
02653             ftdi_error_return(-1, "reading eeprom failed");
02654     }
02655 
02656     return 0;
02657 }
02658 
02659 /*
02660     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
02661     Function is only used internally
02662     \internal
02663 */
02664 static unsigned char ftdi_read_chipid_shift(unsigned char value)
02665 {
02666     return ((value & 1) << 1) |
02667            ((value & 2) << 5) |
02668            ((value & 4) >> 2) |
02669            ((value & 8) << 4) |
02670            ((value & 16) >> 1) |
02671            ((value & 32) >> 1) |
02672            ((value & 64) >> 4) |
02673            ((value & 128) >> 2);
02674 }
02675 
02686 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
02687 {
02688     unsigned int a = 0, b = 0;
02689 
02690     if (ftdi == NULL || ftdi->usb_dev == NULL)
02691         ftdi_error_return(-2, "USB device unavailable");
02692 
02693     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)
02694     {
02695         a = a << 8 | a >> 8;
02696         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)
02697         {
02698             b = b << 8 | b >> 8;
02699             a = (a << 16) | (b & 0xFFFF);
02700             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
02701                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
02702             *chipid = a ^ 0xa5f0f7d1;
02703             return 0;
02704         }
02705     }
02706 
02707     ftdi_error_return(-1, "read of FTDIChip-ID failed");
02708 }
02709 
02722 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
02723 {
02724     int i=0,j,minsize=32;
02725     int size=minsize;
02726 
02727     if (ftdi == NULL || ftdi->usb_dev == NULL)
02728         ftdi_error_return(-2, "USB device unavailable");
02729 
02730     do
02731     {
02732         for (j = 0; i < maxsize/2 && j<size; j++)
02733         {
02734             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
02735                                 SIO_READ_EEPROM_REQUEST, 0, i,
02736                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02737                 ftdi_error_return(-1, "eeprom read failed");
02738             i++;
02739         }
02740         size*=2;
02741     }
02742     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
02743 
02744     return size/2;
02745 }
02746 
02758 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
02759 {
02760     if (ftdi == NULL || ftdi->usb_dev == NULL)
02761         ftdi_error_return(-2, "USB device unavailable");
02762 
02763     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02764                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
02765                                     NULL, 0, ftdi->usb_write_timeout) != 0)
02766         ftdi_error_return(-1, "unable to write eeprom");
02767 
02768     return 0;
02769 }
02770 
02781 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02782 {
02783     unsigned short usb_val, status;
02784     int i, ret;
02785 
02786     if (ftdi == NULL || ftdi->usb_dev == NULL)
02787         ftdi_error_return(-2, "USB device unavailable");
02788 
02789     /* These commands were traced while running MProg */
02790     if ((ret = ftdi_usb_reset(ftdi)) != 0)
02791         return ret;
02792     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
02793         return ret;
02794     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
02795         return ret;
02796 
02797     for (i = 0; i < ftdi->eeprom_size/2; i++)
02798     {
02799         usb_val = eeprom[i*2];
02800         usb_val += eeprom[(i*2)+1] << 8;
02801         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02802                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
02803                             NULL, 0, ftdi->usb_write_timeout) != 0)
02804             ftdi_error_return(-1, "unable to write eeprom");
02805     }
02806 
02807     return 0;
02808 }
02809 
02821 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
02822 {
02823     if (ftdi == NULL || ftdi->usb_dev == NULL)
02824         ftdi_error_return(-2, "USB device unavailable");
02825 
02826     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
02827         ftdi_error_return(-1, "unable to erase eeprom");
02828 
02829     return 0;
02830 }
02831 
02839 char *ftdi_get_error_string (struct ftdi_context *ftdi)
02840 {
02841     if (ftdi == NULL)
02842         return "";
02843 
02844     return ftdi->error_str;
02845 }
02846 
02847 /* @} end of doxygen libftdi group */