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