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