libftdi  0.19
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         ftdi->error_str = str;             \
00049         return code;                       \
00050    } while(0);
00051 
00052 
00062 static int ftdi_usb_close_internal (struct ftdi_context *ftdi)
00063 {
00064     int ret = 0;
00065 
00066     if (ftdi && ftdi->usb_dev)
00067     {
00068        ret = usb_close (ftdi->usb_dev);
00069        ftdi->usb_dev = NULL;
00070     }
00071 
00072     return ret;
00073 }
00074 
00085 int ftdi_init(struct ftdi_context *ftdi)
00086 {
00087     unsigned int i;
00088 
00089     ftdi->usb_dev = NULL;
00090     ftdi->usb_read_timeout = 5000;
00091     ftdi->usb_write_timeout = 5000;
00092 
00093     ftdi->type = TYPE_BM;    /* chip type */
00094     ftdi->baudrate = -1;
00095     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
00096 
00097     ftdi->readbuffer = NULL;
00098     ftdi->readbuffer_offset = 0;
00099     ftdi->readbuffer_remaining = 0;
00100     ftdi->writebuffer_chunksize = 4096;
00101     ftdi->max_packet_size = 0;
00102 
00103     ftdi->interface = 0;
00104     ftdi->index = 0;
00105     ftdi->in_ep = 0x02;
00106     ftdi->out_ep = 0x81;
00107     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
00108 
00109     ftdi->error_str = NULL;
00110 
00111 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00112     ftdi->async_usb_buffer_size=10;
00113     if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
00114         ftdi_error_return(-1, "out of memory for async usb buffer");
00115 
00116     /* initialize async usb buffer with unused-marker */
00117     for (i=0; i < ftdi->async_usb_buffer_size; i++)
00118         ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
00119 #else
00120     ftdi->async_usb_buffer_size=0;
00121     ftdi->async_usb_buffer = NULL;
00122 #endif
00123 
00124     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
00125 
00126     ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;
00127 
00128     /* All fine. Now allocate the readbuffer */
00129     return ftdi_read_data_set_chunksize(ftdi, 4096);
00130 }
00131 
00137 struct ftdi_context *ftdi_new(void)
00138 {
00139     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
00140 
00141     if (ftdi == NULL)
00142     {
00143         return NULL;
00144     }
00145 
00146     if (ftdi_init(ftdi) != 0)
00147     {
00148         free(ftdi);
00149         return NULL;
00150     }
00151 
00152     return ftdi;
00153 }
00154 
00165 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
00166 {
00167     if (ftdi == NULL)
00168         ftdi_error_return(-2, "USB device unavailable");
00169 
00170     switch (interface)
00171     {
00172         case INTERFACE_ANY:
00173         case INTERFACE_A:
00174             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
00175             break;
00176         case INTERFACE_B:
00177             ftdi->interface = 1;
00178             ftdi->index     = INTERFACE_B;
00179             ftdi->in_ep     = 0x04;
00180             ftdi->out_ep    = 0x83;
00181             break;
00182         case INTERFACE_C:
00183             ftdi->interface = 2;
00184             ftdi->index     = INTERFACE_C;
00185             ftdi->in_ep     = 0x06;
00186             ftdi->out_ep    = 0x85;
00187             break;
00188         case INTERFACE_D:
00189             ftdi->interface = 3;
00190             ftdi->index     = INTERFACE_D;
00191             ftdi->in_ep     = 0x08;
00192             ftdi->out_ep    = 0x87;
00193             break;
00194         default:
00195             ftdi_error_return(-1, "Unknown interface");
00196     }
00197     return 0;
00198 }
00199 
00205 void ftdi_deinit(struct ftdi_context *ftdi)
00206 {
00207     if (ftdi == NULL)
00208         return;
00209 
00210     ftdi_usb_close_internal (ftdi);
00211 
00212     if (ftdi->async_usb_buffer != NULL)
00213     {
00214         free(ftdi->async_usb_buffer);
00215         ftdi->async_usb_buffer = NULL;
00216     }
00217 
00218     if (ftdi->readbuffer != NULL)
00219     {
00220         free(ftdi->readbuffer);
00221         ftdi->readbuffer = NULL;
00222     }
00223 }
00224 
00230 void ftdi_free(struct ftdi_context *ftdi)
00231 {
00232     ftdi_deinit(ftdi);
00233     free(ftdi);
00234 }
00235 
00242 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
00243 {
00244     if (ftdi == NULL)
00245         return;
00246 
00247     ftdi->usb_dev = usb;
00248 }
00249 
00250 
00265 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
00266 {
00267     struct ftdi_device_list **curdev;
00268     struct usb_bus *bus;
00269     struct usb_device *dev;
00270     int count = 0;
00271 
00272     usb_init();
00273     if (usb_find_busses() < 0)
00274         ftdi_error_return(-1, "usb_find_busses() failed");
00275     if (usb_find_devices() < 0)
00276         ftdi_error_return(-2, "usb_find_devices() failed");
00277 
00278     curdev = devlist;
00279     *curdev = NULL;
00280     for (bus = usb_get_busses(); bus; bus = bus->next)
00281     {
00282         for (dev = bus->devices; dev; dev = dev->next)
00283         {
00284             if (dev->descriptor.idVendor == vendor
00285                     && dev->descriptor.idProduct == product)
00286             {
00287                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
00288                 if (!*curdev)
00289                     ftdi_error_return(-3, "out of memory");
00290 
00291                 (*curdev)->next = NULL;
00292                 (*curdev)->dev = dev;
00293 
00294                 curdev = &(*curdev)->next;
00295                 count++;
00296             }
00297         }
00298     }
00299 
00300     return count;
00301 }
00302 
00308 void ftdi_list_free(struct ftdi_device_list **devlist)
00309 {
00310     struct ftdi_device_list *curdev, *next;
00311 
00312     for (curdev = *devlist; curdev != NULL;)
00313     {
00314         next = curdev->next;
00315         free(curdev);
00316         curdev = next;
00317     }
00318 
00319     *devlist = NULL;
00320 }
00321 
00327 void ftdi_list_free2(struct ftdi_device_list *devlist)
00328 {
00329     ftdi_list_free(&devlist);
00330 }
00331 
00358 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
00359                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
00360 {
00361     if ((ftdi==NULL) || (dev==NULL))
00362         return -1;
00363 
00364     if (!(ftdi->usb_dev = usb_open(dev)))
00365         ftdi_error_return(-4, usb_strerror());
00366 
00367     if (manufacturer != NULL)
00368     {
00369         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
00370         {
00371             ftdi_usb_close_internal (ftdi);
00372             ftdi_error_return(-7, usb_strerror());
00373         }
00374     }
00375 
00376     if (description != NULL)
00377     {
00378         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
00379         {
00380             ftdi_usb_close_internal (ftdi);
00381             ftdi_error_return(-8, usb_strerror());
00382         }
00383     }
00384 
00385     if (serial != NULL)
00386     {
00387         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
00388         {
00389             ftdi_usb_close_internal (ftdi);
00390             ftdi_error_return(-9, usb_strerror());
00391         }
00392     }
00393 
00394     if (ftdi_usb_close_internal (ftdi) != 0)
00395         ftdi_error_return(-10, usb_strerror());
00396 
00397     return 0;
00398 }
00399 
00406 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, struct usb_device *dev)
00407 {
00408     unsigned int packet_size;
00409 
00410     // Sanity check
00411     if (ftdi == NULL || dev == NULL)
00412         return 64;
00413 
00414     // Determine maximum packet size. Init with default value.
00415     // New hi-speed devices from FTDI use a packet size of 512 bytes
00416     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
00417     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
00418         packet_size = 512;
00419     else
00420         packet_size = 64;
00421 
00422     if (dev->descriptor.bNumConfigurations > 0 && dev->config)
00423     {
00424         struct usb_config_descriptor config = dev->config[0];
00425 
00426         if (ftdi->interface < config.bNumInterfaces)
00427         {
00428             struct usb_interface interface = config.interface[ftdi->interface];
00429             if (interface.num_altsetting > 0)
00430             {
00431                 struct usb_interface_descriptor descriptor = interface.altsetting[0];
00432                 if (descriptor.bNumEndpoints > 0)
00433                 {
00434                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
00435                 }
00436             }
00437         }
00438     }
00439 
00440     return packet_size;
00441 }
00442 
00457 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
00458 {
00459     int detach_errno = 0;
00460     int config_val = 1;
00461 
00462     if (ftdi == NULL)
00463         ftdi_error_return(-8, "ftdi context invalid");
00464 
00465     if (!(ftdi->usb_dev = usb_open(dev)))
00466         ftdi_error_return(-4, "usb_open() failed");
00467 
00468 #ifdef LIBUSB_HAS_GET_DRIVER_NP
00469     // Try to detach ftdi_sio kernel module.
00470     // Returns ENODATA if driver is not loaded.
00471     //
00472     // The return code is kept in a separate variable and only parsed
00473     // if usb_set_configuration() or usb_claim_interface() fails as the
00474     // detach operation might be denied and everything still works fine.
00475     // Likely scenario is a static ftdi_sio kernel module.
00476     if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
00477     {
00478         if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
00479             detach_errno = errno;
00480     }
00481 #endif
00482 
00483 #ifdef __WIN32__
00484     // set configuration (needed especially for windows)
00485     // tolerate EBUSY: one device with one configuration, but two interfaces
00486     //    and libftdi sessions to both interfaces (e.g. FT2232)
00487 
00488     if (dev->descriptor.bNumConfigurations > 0)
00489     {
00490         // libusb-win32 on Windows 64 can return a null pointer for a valid device
00491         if (dev->config)
00492             config_val = dev->config[0].bConfigurationValue;
00493 
00494         if (usb_set_configuration(ftdi->usb_dev, config_val) &&
00495             errno != EBUSY)
00496         {
00497             ftdi_usb_close_internal (ftdi);
00498             if (detach_errno == EPERM)
00499             {
00500                 ftdi_error_return(-8, "inappropriate permissions on device!");
00501             }
00502             else
00503             {
00504                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
00505             }
00506         }
00507     }
00508 #endif
00509 
00510     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
00511     {
00512         ftdi_usb_close_internal (ftdi);
00513         if (detach_errno == EPERM)
00514         {
00515             ftdi_error_return(-8, "inappropriate permissions on device!");
00516         }
00517         else
00518         {
00519             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
00520         }
00521     }
00522 
00523     if (ftdi_usb_reset (ftdi) != 0)
00524     {
00525         ftdi_usb_close_internal (ftdi);
00526         ftdi_error_return(-6, "ftdi_usb_reset failed");
00527     }
00528 
00529     // Try to guess chip type
00530     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
00531     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
00532             && dev->descriptor.iSerialNumber == 0))
00533         ftdi->type = TYPE_BM;
00534     else if (dev->descriptor.bcdDevice == 0x200)
00535         ftdi->type = TYPE_AM;
00536     else if (dev->descriptor.bcdDevice == 0x500)
00537         ftdi->type = TYPE_2232C;
00538     else if (dev->descriptor.bcdDevice == 0x600)
00539         ftdi->type = TYPE_R;
00540     else if (dev->descriptor.bcdDevice == 0x700)
00541         ftdi->type = TYPE_2232H;
00542     else if (dev->descriptor.bcdDevice == 0x800)
00543         ftdi->type = TYPE_4232H;
00544 
00545     // Set default interface on dual/quad type chips
00546     switch(ftdi->type)
00547     {
00548         case TYPE_2232C:
00549         case TYPE_2232H:
00550         case TYPE_4232H:
00551             if (!ftdi->index)
00552                 ftdi->index = INTERFACE_A;
00553             break;
00554         default:
00555             break;
00556     }
00557 
00558     // Determine maximum packet size
00559     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
00560 
00561     if (ftdi_set_baudrate (ftdi, 9600) != 0)
00562     {
00563         ftdi_usb_close_internal (ftdi);
00564         ftdi_error_return(-7, "set baudrate failed");
00565     }
00566 
00567     ftdi_error_return(0, "all fine");
00568 }
00569 
00579 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
00580 {
00581     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
00582 }
00583 
00606 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
00607                        const char* description, const char* serial)
00608 {
00609     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
00610 }
00611 
00636 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
00637                        const char* description, const char* serial, unsigned int index)
00638 {
00639     struct usb_bus *bus;
00640     struct usb_device *dev;
00641     char string[256];
00642 
00643     usb_init();
00644 
00645     if (usb_find_busses() < 0)
00646         ftdi_error_return(-1, "usb_find_busses() failed");
00647     if (usb_find_devices() < 0)
00648         ftdi_error_return(-2, "usb_find_devices() failed");
00649 
00650     if (ftdi == NULL)
00651         ftdi_error_return(-11, "ftdi context invalid");
00652 
00653     for (bus = usb_get_busses(); bus; bus = bus->next)
00654     {
00655         for (dev = bus->devices; dev; dev = dev->next)
00656         {
00657             if (dev->descriptor.idVendor == vendor
00658                     && dev->descriptor.idProduct == product)
00659             {
00660                 if (!(ftdi->usb_dev = usb_open(dev)))
00661                     ftdi_error_return(-4, "usb_open() failed");
00662 
00663                 if (description != NULL)
00664                 {
00665                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
00666                     {
00667                         ftdi_usb_close_internal (ftdi);
00668                         ftdi_error_return(-8, "unable to fetch product description");
00669                     }
00670                     if (strncmp(string, description, sizeof(string)) != 0)
00671                     {
00672                         if (ftdi_usb_close_internal (ftdi) != 0)
00673                             ftdi_error_return(-10, "unable to close device");
00674                         continue;
00675                     }
00676                 }
00677                 if (serial != NULL)
00678                 {
00679                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
00680                     {
00681                         ftdi_usb_close_internal (ftdi);
00682                         ftdi_error_return(-9, "unable to fetch serial number");
00683                     }
00684                     if (strncmp(string, serial, sizeof(string)) != 0)
00685                     {
00686                         if (ftdi_usb_close_internal (ftdi) != 0)
00687                             ftdi_error_return(-10, "unable to close device");
00688                         continue;
00689                     }
00690                 }
00691 
00692                 if (ftdi_usb_close_internal (ftdi) != 0)
00693                     ftdi_error_return(-10, "unable to close device");
00694 
00695                 if (index > 0)
00696                 {
00697                     index--;
00698                     continue;
00699                 }
00700 
00701                 return ftdi_usb_open_dev(ftdi, dev);
00702             }
00703         }
00704     }
00705 
00706     // device not found
00707     ftdi_error_return(-3, "device not found");
00708 }
00709 
00737 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
00738 {
00739     if (ftdi == NULL)
00740         ftdi_error_return(-12, "ftdi context invalid");
00741 
00742     if (description[0] == 0 || description[1] != ':')
00743         ftdi_error_return(-11, "illegal description format");
00744 
00745     if (description[0] == 'd')
00746     {
00747         struct usb_bus *bus;
00748         struct usb_device *dev;
00749 
00750         usb_init();
00751 
00752         if (usb_find_busses() < 0)
00753             ftdi_error_return(-1, "usb_find_busses() failed");
00754         if (usb_find_devices() < 0)
00755             ftdi_error_return(-2, "usb_find_devices() failed");
00756 
00757         for (bus = usb_get_busses(); bus; bus = bus->next)
00758         {
00759             for (dev = bus->devices; dev; dev = dev->next)
00760             {
00761                 /* XXX: This doesn't handle symlinks/odd paths/etc... */
00762                 const char *desc = description + 2;
00763                 size_t len = strlen(bus->dirname);
00764                 if (strncmp(desc, bus->dirname, len))
00765                     continue;
00766                 desc += len;
00767                 if (desc[0] != '/')
00768                     continue;
00769                 ++desc;
00770                 if (strcmp(desc, dev->filename))
00771                     continue;
00772                 return ftdi_usb_open_dev(ftdi, dev);
00773             }
00774         }
00775 
00776         // device not found
00777         ftdi_error_return(-3, "device not found");
00778     }
00779     else if (description[0] == 'i' || description[0] == 's')
00780     {
00781         unsigned int vendor;
00782         unsigned int product;
00783         unsigned int index=0;
00784         const char *serial=NULL;
00785         const char *startp, *endp;
00786 
00787         errno=0;
00788         startp=description+2;
00789         vendor=strtoul((char*)startp,(char**)&endp,0);
00790         if (*endp != ':' || endp == startp || errno != 0)
00791             ftdi_error_return(-11, "illegal description format");
00792 
00793         startp=endp+1;
00794         product=strtoul((char*)startp,(char**)&endp,0);
00795         if (endp == startp || errno != 0)
00796             ftdi_error_return(-11, "illegal description format");
00797 
00798         if (description[0] == 'i' && *endp != 0)
00799         {
00800             /* optional index field in i-mode */
00801             if (*endp != ':')
00802                 ftdi_error_return(-11, "illegal description format");
00803 
00804             startp=endp+1;
00805             index=strtoul((char*)startp,(char**)&endp,0);
00806             if (*endp != 0 || endp == startp || errno != 0)
00807                 ftdi_error_return(-11, "illegal description format");
00808         }
00809         if (description[0] == 's')
00810         {
00811             if (*endp != ':')
00812                 ftdi_error_return(-11, "illegal description format");
00813 
00814             /* rest of the description is the serial */
00815             serial=endp+1;
00816         }
00817 
00818         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
00819     }
00820     else
00821     {
00822         ftdi_error_return(-11, "illegal description format");
00823     }
00824 }
00825 
00835 int ftdi_usb_reset(struct ftdi_context *ftdi)
00836 {
00837     if (ftdi == NULL || ftdi->usb_dev == NULL)
00838         ftdi_error_return(-2, "USB device unavailable");
00839 
00840     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00841                         SIO_RESET_REQUEST, SIO_RESET_SIO,
00842                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00843         ftdi_error_return(-1,"FTDI reset failed");
00844 
00845     // Invalidate data in the readbuffer
00846     ftdi->readbuffer_offset = 0;
00847     ftdi->readbuffer_remaining = 0;
00848 
00849     return 0;
00850 }
00851 
00861 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
00862 {
00863     if (ftdi == NULL || ftdi->usb_dev == NULL)
00864         ftdi_error_return(-2, "USB device unavailable");
00865 
00866     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00867                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
00868                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00869         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
00870 
00871     // Invalidate data in the readbuffer
00872     ftdi->readbuffer_offset = 0;
00873     ftdi->readbuffer_remaining = 0;
00874 
00875     return 0;
00876 }
00877 
00887 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
00888 {
00889     if (ftdi == NULL || ftdi->usb_dev == NULL)
00890         ftdi_error_return(-2, "USB device unavailable");
00891 
00892     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00893                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
00894                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00895         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
00896 
00897     return 0;
00898 }
00899 
00910 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
00911 {
00912     int result;
00913 
00914     if (ftdi == NULL || ftdi->usb_dev == NULL)
00915         ftdi_error_return(-3, "USB device unavailable");
00916 
00917     result = ftdi_usb_purge_rx_buffer(ftdi);
00918     if (result < 0)
00919         return -1;
00920 
00921     result = ftdi_usb_purge_tx_buffer(ftdi);
00922     if (result < 0)
00923         return -2;
00924 
00925     return 0;
00926 }
00927 
00928 
00929 
00940 int ftdi_usb_close(struct ftdi_context *ftdi)
00941 {
00942     int rtn = 0;
00943 
00944     if (ftdi == NULL)
00945         ftdi_error_return(-3, "ftdi context invalid");
00946 
00947 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00948     /* try to release some kernel resources */
00949     ftdi_async_complete(ftdi,1);
00950 #endif
00951 
00952     if (ftdi->usb_dev != NULL)
00953         if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
00954             rtn = -1;
00955 
00956     if (ftdi_usb_close_internal (ftdi) != 0)
00957         rtn = -2;
00958 
00959     return rtn;
00960 }
00961 
00967 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
00968                                  unsigned short *value, unsigned short *index)
00969 {
00970     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
00971     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
00972     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
00973     int divisor, best_divisor, best_baud, best_baud_diff;
00974     unsigned long encoded_divisor;
00975     int i;
00976 
00977     if (baudrate <= 0)
00978     {
00979         // Return error
00980         return -1;
00981     }
00982 
00983     divisor = 24000000 / baudrate;
00984 
00985     if (ftdi->type == TYPE_AM)
00986     {
00987         // Round down to supported fraction (AM only)
00988         divisor -= am_adjust_dn[divisor & 7];
00989     }
00990 
00991     // Try this divisor and the one above it (because division rounds down)
00992     best_divisor = 0;
00993     best_baud = 0;
00994     best_baud_diff = 0;
00995     for (i = 0; i < 2; i++)
00996     {
00997         int try_divisor = divisor + i;
00998         int baud_estimate;
00999         int baud_diff;
01000 
01001         // Round up to supported divisor value
01002         if (try_divisor <= 8)
01003         {
01004             // Round up to minimum supported divisor
01005             try_divisor = 8;
01006         }
01007         else if (ftdi->type != TYPE_AM && try_divisor < 12)
01008         {
01009             // BM doesn't support divisors 9 through 11 inclusive
01010             try_divisor = 12;
01011         }
01012         else if (divisor < 16)
01013         {
01014             // AM doesn't support divisors 9 through 15 inclusive
01015             try_divisor = 16;
01016         }
01017         else
01018         {
01019             if (ftdi->type == TYPE_AM)
01020             {
01021                 // Round up to supported fraction (AM only)
01022                 try_divisor += am_adjust_up[try_divisor & 7];
01023                 if (try_divisor > 0x1FFF8)
01024                 {
01025                     // Round down to maximum supported divisor value (for AM)
01026                     try_divisor = 0x1FFF8;
01027                 }
01028             }
01029             else
01030             {
01031                 if (try_divisor > 0x1FFFF)
01032                 {
01033                     // Round down to maximum supported divisor value (for BM)
01034                     try_divisor = 0x1FFFF;
01035                 }
01036             }
01037         }
01038         // Get estimated baud rate (to nearest integer)
01039         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
01040         // Get absolute difference from requested baud rate
01041         if (baud_estimate < baudrate)
01042         {
01043             baud_diff = baudrate - baud_estimate;
01044         }
01045         else
01046         {
01047             baud_diff = baud_estimate - baudrate;
01048         }
01049         if (i == 0 || baud_diff < best_baud_diff)
01050         {
01051             // Closest to requested baud rate so far
01052             best_divisor = try_divisor;
01053             best_baud = baud_estimate;
01054             best_baud_diff = baud_diff;
01055             if (baud_diff == 0)
01056             {
01057                 // Spot on! No point trying
01058                 break;
01059             }
01060         }
01061     }
01062     // Encode the best divisor value
01063     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
01064     // Deal with special cases for encoded value
01065     if (encoded_divisor == 1)
01066     {
01067         encoded_divisor = 0;    // 3000000 baud
01068     }
01069     else if (encoded_divisor == 0x4001)
01070     {
01071         encoded_divisor = 1;    // 2000000 baud (BM only)
01072     }
01073     // Split into "value" and "index" values
01074     *value = (unsigned short)(encoded_divisor & 0xFFFF);
01075     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
01076     {
01077         *index = (unsigned short)(encoded_divisor >> 8);
01078         *index &= 0xFF00;
01079         *index |= ftdi->index;
01080     }
01081     else
01082         *index = (unsigned short)(encoded_divisor >> 16);
01083 
01084     // Return the nearest baud rate
01085     return best_baud;
01086 }
01087 
01099 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
01100 {
01101     unsigned short value, index;
01102     int actual_baudrate;
01103 
01104     if (ftdi == NULL || ftdi->usb_dev == NULL)
01105         ftdi_error_return(-3, "USB device unavailable");
01106 
01107     if (ftdi->bitbang_enabled)
01108     {
01109         baudrate = baudrate*4;
01110     }
01111 
01112     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
01113     if (actual_baudrate <= 0)
01114         ftdi_error_return (-1, "Silly baudrate <= 0.");
01115 
01116     // Check within tolerance (about 5%)
01117     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
01118             || ((actual_baudrate < baudrate)
01119                 ? (actual_baudrate * 21 < baudrate * 20)
01120                 : (baudrate * 21 < actual_baudrate * 20)))
01121         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
01122 
01123     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01124                         SIO_SET_BAUDRATE_REQUEST, value,
01125                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
01126         ftdi_error_return (-2, "Setting new baudrate failed");
01127 
01128     ftdi->baudrate = baudrate;
01129     return 0;
01130 }
01131 
01145 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01146                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
01147 {
01148     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
01149 }
01150 
01164 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01165                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
01166                             enum ftdi_break_type break_type)
01167 {
01168     unsigned short value = bits;
01169 
01170     if (ftdi == NULL || ftdi->usb_dev == NULL)
01171         ftdi_error_return(-2, "USB device unavailable");
01172 
01173     switch (parity)
01174     {
01175         case NONE:
01176             value |= (0x00 << 8);
01177             break;
01178         case ODD:
01179             value |= (0x01 << 8);
01180             break;
01181         case EVEN:
01182             value |= (0x02 << 8);
01183             break;
01184         case MARK:
01185             value |= (0x03 << 8);
01186             break;
01187         case SPACE:
01188             value |= (0x04 << 8);
01189             break;
01190     }
01191 
01192     switch (sbit)
01193     {
01194         case STOP_BIT_1:
01195             value |= (0x00 << 11);
01196             break;
01197         case STOP_BIT_15:
01198             value |= (0x01 << 11);
01199             break;
01200         case STOP_BIT_2:
01201             value |= (0x02 << 11);
01202             break;
01203     }
01204 
01205     switch (break_type)
01206     {
01207         case BREAK_OFF:
01208             value |= (0x00 << 14);
01209             break;
01210         case BREAK_ON:
01211             value |= (0x01 << 14);
01212             break;
01213     }
01214 
01215     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01216                         SIO_SET_DATA_REQUEST, value,
01217                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01218         ftdi_error_return (-1, "Setting new line property failed");
01219 
01220     return 0;
01221 }
01222 
01234 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01235 {
01236     int ret;
01237     int offset = 0;
01238     int total_written = 0;
01239 
01240     if (ftdi == NULL || ftdi->usb_dev == NULL)
01241         ftdi_error_return(-666, "USB device unavailable");
01242 
01243     while (offset < size)
01244     {
01245         int write_size = ftdi->writebuffer_chunksize;
01246 
01247         if (offset+write_size > size)
01248             write_size = size-offset;
01249 
01250         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
01251         if (ret < 0)
01252             ftdi_error_return(ret, "usb bulk write failed");
01253 
01254         total_written += ret;
01255         offset += write_size;
01256     }
01257 
01258     return total_written;
01259 }
01260 
01261 #ifdef LIBFTDI_LINUX_ASYNC_MODE
01262 #if 0 /*def USB_CLASS_PTP*/
01263 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
01264 #endif
01265 /* this is strongly dependent on libusb using the same struct layout. If libusb
01266    changes in some later version this may break horribly (this is for libusb 0.1.12) */
01267 struct usb_dev_handle
01268 {
01269     int fd;
01270     // some other stuff coming here we don't need
01271 };
01272 
01277 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
01278 {
01279     struct usbdevfs_urb *urb;
01280     int pending=0;
01281     unsigned int i;
01282 
01283     for (i=0; i < ftdi->async_usb_buffer_size; i++)
01284     {
01285         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01286         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
01287             pending++;
01288     }
01289 
01290     return pending;
01291 }
01292 
01303 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
01304 {
01305     struct timeval tv;
01306     struct usbdevfs_urb *urb;
01307     int ret;
01308     fd_set writefds;
01309     int keep_going=0;
01310 
01311     FD_ZERO(&writefds);
01312     FD_SET(ftdi->usb_dev->fd, &writefds);
01313 
01314     /* init timeout only once, select writes time left after call */
01315     tv.tv_sec = timeout_msec / 1000;
01316     tv.tv_usec = (timeout_msec % 1000) * 1000;
01317 
01318     do
01319     {
01320         ret = -1;
01321         urb = NULL;
01322 
01323         while (_usb_get_async_urbs_pending(ftdi)
01324                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
01325                 && errno == EAGAIN)
01326         {
01327             if (keep_going && !wait_for_more)
01328             {
01329                 /* don't wait if repeating only for keep_going */
01330                 keep_going=0;
01331                 break;
01332             }
01333 
01334             /* wait for timeout msec or something written ready */
01335             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
01336         }
01337 
01338         if (ret == 0 && urb != NULL)
01339         {
01340             /* got a free urb, mark it */
01341             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
01342 
01343             /* try to get more urbs that are ready now, but don't wait anymore */
01344             keep_going=1;
01345         }
01346         else
01347         {
01348             /* no more urbs waiting */
01349             keep_going=0;
01350         }
01351     }
01352     while (keep_going);
01353 }
01354 
01362 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
01363 {
01364     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
01365 }
01366 
01372 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
01373 {
01374     struct usbdevfs_urb *urb;
01375     int bytesdone = 0, requested;
01376     int ret, cleanup_count;
01377     unsigned int i;
01378 
01379     do
01380     {
01381         /* find a free urb buffer we can use */
01382         i = 0;
01383         urb=NULL;
01384         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
01385         {
01386             if (i==ftdi->async_usb_buffer_size)
01387             {
01388                 /* wait until some buffers are free */
01389                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
01390             }
01391 
01392             for (i=0; i < ftdi->async_usb_buffer_size; i++)
01393             {
01394                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01395                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
01396                     break;  /* found a free urb position */
01397                 urb=NULL;
01398             }
01399         }
01400 
01401         /* no free urb position found */
01402         if (urb==NULL)
01403             return -1;
01404 
01405         requested = size - bytesdone;
01406         if (requested > 4096)
01407             requested = 4096;
01408 
01409         memset(urb,0,sizeof(urb));
01410 
01411         urb->type = USBDEVFS_URB_TYPE_BULK;
01412         urb->endpoint = ep;
01413         urb->flags = 0;
01414         urb->buffer = bytes + bytesdone;
01415         urb->buffer_length = requested;
01416         urb->signr = 0;
01417         urb->actual_length = 0;
01418         urb->number_of_packets = 0;
01419         urb->usercontext = 0;
01420 
01421         do
01422         {
01423             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
01424         }
01425         while (ret < 0 && errno == EINTR);
01426         if (ret < 0)
01427             return ret;       /* the caller can read errno to get more info */
01428 
01429         bytesdone += requested;
01430     }
01431     while (bytesdone < size);
01432     return bytesdone;
01433 }
01434 
01454 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
01455 {
01456     int ret;
01457     int offset = 0;
01458     int total_written = 0;
01459 
01460     if (ftdi == NULL || ftdi->usb_dev == NULL)
01461         ftdi_error_return(-666, "USB device unavailable");
01462 
01463     while (offset < size)
01464     {
01465         int write_size = ftdi->writebuffer_chunksize;
01466 
01467         if (offset+write_size > size)
01468             write_size = size-offset;
01469 
01470         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
01471         if (ret < 0)
01472             ftdi_error_return(ret, "usb bulk write async failed");
01473 
01474         total_written += ret;
01475         offset += write_size;
01476     }
01477 
01478     return total_written;
01479 }
01480 #endif // LIBFTDI_LINUX_ASYNC_MODE
01481 
01492 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01493 {
01494     if (ftdi == NULL)
01495         ftdi_error_return(-1, "ftdi context invalid");
01496 
01497     ftdi->writebuffer_chunksize = chunksize;
01498     return 0;
01499 }
01500 
01510 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01511 {
01512     if (ftdi == NULL)
01513         ftdi_error_return(-1, "ftdi context invalid");
01514 
01515     *chunksize = ftdi->writebuffer_chunksize;
01516     return 0;
01517 }
01518 
01535 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01536 {
01537     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
01538     int packet_size;
01539 
01540     if (ftdi == NULL || ftdi->usb_dev == NULL)
01541         ftdi_error_return(-666, "USB device unavailable");
01542 
01543     packet_size = ftdi->max_packet_size;
01544     // Packet size sanity check (avoid division by zero)
01545     if (packet_size == 0)
01546         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
01547 
01548     // everything we want is still in the readbuffer?
01549     if (size <= ftdi->readbuffer_remaining)
01550     {
01551         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
01552 
01553         // Fix offsets
01554         ftdi->readbuffer_remaining -= size;
01555         ftdi->readbuffer_offset += size;
01556 
01557         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
01558 
01559         return size;
01560     }
01561     // something still in the readbuffer, but not enough to satisfy 'size'?
01562     if (ftdi->readbuffer_remaining != 0)
01563     {
01564         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
01565 
01566         // Fix offset
01567         offset += ftdi->readbuffer_remaining;
01568     }
01569     // do the actual USB read
01570     while (offset < size && ret > 0)
01571     {
01572         ftdi->readbuffer_remaining = 0;
01573         ftdi->readbuffer_offset = 0;
01574         /* returns how much received */
01575         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
01576         if (ret < 0)
01577             ftdi_error_return(ret, "usb bulk read failed");
01578 
01579         if (ret > 2)
01580         {
01581             // skip FTDI status bytes.
01582             // Maybe stored in the future to enable modem use
01583             num_of_chunks = ret / packet_size;
01584             chunk_remains = ret % packet_size;
01585             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
01586 
01587             ftdi->readbuffer_offset += 2;
01588             ret -= 2;
01589 
01590             if (ret > packet_size - 2)
01591             {
01592                 for (i = 1; i < num_of_chunks; i++)
01593                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01594                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01595                              packet_size - 2);
01596                 if (chunk_remains > 2)
01597                 {
01598                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01599                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01600                              chunk_remains-2);
01601                     ret -= 2*num_of_chunks;
01602                 }
01603                 else
01604                     ret -= 2*(num_of_chunks-1)+chunk_remains;
01605             }
01606         }
01607         else if (ret <= 2)
01608         {
01609             // no more data to read?
01610             return offset;
01611         }
01612         if (ret > 0)
01613         {
01614             // data still fits in buf?
01615             if (offset+ret <= size)
01616             {
01617                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
01618                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
01619                 offset += ret;
01620 
01621                 /* Did we read exactly the right amount of bytes? */
01622                 if (offset == size)
01623                     //printf("read_data exact rem %d offset %d\n",
01624                     //ftdi->readbuffer_remaining, offset);
01625                     return offset;
01626             }
01627             else
01628             {
01629                 // only copy part of the data or size <= readbuffer_chunksize
01630                 int part_size = size-offset;
01631                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
01632 
01633                 ftdi->readbuffer_offset += part_size;
01634                 ftdi->readbuffer_remaining = ret-part_size;
01635                 offset += part_size;
01636 
01637                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
01638                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
01639 
01640                 return offset;
01641             }
01642         }
01643     }
01644     // never reached
01645     return -127;
01646 }
01647 
01660 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01661 {
01662     unsigned char *new_buf;
01663 
01664     if (ftdi == NULL)
01665         ftdi_error_return(-1, "ftdi context invalid");
01666 
01667     // Invalidate all remaining data
01668     ftdi->readbuffer_offset = 0;
01669     ftdi->readbuffer_remaining = 0;
01670 
01671     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
01672         ftdi_error_return(-1, "out of memory for readbuffer");
01673 
01674     ftdi->readbuffer = new_buf;
01675     ftdi->readbuffer_chunksize = chunksize;
01676 
01677     return 0;
01678 }
01679 
01689 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01690 {
01691     if (ftdi == NULL)
01692         ftdi_error_return(-1, "FTDI context invalid");
01693 
01694     *chunksize = ftdi->readbuffer_chunksize;
01695     return 0;
01696 }
01697 
01698 
01712 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
01713 {
01714     unsigned short usb_val;
01715 
01716     if (ftdi == NULL || ftdi->usb_dev == NULL)
01717         ftdi_error_return(-2, "USB device unavailable");
01718 
01719     usb_val = bitmask; // low byte: bitmask
01720     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
01721     usb_val |= (ftdi->bitbang_mode << 8);
01722 
01723     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01724                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
01725                         NULL, 0, ftdi->usb_write_timeout) != 0)
01726         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
01727 
01728     ftdi->bitbang_enabled = 1;
01729     return 0;
01730 }
01731 
01741 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
01742 {
01743     if (ftdi == NULL || ftdi->usb_dev == NULL)
01744         ftdi_error_return(-2, "USB device unavailable");
01745 
01746     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)
01747         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
01748 
01749     ftdi->bitbang_enabled = 0;
01750     return 0;
01751 }
01752 
01765 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
01766 {
01767     unsigned short usb_val;
01768 
01769     if (ftdi == NULL || ftdi->usb_dev == NULL)
01770         ftdi_error_return(-2, "USB device unavailable");
01771 
01772     usb_val = bitmask; // low byte: bitmask
01773     usb_val |= (mode << 8);
01774     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)
01775         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps selected mode not supported on your chip?");
01776 
01777     ftdi->bitbang_mode = mode;
01778     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
01779     return 0;
01780 }
01781 
01792 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
01793 {
01794     if (ftdi == NULL || ftdi->usb_dev == NULL)
01795         ftdi_error_return(-2, "USB device unavailable");
01796 
01797     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)
01798         ftdi_error_return(-1, "read pins failed");
01799 
01800     return 0;
01801 }
01802 
01818 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
01819 {
01820     unsigned short usb_val;
01821 
01822     if (latency < 1)
01823         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
01824 
01825     if (ftdi == NULL || ftdi->usb_dev == NULL)
01826         ftdi_error_return(-3, "USB device unavailable");
01827 
01828     usb_val = latency;
01829     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)
01830         ftdi_error_return(-2, "unable to set latency timer");
01831 
01832     return 0;
01833 }
01834 
01845 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
01846 {
01847     unsigned short usb_val;
01848 
01849     if (ftdi == NULL || ftdi->usb_dev == NULL)
01850         ftdi_error_return(-2, "USB device unavailable");
01851 
01852     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)
01853         ftdi_error_return(-1, "reading latency timer failed");
01854 
01855     *latency = (unsigned char)usb_val;
01856     return 0;
01857 }
01858 
01899 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
01900 {
01901     char usb_val[2];
01902 
01903     if (ftdi == NULL || ftdi->usb_dev == NULL)
01904         ftdi_error_return(-2, "USB device unavailable");
01905 
01906     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)
01907         ftdi_error_return(-1, "getting modem status failed");
01908 
01909     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
01910 
01911     return 0;
01912 }
01913 
01925 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
01926 {
01927     if (ftdi == NULL || ftdi->usb_dev == NULL)
01928         ftdi_error_return(-2, "USB device unavailable");
01929 
01930     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01931                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
01932                         NULL, 0, ftdi->usb_write_timeout) != 0)
01933         ftdi_error_return(-1, "set flow control failed");
01934 
01935     return 0;
01936 }
01937 
01948 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
01949 {
01950     unsigned short usb_val;
01951 
01952     if (ftdi == NULL || ftdi->usb_dev == NULL)
01953         ftdi_error_return(-2, "USB device unavailable");
01954 
01955     if (state)
01956         usb_val = SIO_SET_DTR_HIGH;
01957     else
01958         usb_val = SIO_SET_DTR_LOW;
01959 
01960     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01961                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01962                         NULL, 0, ftdi->usb_write_timeout) != 0)
01963         ftdi_error_return(-1, "set dtr failed");
01964 
01965     return 0;
01966 }
01967 
01978 int ftdi_setrts(struct ftdi_context *ftdi, int state)
01979 {
01980     unsigned short usb_val;
01981 
01982     if (ftdi == NULL || ftdi->usb_dev == NULL)
01983         ftdi_error_return(-2, "USB device unavailable");
01984 
01985     if (state)
01986         usb_val = SIO_SET_RTS_HIGH;
01987     else
01988         usb_val = SIO_SET_RTS_LOW;
01989 
01990     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01991                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01992                         NULL, 0, ftdi->usb_write_timeout) != 0)
01993         ftdi_error_return(-1, "set of rts failed");
01994 
01995     return 0;
01996 }
01997 
02009 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
02010 {
02011     unsigned short usb_val;
02012 
02013     if (ftdi == NULL || ftdi->usb_dev == NULL)
02014         ftdi_error_return(-2, "USB device unavailable");
02015 
02016     if (dtr)
02017         usb_val = SIO_SET_DTR_HIGH;
02018     else
02019         usb_val = SIO_SET_DTR_LOW;
02020 
02021     if (rts)
02022         usb_val |= SIO_SET_RTS_HIGH;
02023     else
02024         usb_val |= SIO_SET_RTS_LOW;
02025 
02026     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02027                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
02028                         NULL, 0, ftdi->usb_write_timeout) != 0)
02029         ftdi_error_return(-1, "set of rts/dtr failed");
02030 
02031     return 0;
02032 }
02033 
02045 int ftdi_set_event_char(struct ftdi_context *ftdi,
02046                         unsigned char eventch, unsigned char enable)
02047 {
02048     unsigned short usb_val;
02049 
02050     if (ftdi == NULL || ftdi->usb_dev == NULL)
02051         ftdi_error_return(-2, "USB device unavailable");
02052 
02053     usb_val = eventch;
02054     if (enable)
02055         usb_val |= 1 << 8;
02056 
02057     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)
02058         ftdi_error_return(-1, "setting event character failed");
02059 
02060     return 0;
02061 }
02062 
02074 int ftdi_set_error_char(struct ftdi_context *ftdi,
02075                         unsigned char errorch, unsigned char enable)
02076 {
02077     unsigned short usb_val;
02078 
02079     if (ftdi == NULL || ftdi->usb_dev == NULL)
02080         ftdi_error_return(-2, "USB device unavailable");
02081 
02082     usb_val = errorch;
02083     if (enable)
02084         usb_val |= 1 << 8;
02085 
02086     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)
02087         ftdi_error_return(-1, "setting error character failed");
02088 
02089     return 0;
02090 }
02091 
02100 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
02101 {
02102     if (ftdi == NULL)
02103         return;
02104 
02105     ftdi->eeprom_size=size;
02106     eeprom->size=size;
02107 }
02108 
02114 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
02115 {
02116     int i;
02117 
02118     if (eeprom == NULL)
02119         return;
02120 
02121     eeprom->vendor_id = 0x0403;
02122     eeprom->product_id = 0x6001;
02123 
02124     eeprom->self_powered = 1;
02125     eeprom->remote_wakeup = 1;
02126     eeprom->chip_type = TYPE_BM;
02127 
02128     eeprom->in_is_isochronous = 0;
02129     eeprom->out_is_isochronous = 0;
02130     eeprom->suspend_pull_downs = 0;
02131 
02132     eeprom->use_serial = 0;
02133     eeprom->change_usb_version = 0;
02134     eeprom->usb_version = 0x0200;
02135     eeprom->max_power = 0;
02136 
02137     eeprom->manufacturer = NULL;
02138     eeprom->product = NULL;
02139     eeprom->serial = NULL;
02140     for (i=0; i < 5; i++)
02141     {
02142         eeprom->cbus_function[i] = 0;
02143     }
02144     eeprom->high_current = 0;
02145     eeprom->invert = 0;
02146 
02147     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
02148 }
02149 
02155 void ftdi_eeprom_free(struct ftdi_eeprom *eeprom)
02156 {
02157     if (!eeprom)
02158         return;
02159 
02160     if (eeprom->manufacturer != 0) {
02161         free(eeprom->manufacturer);
02162         eeprom->manufacturer = 0;
02163     }
02164     if (eeprom->product != 0) {
02165         free(eeprom->product);
02166         eeprom->product = 0;
02167     }
02168     if (eeprom->serial != 0) {
02169         free(eeprom->serial);
02170         eeprom->serial = 0;
02171     }
02172 }
02173 
02189 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
02190 {
02191     unsigned char i, j;
02192     unsigned short checksum, value;
02193     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02194     int size_check;
02195     const int cbus_max[5] = {13, 13, 13, 13, 9};
02196 
02197     if (eeprom == NULL)
02198         return -2;
02199 
02200     if (eeprom->manufacturer != NULL)
02201         manufacturer_size = strlen(eeprom->manufacturer);
02202     if (eeprom->product != NULL)
02203         product_size = strlen(eeprom->product);
02204     if (eeprom->serial != NULL)
02205         serial_size = strlen(eeprom->serial);
02206 
02207     // highest allowed cbus value
02208     for (i = 0; i < 5; i++)
02209     {
02210         if ((eeprom->cbus_function[i] > cbus_max[i]) ||
02211             (eeprom->cbus_function[i] && eeprom->chip_type != TYPE_R)) return -3;
02212     }
02213     if (eeprom->chip_type != TYPE_R)
02214     {
02215         if (eeprom->invert) return -4;
02216         if (eeprom->high_current) return -5;
02217     }
02218 
02219     size_check = eeprom->size;
02220     size_check -= 28; // 28 are always in use (fixed)
02221 
02222     // Top half of a 256byte eeprom is used just for strings and checksum
02223     // it seems that the FTDI chip will not read these strings from the lower half
02224     // Each string starts with two bytes; offset and type (0x03 for string)
02225     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02226     if (eeprom->size>=256) size_check = 120;
02227     size_check -= manufacturer_size*2;
02228     size_check -= product_size*2;
02229     size_check -= serial_size*2;
02230 
02231     // eeprom size exceeded?
02232     if (size_check < 0)
02233         return (-1);
02234 
02235     // empty eeprom
02236     memset (output, 0, eeprom->size);
02237 
02238     // Addr 00: High current IO
02239     output[0x00] = eeprom->high_current ? HIGH_CURRENT_DRIVE : 0;
02240     // Addr 01: IN endpoint size (for R type devices, different for FT2232)
02241     if (eeprom->chip_type == TYPE_R) {
02242         output[0x01] = 0x40;
02243     }
02244     // Addr 02: Vendor ID
02245     output[0x02] = eeprom->vendor_id;
02246     output[0x03] = eeprom->vendor_id >> 8;
02247 
02248     // Addr 04: Product ID
02249     output[0x04] = eeprom->product_id;
02250     output[0x05] = eeprom->product_id >> 8;
02251 
02252     // Addr 06: Device release number (0400h for BM features)
02253     output[0x06] = 0x00;
02254     switch (eeprom->chip_type) {
02255         case TYPE_AM:
02256             output[0x07] = 0x02;
02257             break;
02258         case TYPE_BM:
02259             output[0x07] = 0x04;
02260             break;
02261         case TYPE_2232C:
02262             output[0x07] = 0x05;
02263             break;
02264         case TYPE_R:
02265             output[0x07] = 0x06;
02266             break;
02267         default:
02268             output[0x07] = 0x00;
02269     }
02270 
02271     // Addr 08: Config descriptor
02272     // Bit 7: always 1
02273     // Bit 6: 1 if this device is self powered, 0 if bus powered
02274     // Bit 5: 1 if this device uses remote wakeup
02275     // Bit 4: 1 if this device is battery powered
02276     j = 0x80;
02277     if (eeprom->self_powered == 1)
02278         j |= 0x40;
02279     if (eeprom->remote_wakeup == 1)
02280         j |= 0x20;
02281     output[0x08] = j;
02282 
02283     // Addr 09: Max power consumption: max power = value * 2 mA
02284     output[0x09] = eeprom->max_power;
02285 
02286     // Addr 0A: Chip configuration
02287     // Bit 7: 0 - reserved
02288     // Bit 6: 0 - reserved
02289     // Bit 5: 0 - reserved
02290     // Bit 4: 1 - Change USB version
02291     // Bit 3: 1 - Use the serial number string
02292     // Bit 2: 1 - Enable suspend pull downs for lower power
02293     // Bit 1: 1 - Out EndPoint is Isochronous
02294     // Bit 0: 1 - In EndPoint is Isochronous
02295     //
02296     j = 0;
02297     if (eeprom->in_is_isochronous == 1)
02298         j = j | 1;
02299     if (eeprom->out_is_isochronous == 1)
02300         j = j | 2;
02301     if (eeprom->suspend_pull_downs == 1)
02302         j = j | 4;
02303     if (eeprom->use_serial == 1)
02304         j = j | 8;
02305     if (eeprom->change_usb_version == 1)
02306         j = j | 16;
02307     output[0x0A] = j;
02308 
02309     // Addr 0B: Invert data lines
02310     output[0x0B] = eeprom->invert & 0xff;
02311 
02312     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02313     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02314     if (eeprom->change_usb_version == 1)
02315     {
02316         output[0x0C] = eeprom->usb_version;
02317         output[0x0D] = eeprom->usb_version >> 8;
02318     }
02319 
02320 
02321     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02322     // Addr 0F: Length of manufacturer string
02323     output[0x0F] = manufacturer_size*2 + 2;
02324 
02325     // Addr 10: Offset of the product string + 0x80, calculated later
02326     // Addr 11: Length of product string
02327     output[0x11] = product_size*2 + 2;
02328 
02329     // Addr 12: Offset of the serial string + 0x80, calculated later
02330     // Addr 13: Length of serial string
02331     output[0x13] = serial_size*2 + 2;
02332 
02333     // Addr 14: CBUS function: CBUS0, CBUS1
02334     // Addr 15: CBUS function: CBUS2, CBUS3
02335     // Addr 16: CBUS function: CBUS5
02336     output[0x14] = eeprom->cbus_function[0] | (eeprom->cbus_function[1] << 4);
02337     output[0x15] = eeprom->cbus_function[2] | (eeprom->cbus_function[3] << 4);
02338     output[0x16] = eeprom->cbus_function[4];
02339     // Addr 17: Unknown
02340 
02341     // Dynamic content
02342     // In images produced by FTDI's FT_Prog for FT232R strings start at 0x18
02343     // Space till 0x18 should be considered as reserved.
02344     if (eeprom->chip_type >= TYPE_R) {
02345         i = 0x18;
02346     } else {
02347         i = 0x14;
02348     }
02349     if (eeprom->size >= 256) i = 0x80;
02350 
02351 
02352     // Output manufacturer
02353     output[0x0E] = i | 0x80;  // calculate offset
02354     output[i++] = manufacturer_size*2 + 2;
02355     output[i++] = 0x03; // type: string
02356     for (j = 0; j < manufacturer_size; j++)
02357     {
02358         output[i] = eeprom->manufacturer[j], i++;
02359         output[i] = 0x00, i++;
02360     }
02361 
02362     // Output product name
02363     output[0x10] = i | 0x80;  // calculate offset
02364     output[i] = product_size*2 + 2, i++;
02365     output[i] = 0x03, i++;
02366     for (j = 0; j < product_size; j++)
02367     {
02368         output[i] = eeprom->product[j], i++;
02369         output[i] = 0x00, i++;
02370     }
02371 
02372     // Output serial
02373     output[0x12] = i | 0x80; // calculate offset
02374     output[i] = serial_size*2 + 2, i++;
02375     output[i] = 0x03, i++;
02376     for (j = 0; j < serial_size; j++)
02377     {
02378         output[i] = eeprom->serial[j], i++;
02379         output[i] = 0x00, i++;
02380     }
02381 
02382     // calculate checksum
02383     checksum = 0xAAAA;
02384 
02385     for (i = 0; i < eeprom->size/2-1; i++)
02386     {
02387         value = output[i*2];
02388         value += output[(i*2)+1] << 8;
02389 
02390         checksum = value^checksum;
02391         checksum = (checksum << 1) | (checksum >> 15);
02392     }
02393 
02394     output[eeprom->size-2] = checksum;
02395     output[eeprom->size-1] = checksum >> 8;
02396 
02397     return size_check;
02398 }
02399 
02413 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
02414 {
02415     unsigned char i, j;
02416     unsigned short checksum, eeprom_checksum, value;
02417     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02418     int size_check;
02419     int eeprom_size = 128;
02420 
02421     if (eeprom == NULL)
02422         return -1;
02423 #if 0
02424     size_check = eeprom->size;
02425     size_check -= 28; // 28 are always in use (fixed)
02426 
02427     // Top half of a 256byte eeprom is used just for strings and checksum
02428     // it seems that the FTDI chip will not read these strings from the lower half
02429     // Each string starts with two bytes; offset and type (0x03 for string)
02430     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02431     if (eeprom->size>=256)size_check = 120;
02432     size_check -= manufacturer_size*2;
02433     size_check -= product_size*2;
02434     size_check -= serial_size*2;
02435 
02436     // eeprom size exceeded?
02437     if (size_check < 0)
02438         return (-1);
02439 #endif
02440 
02441     // empty eeprom struct
02442     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
02443 
02444     // Addr 00: High current IO
02445     eeprom->high_current = (buf[0x02] & HIGH_CURRENT_DRIVE);
02446 
02447     // Addr 02: Vendor ID
02448     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
02449 
02450     // Addr 04: Product ID
02451     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
02452 
02453     value = buf[0x06] + (buf[0x07]<<8);
02454     switch (value)
02455     {
02456         case 0x0600:
02457             eeprom->chip_type = TYPE_R;
02458             break;
02459         case 0x0400:
02460             eeprom->chip_type = TYPE_BM;
02461             break;
02462         case 0x0200:
02463             eeprom->chip_type = TYPE_AM;
02464             break;
02465         default: // Unknown device
02466             eeprom->chip_type = 0;
02467             break;
02468     }
02469 
02470     // Addr 08: Config descriptor
02471     // Bit 7: always 1
02472     // Bit 6: 1 if this device is self powered, 0 if bus powered
02473     // Bit 5: 1 if this device uses remote wakeup
02474     // Bit 4: 1 if this device is battery powered
02475     j = buf[0x08];
02476     if (j&0x40) eeprom->self_powered = 1;
02477     if (j&0x20) eeprom->remote_wakeup = 1;
02478 
02479     // Addr 09: Max power consumption: max power = value * 2 mA
02480     eeprom->max_power = buf[0x09];
02481 
02482     // Addr 0A: Chip configuration
02483     // Bit 7: 0 - reserved
02484     // Bit 6: 0 - reserved
02485     // Bit 5: 0 - reserved
02486     // Bit 4: 1 - Change USB version
02487     // Bit 3: 1 - Use the serial number string
02488     // Bit 2: 1 - Enable suspend pull downs for lower power
02489     // Bit 1: 1 - Out EndPoint is Isochronous
02490     // Bit 0: 1 - In EndPoint is Isochronous
02491     //
02492     j = buf[0x0A];
02493     if (j&0x01) eeprom->in_is_isochronous = 1;
02494     if (j&0x02) eeprom->out_is_isochronous = 1;
02495     if (j&0x04) eeprom->suspend_pull_downs = 1;
02496     if (j&0x08) eeprom->use_serial = 1;
02497     if (j&0x10) eeprom->change_usb_version = 1;
02498 
02499     // Addr 0B: Invert data lines
02500     eeprom->invert = buf[0x0B];
02501 
02502     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02503     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02504     if (eeprom->change_usb_version == 1)
02505     {
02506         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
02507     }
02508 
02509     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02510     // Addr 0F: Length of manufacturer string
02511     manufacturer_size = buf[0x0F]/2;
02512     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
02513     else eeprom->manufacturer = NULL;
02514 
02515     // Addr 10: Offset of the product string + 0x80, calculated later
02516     // Addr 11: Length of product string
02517     product_size = buf[0x11]/2;
02518     if (product_size > 0) eeprom->product = malloc(product_size);
02519     else eeprom->product = NULL;
02520 
02521     // Addr 12: Offset of the serial string + 0x80, calculated later
02522     // Addr 13: Length of serial string
02523     serial_size = buf[0x13]/2;
02524     if (serial_size > 0) eeprom->serial = malloc(serial_size);
02525     else eeprom->serial = NULL;
02526 
02527     // Addr 14: CBUS function: CBUS0, CBUS1
02528     // Addr 15: CBUS function: CBUS2, CBUS3
02529     // Addr 16: CBUS function: CBUS5
02530     if (eeprom->chip_type == TYPE_R) {
02531         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
02532         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
02533         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
02534         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
02535         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
02536     } else {
02537         for (j=0; j<5; j++) eeprom->cbus_function[j] = 0;
02538     }
02539 
02540     // Decode manufacturer
02541     i = buf[0x0E] & 0x7f; // offset
02542     for (j=0;j<manufacturer_size-1;j++)
02543     {
02544         eeprom->manufacturer[j] = buf[2*j+i+2];
02545     }
02546     eeprom->manufacturer[j] = '\0';
02547 
02548     // Decode product name
02549     i = buf[0x10] & 0x7f; // offset
02550     for (j=0;j<product_size-1;j++)
02551     {
02552         eeprom->product[j] = buf[2*j+i+2];
02553     }
02554     eeprom->product[j] = '\0';
02555 
02556     // Decode serial
02557     i = buf[0x12] & 0x7f; // offset
02558     for (j=0;j<serial_size-1;j++)
02559     {
02560         eeprom->serial[j] = buf[2*j+i+2];
02561     }
02562     eeprom->serial[j] = '\0';
02563 
02564     // verify checksum
02565     checksum = 0xAAAA;
02566 
02567     for (i = 0; i < eeprom_size/2-1; i++)
02568     {
02569         value = buf[i*2];
02570         value += buf[(i*2)+1] << 8;
02571 
02572         checksum = value^checksum;
02573         checksum = (checksum << 1) | (checksum >> 15);
02574     }
02575 
02576     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
02577 
02578     if (eeprom_checksum != checksum)
02579     {
02580         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
02581         return -1;
02582     }
02583 
02584     return 0;
02585 }
02586 
02598 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
02599 {
02600     if (ftdi == NULL || ftdi->usb_dev == NULL)
02601         ftdi_error_return(-2, "USB device unavailable");
02602 
02603     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)
02604         ftdi_error_return(-1, "reading eeprom failed");
02605 
02606     return 0;
02607 }
02608 
02619 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02620 {
02621     int i;
02622 
02623     if (ftdi == NULL || ftdi->usb_dev == NULL)
02624         ftdi_error_return(-2, "USB device unavailable");
02625 
02626     for (i = 0; i < ftdi->eeprom_size/2; i++)
02627     {
02628         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)
02629             ftdi_error_return(-1, "reading eeprom failed");
02630     }
02631 
02632     return 0;
02633 }
02634 
02635 /*
02636     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
02637     Function is only used internally
02638     \internal
02639 */
02640 static unsigned char ftdi_read_chipid_shift(unsigned char value)
02641 {
02642     return ((value & 1) << 1) |
02643            ((value & 2) << 5) |
02644            ((value & 4) >> 2) |
02645            ((value & 8) << 4) |
02646            ((value & 16) >> 1) |
02647            ((value & 32) >> 1) |
02648            ((value & 64) >> 4) |
02649            ((value & 128) >> 2);
02650 }
02651 
02662 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
02663 {
02664     unsigned int a = 0, b = 0;
02665 
02666     if (ftdi == NULL || ftdi->usb_dev == NULL)
02667         ftdi_error_return(-2, "USB device unavailable");
02668 
02669     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)
02670     {
02671         a = a << 8 | a >> 8;
02672         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)
02673         {
02674             b = b << 8 | b >> 8;
02675             a = (a << 16) | (b & 0xFFFF);
02676             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
02677                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
02678             *chipid = a ^ 0xa5f0f7d1;
02679             return 0;
02680         }
02681     }
02682 
02683     ftdi_error_return(-1, "read of FTDIChip-ID failed");
02684 }
02685 
02698 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
02699 {
02700     int i=0,j,minsize=32;
02701     int size=minsize;
02702 
02703     if (ftdi == NULL || ftdi->usb_dev == NULL)
02704         ftdi_error_return(-2, "USB device unavailable");
02705 
02706     do
02707     {
02708         for (j = 0; i < maxsize/2 && j<size; j++)
02709         {
02710             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
02711                                 SIO_READ_EEPROM_REQUEST, 0, i,
02712                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02713                 ftdi_error_return(-1, "eeprom read failed");
02714             i++;
02715         }
02716         size*=2;
02717     }
02718     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
02719 
02720     return size/2;
02721 }
02722 
02734 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
02735 {
02736     if (ftdi == NULL || ftdi->usb_dev == NULL)
02737         ftdi_error_return(-2, "USB device unavailable");
02738 
02739     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02740                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
02741                                     NULL, 0, ftdi->usb_write_timeout) != 0)
02742         ftdi_error_return(-1, "unable to write eeprom");
02743 
02744     return 0;
02745 }
02746 
02757 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02758 {
02759     unsigned short usb_val, status;
02760     int i, ret;
02761 
02762     if (ftdi == NULL || ftdi->usb_dev == NULL)
02763         ftdi_error_return(-2, "USB device unavailable");
02764 
02765     /* These commands were traced while running MProg */
02766     if ((ret = ftdi_usb_reset(ftdi)) != 0)
02767         return ret;
02768     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
02769         return ret;
02770     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
02771         return ret;
02772 
02773     for (i = 0; i < ftdi->eeprom_size/2; i++)
02774     {
02775         usb_val = eeprom[i*2];
02776         usb_val += eeprom[(i*2)+1] << 8;
02777         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02778                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
02779                             NULL, 0, ftdi->usb_write_timeout) != 0)
02780             ftdi_error_return(-1, "unable to write eeprom");
02781     }
02782 
02783     return 0;
02784 }
02785 
02797 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
02798 {
02799     if (ftdi == NULL || ftdi->usb_dev == NULL)
02800         ftdi_error_return(-2, "USB device unavailable");
02801 
02802     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
02803         ftdi_error_return(-1, "unable to erase eeprom");
02804 
02805     return 0;
02806 }
02807 
02815 char *ftdi_get_error_string (struct ftdi_context *ftdi)
02816 {
02817     if (ftdi == NULL)
02818         return "";
02819 
02820     return ftdi->error_str;
02821 }
02822 
02823 /* @} end of doxygen libftdi group */