]> sigrok.org Git - libsigrok.git/blob - hardware/chronovu-la/protocol.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / hardware / chronovu-la / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2011-2014 Uwe Hermann <uwe@hermann-uwe.de>
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 2 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include "protocol.h"
22
23 SR_PRIV const struct cv_profile cv_profiles[] = {
24         { CHRONOVU_LA8,  "LA8",  "ChronoVu LA8",  8,  SR_MHZ(100), "01",
25           0.8388608 },
26         { CHRONOVU_LA16, "LA16", "ChronoVu LA16", 16, SR_MHZ(200), "01rf",
27           0.042 },
28         { 0, NULL, NULL, 0, 0, NULL, 0.0 },
29 };
30
31 /* LA8: channels are numbered 0-7. LA16: channels are numbered 0-15. */
32 SR_PRIV const char *cv_channel_names[] = {
33         "0", "1", "2", "3", "4", "5", "6", "7",
34         "8", "9", "10", "11", "12", "13", "14", "15",
35 };
36
37 static int close_usb_reset_sequencer(struct dev_context *devc);
38
39 SR_PRIV void cv_fill_samplerates_if_needed(const struct sr_dev_inst *sdi)
40 {
41         int i;
42         struct dev_context *devc;
43
44         devc = sdi->priv;
45
46         if (devc->samplerates[0] != 0)
47                 return;
48
49         for (i = 0; i < 255; i++)
50                 devc->samplerates[254 - i] = devc->prof->max_samplerate / (i + 1);
51 }
52
53 /**
54  * Check if the given samplerate is supported by the hardware.
55  *
56  * @param sdi Device instance.
57  * @param samplerate The samplerate (in Hz) to check.
58  *
59  * @return 1 if the samplerate is supported/valid, 0 otherwise.
60  */
61 static int is_valid_samplerate(const struct sr_dev_inst *sdi,
62                                uint64_t samplerate)
63 {
64         int i;
65         struct dev_context *devc;
66
67         devc = sdi->priv;
68
69         cv_fill_samplerates_if_needed(sdi);
70
71         for (i = 0; i < 255; i++) {
72                 if (devc->samplerates[i] == samplerate)
73                         return 1;
74         }
75
76         sr_err("Invalid samplerate (%" PRIu64 "Hz).", samplerate);
77
78         return 0;
79 }
80
81 /**
82  * Convert a samplerate (in Hz) to the 'divcount' value the device wants.
83  *
84  * The divcount value can be 0x00 - 0xfe (0xff is not valid).
85  *
86  * LA8:
87  * sample period = (divcount + 1) * 10ns.
88  * divcount = 0x00: 10ns period, 100MHz samplerate.
89  * divcount = 0xfe: 2550ns period, 392.15kHz samplerate.
90  *
91  * LA16:
92  * sample period = (divcount + 1) * 5ns.
93  * divcount = 0x00: 5ns period, 200MHz samplerate.
94  * divcount = 0xfe: 1275ns period, ~784.31kHz samplerate.
95  *
96  * @param sdi Device instance.
97  * @param samplerate The samplerate in Hz.
98  *
99  * @return The divcount value as needed by the hardware, or 0xff upon errors.
100  */
101 SR_PRIV uint8_t cv_samplerate_to_divcount(const struct sr_dev_inst *sdi,
102                                           uint64_t samplerate)
103 {
104         struct dev_context *devc;
105
106         devc = sdi->priv;
107
108         if (samplerate == 0) {
109                 sr_err("Can't convert invalid samplerate of 0 Hz.");
110                 return 0xff;
111         }
112
113         if (!is_valid_samplerate(sdi, samplerate)) {
114                 sr_err("Can't get divcount, samplerate invalid.");
115                 return 0xff;
116         }
117
118         return (devc->prof->max_samplerate / samplerate) - 1;
119 }
120
121 /**
122  * Write data of a certain length to the FTDI device.
123  *
124  * @param devc The struct containing private per-device-instance data. Must not
125  *             be NULL. devc->ftdic must not be NULL either.
126  * @param buf The buffer containing the data to write. Must not be NULL.
127  * @param size The number of bytes to write. Must be > 0.
128  *
129  * @return The number of bytes written, or a negative value upon errors.
130  */
131 SR_PRIV int cv_write(struct dev_context *devc, uint8_t *buf, int size)
132 {
133         int bytes_written;
134
135         /* Note: Caller ensures devc/devc->ftdic/buf != NULL and size > 0. */
136
137         bytes_written = ftdi_write_data(devc->ftdic, buf, size);
138
139         if (bytes_written < 0) {
140                 sr_err("Failed to write data (%d): %s.",
141                        bytes_written, ftdi_get_error_string(devc->ftdic));
142                 (void) close_usb_reset_sequencer(devc); /* Ignore errors. */
143         } else if (bytes_written != size) {
144                 sr_err("Failed to write data, only %d/%d bytes written.",
145                        size, bytes_written);
146                 (void) close_usb_reset_sequencer(devc); /* Ignore errors. */
147         }
148
149         return bytes_written;
150 }
151
152 /**
153  * Read a certain amount of bytes from the FTDI device.
154  *
155  * @param devc The struct containing private per-device-instance data. Must not
156  *             be NULL. devc->ftdic must not be NULL either.
157  * @param buf The buffer where the received data will be stored. Must not
158  *            be NULL.
159  * @param size The number of bytes to read. Must be >= 1.
160  *
161  * @return The number of bytes read, or a negative value upon errors.
162  */
163 static int cv_read(struct dev_context *devc, uint8_t *buf, int size)
164 {
165         int bytes_read;
166
167         /* Note: Caller ensures devc/devc->ftdic/buf != NULL and size > 0. */
168
169         bytes_read = ftdi_read_data(devc->ftdic, buf, size);
170
171         if (bytes_read < 0) {
172                 sr_err("Failed to read data (%d): %s.",
173                        bytes_read, ftdi_get_error_string(devc->ftdic));
174         } else if (bytes_read != size) {
175                 // sr_err("Failed to read data, only %d/%d bytes read.",
176                 //        bytes_read, size);
177         }
178
179         return bytes_read;
180 }
181
182 /**
183  * Close the USB port and reset the sequencer logic.
184  *
185  * @param devc The struct containing private per-device-instance data.
186  *
187  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments.
188  */
189 static int close_usb_reset_sequencer(struct dev_context *devc)
190 {
191         /* Magic sequence of bytes for resetting the sequencer logic. */
192         uint8_t buf[8] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
193         int ret;
194
195         /* Note: Caller checked that devc and devc->ftdic != NULL. */
196
197         if (devc->ftdic->usb_dev) {
198                 /* Reset the sequencer logic, then wait 100ms. */
199                 sr_dbg("Resetting sequencer logic.");
200                 (void) cv_write(devc, buf, 8); /* Ignore errors. */
201                 g_usleep(100 * 1000);
202
203                 /* Purge FTDI buffers, then reset and close the FTDI device. */
204                 sr_dbg("Purging buffers, resetting+closing FTDI device.");
205
206                 /* Log errors, but ignore them (i.e., don't abort). */
207                 if ((ret = ftdi_usb_purge_buffers(devc->ftdic)) < 0)
208                         sr_err("Failed to purge FTDI buffers (%d): %s.",
209                                ret, ftdi_get_error_string(devc->ftdic));
210                 if ((ret = ftdi_usb_reset(devc->ftdic)) < 0)
211                         sr_err("Failed to reset FTDI device (%d): %s.",
212                                ret, ftdi_get_error_string(devc->ftdic));
213                 if ((ret = ftdi_usb_close(devc->ftdic)) < 0)
214                         sr_err("Failed to close FTDI device (%d): %s.",
215                                ret, ftdi_get_error_string(devc->ftdic));
216         }
217
218         /* Close USB device, deinitialize and free the FTDI context. */
219         ftdi_free(devc->ftdic);
220         devc->ftdic = NULL;
221
222         return SR_OK;
223 }
224
225 /**
226  * Reset the ChronoVu device.
227  *
228  * A reset is required after a failed read/write operation or upon timeouts.
229  *
230  * @param devc The struct containing private per-device-instance data.
231  *
232  * @return SR_OK upon success, SR_ERR upon failure.
233  */
234 static int reset_device(struct dev_context *devc)
235 {
236         uint8_t buf[BS];
237         gint64 done, now;
238         int bytes_read;
239
240         /* Note: Caller checked that devc and devc->ftdic != NULL. */
241
242         sr_dbg("Resetting the device.");
243
244         /*
245          * Purge pending read data from the FTDI hardware FIFO until
246          * no more data is left, or a timeout occurs (after 20s).
247          */
248         done = (20 * G_TIME_SPAN_SECOND) + g_get_monotonic_time();
249         do {
250                 /* Try to read bytes until none are left (or errors occur). */
251                 bytes_read = cv_read(devc, (uint8_t *)&buf, BS);
252                 now = g_get_monotonic_time();
253         } while ((done > now) && (bytes_read > 0));
254
255         /* Reset the sequencer logic and close the USB port. */
256         (void) close_usb_reset_sequencer(devc); /* Ignore errors. */
257
258         sr_dbg("Device reset finished.");
259
260         return SR_OK;
261 }
262
263 SR_PRIV int cv_configure_channels(const struct sr_dev_inst *sdi)
264 {
265         struct dev_context *devc;
266         const struct sr_channel *ch;
267         const GSList *l;
268         uint16_t channel_bit;
269         char *tc;
270
271         devc = sdi->priv;
272         devc->trigger_pattern = 0x0000; /* Default to "low" trigger. */
273         devc->trigger_mask = 0x0000; /* Default to "don't care". */
274         devc->trigger_edgemask = 0x0000; /* Default to "state triggered". */
275
276         for (l = sdi->channels; l; l = l->next) {
277                 ch = (struct sr_channel *)l->data;
278
279                 if (!ch) {
280                         sr_err("%s: channel was NULL.", __func__);
281                         return SR_ERR;
282                 }
283
284                 /* Skip disabled channels. */
285                 if (!ch->enabled)
286                         continue;
287
288                 /* Skip (enabled) channels with no configured trigger. */
289                 if (!ch->trigger)
290                         continue;
291
292                 /* Note: Must only be run if ch->trigger != NULL. */
293                 if (ch->index < 0 || ch->index > (int)devc->prof->num_channels - 1) {
294                         sr_err("Invalid channel index %d, must be "
295                                "between 0 and %d.", ch->index,
296                                devc->prof->num_channels - 1);
297                         return SR_ERR;
298                 }
299
300                 channel_bit = (1 << (ch->index));
301
302                 /* Configure the channel's trigger pattern/mask/edgemask. */
303                 for (tc = ch->trigger; tc && *tc; tc++) {
304                         devc->trigger_mask |= channel_bit;
305
306                         /* Sanity check, LA8 only supports low/high trigger. */
307                         if ((devc->prof->model == CHRONOVU_LA8) &&
308                             (*tc != '0' && *tc != '1')) {
309                                 sr_err("Invalid trigger '%c', only "
310                                        "'0'/'1' supported.", *tc);
311                                 return SR_ERR;
312                         }
313
314                         /* state: 1 == high, edge: 1 == rising edge. */
315                         if (*tc == '1' || *tc == 'r')
316                                 devc->trigger_pattern |= channel_bit;
317
318                         /* LA16 (but not LA8) supports edge triggering. */
319                         if ((devc->prof->model == CHRONOVU_LA16)) {
320                                 if (*tc == 'r' || *tc == 'f')
321                                         devc->trigger_edgemask |= channel_bit;
322                         }
323
324                 }
325         }
326
327         sr_dbg("Trigger pattern/mask/edgemask = 0x%04x / 0x%04x / 0x%04x.",
328                devc->trigger_pattern, devc->trigger_mask,
329                devc->trigger_edgemask);
330
331         return SR_OK;
332 }
333
334 SR_PRIV int cv_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate)
335 {
336         struct dev_context *devc;
337
338         /* Note: Caller checked that sdi and sdi->priv != NULL. */
339
340         devc = sdi->priv;
341
342         sr_spew("Trying to set samplerate to %" PRIu64 "Hz.", samplerate);
343
344         cv_fill_samplerates_if_needed(sdi);
345
346         /* Check if this is a samplerate supported by the hardware. */
347         if (!is_valid_samplerate(sdi, samplerate)) {
348                 sr_dbg("Failed to set invalid samplerate (%" PRIu64 "Hz).",
349                        samplerate);
350                 return SR_ERR;
351         }
352
353         devc->cur_samplerate = samplerate;
354
355         sr_dbg("Samplerate set to %" PRIu64 "Hz.", devc->cur_samplerate);
356
357         return SR_OK;
358 }
359
360 /**
361  * Get a block of data from the device.
362  *
363  * @param devc The struct containing private per-device-instance data. Must not
364  *             be NULL. devc->ftdic must not be NULL either.
365  *
366  * @return SR_OK upon success, or SR_ERR upon errors.
367  */
368 SR_PRIV int cv_read_block(struct dev_context *devc)
369 {
370         int i, byte_offset, m, mi, p, q, index, bytes_read;
371         gint64 now;
372
373         /* Note: Caller checked that devc and devc->ftdic != NULL. */
374
375         sr_spew("Reading block %d.", devc->block_counter);
376
377         bytes_read = cv_read(devc, devc->mangled_buf, BS);
378
379         /* If first block read got 0 bytes, retry until success or timeout. */
380         if ((bytes_read == 0) && (devc->block_counter == 0)) {
381                 do {
382                         sr_spew("Reading block 0 (again).");
383                         /* Note: If bytes_read < 0 cv_read() will log errors. */
384                         bytes_read = cv_read(devc, devc->mangled_buf, BS);
385                         now = g_get_monotonic_time();
386                 } while ((devc->done > now) && (bytes_read == 0));
387         }
388
389         /* Check if block read was successful or a timeout occured. */
390         if (bytes_read != BS) {
391                 sr_err("Trigger timed out. Bytes read: %d.", bytes_read);
392                 (void) reset_device(devc); /* Ignore errors. */
393                 return SR_ERR;
394         }
395
396         /* De-mangle the data. */
397         sr_spew("Demangling block %d.", devc->block_counter);
398         byte_offset = devc->block_counter * BS;
399         m = byte_offset / (1024 * 1024);
400         mi = m * (1024 * 1024);
401         for (i = 0; i < BS; i++) {
402                 if (devc->prof->model == CHRONOVU_LA8) {
403                         p = i & (1 << 0);
404                         index = m * 2 + (((byte_offset + i) - mi) / 2) * 16;
405                         index += (devc->divcount == 0) ? p : (1 - p);
406                 } else {
407                         p = i & (1 << 0);
408                         q = i & (1 << 1);
409                         index = m * 4 + (((byte_offset + i) - mi) / 4) * 32;
410                         index += q + (1 - p);
411                 }
412                 devc->final_buf[index] = devc->mangled_buf[i];
413         }
414
415         return SR_OK;
416 }
417
418 SR_PRIV void cv_send_block_to_session_bus(struct dev_context *devc, int block)
419 {
420         int i, idx;
421         uint8_t sample, expected_sample, tmp8;
422         struct sr_datafeed_packet packet;
423         struct sr_datafeed_logic logic;
424         int trigger_point; /* Relative trigger point (in this block). */
425
426         /* Note: Caller ensures devc/devc->ftdic != NULL and block > 0. */
427
428         /* TODO: Implement/test proper trigger support for the LA16. */
429
430         /* Check if we can find the trigger condition in this block. */
431         trigger_point = -1;
432         expected_sample = devc->trigger_pattern & devc->trigger_mask;
433         for (i = 0; i < BS; i++) {
434                 /* Don't continue if the trigger was found previously. */
435                 if (devc->trigger_found)
436                         break;
437
438                 /*
439                  * Also, don't continue if triggers are "don't care", i.e. if
440                  * no trigger conditions were specified by the user. In that
441                  * case we don't want to send an SR_DF_TRIGGER packet at all.
442                  */
443                 if (devc->trigger_mask == 0x0000)
444                         break;
445
446                 sample = *(devc->final_buf + (block * BS) + i);
447
448                 if ((sample & devc->trigger_mask) == expected_sample) {
449                         trigger_point = i;
450                         devc->trigger_found = 1;
451                         break;
452                 }
453         }
454
455         /* Swap low and high bytes of the 16-bit LA16 samples. */
456         if (devc->prof->model == CHRONOVU_LA16) {
457                 for (i = 0; i < BS; i += 2) {
458                         idx = (block * BS) + i;
459                         tmp8 = devc->final_buf[idx];
460                         devc->final_buf[idx] = devc->final_buf[idx + 1];
461                         devc->final_buf[idx + 1] = tmp8;
462                 }
463         }
464
465         /* If no trigger was found, send one SR_DF_LOGIC packet. */
466         if (trigger_point == -1) {
467                 /* Send an SR_DF_LOGIC packet to the session bus. */
468                 sr_spew("Sending SR_DF_LOGIC packet (%d bytes) for "
469                         "block %d.", BS, block);
470                 packet.type = SR_DF_LOGIC;
471                 packet.payload = &logic;
472                 logic.length = BS;
473                 logic.unitsize = devc->prof->num_channels / 8;
474                 logic.data = devc->final_buf + (block * BS);
475                 sr_session_send(devc->cb_data, &packet);
476                 return;
477         }
478
479         /*
480          * We found the trigger, so some special handling is needed. We have
481          * to send an SR_DF_LOGIC packet with the samples before the trigger
482          * (if any), then the SD_DF_TRIGGER packet itself, then another
483          * SR_DF_LOGIC packet with the samples after the trigger (if any).
484          */
485
486         /* TODO: Send SR_DF_TRIGGER packet before or after the actual sample? */
487
488         /* If at least one sample is located before the trigger... */
489         if (trigger_point > 0) {
490                 /* Send pre-trigger SR_DF_LOGIC packet to the session bus. */
491                 sr_spew("Sending pre-trigger SR_DF_LOGIC packet, "
492                         "start = %d, length = %d.", block * BS, trigger_point);
493                 packet.type = SR_DF_LOGIC;
494                 packet.payload = &logic;
495                 logic.length = trigger_point;
496                 logic.unitsize = devc->prof->num_channels / 8;
497                 logic.data = devc->final_buf + (block * BS);
498                 sr_session_send(devc->cb_data, &packet);
499         }
500
501         /* Send the SR_DF_TRIGGER packet to the session bus. */
502         sr_spew("Sending SR_DF_TRIGGER packet, sample = %d.",
503                 (block * BS) + trigger_point);
504         packet.type = SR_DF_TRIGGER;
505         packet.payload = NULL;
506         sr_session_send(devc->cb_data, &packet);
507
508         /* If at least one sample is located after the trigger... */
509         if (trigger_point < (BS - 1)) {
510                 /* Send post-trigger SR_DF_LOGIC packet to the session bus. */
511                 sr_spew("Sending post-trigger SR_DF_LOGIC packet, "
512                         "start = %d, length = %d.",
513                         (block * BS) + trigger_point, BS - trigger_point);
514                 packet.type = SR_DF_LOGIC;
515                 packet.payload = &logic;
516                 logic.length = BS - trigger_point;
517                 logic.unitsize = devc->prof->num_channels / 8;
518                 logic.data = devc->final_buf + (block * BS) + trigger_point;
519                 sr_session_send(devc->cb_data, &packet);
520         }
521 }