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