use_serial is used in all devices beside AM types. So move out of the switch(ftdi...
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2010 by Intra2net AG
6     email                : opensource@intra2net.com
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU Lesser General Public License           *
13  *   version 2.1 as published by the Free Software Foundation;             *
14  *                                                                         *
15  ***************************************************************************/
16
17 /**
18     \mainpage libftdi API documentation
19
20     Library to talk to FTDI chips. You find the latest versions of libftdi at
21     http://www.intra2net.com/en/developer/libftdi/
22
23     The library is easy to use. Have a look at this short example:
24     \include simple.c
25
26     More examples can be found in the "examples" directory.
27 */
28 /** \addtogroup libftdi */
29 /* @{ */
30
31 #include <libusb.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include "ftdi.h"
38
39 #define ftdi_error_return(code, str) do {  \
40         ftdi->error_str = str;             \
41         return code;                       \
42    } while(0);
43
44 #define ftdi_error_return_free_device_list(code, str, devs) do {    \
45         libusb_free_device_list(devs,1);   \
46         ftdi->error_str = str;             \
47         return code;                       \
48    } while(0);
49
50
51 /**
52     Internal function to close usb device pointer.
53     Sets ftdi->usb_dev to NULL.
54     \internal
55
56     \param ftdi pointer to ftdi_context
57
58     \retval none
59 */
60 static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
61 {
62     if (ftdi && ftdi->usb_dev)
63     {
64        libusb_close (ftdi->usb_dev);
65        ftdi->usb_dev = NULL;
66     }
67 }
68
69 /**
70     Initializes a ftdi_context.
71
72     \param ftdi pointer to ftdi_context
73
74     \retval  0: all fine
75     \retval -1: couldn't allocate read buffer
76     \retval -2: couldn't allocate struct  buffer
77
78     \remark This should be called before all functions
79 */
80 int ftdi_init(struct ftdi_context *ftdi)
81 {
82     struct ftdi_eeprom* eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
83     ftdi->usb_ctx = NULL;
84     ftdi->usb_dev = NULL;
85     ftdi->usb_read_timeout = 5000;
86     ftdi->usb_write_timeout = 5000;
87
88     ftdi->type = TYPE_BM;    /* chip type */
89     ftdi->baudrate = -1;
90     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
91
92     ftdi->readbuffer = NULL;
93     ftdi->readbuffer_offset = 0;
94     ftdi->readbuffer_remaining = 0;
95     ftdi->writebuffer_chunksize = 4096;
96     ftdi->max_packet_size = 0;
97
98     ftdi->interface = 0;
99     ftdi->index = 0;
100     ftdi->in_ep = 0x02;
101     ftdi->out_ep = 0x81;
102     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
103
104     ftdi->error_str = NULL;
105
106     if (eeprom == 0)
107         ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
108     ftdi->eeprom = eeprom;
109
110     /* All fine. Now allocate the readbuffer */
111     return ftdi_read_data_set_chunksize(ftdi, 4096);
112 }
113
114 /**
115     Allocate and initialize a new ftdi_context
116
117     \return a pointer to a new ftdi_context, or NULL on failure
118 */
119 struct ftdi_context *ftdi_new(void)
120 {
121     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
122
123     if (ftdi == NULL)
124     {
125         return NULL;
126     }
127
128     if (ftdi_init(ftdi) != 0)
129     {
130         free(ftdi);
131         return NULL;
132     }
133
134     return ftdi;
135 }
136
137 /**
138     Open selected channels on a chip, otherwise use first channel.
139
140     \param ftdi pointer to ftdi_context
141     \param interface Interface to use for FT2232C/2232H/4232H chips.
142
143     \retval  0: all fine
144     \retval -1: unknown interface
145     \retval -2: USB device unavailable
146 */
147 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
148 {
149     if (ftdi == NULL)
150         ftdi_error_return(-2, "USB device unavailable");
151
152     switch (interface)
153     {
154         case INTERFACE_ANY:
155         case INTERFACE_A:
156             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
157             break;
158         case INTERFACE_B:
159             ftdi->interface = 1;
160             ftdi->index     = INTERFACE_B;
161             ftdi->in_ep     = 0x04;
162             ftdi->out_ep    = 0x83;
163             break;
164         case INTERFACE_C:
165             ftdi->interface = 2;
166             ftdi->index     = INTERFACE_C;
167             ftdi->in_ep     = 0x06;
168             ftdi->out_ep    = 0x85;
169             break;
170         case INTERFACE_D:
171             ftdi->interface = 3;
172             ftdi->index     = INTERFACE_D;
173             ftdi->in_ep     = 0x08;
174             ftdi->out_ep    = 0x87;
175             break;
176         default:
177             ftdi_error_return(-1, "Unknown interface");
178     }
179     return 0;
180 }
181
182 /**
183     Deinitializes a ftdi_context.
184
185     \param ftdi pointer to ftdi_context
186 */
187 void ftdi_deinit(struct ftdi_context *ftdi)
188 {
189     if (ftdi == NULL)
190         return;
191
192     ftdi_usb_close_internal (ftdi);
193
194     if (ftdi->readbuffer != NULL)
195     {
196         free(ftdi->readbuffer);
197         ftdi->readbuffer = NULL;
198     }
199
200     if (ftdi->eeprom != NULL)
201     {
202         if (ftdi->eeprom->manufacturer != 0)
203         {
204             free(ftdi->eeprom->manufacturer);
205             ftdi->eeprom->manufacturer = 0;
206         }
207         if (ftdi->eeprom->product != 0)
208         {
209             free(ftdi->eeprom->product);
210             ftdi->eeprom->product = 0;
211         }
212         if (ftdi->eeprom->serial != 0)
213         {
214             free(ftdi->eeprom->serial);
215             ftdi->eeprom->serial = 0;
216         }
217         free(ftdi->eeprom);
218         ftdi->eeprom = NULL;
219     }
220     libusb_exit(ftdi->usb_ctx);
221 }
222
223 /**
224     Deinitialize and free an ftdi_context.
225
226     \param ftdi pointer to ftdi_context
227 */
228 void ftdi_free(struct ftdi_context *ftdi)
229 {
230     ftdi_deinit(ftdi);
231     free(ftdi);
232 }
233
234 /**
235     Use an already open libusb device.
236
237     \param ftdi pointer to ftdi_context
238     \param usb libusb libusb_device_handle to use
239 */
240 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
241 {
242     if (ftdi == NULL)
243         return;
244
245     ftdi->usb_dev = usb;
246 }
247
248
249 /**
250     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
251     needs to be deallocated by ftdi_list_free() after use.
252
253     \param ftdi pointer to ftdi_context
254     \param devlist Pointer where to store list of found devices
255     \param vendor Vendor ID to search for
256     \param product Product ID to search for
257
258     \retval >0: number of devices found
259     \retval -3: out of memory
260     \retval -4: libusb_init() failed
261     \retval -5: libusb_get_device_list() failed
262     \retval -6: libusb_get_device_descriptor() failed
263 */
264 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
265 {
266     struct ftdi_device_list **curdev;
267     libusb_device *dev;
268     libusb_device **devs;
269     int count = 0;
270     int i = 0;
271
272     if (libusb_init(&ftdi->usb_ctx) < 0)
273         ftdi_error_return(-4, "libusb_init() failed");
274
275     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
276         ftdi_error_return(-5, "libusb_get_device_list() failed");
277
278     curdev = devlist;
279     *curdev = NULL;
280
281     while ((dev = devs[i++]) != NULL)
282     {
283         struct libusb_device_descriptor desc;
284
285         if (libusb_get_device_descriptor(dev, &desc) < 0)
286             ftdi_error_return(-6, "libusb_get_device_descriptor() failed");
287
288         if (desc.idVendor == vendor && desc.idProduct == product)
289         {
290             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
291             if (!*curdev)
292                 ftdi_error_return(-3, "out of memory");
293               
294             (*curdev)->next = NULL;
295             (*curdev)->dev = dev;
296
297             curdev = &(*curdev)->next;
298             count++;
299         }
300     }
301
302     return count;
303 }
304
305 /**
306     Frees a usb device list.
307
308     \param devlist USB device list created by ftdi_usb_find_all()
309 */
310 void ftdi_list_free(struct ftdi_device_list **devlist)
311 {
312     struct ftdi_device_list *curdev, *next;
313
314     for (curdev = *devlist; curdev != NULL;)
315     {
316         next = curdev->next;
317         free(curdev);
318         curdev = next;
319     }
320
321     *devlist = NULL;
322 }
323
324 /**
325     Frees a usb device list.
326
327     \param devlist USB device list created by ftdi_usb_find_all()
328 */
329 void ftdi_list_free2(struct ftdi_device_list *devlist)
330 {
331     ftdi_list_free(&devlist);
332 }
333
334 /**
335     Return device ID strings from the usb device.
336
337     The parameters manufacturer, description and serial may be NULL
338     or pointer to buffers to store the fetched strings.
339
340     \note Use this function only in combination with ftdi_usb_find_all()
341           as it closes the internal "usb_dev" after use.
342
343     \param ftdi pointer to ftdi_context
344     \param dev libusb usb_dev to use
345     \param manufacturer Store manufacturer string here if not NULL
346     \param mnf_len Buffer size of manufacturer string
347     \param description Store product description string here if not NULL
348     \param desc_len Buffer size of product description string
349     \param serial Store serial string here if not NULL
350     \param serial_len Buffer size of serial string
351
352     \retval   0: all fine
353     \retval  -1: wrong arguments
354     \retval  -4: unable to open device
355     \retval  -7: get product manufacturer failed
356     \retval  -8: get product description failed
357     \retval  -9: get serial number failed
358     \retval -11: libusb_get_device_descriptor() failed
359 */
360 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
361                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
362 {
363     struct libusb_device_descriptor desc;
364
365     if ((ftdi==NULL) || (dev==NULL))
366         return -1;
367
368     if (libusb_open(dev, &ftdi->usb_dev) < 0)
369         ftdi_error_return(-4, "libusb_open() failed");
370
371     if (libusb_get_device_descriptor(dev, &desc) < 0)
372         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
373
374     if (manufacturer != NULL)
375     {
376         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
377         {
378             ftdi_usb_close_internal (ftdi);
379             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
380         }
381     }
382
383     if (description != NULL)
384     {
385         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
386         {
387             ftdi_usb_close_internal (ftdi);
388             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
389         }
390     }
391
392     if (serial != NULL)
393     {
394         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
395         {
396             ftdi_usb_close_internal (ftdi);
397             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
398         }
399     }
400
401     ftdi_usb_close_internal (ftdi);
402
403     return 0;
404 }
405
406 /**
407  * Internal function to determine the maximum packet size.
408  * \param ftdi pointer to ftdi_context
409  * \param dev libusb usb_dev to use
410  * \retval Maximum packet size for this device
411  */
412 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
413 {
414     struct libusb_device_descriptor desc;
415     struct libusb_config_descriptor *config0;
416     unsigned int packet_size;
417
418     // Sanity check
419     if (ftdi == NULL || dev == NULL)
420         return 64;
421
422     // Determine maximum packet size. Init with default value.
423     // New hi-speed devices from FTDI use a packet size of 512 bytes
424     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
425     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
426         packet_size = 512;
427     else
428         packet_size = 64;
429
430     if (libusb_get_device_descriptor(dev, &desc) < 0)
431         return packet_size;
432
433     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
434         return packet_size;
435
436     if (desc.bNumConfigurations > 0)
437     {
438         if (ftdi->interface < config0->bNumInterfaces)
439         {
440             struct libusb_interface interface = config0->interface[ftdi->interface];
441             if (interface.num_altsetting > 0)
442             {
443                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
444                 if (descriptor.bNumEndpoints > 0)
445                 {
446                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
447                 }
448             }
449         }
450     }
451
452     libusb_free_config_descriptor (config0);
453     return packet_size;
454 }
455
456 /**
457     Opens a ftdi device given by an usb_device.
458
459     \param ftdi pointer to ftdi_context
460     \param dev libusb usb_dev to use
461
462     \retval  0: all fine
463     \retval -3: unable to config device
464     \retval -4: unable to open device
465     \retval -5: unable to claim device
466     \retval -6: reset failed
467     \retval -7: set baudrate failed
468     \retval -8: ftdi context invalid
469     \retval -9: libusb_get_device_descriptor() failed
470     \retval -10: libusb_get_config_descriptor() failed
471     \retval -11: libusb_etach_kernel_driver() failed
472     \retval -12: libusb_get_configuration() failed
473 */
474 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
475 {
476     struct libusb_device_descriptor desc;
477     struct libusb_config_descriptor *config0;
478     int cfg, cfg0, detach_errno = 0;
479
480     if (ftdi == NULL)
481         ftdi_error_return(-8, "ftdi context invalid");
482
483     if (libusb_open(dev, &ftdi->usb_dev) < 0)
484         ftdi_error_return(-4, "libusb_open() failed");
485
486     if (libusb_get_device_descriptor(dev, &desc) < 0)
487         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
488
489     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
490         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
491     cfg0 = config0->bConfigurationValue;
492     libusb_free_config_descriptor (config0);
493
494     // Try to detach ftdi_sio kernel module.
495     //
496     // The return code is kept in a separate variable and only parsed
497     // if usb_set_configuration() or usb_claim_interface() fails as the
498     // detach operation might be denied and everything still works fine.
499     // Likely scenario is a static ftdi_sio kernel module.
500     if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
501         detach_errno = errno;
502
503     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
504         ftdi_error_return(-12, "libusb_get_configuration () failed");
505     // set configuration (needed especially for windows)
506     // tolerate EBUSY: one device with one configuration, but two interfaces
507     //    and libftdi sessions to both interfaces (e.g. FT2232)
508     if (desc.bNumConfigurations > 0 && cfg != cfg0)
509     {
510         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
511         {
512             ftdi_usb_close_internal (ftdi);
513             if(detach_errno == EPERM)
514             {
515                 ftdi_error_return(-8, "inappropriate permissions on device!");
516             }
517             else
518             {
519                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
520             }
521         }
522     }
523
524     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
525     {
526         ftdi_usb_close_internal (ftdi);
527         if(detach_errno == EPERM)
528         {
529             ftdi_error_return(-8, "inappropriate permissions on device!");
530         }
531         else
532         {
533             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
534         }
535     }
536
537     if (ftdi_usb_reset (ftdi) != 0)
538     {
539         ftdi_usb_close_internal (ftdi);
540         ftdi_error_return(-6, "ftdi_usb_reset failed");
541     }
542
543     // Try to guess chip type
544     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
545     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
546             && desc.iSerialNumber == 0))
547         ftdi->type = TYPE_BM;
548     else if (desc.bcdDevice == 0x200)
549         ftdi->type = TYPE_AM;
550     else if (desc.bcdDevice == 0x500)
551         ftdi->type = TYPE_2232C;
552     else if (desc.bcdDevice == 0x600)
553         ftdi->type = TYPE_R;
554     else if (desc.bcdDevice == 0x700)
555         ftdi->type = TYPE_2232H;
556     else if (desc.bcdDevice == 0x800)
557         ftdi->type = TYPE_4232H;
558
559     // Set default interface on dual/quad type chips
560     switch(ftdi->type)
561     {
562         case TYPE_2232C:
563         case TYPE_2232H:
564         case TYPE_4232H:
565             if (!ftdi->index)
566                 ftdi->index = INTERFACE_A;
567             break;
568         default:
569             break;
570     }
571
572     // Determine maximum packet size
573     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
574
575     if (ftdi_set_baudrate (ftdi, 9600) != 0)
576     {
577         ftdi_usb_close_internal (ftdi);
578         ftdi_error_return(-7, "set baudrate failed");
579     }
580
581     ftdi_error_return(0, "all fine");
582 }
583
584 /**
585     Opens the first device with a given vendor and product ids.
586
587     \param ftdi pointer to ftdi_context
588     \param vendor Vendor ID
589     \param product Product ID
590
591     \retval same as ftdi_usb_open_desc()
592 */
593 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
594 {
595     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
596 }
597
598 /**
599     Opens the first device with a given, vendor id, product id,
600     description and serial.
601
602     \param ftdi pointer to ftdi_context
603     \param vendor Vendor ID
604     \param product Product ID
605     \param description Description to search for. Use NULL if not needed.
606     \param serial Serial to search for. Use NULL if not needed.
607
608     \retval  0: all fine
609     \retval -3: usb device not found
610     \retval -4: unable to open device
611     \retval -5: unable to claim device
612     \retval -6: reset failed
613     \retval -7: set baudrate failed
614     \retval -8: get product description failed
615     \retval -9: get serial number failed
616     \retval -11: libusb_init() failed
617     \retval -12: libusb_get_device_list() failed
618     \retval -13: libusb_get_device_descriptor() failed
619 */
620 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
621                        const char* description, const char* serial)
622 {
623     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
624 }
625
626 /**
627     Opens the index-th device with a given, vendor id, product id,
628     description and serial.
629
630     \param ftdi pointer to ftdi_context
631     \param vendor Vendor ID
632     \param product Product ID
633     \param description Description to search for. Use NULL if not needed.
634     \param serial Serial to search for. Use NULL if not needed.
635     \param index Number of matching device to open if there are more than one, starts with 0.
636
637     \retval  0: all fine
638     \retval -1: usb_find_busses() failed
639     \retval -2: usb_find_devices() failed
640     \retval -3: usb device not found
641     \retval -4: unable to open device
642     \retval -5: unable to claim device
643     \retval -6: reset failed
644     \retval -7: set baudrate failed
645     \retval -8: get product description failed
646     \retval -9: get serial number failed
647     \retval -10: unable to close device
648     \retval -11: ftdi context invalid
649 */
650 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
651                        const char* description, const char* serial, unsigned int index)
652 {
653     libusb_device *dev;
654     libusb_device **devs;
655     char string[256];
656     int i = 0;
657
658     if (libusb_init(&ftdi->usb_ctx) < 0)
659         ftdi_error_return(-11, "libusb_init() failed");
660
661     if (ftdi == NULL)
662         ftdi_error_return(-11, "ftdi context invalid");
663
664     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
665         ftdi_error_return(-12, "libusb_get_device_list() failed");
666
667     while ((dev = devs[i++]) != NULL)
668     {
669         struct libusb_device_descriptor desc;
670         int res;
671
672         if (libusb_get_device_descriptor(dev, &desc) < 0)
673             ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);
674
675         if (desc.idVendor == vendor && desc.idProduct == product)
676         {
677             if (libusb_open(dev, &ftdi->usb_dev) < 0)
678                 ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);
679
680             if (description != NULL)
681             {
682                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
683                 {
684                     libusb_close (ftdi->usb_dev);
685                     ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
686                 }
687                 if (strncmp(string, description, sizeof(string)) != 0)
688                 {
689                     libusb_close (ftdi->usb_dev);
690                     continue;
691                 }
692             }
693             if (serial != NULL)
694             {
695                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
696                 {
697                     ftdi_usb_close_internal (ftdi);
698                     ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
699                 }
700                 if (strncmp(string, serial, sizeof(string)) != 0)
701                 {
702                     ftdi_usb_close_internal (ftdi);
703                     continue;
704                 }
705             }
706
707             ftdi_usb_close_internal (ftdi);
708
709                 if (index > 0)
710                 {
711                     index--;
712                     continue;
713                 }
714
715             res = ftdi_usb_open_dev(ftdi, dev);
716             libusb_free_device_list(devs,1);
717             return res;
718         }
719     }
720
721     // device not found
722     ftdi_error_return_free_device_list(-3, "device not found", devs);
723 }
724
725 /**
726     Opens the ftdi-device described by a description-string.
727     Intended to be used for parsing a device-description given as commandline argument.
728
729     \param ftdi pointer to ftdi_context
730     \param description NULL-terminated description-string, using this format:
731         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
732         \li <tt>i:\<vendor>:\<product></tt> first device with given vendor and product id, ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
733         \li <tt>i:\<vendor>:\<product>:\<index></tt> as above with index being the number of the device (starting with 0) if there are more than one
734         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
735
736     \note The description format may be extended in later versions.
737
738     \retval  0: all fine
739     \retval -1: libusb_init() failed
740     \retval -2: libusb_get_device_list() failed
741     \retval -3: usb device not found
742     \retval -4: unable to open device
743     \retval -5: unable to claim device
744     \retval -6: reset failed
745     \retval -7: set baudrate failed
746     \retval -8: get product description failed
747     \retval -9: get serial number failed
748     \retval -10: unable to close device
749     \retval -11: illegal description format
750     \retval -12: ftdi context invalid
751 */
752 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
753 {
754     if (ftdi == NULL)
755         ftdi_error_return(-12, "ftdi context invalid");
756
757     if (description[0] == 0 || description[1] != ':')
758         ftdi_error_return(-11, "illegal description format");
759
760     if (description[0] == 'd')
761     {
762         libusb_device *dev;
763         libusb_device **devs;
764         unsigned int bus_number, device_address;
765         int i = 0;
766
767         if (libusb_init (&ftdi->usb_ctx) < 0)
768             ftdi_error_return(-1, "libusb_init() failed");
769
770         if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
771             ftdi_error_return(-2, "libusb_get_device_list() failed");
772
773         /* XXX: This doesn't handle symlinks/odd paths/etc... */
774         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
775             ftdi_error_return_free_device_list(-11, "illegal description format", devs);
776
777         while ((dev = devs[i++]) != NULL)
778         {
779             int ret;
780             if (bus_number == libusb_get_bus_number (dev)
781                 && device_address == libusb_get_device_address (dev))
782             {
783                 ret = ftdi_usb_open_dev(ftdi, dev);
784                 libusb_free_device_list(devs,1);
785                 return ret;
786             }
787         }
788
789         // device not found
790         ftdi_error_return_free_device_list(-3, "device not found", devs);
791     }
792     else if (description[0] == 'i' || description[0] == 's')
793     {
794         unsigned int vendor;
795         unsigned int product;
796         unsigned int index=0;
797         const char *serial=NULL;
798         const char *startp, *endp;
799
800         errno=0;
801         startp=description+2;
802         vendor=strtoul((char*)startp,(char**)&endp,0);
803         if (*endp != ':' || endp == startp || errno != 0)
804             ftdi_error_return(-11, "illegal description format");
805
806         startp=endp+1;
807         product=strtoul((char*)startp,(char**)&endp,0);
808         if (endp == startp || errno != 0)
809             ftdi_error_return(-11, "illegal description format");
810
811         if (description[0] == 'i' && *endp != 0)
812         {
813             /* optional index field in i-mode */
814             if (*endp != ':')
815                 ftdi_error_return(-11, "illegal description format");
816
817             startp=endp+1;
818             index=strtoul((char*)startp,(char**)&endp,0);
819             if (*endp != 0 || endp == startp || errno != 0)
820                 ftdi_error_return(-11, "illegal description format");
821         }
822         if (description[0] == 's')
823         {
824             if (*endp != ':')
825                 ftdi_error_return(-11, "illegal description format");
826
827             /* rest of the description is the serial */
828             serial=endp+1;
829         }
830
831         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
832     }
833     else
834     {
835         ftdi_error_return(-11, "illegal description format");
836     }
837 }
838
839 /**
840     Resets the ftdi device.
841
842     \param ftdi pointer to ftdi_context
843
844     \retval  0: all fine
845     \retval -1: FTDI reset failed
846     \retval -2: USB device unavailable
847 */
848 int ftdi_usb_reset(struct ftdi_context *ftdi)
849 {
850     if (ftdi == NULL || ftdi->usb_dev == NULL)
851         ftdi_error_return(-2, "USB device unavailable");
852
853     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
854                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
855                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
856         ftdi_error_return(-1,"FTDI reset failed");
857
858     // Invalidate data in the readbuffer
859     ftdi->readbuffer_offset = 0;
860     ftdi->readbuffer_remaining = 0;
861
862     return 0;
863 }
864
865 /**
866     Clears the read buffer on the chip and the internal read buffer.
867
868     \param ftdi pointer to ftdi_context
869
870     \retval  0: all fine
871     \retval -1: read buffer purge failed
872     \retval -2: USB device unavailable
873 */
874 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
875 {
876     if (ftdi == NULL || ftdi->usb_dev == NULL)
877         ftdi_error_return(-2, "USB device unavailable");
878
879     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
880                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
881                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
882         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
883
884     // Invalidate data in the readbuffer
885     ftdi->readbuffer_offset = 0;
886     ftdi->readbuffer_remaining = 0;
887
888     return 0;
889 }
890
891 /**
892     Clears the write buffer on the chip.
893
894     \param ftdi pointer to ftdi_context
895
896     \retval  0: all fine
897     \retval -1: write buffer purge failed
898     \retval -2: USB device unavailable
899 */
900 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
901 {
902     if (ftdi == NULL || ftdi->usb_dev == NULL)
903         ftdi_error_return(-2, "USB device unavailable");
904
905     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
906                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
907                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
908         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
909
910     return 0;
911 }
912
913 /**
914     Clears the buffers on the chip and the internal read buffer.
915
916     \param ftdi pointer to ftdi_context
917
918     \retval  0: all fine
919     \retval -1: read buffer purge failed
920     \retval -2: write buffer purge failed
921     \retval -3: USB device unavailable
922 */
923 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
924 {
925     int result;
926
927     if (ftdi == NULL || ftdi->usb_dev == NULL)
928         ftdi_error_return(-3, "USB device unavailable");
929
930     result = ftdi_usb_purge_rx_buffer(ftdi);
931     if (result < 0)
932         return -1;
933
934     result = ftdi_usb_purge_tx_buffer(ftdi);
935     if (result < 0)
936         return -2;
937
938     return 0;
939 }
940
941
942
943 /**
944     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
945
946     \param ftdi pointer to ftdi_context
947
948     \retval  0: all fine
949     \retval -1: usb_release failed
950     \retval -3: ftdi context invalid
951 */
952 int ftdi_usb_close(struct ftdi_context *ftdi)
953 {
954     int rtn = 0;
955
956     if (ftdi == NULL)
957         ftdi_error_return(-3, "ftdi context invalid");
958
959     if (ftdi->usb_dev != NULL)
960         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
961             rtn = -1;
962
963     ftdi_usb_close_internal (ftdi);
964
965     return rtn;
966 }
967
968 /**
969     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
970     Function is only used internally
971     \internal
972 */
973 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
974                                  unsigned short *value, unsigned short *index)
975 {
976     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
977     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
978     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
979     int divisor, best_divisor, best_baud, best_baud_diff;
980     unsigned long encoded_divisor;
981     int i;
982
983     if (baudrate <= 0)
984     {
985         // Return error
986         return -1;
987     }
988
989     divisor = 24000000 / baudrate;
990
991     if (ftdi->type == TYPE_AM)
992     {
993         // Round down to supported fraction (AM only)
994         divisor -= am_adjust_dn[divisor & 7];
995     }
996
997     // Try this divisor and the one above it (because division rounds down)
998     best_divisor = 0;
999     best_baud = 0;
1000     best_baud_diff = 0;
1001     for (i = 0; i < 2; i++)
1002     {
1003         int try_divisor = divisor + i;
1004         int baud_estimate;
1005         int baud_diff;
1006
1007         // Round up to supported divisor value
1008         if (try_divisor <= 8)
1009         {
1010             // Round up to minimum supported divisor
1011             try_divisor = 8;
1012         }
1013         else if (ftdi->type != TYPE_AM && try_divisor < 12)
1014         {
1015             // BM doesn't support divisors 9 through 11 inclusive
1016             try_divisor = 12;
1017         }
1018         else if (divisor < 16)
1019         {
1020             // AM doesn't support divisors 9 through 15 inclusive
1021             try_divisor = 16;
1022         }
1023         else
1024         {
1025             if (ftdi->type == TYPE_AM)
1026             {
1027                 // Round up to supported fraction (AM only)
1028                 try_divisor += am_adjust_up[try_divisor & 7];
1029                 if (try_divisor > 0x1FFF8)
1030                 {
1031                     // Round down to maximum supported divisor value (for AM)
1032                     try_divisor = 0x1FFF8;
1033                 }
1034             }
1035             else
1036             {
1037                 if (try_divisor > 0x1FFFF)
1038                 {
1039                     // Round down to maximum supported divisor value (for BM)
1040                     try_divisor = 0x1FFFF;
1041                 }
1042             }
1043         }
1044         // Get estimated baud rate (to nearest integer)
1045         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1046         // Get absolute difference from requested baud rate
1047         if (baud_estimate < baudrate)
1048         {
1049             baud_diff = baudrate - baud_estimate;
1050         }
1051         else
1052         {
1053             baud_diff = baud_estimate - baudrate;
1054         }
1055         if (i == 0 || baud_diff < best_baud_diff)
1056         {
1057             // Closest to requested baud rate so far
1058             best_divisor = try_divisor;
1059             best_baud = baud_estimate;
1060             best_baud_diff = baud_diff;
1061             if (baud_diff == 0)
1062             {
1063                 // Spot on! No point trying
1064                 break;
1065             }
1066         }
1067     }
1068     // Encode the best divisor value
1069     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1070     // Deal with special cases for encoded value
1071     if (encoded_divisor == 1)
1072     {
1073         encoded_divisor = 0;    // 3000000 baud
1074     }
1075     else if (encoded_divisor == 0x4001)
1076     {
1077         encoded_divisor = 1;    // 2000000 baud (BM only)
1078     }
1079     // Split into "value" and "index" values
1080     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1081     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1082     {
1083         *index = (unsigned short)(encoded_divisor >> 8);
1084         *index &= 0xFF00;
1085         *index |= ftdi->index;
1086     }
1087     else
1088         *index = (unsigned short)(encoded_divisor >> 16);
1089
1090     // Return the nearest baud rate
1091     return best_baud;
1092 }
1093
1094 /**
1095     Sets the chip baud rate
1096
1097     \param ftdi pointer to ftdi_context
1098     \param baudrate baud rate to set
1099
1100     \retval  0: all fine
1101     \retval -1: invalid baudrate
1102     \retval -2: setting baudrate failed
1103     \retval -3: USB device unavailable
1104 */
1105 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1106 {
1107     unsigned short value, index;
1108     int actual_baudrate;
1109
1110     if (ftdi == NULL || ftdi->usb_dev == NULL)
1111         ftdi_error_return(-3, "USB device unavailable");
1112
1113     if (ftdi->bitbang_enabled)
1114     {
1115         baudrate = baudrate*4;
1116     }
1117
1118     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1119     if (actual_baudrate <= 0)
1120         ftdi_error_return (-1, "Silly baudrate <= 0.");
1121
1122     // Check within tolerance (about 5%)
1123     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1124             || ((actual_baudrate < baudrate)
1125                 ? (actual_baudrate * 21 < baudrate * 20)
1126                 : (baudrate * 21 < actual_baudrate * 20)))
1127         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1128
1129     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1130                                 SIO_SET_BAUDRATE_REQUEST, value,
1131                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1132         ftdi_error_return (-2, "Setting new baudrate failed");
1133
1134     ftdi->baudrate = baudrate;
1135     return 0;
1136 }
1137
1138 /**
1139     Set (RS232) line characteristics.
1140     The break type can only be set via ftdi_set_line_property2()
1141     and defaults to "off".
1142
1143     \param ftdi pointer to ftdi_context
1144     \param bits Number of bits
1145     \param sbit Number of stop bits
1146     \param parity Parity mode
1147
1148     \retval  0: all fine
1149     \retval -1: Setting line property failed
1150 */
1151 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1152                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1153 {
1154     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1155 }
1156
1157 /**
1158     Set (RS232) line characteristics
1159
1160     \param ftdi pointer to ftdi_context
1161     \param bits Number of bits
1162     \param sbit Number of stop bits
1163     \param parity Parity mode
1164     \param break_type Break type
1165
1166     \retval  0: all fine
1167     \retval -1: Setting line property failed
1168     \retval -2: USB device unavailable
1169 */
1170 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1171                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1172                             enum ftdi_break_type break_type)
1173 {
1174     unsigned short value = bits;
1175
1176     if (ftdi == NULL || ftdi->usb_dev == NULL)
1177         ftdi_error_return(-2, "USB device unavailable");
1178
1179     switch (parity)
1180     {
1181         case NONE:
1182             value |= (0x00 << 8);
1183             break;
1184         case ODD:
1185             value |= (0x01 << 8);
1186             break;
1187         case EVEN:
1188             value |= (0x02 << 8);
1189             break;
1190         case MARK:
1191             value |= (0x03 << 8);
1192             break;
1193         case SPACE:
1194             value |= (0x04 << 8);
1195             break;
1196     }
1197
1198     switch (sbit)
1199     {
1200         case STOP_BIT_1:
1201             value |= (0x00 << 11);
1202             break;
1203         case STOP_BIT_15:
1204             value |= (0x01 << 11);
1205             break;
1206         case STOP_BIT_2:
1207             value |= (0x02 << 11);
1208             break;
1209     }
1210
1211     switch (break_type)
1212     {
1213         case BREAK_OFF:
1214             value |= (0x00 << 14);
1215             break;
1216         case BREAK_ON:
1217             value |= (0x01 << 14);
1218             break;
1219     }
1220
1221     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1222                                 SIO_SET_DATA_REQUEST, value,
1223                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1224         ftdi_error_return (-1, "Setting new line property failed");
1225
1226     return 0;
1227 }
1228
1229 /**
1230     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1231
1232     \param ftdi pointer to ftdi_context
1233     \param buf Buffer with the data
1234     \param size Size of the buffer
1235
1236     \retval -666: USB device unavailable
1237     \retval <0: error code from usb_bulk_write()
1238     \retval >0: number of bytes written
1239 */
1240 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1241 {
1242     int offset = 0;
1243     int actual_length;
1244
1245     if (ftdi == NULL || ftdi->usb_dev == NULL)
1246         ftdi_error_return(-666, "USB device unavailable");
1247
1248     while (offset < size)
1249     {
1250         int write_size = ftdi->writebuffer_chunksize;
1251
1252         if (offset+write_size > size)
1253             write_size = size-offset;
1254
1255         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1256             ftdi_error_return(-1, "usb bulk write failed");
1257
1258         offset += actual_length;
1259     }
1260
1261     return offset;
1262 }
1263
1264 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1265 {
1266     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1267     struct ftdi_context *ftdi = tc->ftdi;
1268     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1269
1270     packet_size = ftdi->max_packet_size;
1271
1272     actual_length = transfer->actual_length;
1273
1274     if (actual_length > 2)
1275     {
1276         // skip FTDI status bytes.
1277         // Maybe stored in the future to enable modem use
1278         num_of_chunks = actual_length / packet_size;
1279         chunk_remains = actual_length % packet_size;
1280         //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1281
1282         ftdi->readbuffer_offset += 2;
1283         actual_length -= 2;
1284
1285         if (actual_length > packet_size - 2)
1286         {
1287             for (i = 1; i < num_of_chunks; i++)
1288               memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1289                        ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1290                        packet_size - 2);
1291             if (chunk_remains > 2)
1292             {
1293                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1294                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1295                          chunk_remains-2);
1296                 actual_length -= 2*num_of_chunks;
1297             }
1298             else
1299               actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1300         }
1301
1302         if (actual_length > 0)
1303         {
1304             // data still fits in buf?
1305             if (tc->offset + actual_length <= tc->size)
1306             {
1307                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1308                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1309                 tc->offset += actual_length;
1310
1311                 ftdi->readbuffer_offset = 0;
1312                 ftdi->readbuffer_remaining = 0;
1313
1314                 /* Did we read exactly the right amount of bytes? */
1315                 if (tc->offset == tc->size)
1316                 {
1317                     //printf("read_data exact rem %d offset %d\n",
1318                     //ftdi->readbuffer_remaining, offset);
1319                     tc->completed = 1;
1320                     return;
1321                 }
1322             }
1323             else
1324             {
1325                 // only copy part of the data or size <= readbuffer_chunksize
1326                 int part_size = tc->size - tc->offset;
1327                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1328                 tc->offset += part_size;
1329
1330                 ftdi->readbuffer_offset += part_size;
1331                 ftdi->readbuffer_remaining = actual_length - part_size;
1332
1333                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1334                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1335                 tc->completed = 1;
1336                 return;
1337             }
1338         }
1339     }
1340     ret = libusb_submit_transfer (transfer);
1341     if (ret < 0)
1342         tc->completed = 1;
1343 }
1344
1345
1346 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1347 {
1348     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1349     struct ftdi_context *ftdi = tc->ftdi;
1350     
1351     tc->offset += transfer->actual_length;
1352     
1353     if (tc->offset == tc->size)
1354     {
1355         tc->completed = 1;
1356     }
1357     else
1358     {
1359         int write_size = ftdi->writebuffer_chunksize;
1360         int ret;
1361
1362         if (tc->offset + write_size > tc->size)
1363             write_size = tc->size - tc->offset;
1364
1365         transfer->length = write_size;
1366         transfer->buffer = tc->buf + tc->offset;
1367         ret = libusb_submit_transfer (transfer);
1368         if (ret < 0)
1369             tc->completed = 1;
1370     }
1371 }
1372
1373
1374 /**
1375     Writes data to the chip. Does not wait for completion of the transfer
1376     nor does it make sure that the transfer was successful.
1377
1378     Use libusb 1.0 asynchronous API.
1379
1380     \param ftdi pointer to ftdi_context
1381     \param buf Buffer with the data
1382     \param size Size of the buffer
1383
1384     \retval NULL: Some error happens when submit transfer
1385     \retval !NULL: Pointer to a ftdi_transfer_control
1386 */
1387
1388 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1389 {
1390     struct ftdi_transfer_control *tc;
1391     struct libusb_transfer *transfer = libusb_alloc_transfer(0);
1392     int write_size, ret;
1393
1394     if (ftdi == NULL || ftdi->usb_dev == NULL)
1395     {
1396         libusb_free_transfer(transfer);
1397         return NULL;
1398     }
1399
1400     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1401
1402     if (!tc || !transfer)
1403         return NULL;
1404
1405     tc->ftdi = ftdi;
1406     tc->completed = 0;
1407     tc->buf = buf;
1408     tc->size = size;
1409     tc->offset = 0;
1410
1411     if (size < ftdi->writebuffer_chunksize)
1412       write_size = size;
1413     else
1414       write_size = ftdi->writebuffer_chunksize;
1415
1416     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1417                               write_size, ftdi_write_data_cb, tc,
1418                               ftdi->usb_write_timeout);
1419     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1420
1421     ret = libusb_submit_transfer(transfer);
1422     if (ret < 0)
1423     {
1424         libusb_free_transfer(transfer);
1425         tc->completed = 1;
1426         tc->transfer = NULL;
1427         return NULL;
1428     }
1429     tc->transfer = transfer;
1430
1431     return tc;
1432 }
1433
1434 /**
1435     Reads data from the chip. Does not wait for completion of the transfer
1436     nor does it make sure that the transfer was successful.
1437
1438     Use libusb 1.0 asynchronous API.
1439
1440     \param ftdi pointer to ftdi_context
1441     \param buf Buffer with the data
1442     \param size Size of the buffer
1443
1444     \retval NULL: Some error happens when submit transfer
1445     \retval !NULL: Pointer to a ftdi_transfer_control
1446 */
1447
1448 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1449 {
1450     struct ftdi_transfer_control *tc;
1451     struct libusb_transfer *transfer;
1452     int ret;
1453
1454     if (ftdi == NULL || ftdi->usb_dev == NULL)
1455         return NULL;
1456
1457     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1458     if (!tc)
1459         return NULL;
1460
1461     tc->ftdi = ftdi;
1462     tc->buf = buf;
1463     tc->size = size;
1464
1465     if (size <= ftdi->readbuffer_remaining)
1466     {
1467         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1468
1469         // Fix offsets
1470         ftdi->readbuffer_remaining -= size;
1471         ftdi->readbuffer_offset += size;
1472
1473         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1474
1475         tc->completed = 1;
1476         tc->offset = size;
1477         tc->transfer = NULL;
1478         return tc;
1479     }
1480
1481     tc->completed = 0;
1482     if (ftdi->readbuffer_remaining != 0)
1483     {
1484         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1485
1486         tc->offset = ftdi->readbuffer_remaining;
1487     }
1488     else
1489         tc->offset = 0;
1490
1491     transfer = libusb_alloc_transfer(0);
1492     if (!transfer)
1493     {
1494         free (tc);
1495         return NULL;
1496     }
1497
1498     ftdi->readbuffer_remaining = 0;
1499     ftdi->readbuffer_offset = 0;
1500
1501     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi_read_data_cb, tc, ftdi->usb_read_timeout);
1502     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1503
1504     ret = libusb_submit_transfer(transfer);
1505     if (ret < 0)
1506     {
1507         libusb_free_transfer(transfer);
1508         free (tc);
1509         return NULL;
1510     }
1511     tc->transfer = transfer;
1512
1513     return tc;
1514 }
1515
1516 /**
1517     Wait for completion of the transfer.
1518
1519     Use libusb 1.0 asynchronous API.
1520
1521     \param tc pointer to ftdi_transfer_control
1522
1523     \retval < 0: Some error happens
1524     \retval >= 0: Data size transferred
1525 */
1526
1527 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1528 {
1529     int ret;
1530
1531     while (!tc->completed)
1532     {
1533         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1534         if (ret < 0)
1535         {
1536             if (ret == LIBUSB_ERROR_INTERRUPTED)
1537                 continue;
1538             libusb_cancel_transfer(tc->transfer);
1539             while (!tc->completed)
1540                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1541                     break;
1542             libusb_free_transfer(tc->transfer);
1543             free (tc);
1544             return ret;
1545         }
1546     }
1547
1548     ret = tc->offset;
1549     /**
1550      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1551      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1552      **/
1553     if (tc->transfer)
1554     {
1555         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1556             ret = -1;
1557         libusb_free_transfer(tc->transfer);
1558     }
1559     free(tc);
1560     return ret;
1561 }
1562
1563 /**
1564     Configure write buffer chunk size.
1565     Default is 4096.
1566
1567     \param ftdi pointer to ftdi_context
1568     \param chunksize Chunk size
1569
1570     \retval 0: all fine
1571     \retval -1: ftdi context invalid
1572 */
1573 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1574 {
1575     if (ftdi == NULL)
1576         ftdi_error_return(-1, "ftdi context invalid");
1577
1578     ftdi->writebuffer_chunksize = chunksize;
1579     return 0;
1580 }
1581
1582 /**
1583     Get write buffer chunk size.
1584
1585     \param ftdi pointer to ftdi_context
1586     \param chunksize Pointer to store chunk size in
1587
1588     \retval 0: all fine
1589     \retval -1: ftdi context invalid
1590 */
1591 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1592 {
1593     if (ftdi == NULL)
1594         ftdi_error_return(-1, "ftdi context invalid");
1595
1596     *chunksize = ftdi->writebuffer_chunksize;
1597     return 0;
1598 }
1599
1600 /**
1601     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1602
1603     Automatically strips the two modem status bytes transfered during every read.
1604
1605     \param ftdi pointer to ftdi_context
1606     \param buf Buffer to store data in
1607     \param size Size of the buffer
1608
1609     \retval -666: USB device unavailable
1610     \retval <0: error code from libusb_bulk_transfer()
1611     \retval  0: no data was available
1612     \retval >0: number of bytes read
1613
1614 */
1615 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1616 {
1617     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1618     int packet_size = ftdi->max_packet_size;
1619     int actual_length = 1;
1620
1621     if (ftdi == NULL || ftdi->usb_dev == NULL)
1622         ftdi_error_return(-666, "USB device unavailable");
1623
1624     // Packet size sanity check (avoid division by zero)
1625     if (packet_size == 0)
1626         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1627
1628     // everything we want is still in the readbuffer?
1629     if (size <= ftdi->readbuffer_remaining)
1630     {
1631         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1632
1633         // Fix offsets
1634         ftdi->readbuffer_remaining -= size;
1635         ftdi->readbuffer_offset += size;
1636
1637         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1638
1639         return size;
1640     }
1641     // something still in the readbuffer, but not enough to satisfy 'size'?
1642     if (ftdi->readbuffer_remaining != 0)
1643     {
1644         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1645
1646         // Fix offset
1647         offset += ftdi->readbuffer_remaining;
1648     }
1649     // do the actual USB read
1650     while (offset < size && actual_length > 0)
1651     {
1652         ftdi->readbuffer_remaining = 0;
1653         ftdi->readbuffer_offset = 0;
1654         /* returns how much received */
1655         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1656         if (ret < 0)
1657             ftdi_error_return(ret, "usb bulk read failed");
1658
1659         if (actual_length > 2)
1660         {
1661             // skip FTDI status bytes.
1662             // Maybe stored in the future to enable modem use
1663             num_of_chunks = actual_length / packet_size;
1664             chunk_remains = actual_length % packet_size;
1665             //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1666
1667             ftdi->readbuffer_offset += 2;
1668             actual_length -= 2;
1669
1670             if (actual_length > packet_size - 2)
1671             {
1672                 for (i = 1; i < num_of_chunks; i++)
1673                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1674                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1675                              packet_size - 2);
1676                 if (chunk_remains > 2)
1677                 {
1678                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1679                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1680                              chunk_remains-2);
1681                     actual_length -= 2*num_of_chunks;
1682                 }
1683                 else
1684                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1685             }
1686         }
1687         else if (actual_length <= 2)
1688         {
1689             // no more data to read?
1690             return offset;
1691         }
1692         if (actual_length > 0)
1693         {
1694             // data still fits in buf?
1695             if (offset+actual_length <= size)
1696             {
1697                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1698                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1699                 offset += actual_length;
1700
1701                 /* Did we read exactly the right amount of bytes? */
1702                 if (offset == size)
1703                     //printf("read_data exact rem %d offset %d\n",
1704                     //ftdi->readbuffer_remaining, offset);
1705                     return offset;
1706             }
1707             else
1708             {
1709                 // only copy part of the data or size <= readbuffer_chunksize
1710                 int part_size = size-offset;
1711                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1712
1713                 ftdi->readbuffer_offset += part_size;
1714                 ftdi->readbuffer_remaining = actual_length-part_size;
1715                 offset += part_size;
1716
1717                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1718                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1719
1720                 return offset;
1721             }
1722         }
1723     }
1724     // never reached
1725     return -127;
1726 }
1727
1728 /**
1729     Configure read buffer chunk size.
1730     Default is 4096.
1731
1732     Automatically reallocates the buffer.
1733
1734     \param ftdi pointer to ftdi_context
1735     \param chunksize Chunk size
1736
1737     \retval 0: all fine
1738     \retval -1: ftdi context invalid
1739 */
1740 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1741 {
1742     unsigned char *new_buf;
1743
1744     if (ftdi == NULL)
1745         ftdi_error_return(-1, "ftdi context invalid");
1746
1747     // Invalidate all remaining data
1748     ftdi->readbuffer_offset = 0;
1749     ftdi->readbuffer_remaining = 0;
1750 #ifdef __linux__
1751     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1752        which is defined in libusb-1.0.  Otherwise, each USB read request will
1753        be divided into multiple URBs.  This will cause issues on Linux kernel
1754        older than 2.6.32.  */
1755     if (chunksize > 16384)
1756         chunksize = 16384;
1757 #endif
1758
1759     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1760         ftdi_error_return(-1, "out of memory for readbuffer");
1761
1762     ftdi->readbuffer = new_buf;
1763     ftdi->readbuffer_chunksize = chunksize;
1764
1765     return 0;
1766 }
1767
1768 /**
1769     Get read buffer chunk size.
1770
1771     \param ftdi pointer to ftdi_context
1772     \param chunksize Pointer to store chunk size in
1773
1774     \retval 0: all fine
1775     \retval -1: FTDI context invalid
1776 */
1777 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1778 {
1779     if (ftdi == NULL)
1780         ftdi_error_return(-1, "FTDI context invalid");
1781
1782     *chunksize = ftdi->readbuffer_chunksize;
1783     return 0;
1784 }
1785
1786
1787 /**
1788     Enable bitbang mode.
1789
1790     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1791
1792     \param ftdi pointer to ftdi_context
1793     \param bitmask Bitmask to configure lines.
1794            HIGH/ON value configures a line as output.
1795
1796     \retval  0: all fine
1797     \retval -1: can't enable bitbang mode
1798     \retval -2: USB device unavailable
1799 */
1800 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1801 {
1802     unsigned short usb_val;
1803
1804     if (ftdi == NULL || ftdi->usb_dev == NULL)
1805         ftdi_error_return(-2, "USB device unavailable");
1806
1807     usb_val = bitmask; // low byte: bitmask
1808     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1809     usb_val |= (ftdi->bitbang_mode << 8);
1810
1811     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1812                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1813                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1814         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1815
1816     ftdi->bitbang_enabled = 1;
1817     return 0;
1818 }
1819
1820 /**
1821     Disable bitbang mode.
1822
1823     \param ftdi pointer to ftdi_context
1824
1825     \retval  0: all fine
1826     \retval -1: can't disable bitbang mode
1827     \retval -2: USB device unavailable
1828 */
1829 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1830 {
1831     if (ftdi == NULL || ftdi->usb_dev == NULL)
1832         ftdi_error_return(-2, "USB device unavailable");
1833
1834     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1835         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1836
1837     ftdi->bitbang_enabled = 0;
1838     return 0;
1839 }
1840
1841 /**
1842     Enable/disable bitbang modes.
1843
1844     \param ftdi pointer to ftdi_context
1845     \param bitmask Bitmask to configure lines.
1846            HIGH/ON value configures a line as output.
1847     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1848
1849     \retval  0: all fine
1850     \retval -1: can't enable bitbang mode
1851     \retval -2: USB device unavailable
1852 */
1853 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1854 {
1855     unsigned short usb_val;
1856
1857     if (ftdi == NULL || ftdi->usb_dev == NULL)
1858         ftdi_error_return(-2, "USB device unavailable");
1859
1860     usb_val = bitmask; // low byte: bitmask
1861     usb_val |= (mode << 8);
1862     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1863         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1864
1865     ftdi->bitbang_mode = mode;
1866     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1867     return 0;
1868 }
1869
1870 /**
1871     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1872
1873     \param ftdi pointer to ftdi_context
1874     \param pins Pointer to store pins into
1875
1876     \retval  0: all fine
1877     \retval -1: read pins failed
1878     \retval -2: USB device unavailable
1879 */
1880 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1881 {
1882     if (ftdi == NULL || ftdi->usb_dev == NULL)
1883         ftdi_error_return(-2, "USB device unavailable");
1884
1885     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (unsigned char *)pins, 1, ftdi->usb_read_timeout) != 1)
1886         ftdi_error_return(-1, "read pins failed");
1887
1888     return 0;
1889 }
1890
1891 /**
1892     Set latency timer
1893
1894     The FTDI chip keeps data in the internal buffer for a specific
1895     amount of time if the buffer is not full yet to decrease
1896     load on the usb bus.
1897
1898     \param ftdi pointer to ftdi_context
1899     \param latency Value between 1 and 255
1900
1901     \retval  0: all fine
1902     \retval -1: latency out of range
1903     \retval -2: unable to set latency timer
1904     \retval -3: USB device unavailable
1905 */
1906 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1907 {
1908     unsigned short usb_val;
1909
1910     if (latency < 1)
1911         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1912
1913     if (ftdi == NULL || ftdi->usb_dev == NULL)
1914         ftdi_error_return(-3, "USB device unavailable");
1915
1916     usb_val = latency;
1917     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1918         ftdi_error_return(-2, "unable to set latency timer");
1919
1920     return 0;
1921 }
1922
1923 /**
1924     Get latency timer
1925
1926     \param ftdi pointer to ftdi_context
1927     \param latency Pointer to store latency value in
1928
1929     \retval  0: all fine
1930     \retval -1: unable to get latency timer
1931     \retval -2: USB device unavailable
1932 */
1933 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1934 {
1935     unsigned short usb_val;
1936
1937     if (ftdi == NULL || ftdi->usb_dev == NULL)
1938         ftdi_error_return(-2, "USB device unavailable");
1939
1940     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (unsigned char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1941         ftdi_error_return(-1, "reading latency timer failed");
1942
1943     *latency = (unsigned char)usb_val;
1944     return 0;
1945 }
1946
1947 /**
1948     Poll modem status information
1949
1950     This function allows the retrieve the two status bytes of the device.
1951     The device sends these bytes also as a header for each read access
1952     where they are discarded by ftdi_read_data(). The chip generates
1953     the two stripped status bytes in the absence of data every 40 ms.
1954
1955     Layout of the first byte:
1956     - B0..B3 - must be 0
1957     - B4       Clear to send (CTS)
1958                  0 = inactive
1959                  1 = active
1960     - B5       Data set ready (DTS)
1961                  0 = inactive
1962                  1 = active
1963     - B6       Ring indicator (RI)
1964                  0 = inactive
1965                  1 = active
1966     - B7       Receive line signal detect (RLSD)
1967                  0 = inactive
1968                  1 = active
1969
1970     Layout of the second byte:
1971     - B0       Data ready (DR)
1972     - B1       Overrun error (OE)
1973     - B2       Parity error (PE)
1974     - B3       Framing error (FE)
1975     - B4       Break interrupt (BI)
1976     - B5       Transmitter holding register (THRE)
1977     - B6       Transmitter empty (TEMT)
1978     - B7       Error in RCVR FIFO
1979
1980     \param ftdi pointer to ftdi_context
1981     \param status Pointer to store status information in. Must be two bytes.
1982
1983     \retval  0: all fine
1984     \retval -1: unable to retrieve status information
1985     \retval -2: USB device unavailable
1986 */
1987 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1988 {
1989     char usb_val[2];
1990
1991     if (ftdi == NULL || ftdi->usb_dev == NULL)
1992         ftdi_error_return(-2, "USB device unavailable");
1993
1994     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, (unsigned char *)usb_val, 2, ftdi->usb_read_timeout) != 2)
1995         ftdi_error_return(-1, "getting modem status failed");
1996
1997     *status = (usb_val[1] << 8) | usb_val[0];
1998
1999     return 0;
2000 }
2001
2002 /**
2003     Set flowcontrol for ftdi chip
2004
2005     \param ftdi pointer to ftdi_context
2006     \param flowctrl flow control to use. should be
2007            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
2008
2009     \retval  0: all fine
2010     \retval -1: set flow control failed
2011     \retval -2: USB device unavailable
2012 */
2013 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
2014 {
2015     if (ftdi == NULL || ftdi->usb_dev == NULL)
2016         ftdi_error_return(-2, "USB device unavailable");
2017
2018     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2019                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2020                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2021         ftdi_error_return(-1, "set flow control failed");
2022
2023     return 0;
2024 }
2025
2026 /**
2027     Set dtr line
2028
2029     \param ftdi pointer to ftdi_context
2030     \param state state to set line to (1 or 0)
2031
2032     \retval  0: all fine
2033     \retval -1: set dtr failed
2034     \retval -2: USB device unavailable
2035 */
2036 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2037 {
2038     unsigned short usb_val;
2039
2040     if (ftdi == NULL || ftdi->usb_dev == NULL)
2041         ftdi_error_return(-2, "USB device unavailable");
2042
2043     if (state)
2044         usb_val = SIO_SET_DTR_HIGH;
2045     else
2046         usb_val = SIO_SET_DTR_LOW;
2047
2048     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2049                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2050                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2051         ftdi_error_return(-1, "set dtr failed");
2052
2053     return 0;
2054 }
2055
2056 /**
2057     Set rts line
2058
2059     \param ftdi pointer to ftdi_context
2060     \param state state to set line to (1 or 0)
2061
2062     \retval  0: all fine
2063     \retval -1: set rts failed
2064     \retval -2: USB device unavailable
2065 */
2066 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2067 {
2068     unsigned short usb_val;
2069
2070     if (ftdi == NULL || ftdi->usb_dev == NULL)
2071         ftdi_error_return(-2, "USB device unavailable");
2072
2073     if (state)
2074         usb_val = SIO_SET_RTS_HIGH;
2075     else
2076         usb_val = SIO_SET_RTS_LOW;
2077
2078     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2079                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2080                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2081         ftdi_error_return(-1, "set of rts failed");
2082
2083     return 0;
2084 }
2085
2086 /**
2087     Set dtr and rts line in one pass
2088
2089     \param ftdi pointer to ftdi_context
2090     \param dtr  DTR state to set line to (1 or 0)
2091     \param rts  RTS state to set line to (1 or 0)
2092
2093     \retval  0: all fine
2094     \retval -1: set dtr/rts failed
2095     \retval -2: USB device unavailable
2096  */
2097 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2098 {
2099     unsigned short usb_val;
2100
2101     if (ftdi == NULL || ftdi->usb_dev == NULL)
2102         ftdi_error_return(-2, "USB device unavailable");
2103
2104     if (dtr)
2105         usb_val = SIO_SET_DTR_HIGH;
2106     else
2107         usb_val = SIO_SET_DTR_LOW;
2108
2109     if (rts)
2110         usb_val |= SIO_SET_RTS_HIGH;
2111     else
2112         usb_val |= SIO_SET_RTS_LOW;
2113
2114     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2115                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2116                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2117         ftdi_error_return(-1, "set of rts/dtr failed");
2118
2119     return 0;
2120 }
2121
2122 /**
2123     Set the special event character
2124
2125     \param ftdi pointer to ftdi_context
2126     \param eventch Event character
2127     \param enable 0 to disable the event character, non-zero otherwise
2128
2129     \retval  0: all fine
2130     \retval -1: unable to set event character
2131     \retval -2: USB device unavailable
2132 */
2133 int ftdi_set_event_char(struct ftdi_context *ftdi,
2134                         unsigned char eventch, unsigned char enable)
2135 {
2136     unsigned short usb_val;
2137
2138     if (ftdi == NULL || ftdi->usb_dev == NULL)
2139         ftdi_error_return(-2, "USB device unavailable");
2140
2141     usb_val = eventch;
2142     if (enable)
2143         usb_val |= 1 << 8;
2144
2145     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2146         ftdi_error_return(-1, "setting event character failed");
2147
2148     return 0;
2149 }
2150
2151 /**
2152     Set error character
2153
2154     \param ftdi pointer to ftdi_context
2155     \param errorch Error character
2156     \param enable 0 to disable the error character, non-zero otherwise
2157
2158     \retval  0: all fine
2159     \retval -1: unable to set error character
2160     \retval -2: USB device unavailable
2161 */
2162 int ftdi_set_error_char(struct ftdi_context *ftdi,
2163                         unsigned char errorch, unsigned char enable)
2164 {
2165     unsigned short usb_val;
2166
2167     if (ftdi == NULL || ftdi->usb_dev == NULL)
2168         ftdi_error_return(-2, "USB device unavailable");
2169
2170     usb_val = errorch;
2171     if (enable)
2172         usb_val |= 1 << 8;
2173
2174     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2175         ftdi_error_return(-1, "setting error character failed");
2176
2177     return 0;
2178 }
2179
2180 /**
2181     Init eeprom with default values.
2182     \param ftdi pointer to ftdi_context
2183     \param manufacturer String to use as Manufacturer
2184     \param product String to use as Product description
2185     \param serial String to use as Serial number description
2186     
2187     \retval  0: all fine
2188     \retval -1: No struct ftdi_context
2189     \retval -2: No struct ftdi_eeprom
2190 */
2191 int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, char * manufacturer,
2192                               char * product, char * serial)
2193 {
2194     struct ftdi_eeprom *eeprom;
2195
2196     if (ftdi == NULL)
2197         ftdi_error_return(-1, "No struct ftdi_context");
2198         
2199
2200     if (ftdi->eeprom == NULL)
2201         ftdi_error_return(-2,"No struct ftdi_eeprom"); 
2202
2203     eeprom = ftdi->eeprom;
2204     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2205
2206     eeprom->vendor_id = 0x0403;
2207     eeprom->use_serial = USE_SERIAL_NUM;
2208     if((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2209        (ftdi->type == TYPE_R))
2210         eeprom->product_id = 0x6001;
2211     else
2212         eeprom->product_id = 0x6010;
2213     if (ftdi->type == TYPE_AM)
2214         eeprom->usb_version = 0x0101;
2215     else
2216         eeprom->usb_version = 0x0200;
2217     eeprom->max_power = 50;
2218
2219     if (eeprom->manufacturer)
2220         free (eeprom->manufacturer);
2221     eeprom->manufacturer = NULL;
2222     if (manufacturer)
2223     {
2224         eeprom->manufacturer = malloc(strlen(manufacturer)+1);
2225         if (eeprom->manufacturer)
2226             strcpy(eeprom->manufacturer, manufacturer);
2227     }
2228
2229     if (eeprom->product)
2230         free (eeprom->product);
2231     eeprom->product = NULL;
2232     {
2233         eeprom->product = malloc(strlen(product)+1);
2234         if (eeprom->product)
2235             strcpy(eeprom->product, product);
2236     }
2237
2238     if (eeprom->serial)
2239         free (eeprom->serial);
2240     eeprom->serial = NULL;
2241     if (serial)
2242     {
2243         eeprom->serial = malloc(strlen(serial)+1);
2244         if (eeprom->serial)
2245             strcpy(eeprom->serial, serial);
2246     }
2247
2248
2249     if(ftdi->type == TYPE_R)
2250     {
2251         eeprom->max_power = 45;
2252         eeprom->size = 0x80;
2253         eeprom->cbus_function[0] = CBUS_TXLED;
2254         eeprom->cbus_function[1] = CBUS_RXLED;
2255         eeprom->cbus_function[2] = CBUS_TXDEN;
2256         eeprom->cbus_function[3] = CBUS_PWREN;
2257         eeprom->cbus_function[4] = CBUS_SLEEP;
2258     }
2259     else
2260         eeprom->size = -1;
2261     return 0;
2262 }
2263
2264 /**
2265     Build binary buffer from ftdi_eeprom structure.
2266     Output is suitable for ftdi_write_eeprom().
2267
2268     \param ftdi pointer to ftdi_context
2269
2270     \retval >0: free eeprom size
2271     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2272     \retval -2: Invalid eeprom pointer
2273     \retval -3: Invalid cbus function setting
2274     \retval -4: Chip doesn't support invert
2275     \retval -5: Chip doesn't support high current drive
2276     \retval -6: No connected EEPROM or EEPROM Type unknown
2277 */
2278 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2279 {
2280     unsigned char i, j, k;
2281     unsigned short checksum, value;
2282     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2283     int size_check;
2284     struct ftdi_eeprom *eeprom;
2285     unsigned char * output;
2286
2287     if (ftdi == NULL)
2288         ftdi_error_return(-2,"No context");
2289     if (ftdi->eeprom == NULL)
2290         ftdi_error_return(-2,"No eeprom structure");
2291
2292     eeprom= ftdi->eeprom;
2293     output = eeprom->buf;
2294
2295     if(eeprom->chip == -1)
2296         ftdi_error_return(-5,"No connected EEPROM or EEPROM Type unknown");
2297
2298     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2299         eeprom->size = 0x100;
2300     else
2301         eeprom->size = 0x80;
2302
2303     if (eeprom->manufacturer != NULL)
2304         manufacturer_size = strlen(eeprom->manufacturer);
2305     if (eeprom->product != NULL)
2306         product_size = strlen(eeprom->product);
2307     if (eeprom->serial != NULL)
2308         serial_size = strlen(eeprom->serial);
2309
2310     size_check = 0x80;
2311     switch(ftdi->type)
2312     {
2313     case TYPE_2232H:
2314     case TYPE_4232H:
2315         size_check -= 4;
2316     case TYPE_R:
2317         size_check -= 4;
2318     case TYPE_2232C:
2319         size_check -= 4;
2320     case TYPE_AM:
2321     case TYPE_BM:
2322         size_check -= 0x14*2;
2323     }
2324
2325     size_check -= manufacturer_size*2;
2326     size_check -= product_size*2;
2327     size_check -= serial_size*2;
2328
2329     /* Space for the string type and pointer bytes */
2330     size_check -= -9;
2331
2332     // eeprom size exceeded?
2333     if (size_check < 0)
2334         return (-1);
2335
2336     // empty eeprom
2337     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2338
2339     // Bytes and Bits set for all Types
2340
2341     // Addr 02: Vendor ID
2342     output[0x02] = eeprom->vendor_id;
2343     output[0x03] = eeprom->vendor_id >> 8;
2344
2345     // Addr 04: Product ID
2346     output[0x04] = eeprom->product_id;
2347     output[0x05] = eeprom->product_id >> 8;
2348
2349     // Addr 06: Device release number (0400h for BM features)
2350     output[0x06] = 0x00;
2351     switch (ftdi->type) {
2352         case TYPE_AM:
2353             output[0x07] = 0x02;
2354             break;
2355         case TYPE_BM:
2356             output[0x07] = 0x04;
2357             break;
2358         case TYPE_2232C:
2359             output[0x07] = 0x05;
2360             break;
2361         case TYPE_R:
2362             output[0x07] = 0x06;
2363             break;
2364          case TYPE_2232H:
2365             output[0x07] = 0x07;
2366             break;
2367          case TYPE_4232H:
2368             output[0x07] = 0x08;
2369             break;
2370         default:
2371             output[0x07] = 0x00;
2372     }
2373
2374     // Addr 08: Config descriptor
2375     // Bit 7: always 1
2376     // Bit 6: 1 if this device is self powered, 0 if bus powered
2377     // Bit 5: 1 if this device uses remote wakeup
2378     // Bit 4: 1 if this device is battery powered
2379     j = 0x80;
2380     if (eeprom->self_powered == 1)
2381         j |= 0x40;
2382     if (eeprom->remote_wakeup == 1)
2383         j |= 0x20;
2384     output[0x08] = j;
2385
2386     // Addr 09: Max power consumption: max power = value * 2 mA
2387     output[0x09] = eeprom->max_power>>1;
2388
2389     if(ftdi->type != TYPE_AM)
2390     {
2391         // Addr 0A: Chip configuration
2392         // Bit 7: 0 - reserved
2393         // Bit 6: 0 - reserved
2394         // Bit 5: 0 - reserved
2395         // Bit 4: 1 - Change USB version 
2396         // Bit 3: 1 - Use the serial number string
2397         // Bit 2: 1 - Enable suspend pull downs for lower power
2398         // Bit 1: 1 - Out EndPoint is Isochronous
2399         // Bit 0: 1 - In EndPoint is Isochronous
2400         //
2401         j = 0;
2402         if (eeprom->in_is_isochronous == 1)
2403             j = j | 1;
2404         if (eeprom->out_is_isochronous == 1)
2405             j = j | 2;
2406         output[0x0A] = j;
2407     }
2408
2409     // Dynamic content
2410     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2411     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2412     i = 0;
2413     switch(ftdi->type)
2414     {
2415     case TYPE_2232H:
2416     case TYPE_4232H:
2417         i += 2;
2418     case TYPE_R:
2419         i += 2;
2420     case TYPE_2232C:
2421         i += 2;
2422     case TYPE_AM:
2423     case TYPE_BM:
2424         i += 0x94;
2425     }
2426     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2427     k = eeprom->size -1;
2428
2429     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2430     // Addr 0F: Length of manufacturer string
2431     // Output manufacturer
2432     output[0x0E] = i;  // calculate offset
2433     output[i++ & k] = manufacturer_size*2 + 2;
2434     output[i++ & k] = 0x03; // type: string
2435     for (j = 0; j < manufacturer_size; j++)
2436     {
2437         output[i & k] = eeprom->manufacturer[j], i++;
2438         output[i & k] = 0x00, i++;
2439     }
2440     output[0x0F] = manufacturer_size*2 + 2;
2441
2442     // Addr 10: Offset of the product string + 0x80, calculated later
2443     // Addr 11: Length of product string
2444     output[0x10] = i | 0x80;  // calculate offset
2445     output[i & k] = product_size*2 + 2, i++;
2446     output[i & k] = 0x03, i++;
2447     for (j = 0; j < product_size; j++)
2448     {
2449         output[i & k] = eeprom->product[j], i++;
2450         output[i & k] = 0x00, i++;
2451     }
2452     output[0x11] = product_size*2 + 2;
2453     
2454     // Addr 12: Offset of the serial string + 0x80, calculated later
2455     // Addr 13: Length of serial string
2456     output[0x12] = i | 0x80; // calculate offset
2457     output[i & k] = serial_size*2 + 2, i++;
2458     output[i & k] = 0x03, i++;
2459     for (j = 0; j < serial_size; j++)
2460     {
2461         output[i & k] = eeprom->serial[j], i++;
2462         output[i & k] = 0x00, i++;
2463     }
2464     output[i & k] = 0x02; /* as seen when written with FTD2XX */
2465     i++;
2466     output[i & k] = 0x03; /* as seen when written with FTD2XX */
2467     i++;
2468     output[i & k] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2469     i++;
2470
2471     output[0x13] = serial_size*2 + 2;
2472
2473     if(ftdi->type > TYPE_AM) /*use_serial not used in AM devices*/
2474     {
2475         if (eeprom->use_serial == USE_SERIAL_NUM )
2476             output[0x0A] |= USE_SERIAL_NUM;
2477         else
2478             output[0x0A] &= ~USE_SERIAL_NUM;
2479     }
2480     /* Fixme: ftd2xx seems to append 0x02, 0x03 and 0x01 for PnP = 0 or 0x00 else */
2481     // calculate checksum
2482
2483     /* Bytes and Bits specific to (some) types
2484        Write linear, as this allows easier fixing*/
2485     switch(ftdi->type)
2486     {
2487     case TYPE_AM:
2488         break;
2489     case TYPE_BM:
2490         output[0x0C] = eeprom->usb_version & 0xff;
2491         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2492         output[0x14] = eeprom->chip;
2493         break;
2494     case TYPE_2232C:
2495
2496         output[0x00] = (eeprom->channel_a_type);
2497         if ( eeprom->channel_a_driver == DRIVER_VCP)
2498             output[0x00] |= DRIVER_VCP;
2499         else
2500             output[0x00] &= ~DRIVER_VCP;
2501             
2502         if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2503             output[0x00] |= HIGH_CURRENT_DRIVE;
2504         else
2505             output[0x00] &= ~HIGH_CURRENT_DRIVE;
2506
2507         output[0x01] = (eeprom->channel_b_type);
2508         if ( eeprom->channel_b_driver == DRIVER_VCP)
2509             output[0x01] |= DRIVER_VCP;
2510         else
2511             output[0x01] &= ~DRIVER_VCP;
2512             
2513         if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2514             output[0x01] |= HIGH_CURRENT_DRIVE;
2515         else
2516             output[0x01] &= ~HIGH_CURRENT_DRIVE;
2517
2518         if (eeprom->in_is_isochronous == 1)
2519             output[0x0A] |= 0x1;
2520         else
2521             output[0x0A] &= ~0x1;
2522         if (eeprom->out_is_isochronous == 1)
2523             output[0x0A] |= 0x2;
2524         else
2525             output[0x0A] &= ~0x2;
2526         if (eeprom->suspend_pull_downs == 1)
2527             output[0x0A] |= 0x4;
2528         else
2529             output[0x0A] &= ~0x4;
2530         output[0x0C] = eeprom->usb_version & 0xff;
2531         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2532         output[0x14] = eeprom->chip;
2533         break;
2534     case TYPE_R:
2535         if(eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2536             output[0x00] |= HIGH_CURRENT_DRIVE_R;
2537         output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2538         
2539         if (eeprom->suspend_pull_downs == 1)
2540             output[0x0A] |= 0x4;
2541         else
2542             output[0x0A] &= ~0x4;
2543         output[0x0B] = eeprom->invert;
2544         output[0x0C] = eeprom->usb_version & 0xff;
2545         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2546         
2547         if(eeprom->cbus_function[0] > CBUS_BB)
2548             output[0x14] = CBUS_TXLED;
2549         else
2550             output[0x14] = eeprom->cbus_function[0];
2551         
2552         if(eeprom->cbus_function[1] > CBUS_BB)
2553             output[0x14] |= CBUS_RXLED<<4;
2554         else
2555             output[0x14] |= eeprom->cbus_function[1]<<4;
2556         
2557         if(eeprom->cbus_function[2] > CBUS_BB)
2558             output[0x15] = CBUS_TXDEN;
2559         else
2560             output[0x15] = eeprom->cbus_function[2];
2561         
2562         if(eeprom->cbus_function[3] > CBUS_BB)
2563             output[0x15] |= CBUS_PWREN<<4;
2564         else
2565             output[0x15] |= eeprom->cbus_function[3]<<4;
2566         
2567         if(eeprom->cbus_function[4] > CBUS_CLK6)
2568             output[0x16] = CBUS_SLEEP;
2569         else
2570             output[0x16] = eeprom->cbus_function[4];
2571         break;
2572     case TYPE_2232H:
2573         output[0x00] = (eeprom->channel_a_type);
2574         if ( eeprom->channel_a_driver == DRIVER_VCP)
2575             output[0x00] |= DRIVER_VCP;
2576         else
2577             output[0x00] &= ~DRIVER_VCP;
2578         
2579         output[0x01] = (eeprom->channel_b_type);
2580         if ( eeprom->channel_b_driver == DRIVER_VCP)
2581             output[0x01] |= DRIVER_VCP;
2582         else
2583             output[0x01] &= ~DRIVER_VCP;
2584         if(eeprom->suspend_dbus7 == SUSPEND_DBUS7)
2585             output[0x01] |= SUSPEND_DBUS7;
2586         else
2587             output[0x01] &= ~SUSPEND_DBUS7;
2588         
2589         if(eeprom->group0_drive > DRIVE_16MA)
2590             output[0x0c] |= DRIVE_16MA;
2591         else
2592             output[0x0c] |= eeprom->group0_drive;
2593         if (eeprom->group0_schmitt == IS_SCHMITT)
2594             output[0x0c] |= IS_SCHMITT;
2595         if (eeprom->group0_slew == SLOW_SLEW)
2596             output[0x0c] |= SLOW_SLEW;
2597
2598         if(eeprom->group1_drive > DRIVE_16MA)
2599             output[0x0c] |= DRIVE_16MA<<4;
2600         else
2601             output[0x0c] |= eeprom->group1_drive<<4;
2602         if (eeprom->group1_schmitt == IS_SCHMITT)
2603             output[0x0c] |= IS_SCHMITT<<4;
2604         if (eeprom->group1_slew == SLOW_SLEW)
2605             output[0x0c] |= SLOW_SLEW<<4;
2606         
2607         if(eeprom->group2_drive > DRIVE_16MA)
2608             output[0x0d] |= DRIVE_16MA;
2609         else
2610             output[0x0d] |= eeprom->group2_drive;
2611         if (eeprom->group2_schmitt == IS_SCHMITT)
2612             output[0x0d] |= IS_SCHMITT;
2613         if (eeprom->group2_slew == SLOW_SLEW)
2614             output[0x0d] |= SLOW_SLEW;
2615
2616         if(eeprom->group3_drive > DRIVE_16MA)
2617             output[0x0d] |= DRIVE_16MA<<4;
2618         else
2619             output[0x0d] |= eeprom->group3_drive<<4;
2620         if (eeprom->group3_schmitt == IS_SCHMITT)
2621             output[0x0d] |= IS_SCHMITT<<4;
2622         if (eeprom->group3_slew == SLOW_SLEW)
2623             output[0x0d] |= SLOW_SLEW<<4;
2624
2625         output[0x18] = eeprom->chip;
2626
2627         break;
2628     }
2629
2630     // calculate checksum
2631     checksum = 0xAAAA;
2632
2633     for (i = 0; i < eeprom->size/2-1; i++)
2634     {
2635         value = output[i*2];
2636         value += output[(i*2)+1] << 8;
2637
2638         checksum = value^checksum;
2639         checksum = (checksum << 1) | (checksum >> 15);
2640     }
2641
2642     output[eeprom->size-2] = checksum;
2643     output[eeprom->size-1] = checksum >> 8;
2644
2645     return size_check;
2646 }
2647
2648 /**
2649    Decode binary EEPROM image into an ftdi_eeprom structure.
2650
2651    \param ftdi pointer to ftdi_context
2652    \param verbose Decode EEPROM on stdout
2653    
2654    \retval 0: all fine
2655    \retval -1: something went wrong
2656
2657    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2658    FIXME: Strings are malloc'ed here and should be freed somewhere
2659 */
2660 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2661 {
2662     unsigned char i, j;
2663     unsigned short checksum, eeprom_checksum, value;
2664     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2665     int eeprom_size;
2666     struct ftdi_eeprom *eeprom;
2667     unsigned char *buf = ftdi->eeprom->buf;
2668     int release;
2669
2670     if (ftdi == NULL)
2671         ftdi_error_return(-1,"No context");
2672     if (ftdi->eeprom == NULL)
2673         ftdi_error_return(-1,"No eeprom structure");
2674  
2675     eeprom = ftdi->eeprom;
2676     eeprom_size = eeprom->size;
2677
2678     // Addr 02: Vendor ID
2679     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2680
2681     // Addr 04: Product ID
2682     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2683
2684     release = buf[0x06] + (buf[0x07]<<8);
2685
2686     // Addr 08: Config descriptor
2687     // Bit 7: always 1
2688     // Bit 6: 1 if this device is self powered, 0 if bus powered
2689     // Bit 5: 1 if this device uses remote wakeup
2690     // Bit 4: 1 if this device is battery powered
2691     eeprom->self_powered = buf[0x08] & 0x40;
2692     eeprom->remote_wakeup = buf[0x08] & 0x20;;
2693
2694     // Addr 09: Max power consumption: max power = value * 2 mA
2695     eeprom->max_power = buf[0x09];
2696
2697     // Addr 0A: Chip configuration
2698     // Bit 7: 0 - reserved
2699     // Bit 6: 0 - reserved
2700     // Bit 5: 0 - reserved
2701     // Bit 4: 1 - Change USB version
2702     //            Not seen on FT2232(D)
2703     // Bit 3: 1 - Use the serial number string
2704     // Bit 2: 1 - Enable suspend pull downs for lower power
2705     // Bit 1: 1 - Out EndPoint is Isochronous
2706     // Bit 0: 1 - In EndPoint is Isochronous
2707     //
2708     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2709     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2710     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2711     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2712     if(buf[0x0A]&0x10)
2713         fprintf(stderr,
2714                 "EEPROM byte[0x0a] Bit 4 unexpected set. If this happened with the EEPROM\n"
2715                 "programmed by FTDI tools, please report to libftdi@developer.intra2net.com\n");
2716
2717
2718     // Addr 0C: USB version low byte when 0x0A
2719     // Addr 0D: USB version high byte when 0x0A 
2720     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2721
2722     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2723     // Addr 0F: Length of manufacturer string
2724     manufacturer_size = buf[0x0F]/2;
2725     if(eeprom->manufacturer)
2726         free(eeprom->manufacturer);
2727     if (manufacturer_size > 0) 
2728     {
2729         eeprom->manufacturer = malloc(manufacturer_size);
2730         if (eeprom->manufacturer)
2731         {
2732             // Decode manufacturer
2733             i = buf[0x0E] & (eeprom_size -1); // offset
2734             for (j=0;j<manufacturer_size-1;j++)
2735             {
2736                 eeprom->manufacturer[j] = buf[2*j+i+2];
2737             }
2738             eeprom->manufacturer[j] = '\0';
2739         }
2740     }
2741     else eeprom->manufacturer = NULL;
2742
2743     // Addr 10: Offset of the product string + 0x80, calculated later
2744     // Addr 11: Length of product string
2745     if(eeprom->product)
2746         free(eeprom->product);
2747     product_size = buf[0x11]/2;
2748     if (product_size > 0)
2749     {
2750         eeprom->product = malloc(product_size);
2751         if(eeprom->product)
2752         {
2753             // Decode product name
2754             i = buf[0x10] & (eeprom_size -1); // offset
2755             for (j=0;j<product_size-1;j++)
2756             {
2757                 eeprom->product[j] = buf[2*j+i+2];
2758             }
2759             eeprom->product[j] = '\0';
2760         }
2761     }
2762     else eeprom->product = NULL;
2763
2764     // Addr 12: Offset of the serial string + 0x80, calculated later
2765     // Addr 13: Length of serial string
2766     if(eeprom->serial)
2767         free(eeprom->serial);
2768     serial_size = buf[0x13]/2;
2769     if (serial_size > 0)
2770     {
2771         eeprom->serial = malloc(serial_size);
2772         if(eeprom->serial)
2773         {
2774             // Decode serial
2775             i = buf[0x12] & (eeprom_size -1); // offset
2776             for (j=0;j<serial_size-1;j++)
2777             {
2778                 eeprom->serial[j] = buf[2*j+i+2];
2779             }
2780             eeprom->serial[j] = '\0';
2781         }
2782     }
2783     else eeprom->serial = NULL;
2784
2785     // verify checksum
2786     checksum = 0xAAAA;
2787
2788     for (i = 0; i < eeprom_size/2-1; i++)
2789     {
2790         value = buf[i*2];
2791         value += buf[(i*2)+1] << 8;
2792
2793         checksum = value^checksum;
2794         checksum = (checksum << 1) | (checksum >> 15);
2795     }
2796
2797     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2798
2799     if (eeprom_checksum != checksum)
2800     {
2801         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2802         ftdi_error_return(-1,"EEPROM checksum error");
2803     }
2804
2805     eeprom->channel_a_type   = 0;
2806     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2807     {
2808         eeprom->chip = -1;
2809     }
2810     else if(ftdi->type == TYPE_2232C)
2811     {
2812         eeprom->channel_a_type   = buf[0x00] & 0x7;
2813         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2814         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2815         eeprom->channel_b_type   = buf[0x01] & 0x7;
2816         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2817         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2818         eeprom->chip = buf[0x14];
2819     }
2820     else if(ftdi->type == TYPE_R)
2821     {
2822         /* TYPE_R flags D2XX, not VCP as all others*/
2823         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2824         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2825         if( (buf[0x01]&0x40) != 0x40)
2826         fprintf(stderr,
2827                 "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
2828                 " If this happened with the\n"
2829                 " EEPROM programmed by FTDI tools, please report "
2830                 "to libftdi@developer.intra2net.com\n");
2831
2832         eeprom->chip = buf[0x16];
2833         // Addr 0B: Invert data lines
2834         // Works only on FT232R, not FT245R, but no way to distinguish
2835         eeprom->invert = buf[0x0B];
2836         // Addr 14: CBUS function: CBUS0, CBUS1
2837         // Addr 15: CBUS function: CBUS2, CBUS3
2838         // Addr 16: CBUS function: CBUS5
2839         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
2840         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
2841         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
2842         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
2843         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
2844     }
2845     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H)) 
2846     {
2847         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2848         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2849         eeprom->channel_b_type   = buf[0x01] & 0x7;
2850         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2851
2852         if(ftdi->type == TYPE_2232H)
2853             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7;
2854
2855         eeprom->chip = buf[0x18];
2856         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2857         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2858         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2859         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
2860         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
2861         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
2862         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
2863         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
2864         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
2865         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
2866         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
2867         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
2868     }
2869     
2870     if(verbose)
2871     {
2872         char *channel_mode[] = {"UART","245","CPU", "unknown", "OPTO"};
2873         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
2874         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
2875         fprintf(stdout, "Release: 0x%04x\n",release);
2876
2877         if(eeprom->self_powered)
2878             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
2879         else
2880             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
2881                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
2882         if(eeprom->manufacturer)
2883             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
2884         if(eeprom->product)
2885             fprintf(stdout, "Product:      %s\n",eeprom->product);
2886         if(eeprom->serial)
2887             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
2888         fprintf(stdout,     "Checksum      : %04x\n", checksum);
2889         if (ftdi->type == TYPE_R)
2890             fprintf(stdout,     "Internal EEPROM\n");
2891         else if (eeprom->chip >= 0x46)
2892             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
2893         if(eeprom->suspend_dbus7)
2894             fprintf(stdout, "Suspend on DBUS7\n");            
2895         if(eeprom->suspend_pull_downs)
2896             fprintf(stdout, "Pull IO pins low during suspend\n");
2897         if(eeprom->remote_wakeup)
2898             fprintf(stdout, "Enable Remote Wake Up\n");
2899         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
2900         if (ftdi->type >= TYPE_2232C)
2901             fprintf(stdout,"Channel A has Mode %s%s%s\n", 
2902                     channel_mode[eeprom->channel_a_type],
2903                     (eeprom->channel_a_driver)?" VCP":"",
2904                     (eeprom->high_current_a)?" High Current IO":"");
2905         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R)) 
2906             fprintf(stdout,"Channel B has Mode %s%s%s\n", 
2907                     channel_mode[eeprom->channel_b_type],
2908                     (eeprom->channel_b_driver)?" VCP":"",
2909                     (eeprom->high_current_b)?" High Current IO":"");
2910         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H)) 
2911         {
2912             fprintf(stdout,"%s has %d mA drive%s%s\n",
2913                     (ftdi->type == TYPE_2232H)?"AL":"A",
2914                     (eeprom->group0_drive+1) *4,
2915                     (eeprom->group0_schmitt)?" Schmitt Input":"",
2916                     (eeprom->group0_slew)?" Slow Slew":"");
2917             fprintf(stdout,"%s has %d mA drive%s%s\n",
2918                     (ftdi->type == TYPE_2232H)?"AH":"B",
2919                     (eeprom->group1_drive+1) *4,
2920                     (eeprom->group1_schmitt)?" Schmitt Input":"",
2921                     (eeprom->group1_slew)?" Slow Slew":"");
2922             fprintf(stdout,"%s has %d mA drive%s%s\n",
2923                     (ftdi->type == TYPE_2232H)?"BL":"C",
2924                     (eeprom->group2_drive+1) *4,
2925                     (eeprom->group2_schmitt)?" Schmitt Input":"",
2926                     (eeprom->group2_slew)?" Slow Slew":"");
2927             fprintf(stdout,"%s has %d mA drive%s%s\n",
2928                     (ftdi->type == TYPE_2232H)?"BH":"D",
2929                     (eeprom->group3_drive+1) *4,
2930                     (eeprom->group3_schmitt)?" Schmitt Input":"",
2931                     (eeprom->group3_slew)?" Slow Slew":"");
2932         }
2933         if (ftdi->type == TYPE_R)
2934         {
2935             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
2936                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
2937                                 "IOMODE","BB_WR","BB_RD"};
2938             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
2939             int i;
2940             
2941             if(eeprom->invert)
2942             { 
2943                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
2944                 fprintf(stdout,"Inverted bits:");
2945                 for (i=0; i<8; i++)
2946                     if((eeprom->invert & (1<<i)) == (1<<i))
2947                         fprintf(stdout," %s",r_bits[i]);
2948                 fprintf(stdout,"\n");
2949             }
2950             for(i=0; i<5; i++)
2951             {
2952                 if(eeprom->cbus_function[i]<CBUS_BB)
2953                     fprintf(stdout,"C%d Function: %s\n", i,
2954                             cbus_mux[eeprom->cbus_function[i]]);
2955                 else
2956                     fprintf(stdout,"C%d BB Function: %s\n", i,
2957                             cbus_BB[i]);
2958             }
2959         }
2960     }
2961     return 0;
2962 }
2963
2964 /**
2965     Read eeprom location
2966
2967     \param ftdi pointer to ftdi_context
2968     \param eeprom_addr Address of eeprom location to be read
2969     \param eeprom_val Pointer to store read eeprom location
2970
2971     \retval  0: all fine
2972     \retval -1: read failed
2973     \retval -2: USB device unavailable
2974 */
2975 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2976 {
2977     if (ftdi == NULL || ftdi->usb_dev == NULL)
2978         ftdi_error_return(-2, "USB device unavailable");
2979
2980     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (unsigned char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
2981         ftdi_error_return(-1, "reading eeprom failed");
2982
2983     return 0;
2984 }
2985
2986 /**
2987     Read eeprom
2988
2989     \param ftdi pointer to ftdi_context
2990
2991     \retval  0: all fine
2992     \retval -1: read failed
2993     \retval -2: USB device unavailable
2994 */
2995 int ftdi_read_eeprom(struct ftdi_context *ftdi)
2996 {
2997     int i;
2998     unsigned char *buf;
2999
3000     if (ftdi == NULL || ftdi->usb_dev == NULL)
3001         ftdi_error_return(-2, "USB device unavailable");
3002     buf = ftdi->eeprom->buf;
3003
3004     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3005     {
3006         if (libusb_control_transfer(
3007                 ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3008                 buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3009             ftdi_error_return(-1, "reading eeprom failed");
3010     }
3011
3012     if (ftdi->type == TYPE_R)
3013         ftdi->eeprom->size = 0x80;
3014     /*    Guesses size of eeprom by comparing halves 
3015           - will not work with blank eeprom */
3016     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3017         ftdi->eeprom->size = -1;
3018     else if(memcmp(buf,&buf[0x80],0x80) == 0)
3019         ftdi->eeprom->size = 0x80;
3020     else if(memcmp(buf,&buf[0x40],0x40) == 0)
3021         ftdi->eeprom->size = 0x40;
3022     else
3023         ftdi->eeprom->size = 0x100;
3024     return 0;
3025 }
3026
3027 /*
3028     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3029     Function is only used internally
3030     \internal
3031 */
3032 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3033 {
3034     return ((value & 1) << 1) |
3035            ((value & 2) << 5) |
3036            ((value & 4) >> 2) |
3037            ((value & 8) << 4) |
3038            ((value & 16) >> 1) |
3039            ((value & 32) >> 1) |
3040            ((value & 64) >> 4) |
3041            ((value & 128) >> 2);
3042 }
3043
3044 /**
3045     Read the FTDIChip-ID from R-type devices
3046
3047     \param ftdi pointer to ftdi_context
3048     \param chipid Pointer to store FTDIChip-ID
3049
3050     \retval  0: all fine
3051     \retval -1: read failed
3052     \retval -2: USB device unavailable
3053 */
3054 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3055 {
3056     unsigned int a = 0, b = 0;
3057
3058     if (ftdi == NULL || ftdi->usb_dev == NULL)
3059         ftdi_error_return(-2, "USB device unavailable");
3060
3061     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (unsigned char *)&a, 2, ftdi->usb_read_timeout) == 2)
3062     {
3063         a = a << 8 | a >> 8;
3064         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (unsigned char *)&b, 2, ftdi->usb_read_timeout) == 2)
3065         {
3066             b = b << 8 | b >> 8;
3067             a = (a << 16) | (b & 0xFFFF);
3068             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3069                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3070             *chipid = a ^ 0xa5f0f7d1;
3071             return 0;
3072         }
3073     }
3074
3075     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3076 }
3077
3078 /**
3079     Write eeprom location
3080
3081     \param ftdi pointer to ftdi_context
3082     \param eeprom_addr Address of eeprom location to be written
3083     \param eeprom_val Value to be written
3084
3085     \retval  0: all fine
3086     \retval -1: read failed
3087     \retval -2: USB device unavailable
3088 */
3089 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
3090 {
3091     if (ftdi == NULL || ftdi->usb_dev == NULL)
3092         ftdi_error_return(-2, "USB device unavailable");
3093
3094     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3095                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3096                                     NULL, 0, ftdi->usb_write_timeout) != 0)
3097         ftdi_error_return(-1, "unable to write eeprom");
3098
3099     return 0;
3100 }
3101
3102 /**
3103     Write eeprom
3104
3105     \param ftdi pointer to ftdi_context
3106  
3107     \retval  0: all fine
3108     \retval -1: read failed
3109     \retval -2: USB device unavailable
3110 */
3111 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3112 {
3113     unsigned short usb_val, status;
3114     int i, ret;
3115     unsigned char *eeprom;
3116
3117     if (ftdi == NULL || ftdi->usb_dev == NULL)
3118         ftdi_error_return(-2, "USB device unavailable");
3119     eeprom = ftdi->eeprom->buf;
3120
3121     /* These commands were traced while running MProg */
3122     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3123         return ret;
3124     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3125         return ret;
3126     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3127         return ret;
3128
3129     for (i = 0; i < ftdi->eeprom->size/2; i++)
3130     {
3131         usb_val = eeprom[i*2];
3132         usb_val += eeprom[(i*2)+1] << 8;
3133         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3134                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3135                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3136             ftdi_error_return(-1, "unable to write eeprom");
3137     }
3138
3139     return 0;
3140 }
3141
3142 /**
3143     Erase eeprom
3144
3145     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3146
3147     \param ftdi pointer to ftdi_context
3148
3149     \retval  0: all fine
3150     \retval -1: erase failed
3151     \retval -2: USB device unavailable
3152     \retval -3: Writing magic failed
3153     \retval -4: Read EEPROM failed
3154     \retval -5: Unexpected EEPROM value
3155 */
3156 #define MAGIC 0x55aa
3157 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3158 {
3159     unsigned short eeprom_value;
3160     if (ftdi == NULL || ftdi->usb_dev == NULL)
3161         ftdi_error_return(-2, "USB device unavailable");
3162
3163     if(ftdi->type == TYPE_R)
3164     {
3165         ftdi->eeprom->chip = 0;
3166         return 0;
3167     }
3168
3169     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 
3170                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3171         ftdi_error_return(-1, "unable to erase eeprom");
3172
3173     
3174     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3175        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3176        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3177        Chip is 93x66 if magic is only read at word position 0xc0*/
3178     if( ftdi_write_eeprom_location(ftdi, 0xc0, MAGIC))
3179         ftdi_error_return(-3, "Writing magic failed");
3180     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value)) 
3181         ftdi_error_return(-4, "Reading failed failed");
3182     if(eeprom_value == MAGIC)
3183     {
3184         ftdi->eeprom->chip = 0x46;
3185     }
3186     else 
3187     {
3188         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value)) 
3189             ftdi_error_return(-4, "Reading failed failed");
3190         if(eeprom_value == MAGIC)
3191             ftdi->eeprom->chip = 0x56;
3192         else 
3193         {
3194             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value)) 
3195                 ftdi_error_return(-4, "Reading failed failed");
3196             if(eeprom_value == MAGIC)
3197                 ftdi->eeprom->chip = 0x66;
3198             else
3199             {
3200                 ftdi->eeprom->chip = -1;
3201             }
3202         }
3203     }
3204     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 
3205                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3206         ftdi_error_return(-1, "unable to erase eeprom");
3207     return 0;
3208 }
3209
3210 /**
3211     Get string representation for last error code
3212
3213     \param ftdi pointer to ftdi_context
3214
3215     \retval Pointer to error string
3216 */
3217 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3218 {
3219     if (ftdi == NULL)
3220         return "";
3221
3222     return ftdi->error_str;
3223 }
3224
3225 /* @} end of doxygen libftdi group */