]> sigrok.org Git - libsigrok.git/blob - hardware/zeroplus-logic-cube/api.c
zeroplus: Add voltage threshold support
[libsigrok.git] / hardware / zeroplus-logic-cube / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 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 #define VENDOR_NAME                     "ZEROPLUS"
23 #define USB_INTERFACE                   0
24 #define USB_CONFIGURATION               1
25 #define NUM_TRIGGER_STAGES              4
26 #define TRIGGER_TYPE                    "01"
27 #define PACKET_SIZE                     2048    /* ?? */
28
29 //#define ZP_EXPERIMENTAL
30
31 struct zp_model {
32         uint16_t vid;
33         uint16_t pid;
34         char *model_name;
35         unsigned int channels;
36         unsigned int sample_depth;      /* In Ksamples/channel */
37         unsigned int max_sampling_freq;
38 };
39
40 /*
41  * Note -- 16032, 16064 and 16128 *usually* -- but not always -- have the
42  * same 128K sample depth.
43  */
44 static const struct zp_model zeroplus_models[] = {
45         {0x0c12, 0x7002, "LAP-16128U",    16, 128,  200},
46         {0x0c12, 0x7009, "LAP-C(16064)",  16, 64,   100},
47         {0x0c12, 0x700a, "LAP-C(16128)",  16, 128,  200},
48         {0x0c12, 0x700b, "LAP-C(32128)",  32, 128,  200},
49         {0x0c12, 0x700c, "LAP-C(321000)", 32, 1024, 200},
50         {0x0c12, 0x700d, "LAP-C(322000)", 32, 2048, 200},
51         {0x0c12, 0x700e, "LAP-C(16032)",  16, 32,   100},
52         {0x0c12, 0x7016, "LAP-C(162000)", 16, 2048, 200},
53         { 0, 0, 0, 0, 0, 0 }
54 };
55
56 static const int32_t hwcaps[] = {
57         SR_CONF_LOGIC_ANALYZER,
58         SR_CONF_SAMPLERATE,
59         SR_CONF_CAPTURE_RATIO,
60         SR_CONF_VOLTAGE_THRESHOLD,
61         SR_CONF_LIMIT_SAMPLES,
62 };
63
64 /*
65  * ZEROPLUS LAP-C (16032) numbers the 16 probes A0-A7 and B0-B7.
66  * We currently ignore other untested/unsupported devices here.
67  */
68 static const char *probe_names[] = {
69         "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7",
70         "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7",
71         "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7",
72         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
73         NULL,
74 };
75
76 SR_PRIV struct sr_dev_driver zeroplus_logic_cube_driver_info;
77 static struct sr_dev_driver *di = &zeroplus_logic_cube_driver_info;
78
79 /*
80  * The hardware supports more samplerates than these, but these are the
81  * options hardcoded into the vendor's Windows GUI.
82  */
83
84 static const uint64_t samplerates_100[] = {
85         SR_HZ(100),
86         SR_HZ(500),
87         SR_KHZ(1),
88         SR_KHZ(5),
89         SR_KHZ(25),
90         SR_KHZ(50),
91         SR_KHZ(100),
92         SR_KHZ(200),
93         SR_KHZ(400),
94         SR_KHZ(800),
95         SR_MHZ(1),
96         SR_MHZ(10),
97         SR_MHZ(25),
98         SR_MHZ(50),
99         SR_MHZ(80),
100         SR_MHZ(100),
101 };
102
103 const uint64_t samplerates_200[] = {
104         SR_HZ(100),
105         SR_HZ(500),
106         SR_KHZ(1),
107         SR_KHZ(5),
108         SR_KHZ(25),
109         SR_KHZ(50),
110         SR_KHZ(100),
111         SR_KHZ(200),
112         SR_KHZ(400),
113         SR_KHZ(800),
114         SR_MHZ(1),
115         SR_MHZ(10),
116         SR_MHZ(25),
117         SR_MHZ(50),
118         SR_MHZ(80),
119         SR_MHZ(100),
120         SR_MHZ(150),
121         SR_MHZ(200),
122 };
123
124 static int dev_close(struct sr_dev_inst *sdi);
125
126 #if 0
127 static int configure_probes(const struct sr_dev_inst *sdi)
128 {
129         struct dev_context *devc;
130         const struct sr_probe *probe;
131         const GSList *l;
132         int probe_bit, stage, i;
133         char *tc;
134
135         /* Note: sdi and sdi->priv are non-NULL, the caller checked this. */
136         devc = sdi->priv;
137
138         devc->probe_mask = 0;
139         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
140                 devc->trigger_mask[i] = 0;
141                 devc->trigger_value[i] = 0;
142         }
143
144         stage = -1;
145         for (l = sdi->probes; l; l = l->next) {
146                 probe = (struct sr_probe *)l->data;
147                 if (probe->enabled == FALSE)
148                         continue;
149                 probe_bit = 1 << (probe->index);
150                 devc->probe_mask |= probe_bit;
151
152                 if (probe->trigger) {
153                         stage = 0;
154                         for (tc = probe->trigger; *tc; tc++) {
155                                 devc->trigger_mask[stage] |= probe_bit;
156                                 if (*tc == '1')
157                                         devc->trigger_value[stage] |= probe_bit;
158                                 stage++;
159                                 if (stage > NUM_TRIGGER_STAGES)
160                                         return SR_ERR;
161                         }
162                 }
163         }
164
165         return SR_OK;
166 }
167 #endif
168
169 static int configure_probes(const struct sr_dev_inst *sdi)
170 {
171         struct dev_context *devc;
172         const GSList *l;
173         const struct sr_probe *probe;
174         char *tc;
175         int type;
176
177         /* Note: sdi and sdi->priv are non-NULL, the caller checked this. */
178         devc = sdi->priv;
179
180         for (l = sdi->probes; l; l = l->next) {
181                 probe = (struct sr_probe *)l->data;
182                 if (probe->enabled == FALSE)
183                         continue;
184
185                 if ((tc = probe->trigger)) {
186                         switch (*tc) {
187                         case '1':
188                                 type = TRIGGER_HIGH;
189                                 break;
190                         case '0':
191                                 type = TRIGGER_LOW;
192                                 break;
193 #if 0
194                         case 'r':
195                                 type = TRIGGER_POSEDGE;
196                                 break;
197                         case 'f':
198                                 type = TRIGGER_NEGEDGE;
199                                 break;
200                         case 'c':
201                                 type = TRIGGER_ANYEDGE;
202                                 break;
203 #endif
204                         default:
205                                 return SR_ERR;
206                         }
207                         analyzer_add_trigger(probe->index, type);
208                         devc->trigger = 1;
209                 }
210         }
211
212         return SR_OK;
213 }
214
215 SR_PRIV int zp_set_samplerate(struct dev_context *devc, uint64_t samplerate)
216 {
217         int i;
218
219         for (i = 0; ARRAY_SIZE(samplerates_200); i++)
220                 if (samplerate == samplerates_200[i])
221                         break;
222
223         if (i == ARRAY_SIZE(samplerates_200) || samplerate > devc->max_samplerate) {
224                 sr_err("Unsupported samplerate: %" PRIu64 "Hz.", samplerate);
225                 return SR_ERR_ARG;
226         }
227
228         sr_info("Setting samplerate to %" PRIu64 "Hz.", samplerate);
229
230         if (samplerate >= SR_MHZ(1))
231                 analyzer_set_freq(samplerate / SR_MHZ(1), FREQ_SCALE_MHZ);
232         else if (samplerate >= SR_KHZ(1))
233                 analyzer_set_freq(samplerate / SR_KHZ(1), FREQ_SCALE_KHZ);
234         else
235                 analyzer_set_freq(samplerate, FREQ_SCALE_HZ);
236
237         devc->cur_samplerate = samplerate;
238
239         return SR_OK;
240 }
241
242 static int dev_clear(void)
243 {
244         return std_dev_clear(di, NULL);
245 }
246
247 static int init(struct sr_context *sr_ctx)
248 {
249         return std_init(sr_ctx, di, LOG_PREFIX);
250 }
251
252 static GSList *scan(GSList *options)
253 {
254         struct sr_dev_inst *sdi;
255         struct sr_probe *probe;
256         struct drv_context *drvc;
257         struct dev_context *devc;
258         const struct zp_model *prof;
259         struct libusb_device_descriptor des;
260         libusb_device **devlist;
261         GSList *devices;
262         int ret, devcnt, i, j;
263
264         (void)options;
265
266         drvc = di->priv;
267
268         devices = NULL;
269
270         /* Find all ZEROPLUS analyzers and add them to device list. */
271         devcnt = 0;
272         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); /* TODO: Errors. */
273
274         for (i = 0; devlist[i]; i++) {
275                 ret = libusb_get_device_descriptor(devlist[i], &des);
276                 if (ret != 0) {
277                         sr_err("Failed to get device descriptor: %s.",
278                                libusb_error_name(ret));
279                         continue;
280                 }
281
282                 prof = NULL;
283                 for (j = 0; j < zeroplus_models[j].vid; j++) {
284                         if (des.idVendor == zeroplus_models[j].vid &&
285                                 des.idProduct == zeroplus_models[j].pid) {
286                                 prof = &zeroplus_models[j];
287                         }
288                 }
289                 /* Skip if the device was not found. */
290                 if (!prof)
291                         continue;
292                 sr_info("Found ZEROPLUS %s.", prof->model_name);
293
294                 /* Register the device with libsigrok. */
295                 if (!(sdi = sr_dev_inst_new(devcnt, SR_ST_INACTIVE,
296                                 VENDOR_NAME, prof->model_name, NULL))) {
297                         sr_err("%s: sr_dev_inst_new failed", __func__);
298                         return NULL;
299                 }
300                 sdi->driver = di;
301
302                 /* Allocate memory for our private driver context. */
303                 if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
304                         sr_err("Device context malloc failed.");
305                         return NULL;
306                 }
307
308                 sdi->priv = devc;
309                 devc->prof = prof;
310                 devc->num_channels = prof->channels;
311 #ifdef ZP_EXPERIMENTAL
312                 devc->max_sample_depth = 128 * 1024;
313                 devc->max_samplerate = 200;
314 #else
315                 devc->max_sample_depth = prof->sample_depth * 1024;
316                 devc->max_samplerate = prof->max_sampling_freq;
317 #endif
318                 devc->max_samplerate *= SR_MHZ(1);
319                 devc->memory_size = MEMORY_SIZE_8K;
320                 // memset(devc->trigger_buffer, 0, NUM_TRIGGER_STAGES);
321
322                 /* Fill in probelist according to this device's profile. */
323                 for (j = 0; j < devc->num_channels; j++) {
324                         if (!(probe = sr_probe_new(j, SR_PROBE_LOGIC, TRUE,
325                                         probe_names[j])))
326                                 return NULL;
327                         sdi->probes = g_slist_append(sdi->probes, probe);
328                 }
329
330                 devices = g_slist_append(devices, sdi);
331                 drvc->instances = g_slist_append(drvc->instances, sdi);
332                 sdi->inst_type = SR_INST_USB;
333                 sdi->conn = sr_usb_dev_inst_new(
334                         libusb_get_bus_number(devlist[i]),
335                         libusb_get_device_address(devlist[i]), NULL);
336                 devcnt++;
337
338         }
339         libusb_free_device_list(devlist, 1);
340
341         return devices;
342 }
343
344 static GSList *dev_list(void)
345 {
346         return ((struct drv_context *)(di->priv))->instances;
347 }
348
349 static int dev_open(struct sr_dev_inst *sdi)
350 {
351         struct dev_context *devc;
352         struct drv_context *drvc;
353         struct sr_usb_dev_inst *usb;
354         libusb_device **devlist, *dev;
355         struct libusb_device_descriptor des;
356         int device_count, ret, i;
357
358         drvc = di->priv;
359         usb = sdi->conn;
360
361         if (!(devc = sdi->priv)) {
362                 sr_err("%s: sdi->priv was NULL", __func__);
363                 return SR_ERR_ARG;
364         }
365
366         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx,
367                                               &devlist);
368         if (device_count < 0) {
369                 sr_err("Failed to retrieve device list.");
370                 return SR_ERR;
371         }
372
373         dev = NULL;
374         for (i = 0; i < device_count; i++) {
375                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
376                         sr_err("Failed to get device descriptor: %s.",
377                                libusb_error_name(ret));
378                         continue;
379                 }
380                 if (libusb_get_bus_number(devlist[i]) == usb->bus
381                     && libusb_get_device_address(devlist[i]) == usb->address) {
382                         dev = devlist[i];
383                         break;
384                 }
385         }
386         if (!dev) {
387                 sr_err("Device on bus %d address %d disappeared!",
388                        usb->bus, usb->address);
389                 return SR_ERR;
390         }
391
392         if (!(ret = libusb_open(dev, &(usb->devhdl)))) {
393                 sdi->status = SR_ST_ACTIVE;
394                 sr_info("Opened device %d on %d.%d interface %d.",
395                         sdi->index, usb->bus, usb->address, USB_INTERFACE);
396         } else {
397                 sr_err("Failed to open device: %s.", libusb_error_name(ret));
398                 return SR_ERR;
399         }
400
401         ret = libusb_set_configuration(usb->devhdl, USB_CONFIGURATION);
402         if (ret < 0) {
403                 sr_err("Unable to set USB configuration %d: %s.",
404                        USB_CONFIGURATION, libusb_error_name(ret));
405                 return SR_ERR;
406         }
407
408         ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
409         if (ret != 0) {
410                 sr_err("Unable to claim interface: %s.",
411                        libusb_error_name(ret));
412                 return SR_ERR;
413         }
414
415         /* Set default configuration after power on. */
416         if (analyzer_read_status(usb->devhdl) == 0)
417                 analyzer_configure(usb->devhdl);
418
419         analyzer_reset(usb->devhdl);
420         analyzer_initialize(usb->devhdl);
421
422         //analyzer_set_memory_size(MEMORY_SIZE_512K);
423         // analyzer_set_freq(g_freq, g_freq_scale);
424         analyzer_set_trigger_count(1);
425         // analyzer_set_ramsize_trigger_address((((100 - g_pre_trigger)
426         // * get_memory_size(g_memory_size)) / 100) >> 2);
427
428 #if 0
429         if (g_double_mode == 1)
430                 analyzer_set_compression(COMPRESSION_DOUBLE);
431         else if (g_compression == 1)
432                 analyzer_set_compression(COMPRESSION_ENABLE);
433         else
434 #endif
435         analyzer_set_compression(COMPRESSION_NONE);
436
437         if (devc->cur_samplerate == 0) {
438                 /* Samplerate hasn't been set. Default to 1MHz. */
439                 analyzer_set_freq(1, FREQ_SCALE_MHZ);
440                 devc->cur_samplerate = SR_MHZ(1);
441         }
442
443         if (devc->cur_threshold == 0)
444                 set_voltage_threshold(devc, 1.5);
445
446         return SR_OK;
447 }
448
449 static int dev_close(struct sr_dev_inst *sdi)
450 {
451         struct sr_usb_dev_inst *usb;
452
453         usb = sdi->conn;
454
455         if (!usb->devhdl)
456                 return SR_ERR;
457
458         sr_info("Closing device %d on %d.%d interface %d.", sdi->index,
459                 usb->bus, usb->address, USB_INTERFACE);
460         libusb_release_interface(usb->devhdl, USB_INTERFACE);
461         libusb_reset_device(usb->devhdl);
462         libusb_close(usb->devhdl);
463         usb->devhdl = NULL;
464         sdi->status = SR_ST_INACTIVE;
465
466         return SR_OK;
467 }
468
469 static int cleanup(void)
470 {
471         return dev_clear();
472 }
473
474 static int config_get(int id, GVariant **data, const struct sr_dev_inst *sdi,
475                 const struct sr_probe_group *probe_group)
476 {
477         struct dev_context *devc;
478
479         (void)probe_group;
480
481         switch (id) {
482         case SR_CONF_SAMPLERATE:
483                 if (sdi) {
484                         devc = sdi->priv;
485                         *data = g_variant_new_uint64(devc->cur_samplerate);
486                         sr_spew("Returning samplerate: %" PRIu64 "Hz.",
487                                 devc->cur_samplerate);
488                 } else
489                         return SR_ERR;
490                 break;
491         case SR_CONF_CAPTURE_RATIO:
492                 if (sdi) {
493                         devc = sdi->priv;
494                         *data = g_variant_new_uint64(devc->capture_ratio);
495                 } else
496                         return SR_ERR;
497                 break;
498         case SR_CONF_VOLTAGE_THRESHOLD:
499                 if (sdi) {
500                         GVariant *range[2];
501                         devc = sdi->priv;
502                         range[0] = g_variant_new_double(devc->cur_threshold);
503                         range[1] = g_variant_new_double(devc->cur_threshold);
504                         *data = g_variant_new_tuple(range, 2);
505                 } else
506                         return SR_ERR;
507                 break;
508         default:
509                 return SR_ERR_NA;
510         }
511
512         return SR_OK;
513 }
514
515 static int config_set(int id, GVariant *data, const struct sr_dev_inst *sdi,
516                 const struct sr_probe_group *probe_group)
517 {
518         struct dev_context *devc;
519         gdouble low, high;
520
521         (void)probe_group;
522
523         if (sdi->status != SR_ST_ACTIVE)
524                 return SR_ERR_DEV_CLOSED;
525
526         if (!(devc = sdi->priv)) {
527                 sr_err("%s: sdi->priv was NULL", __func__);
528                 return SR_ERR_ARG;
529         }
530
531         switch (id) {
532         case SR_CONF_SAMPLERATE:
533                 return zp_set_samplerate(devc, g_variant_get_uint64(data));
534         case SR_CONF_LIMIT_SAMPLES:
535                 return set_limit_samples(devc, g_variant_get_uint64(data));
536         case SR_CONF_CAPTURE_RATIO:
537                 return set_capture_ratio(devc, g_variant_get_uint64(data));
538         case SR_CONF_VOLTAGE_THRESHOLD:
539                 g_variant_get(data, "(dd)", &low, &high);
540                 return set_voltage_threshold(devc, (low + high) / 2.0);
541         default:
542                 return SR_ERR_NA;
543         }
544
545         return SR_OK;
546 }
547
548 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi,
549                 const struct sr_probe_group *probe_group)
550 {
551         struct dev_context *devc;
552         GVariant *gvar;
553         GVariantBuilder gvb;
554         double v;
555         GVariant *range[2];
556
557         (void)probe_group;
558
559         switch (key) {
560         case SR_CONF_DEVICE_OPTIONS:
561                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
562                                 hwcaps, ARRAY_SIZE(hwcaps), sizeof(int32_t));
563                 break;
564         case SR_CONF_SAMPLERATE:
565                 devc = sdi->priv;
566                 g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
567                 if (devc->prof->max_sampling_freq == 100) {
568                         gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"),
569                                         samplerates_100, ARRAY_SIZE(samplerates_100),
570                                         sizeof(uint64_t));
571                 } else if (devc->prof->max_sampling_freq == 200) {
572                         gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"),
573                                         samplerates_200, ARRAY_SIZE(samplerates_200),
574                                         sizeof(uint64_t));
575                 } else {
576                         sr_err("Internal error: Unknown max. samplerate: %d.",
577                                devc->prof->max_sampling_freq);
578                         return SR_ERR_ARG;
579                 }
580                 g_variant_builder_add(&gvb, "{sv}", "samplerates", gvar);
581                 *data = g_variant_builder_end(&gvb);
582                 break;
583         case SR_CONF_TRIGGER_TYPE:
584                 *data = g_variant_new_string(TRIGGER_TYPE);
585                 break;
586         case SR_CONF_VOLTAGE_THRESHOLD:
587                 g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
588                 for (v = -6.0; v <= 6.0; v += 0.1) {
589                         range[0] = g_variant_new_double(v);
590                         range[1] = g_variant_new_double(v);
591                         gvar = g_variant_new_tuple(range, 2);
592                         g_variant_builder_add_value(&gvb, gvar);
593                 }
594                 *data = g_variant_builder_end(&gvb);
595                 break;
596         default:
597                 return SR_ERR_NA;
598         }
599
600         return SR_OK;
601 }
602
603 static int dev_acquisition_start(const struct sr_dev_inst *sdi,
604                 void *cb_data)
605 {
606         struct dev_context *devc;
607         struct sr_usb_dev_inst *usb;
608         struct sr_datafeed_packet packet;
609         struct sr_datafeed_logic logic;
610         unsigned int samples_read;
611         int res;
612         unsigned int packet_num, n;
613         unsigned char *buf;
614         unsigned int status;
615         unsigned int stop_address;
616         unsigned int now_address;
617         unsigned int trigger_address;
618         unsigned int trigger_offset;
619         unsigned int triggerbar;
620         unsigned int ramsize_trigger;
621         unsigned int memory_size;
622         unsigned int valid_samples;
623         unsigned int discard;
624         int trigger_now;
625
626         if (sdi->status != SR_ST_ACTIVE)
627                 return SR_ERR_DEV_CLOSED;
628
629         if (!(devc = sdi->priv)) {
630                 sr_err("%s: sdi->priv was NULL", __func__);
631                 return SR_ERR_ARG;
632         }
633
634         if (configure_probes(sdi) != SR_OK) {
635                 sr_err("Failed to configure probes.");
636                 return SR_ERR;
637         }
638
639         usb = sdi->conn;
640
641         set_triggerbar(devc);
642
643         /* Push configured settings to device. */
644         analyzer_configure(usb->devhdl);
645
646         analyzer_start(usb->devhdl);
647         sr_info("Waiting for data.");
648         analyzer_wait_data(usb->devhdl);
649
650         status = analyzer_read_status(usb->devhdl);
651         stop_address = analyzer_get_stop_address(usb->devhdl);
652         now_address = analyzer_get_now_address(usb->devhdl);
653         trigger_address = analyzer_get_trigger_address(usb->devhdl);
654
655         triggerbar = analyzer_get_triggerbar_address();
656         ramsize_trigger = analyzer_get_ramsize_trigger_address();
657
658         n = get_memory_size(devc->memory_size);
659         memory_size = n / 4;
660
661         sr_info("Status = 0x%x.", status);
662         sr_info("Stop address       = 0x%x.", stop_address);
663         sr_info("Now address        = 0x%x.", now_address);
664         sr_info("Trigger address    = 0x%x.", trigger_address);
665         sr_info("Triggerbar address = 0x%x.", triggerbar);
666         sr_info("Ramsize trigger    = 0x%x.", ramsize_trigger);
667         sr_info("Memory size        = 0x%x.", memory_size);
668
669         /* Send header packet to the session bus. */
670         std_session_send_df_header(cb_data, LOG_PREFIX);
671
672         /* Check for empty capture */
673         if ((status & STATUS_READY) && !stop_address) {
674                 packet.type = SR_DF_END;
675                 sr_session_send(cb_data, &packet);
676                 return SR_OK;
677         }
678
679         if (!(buf = g_try_malloc(PACKET_SIZE))) {
680                 sr_err("Packet buffer malloc failed.");
681                 return SR_ERR_MALLOC;
682         }
683
684         /* Check if the trigger is in the samples we are throwing away */
685         trigger_now = now_address == trigger_address ||
686                 ((now_address + 1) % memory_size) == trigger_address;
687
688         /*
689          * STATUS_READY doesn't clear until now_address advances past
690          * addr 0, but for our logic, clear it in that case
691          */
692         if (!now_address)
693                 status &= ~STATUS_READY;
694
695         analyzer_read_start(usb->devhdl);
696
697         /* Calculate how much data to discard */
698         discard = 0;
699         if (status & STATUS_READY) {
700                 /*
701                  * We haven't wrapped around, we need to throw away data from
702                  * our current position to the end of the buffer.
703                  * Additionally, the first two samples captured are always
704                  * bogus.
705                  */
706                 discard += memory_size - now_address + 2;
707                 now_address = 2;
708         }
709
710         /* If we have more samples than we need, discard them */
711         valid_samples = (stop_address - now_address) % memory_size;
712         if (valid_samples > ramsize_trigger + triggerbar) {
713                 discard += valid_samples - (ramsize_trigger + triggerbar);
714                 now_address += valid_samples - (ramsize_trigger + triggerbar);
715         }
716
717         sr_info("Need to discard %d samples.", discard);
718
719         /* Calculate how far in the trigger is */
720         if (trigger_now)
721                 trigger_offset = 0;
722         else
723                 trigger_offset = (trigger_address - now_address) % memory_size;
724
725         /* Recalculate the number of samples available */
726         valid_samples = (stop_address - now_address) % memory_size;
727
728         /* Send the incoming transfer to the session bus. */
729         samples_read = 0;
730         for (packet_num = 0; packet_num < n / PACKET_SIZE; packet_num++) {
731                 unsigned int len;
732                 unsigned int buf_offset;
733
734                 res = analyzer_read_data(usb->devhdl, buf, PACKET_SIZE);
735                 sr_info("Tried to read %d bytes, actually read %d bytes.",
736                         PACKET_SIZE, res);
737
738                 if (discard >= PACKET_SIZE / 4) {
739                         discard -= PACKET_SIZE / 4;
740                         continue;
741                 }
742
743                 len = PACKET_SIZE - discard * 4;
744                 buf_offset = discard * 4;
745                 discard = 0;
746
747                 /* Check if we've read all the samples */
748                 if (samples_read + len / 4 >= valid_samples)
749                         len = (valid_samples - samples_read) * 4;
750                 if (!len)
751                         break;
752
753                 if (samples_read < trigger_offset &&
754                     samples_read + len / 4 > trigger_offset) {
755                         /* Send out samples remaining before trigger */
756                         packet.type = SR_DF_LOGIC;
757                         packet.payload = &logic;
758                         logic.length = (trigger_offset - samples_read) * 4;
759                         logic.unitsize = 4;
760                         logic.data = buf + buf_offset;
761                         sr_session_send(cb_data, &packet);
762                         len -= logic.length;
763                         samples_read += logic.length / 4;
764                         buf_offset += logic.length;
765                 }
766
767                 if (samples_read == trigger_offset) {
768                         /* Send out trigger */
769                         packet.type = SR_DF_TRIGGER;
770                         packet.payload = NULL;
771                         sr_session_send(cb_data, &packet);
772                 }
773
774                 /* Send out data (or data after trigger) */
775                 packet.type = SR_DF_LOGIC;
776                 packet.payload = &logic;
777                 logic.length = len;
778                 logic.unitsize = 4;
779                 logic.data = buf + buf_offset;
780                 sr_session_send(cb_data, &packet);
781                 samples_read += len / 4;
782         }
783         analyzer_read_stop(usb->devhdl);
784         g_free(buf);
785
786         packet.type = SR_DF_END;
787         sr_session_send(cb_data, &packet);
788
789         return SR_OK;
790 }
791
792 /* TODO: This stops acquisition on ALL devices, ignoring dev_index. */
793 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
794 {
795         struct dev_context *devc;
796         struct sr_usb_dev_inst *usb;
797         struct sr_datafeed_packet packet;
798
799         packet.type = SR_DF_END;
800         sr_session_send(cb_data, &packet);
801
802         if (!(devc = sdi->priv)) {
803                 sr_err("%s: sdi->priv was NULL", __func__);
804                 return SR_ERR_BUG;
805         }
806
807         usb = sdi->conn;
808         analyzer_reset(usb->devhdl);
809         /* TODO: Need to cancel and free any queued up transfers. */
810
811         return SR_OK;
812 }
813
814 SR_PRIV struct sr_dev_driver zeroplus_logic_cube_driver_info = {
815         .name = "zeroplus-logic-cube",
816         .longname = "ZEROPLUS Logic Cube LAP-C series",
817         .api_version = 1,
818         .init = init,
819         .cleanup = cleanup,
820         .scan = scan,
821         .dev_list = dev_list,
822         .dev_clear = dev_clear,
823         .config_get = config_get,
824         .config_set = config_set,
825         .config_list = config_list,
826         .dev_open = dev_open,
827         .dev_close = dev_close,
828         .dev_acquisition_start = dev_acquisition_start,
829         .dev_acquisition_stop = dev_acquisition_stop,
830         .priv = NULL,
831 };