]> sigrok.org Git - libsigrok.git/blob - src/hardware/pipistrello-ols/protocol.c
added pipistrello-ols
[libsigrok.git] / src / hardware / pipistrello-ols / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "protocol.h"
21
22 extern SR_PRIV struct sr_dev_driver p_ols_driver_info;
23 static struct sr_dev_driver *di = &p_ols_driver_info;
24
25 SR_PRIV int write_shortcommand(struct dev_context *devc, uint8_t command)
26 {
27         uint8_t buf[1];
28         int bytes_written;
29
30         sr_dbg("Sending cmd 0x%.2x.", command);
31         buf[0] = command;
32         bytes_written = ftdi_write_data(devc->ftdic, buf, 1);
33         if (bytes_written < 0) {
34                 sr_err("Failed to write FTDI data (%d): %s.",
35                        bytes_written, ftdi_get_error_string(devc->ftdic));
36                 return SR_ERR;
37         } else if (bytes_written != 1) {
38                 sr_err("FTDI write error, only %d/%d bytes written: %s.",
39                        bytes_written, 1, ftdi_get_error_string(devc->ftdic));
40                 return SR_ERR;
41         }
42
43         return SR_OK;
44 }
45
46 SR_PRIV int write_longcommand(struct dev_context *devc, uint8_t command, uint8_t *data)
47 {
48         uint8_t buf[5];
49         int bytes_written;
50
51         sr_dbg("Sending cmd 0x%.2x data 0x%.2x%.2x%.2x%.2x.", command,
52                         data[0], data[1], data[2], data[3]);
53         buf[0] = command;
54         buf[1] = data[0];
55         buf[2] = data[1];
56         buf[3] = data[2];
57         buf[4] = data[3];
58         bytes_written = ftdi_write_data(devc->ftdic, buf, 5);
59         if (bytes_written < 0) {
60                 sr_err("Failed to write FTDI data (%d): %s.",
61                        bytes_written, ftdi_get_error_string(devc->ftdic));
62                 return SR_ERR;
63         } else if (bytes_written != 5) {
64                 sr_err("FTDI write error, only %d/%d bytes written: %s.",
65                        bytes_written, 1, ftdi_get_error_string(devc->ftdic));
66                 return SR_ERR;
67         }
68
69         return SR_OK;
70 }
71
72 SR_PRIV int p_ols_open(struct dev_context *devc)
73 {
74         int ret;
75
76         /* Note: Caller checks devc and devc->ftdic. */
77
78         /* Select interface B, otherwise communication will fail. */
79         ret = ftdi_set_interface(devc->ftdic, INTERFACE_B);
80         if (ret < 0) {
81                 sr_err("Failed to set FTDI interface B (%d): %s", ret,
82                        ftdi_get_error_string(devc->ftdic));
83                 return SR_ERR;
84         }
85         sr_dbg("FTDI chip interface B set successfully.");
86
87         /* Check for the device and temporarily open it. */
88         ret = ftdi_usb_open_desc(devc->ftdic, USB_VENDOR_ID, USB_DEVICE_ID,
89                                  USB_IPRODUCT, NULL);
90         if (ret < 0) {
91                 /* Log errors, except for -3 ("device not found"). */
92                 if (ret != -3)
93                         sr_err("Failed to open device (%d): %s", ret,
94                                ftdi_get_error_string(devc->ftdic));
95                 return SR_ERR;
96         }
97         sr_dbg("FTDI device opened successfully.");
98
99         /* Purge RX/TX buffers in the FTDI chip. */
100         if ((ret = ftdi_usb_purge_buffers(devc->ftdic)) < 0) {
101                 sr_err("Failed to purge FTDI RX/TX buffers (%d): %s.",
102                        ret, ftdi_get_error_string(devc->ftdic));
103                 goto err_open_close_ftdic;
104         }
105         sr_dbg("FTDI chip buffers purged successfully.");
106
107         /* Reset the FTDI bitmode. */
108         ret = ftdi_set_bitmode(devc->ftdic, 0xff, BITMODE_RESET);
109         if (ret < 0) {
110                 sr_err("Failed to reset the FTDI chip bitmode (%d): %s.",
111                        ret, ftdi_get_error_string(devc->ftdic));
112                 goto err_open_close_ftdic;
113         }
114         sr_dbg("FTDI chip bitmode reset successfully.");
115
116         /* Set the FTDI latency timer to 16. */
117         ret = ftdi_set_latency_timer(devc->ftdic, 16);
118         if (ret < 0) {
119                 sr_err("Failed to set FTDI latency timer (%d): %s.",
120                        ret, ftdi_get_error_string(devc->ftdic));
121                 goto err_open_close_ftdic;
122         }
123         sr_dbg("FTDI chip latency timer set successfully.");
124
125         /* Set the FTDI read data chunk size to 64kB. */
126         ret = ftdi_read_data_set_chunksize(devc->ftdic, 64 * 1024);
127         if (ret < 0) {
128                 sr_err("Failed to set FTDI read data chunk size (%d): %s.",
129                        ret, ftdi_get_error_string(devc->ftdic));
130                 goto err_open_close_ftdic;
131         }
132         sr_dbg("FTDI chip read data chunk size set successfully.");
133         
134         return SR_OK;
135
136 err_open_close_ftdic:
137         ftdi_usb_close(devc->ftdic))
138         return SR_ERR;
139 }
140
141 SR_PRIV int p_ols_close(struct dev_context *devc)
142 {
143         int ret;
144
145         /* Note: Caller checks devc and devc->ftdic. */
146
147         if ((ret = ftdi_usb_close(devc->ftdic)) < 0) {
148                 sr_err("Failed to close FTDI device (%d): %s.",
149                        ret, ftdi_get_error_string(devc->ftdic));
150                 return SR_ERR;
151         }
152
153         return SR_OK;
154 }
155
156 SR_PRIV int p_ols_configure_channels(const struct sr_dev_inst *sdi)
157 {
158         struct dev_context *devc;
159         const struct sr_channel *ch;
160         const GSList *l;
161         int channel_bit, stage, i;
162         char *tc;
163
164         devc = sdi->priv;
165
166         devc->channel_mask = 0;
167         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
168                 devc->trigger_mask[i] = 0;
169                 devc->trigger_value[i] = 0;
170         }
171
172         devc->num_stages = 0;
173         for (l = sdi->channels; l; l = l->next) {
174                 ch = (const struct sr_channel *)l->data;
175                 if (!ch->enabled)
176                         continue;
177
178                 if (ch->index >= devc->max_channels) {
179                         sr_err("Channels over the limit of %d\n", devc->max_channels);
180                         return SR_ERR;
181                 }
182
183                 /*
184                  * Set up the channel mask for later configuration into the
185                  * flag register.
186                  */
187                 channel_bit = 1 << (ch->index);
188                 devc->channel_mask |= channel_bit;
189
190                 if (!ch->trigger)
191                         continue;
192
193                 /* Configure trigger mask and value. */
194                 stage = 0;
195                 for (tc = ch->trigger; tc && *tc; tc++) {
196                         devc->trigger_mask[stage] |= channel_bit;
197                         if (*tc == '1')
198                                 devc->trigger_value[stage] |= channel_bit;
199                         stage++;
200                         /* Only supporting parallel mode, with up to 4 stages. */
201                         if (stage > 3)
202                                 return SR_ERR;
203                 }
204                 if (stage > devc->num_stages)
205                         devc->num_stages = stage - 1;
206         }
207
208         return SR_OK;
209 }
210
211 SR_PRIV struct sr_dev_inst *p_ols_get_metadata(uint8_t *buf, int bytes_read, struct dev_context *devc)
212 {
213         struct sr_dev_inst *sdi;
214         struct sr_channel *ch;
215         uint32_t tmp_int, ui;
216         uint8_t key, type, token;
217         GString *tmp_str, *devname, *version;
218         guchar tmp_c;
219         int index, i;
220
221         sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, NULL, NULL, NULL);
222         sdi->driver = di;
223         sdi->priv = devc;
224
225         devname = g_string_new("");
226         version = g_string_new("");
227
228         index = 0;
229         while (index < bytes_read) {
230                 key = buf[index++];
231                 if (key == 0x00) {
232                         sr_dbg("Got metadata key 0x00, metadata ends.");
233                         break;
234                 }
235                 type = key >> 5;
236                 token = key & 0x1f;
237                 switch (type) {
238                 case 0:
239                         /* NULL-terminated string */
240                         tmp_str = g_string_new("");
241                         while ((index < bytes_read) && ((tmp_c = buf[index++]) != '\0'))
242                                 g_string_append_c(tmp_str, tmp_c);
243                         sr_dbg("Got metadata key 0x%.2x value '%s'.",
244                                key, tmp_str->str);
245                         switch (token) {
246                         case 0x01:
247                                 /* Device name */
248                                 devname = g_string_append(devname, tmp_str->str);
249                                 break;
250                         case 0x02:
251                                 /* FPGA firmware version */
252                                 if (version->len)
253                                         g_string_append(version, ", ");
254                                 g_string_append(version, "FPGA version ");
255                                 g_string_append(version, tmp_str->str);
256                                 break;
257                         case 0x03:
258                                 /* Ancillary version */
259                                 if (version->len)
260                                         g_string_append(version, ", ");
261                                 g_string_append(version, "Ancillary version ");
262                                 g_string_append(version, tmp_str->str);
263                                 break;
264                         default:
265                                 sr_info("Unknown token 0x%.2x: '%s'",
266                                         token, tmp_str->str);
267                                 break;
268                         }
269                         g_string_free(tmp_str, TRUE);
270                         break;
271                 case 1:
272                         /* 32-bit unsigned integer */
273                         tmp_int = 0;
274                         for (i = 0; i < 4; i++) {
275                                 tmp_int = (tmp_int << 8) | buf[index++];
276                         }
277                         sr_dbg("Got metadata key 0x%.2x value 0x%.8x.",
278                                key, tmp_int);
279                         switch (token) {
280                         case 0x00:
281                                 /* Number of usable channels */
282                                 for (ui = 0; ui < tmp_int; ui++) {
283                                         if (!(ch = sr_channel_new(ui, SR_CHANNEL_LOGIC, TRUE,
284                                                         p_ols_channel_names[ui])))
285                                                 return 0;
286                                         sdi->channels = g_slist_append(sdi->channels, ch);
287                                 }
288                                 break;
289                         case 0x01:
290                                 /* Amount of sample memory available (bytes) */
291                                 devc->max_samples = tmp_int;
292                                 break;
293                         case 0x02:
294                                 /* Amount of dynamic memory available (bytes) */
295                                 /* what is this for? */
296                                 break;
297                         case 0x03:
298                                 /* Maximum sample rate (hz) */
299                                 devc->max_samplerate = tmp_int;
300                                 break;
301                         case 0x04:
302                                 /* protocol version */
303                                 devc->protocol_version = tmp_int;
304                                 break;
305                         default:
306                                 sr_info("Unknown token 0x%.2x: 0x%.8x.",
307                                         token, tmp_int);
308                                 break;
309                         }
310                         break;
311                 case 2:
312                         /* 8-bit unsigned integer */
313                         tmp_c = buf[index++];
314                         sr_dbg("Got metadata key 0x%.2x value 0x%.2x.",
315                                key, tmp_c);
316                         switch (token) {
317                         case 0x00:
318                                 /* Number of usable channels */
319                                 for (ui = 0; ui < tmp_c; ui++) {
320                                         if (!(ch = sr_channel_new(ui, SR_CHANNEL_LOGIC, TRUE,
321                                                         p_ols_channel_names[ui])))
322                                                 return 0;
323                                         sdi->channels = g_slist_append(sdi->channels, ch);
324                                 }
325                                 break;
326                         case 0x01:
327                                 /* protocol version */
328                                 devc->protocol_version = tmp_c;
329                                 break;
330                         default:
331                                 sr_info("Unknown token 0x%.2x: 0x%.2x.",
332                                         token, tmp_c);
333                                 break;
334                         }
335                         break;
336                 default:
337                         /* unknown type */
338                         break;
339                 }
340         }
341
342         sdi->model = devname->str;
343         sdi->version = version->str;
344         g_string_free(devname, FALSE);
345         g_string_free(version, FALSE);
346
347         return sdi;
348 }
349
350 SR_PRIV int p_ols_set_samplerate(const struct sr_dev_inst *sdi,
351                 const uint64_t samplerate)
352 {
353         struct dev_context *devc;
354
355         devc = sdi->priv;
356         if (devc->max_samplerate && samplerate > devc->max_samplerate)
357                 return SR_ERR_SAMPLERATE;
358
359         if (samplerate > CLOCK_RATE) {
360                 sr_info("Enabling demux mode.");
361                 devc->flag_reg |= FLAG_DEMUX;
362                 devc->flag_reg &= ~FLAG_FILTER;
363                 devc->max_channels = NUM_CHANNELS / 2;
364                 devc->cur_samplerate_divider = (CLOCK_RATE * 2 / samplerate) - 1;
365         } else {
366                 sr_info("Disabling demux mode.");
367                 devc->flag_reg &= ~FLAG_DEMUX;
368                 devc->flag_reg |= FLAG_FILTER;
369                 devc->max_channels = NUM_CHANNELS;
370                 devc->cur_samplerate_divider = (CLOCK_RATE / samplerate) - 1;
371         }
372
373         /* Calculate actual samplerate used and complain if it is different
374          * from the requested.
375          */
376         devc->cur_samplerate = CLOCK_RATE / (devc->cur_samplerate_divider + 1);
377         if (devc->flag_reg & FLAG_DEMUX)
378                 devc->cur_samplerate *= 2;
379         if (devc->cur_samplerate != samplerate)
380                 sr_info("Can't match samplerate %" PRIu64 ", using %"
381                        PRIu64 ".", samplerate, devc->cur_samplerate);
382
383         return SR_OK;
384 }
385
386
387 SR_PRIV int p_ols_receive_data(int fd, int revents, void *cb_data)
388 {
389         struct dev_context *devc;
390         struct sr_dev_inst *sdi;
391         struct sr_datafeed_packet packet;
392         struct sr_datafeed_logic logic;
393         uint32_t sample;
394         int num_channels, offset, j;
395         int bytes_read, index;
396         unsigned int i;
397         unsigned char byte;
398
399         (void)fd;
400         (void)revents;
401
402         sdi = cb_data;
403         devc = sdi->priv;
404
405         if (devc->num_transfers++ == 0) {
406                 devc->raw_sample_buf = g_try_malloc(devc->limit_samples * 4);
407                 if (!devc->raw_sample_buf) {
408                         sr_err("Sample buffer malloc failed.");
409                         return FALSE;
410                 }
411                 /* fill with 1010... for debugging */
412                 memset(devc->raw_sample_buf, 0x82, devc->limit_samples * 4);
413         }
414
415         if (devc->num_samples < devc->limit_samples) {
416
417                 num_channels = 0;
418                 for (i = NUM_CHANNELS; i > 0x02; i /= 2) {
419                         if ((devc->flag_reg & i) == 0) {
420                                 num_channels++;
421                         }
422                 }
423
424                 /* Get a block of data. */
425                 bytes_read = ftdi_read_data(devc->ftdic, devc->ftdi_buf, FTDI_BUF_SIZE);
426                 if (bytes_read < 0) {
427                         sr_err("Failed to read FTDI data (%d): %s.",
428                                bytes_read, ftdi_get_error_string(devc->ftdic));
429                         sdi->driver->dev_acquisition_stop(sdi, sdi);
430                         return FALSE;
431                 }
432                 if (bytes_read == 0) {
433                         sr_spew("Received 0 bytes, nothing to do.");
434                         return TRUE;
435                 }
436
437                 sr_dbg("Received %d bytes", bytes_read);
438
439                 index = 0;
440                 while (index < bytes_read) {
441                         byte = devc->ftdi_buf[index++];
442                         devc->cnt_bytes++;
443
444                         devc->sample[devc->num_bytes++] = byte;
445                         sr_spew("Received byte 0x%.2x.", byte);
446                         if (devc->num_bytes == num_channels) {
447                                 devc->cnt_samples++;
448                                 devc->cnt_samples_rle++;
449                                 /*
450                                  * Got a full sample. Convert from the OLS's little-endian
451                                  * sample to the local format.
452                                  */
453                                 sample = devc->sample[0] | (devc->sample[1] << 8) \
454                                                 | (devc->sample[2] << 16) | (devc->sample[3] << 24);
455                                 sr_spew("Received sample 0x%.*x.", devc->num_bytes * 2, sample);
456                                 if (devc->flag_reg & FLAG_RLE) {
457                                         /*
458                                          * In RLE mode the high bit of the sample is the
459                                          * "count" flag, meaning this sample is the number
460                                          * of times the previous sample occurred.
461                                          */
462                                         if (devc->sample[devc->num_bytes - 1] & 0x80) {
463                                                 /* Clear the high bit. */
464                                                 sample &= ~(0x80 << (devc->num_bytes - 1) * 8);
465                                                 devc->rle_count = sample;
466                                                 devc->cnt_samples_rle += devc->rle_count;
467                                                 sr_dbg("RLE count: %u.", devc->rle_count);
468                                                 devc->num_bytes = 0;
469                                                 continue;
470                                         }
471                                 }
472                                 devc->num_samples += devc->rle_count + 1;
473                                 if (devc->num_samples > devc->limit_samples) {
474                                         /* Save us from overrunning the buffer. */
475                                         devc->rle_count -= devc->num_samples - devc->limit_samples;
476                                         devc->num_samples = devc->limit_samples;
477                                 }
478
479                                 if (num_channels < 4) {
480                                         /*
481                                          * Some channel groups may have been turned
482                                          * off, to speed up transfer between the
483                                          * hardware and the PC. Expand that here before
484                                          * submitting it over the session bus --
485                                          * whatever is listening on the bus will be
486                                          * expecting a full 32-bit sample, based on
487                                          * the number of channels.
488                                          */
489                                         j = 0;
490                                         memset(devc->tmp_sample, 0, 4);
491                                         for (i = 0; i < 4; i++) {
492                                                 if (((devc->flag_reg >> 2) & (1 << i)) == 0) {
493                                                         /*
494                                                          * This channel group was
495                                                          * enabled, copy from received
496                                                          * sample.
497                                                          */
498                                                         devc->tmp_sample[i] = devc->sample[j++];
499                                                 } else if (devc->flag_reg & FLAG_DEMUX && (i > 2)) {
500                                                         /* group 2 & 3 get added to 0 & 1 */
501                                                         devc->tmp_sample[i - 2] = devc->sample[j++];
502                                                 }
503                                         }
504                                         memcpy(devc->sample, devc->tmp_sample, 4);
505                                         sr_spew("Expanded sample: 0x%.8x.", sample);
506                                 }
507
508                                 /*
509                                  * Pipistrello OLS sends its sample buffer backwards.
510                                  * store it in reverse order here, so we can dump
511                                  * this on the session bus later.
512                                  */
513                                 offset = (devc->limit_samples - devc->num_samples) * 4;
514                                 for (i = 0; i <= devc->rle_count; i++) {
515                                         memcpy(devc->raw_sample_buf + offset + (i * 4),
516                                                devc->sample, 4);
517                                 }
518                                 memset(devc->sample, 0, 4);
519                                 devc->num_bytes = 0;
520                                 devc->rle_count = 0;
521                         }
522                 }
523                 return TRUE;
524         } else {
525                 /*
526                  * We've acquired all the samples we asked for -- we're done.
527                  * Send the (properly-ordered) buffer to the frontend.
528                  */
529                 sr_dbg("Received %d bytes, %d samples, %d decompressed samples.",
530                                 devc->cnt_bytes, devc->cnt_samples,
531                                 devc->cnt_samples_rle);
532                 if (devc->trigger_at != -1) {
533                         /*
534                          * A trigger was set up, so we need to tell the frontend
535                          * about it.
536                          */
537                         if (devc->trigger_at > 0) {
538                                 /* There are pre-trigger samples, send those first. */
539                                 packet.type = SR_DF_LOGIC;
540                                 packet.payload = &logic;
541                                 logic.length = devc->trigger_at * 4;
542                                 logic.unitsize = 4;
543                                 logic.data = devc->raw_sample_buf +
544                                         (devc->limit_samples - devc->num_samples) * 4;
545                                 sr_session_send(cb_data, &packet);
546                         }
547
548                         /* Send the trigger. */
549                         packet.type = SR_DF_TRIGGER;
550                         sr_session_send(cb_data, &packet);
551
552                         /* Send post-trigger samples. */
553                         packet.type = SR_DF_LOGIC;
554                         packet.payload = &logic;
555                         logic.length = (devc->num_samples * 4) - (devc->trigger_at * 4);
556                         logic.unitsize = 4;
557                         logic.data = devc->raw_sample_buf + devc->trigger_at * 4 +
558                                 (devc->limit_samples - devc->num_samples) * 4;
559                         sr_session_send(cb_data, &packet);
560                 } else {
561                         /* no trigger was used */
562                         packet.type = SR_DF_LOGIC;
563                         packet.payload = &logic;
564                         logic.length = devc->num_samples * 4;
565                         logic.unitsize = 4;
566                         logic.data = devc->raw_sample_buf +
567                                 (devc->limit_samples - devc->num_samples) * 4;
568                         sr_session_send(cb_data, &packet);
569                 }
570                 g_free(devc->raw_sample_buf);
571
572                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
573         }
574
575         return TRUE;
576 }