Export ftdi_readstream()
[libftdi] / src / ftdi_stream.c
1 /***************************************************************************
2                           ftdi_stream.c  -  description
3                              -------------------
4     copyright            : (C) 2009 Micah Dowty 2010 Uwe Bonnes
5     email                : opensource@intra2net.com
6  ***************************************************************************/
7  
8 /***************************************************************************
9  *                                                                         *
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;             *
13  *                                                                         *
14  ***************************************************************************/
15
16 /* Adapted from 
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
20  *
21  * Copyright (C) 2009 Micah Dowty
22  *
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:
29  *
30  * The above copyright notice and this permission notice shall be included in
31  * all copies or substantial portions of the Software.
32  *
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
39  * THE SOFTWARE.
40  */
41
42 #include <stdlib.h>
43 #include <stdio.h>
44
45 #include "ftdi.h"
46
47 typedef struct
48 {
49     FTDIStreamCallback *callback;
50     void *userdata;
51     int packetsize;
52     int result;
53     FTDIProgressInfo progress;
54 } FTDIStreamState;
55
56 static void
57 ftdi_readstream_cb(struct libusb_transfer *transfer)
58 {
59    FTDIStreamState *state = transfer->user_data;
60    int packet_size = state->packetsize;
61
62    if(transfer->status & LIBUSB_TRANSFER_CANCELLED)
63    {
64        free(transfer->buffer);
65        libusb_free_transfer(transfer);
66        return;
67    }
68    if (state->result == 0)
69    {
70        if (transfer->status == LIBUSB_TRANSFER_COMPLETED)
71        {
72            int i;
73            uint8_t *ptr = transfer->buffer;
74            int length = transfer->actual_length;
75            int numPackets = (length + packet_size - 1) / packet_size;
76
77            for (i = 0; i < numPackets; i++)
78            {
79                int payloadLen;
80                int packetLen = length;
81
82                if (packetLen > packet_size)
83                    packetLen = packet_size;
84
85                payloadLen = packetLen - 2;
86                state->progress.current.totalBytes += payloadLen;
87
88                state->result = state->callback(ptr + 2, payloadLen,
89                                                NULL, state->userdata);
90                if (state->result)
91                    break;
92
93                ptr += packetLen;
94                length -= packetLen;
95            }
96
97
98        }
99        else
100        {
101            fprintf(stderr, "unknown status %d\n",transfer->status); 
102            state->result = LIBUSB_ERROR_IO;
103        }
104    }
105    else
106        fprintf(stderr,"state->result %d\n", state->result);
107
108    if (state->result == 0)
109    {
110        transfer->status = -1;
111        state->result = libusb_submit_transfer(transfer);
112    }
113 }
114
115 /**
116    Helper function to calculate (unix) time differences
117
118    \param a timeval
119    \param b timeval
120 */
121 static double
122 TimevalDiff(const struct timeval *a, const struct timeval *b)
123 {
124    return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
125 }
126
127 /**
128     Streaming reading of data from the device
129
130     Use asynchronous transfers in libusb-1.0 for high-performance
131     streaming of data from a device interface back to the PC. This
132     function continuously transfers data until either an error occurs
133     or the callback returns a nonzero value. This function returns
134     a libusb error code or the callback's return value.
135
136     For every contiguous block of received data, the callback will
137     be invoked.
138
139     \param  ftdi pointer to ftdi_context
140     \param  callback to user supplied function for one block of data
141     \param  userdata
142     \param  packetsPerTransfer number of packets per transfer
143     \param  numTransfers Number of transfers per callback
144
145 */
146
147 int
148 ftdi_readstream(struct ftdi_context *ftdi,
149                       FTDIStreamCallback *callback, void *userdata,
150                       int packetsPerTransfer, int numTransfers)
151 {
152     struct libusb_transfer **transfers;
153     FTDIStreamState state = { callback, userdata, ftdi->max_packet_size };
154     int bufferSize = packetsPerTransfer * ftdi->max_packet_size;
155     int xferIndex;
156     int err = 0;
157
158     fprintf(stderr, "ftdi_readstream\n");
159     /*
160      * Set up all transfers
161      */
162
163     transfers = calloc(numTransfers, sizeof *transfers);
164     if (!transfers) {
165         err = LIBUSB_ERROR_NO_MEM;
166         goto cleanup;
167     }
168
169     for (xferIndex = 0; xferIndex < numTransfers; xferIndex++)
170     {
171         struct libusb_transfer *transfer;
172
173         transfer = libusb_alloc_transfer(0);
174         transfers[xferIndex] = transfer;
175         if (!transfer) {
176             err = LIBUSB_ERROR_NO_MEM;
177             goto cleanup;
178         }
179
180         libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep,
181                                   malloc(bufferSize), bufferSize, 
182                                   ftdi_readstream_cb,
183                                   &state, 0);
184
185         if (!transfer->buffer) {
186             err = LIBUSB_ERROR_NO_MEM;
187             goto cleanup;
188         }
189
190         transfer->status = -1;
191         err = libusb_submit_transfer(transfer);
192         if (err)
193             goto cleanup;
194     }
195
196     /* Start the transfers only when everything has been set up.
197      * Otherwise the transfers start stuttering and the PC not 
198      * fetching data for several to several ten milliseconds 
199      * and we skip blocks
200      */
201     if (ftdi_set_bitmode(ftdi,  0xff, BITMODE_SYNCFF) < 0)
202     {
203         fprintf(stderr,"Can't set synchronous fifo mode\n",
204                 ftdi_get_error_string(ftdi));
205         goto cleanup;
206     }
207
208     /*
209      * Run the transfers, and periodically assess progress.
210      */
211
212     gettimeofday(&state.progress.first.time, NULL);
213
214     do
215     {
216         FTDIProgressInfo  *progress = &state.progress;
217         const double progressInterval = 1.0;
218         struct timeval timeout = { 0, ftdi->usb_read_timeout };
219         struct timeval now;
220
221         int err = libusb_handle_events_timeout(NULL, &timeout);
222         if (!state.result)
223         {
224             state.result = err;
225         }
226
227         // If enough time has elapsed, update the progress
228         gettimeofday(&now, NULL);
229         if (TimevalDiff(&now, &progress->current.time) >= progressInterval)
230         {
231             progress->current.time = now;
232             progress->totalTime = TimevalDiff(&progress->current.time,
233                                               &progress->first.time);
234
235             if (progress->prev.totalBytes)
236             {
237                 // We have enough information to calculate rates
238
239                 double currentTime;
240
241                 currentTime = TimevalDiff(&progress->current.time,
242                                           &progress->prev.time);
243
244                 progress->totalRate = 
245                     progress->current.totalBytes /progress->totalTime;
246                 progress->currentRate = 
247                     (progress->current.totalBytes -
248                      progress->prev.totalBytes) / currentTime;
249             }
250
251             state.result = state.callback(NULL, 0, progress, state.userdata);
252             progress->prev = progress->current;
253
254         }
255     } while (!state.result);
256
257     /*
258      * Cancel any outstanding transfers, and free memory.
259      */
260
261  cleanup:
262     fprintf(stderr, "cleanup\n");
263     if (transfers) {
264         int i;
265         for (xferIndex = 0; xferIndex < numTransfers; xferIndex++)
266         {
267             struct libusb_transfer *transfer = transfers[xferIndex];
268
269             if (transfer) {
270                     libusb_cancel_transfer(transfer);
271             }
272         }
273             libusb_handle_events(NULL);
274         free(transfers);
275     }
276
277     if (err)
278         return err;
279     else
280         return state.result;
281 }
282