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