libftdi: (tomj) added ftdi_usb_get_strings function from external patch
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003 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/de/produkte/opensource/ftdi/
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 <usb.h>
32 #include <string.h>
33 #include <errno.h>
34
35 #include "ftdi.h"
36
37 #define ftdi_error_return(code, str) do {  \
38         ftdi->error_str = str;             \
39         return code;                       \
40    } while(0);
41
42
43 /**
44     Initializes a ftdi_context.
45
46     \param ftdi pointer to ftdi_context
47
48     \retval  0: all fine
49     \retval -1: couldn't allocate read buffer
50
51     \remark This should be called before all functions
52 */
53 int ftdi_init(struct ftdi_context *ftdi)
54 {
55     ftdi->usb_dev = NULL;
56     ftdi->usb_read_timeout = 5000;
57     ftdi->usb_write_timeout = 5000;
58
59     ftdi->type = TYPE_BM;    /* chip type */
60     ftdi->baudrate = -1;
61     ftdi->bitbang_enabled = 0;
62
63     ftdi->readbuffer = NULL;
64     ftdi->readbuffer_offset = 0;
65     ftdi->readbuffer_remaining = 0;
66     ftdi->writebuffer_chunksize = 4096;
67
68     ftdi->interface = 0;
69     ftdi->index = 0;
70     ftdi->in_ep = 0x02;
71     ftdi->out_ep = 0x81;
72     ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
73
74     ftdi->error_str = NULL;
75
76     /* All fine. Now allocate the readbuffer */
77     return ftdi_read_data_set_chunksize(ftdi, 4096);
78 }
79
80 /**
81     Open selected channels on a chip, otherwise use first channel.
82
83     \param ftdi pointer to ftdi_context
84     \param interface Interface to use for FT2232C chips.
85
86     \retval  0: all fine
87     \retval -1: unknown interface
88 */
89 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
90 {
91     switch (interface) {
92     case INTERFACE_ANY:
93     case INTERFACE_A:
94         /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
95         break;
96     case INTERFACE_B:
97         ftdi->interface = 1;
98         ftdi->index     = INTERFACE_B;
99         ftdi->in_ep     = 0x04;
100         ftdi->out_ep    = 0x83;
101         break;
102     default:
103         ftdi_error_return(-1, "Unknown interface");
104     }
105     return 0;
106 }
107
108 /**
109     Deinitializes a ftdi_context.
110
111     \param ftdi pointer to ftdi_context
112 */
113 void ftdi_deinit(struct ftdi_context *ftdi)
114 {
115     if (ftdi->readbuffer != NULL) {
116         free(ftdi->readbuffer);
117         ftdi->readbuffer = NULL;
118     }
119 }
120
121 /**
122     Use an already open libusb device.
123
124     \param ftdi pointer to ftdi_context
125     \param usb libusb usb_dev_handle to use
126 */
127 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
128 {
129     ftdi->usb_dev = usb;
130 }
131
132
133 /**
134     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
135     needs to be deallocated by ftdi_list_free() after use.
136
137     \param ftdi pointer to ftdi_context
138     \param devlist Pointer where to store list of found devices
139     \param vendor Vendor ID to search for
140     \param product Product ID to search for
141
142     \retval >0: number of devices found
143     \retval -1: usb_find_busses() failed
144     \retval -2: usb_find_devices() failed
145     \retval -3: out of memory
146 */
147 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
148 {
149     struct ftdi_device_list **curdev;
150     struct usb_bus *bus;
151     struct usb_device *dev;
152     int count = 0;
153
154     usb_init();
155     if (usb_find_busses() < 0)
156         ftdi_error_return(-1, "usb_find_busses() failed");
157     if (usb_find_devices() < 0)
158         ftdi_error_return(-2, "usb_find_devices() failed");
159
160     curdev = devlist;
161     for (bus = usb_busses; bus; bus = bus->next) {
162         for (dev = bus->devices; dev; dev = dev->next) {
163             if (dev->descriptor.idVendor == vendor
164                     && dev->descriptor.idProduct == product)
165             {
166                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
167                 if (!*curdev)
168                     ftdi_error_return(-3, "out of memory");
169
170                 (*curdev)->next = NULL;
171                 (*curdev)->dev = dev;
172
173                 curdev = &(*curdev)->next;
174                 count++;
175             }
176         }
177     }
178
179     return count;
180 }
181
182 /**
183     Frees a usb device list.
184
185     \param devlist USB device list created by ftdi_usb_find_all()
186 */
187 void ftdi_list_free(struct ftdi_device_list **devlist)
188 {
189     struct ftdi_device_list **curdev;
190     for (; *devlist == NULL; devlist = curdev) {
191         curdev = &(*devlist)->next;
192         free(*devlist);
193     }
194
195     devlist = NULL;
196 }
197
198 /**
199     Return device ID strings from the usb device.
200
201     The parameters manufacturer, description and serial may be NULL
202     or pointer to buffers to store the fetched strings.
203
204     \param ftdi pointer to ftdi_context
205     \param dev libusb usb_dev to use
206     \param manufacturer Store manufacturer string here if not NULL
207     \param mnf_len Buffer size of manufacturer string
208     \param description Store product description string here if not NULL
209     \param desc_len Buffer size of product description string
210     \param serial Store serial string here if not NULL
211     \param serial_len Buffer size of serial string
212
213     \retval   0: all fine
214     \retval  -1: wrong arguments
215     \retval  -4: unable to open device
216     \retval  -7: get product manufacturer failed
217     \retval  -8: get product description failed
218     \retval  -9: get serial number failed
219     \retval -10: unable to close device
220 */
221 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
222         char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
223 {
224     if ((ftdi==NULL) || (dev==NULL))
225         return -1;
226
227     if (!(ftdi->usb_dev = usb_open(dev)))
228         ftdi_error_return(-4, usb_strerror());
229
230     if (manufacturer != NULL) {
231         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0) {
232             usb_close (ftdi->usb_dev);
233             ftdi_error_return(-7, usb_strerror());
234         }
235     }
236
237     if (description != NULL) {
238         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0) {
239             usb_close (ftdi->usb_dev);
240             ftdi_error_return(-8, usb_strerror());
241         }
242     }
243
244     if (serial != NULL) {
245         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0) {
246             usb_close (ftdi->usb_dev);
247             ftdi_error_return(-9, usb_strerror());
248         }
249     }
250
251     if (usb_close (ftdi->usb_dev) != 0)
252         ftdi_error_return(-10, usb_strerror());
253
254     return 0;
255 }
256
257 /**
258     Opens a ftdi device given by a usb_device.
259
260     \param ftdi pointer to ftdi_context
261     \param dev libusb usb_dev to use
262
263     \retval  0: all fine
264     \retval -4: unable to open device
265     \retval -5: unable to claim device
266     \retval -6: reset failed
267     \retval -7: set baudrate failed
268 */
269 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
270 {
271     int detach_errno = 0;
272     if (!(ftdi->usb_dev = usb_open(dev)))
273         ftdi_error_return(-4, "usb_open() failed");
274
275 #ifdef LIBUSB_HAS_GET_DRIVER_NP
276     // Try to detach ftdi_sio kernel module
277     // Returns ENODATA if driver is not loaded
278     if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
279         detach_errno = errno;
280 #endif
281
282     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
283         usb_close (ftdi->usb_dev);
284         if (detach_errno == EPERM) {
285             ftdi_error_return(-8, "inappropriate permissions on device!");
286         } else {
287             ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
288         }
289     }
290
291     if (ftdi_usb_reset (ftdi) != 0) {
292         usb_close (ftdi->usb_dev);
293         ftdi_error_return(-6, "ftdi_usb_reset failed");
294     }
295
296     if (ftdi_set_baudrate (ftdi, 9600) != 0) {
297         usb_close (ftdi->usb_dev);
298         ftdi_error_return(-7, "set baudrate failed");
299     }
300
301     // Try to guess chip type
302     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
303     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
304             && dev->descriptor.iSerialNumber == 0))
305         ftdi->type = TYPE_BM;
306     else if (dev->descriptor.bcdDevice == 0x200)
307         ftdi->type = TYPE_AM;
308     else if (dev->descriptor.bcdDevice == 0x500) {
309         ftdi->type = TYPE_2232C;
310         if (!ftdi->index)
311             ftdi->index = INTERFACE_A;
312     }
313
314     ftdi_error_return(0, "all fine");
315 }
316
317 /**
318     Opens the first device with a given vendor and product ids.
319
320     \param ftdi pointer to ftdi_context
321     \param vendor Vendor ID
322     \param product Product ID
323
324     \retval same as ftdi_usb_open_desc()
325 */
326 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
327 {
328     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
329 }
330
331 /**
332     Opens the first device with a given, vendor id, product id,
333     description and serial.
334
335     \param ftdi pointer to ftdi_context
336     \param vendor Vendor ID
337     \param product Product ID
338     \param description Description to search for. Use NULL if not needed.
339     \param serial Serial to search for. Use NULL if not needed.
340
341     \retval  0: all fine
342     \retval -1: usb_find_busses() failed
343     \retval -2: usb_find_devices() failed
344     \retval -3: usb device not found
345     \retval -4: unable to open device
346     \retval -5: unable to claim device
347     \retval -6: reset failed
348     \retval -7: set baudrate failed
349     \retval -8: get product description failed
350     \retval -9: get serial number failed
351     \retval -10: unable to close device
352 */
353 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
354                        const char* description, const char* serial)
355 {
356     struct usb_bus *bus;
357     struct usb_device *dev;
358     char string[256];
359
360     usb_init();
361
362     if (usb_find_busses() < 0)
363         ftdi_error_return(-1, "usb_find_busses() failed");
364     if (usb_find_devices() < 0)
365         ftdi_error_return(-2, "usb_find_devices() failed");
366
367     for (bus = usb_busses; bus; bus = bus->next) {
368         for (dev = bus->devices; dev; dev = dev->next) {
369             if (dev->descriptor.idVendor == vendor
370                     && dev->descriptor.idProduct == product) {
371                 if (!(ftdi->usb_dev = usb_open(dev)))
372                     ftdi_error_return(-4, "usb_open() failed");
373
374                 if (description != NULL) {
375                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
376                         usb_close (ftdi->usb_dev);
377                         ftdi_error_return(-8, "unable to fetch product description");
378                     }
379                     if (strncmp(string, description, sizeof(string)) != 0) {
380                         if (usb_close (ftdi->usb_dev) != 0)
381                             ftdi_error_return(-10, "unable to close device");
382                         continue;
383                     }
384                 }
385                 if (serial != NULL) {
386                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
387                         usb_close (ftdi->usb_dev);
388                         ftdi_error_return(-9, "unable to fetch serial number");
389                     }
390                     if (strncmp(string, serial, sizeof(string)) != 0) {
391                         if (usb_close (ftdi->usb_dev) != 0)
392                             ftdi_error_return(-10, "unable to close device");
393                         continue;
394                     }
395                 }
396
397                 if (usb_close (ftdi->usb_dev) != 0)
398                     ftdi_error_return(-10, "unable to close device");
399
400                 return ftdi_usb_open_dev(ftdi, dev);
401             }
402         }
403     }
404
405     // device not found
406     ftdi_error_return(-3, "device not found");
407 }
408
409 /**
410     Resets the ftdi device.
411
412     \param ftdi pointer to ftdi_context
413
414     \retval  0: all fine
415     \retval -1: FTDI reset failed
416 */
417 int ftdi_usb_reset(struct ftdi_context *ftdi)
418 {
419     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
420         ftdi_error_return(-1,"FTDI reset failed");
421
422     // Invalidate data in the readbuffer
423     ftdi->readbuffer_offset = 0;
424     ftdi->readbuffer_remaining = 0;
425
426     return 0;
427 }
428
429 /**
430     Clears the buffers on the chip.
431
432     \param ftdi pointer to ftdi_context
433
434     \retval  0: all fine
435     \retval -1: write buffer purge failed
436     \retval -2: read buffer purge failed
437 */
438 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
439 {
440     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
441         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
442
443     // Invalidate data in the readbuffer
444     ftdi->readbuffer_offset = 0;
445     ftdi->readbuffer_remaining = 0;
446
447     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
448         ftdi_error_return(-2, "FTDI purge of TX buffer failed");
449
450     return 0;
451 }
452
453 /**
454     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
455
456     \param ftdi pointer to ftdi_context
457
458     \retval  0: all fine
459     \retval -1: usb_release failed
460     \retval -2: usb_close failed
461 */
462 int ftdi_usb_close(struct ftdi_context *ftdi)
463 {
464     int rtn = 0;
465
466     if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
467         rtn = -1;
468
469     if (usb_close (ftdi->usb_dev) != 0)
470         rtn = -2;
471
472     return rtn;
473 }
474
475 /*
476     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
477     Function is only used internally
478     \internal
479 */
480 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
481                                  unsigned short *value, unsigned short *index)
482 {
483     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
484     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
485     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
486     int divisor, best_divisor, best_baud, best_baud_diff;
487     unsigned long encoded_divisor;
488     int i;
489
490     if (baudrate <= 0) {
491         // Return error
492         return -1;
493     }
494
495     divisor = 24000000 / baudrate;
496
497     if (ftdi->type == TYPE_AM) {
498         // Round down to supported fraction (AM only)
499         divisor -= am_adjust_dn[divisor & 7];
500     }
501
502     // Try this divisor and the one above it (because division rounds down)
503     best_divisor = 0;
504     best_baud = 0;
505     best_baud_diff = 0;
506     for (i = 0; i < 2; i++) {
507         int try_divisor = divisor + i;
508         int baud_estimate;
509         int baud_diff;
510
511         // Round up to supported divisor value
512         if (try_divisor <= 8) {
513             // Round up to minimum supported divisor
514             try_divisor = 8;
515         } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
516             // BM doesn't support divisors 9 through 11 inclusive
517             try_divisor = 12;
518         } else if (divisor < 16) {
519             // AM doesn't support divisors 9 through 15 inclusive
520             try_divisor = 16;
521         } else {
522             if (ftdi->type == TYPE_AM) {
523                 // Round up to supported fraction (AM only)
524                 try_divisor += am_adjust_up[try_divisor & 7];
525                 if (try_divisor > 0x1FFF8) {
526                     // Round down to maximum supported divisor value (for AM)
527                     try_divisor = 0x1FFF8;
528                 }
529             } else {
530                 if (try_divisor > 0x1FFFF) {
531                     // Round down to maximum supported divisor value (for BM)
532                     try_divisor = 0x1FFFF;
533                 }
534             }
535         }
536         // Get estimated baud rate (to nearest integer)
537         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
538         // Get absolute difference from requested baud rate
539         if (baud_estimate < baudrate) {
540             baud_diff = baudrate - baud_estimate;
541         } else {
542             baud_diff = baud_estimate - baudrate;
543         }
544         if (i == 0 || baud_diff < best_baud_diff) {
545             // Closest to requested baud rate so far
546             best_divisor = try_divisor;
547             best_baud = baud_estimate;
548             best_baud_diff = baud_diff;
549             if (baud_diff == 0) {
550                 // Spot on! No point trying
551                 break;
552             }
553         }
554     }
555     // Encode the best divisor value
556     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
557     // Deal with special cases for encoded value
558     if (encoded_divisor == 1) {
559         encoded_divisor = 0;    // 3000000 baud
560     } else if (encoded_divisor == 0x4001) {
561         encoded_divisor = 1;    // 2000000 baud (BM only)
562     }
563     // Split into "value" and "index" values
564     *value = (unsigned short)(encoded_divisor & 0xFFFF);
565     if(ftdi->type == TYPE_2232C) {
566         *index = (unsigned short)(encoded_divisor >> 8);
567         *index &= 0xFF00;
568         *index |= ftdi->index;
569     }
570     else
571         *index = (unsigned short)(encoded_divisor >> 16);
572
573     // Return the nearest baud rate
574     return best_baud;
575 }
576
577 /**
578     Sets the chip baud rate
579
580     \param ftdi pointer to ftdi_context
581     \param baudrate baud rate to set
582
583     \retval  0: all fine
584     \retval -1: invalid baudrate
585     \retval -2: setting baudrate failed
586 */
587 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
588 {
589     unsigned short value, index;
590     int actual_baudrate;
591
592     if (ftdi->bitbang_enabled) {
593         baudrate = baudrate*4;
594     }
595
596     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
597     if (actual_baudrate <= 0)
598         ftdi_error_return (-1, "Silly baudrate <= 0.");
599
600     // Check within tolerance (about 5%)
601     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
602             || ((actual_baudrate < baudrate)
603                 ? (actual_baudrate * 21 < baudrate * 20)
604                 : (baudrate * 21 < actual_baudrate * 20)))
605         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
606
607     if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
608         ftdi_error_return (-2, "Setting new baudrate failed");
609
610     ftdi->baudrate = baudrate;
611     return 0;
612 }
613
614 /**
615     Set (RS232) line characteristics by Alain Abbas
616
617     \param ftdi pointer to ftdi_context
618     \param bits Number of bits
619     \param sbit Number of stop bits
620     \param parity Parity mode
621
622     \retval  0: all fine
623     \retval -1: Setting line property failed
624 */
625 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
626                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
627 {
628     unsigned short value = bits;
629
630     switch(parity) {
631     case NONE:
632         value |= (0x00 << 8);
633         break;
634     case ODD:
635         value |= (0x01 << 8);
636         break;
637     case EVEN:
638         value |= (0x02 << 8);
639         break;
640     case MARK:
641         value |= (0x03 << 8);
642         break;
643     case SPACE:
644         value |= (0x04 << 8);
645         break;
646     }
647
648     switch(sbit) {
649     case STOP_BIT_1:
650         value |= (0x00 << 11);
651         break;
652     case STOP_BIT_15:
653         value |= (0x01 << 11);
654         break;
655     case STOP_BIT_2:
656         value |= (0x02 << 11);
657         break;
658     }
659
660     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
661         ftdi_error_return (-1, "Setting new line property failed");
662
663     return 0;
664 }
665
666 /**
667     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
668
669     \param ftdi pointer to ftdi_context
670     \param buf Buffer with the data
671     \param size Size of the buffer
672
673     \retval <0: error code from usb_bulk_write()
674     \retval >0: number of bytes written
675 */
676 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
677 {
678     int ret;
679     int offset = 0;
680     int total_written = 0;
681
682     while (offset < size) {
683         int write_size = ftdi->writebuffer_chunksize;
684
685         if (offset+write_size > size)
686             write_size = size-offset;
687
688         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
689         if (ret < 0)
690             ftdi_error_return(ret, "usb bulk write failed");
691
692         total_written += ret;
693         offset += write_size;
694     }
695
696     return total_written;
697 }
698
699 /**
700     Configure write buffer chunk size.
701     Default is 4096.
702
703     \param ftdi pointer to ftdi_context
704     \param chunksize Chunk size
705
706     \retval 0: all fine
707 */
708 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
709 {
710     ftdi->writebuffer_chunksize = chunksize;
711     return 0;
712 }
713
714 /**
715     Get write buffer chunk size.
716
717     \param ftdi pointer to ftdi_context
718     \param chunksize Pointer to store chunk size in
719
720     \retval 0: all fine
721 */
722 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
723 {
724     *chunksize = ftdi->writebuffer_chunksize;
725     return 0;
726 }
727
728 /**
729     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
730
731     Automatically strips the two modem status bytes transfered during every read.
732
733     \param ftdi pointer to ftdi_context
734     \param buf Buffer to store data in
735     \param size Size of the buffer
736
737     \retval <0: error code from usb_bulk_read()
738     \retval >0: number of bytes read
739
740     \remark This function is not useful in bitbang mode.
741             Use ftdi_read_pins() to get the current state of the pins.
742 */
743 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
744 {
745     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
746
747     // everything we want is still in the readbuffer?
748     if (size <= ftdi->readbuffer_remaining) {
749         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
750
751         // Fix offsets
752         ftdi->readbuffer_remaining -= size;
753         ftdi->readbuffer_offset += size;
754
755         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
756
757         return size;
758     }
759     // something still in the readbuffer, but not enough to satisfy 'size'?
760     if (ftdi->readbuffer_remaining != 0) {
761         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
762
763         // Fix offset
764         offset += ftdi->readbuffer_remaining;
765     }
766     // do the actual USB read
767     while (offset < size && ret > 0) {
768         ftdi->readbuffer_remaining = 0;
769         ftdi->readbuffer_offset = 0;
770         /* returns how much received */
771         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
772         if (ret < 0)
773             ftdi_error_return(ret, "usb bulk read failed");
774
775         if (ret > 2) {
776             // skip FTDI status bytes.
777             // Maybe stored in the future to enable modem use
778             num_of_chunks = ret / 64;
779             chunk_remains = ret % 64;
780             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
781
782             ftdi->readbuffer_offset += 2;
783             ret -= 2;
784
785             if (ret > 62) {
786                 for (i = 1; i < num_of_chunks; i++)
787                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
788                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
789                              62);
790                 if (chunk_remains > 2) {
791                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
792                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
793                              chunk_remains-2);
794                     ret -= 2*num_of_chunks;
795                 } else
796                     ret -= 2*(num_of_chunks-1)+chunk_remains;
797             }
798         } else if (ret <= 2) {
799             // no more data to read?
800             return offset;
801         }
802         if (ret > 0) {
803             // data still fits in buf?
804             if (offset+ret <= size) {
805                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
806                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
807                 offset += ret;
808
809                 /* Did we read exactly the right amount of bytes? */
810                 if (offset == size)
811                     //printf("read_data exact rem %d offset %d\n",
812                     //ftdi->readbuffer_remaining, offset);
813                     return offset;
814             } else {
815                 // only copy part of the data or size <= readbuffer_chunksize
816                 int part_size = size-offset;
817                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
818
819                 ftdi->readbuffer_offset += part_size;
820                 ftdi->readbuffer_remaining = ret-part_size;
821                 offset += part_size;
822
823                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
824                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
825
826                 return offset;
827             }
828         }
829     }
830     // never reached
831     return -127;
832 }
833
834 /**
835     Configure read buffer chunk size.
836     Default is 4096.
837
838     Automatically reallocates the buffer.
839
840     \param ftdi pointer to ftdi_context
841     \param chunksize Chunk size
842
843     \retval 0: all fine
844 */
845 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
846 {
847     unsigned char *new_buf;
848
849     // Invalidate all remaining data
850     ftdi->readbuffer_offset = 0;
851     ftdi->readbuffer_remaining = 0;
852
853     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
854         ftdi_error_return(-1, "out of memory for readbuffer");
855
856     ftdi->readbuffer = new_buf;
857     ftdi->readbuffer_chunksize = chunksize;
858
859     return 0;
860 }
861
862 /**
863     Get read buffer chunk size.
864
865     \param ftdi pointer to ftdi_context
866     \param chunksize Pointer to store chunk size in
867
868     \retval 0: all fine
869 */
870 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
871 {
872     *chunksize = ftdi->readbuffer_chunksize;
873     return 0;
874 }
875
876
877 /**
878     Enable bitbang mode.
879
880     For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
881
882     \param ftdi pointer to ftdi_context
883     \param bitmask Bitmask to configure lines.
884            HIGH/ON value configures a line as output.
885
886     \retval  0: all fine
887     \retval -1: can't enable bitbang mode
888 */
889 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
890 {
891     unsigned short usb_val;
892
893     usb_val = bitmask; // low byte: bitmask
894     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
895     usb_val |= (ftdi->bitbang_mode << 8);
896
897     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
898         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
899
900     ftdi->bitbang_enabled = 1;
901     return 0;
902 }
903
904 /**
905     Disable bitbang mode.
906
907     \param ftdi pointer to ftdi_context
908
909     \retval  0: all fine
910     \retval -1: can't disable bitbang mode
911 */
912 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
913 {
914     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
915         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
916
917     ftdi->bitbang_enabled = 0;
918     return 0;
919 }
920
921 /**
922     Enable advanced bitbang mode for FT2232C chips.
923
924     \param ftdi pointer to ftdi_context
925     \param bitmask Bitmask to configure lines.
926            HIGH/ON value configures a line as output.
927     \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
928
929     \retval  0: all fine
930     \retval -1: can't enable bitbang mode
931 */
932 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
933 {
934     unsigned short usb_val;
935
936     usb_val = bitmask; // low byte: bitmask
937     usb_val |= (mode << 8);
938     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
939         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
940
941     ftdi->bitbang_mode = mode;
942     ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
943     return 0;
944 }
945
946 /**
947     Directly read pin state. Useful for bitbang mode.
948
949     \param ftdi pointer to ftdi_context
950     \param pins Pointer to store pins into
951
952     \retval  0: all fine
953     \retval -1: read pins failed
954 */
955 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
956 {
957     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
958         ftdi_error_return(-1, "read pins failed");
959
960     return 0;
961 }
962
963 /**
964     Set latency timer
965
966     The FTDI chip keeps data in the internal buffer for a specific
967     amount of time if the buffer is not full yet to decrease
968     load on the usb bus.
969
970     \param ftdi pointer to ftdi_context
971     \param latency Value between 1 and 255
972
973     \retval  0: all fine
974     \retval -1: latency out of range
975     \retval -2: unable to set latency timer
976 */
977 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
978 {
979     unsigned short usb_val;
980
981     if (latency < 1)
982         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
983
984     usb_val = latency;
985     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
986         ftdi_error_return(-2, "unable to set latency timer");
987
988     return 0;
989 }
990
991 /**
992     Get latency timer
993
994     \param ftdi pointer to ftdi_context
995     \param latency Pointer to store latency value in
996
997     \retval  0: all fine
998     \retval -1: unable to get latency timer
999 */
1000 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1001 {
1002     unsigned short usb_val;
1003     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1004         ftdi_error_return(-1, "reading latency timer failed");
1005
1006     *latency = (unsigned char)usb_val;
1007     return 0;
1008 }
1009
1010 /**
1011     Init eeprom with default values.
1012
1013     \param eeprom Pointer to ftdi_eeprom
1014 */
1015 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1016 {
1017     eeprom->vendor_id = 0x0403;
1018     eeprom->product_id = 0x6001;
1019
1020     eeprom->self_powered = 1;
1021     eeprom->remote_wakeup = 1;
1022     eeprom->BM_type_chip = 1;
1023
1024     eeprom->in_is_isochronous = 0;
1025     eeprom->out_is_isochronous = 0;
1026     eeprom->suspend_pull_downs = 0;
1027
1028     eeprom->use_serial = 0;
1029     eeprom->change_usb_version = 0;
1030     eeprom->usb_version = 0x0200;
1031     eeprom->max_power = 0;
1032
1033     eeprom->manufacturer = NULL;
1034     eeprom->product = NULL;
1035     eeprom->serial = NULL;
1036 }
1037
1038 /**
1039    Build binary output from ftdi_eeprom structure.
1040    Output is suitable for ftdi_write_eeprom().
1041
1042    \param eeprom Pointer to ftdi_eeprom
1043    \param output Buffer of 128 bytes to store eeprom image to
1044
1045    \retval >0: used eeprom size
1046    \retval -1: eeprom size (128 bytes) exceeded by custom strings
1047 */
1048 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1049 {
1050     unsigned char i, j;
1051     unsigned short checksum, value;
1052     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1053     int size_check;
1054
1055     if (eeprom->manufacturer != NULL)
1056         manufacturer_size = strlen(eeprom->manufacturer);
1057     if (eeprom->product != NULL)
1058         product_size = strlen(eeprom->product);
1059     if (eeprom->serial != NULL)
1060         serial_size = strlen(eeprom->serial);
1061
1062     size_check = 128; // eeprom is 128 bytes
1063     size_check -= 28; // 28 are always in use (fixed)
1064     size_check -= manufacturer_size*2;
1065     size_check -= product_size*2;
1066     size_check -= serial_size*2;
1067
1068     // eeprom size exceeded?
1069     if (size_check < 0)
1070         return (-1);
1071
1072     // empty eeprom
1073     memset (output, 0, 128);
1074
1075     // Addr 00: Stay 00 00
1076     // Addr 02: Vendor ID
1077     output[0x02] = eeprom->vendor_id;
1078     output[0x03] = eeprom->vendor_id >> 8;
1079
1080     // Addr 04: Product ID
1081     output[0x04] = eeprom->product_id;
1082     output[0x05] = eeprom->product_id >> 8;
1083
1084     // Addr 06: Device release number (0400h for BM features)
1085     output[0x06] = 0x00;
1086
1087     if (eeprom->BM_type_chip == 1)
1088         output[0x07] = 0x04;
1089     else
1090         output[0x07] = 0x02;
1091
1092     // Addr 08: Config descriptor
1093     // Bit 1: remote wakeup if 1
1094     // Bit 0: self powered if 1
1095     //
1096     j = 0;
1097     if (eeprom->self_powered == 1)
1098         j = j | 1;
1099     if (eeprom->remote_wakeup == 1)
1100         j = j | 2;
1101     output[0x08] = j;
1102
1103     // Addr 09: Max power consumption: max power = value * 2 mA
1104     output[0x09] = eeprom->max_power;
1105     ;
1106
1107     // Addr 0A: Chip configuration
1108     // Bit 7: 0 - reserved
1109     // Bit 6: 0 - reserved
1110     // Bit 5: 0 - reserved
1111     // Bit 4: 1 - Change USB version
1112     // Bit 3: 1 - Use the serial number string
1113     // Bit 2: 1 - Enable suspend pull downs for lower power
1114     // Bit 1: 1 - Out EndPoint is Isochronous
1115     // Bit 0: 1 - In EndPoint is Isochronous
1116     //
1117     j = 0;
1118     if (eeprom->in_is_isochronous == 1)
1119         j = j | 1;
1120     if (eeprom->out_is_isochronous == 1)
1121         j = j | 2;
1122     if (eeprom->suspend_pull_downs == 1)
1123         j = j | 4;
1124     if (eeprom->use_serial == 1)
1125         j = j | 8;
1126     if (eeprom->change_usb_version == 1)
1127         j = j | 16;
1128     output[0x0A] = j;
1129
1130     // Addr 0B: reserved
1131     output[0x0B] = 0x00;
1132
1133     // Addr 0C: USB version low byte when 0x0A bit 4 is set
1134     // Addr 0D: USB version high byte when 0x0A bit 4 is set
1135     if (eeprom->change_usb_version == 1) {
1136         output[0x0C] = eeprom->usb_version;
1137         output[0x0D] = eeprom->usb_version >> 8;
1138     }
1139
1140
1141     // Addr 0E: Offset of the manufacturer string + 0x80
1142     output[0x0E] = 0x14 + 0x80;
1143
1144     // Addr 0F: Length of manufacturer string
1145     output[0x0F] = manufacturer_size*2 + 2;
1146
1147     // Addr 10: Offset of the product string + 0x80, calculated later
1148     // Addr 11: Length of product string
1149     output[0x11] = product_size*2 + 2;
1150
1151     // Addr 12: Offset of the serial string + 0x80, calculated later
1152     // Addr 13: Length of serial string
1153     output[0x13] = serial_size*2 + 2;
1154
1155     // Dynamic content
1156     output[0x14] = manufacturer_size*2 + 2;
1157     output[0x15] = 0x03; // type: string
1158
1159     i = 0x16, j = 0;
1160
1161     // Output manufacturer
1162     for (j = 0; j < manufacturer_size; j++) {
1163         output[i] = eeprom->manufacturer[j], i++;
1164         output[i] = 0x00, i++;
1165     }
1166
1167     // Output product name
1168     output[0x10] = i + 0x80;  // calculate offset
1169     output[i] = product_size*2 + 2, i++;
1170     output[i] = 0x03, i++;
1171     for (j = 0; j < product_size; j++) {
1172         output[i] = eeprom->product[j], i++;
1173         output[i] = 0x00, i++;
1174     }
1175
1176     // Output serial
1177     output[0x12] = i + 0x80; // calculate offset
1178     output[i] = serial_size*2 + 2, i++;
1179     output[i] = 0x03, i++;
1180     for (j = 0; j < serial_size; j++) {
1181         output[i] = eeprom->serial[j], i++;
1182         output[i] = 0x00, i++;
1183     }
1184
1185     // calculate checksum
1186     checksum = 0xAAAA;
1187
1188     for (i = 0; i < 63; i++) {
1189         value = output[i*2];
1190         value += output[(i*2)+1] << 8;
1191
1192         checksum = value^checksum;
1193         checksum = (checksum << 1) | (checksum >> 15);
1194     }
1195
1196     output[0x7E] = checksum;
1197     output[0x7F] = checksum >> 8;
1198
1199     return size_check;
1200 }
1201
1202 /**
1203     Read eeprom
1204
1205     \param ftdi pointer to ftdi_context
1206     \param eeprom Pointer to store eeprom into
1207
1208     \retval  0: all fine
1209     \retval -1: read failed
1210 */
1211 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1212 {
1213     int i;
1214
1215     for (i = 0; i < 64; i++) {
1216         if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1217             ftdi_error_return(-1, "reading eeprom failed");
1218     }
1219
1220     return 0;
1221 }
1222
1223 /**
1224     Write eeprom
1225
1226     \param ftdi pointer to ftdi_context
1227     \param eeprom Pointer to read eeprom from
1228
1229     \retval  0: all fine
1230     \retval -1: read failed
1231 */
1232 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1233 {
1234     unsigned short usb_val;
1235     int i;
1236
1237     for (i = 0; i < 64; i++) {
1238         usb_val = eeprom[i*2];
1239         usb_val += eeprom[(i*2)+1] << 8;
1240         if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1241             ftdi_error_return(-1, "unable to write eeprom");
1242     }
1243
1244     return 0;
1245 }
1246
1247 /**
1248     Erase eeprom
1249
1250     \param ftdi pointer to ftdi_context
1251
1252     \retval  0: all fine
1253     \retval -1: erase failed
1254 */
1255 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1256 {
1257     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1258         ftdi_error_return(-1, "unable to erase eeprom");
1259
1260     return 0;
1261 }
1262
1263 /**
1264     Get string representation for last error code
1265
1266     \param ftdi pointer to ftdi_context
1267
1268     \retval Pointer to error string
1269 */
1270 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1271 {
1272     return ftdi->error_str;
1273 }
1274
1275 /*
1276     Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1277     and Matthias Kranz  (matthias@hcilab.org)
1278 */
1279 /**
1280     Set flowcontrol for ftdi chip
1281
1282     \param ftdi pointer to ftdi_context
1283     \param flowctrl flow control to use. should be 
1284            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS   
1285
1286     \retval  0: all fine
1287     \retval -1: set flow control failed
1288 */
1289 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1290 {
1291     if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1292                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1293                         NULL, 0, ftdi->usb_write_timeout) != 0)
1294         ftdi_error_return(-1, "set flow control failed");
1295
1296     return 0;
1297 }
1298
1299 /**
1300     Set dtr line
1301
1302     \param ftdi pointer to ftdi_context
1303     \param state state to set line to (1 or 0)
1304
1305     \retval  0: all fine
1306     \retval -1: set dtr failed
1307 */
1308 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1309 {
1310     unsigned short usb_val;
1311
1312     if (state)
1313         usb_val = SIO_SET_DTR_HIGH;
1314     else
1315         usb_val = SIO_SET_DTR_LOW;
1316
1317     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1318                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1319                         NULL, 0, ftdi->usb_write_timeout) != 0)
1320         ftdi_error_return(-1, "set dtr failed");
1321
1322     return 0;
1323 }
1324
1325 /**
1326     Set rts line
1327
1328     \param ftdi pointer to ftdi_context
1329     \param state state to set line to (1 or 0)
1330
1331     \retval  0: all fine
1332     \retval -1 set rts failed
1333 */
1334 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1335 {
1336     unsigned short usb_val;
1337
1338     if (state)
1339         usb_val = SIO_SET_RTS_HIGH;
1340     else
1341         usb_val = SIO_SET_RTS_LOW;
1342
1343     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1344                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1345                         NULL, 0, ftdi->usb_write_timeout) != 0)
1346         ftdi_error_return(-1, "set of rts failed");
1347
1348     return 0;
1349 }
1350
1351 /* @} end of doxygen libftdi group */