1 /***************************************************************************
2 ftdi_stream.c - description
4 copyright : (C) 2009 Micah Dowty 2010 Uwe Bonnes
5 email : opensource@intra2net.com
6 ***************************************************************************/
8 /***************************************************************************
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU Lesser General Public License *
12 * version 2.1 as published by the Free Software Foundation; *
14 ***************************************************************************/
17 * fastftdi.c - A minimal FTDI FT232H interface for which supports bit-bang
18 * mode, but focuses on very high-performance support for
19 * synchronous FIFO mode. Requires libusb-1.0
21 * Copyright (C) 2009 Micah Dowty
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
49 FTDIStreamCallback *callback;
54 FTDIProgressInfo progress;
59 * With Exit request, free memory and release the transfer
61 * state->result is only set when some error happens
64 ftdi_readstream_cb(struct libusb_transfer *transfer)
66 FTDIStreamState *state = transfer->user_data;
67 int packet_size = state->packetsize;
70 if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
73 uint8_t *ptr = transfer->buffer;
74 int length = transfer->actual_length;
75 int numPackets = (length + packet_size - 1) / packet_size;
78 for (i = 0; i < numPackets; i++)
81 int packetLen = length;
83 if (packetLen > packet_size)
84 packetLen = packet_size;
86 payloadLen = packetLen - 2;
87 state->progress.current.totalBytes += payloadLen;
89 res = state->callback(ptr + 2, payloadLen,
90 NULL, state->userdata);
97 free(transfer->buffer);
98 libusb_free_transfer(transfer);
102 transfer->status = -1;
103 state->result = libusb_submit_transfer(transfer);
108 fprintf(stderr, "unknown status %d\n",transfer->status);
109 state->result = LIBUSB_ERROR_IO;
114 Helper function to calculate (unix) time differences
120 TimevalDiff(const struct timeval *a, const struct timeval *b)
122 return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
126 Streaming reading of data from the device
128 Use asynchronous transfers in libusb-1.0 for high-performance
129 streaming of data from a device interface back to the PC. This
130 function continuously transfers data until either an error occurs
131 or the callback returns a nonzero value. This function returns
132 a libusb error code or the callback's return value.
134 For every contiguous block of received data, the callback will
137 \param ftdi pointer to ftdi_context
138 \param callback to user supplied function for one block of data
140 \param packetsPerTransfer number of packets per transfer
141 \param numTransfers Number of transfers per callback
146 ftdi_readstream(struct ftdi_context *ftdi,
147 FTDIStreamCallback *callback, void *userdata,
148 int packetsPerTransfer, int numTransfers)
150 struct libusb_transfer **transfers;
151 FTDIStreamState state = { callback, userdata, ftdi->max_packet_size, 1 };
152 int bufferSize = packetsPerTransfer * ftdi->max_packet_size;
156 /* Only FT2232H and FT232H know about the synchronous FIFO Mode*/
157 if ((ftdi->type != TYPE_2232H) && (ftdi->type != TYPE_232H))
159 fprintf(stderr,"Device doesn't support synchronous FIFO mode\n");
163 /* We don't know in what state we are, switch to reset*/
164 if (ftdi_set_bitmode(ftdi, 0xff, BITMODE_RESET) < 0)
166 fprintf(stderr,"Can't reset mode\n");
170 /* Purge anything remaining in the buffers*/
171 if (ftdi_usb_purge_buffers(ftdi) < 0)
173 fprintf(stderr,"Can't Purge\n");
178 * Set up all transfers
181 transfers = calloc(numTransfers, sizeof *transfers);
183 err = LIBUSB_ERROR_NO_MEM;
187 for (xferIndex = 0; xferIndex < numTransfers; xferIndex++)
189 struct libusb_transfer *transfer;
191 transfer = libusb_alloc_transfer(0);
192 transfers[xferIndex] = transfer;
194 err = LIBUSB_ERROR_NO_MEM;
198 libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep,
199 malloc(bufferSize), bufferSize,
203 if (!transfer->buffer) {
204 err = LIBUSB_ERROR_NO_MEM;
208 transfer->status = -1;
209 err = libusb_submit_transfer(transfer);
214 /* Start the transfers only when everything has been set up.
215 * Otherwise the transfers start stuttering and the PC not
216 * fetching data for several to several ten milliseconds
219 if (ftdi_set_bitmode(ftdi, 0xff, BITMODE_SYNCFF) < 0)
221 fprintf(stderr,"Can't set synchronous fifo mode: %s\n",
222 ftdi_get_error_string(ftdi));
227 * Run the transfers, and periodically assess progress.
230 gettimeofday(&state.progress.first.time, NULL);
234 FTDIProgressInfo *progress = &state.progress;
235 const double progressInterval = 1.0;
236 struct timeval timeout = { 0, ftdi->usb_read_timeout };
239 int err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
240 if (err == LIBUSB_ERROR_INTERRUPTED)
241 /* restart interrupted events */
242 err = libusb_handle_events_timeout(ftdi->usb_ctx, &timeout);
247 if (state.activity == 0)
252 // If enough time has elapsed, update the progress
253 gettimeofday(&now, NULL);
254 if (TimevalDiff(&now, &progress->current.time) >= progressInterval)
256 progress->current.time = now;
257 progress->totalTime = TimevalDiff(&progress->current.time,
258 &progress->first.time);
260 if (progress->prev.totalBytes)
262 // We have enough information to calculate rates
266 currentTime = TimevalDiff(&progress->current.time,
267 &progress->prev.time);
269 progress->totalRate =
270 progress->current.totalBytes /progress->totalTime;
271 progress->currentRate =
272 (progress->current.totalBytes -
273 progress->prev.totalBytes) / currentTime;
276 state.callback(NULL, 0, progress, state.userdata);
277 progress->prev = progress->current;
280 } while (!state.result);
283 * Cancel any outstanding transfers, and free memory.
287 fprintf(stderr, "cleanup\n");