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-2008 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/time.h>
00042 #include <sys/select.h>
00043 #include <sys/types.h>
00044 #include <unistd.h>
00045 #include <linux/usbdevice_fs.h>
00046 #endif
00047 
00048 #define ftdi_error_return(code, str) do {  \
00049         ftdi->error_str = str;             \
00050         return code;                       \
00051    } while(0);
00052 
00053 
00063 static int ftdi_usb_close_internal (struct ftdi_context *ftdi)
00064 {
00065     int ret = 0;
00066 
00067     if (ftdi->usb_dev)
00068     {
00069        ret = usb_close (ftdi->usb_dev);
00070        ftdi->usb_dev = NULL;
00071     }
00072 
00073     return ret;
00074 }
00075 
00086 int ftdi_init(struct ftdi_context *ftdi)
00087 {
00088     unsigned int i;
00089 
00090     ftdi->usb_dev = NULL;
00091     ftdi->usb_read_timeout = 5000;
00092     ftdi->usb_write_timeout = 5000;
00093 
00094     ftdi->type = TYPE_BM;    /* chip type */
00095     ftdi->baudrate = -1;
00096     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
00097 
00098     ftdi->readbuffer = NULL;
00099     ftdi->readbuffer_offset = 0;
00100     ftdi->readbuffer_remaining = 0;
00101     ftdi->writebuffer_chunksize = 4096;
00102     ftdi->max_packet_size = 0;
00103 
00104     ftdi->interface = 0;
00105     ftdi->index = 0;
00106     ftdi->in_ep = 0x02;
00107     ftdi->out_ep = 0x81;
00108     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
00109 
00110     ftdi->error_str = NULL;
00111 
00112 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00113     ftdi->async_usb_buffer_size=10;
00114     if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
00115         ftdi_error_return(-1, "out of memory for async usb buffer");
00116 
00117     /* initialize async usb buffer with unused-marker */
00118     for (i=0; i < ftdi->async_usb_buffer_size; i++)
00119         ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
00120 #else
00121     ftdi->async_usb_buffer_size=0;
00122     ftdi->async_usb_buffer = NULL;
00123 #endif
00124 
00125     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
00126 
00127     /* All fine. Now allocate the readbuffer */
00128     return ftdi_read_data_set_chunksize(ftdi, 4096);
00129 }
00130 
00136 struct ftdi_context *ftdi_new(void)
00137 {
00138     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
00139 
00140     if (ftdi == NULL)
00141     {
00142         return NULL;
00143     }
00144 
00145     if (ftdi_init(ftdi) != 0)
00146     {
00147         free(ftdi);
00148         return NULL;
00149     }
00150 
00151     return ftdi;
00152 }
00153 
00163 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
00164 {
00165     switch (interface)
00166     {
00167         case INTERFACE_ANY:
00168         case INTERFACE_A:
00169             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
00170             break;
00171         case INTERFACE_B:
00172             ftdi->interface = 1;
00173             ftdi->index     = INTERFACE_B;
00174             ftdi->in_ep     = 0x04;
00175             ftdi->out_ep    = 0x83;
00176             break;
00177         case INTERFACE_C:
00178             ftdi->interface = 2;
00179             ftdi->index     = INTERFACE_C;
00180             ftdi->in_ep     = 0x06;
00181             ftdi->out_ep    = 0x85;
00182             break;
00183         case INTERFACE_D:
00184             ftdi->interface = 3;
00185             ftdi->index     = INTERFACE_D;
00186             ftdi->in_ep     = 0x08;
00187             ftdi->out_ep    = 0x87;
00188             break;
00189         default:
00190             ftdi_error_return(-1, "Unknown interface");
00191     }
00192     return 0;
00193 }
00194 
00200 void ftdi_deinit(struct ftdi_context *ftdi)
00201 {
00202     ftdi_usb_close_internal (ftdi);
00203 
00204     if (ftdi->async_usb_buffer != NULL)
00205     {
00206         free(ftdi->async_usb_buffer);
00207         ftdi->async_usb_buffer = NULL;
00208     }
00209 
00210     if (ftdi->readbuffer != NULL)
00211     {
00212         free(ftdi->readbuffer);
00213         ftdi->readbuffer = NULL;
00214     }
00215 }
00216 
00222 void ftdi_free(struct ftdi_context *ftdi)
00223 {
00224     ftdi_deinit(ftdi);
00225     free(ftdi);
00226 }
00227 
00234 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
00235 {
00236     ftdi->usb_dev = usb;
00237 }
00238 
00239 
00254 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
00255 {
00256     struct ftdi_device_list **curdev;
00257     struct usb_bus *bus;
00258     struct usb_device *dev;
00259     int count = 0;
00260 
00261     usb_init();
00262     if (usb_find_busses() < 0)
00263         ftdi_error_return(-1, "usb_find_busses() failed");
00264     if (usb_find_devices() < 0)
00265         ftdi_error_return(-2, "usb_find_devices() failed");
00266 
00267     curdev = devlist;
00268     *curdev = NULL;
00269     for (bus = usb_get_busses(); bus; bus = bus->next)
00270     {
00271         for (dev = bus->devices; dev; dev = dev->next)
00272         {
00273             if (dev->descriptor.idVendor == vendor
00274                     && dev->descriptor.idProduct == product)
00275             {
00276                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
00277                 if (!*curdev)
00278                     ftdi_error_return(-3, "out of memory");
00279 
00280                 (*curdev)->next = NULL;
00281                 (*curdev)->dev = dev;
00282 
00283                 curdev = &(*curdev)->next;
00284                 count++;
00285             }
00286         }
00287     }
00288 
00289     return count;
00290 }
00291 
00297 void ftdi_list_free(struct ftdi_device_list **devlist)
00298 {
00299     struct ftdi_device_list *curdev, *next;
00300 
00301     for (curdev = *devlist; curdev != NULL;)
00302     {
00303         next = curdev->next;
00304         free(curdev);
00305         curdev = next;
00306     }
00307 
00308     *devlist = NULL;
00309 }
00310 
00316 void ftdi_list_free2(struct ftdi_device_list *devlist)
00317 {
00318     ftdi_list_free(&devlist);
00319 }
00320 
00347 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
00348                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
00349 {
00350     if ((ftdi==NULL) || (dev==NULL))
00351         return -1;
00352 
00353     if (!(ftdi->usb_dev = usb_open(dev)))
00354         ftdi_error_return(-4, usb_strerror());
00355 
00356     if (manufacturer != NULL)
00357     {
00358         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
00359         {
00360             ftdi_usb_close_internal (ftdi);
00361             ftdi_error_return(-7, usb_strerror());
00362         }
00363     }
00364 
00365     if (description != NULL)
00366     {
00367         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
00368         {
00369             ftdi_usb_close_internal (ftdi);
00370             ftdi_error_return(-8, usb_strerror());
00371         }
00372     }
00373 
00374     if (serial != NULL)
00375     {
00376         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
00377         {
00378             ftdi_usb_close_internal (ftdi);
00379             ftdi_error_return(-9, usb_strerror());
00380         }
00381     }
00382 
00383     if (ftdi_usb_close_internal (ftdi) != 0)
00384         ftdi_error_return(-10, usb_strerror());
00385 
00386     return 0;
00387 }
00388 
00395 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, struct usb_device *dev)
00396 {
00397     unsigned int packet_size;
00398 
00399     // Determine maximum packet size. Init with default value.
00400     // New hi-speed devices from FTDI use a packet size of 512 bytes
00401     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
00402     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
00403         packet_size = 512;
00404     else
00405         packet_size = 64;
00406 
00407     if (dev->descriptor.bNumConfigurations > 0 && dev->config)
00408     {
00409         struct usb_config_descriptor config = dev->config[0];
00410 
00411         if (ftdi->interface < config.bNumInterfaces)
00412         {
00413             struct usb_interface interface = config.interface[ftdi->interface];
00414             if (interface.num_altsetting > 0)
00415             {
00416                 struct usb_interface_descriptor descriptor = interface.altsetting[0];
00417                 if (descriptor.bNumEndpoints > 0)
00418                 {
00419                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
00420                 }
00421             }
00422         }
00423     }
00424 
00425     return packet_size;
00426 }
00427 
00441 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
00442 {
00443     int detach_errno = 0;
00444     int config_val = 1;
00445     if (!(ftdi->usb_dev = usb_open(dev)))
00446         ftdi_error_return(-4, "usb_open() failed");
00447 
00448 #ifdef LIBUSB_HAS_GET_DRIVER_NP
00449     // Try to detach ftdi_sio kernel module.
00450     // Returns ENODATA if driver is not loaded.
00451     //
00452     // The return code is kept in a separate variable and only parsed
00453     // if usb_set_configuration() or usb_claim_interface() fails as the
00454     // detach operation might be denied and everything still works fine.
00455     // Likely scenario is a static ftdi_sio kernel module.
00456     if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
00457         detach_errno = errno;
00458 #endif
00459 
00460 #ifdef __WIN32__
00461     // set configuration (needed especially for windows)
00462     // tolerate EBUSY: one device with one configuration, but two interfaces
00463     //    and libftdi sessions to both interfaces (e.g. FT2232)
00464 
00465     if (dev->descriptor.bNumConfigurations > 0)
00466     {
00467         // libusb-win32 on Windows 64 can return a null pointer for a valid device
00468         if (dev->config)
00469             config_val = dev->config[0].bConfigurationValue;
00470 
00471         if (usb_set_configuration(ftdi->usb_dev, config_val) &&
00472             errno != EBUSY)
00473         {
00474             ftdi_usb_close_internal (ftdi);
00475             if (detach_errno == EPERM)
00476             {
00477                 ftdi_error_return(-8, "inappropriate permissions on device!");
00478             }
00479             else
00480             {
00481                 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
00482             }
00483         }
00484     }
00485 #endif
00486 
00487     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
00488     {
00489         ftdi_usb_close_internal (ftdi);
00490         if (detach_errno == EPERM)
00491         {
00492             ftdi_error_return(-8, "inappropriate permissions on device!");
00493         }
00494         else
00495         {
00496             ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
00497         }
00498     }
00499 
00500     if (ftdi_usb_reset (ftdi) != 0)
00501     {
00502         ftdi_usb_close_internal (ftdi);
00503         ftdi_error_return(-6, "ftdi_usb_reset failed");
00504     }
00505 
00506     // Try to guess chip type
00507     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
00508     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
00509             && dev->descriptor.iSerialNumber == 0))
00510         ftdi->type = TYPE_BM;
00511     else if (dev->descriptor.bcdDevice == 0x200)
00512         ftdi->type = TYPE_AM;
00513     else if (dev->descriptor.bcdDevice == 0x500)
00514         ftdi->type = TYPE_2232C;
00515     else if (dev->descriptor.bcdDevice == 0x600)
00516         ftdi->type = TYPE_R;
00517     else if (dev->descriptor.bcdDevice == 0x700)
00518         ftdi->type = TYPE_2232H;
00519     else if (dev->descriptor.bcdDevice == 0x800)
00520         ftdi->type = TYPE_4232H;
00521 
00522     // Set default interface on dual/quad type chips
00523     switch(ftdi->type)
00524     {
00525         case TYPE_2232C:
00526         case TYPE_2232H:
00527         case TYPE_4232H:
00528             if (!ftdi->index)
00529                 ftdi->index = INTERFACE_A;
00530             break;
00531         default:
00532             break;
00533     }
00534 
00535     // Determine maximum packet size
00536     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
00537 
00538     if (ftdi_set_baudrate (ftdi, 9600) != 0)
00539     {
00540         ftdi_usb_close_internal (ftdi);
00541         ftdi_error_return(-7, "set baudrate failed");
00542     }
00543 
00544     ftdi_error_return(0, "all fine");
00545 }
00546 
00556 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
00557 {
00558     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
00559 }
00560 
00583 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
00584                        const char* description, const char* serial)
00585 {
00586     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
00587 }
00588 
00612 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
00613                        const char* description, const char* serial, unsigned int index)
00614 {
00615     struct usb_bus *bus;
00616     struct usb_device *dev;
00617     char string[256];
00618 
00619     usb_init();
00620 
00621     if (usb_find_busses() < 0)
00622         ftdi_error_return(-1, "usb_find_busses() failed");
00623     if (usb_find_devices() < 0)
00624         ftdi_error_return(-2, "usb_find_devices() failed");
00625 
00626     for (bus = usb_get_busses(); bus; bus = bus->next)
00627     {
00628         for (dev = bus->devices; dev; dev = dev->next)
00629         {
00630             if (dev->descriptor.idVendor == vendor
00631                     && dev->descriptor.idProduct == product)
00632             {
00633                 if (!(ftdi->usb_dev = usb_open(dev)))
00634                     ftdi_error_return(-4, "usb_open() failed");
00635 
00636                 if (description != NULL)
00637                 {
00638                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
00639                     {
00640                         ftdi_usb_close_internal (ftdi);
00641                         ftdi_error_return(-8, "unable to fetch product description");
00642                     }
00643                     if (strncmp(string, description, sizeof(string)) != 0)
00644                     {
00645                         if (ftdi_usb_close_internal (ftdi) != 0)
00646                             ftdi_error_return(-10, "unable to close device");
00647                         continue;
00648                     }
00649                 }
00650                 if (serial != NULL)
00651                 {
00652                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
00653                     {
00654                         ftdi_usb_close_internal (ftdi);
00655                         ftdi_error_return(-9, "unable to fetch serial number");
00656                     }
00657                     if (strncmp(string, serial, sizeof(string)) != 0)
00658                     {
00659                         if (ftdi_usb_close_internal (ftdi) != 0)
00660                             ftdi_error_return(-10, "unable to close device");
00661                         continue;
00662                     }
00663                 }
00664 
00665                 if (ftdi_usb_close_internal (ftdi) != 0)
00666                     ftdi_error_return(-10, "unable to close device");
00667 
00668                 if (index > 0)
00669                 {
00670                     index--;
00671                     continue;
00672                 }
00673 
00674                 return ftdi_usb_open_dev(ftdi, dev);
00675             }
00676         }
00677     }
00678 
00679     // device not found
00680     ftdi_error_return(-3, "device not found");
00681 }
00682 
00709 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
00710 {
00711     if (description[0] == 0 || description[1] != ':')
00712         ftdi_error_return(-11, "illegal description format");
00713 
00714     if (description[0] == 'd')
00715     {
00716         struct usb_bus *bus;
00717         struct usb_device *dev;
00718         char dev_name[PATH_MAX+1];
00719 
00720         usb_init();
00721 
00722         if (usb_find_busses() < 0)
00723             ftdi_error_return(-1, "usb_find_busses() failed");
00724         if (usb_find_devices() < 0)
00725             ftdi_error_return(-2, "usb_find_devices() failed");
00726 
00727         for (bus = usb_get_busses(); bus; bus = bus->next)
00728         {
00729             for (dev = bus->devices; dev; dev = dev->next)
00730             {
00731                 snprintf(dev_name, sizeof(dev_name), "%s/%s",bus->dirname,dev->filename);
00732                 if (strcmp(description+2,dev_name) == 0)
00733                     return ftdi_usb_open_dev(ftdi, dev);
00734             }
00735         }
00736 
00737         // device not found
00738         ftdi_error_return(-3, "device not found");
00739     }
00740     else if (description[0] == 'i' || description[0] == 's')
00741     {
00742         unsigned int vendor;
00743         unsigned int product;
00744         unsigned int index=0;
00745         const char *serial=NULL;
00746         const char *startp, *endp;
00747 
00748         errno=0;
00749         startp=description+2;
00750         vendor=strtoul((char*)startp,(char**)&endp,0);
00751         if (*endp != ':' || endp == startp || errno != 0)
00752             ftdi_error_return(-11, "illegal description format");
00753 
00754         startp=endp+1;
00755         product=strtoul((char*)startp,(char**)&endp,0);
00756         if (endp == startp || errno != 0)
00757             ftdi_error_return(-11, "illegal description format");
00758 
00759         if (description[0] == 'i' && *endp != 0)
00760         {
00761             /* optional index field in i-mode */
00762             if (*endp != ':')
00763                 ftdi_error_return(-11, "illegal description format");
00764 
00765             startp=endp+1;
00766             index=strtoul((char*)startp,(char**)&endp,0);
00767             if (*endp != 0 || endp == startp || errno != 0)
00768                 ftdi_error_return(-11, "illegal description format");
00769         }
00770         if (description[0] == 's')
00771         {
00772             if (*endp != ':')
00773                 ftdi_error_return(-11, "illegal description format");
00774 
00775             /* rest of the description is the serial */
00776             serial=endp+1;
00777         }
00778 
00779         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
00780     }
00781     else
00782     {
00783         ftdi_error_return(-11, "illegal description format");
00784     }
00785 }
00786 
00795 int ftdi_usb_reset(struct ftdi_context *ftdi)
00796 {
00797     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00798                         SIO_RESET_REQUEST, SIO_RESET_SIO,
00799                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00800         ftdi_error_return(-1,"FTDI reset failed");
00801 
00802     // Invalidate data in the readbuffer
00803     ftdi->readbuffer_offset = 0;
00804     ftdi->readbuffer_remaining = 0;
00805 
00806     return 0;
00807 }
00808 
00817 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
00818 {
00819     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00820                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
00821                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00822         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
00823 
00824     // Invalidate data in the readbuffer
00825     ftdi->readbuffer_offset = 0;
00826     ftdi->readbuffer_remaining = 0;
00827 
00828     return 0;
00829 }
00830 
00839 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
00840 {
00841     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00842                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
00843                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00844         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
00845 
00846     return 0;
00847 }
00848 
00858 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
00859 {
00860     int result;
00861 
00862     result = ftdi_usb_purge_rx_buffer(ftdi);
00863     if (result < 0)
00864         return -1;
00865 
00866     result = ftdi_usb_purge_tx_buffer(ftdi);
00867     if (result < 0)
00868         return -2;
00869 
00870     return 0;
00871 }
00872 
00873 
00874 
00884 int ftdi_usb_close(struct ftdi_context *ftdi)
00885 {
00886     int rtn = 0;
00887 
00888 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00889     /* try to release some kernel resources */
00890     ftdi_async_complete(ftdi,1);
00891 #endif
00892 
00893     if (ftdi->usb_dev != NULL)
00894         if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
00895             rtn = -1;
00896 
00897     if (ftdi_usb_close_internal (ftdi) != 0)
00898         rtn = -2;
00899 
00900     return rtn;
00901 }
00902 
00908 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
00909                                  unsigned short *value, unsigned short *index)
00910 {
00911     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
00912     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
00913     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
00914     int divisor, best_divisor, best_baud, best_baud_diff;
00915     unsigned long encoded_divisor;
00916     int i;
00917 
00918     if (baudrate <= 0)
00919     {
00920         // Return error
00921         return -1;
00922     }
00923 
00924     divisor = 24000000 / baudrate;
00925 
00926     if (ftdi->type == TYPE_AM)
00927     {
00928         // Round down to supported fraction (AM only)
00929         divisor -= am_adjust_dn[divisor & 7];
00930     }
00931 
00932     // Try this divisor and the one above it (because division rounds down)
00933     best_divisor = 0;
00934     best_baud = 0;
00935     best_baud_diff = 0;
00936     for (i = 0; i < 2; i++)
00937     {
00938         int try_divisor = divisor + i;
00939         int baud_estimate;
00940         int baud_diff;
00941 
00942         // Round up to supported divisor value
00943         if (try_divisor <= 8)
00944         {
00945             // Round up to minimum supported divisor
00946             try_divisor = 8;
00947         }
00948         else if (ftdi->type != TYPE_AM && try_divisor < 12)
00949         {
00950             // BM doesn't support divisors 9 through 11 inclusive
00951             try_divisor = 12;
00952         }
00953         else if (divisor < 16)
00954         {
00955             // AM doesn't support divisors 9 through 15 inclusive
00956             try_divisor = 16;
00957         }
00958         else
00959         {
00960             if (ftdi->type == TYPE_AM)
00961             {
00962                 // Round up to supported fraction (AM only)
00963                 try_divisor += am_adjust_up[try_divisor & 7];
00964                 if (try_divisor > 0x1FFF8)
00965                 {
00966                     // Round down to maximum supported divisor value (for AM)
00967                     try_divisor = 0x1FFF8;
00968                 }
00969             }
00970             else
00971             {
00972                 if (try_divisor > 0x1FFFF)
00973                 {
00974                     // Round down to maximum supported divisor value (for BM)
00975                     try_divisor = 0x1FFFF;
00976                 }
00977             }
00978         }
00979         // Get estimated baud rate (to nearest integer)
00980         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
00981         // Get absolute difference from requested baud rate
00982         if (baud_estimate < baudrate)
00983         {
00984             baud_diff = baudrate - baud_estimate;
00985         }
00986         else
00987         {
00988             baud_diff = baud_estimate - baudrate;
00989         }
00990         if (i == 0 || baud_diff < best_baud_diff)
00991         {
00992             // Closest to requested baud rate so far
00993             best_divisor = try_divisor;
00994             best_baud = baud_estimate;
00995             best_baud_diff = baud_diff;
00996             if (baud_diff == 0)
00997             {
00998                 // Spot on! No point trying
00999                 break;
01000             }
01001         }
01002     }
01003     // Encode the best divisor value
01004     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
01005     // Deal with special cases for encoded value
01006     if (encoded_divisor == 1)
01007     {
01008         encoded_divisor = 0;    // 3000000 baud
01009     }
01010     else if (encoded_divisor == 0x4001)
01011     {
01012         encoded_divisor = 1;    // 2000000 baud (BM only)
01013     }
01014     // Split into "value" and "index" values
01015     *value = (unsigned short)(encoded_divisor & 0xFFFF);
01016     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
01017     {
01018         *index = (unsigned short)(encoded_divisor >> 8);
01019         *index &= 0xFF00;
01020         *index |= ftdi->index;
01021     }
01022     else
01023         *index = (unsigned short)(encoded_divisor >> 16);
01024 
01025     // Return the nearest baud rate
01026     return best_baud;
01027 }
01028 
01039 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
01040 {
01041     unsigned short value, index;
01042     int actual_baudrate;
01043 
01044     if (ftdi->bitbang_enabled)
01045     {
01046         baudrate = baudrate*4;
01047     }
01048 
01049     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
01050     if (actual_baudrate <= 0)
01051         ftdi_error_return (-1, "Silly baudrate <= 0.");
01052 
01053     // Check within tolerance (about 5%)
01054     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
01055             || ((actual_baudrate < baudrate)
01056                 ? (actual_baudrate * 21 < baudrate * 20)
01057                 : (baudrate * 21 < actual_baudrate * 20)))
01058         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
01059 
01060     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01061                         SIO_SET_BAUDRATE_REQUEST, value,
01062                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
01063         ftdi_error_return (-2, "Setting new baudrate failed");
01064 
01065     ftdi->baudrate = baudrate;
01066     return 0;
01067 }
01068 
01082 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01083                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
01084 {
01085     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
01086 }
01087 
01100 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
01101                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
01102                             enum ftdi_break_type break_type)
01103 {
01104     unsigned short value = bits;
01105 
01106     switch (parity)
01107     {
01108         case NONE:
01109             value |= (0x00 << 8);
01110             break;
01111         case ODD:
01112             value |= (0x01 << 8);
01113             break;
01114         case EVEN:
01115             value |= (0x02 << 8);
01116             break;
01117         case MARK:
01118             value |= (0x03 << 8);
01119             break;
01120         case SPACE:
01121             value |= (0x04 << 8);
01122             break;
01123     }
01124 
01125     switch (sbit)
01126     {
01127         case STOP_BIT_1:
01128             value |= (0x00 << 11);
01129             break;
01130         case STOP_BIT_15:
01131             value |= (0x01 << 11);
01132             break;
01133         case STOP_BIT_2:
01134             value |= (0x02 << 11);
01135             break;
01136     }
01137 
01138     switch (break_type)
01139     {
01140         case BREAK_OFF:
01141             value |= (0x00 << 14);
01142             break;
01143         case BREAK_ON:
01144             value |= (0x01 << 14);
01145             break;
01146     }
01147 
01148     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01149                         SIO_SET_DATA_REQUEST, value,
01150                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01151         ftdi_error_return (-1, "Setting new line property failed");
01152 
01153     return 0;
01154 }
01155 
01166 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01167 {
01168     int ret;
01169     int offset = 0;
01170     int total_written = 0;
01171 
01172     while (offset < size)
01173     {
01174         int write_size = ftdi->writebuffer_chunksize;
01175 
01176         if (offset+write_size > size)
01177             write_size = size-offset;
01178 
01179         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
01180         if (ret < 0)
01181             ftdi_error_return(ret, "usb bulk write failed");
01182 
01183         total_written += ret;
01184         offset += write_size;
01185     }
01186 
01187     return total_written;
01188 }
01189 
01190 #ifdef LIBFTDI_LINUX_ASYNC_MODE
01191 #ifdef USB_CLASS_PTP
01192 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
01193 #endif
01194 /* this is strongly dependent on libusb using the same struct layout. If libusb
01195    changes in some later version this may break horribly (this is for libusb 0.1.12) */
01196 struct usb_dev_handle
01197 {
01198     int fd;
01199     // some other stuff coming here we don't need
01200 };
01201 
01206 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
01207 {
01208     struct usbdevfs_urb *urb;
01209     int pending=0;
01210     unsigned int i;
01211 
01212     for (i=0; i < ftdi->async_usb_buffer_size; i++)
01213     {
01214         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01215         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
01216             pending++;
01217     }
01218 
01219     return pending;
01220 }
01221 
01232 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
01233 {
01234     struct timeval tv;
01235     struct usbdevfs_urb *urb=NULL;
01236     int ret;
01237     fd_set writefds;
01238     int keep_going=0;
01239 
01240     FD_ZERO(&writefds);
01241     FD_SET(ftdi->usb_dev->fd, &writefds);
01242 
01243     /* init timeout only once, select writes time left after call */
01244     tv.tv_sec = timeout_msec / 1000;
01245     tv.tv_usec = (timeout_msec % 1000) * 1000;
01246 
01247     do
01248     {
01249         while (_usb_get_async_urbs_pending(ftdi)
01250                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
01251                 && errno == EAGAIN)
01252         {
01253             if (keep_going && !wait_for_more)
01254             {
01255                 /* don't wait if repeating only for keep_going */
01256                 keep_going=0;
01257                 break;
01258             }
01259 
01260             /* wait for timeout msec or something written ready */
01261             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
01262         }
01263 
01264         if (ret == 0 && urb != NULL)
01265         {
01266             /* got a free urb, mark it */
01267             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
01268 
01269             /* try to get more urbs that are ready now, but don't wait anymore */
01270             urb=NULL;
01271             keep_going=1;
01272         }
01273         else
01274         {
01275             /* no more urbs waiting */
01276             keep_going=0;
01277         }
01278     }
01279     while (keep_going);
01280 }
01281 
01289 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
01290 {
01291     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
01292 }
01293 
01299 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
01300 {
01301     struct usbdevfs_urb *urb;
01302     int bytesdone = 0, requested;
01303     int ret, cleanup_count;
01304     unsigned int i;
01305 
01306     do
01307     {
01308         /* find a free urb buffer we can use */
01309         urb=NULL;
01310         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
01311         {
01312             if (i==ftdi->async_usb_buffer_size)
01313             {
01314                 /* wait until some buffers are free */
01315                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
01316             }
01317 
01318             for (i=0; i < ftdi->async_usb_buffer_size; i++)
01319             {
01320                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01321                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
01322                     break;  /* found a free urb position */
01323                 urb=NULL;
01324             }
01325         }
01326 
01327         /* no free urb position found */
01328         if (urb==NULL)
01329             return -1;
01330 
01331         requested = size - bytesdone;
01332         if (requested > 4096)
01333             requested = 4096;
01334 
01335         memset(urb,0,sizeof(urb));
01336 
01337         urb->type = USBDEVFS_URB_TYPE_BULK;
01338         urb->endpoint = ep;
01339         urb->flags = 0;
01340         urb->buffer = bytes + bytesdone;
01341         urb->buffer_length = requested;
01342         urb->signr = 0;
01343         urb->actual_length = 0;
01344         urb->number_of_packets = 0;
01345         urb->usercontext = 0;
01346 
01347         do
01348         {
01349             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
01350         }
01351         while (ret < 0 && errno == EINTR);
01352         if (ret < 0)
01353             return ret;       /* the caller can read errno to get more info */
01354 
01355         bytesdone += requested;
01356     }
01357     while (bytesdone < size);
01358     return bytesdone;
01359 }
01360 
01379 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
01380 {
01381     int ret;
01382     int offset = 0;
01383     int total_written = 0;
01384 
01385     while (offset < size)
01386     {
01387         int write_size = ftdi->writebuffer_chunksize;
01388 
01389         if (offset+write_size > size)
01390             write_size = size-offset;
01391 
01392         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
01393         if (ret < 0)
01394             ftdi_error_return(ret, "usb bulk write async failed");
01395 
01396         total_written += ret;
01397         offset += write_size;
01398     }
01399 
01400     return total_written;
01401 }
01402 #endif // LIBFTDI_LINUX_ASYNC_MODE
01403 
01413 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01414 {
01415     ftdi->writebuffer_chunksize = chunksize;
01416     return 0;
01417 }
01418 
01427 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01428 {
01429     *chunksize = ftdi->writebuffer_chunksize;
01430     return 0;
01431 }
01432 
01447 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01448 {
01449     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
01450     int packet_size = ftdi->max_packet_size;
01451 
01452     // Packet size sanity check (avoid division by zero)
01453     if (packet_size == 0)
01454         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
01455 
01456     // everything we want is still in the readbuffer?
01457     if (size <= ftdi->readbuffer_remaining)
01458     {
01459         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
01460 
01461         // Fix offsets
01462         ftdi->readbuffer_remaining -= size;
01463         ftdi->readbuffer_offset += size;
01464 
01465         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
01466 
01467         return size;
01468     }
01469     // something still in the readbuffer, but not enough to satisfy 'size'?
01470     if (ftdi->readbuffer_remaining != 0)
01471     {
01472         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
01473 
01474         // Fix offset
01475         offset += ftdi->readbuffer_remaining;
01476     }
01477     // do the actual USB read
01478     while (offset < size && ret > 0)
01479     {
01480         ftdi->readbuffer_remaining = 0;
01481         ftdi->readbuffer_offset = 0;
01482         /* returns how much received */
01483         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
01484         if (ret < 0)
01485             ftdi_error_return(ret, "usb bulk read failed");
01486 
01487         if (ret > 2)
01488         {
01489             // skip FTDI status bytes.
01490             // Maybe stored in the future to enable modem use
01491             num_of_chunks = ret / packet_size;
01492             chunk_remains = ret % packet_size;
01493             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
01494 
01495             ftdi->readbuffer_offset += 2;
01496             ret -= 2;
01497 
01498             if (ret > packet_size - 2)
01499             {
01500                 for (i = 1; i < num_of_chunks; i++)
01501                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01502                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01503                              packet_size - 2);
01504                 if (chunk_remains > 2)
01505                 {
01506                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01507                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01508                              chunk_remains-2);
01509                     ret -= 2*num_of_chunks;
01510                 }
01511                 else
01512                     ret -= 2*(num_of_chunks-1)+chunk_remains;
01513             }
01514         }
01515         else if (ret <= 2)
01516         {
01517             // no more data to read?
01518             return offset;
01519         }
01520         if (ret > 0)
01521         {
01522             // data still fits in buf?
01523             if (offset+ret <= size)
01524             {
01525                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
01526                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
01527                 offset += ret;
01528 
01529                 /* Did we read exactly the right amount of bytes? */
01530                 if (offset == size)
01531                     //printf("read_data exact rem %d offset %d\n",
01532                     //ftdi->readbuffer_remaining, offset);
01533                     return offset;
01534             }
01535             else
01536             {
01537                 // only copy part of the data or size <= readbuffer_chunksize
01538                 int part_size = size-offset;
01539                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
01540 
01541                 ftdi->readbuffer_offset += part_size;
01542                 ftdi->readbuffer_remaining = ret-part_size;
01543                 offset += part_size;
01544 
01545                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
01546                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
01547 
01548                 return offset;
01549             }
01550         }
01551     }
01552     // never reached
01553     return -127;
01554 }
01555 
01567 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01568 {
01569     unsigned char *new_buf;
01570 
01571     // Invalidate all remaining data
01572     ftdi->readbuffer_offset = 0;
01573     ftdi->readbuffer_remaining = 0;
01574 
01575     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
01576         ftdi_error_return(-1, "out of memory for readbuffer");
01577 
01578     ftdi->readbuffer = new_buf;
01579     ftdi->readbuffer_chunksize = chunksize;
01580 
01581     return 0;
01582 }
01583 
01592 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01593 {
01594     *chunksize = ftdi->readbuffer_chunksize;
01595     return 0;
01596 }
01597 
01598 
01611 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
01612 {
01613     unsigned short usb_val;
01614 
01615     usb_val = bitmask; // low byte: bitmask
01616     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
01617     usb_val |= (ftdi->bitbang_mode << 8);
01618 
01619     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01620                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
01621                         NULL, 0, ftdi->usb_write_timeout) != 0)
01622         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
01623 
01624     ftdi->bitbang_enabled = 1;
01625     return 0;
01626 }
01627 
01636 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
01637 {
01638     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)
01639         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
01640 
01641     ftdi->bitbang_enabled = 0;
01642     return 0;
01643 }
01644 
01656 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
01657 {
01658     unsigned short usb_val;
01659 
01660     usb_val = bitmask; // low byte: bitmask
01661     usb_val |= (mode << 8);
01662     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)
01663         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps selected mode not supported on your chip?");
01664 
01665     ftdi->bitbang_mode = mode;
01666     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
01667     return 0;
01668 }
01669 
01679 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
01680 {
01681     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)
01682         ftdi_error_return(-1, "read pins failed");
01683 
01684     return 0;
01685 }
01686 
01701 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
01702 {
01703     unsigned short usb_val;
01704 
01705     if (latency < 1)
01706         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
01707 
01708     usb_val = latency;
01709     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)
01710         ftdi_error_return(-2, "unable to set latency timer");
01711 
01712     return 0;
01713 }
01714 
01724 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
01725 {
01726     unsigned short usb_val;
01727     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)
01728         ftdi_error_return(-1, "reading latency timer failed");
01729 
01730     *latency = (unsigned char)usb_val;
01731     return 0;
01732 }
01733 
01773 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
01774 {
01775     char usb_val[2];
01776 
01777     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)
01778         ftdi_error_return(-1, "getting modem status failed");
01779 
01780     *status = (usb_val[1] << 8) | usb_val[0];
01781 
01782     return 0;
01783 }
01784 
01795 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
01796 {
01797     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01798                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
01799                         NULL, 0, ftdi->usb_write_timeout) != 0)
01800         ftdi_error_return(-1, "set flow control failed");
01801 
01802     return 0;
01803 }
01804 
01814 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
01815 {
01816     unsigned short usb_val;
01817 
01818     if (state)
01819         usb_val = SIO_SET_DTR_HIGH;
01820     else
01821         usb_val = SIO_SET_DTR_LOW;
01822 
01823     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01824                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01825                         NULL, 0, ftdi->usb_write_timeout) != 0)
01826         ftdi_error_return(-1, "set dtr failed");
01827 
01828     return 0;
01829 }
01830 
01840 int ftdi_setrts(struct ftdi_context *ftdi, int state)
01841 {
01842     unsigned short usb_val;
01843 
01844     if (state)
01845         usb_val = SIO_SET_RTS_HIGH;
01846     else
01847         usb_val = SIO_SET_RTS_LOW;
01848 
01849     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01850                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01851                         NULL, 0, ftdi->usb_write_timeout) != 0)
01852         ftdi_error_return(-1, "set of rts failed");
01853 
01854     return 0;
01855 }
01856 
01867 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
01868 {
01869     unsigned short usb_val;
01870 
01871     if (dtr)
01872         usb_val = SIO_SET_DTR_HIGH;
01873     else
01874         usb_val = SIO_SET_DTR_LOW;
01875 
01876     if (rts)
01877         usb_val |= SIO_SET_RTS_HIGH;
01878     else
01879         usb_val |= SIO_SET_RTS_LOW;
01880 
01881     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01882                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01883                         NULL, 0, ftdi->usb_write_timeout) != 0)
01884         ftdi_error_return(-1, "set of rts/dtr failed");
01885 
01886     return 0;
01887 }
01888 
01899 int ftdi_set_event_char(struct ftdi_context *ftdi,
01900                         unsigned char eventch, unsigned char enable)
01901 {
01902     unsigned short usb_val;
01903 
01904     usb_val = eventch;
01905     if (enable)
01906         usb_val |= 1 << 8;
01907 
01908     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)
01909         ftdi_error_return(-1, "setting event character failed");
01910 
01911     return 0;
01912 }
01913 
01924 int ftdi_set_error_char(struct ftdi_context *ftdi,
01925                         unsigned char errorch, unsigned char enable)
01926 {
01927     unsigned short usb_val;
01928 
01929     usb_val = errorch;
01930     if (enable)
01931         usb_val |= 1 << 8;
01932 
01933     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)
01934         ftdi_error_return(-1, "setting error character failed");
01935 
01936     return 0;
01937 }
01938 
01947 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
01948 {
01949     ftdi->eeprom_size=size;
01950     eeprom->size=size;
01951 }
01952 
01958 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
01959 {
01960     eeprom->vendor_id = 0x0403;
01961     eeprom->product_id = 0x6001;
01962 
01963     eeprom->self_powered = 1;
01964     eeprom->remote_wakeup = 1;
01965     eeprom->BM_type_chip = 1;
01966 
01967     eeprom->in_is_isochronous = 0;
01968     eeprom->out_is_isochronous = 0;
01969     eeprom->suspend_pull_downs = 0;
01970 
01971     eeprom->use_serial = 0;
01972     eeprom->change_usb_version = 0;
01973     eeprom->usb_version = 0x0200;
01974     eeprom->max_power = 0;
01975 
01976     eeprom->manufacturer = NULL;
01977     eeprom->product = NULL;
01978     eeprom->serial = NULL;
01979 
01980     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
01981 }
01982 
01993 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
01994 {
01995     unsigned char i, j;
01996     unsigned short checksum, value;
01997     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
01998     int size_check;
01999 
02000     if (eeprom->manufacturer != NULL)
02001         manufacturer_size = strlen(eeprom->manufacturer);
02002     if (eeprom->product != NULL)
02003         product_size = strlen(eeprom->product);
02004     if (eeprom->serial != NULL)
02005         serial_size = strlen(eeprom->serial);
02006 
02007     size_check = eeprom->size;
02008     size_check -= 28; // 28 are always in use (fixed)
02009 
02010     // Top half of a 256byte eeprom is used just for strings and checksum
02011     // it seems that the FTDI chip will not read these strings from the lower half
02012     // Each string starts with two bytes; offset and type (0x03 for string)
02013     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02014     if (eeprom->size>=256)size_check = 120;
02015     size_check -= manufacturer_size*2;
02016     size_check -= product_size*2;
02017     size_check -= serial_size*2;
02018 
02019     // eeprom size exceeded?
02020     if (size_check < 0)
02021         return (-1);
02022 
02023     // empty eeprom
02024     memset (output, 0, eeprom->size);
02025 
02026     // Addr 00: Stay 00 00
02027     // Addr 02: Vendor ID
02028     output[0x02] = eeprom->vendor_id;
02029     output[0x03] = eeprom->vendor_id >> 8;
02030 
02031     // Addr 04: Product ID
02032     output[0x04] = eeprom->product_id;
02033     output[0x05] = eeprom->product_id >> 8;
02034 
02035     // Addr 06: Device release number (0400h for BM features)
02036     output[0x06] = 0x00;
02037 
02038     if (eeprom->BM_type_chip == 1)
02039         output[0x07] = 0x04;
02040     else
02041         output[0x07] = 0x02;
02042 
02043     // Addr 08: Config descriptor
02044     // Bit 7: always 1
02045     // Bit 6: 1 if this device is self powered, 0 if bus powered
02046     // Bit 5: 1 if this device uses remote wakeup
02047     // Bit 4: 1 if this device is battery powered
02048     j = 0x80;
02049     if (eeprom->self_powered == 1)
02050         j |= 0x40;
02051     if (eeprom->remote_wakeup == 1)
02052         j |= 0x20;
02053     output[0x08] = j;
02054 
02055     // Addr 09: Max power consumption: max power = value * 2 mA
02056     output[0x09] = eeprom->max_power;
02057 
02058     // Addr 0A: Chip configuration
02059     // Bit 7: 0 - reserved
02060     // Bit 6: 0 - reserved
02061     // Bit 5: 0 - reserved
02062     // Bit 4: 1 - Change USB version
02063     // Bit 3: 1 - Use the serial number string
02064     // Bit 2: 1 - Enable suspend pull downs for lower power
02065     // Bit 1: 1 - Out EndPoint is Isochronous
02066     // Bit 0: 1 - In EndPoint is Isochronous
02067     //
02068     j = 0;
02069     if (eeprom->in_is_isochronous == 1)
02070         j = j | 1;
02071     if (eeprom->out_is_isochronous == 1)
02072         j = j | 2;
02073     if (eeprom->suspend_pull_downs == 1)
02074         j = j | 4;
02075     if (eeprom->use_serial == 1)
02076         j = j | 8;
02077     if (eeprom->change_usb_version == 1)
02078         j = j | 16;
02079     output[0x0A] = j;
02080 
02081     // Addr 0B: reserved
02082     output[0x0B] = 0x00;
02083 
02084     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02085     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02086     if (eeprom->change_usb_version == 1)
02087     {
02088         output[0x0C] = eeprom->usb_version;
02089         output[0x0D] = eeprom->usb_version >> 8;
02090     }
02091 
02092 
02093     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02094     // Addr 0F: Length of manufacturer string
02095     output[0x0F] = manufacturer_size*2 + 2;
02096 
02097     // Addr 10: Offset of the product string + 0x80, calculated later
02098     // Addr 11: Length of product string
02099     output[0x11] = product_size*2 + 2;
02100 
02101     // Addr 12: Offset of the serial string + 0x80, calculated later
02102     // Addr 13: Length of serial string
02103     output[0x13] = serial_size*2 + 2;
02104 
02105     // Dynamic content
02106     i=0x14;
02107     if (eeprom->size>=256) i = 0x80;
02108 
02109 
02110     // Output manufacturer
02111     output[0x0E] = i | 0x80;  // calculate offset
02112     output[i++] = manufacturer_size*2 + 2;
02113     output[i++] = 0x03; // type: string
02114     for (j = 0; j < manufacturer_size; j++)
02115     {
02116         output[i] = eeprom->manufacturer[j], i++;
02117         output[i] = 0x00, i++;
02118     }
02119 
02120     // Output product name
02121     output[0x10] = i | 0x80;  // calculate offset
02122     output[i] = product_size*2 + 2, i++;
02123     output[i] = 0x03, i++;
02124     for (j = 0; j < product_size; j++)
02125     {
02126         output[i] = eeprom->product[j], i++;
02127         output[i] = 0x00, i++;
02128     }
02129 
02130     // Output serial
02131     output[0x12] = i | 0x80; // calculate offset
02132     output[i] = serial_size*2 + 2, i++;
02133     output[i] = 0x03, i++;
02134     for (j = 0; j < serial_size; j++)
02135     {
02136         output[i] = eeprom->serial[j], i++;
02137         output[i] = 0x00, i++;
02138     }
02139 
02140     // calculate checksum
02141     checksum = 0xAAAA;
02142 
02143     for (i = 0; i < eeprom->size/2-1; i++)
02144     {
02145         value = output[i*2];
02146         value += output[(i*2)+1] << 8;
02147 
02148         checksum = value^checksum;
02149         checksum = (checksum << 1) | (checksum >> 15);
02150     }
02151 
02152     output[eeprom->size-2] = checksum;
02153     output[eeprom->size-1] = checksum >> 8;
02154 
02155     return size_check;
02156 }
02157 
02171 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
02172 {
02173     unsigned char i, j;
02174     unsigned short checksum, eeprom_checksum, value;
02175     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
02176     int size_check;
02177     int eeprom_size = 128;
02178 #if 0
02179     size_check = eeprom->size;
02180     size_check -= 28; // 28 are always in use (fixed)
02181 
02182     // Top half of a 256byte eeprom is used just for strings and checksum
02183     // it seems that the FTDI chip will not read these strings from the lower half
02184     // Each string starts with two bytes; offset and type (0x03 for string)
02185     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
02186     if (eeprom->size>=256)size_check = 120;
02187     size_check -= manufacturer_size*2;
02188     size_check -= product_size*2;
02189     size_check -= serial_size*2;
02190 
02191     // eeprom size exceeded?
02192     if (size_check < 0)
02193         return (-1);
02194 #endif
02195 
02196     // empty eeprom struct
02197     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
02198 
02199     // Addr 00: Stay 00 00
02200 
02201     // Addr 02: Vendor ID
02202     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
02203 
02204     // Addr 04: Product ID
02205     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
02206 
02207     value = buf[0x06] + (buf[0x07]<<8);
02208     switch (value)
02209     {
02210         case 0x0400:
02211             eeprom->BM_type_chip = 1;
02212             break;
02213         case 0x0200:
02214             eeprom->BM_type_chip = 0;
02215             break;
02216         default: // Unknown device
02217             eeprom->BM_type_chip = 0;
02218             break;
02219     }
02220 
02221     // Addr 08: Config descriptor
02222     // Bit 7: always 1
02223     // Bit 6: 1 if this device is self powered, 0 if bus powered
02224     // Bit 5: 1 if this device uses remote wakeup
02225     // Bit 4: 1 if this device is battery powered
02226     j = buf[0x08];
02227     if (j&0x40) eeprom->self_powered = 1;
02228     if (j&0x20) eeprom->remote_wakeup = 1;
02229 
02230     // Addr 09: Max power consumption: max power = value * 2 mA
02231     eeprom->max_power = buf[0x09];
02232 
02233     // Addr 0A: Chip configuration
02234     // Bit 7: 0 - reserved
02235     // Bit 6: 0 - reserved
02236     // Bit 5: 0 - reserved
02237     // Bit 4: 1 - Change USB version
02238     // Bit 3: 1 - Use the serial number string
02239     // Bit 2: 1 - Enable suspend pull downs for lower power
02240     // Bit 1: 1 - Out EndPoint is Isochronous
02241     // Bit 0: 1 - In EndPoint is Isochronous
02242     //
02243     j = buf[0x0A];
02244     if (j&0x01) eeprom->in_is_isochronous = 1;
02245     if (j&0x02) eeprom->out_is_isochronous = 1;
02246     if (j&0x04) eeprom->suspend_pull_downs = 1;
02247     if (j&0x08) eeprom->use_serial = 1;
02248     if (j&0x10) eeprom->change_usb_version = 1;
02249 
02250     // Addr 0B: reserved
02251 
02252     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02253     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02254     if (eeprom->change_usb_version == 1)
02255     {
02256         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
02257     }
02258 
02259     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02260     // Addr 0F: Length of manufacturer string
02261     manufacturer_size = buf[0x0F]/2;
02262     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
02263     else eeprom->manufacturer = NULL;
02264 
02265     // Addr 10: Offset of the product string + 0x80, calculated later
02266     // Addr 11: Length of product string
02267     product_size = buf[0x11]/2;
02268     if (product_size > 0) eeprom->product = malloc(product_size);
02269     else eeprom->product = NULL;
02270 
02271     // Addr 12: Offset of the serial string + 0x80, calculated later
02272     // Addr 13: Length of serial string
02273     serial_size = buf[0x13]/2;
02274     if (serial_size > 0) eeprom->serial = malloc(serial_size);
02275     else eeprom->serial = NULL;
02276 
02277     // Decode manufacturer
02278     i = buf[0x0E] & 0x7f; // offset
02279     for (j=0;j<manufacturer_size-1;j++)
02280     {
02281         eeprom->manufacturer[j] = buf[2*j+i+2];
02282     }
02283     eeprom->manufacturer[j] = '\0';
02284 
02285     // Decode product name
02286     i = buf[0x10] & 0x7f; // offset
02287     for (j=0;j<product_size-1;j++)
02288     {
02289         eeprom->product[j] = buf[2*j+i+2];
02290     }
02291     eeprom->product[j] = '\0';
02292 
02293     // Decode serial
02294     i = buf[0x12] & 0x7f; // offset
02295     for (j=0;j<serial_size-1;j++)
02296     {
02297         eeprom->serial[j] = buf[2*j+i+2];
02298     }
02299     eeprom->serial[j] = '\0';
02300 
02301     // verify checksum
02302     checksum = 0xAAAA;
02303 
02304     for (i = 0; i < eeprom_size/2-1; i++)
02305     {
02306         value = buf[i*2];
02307         value += buf[(i*2)+1] << 8;
02308 
02309         checksum = value^checksum;
02310         checksum = (checksum << 1) | (checksum >> 15);
02311     }
02312 
02313     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
02314 
02315     if (eeprom_checksum != checksum)
02316     {
02317         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
02318         return -1;
02319     }
02320 
02321     return 0;
02322 }
02323 
02334 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
02335 {
02336     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)
02337         ftdi_error_return(-1, "reading eeprom failed");
02338 
02339     return 0;
02340 }
02341 
02351 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02352 {
02353     int i;
02354 
02355     for (i = 0; i < ftdi->eeprom_size/2; i++)
02356     {
02357         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)
02358             ftdi_error_return(-1, "reading eeprom failed");
02359     }
02360 
02361     return 0;
02362 }
02363 
02364 /*
02365     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
02366     Function is only used internally
02367     \internal
02368 */
02369 static unsigned char ftdi_read_chipid_shift(unsigned char value)
02370 {
02371     return ((value & 1) << 1) |
02372            ((value & 2) << 5) |
02373            ((value & 4) >> 2) |
02374            ((value & 8) << 4) |
02375            ((value & 16) >> 1) |
02376            ((value & 32) >> 1) |
02377            ((value & 64) >> 4) |
02378            ((value & 128) >> 2);
02379 }
02380 
02390 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
02391 {
02392     unsigned int a = 0, b = 0;
02393 
02394     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)
02395     {
02396         a = a << 8 | a >> 8;
02397         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)
02398         {
02399             b = b << 8 | b >> 8;
02400             a = (a << 16) | (b & 0xFFFF);
02401             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
02402                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
02403             *chipid = a ^ 0xa5f0f7d1;
02404             return 0;
02405         }
02406     }
02407 
02408     ftdi_error_return(-1, "read of FTDIChip-ID failed");
02409 }
02410 
02421 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
02422 {
02423     int i=0,j,minsize=32;
02424     int size=minsize;
02425 
02426     do
02427     {
02428         for (j = 0; i < maxsize/2 && j<size; j++)
02429         {
02430             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
02431                                 SIO_READ_EEPROM_REQUEST, 0, i,
02432                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02433                 ftdi_error_return(-1, "reading eeprom failed");
02434             i++;
02435         }
02436         size*=2;
02437     }
02438     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
02439 
02440     return size/2;
02441 }
02442 
02453 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
02454 {
02455     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02456                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
02457                                     NULL, 0, ftdi->usb_write_timeout) != 0)
02458         ftdi_error_return(-1, "unable to write eeprom");
02459 
02460     return 0;
02461 }
02462 
02472 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02473 {
02474     unsigned short usb_val, status;
02475     int i, ret;
02476 
02477     /* These commands were traced while running MProg */
02478     if ((ret = ftdi_usb_reset(ftdi)) != 0)
02479         return ret;
02480     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
02481         return ret;
02482     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
02483         return ret;
02484 
02485     for (i = 0; i < ftdi->eeprom_size/2; i++)
02486     {
02487         usb_val = eeprom[i*2];
02488         usb_val += eeprom[(i*2)+1] << 8;
02489         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02490                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
02491                             NULL, 0, ftdi->usb_write_timeout) != 0)
02492             ftdi_error_return(-1, "unable to write eeprom");
02493     }
02494 
02495     return 0;
02496 }
02497 
02508 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
02509 {
02510     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
02511         ftdi_error_return(-1, "unable to erase eeprom");
02512 
02513     return 0;
02514 }
02515 
02523 char *ftdi_get_error_string (struct ftdi_context *ftdi)
02524 {
02525     return ftdi->error_str;
02526 }
02527 
02528 /* @} end of doxygen libftdi group */

Generated on Thu Feb 4 21:56:53 2010 for libftdi by  doxygen 1.5.4