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         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 || ftdi->type == TYPE_232H)
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     else if (dev->descriptor.bcdDevice == 0x900)
00545         ftdi->type = TYPE_232H;
00546 
00547     // Set default interface on dual/quad type chips
00548     switch(ftdi->type)
00549     {
00550         case TYPE_2232C:
00551         case TYPE_2232H:
00552         case TYPE_4232H:
00553             if (!ftdi->index)
00554                 ftdi->index = INTERFACE_A;
00555             break;
00556         default:
00557             break;
00558     }
00559 
00560     // Determine maximum packet size
00561     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
00562 
00563     if (ftdi_set_baudrate (ftdi, 9600) != 0)
00564     {
00565         ftdi_usb_close_internal (ftdi);
00566         ftdi_error_return(-7, "set baudrate failed");
00567     }
00568 
00569     ftdi_error_return(0, "all fine");
00570 }
00571 
00581 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
00582 {
00583     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
00584 }
00585 
00608 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
00609                        const char* description, const char* serial)
00610 {
00611     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
00612 }
00613 
00638 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
00639                        const char* description, const char* serial, unsigned int index)
00640 {
00641     struct usb_bus *bus;
00642     struct usb_device *dev;
00643     char string[256];
00644 
00645     usb_init();
00646 
00647     if (usb_find_busses() < 0)
00648         ftdi_error_return(-1, "usb_find_busses() failed");
00649     if (usb_find_devices() < 0)
00650         ftdi_error_return(-2, "usb_find_devices() failed");
00651 
00652     if (ftdi == NULL)
00653         ftdi_error_return(-11, "ftdi context invalid");
00654 
00655     for (bus = usb_get_busses(); bus; bus = bus->next)
00656     {
00657         for (dev = bus->devices; dev; dev = dev->next)
00658         {
00659             if (dev->descriptor.idVendor == vendor
00660                     && dev->descriptor.idProduct == product)
00661             {
00662                 if (!(ftdi->usb_dev = usb_open(dev)))
00663                     ftdi_error_return(-4, "usb_open() failed");
00664 
00665                 if (description != NULL)
00666                 {
00667                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
00668                     {
00669                         ftdi_usb_close_internal (ftdi);
00670                         ftdi_error_return(-8, "unable to fetch product description");
00671                     }
00672                     if (strncmp(string, description, sizeof(string)) != 0)
00673                     {
00674                         if (ftdi_usb_close_internal (ftdi) != 0)
00675                             ftdi_error_return(-10, "unable to close device");
00676                         continue;
00677                     }
00678                 }
00679                 if (serial != NULL)
00680                 {
00681                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
00682                     {
00683                         ftdi_usb_close_internal (ftdi);
00684                         ftdi_error_return(-9, "unable to fetch serial number");
00685                     }
00686                     if (strncmp(string, serial, sizeof(string)) != 0)
00687                     {
00688                         if (ftdi_usb_close_internal (ftdi) != 0)
00689                             ftdi_error_return(-10, "unable to close device");
00690                         continue;
00691                     }
00692                 }
00693 
00694                 if (ftdi_usb_close_internal (ftdi) != 0)
00695                     ftdi_error_return(-10, "unable to close device");
00696 
00697                 if (index > 0)
00698                 {
00699                     index--;
00700                     continue;
00701                 }
00702 
00703                 return ftdi_usb_open_dev(ftdi, dev);
00704             }
00705         }
00706     }
00707 
00708     // device not found
00709     ftdi_error_return(-3, "device not found");
00710 }
00711 
00739 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
00740 {
00741     if (ftdi == NULL)
00742         ftdi_error_return(-12, "ftdi context invalid");
00743 
00744     if (description[0] == 0 || description[1] != ':')
00745         ftdi_error_return(-11, "illegal description format");
00746 
00747     if (description[0] == 'd')
00748     {
00749         struct usb_bus *bus;
00750         struct usb_device *dev;
00751 
00752         usb_init();
00753 
00754         if (usb_find_busses() < 0)
00755             ftdi_error_return(-1, "usb_find_busses() failed");
00756         if (usb_find_devices() < 0)
00757             ftdi_error_return(-2, "usb_find_devices() failed");
00758 
00759         for (bus = usb_get_busses(); bus; bus = bus->next)
00760         {
00761             for (dev = bus->devices; dev; dev = dev->next)
00762             {
00763                 /* XXX: This doesn't handle symlinks/odd paths/etc... */
00764                 const char *desc = description + 2;
00765                 size_t len = strlen(bus->dirname);
00766                 if (strncmp(desc, bus->dirname, len))
00767                     continue;
00768                 desc += len;
00769                 if (desc[0] != '/')
00770                     continue;
00771                 ++desc;
00772                 if (strcmp(desc, dev->filename))
00773                     continue;
00774                 return ftdi_usb_open_dev(ftdi, dev);
00775             }
00776         }
00777 
00778         // device not found
00779         ftdi_error_return(-3, "device not found");
00780     }
00781     else if (description[0] == 'i' || description[0] == 's')
00782     {
00783         unsigned int vendor;
00784         unsigned int product;
00785         unsigned int index=0;
00786         const char *serial=NULL;
00787         const char *startp, *endp;
00788 
00789         errno=0;
00790         startp=description+2;
00791         vendor=strtoul((char*)startp,(char**)&endp,0);
00792         if (*endp != ':' || endp == startp || errno != 0)
00793             ftdi_error_return(-11, "illegal description format");
00794 
00795         startp=endp+1;
00796         product=strtoul((char*)startp,(char**)&endp,0);
00797         if (endp == startp || errno != 0)
00798             ftdi_error_return(-11, "illegal description format");
00799 
00800         if (description[0] == 'i' && *endp != 0)
00801         {
00802             /* optional index field in i-mode */
00803             if (*endp != ':')
00804                 ftdi_error_return(-11, "illegal description format");
00805 
00806             startp=endp+1;
00807             index=strtoul((char*)startp,(char**)&endp,0);
00808             if (*endp != 0 || endp == startp || errno != 0)
00809                 ftdi_error_return(-11, "illegal description format");
00810         }
00811         if (description[0] == 's')
00812         {
00813             if (*endp != ':')
00814                 ftdi_error_return(-11, "illegal description format");
00815 
00816             /* rest of the description is the serial */
00817             serial=endp+1;
00818         }
00819 
00820         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
00821     }
00822     else
00823     {
00824         ftdi_error_return(-11, "illegal description format");
00825     }
00826 }
00827 
00837 int ftdi_usb_reset(struct ftdi_context *ftdi)
00838 {
00839     if (ftdi == NULL || ftdi->usb_dev == NULL)
00840         ftdi_error_return(-2, "USB device unavailable");
00841 
00842     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00843                         SIO_RESET_REQUEST, SIO_RESET_SIO,
00844                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00845         ftdi_error_return(-1,"FTDI reset failed");
00846 
00847     // Invalidate data in the readbuffer
00848     ftdi->readbuffer_offset = 0;
00849     ftdi->readbuffer_remaining = 0;
00850 
00851     return 0;
00852 }
00853 
00863 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
00864 {
00865     if (ftdi == NULL || ftdi->usb_dev == NULL)
00866         ftdi_error_return(-2, "USB device unavailable");
00867 
00868     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00869                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
00870                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00871         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
00872 
00873     // Invalidate data in the readbuffer
00874     ftdi->readbuffer_offset = 0;
00875     ftdi->readbuffer_remaining = 0;
00876 
00877     return 0;
00878 }
00879 
00889 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
00890 {
00891     if (ftdi == NULL || ftdi->usb_dev == NULL)
00892         ftdi_error_return(-2, "USB device unavailable");
00893 
00894     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00895                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
00896                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00897         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
00898 
00899     return 0;
00900 }
00901 
00912 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
00913 {
00914     int result;
00915 
00916     if (ftdi == NULL || ftdi->usb_dev == NULL)
00917         ftdi_error_return(-3, "USB device unavailable");
00918 
00919     result = ftdi_usb_purge_rx_buffer(ftdi);
00920     if (result < 0)
00921         return -1;
00922 
00923     result = ftdi_usb_purge_tx_buffer(ftdi);
00924     if (result < 0)
00925         return -2;
00926 
00927     return 0;
00928 }
00929 
00930 
00931 
00942 int ftdi_usb_close(struct ftdi_context *ftdi)
00943 {
00944     int rtn = 0;
00945 
00946     if (ftdi == NULL)
00947         ftdi_error_return(-3, "ftdi context invalid");
00948 
00949 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00950     /* try to release some kernel resources */
00951     ftdi_async_complete(ftdi,1);
00952 #endif
00953 
00954     if (ftdi->usb_dev != NULL)
00955         if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
00956             rtn = -1;
00957 
00958     if (ftdi_usb_close_internal (ftdi) != 0)
00959         rtn = -2;
00960 
00961     return rtn;
00962 }
00963 
00969 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
00970                                  unsigned short *value, unsigned short *index)
00971 {
00972     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
00973     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
00974     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
00975     int divisor, best_divisor, best_baud, best_baud_diff;
00976     unsigned long encoded_divisor;
00977     int i;
00978 
00979     if (baudrate <= 0)
00980     {
00981         // Return error
00982         return -1;
00983     }
00984 
00985     divisor = 24000000 / baudrate;
00986 
00987     if (ftdi->type == TYPE_AM)
00988     {
00989         // Round down to supported fraction (AM only)
00990         divisor -= am_adjust_dn[divisor & 7];
00991     }
00992 
00993     // Try this divisor and the one above it (because division rounds down)
00994     best_divisor = 0;
00995     best_baud = 0;
00996     best_baud_diff = 0;
00997     for (i = 0; i < 2; i++)
00998     {
00999         int try_divisor = divisor + i;
01000         int baud_estimate;
01001         int baud_diff;
01002 
01003         // Round up to supported divisor value
01004         if (try_divisor <= 8)
01005         {
01006             // Round up to minimum supported divisor
01007             try_divisor = 8;
01008         }
01009         else if (ftdi->type != TYPE_AM && try_divisor < 12)
01010         {
01011             // BM doesn't support divisors 9 through 11 inclusive
01012             try_divisor = 12;
01013         }
01014         else if (divisor < 16)
01015         {
01016             // AM doesn't support divisors 9 through 15 inclusive
01017             try_divisor = 16;
01018         }
01019         else
01020         {
01021             if (ftdi->type == TYPE_AM)
01022             {
01023                 // Round up to supported fraction (AM only)
01024                 try_divisor += am_adjust_up[try_divisor & 7];
01025                 if (try_divisor > 0x1FFF8)
01026                 {
01027                     // Round down to maximum supported divisor value (for AM)
01028                     try_divisor = 0x1FFF8;
01029                 }
01030             }
01031             else
01032             {
01033                 if (try_divisor > 0x1FFFF)
01034                 {
01035                     // Round down to maximum supported divisor value (for BM)
01036                     try_divisor = 0x1FFFF;
01037                 }
01038             }
01039         }
01040         // Get estimated baud rate (to nearest integer)
01041         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
01042         // Get absolute difference from requested baud rate
01043         if (baud_estimate < baudrate)
01044         {
01045             baud_diff = baudrate - baud_estimate;
01046         }
01047         else
01048         {
01049             baud_diff = baud_estimate - baudrate;
01050         }
01051         if (i == 0 || baud_diff < best_baud_diff)
01052         {
01053             // Closest to requested baud rate so far
01054             best_divisor = try_divisor;
01055             best_baud = baud_estimate;
01056             best_baud_diff = baud_diff;
01057             if (baud_diff == 0)
01058             {
01059                 // Spot on! No point trying
01060                 break;
01061             }
01062         }
01063     }
01064     // Encode the best divisor value
01065     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
01066     // Deal with special cases for encoded value
01067     if (encoded_divisor == 1)
01068     {
01069         encoded_divisor = 0;    // 3000000 baud
01070     }
01071     else if (encoded_divisor == 0x4001)
01072     {
01073         encoded_divisor = 1;    // 2000000 baud (BM only)
01074     }
01075     // Split into "value" and "index" values
01076     *value = (unsigned short)(encoded_divisor & 0xFFFF);
01077     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H
01078         || ftdi->type == TYPE_232H)
01079     {
01080         *index = (unsigned short)(encoded_divisor >> 8);
01081         *index &= 0xFF00;
01082         *index |= ftdi->index;
01083     }
01084     else
01085         *index = (unsigned short)(encoded_divisor >> 16);
01086 
01087     // Return the nearest baud rate
01088     return best_baud;
01089 }
01090 
01102 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
01103 {
01104     unsigned short value, index;
01105     int actual_baudrate;
01106 
01107     if (ftdi == NULL || ftdi->usb_dev == NULL)
01108         ftdi_error_return(-3, "USB device unavailable");
01109 
01110     if (ftdi->bitbang_enabled)
01111     {
01112         baudrate = baudrate*4;
01113     }
01114 
01115     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
01116     if (actual_baudrate <= 0)
01117         ftdi_error_return (-1, "Silly baudrate <= 0.");
01118 
01119     // Check within tolerance (about 5%)
01120     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
01121             || ((actual_baudrate < baudrate)
01122                 ? (actual_baudrate * 21 < baudrate * 20)
01123                 : (baudrate * 21 < actual_baudrate * 20)))
01124         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
01125 
01126     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01127                         SIO_SET_BAUDRATE_REQUEST, value,
01128                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
01129         ftdi_error_return (-2, "Setting new baudrate failed");
01130 
01131     ftdi->baudrate = baudrate;
01132     return 0;
01133 }
01134 
01148 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01149                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
01150 {
01151     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
01152 }
01153 
01167 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01168                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
01169                             enum ftdi_break_type break_type)
01170 {
01171     unsigned short value = bits;
01172 
01173     if (ftdi == NULL || ftdi->usb_dev == NULL)
01174         ftdi_error_return(-2, "USB device unavailable");
01175 
01176     switch (parity)
01177     {
01178         case NONE:
01179             value |= (0x00 << 8);
01180             break;
01181         case ODD:
01182             value |= (0x01 << 8);
01183             break;
01184         case EVEN:
01185             value |= (0x02 << 8);
01186             break;
01187         case MARK:
01188             value |= (0x03 << 8);
01189             break;
01190         case SPACE:
01191             value |= (0x04 << 8);
01192             break;
01193     }
01194 
01195     switch (sbit)
01196     {
01197         case STOP_BIT_1:
01198             value |= (0x00 << 11);
01199             break;
01200         case STOP_BIT_15:
01201             value |= (0x01 << 11);
01202             break;
01203         case STOP_BIT_2:
01204             value |= (0x02 << 11);
01205             break;
01206     }
01207 
01208     switch (break_type)
01209     {
01210         case BREAK_OFF:
01211             value |= (0x00 << 14);
01212             break;
01213         case BREAK_ON:
01214             value |= (0x01 << 14);
01215             break;
01216     }
01217 
01218     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01219                         SIO_SET_DATA_REQUEST, value,
01220                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01221         ftdi_error_return (-1, "Setting new line property failed");
01222 
01223     return 0;
01224 }
01225 
01237 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01238 {
01239     int ret;
01240     int offset = 0;
01241     int total_written = 0;
01242 
01243     if (ftdi == NULL || ftdi->usb_dev == NULL)
01244         ftdi_error_return(-666, "USB device unavailable");
01245 
01246     while (offset < size)
01247     {
01248         int write_size = ftdi->writebuffer_chunksize;
01249 
01250         if (offset+write_size > size)
01251             write_size = size-offset;
01252 
01253         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
01254         if (ret < 0)
01255             ftdi_error_return(ret, "usb bulk write failed");
01256 
01257         total_written += ret;
01258         offset += write_size;
01259     }
01260 
01261     return total_written;
01262 }
01263 
01264 #ifdef LIBFTDI_LINUX_ASYNC_MODE
01265 #if 0 /*def USB_CLASS_PTP*/
01266 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
01267 #endif
01268 /* this is strongly dependent on libusb using the same struct layout. If libusb
01269    changes in some later version this may break horribly (this is for libusb 0.1.12) */
01270 struct usb_dev_handle
01271 {
01272     int fd;
01273     // some other stuff coming here we don't need
01274 };
01275 
01280 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
01281 {
01282     struct usbdevfs_urb *urb;
01283     int pending=0;
01284     unsigned int i;
01285 
01286     for (i=0; i < ftdi->async_usb_buffer_size; i++)
01287     {
01288         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01289         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
01290             pending++;
01291     }
01292 
01293     return pending;
01294 }
01295 
01306 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
01307 {
01308     struct timeval tv;
01309     struct usbdevfs_urb *urb;
01310     int ret;
01311     fd_set writefds;
01312     int keep_going=0;
01313 
01314     FD_ZERO(&writefds);
01315     FD_SET(ftdi->usb_dev->fd, &writefds);
01316 
01317     /* init timeout only once, select writes time left after call */
01318     tv.tv_sec = timeout_msec / 1000;
01319     tv.tv_usec = (timeout_msec % 1000) * 1000;
01320 
01321     do
01322     {
01323         ret = -1;
01324         urb = NULL;
01325 
01326         while (_usb_get_async_urbs_pending(ftdi)
01327                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
01328                 && errno == EAGAIN)
01329         {
01330             if (keep_going && !wait_for_more)
01331             {
01332                 /* don't wait if repeating only for keep_going */
01333                 keep_going=0;
01334                 break;
01335             }
01336 
01337             /* wait for timeout msec or something written ready */
01338             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
01339         }
01340 
01341         if (ret == 0 && urb != NULL)
01342         {
01343             /* got a free urb, mark it */
01344             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
01345 
01346             /* try to get more urbs that are ready now, but don't wait anymore */
01347             keep_going=1;
01348         }
01349         else
01350         {
01351             /* no more urbs waiting */
01352             keep_going=0;
01353         }
01354     }
01355     while (keep_going);
01356 }
01357 
01365 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
01366 {
01367     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
01368 }
01369 
01375 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
01376 {
01377     struct usbdevfs_urb *urb;
01378     int bytesdone = 0, requested;
01379     int ret, cleanup_count;
01380     unsigned int i;
01381 
01382     do
01383     {
01384         /* find a free urb buffer we can use */
01385         i = 0;
01386         urb=NULL;
01387         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
01388         {
01389             if (i==ftdi->async_usb_buffer_size)
01390             {
01391                 /* wait until some buffers are free */
01392                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
01393             }
01394 
01395             for (i=0; i < ftdi->async_usb_buffer_size; i++)
01396             {
01397                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01398                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
01399                     break;  /* found a free urb position */
01400                 urb=NULL;
01401             }
01402         }
01403 
01404         /* no free urb position found */
01405         if (urb==NULL)
01406             return -1;
01407 
01408         requested = size - bytesdone;
01409         if (requested > 4096)
01410             requested = 4096;
01411 
01412         memset(urb,0,sizeof(urb));
01413 
01414         urb->type = USBDEVFS_URB_TYPE_BULK;
01415         urb->endpoint = ep;
01416         urb->flags = 0;
01417         urb->buffer = bytes + bytesdone;
01418         urb->buffer_length = requested;
01419         urb->signr = 0;
01420         urb->actual_length = 0;
01421         urb->number_of_packets = 0;
01422         urb->usercontext = 0;
01423 
01424         do
01425         {
01426             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
01427         }
01428         while (ret < 0 && errno == EINTR);
01429         if (ret < 0)
01430             return ret;       /* the caller can read errno to get more info */
01431 
01432         bytesdone += requested;
01433     }
01434     while (bytesdone < size);
01435     return bytesdone;
01436 }
01437 
01457 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
01458 {
01459     int ret;
01460     int offset = 0;
01461     int total_written = 0;
01462 
01463     if (ftdi == NULL || ftdi->usb_dev == NULL)
01464         ftdi_error_return(-666, "USB device unavailable");
01465 
01466     while (offset < size)
01467     {
01468         int write_size = ftdi->writebuffer_chunksize;
01469 
01470         if (offset+write_size > size)
01471             write_size = size-offset;
01472 
01473         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
01474         if (ret < 0)
01475             ftdi_error_return(ret, "usb bulk write async failed");
01476 
01477         total_written += ret;
01478         offset += write_size;
01479     }
01480 
01481     return total_written;
01482 }
01483 #endif // LIBFTDI_LINUX_ASYNC_MODE
01484 
01495 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01496 {
01497     if (ftdi == NULL)
01498         ftdi_error_return(-1, "ftdi context invalid");
01499 
01500     ftdi->writebuffer_chunksize = chunksize;
01501     return 0;
01502 }
01503 
01513 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01514 {
01515     if (ftdi == NULL)
01516         ftdi_error_return(-1, "ftdi context invalid");
01517 
01518     *chunksize = ftdi->writebuffer_chunksize;
01519     return 0;
01520 }
01521 
01538 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01539 {
01540     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
01541     int packet_size;
01542 
01543     if (ftdi == NULL || ftdi->usb_dev == NULL)
01544         ftdi_error_return(-666, "USB device unavailable");
01545 
01546     packet_size = ftdi->max_packet_size;
01547     // Packet size sanity check (avoid division by zero)
01548     if (packet_size == 0)
01549         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
01550 
01551     // everything we want is still in the readbuffer?
01552     if (size <= ftdi->readbuffer_remaining)
01553     {
01554         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
01555 
01556         // Fix offsets
01557         ftdi->readbuffer_remaining -= size;
01558         ftdi->readbuffer_offset += size;
01559 
01560         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
01561 
01562         return size;
01563     }
01564     // something still in the readbuffer, but not enough to satisfy 'size'?
01565     if (ftdi->readbuffer_remaining != 0)
01566     {
01567         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
01568 
01569         // Fix offset
01570         offset += ftdi->readbuffer_remaining;
01571     }
01572     // do the actual USB read
01573     while (offset < size && ret > 0)
01574     {
01575         ftdi->readbuffer_remaining = 0;
01576         ftdi->readbuffer_offset = 0;
01577         /* returns how much received */
01578         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
01579         if (ret < 0)
01580             ftdi_error_return(ret, "usb bulk read failed");
01581 
01582         if (ret > 2)
01583         {
01584             // skip FTDI status bytes.
01585             // Maybe stored in the future to enable modem use
01586             num_of_chunks = ret / packet_size;
01587             chunk_remains = ret % packet_size;
01588             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
01589 
01590             ftdi->readbuffer_offset += 2;
01591             ret -= 2;
01592 
01593             if (ret > packet_size - 2)
01594             {
01595                 for (i = 1; i < num_of_chunks; i++)
01596                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01597                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01598                              packet_size - 2);
01599                 if (chunk_remains > 2)
01600                 {
01601                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01602                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01603                              chunk_remains-2);
01604                     ret -= 2*num_of_chunks;
01605                 }
01606                 else
01607                     ret -= 2*(num_of_chunks-1)+chunk_remains;
01608             }
01609         }
01610         else if (ret <= 2)
01611         {
01612             // no more data to read?
01613             return offset;
01614         }
01615         if (ret > 0)
01616         {
01617             // data still fits in buf?
01618             if (offset+ret <= size)
01619             {
01620                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
01621                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
01622                 offset += ret;
01623 
01624                 /* Did we read exactly the right amount of bytes? */
01625                 if (offset == size)
01626                     //printf("read_data exact rem %d offset %d\n",
01627                     //ftdi->readbuffer_remaining, offset);
01628                     return offset;
01629             }
01630             else
01631             {
01632                 // only copy part of the data or size <= readbuffer_chunksize
01633                 int part_size = size-offset;
01634                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
01635 
01636                 ftdi->readbuffer_offset += part_size;
01637                 ftdi->readbuffer_remaining = ret-part_size;
01638                 offset += part_size;
01639 
01640                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
01641                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
01642 
01643                 return offset;
01644             }
01645         }
01646     }
01647     // never reached
01648     return -127;
01649 }
01650 
01663 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01664 {
01665     unsigned char *new_buf;
01666 
01667     if (ftdi == NULL)
01668         ftdi_error_return(-1, "ftdi context invalid");
01669 
01670     // Invalidate all remaining data
01671     ftdi->readbuffer_offset = 0;
01672     ftdi->readbuffer_remaining = 0;
01673 
01674     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
01675         ftdi_error_return(-1, "out of memory for readbuffer");
01676 
01677     ftdi->readbuffer = new_buf;
01678     ftdi->readbuffer_chunksize = chunksize;
01679 
01680     return 0;
01681 }
01682 
01692 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01693 {
01694     if (ftdi == NULL)
01695         ftdi_error_return(-1, "FTDI context invalid");
01696 
01697     *chunksize = ftdi->readbuffer_chunksize;
01698     return 0;
01699 }
01700 
01701 
01715 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
01716 {
01717     unsigned short usb_val;
01718 
01719     if (ftdi == NULL || ftdi->usb_dev == NULL)
01720         ftdi_error_return(-2, "USB device unavailable");
01721 
01722     usb_val = bitmask; // low byte: bitmask
01723     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
01724     usb_val |= (ftdi->bitbang_mode << 8);
01725 
01726     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01727                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
01728                         NULL, 0, ftdi->usb_write_timeout) != 0)
01729         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
01730 
01731     ftdi->bitbang_enabled = 1;
01732     return 0;
01733 }
01734 
01744 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
01745 {
01746     if (ftdi == NULL || ftdi->usb_dev == NULL)
01747         ftdi_error_return(-2, "USB device unavailable");
01748 
01749     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)
01750         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
01751 
01752     ftdi->bitbang_enabled = 0;
01753     return 0;
01754 }
01755 
01768 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
01769 {
01770     unsigned short usb_val;
01771 
01772     if (ftdi == NULL || ftdi->usb_dev == NULL)
01773         ftdi_error_return(-2, "USB device unavailable");
01774 
01775     usb_val = bitmask; // low byte: bitmask
01776     usb_val |= (mode << 8);
01777     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)
01778         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps selected mode not supported on your chip?");
01779 
01780     ftdi->bitbang_mode = mode;
01781     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
01782     return 0;
01783 }
01784 
01795 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
01796 {
01797     if (ftdi == NULL || ftdi->usb_dev == NULL)
01798         ftdi_error_return(-2, "USB device unavailable");
01799 
01800     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)
01801         ftdi_error_return(-1, "read pins failed");
01802 
01803     return 0;
01804 }
01805 
01821 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
01822 {
01823     unsigned short usb_val;
01824 
01825     if (latency < 1)
01826         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
01827 
01828     if (ftdi == NULL || ftdi->usb_dev == NULL)
01829         ftdi_error_return(-3, "USB device unavailable");
01830 
01831     usb_val = latency;
01832     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)
01833         ftdi_error_return(-2, "unable to set latency timer");
01834 
01835     return 0;
01836 }
01837 
01848 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
01849 {
01850     unsigned short usb_val;
01851 
01852     if (ftdi == NULL || ftdi->usb_dev == NULL)
01853         ftdi_error_return(-2, "USB device unavailable");
01854 
01855     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)
01856         ftdi_error_return(-1, "reading latency timer failed");
01857 
01858     *latency = (unsigned char)usb_val;
01859     return 0;
01860 }
01861 
01902 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
01903 {
01904     char usb_val[2];
01905 
01906     if (ftdi == NULL || ftdi->usb_dev == NULL)
01907         ftdi_error_return(-2, "USB device unavailable");
01908 
01909     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)
01910         ftdi_error_return(-1, "getting modem status failed");
01911 
01912     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
01913 
01914     return 0;
01915 }
01916 
01928 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
01929 {
01930     if (ftdi == NULL || ftdi->usb_dev == NULL)
01931         ftdi_error_return(-2, "USB device unavailable");
01932 
01933     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01934                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
01935                         NULL, 0, ftdi->usb_write_timeout) != 0)
01936         ftdi_error_return(-1, "set flow control failed");
01937 
01938     return 0;
01939 }
01940 
01951 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
01952 {
01953     unsigned short usb_val;
01954 
01955     if (ftdi == NULL || ftdi->usb_dev == NULL)
01956         ftdi_error_return(-2, "USB device unavailable");
01957 
01958     if (state)
01959         usb_val = SIO_SET_DTR_HIGH;
01960     else
01961         usb_val = SIO_SET_DTR_LOW;
01962 
01963     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01964                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01965                         NULL, 0, ftdi->usb_write_timeout) != 0)
01966         ftdi_error_return(-1, "set dtr failed");
01967 
01968     return 0;
01969 }
01970 
01981 int ftdi_setrts(struct ftdi_context *ftdi, int state)
01982 {
01983     unsigned short usb_val;
01984 
01985     if (ftdi == NULL || ftdi->usb_dev == NULL)
01986         ftdi_error_return(-2, "USB device unavailable");
01987 
01988     if (state)
01989         usb_val = SIO_SET_RTS_HIGH;
01990     else
01991         usb_val = SIO_SET_RTS_LOW;
01992 
01993     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01994                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01995                         NULL, 0, ftdi->usb_write_timeout) != 0)
01996         ftdi_error_return(-1, "set of rts failed");
01997 
01998     return 0;
01999 }
02000 
02012 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
02013 {
02014     unsigned short usb_val;
02015 
02016     if (ftdi == NULL || ftdi->usb_dev == NULL)
02017         ftdi_error_return(-2, "USB device unavailable");
02018 
02019     if (dtr)
02020         usb_val = SIO_SET_DTR_HIGH;
02021     else
02022         usb_val = SIO_SET_DTR_LOW;
02023 
02024     if (rts)
02025         usb_val |= SIO_SET_RTS_HIGH;
02026     else
02027         usb_val |= SIO_SET_RTS_LOW;
02028 
02029     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02030                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
02031                         NULL, 0, ftdi->usb_write_timeout) != 0)
02032         ftdi_error_return(-1, "set of rts/dtr failed");
02033 
02034     return 0;
02035 }
02036 
02048 int ftdi_set_event_char(struct ftdi_context *ftdi,
02049                         unsigned char eventch, unsigned char enable)
02050 {
02051     unsigned short usb_val;
02052 
02053     if (ftdi == NULL || ftdi->usb_dev == NULL)
02054         ftdi_error_return(-2, "USB device unavailable");
02055 
02056     usb_val = eventch;
02057     if (enable)
02058         usb_val |= 1 << 8;
02059 
02060     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)
02061         ftdi_error_return(-1, "setting event character failed");
02062 
02063     return 0;
02064 }
02065 
02077 int ftdi_set_error_char(struct ftdi_context *ftdi,
02078                         unsigned char errorch, unsigned char enable)
02079 {
02080     unsigned short usb_val;
02081 
02082     if (ftdi == NULL || ftdi->usb_dev == NULL)
02083         ftdi_error_return(-2, "USB device unavailable");
02084 
02085     usb_val = errorch;
02086     if (enable)
02087         usb_val |= 1 << 8;
02088 
02089     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)
02090         ftdi_error_return(-1, "setting error character failed");
02091 
02092     return 0;
02093 }
02094 
02103 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
02104 {
02105     if (ftdi == NULL)
02106         return;
02107 
02108     ftdi->eeprom_size=size;
02109     eeprom->size=size;
02110 }
02111 
02117 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
02118 {
02119     int i;
02120 
02121     if (eeprom == NULL)
02122         return;
02123 
02124     eeprom->vendor_id = 0x0403;
02125     eeprom->product_id = 0x6001;
02126 
02127     eeprom->self_powered = 1;
02128     eeprom->remote_wakeup = 1;
02129     eeprom->chip_type = TYPE_BM;
02130 
02131     eeprom->in_is_isochronous = 0;
02132     eeprom->out_is_isochronous = 0;
02133     eeprom->suspend_pull_downs = 0;
02134 
02135     eeprom->use_serial = 0;
02136     eeprom->change_usb_version = 0;
02137     eeprom->usb_version = 0x0200;
02138     eeprom->max_power = 0;
02139 
02140     eeprom->manufacturer = NULL;
02141     eeprom->product = NULL;
02142     eeprom->serial = NULL;
02143     for (i=0; i < 5; i++)
02144     {
02145         eeprom->cbus_function[i] = 0;
02146     }
02147     eeprom->high_current = 0;
02148     eeprom->invert = 0;
02149 
02150     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
02151 }
02152 
02158 void ftdi_eeprom_free(struct ftdi_eeprom *eeprom)
02159 {
02160     if (!eeprom)
02161         return;
02162 
02163     if (eeprom->manufacturer != 0) {
02164         free(eeprom->manufacturer);
02165         eeprom->manufacturer = 0;
02166     }
02167     if (eeprom->product != 0) {
02168         free(eeprom->product);
02169         eeprom->product = 0;
02170     }
02171     if (eeprom->serial != 0) {
02172         free(eeprom->serial);
02173         eeprom->serial = 0;
02174     }
02175 }
02176 
02192 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
02193 {
02194     unsigned char i, j;
02195     unsigned short checksum, value;
02196     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02197     int size_check;
02198     const int cbus_max[5] = {13, 13, 13, 13, 9};
02199 
02200     if (eeprom == NULL)
02201         return -2;
02202 
02203     if (eeprom->manufacturer != NULL)
02204         manufacturer_size = strlen(eeprom->manufacturer);
02205     if (eeprom->product != NULL)
02206         product_size = strlen(eeprom->product);
02207     if (eeprom->serial != NULL)
02208         serial_size = strlen(eeprom->serial);
02209 
02210     // highest allowed cbus value
02211     for (i = 0; i < 5; i++)
02212     {
02213         if ((eeprom->cbus_function[i] > cbus_max[i]) ||
02214             (eeprom->cbus_function[i] && eeprom->chip_type != TYPE_R)) return -3;
02215     }
02216     if (eeprom->chip_type != TYPE_R)
02217     {
02218         if (eeprom->invert) return -4;
02219         if (eeprom->high_current) return -5;
02220     }
02221 
02222     size_check = eeprom->size;
02223     size_check -= 28; // 28 are always in use (fixed)
02224 
02225     // Top half of a 256byte eeprom is used just for strings and checksum
02226     // it seems that the FTDI chip will not read these strings from the lower half
02227     // Each string starts with two bytes; offset and type (0x03 for string)
02228     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02229     if (eeprom->size>=256) size_check = 120;
02230     size_check -= manufacturer_size*2;
02231     size_check -= product_size*2;
02232     size_check -= serial_size*2;
02233 
02234     // eeprom size exceeded?
02235     if (size_check < 0)
02236         return (-1);
02237 
02238     // empty eeprom
02239     memset (output, 0, eeprom->size);
02240 
02241     // Addr 00: High current IO
02242     output[0x00] = eeprom->high_current ? HIGH_CURRENT_DRIVE : 0;
02243     // Addr 01: IN endpoint size (for R type devices, different for FT2232)
02244     if (eeprom->chip_type == TYPE_R) {
02245         output[0x01] = 0x40;
02246     }
02247     // Addr 02: Vendor ID
02248     output[0x02] = eeprom->vendor_id;
02249     output[0x03] = eeprom->vendor_id >> 8;
02250 
02251     // Addr 04: Product ID
02252     output[0x04] = eeprom->product_id;
02253     output[0x05] = eeprom->product_id >> 8;
02254 
02255     // Addr 06: Device release number (0400h for BM features)
02256     output[0x06] = 0x00;
02257     switch (eeprom->chip_type) {
02258         case TYPE_AM:
02259             output[0x07] = 0x02;
02260             break;
02261         case TYPE_BM:
02262             output[0x07] = 0x04;
02263             break;
02264         case TYPE_2232C:
02265             output[0x07] = 0x05;
02266             break;
02267         case TYPE_R:
02268             output[0x07] = 0x06;
02269             break;
02270         case TYPE_2232H:
02271             output[0x07] = 0x07;
02272             break;
02273          case TYPE_4232H:
02274             output[0x07] = 0x08;
02275             break;
02276         case TYPE_232H:
02277             output[0x07] = 0x09;
02278             break;
02279         default:
02280             output[0x07] = 0x00;
02281     }
02282 
02283     // Addr 08: Config descriptor
02284     // Bit 7: always 1
02285     // Bit 6: 1 if this device is self powered, 0 if bus powered
02286     // Bit 5: 1 if this device uses remote wakeup
02287     // Bit 4: 1 if this device is battery powered
02288     j = 0x80;
02289     if (eeprom->self_powered == 1)
02290         j |= 0x40;
02291     if (eeprom->remote_wakeup == 1)
02292         j |= 0x20;
02293     output[0x08] = j;
02294 
02295     // Addr 09: Max power consumption: max power = value * 2 mA
02296     output[0x09] = eeprom->max_power;
02297 
02298     // Addr 0A: Chip configuration
02299     // Bit 7: 0 - reserved
02300     // Bit 6: 0 - reserved
02301     // Bit 5: 0 - reserved
02302     // Bit 4: 1 - Change USB version
02303     // Bit 3: 1 - Use the serial number string
02304     // Bit 2: 1 - Enable suspend pull downs for lower power
02305     // Bit 1: 1 - Out EndPoint is Isochronous
02306     // Bit 0: 1 - In EndPoint is Isochronous
02307     //
02308     j = 0;
02309     if (eeprom->in_is_isochronous == 1)
02310         j = j | 1;
02311     if (eeprom->out_is_isochronous == 1)
02312         j = j | 2;
02313     if (eeprom->suspend_pull_downs == 1)
02314         j = j | 4;
02315     if (eeprom->use_serial == 1)
02316         j = j | 8;
02317     if (eeprom->change_usb_version == 1)
02318         j = j | 16;
02319     output[0x0A] = j;
02320 
02321     // Addr 0B: Invert data lines
02322     output[0x0B] = eeprom->invert & 0xff;
02323 
02324     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02325     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02326     if (eeprom->change_usb_version == 1)
02327     {
02328         output[0x0C] = eeprom->usb_version;
02329         output[0x0D] = eeprom->usb_version >> 8;
02330     }
02331 
02332 
02333     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02334     // Addr 0F: Length of manufacturer string
02335     output[0x0F] = manufacturer_size*2 + 2;
02336 
02337     // Addr 10: Offset of the product string + 0x80, calculated later
02338     // Addr 11: Length of product string
02339     output[0x11] = product_size*2 + 2;
02340 
02341     // Addr 12: Offset of the serial string + 0x80, calculated later
02342     // Addr 13: Length of serial string
02343     output[0x13] = serial_size*2 + 2;
02344 
02345     // Addr 14: CBUS function: CBUS0, CBUS1
02346     // Addr 15: CBUS function: CBUS2, CBUS3
02347     // Addr 16: CBUS function: CBUS5
02348     output[0x14] = eeprom->cbus_function[0] | (eeprom->cbus_function[1] << 4);
02349     output[0x15] = eeprom->cbus_function[2] | (eeprom->cbus_function[3] << 4);
02350     output[0x16] = eeprom->cbus_function[4];
02351     // Addr 17: Unknown
02352 
02353     // Dynamic content
02354     // In images produced by FTDI's FT_Prog for FT232R strings start at 0x18
02355     // Space till 0x18 should be considered as reserved.
02356     if (eeprom->chip_type >= TYPE_R) {
02357         i = 0x18;
02358     } else {
02359         i = 0x14;
02360     }
02361     if (eeprom->size >= 256) i = 0x80;
02362 
02363 
02364     // Output manufacturer
02365     output[0x0E] = i | 0x80;  // calculate offset
02366     output[i++] = manufacturer_size*2 + 2;
02367     output[i++] = 0x03; // type: string
02368     for (j = 0; j < manufacturer_size; j++)
02369     {
02370         output[i] = eeprom->manufacturer[j], i++;
02371         output[i] = 0x00, i++;
02372     }
02373 
02374     // Output product name
02375     output[0x10] = i | 0x80;  // calculate offset
02376     output[i] = product_size*2 + 2, i++;
02377     output[i] = 0x03, i++;
02378     for (j = 0; j < product_size; j++)
02379     {
02380         output[i] = eeprom->product[j], i++;
02381         output[i] = 0x00, i++;
02382     }
02383 
02384     // Output serial
02385     output[0x12] = i | 0x80; // calculate offset
02386     output[i] = serial_size*2 + 2, i++;
02387     output[i] = 0x03, i++;
02388     for (j = 0; j < serial_size; j++)
02389     {
02390         output[i] = eeprom->serial[j], i++;
02391         output[i] = 0x00, i++;
02392     }
02393 
02394     // calculate checksum
02395     checksum = 0xAAAA;
02396 
02397     for (i = 0; i < eeprom->size/2-1; i++)
02398     {
02399         value = output[i*2];
02400         value += output[(i*2)+1] << 8;
02401 
02402         checksum = value^checksum;
02403         checksum = (checksum << 1) | (checksum >> 15);
02404     }
02405 
02406     output[eeprom->size-2] = checksum;
02407     output[eeprom->size-1] = checksum >> 8;
02408 
02409     return size_check;
02410 }
02411 
02425 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
02426 {
02427     unsigned char i, j;
02428     unsigned short checksum, eeprom_checksum, value;
02429     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02430     int size_check;
02431     int eeprom_size = 128;
02432 
02433     if (eeprom == NULL)
02434         return -1;
02435 #if 0
02436     size_check = eeprom->size;
02437     size_check -= 28; // 28 are always in use (fixed)
02438 
02439     // Top half of a 256byte eeprom is used just for strings and checksum
02440     // it seems that the FTDI chip will not read these strings from the lower half
02441     // Each string starts with two bytes; offset and type (0x03 for string)
02442     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02443     if (eeprom->size>=256)size_check = 120;
02444     size_check -= manufacturer_size*2;
02445     size_check -= product_size*2;
02446     size_check -= serial_size*2;
02447 
02448     // eeprom size exceeded?
02449     if (size_check < 0)
02450         return (-1);
02451 #endif
02452 
02453     // empty eeprom struct
02454     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
02455 
02456     // Addr 00: High current IO
02457     eeprom->high_current = (buf[0x02] & HIGH_CURRENT_DRIVE);
02458 
02459     // Addr 02: Vendor ID
02460     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
02461 
02462     // Addr 04: Product ID
02463     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
02464 
02465     value = buf[0x06] + (buf[0x07]<<8);
02466     switch (value)
02467     {
02468         case 0x0900:
02469             eeprom->chip_type = TYPE_232H;
02470             break;
02471         case 0x0800:
02472             eeprom->chip_type = TYPE_4232H;
02473             break;
02474         case 0x0700:
02475             eeprom->chip_type = TYPE_2232H;
02476             break;
02477         case 0x0600:
02478             eeprom->chip_type = TYPE_R;
02479             break;
02480         case 0x0400:
02481             eeprom->chip_type = TYPE_BM;
02482             break;
02483         case 0x0200:
02484             eeprom->chip_type = TYPE_AM;
02485             break;
02486         default: // Unknown device
02487             eeprom->chip_type = 0;
02488             break;
02489     }
02490 
02491     // Addr 08: Config descriptor
02492     // Bit 7: always 1
02493     // Bit 6: 1 if this device is self powered, 0 if bus powered
02494     // Bit 5: 1 if this device uses remote wakeup
02495     // Bit 4: 1 if this device is battery powered
02496     j = buf[0x08];
02497     if (j&0x40) eeprom->self_powered = 1;
02498     if (j&0x20) eeprom->remote_wakeup = 1;
02499 
02500     // Addr 09: Max power consumption: max power = value * 2 mA
02501     eeprom->max_power = buf[0x09];
02502 
02503     // Addr 0A: Chip configuration
02504     // Bit 7: 0 - reserved
02505     // Bit 6: 0 - reserved
02506     // Bit 5: 0 - reserved
02507     // Bit 4: 1 - Change USB version
02508     // Bit 3: 1 - Use the serial number string
02509     // Bit 2: 1 - Enable suspend pull downs for lower power
02510     // Bit 1: 1 - Out EndPoint is Isochronous
02511     // Bit 0: 1 - In EndPoint is Isochronous
02512     //
02513     j = buf[0x0A];
02514     if (j&0x01) eeprom->in_is_isochronous = 1;
02515     if (j&0x02) eeprom->out_is_isochronous = 1;
02516     if (j&0x04) eeprom->suspend_pull_downs = 1;
02517     if (j&0x08) eeprom->use_serial = 1;
02518     if (j&0x10) eeprom->change_usb_version = 1;
02519 
02520     // Addr 0B: Invert data lines
02521     eeprom->invert = buf[0x0B];
02522 
02523     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02524     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02525     if (eeprom->change_usb_version == 1)
02526     {
02527         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
02528     }
02529 
02530     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02531     // Addr 0F: Length of manufacturer string
02532     manufacturer_size = buf[0x0F]/2;
02533     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
02534     else eeprom->manufacturer = NULL;
02535 
02536     // Addr 10: Offset of the product string + 0x80, calculated later
02537     // Addr 11: Length of product string
02538     product_size = buf[0x11]/2;
02539     if (product_size > 0) eeprom->product = malloc(product_size);
02540     else eeprom->product = NULL;
02541 
02542     // Addr 12: Offset of the serial string + 0x80, calculated later
02543     // Addr 13: Length of serial string
02544     serial_size = buf[0x13]/2;
02545     if (serial_size > 0) eeprom->serial = malloc(serial_size);
02546     else eeprom->serial = NULL;
02547 
02548     // Addr 14: CBUS function: CBUS0, CBUS1
02549     // Addr 15: CBUS function: CBUS2, CBUS3
02550     // Addr 16: CBUS function: CBUS5
02551     if (eeprom->chip_type == TYPE_R) {
02552         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
02553         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
02554         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
02555         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
02556         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
02557     } else {
02558         for (j=0; j<5; j++) eeprom->cbus_function[j] = 0;
02559     }
02560 
02561     // Decode manufacturer
02562     i = buf[0x0E] & 0x7f; // offset
02563     for (j=0;j<manufacturer_size-1;j++)
02564     {
02565         eeprom->manufacturer[j] = buf[2*j+i+2];
02566     }
02567     eeprom->manufacturer[j] = '\0';
02568 
02569     // Decode product name
02570     i = buf[0x10] & 0x7f; // offset
02571     for (j=0;j<product_size-1;j++)
02572     {
02573         eeprom->product[j] = buf[2*j+i+2];
02574     }
02575     eeprom->product[j] = '\0';
02576 
02577     // Decode serial
02578     i = buf[0x12] & 0x7f; // offset
02579     for (j=0;j<serial_size-1;j++)
02580     {
02581         eeprom->serial[j] = buf[2*j+i+2];
02582     }
02583     eeprom->serial[j] = '\0';
02584 
02585     // verify checksum
02586     checksum = 0xAAAA;
02587 
02588     for (i = 0; i < eeprom_size/2-1; i++)
02589     {
02590         value = buf[i*2];
02591         value += buf[(i*2)+1] << 8;
02592 
02593         checksum = value^checksum;
02594         checksum = (checksum << 1) | (checksum >> 15);
02595     }
02596 
02597     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
02598 
02599     if (eeprom_checksum != checksum)
02600     {
02601         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
02602         return -1;
02603     }
02604 
02605     return 0;
02606 }
02607 
02619 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
02620 {
02621     if (ftdi == NULL || ftdi->usb_dev == NULL)
02622         ftdi_error_return(-2, "USB device unavailable");
02623 
02624     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)
02625         ftdi_error_return(-1, "reading eeprom failed");
02626 
02627     return 0;
02628 }
02629 
02640 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02641 {
02642     int i;
02643 
02644     if (ftdi == NULL || ftdi->usb_dev == NULL)
02645         ftdi_error_return(-2, "USB device unavailable");
02646 
02647     for (i = 0; i < ftdi->eeprom_size/2; i++)
02648     {
02649         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)
02650             ftdi_error_return(-1, "reading eeprom failed");
02651     }
02652 
02653     return 0;
02654 }
02655 
02656 /*
02657     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
02658     Function is only used internally
02659     \internal
02660 */
02661 static unsigned char ftdi_read_chipid_shift(unsigned char value)
02662 {
02663     return ((value & 1) << 1) |
02664            ((value & 2) << 5) |
02665            ((value & 4) >> 2) |
02666            ((value & 8) << 4) |
02667            ((value & 16) >> 1) |
02668            ((value & 32) >> 1) |
02669            ((value & 64) >> 4) |
02670            ((value & 128) >> 2);
02671 }
02672 
02683 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
02684 {
02685     unsigned int a = 0, b = 0;
02686 
02687     if (ftdi == NULL || ftdi->usb_dev == NULL)
02688         ftdi_error_return(-2, "USB device unavailable");
02689 
02690     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)
02691     {
02692         a = a << 8 | a >> 8;
02693         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)
02694         {
02695             b = b << 8 | b >> 8;
02696             a = (a << 16) | (b & 0xFFFF);
02697             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
02698                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
02699             *chipid = a ^ 0xa5f0f7d1;
02700             return 0;
02701         }
02702     }
02703 
02704     ftdi_error_return(-1, "read of FTDIChip-ID failed");
02705 }
02706 
02719 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
02720 {
02721     int i=0,j,minsize=32;
02722     int size=minsize;
02723 
02724     if (ftdi == NULL || ftdi->usb_dev == NULL)
02725         ftdi_error_return(-2, "USB device unavailable");
02726 
02727     do
02728     {
02729         for (j = 0; i < maxsize/2 && j<size; j++)
02730         {
02731             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
02732                                 SIO_READ_EEPROM_REQUEST, 0, i,
02733                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02734                 ftdi_error_return(-1, "eeprom read failed");
02735             i++;
02736         }
02737         size*=2;
02738     }
02739     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
02740 
02741     return size/2;
02742 }
02743 
02755 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
02756 {
02757     if (ftdi == NULL || ftdi->usb_dev == NULL)
02758         ftdi_error_return(-2, "USB device unavailable");
02759 
02760     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02761                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
02762                                     NULL, 0, ftdi->usb_write_timeout) != 0)
02763         ftdi_error_return(-1, "unable to write eeprom");
02764 
02765     return 0;
02766 }
02767 
02778 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02779 {
02780     unsigned short usb_val, status;
02781     int i, ret;
02782 
02783     if (ftdi == NULL || ftdi->usb_dev == NULL)
02784         ftdi_error_return(-2, "USB device unavailable");
02785 
02786     /* These commands were traced while running MProg */
02787     if ((ret = ftdi_usb_reset(ftdi)) != 0)
02788         return ret;
02789     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
02790         return ret;
02791     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
02792         return ret;
02793 
02794     for (i = 0; i < ftdi->eeprom_size/2; i++)
02795     {
02796         usb_val = eeprom[i*2];
02797         usb_val += eeprom[(i*2)+1] << 8;
02798         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02799                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
02800                             NULL, 0, ftdi->usb_write_timeout) != 0)
02801             ftdi_error_return(-1, "unable to write eeprom");
02802     }
02803 
02804     return 0;
02805 }
02806 
02818 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
02819 {
02820     if (ftdi == NULL || ftdi->usb_dev == NULL)
02821         ftdi_error_return(-2, "USB device unavailable");
02822 
02823     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
02824         ftdi_error_return(-1, "unable to erase eeprom");
02825 
02826     return 0;
02827 }
02828 
02836 char *ftdi_get_error_string (struct ftdi_context *ftdi)
02837 {
02838     if (ftdi == NULL)
02839         return "";
02840 
02841     return ftdi->error_str;
02842 }
02843 
02844 /* @} end of doxygen libftdi group */