]> sigrok.org Git - libsigrok.git/blob - src/hardware/zeroplus-logic-cube/api.c
drivers: Factor out std_gvar_tuple_u64().
[libsigrok.git] / src / 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 <config.h>
21 #include "protocol.h"
22
23 #define USB_INTERFACE                   0
24 #define USB_CONFIGURATION               1
25 #define NUM_TRIGGER_STAGES              4
26 #define PACKET_SIZE                     2048    /* ?? */
27
28 //#define ZP_EXPERIMENTAL
29
30 struct zp_model {
31         uint16_t vid;
32         uint16_t pid;
33         const char *model_name;
34         unsigned int channels;
35         unsigned int sample_depth;      /* In Ksamples/channel */
36         unsigned int max_sampling_freq;
37 };
38
39 /*
40  * Note -- 16032, 16064 and 16128 *usually* -- but not always -- have the
41  * same 128K sample depth.
42  */
43 static const struct zp_model zeroplus_models[] = {
44         {0x0c12, 0x7002, "LAP-16128U",    16, 128,  200},
45         {0x0c12, 0x7009, "LAP-C(16064)",  16, 64,   100},
46         {0x0c12, 0x700a, "LAP-C(16128)",  16, 128,  200},
47         {0x0c12, 0x700b, "LAP-C(32128)",  32, 128,  200},
48         {0x0c12, 0x700c, "LAP-C(321000)", 32, 1024, 200},
49         {0x0c12, 0x700d, "LAP-C(322000)", 32, 2048, 200},
50         {0x0c12, 0x700e, "LAP-C(16032)",  16, 32,   100},
51         {0x0c12, 0x7016, "LAP-C(162000)", 16, 2048, 200},
52         {0x0c12, 0x7100, "AKIP-9101", 16, 256, 200},
53         ALL_ZERO
54 };
55
56 static const uint32_t drvopts[] = {
57         SR_CONF_LOGIC_ANALYZER,
58 };
59
60 static const uint32_t devopts[] = {
61         SR_CONF_LIMIT_SAMPLES | SR_CONF_SET | SR_CONF_LIST,
62         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
63         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
64         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
65         SR_CONF_VOLTAGE_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
66 };
67
68 static const int32_t trigger_matches[] = {
69         SR_TRIGGER_ZERO,
70         SR_TRIGGER_ONE,
71 };
72
73 /*
74  * ZEROPLUS LAP-C (16032) numbers the 16 channels A0-A7 and B0-B7.
75  * We currently ignore other untested/unsupported devices here.
76  */
77 static const char *channel_names[] = {
78         "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7",
79         "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7",
80         "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7",
81         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
82 };
83
84 /*
85  * The hardware supports more samplerates than these, but these are the
86  * options hardcoded into the vendor's Windows GUI.
87  */
88
89 static const uint64_t samplerates_100[] = {
90         SR_HZ(100),
91         SR_HZ(500),
92         SR_KHZ(1),
93         SR_KHZ(5),
94         SR_KHZ(25),
95         SR_KHZ(50),
96         SR_KHZ(100),
97         SR_KHZ(200),
98         SR_KHZ(400),
99         SR_KHZ(800),
100         SR_MHZ(1),
101         SR_MHZ(10),
102         SR_MHZ(25),
103         SR_MHZ(50),
104         SR_MHZ(80),
105         SR_MHZ(100),
106 };
107
108 const uint64_t samplerates_200[] = {
109         SR_HZ(100),
110         SR_HZ(500),
111         SR_KHZ(1),
112         SR_KHZ(5),
113         SR_KHZ(25),
114         SR_KHZ(50),
115         SR_KHZ(100),
116         SR_KHZ(200),
117         SR_KHZ(400),
118         SR_KHZ(800),
119         SR_MHZ(1),
120         SR_MHZ(10),
121         SR_MHZ(25),
122         SR_MHZ(50),
123         SR_MHZ(80),
124         SR_MHZ(100),
125         SR_MHZ(150),
126         SR_MHZ(200),
127 };
128
129 SR_PRIV int zp_set_samplerate(struct dev_context *devc, uint64_t samplerate)
130 {
131         int i;
132
133         for (i = 0; ARRAY_SIZE(samplerates_200); i++)
134                 if (samplerate == samplerates_200[i])
135                         break;
136
137         if (i == ARRAY_SIZE(samplerates_200) || samplerate > devc->max_samplerate) {
138                 sr_err("Unsupported samplerate: %" PRIu64 "Hz.", samplerate);
139                 return SR_ERR_ARG;
140         }
141
142         sr_info("Setting samplerate to %" PRIu64 "Hz.", samplerate);
143
144         if (samplerate >= SR_MHZ(1))
145                 analyzer_set_freq(samplerate / SR_MHZ(1), FREQ_SCALE_MHZ);
146         else if (samplerate >= SR_KHZ(1))
147                 analyzer_set_freq(samplerate / SR_KHZ(1), FREQ_SCALE_KHZ);
148         else
149                 analyzer_set_freq(samplerate, FREQ_SCALE_HZ);
150
151         devc->cur_samplerate = samplerate;
152
153         return SR_OK;
154 }
155
156 static GSList *scan(struct sr_dev_driver *di, GSList *options)
157 {
158         struct sr_dev_inst *sdi;
159         struct drv_context *drvc;
160         struct dev_context *devc;
161         const struct zp_model *prof;
162         struct libusb_device_descriptor des;
163         struct libusb_device_handle *hdl;
164         libusb_device **devlist;
165         GSList *devices;
166         int ret, i, j;
167         char serial_num[64], connection_id[64];
168
169         (void)options;
170
171         drvc = di->context;
172
173         devices = NULL;
174
175         /* Find all ZEROPLUS analyzers and add them to device list. */
176         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); /* TODO: Errors. */
177
178         for (i = 0; devlist[i]; i++) {
179                 libusb_get_device_descriptor(devlist[i], &des);
180
181                 if ((ret = libusb_open(devlist[i], &hdl)) < 0)
182                         continue;
183
184                 if (des.iSerialNumber == 0) {
185                         serial_num[0] = '\0';
186                 } else if ((ret = libusb_get_string_descriptor_ascii(hdl,
187                                 des.iSerialNumber, (unsigned char *) serial_num,
188                                 sizeof(serial_num))) < 0) {
189                         sr_warn("Failed to get serial number string descriptor: %s.",
190                                 libusb_error_name(ret));
191                         continue;
192                 }
193
194                 libusb_close(hdl);
195
196                 usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
197
198                 prof = NULL;
199                 for (j = 0; j < zeroplus_models[j].vid; j++) {
200                         if (des.idVendor == zeroplus_models[j].vid &&
201                                 des.idProduct == zeroplus_models[j].pid) {
202                                 prof = &zeroplus_models[j];
203                         }
204                 }
205
206                 if (!prof)
207                         continue;
208                 sr_info("Found ZEROPLUS %s.", prof->model_name);
209
210                 sdi = g_malloc0(sizeof(struct sr_dev_inst));
211                 sdi->status = SR_ST_INACTIVE;
212                 sdi->vendor = g_strdup("ZEROPLUS");
213                 sdi->model = g_strdup(prof->model_name);
214                 sdi->serial_num = g_strdup(serial_num);
215                 sdi->connection_id = g_strdup(connection_id);
216
217                 devc = g_malloc0(sizeof(struct dev_context));
218                 sdi->priv = devc;
219                 devc->prof = prof;
220                 devc->num_channels = prof->channels;
221 #ifdef ZP_EXPERIMENTAL
222                 devc->max_sample_depth = 128 * 1024;
223                 devc->max_samplerate = 200;
224 #else
225                 devc->max_sample_depth = prof->sample_depth * 1024;
226                 devc->max_samplerate = prof->max_sampling_freq;
227 #endif
228                 devc->max_samplerate *= SR_MHZ(1);
229                 devc->memory_size = MEMORY_SIZE_8K;
230                 // memset(devc->trigger_buffer, 0, NUM_TRIGGER_STAGES);
231
232                 for (j = 0; j < devc->num_channels; j++)
233                         sr_channel_new(sdi, j, SR_CHANNEL_LOGIC, TRUE,
234                                         channel_names[j]);
235
236                 devices = g_slist_append(devices, sdi);
237                 sdi->inst_type = SR_INST_USB;
238                 sdi->conn = sr_usb_dev_inst_new(
239                         libusb_get_bus_number(devlist[i]),
240                         libusb_get_device_address(devlist[i]), NULL);
241         }
242         libusb_free_device_list(devlist, 1);
243
244         return std_scan_complete(di, devices);
245 }
246
247 static int dev_open(struct sr_dev_inst *sdi)
248 {
249         struct sr_dev_driver *di = sdi->driver;
250         struct dev_context *devc;
251         struct drv_context *drvc;
252         struct sr_usb_dev_inst *usb;
253         int ret;
254
255         drvc = di->context;
256         usb = sdi->conn;
257         devc = sdi->priv;
258
259         ret = sr_usb_open(drvc->sr_ctx->libusb_ctx, usb);
260         if (ret != SR_OK)
261                 return ret;
262
263         ret = libusb_set_configuration(usb->devhdl, USB_CONFIGURATION);
264         if (ret < 0) {
265                 sr_err("Unable to set USB configuration %d: %s.",
266                        USB_CONFIGURATION, libusb_error_name(ret));
267                 return SR_ERR;
268         }
269
270         ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
271         if (ret != 0) {
272                 sr_err("Unable to claim interface: %s.",
273                        libusb_error_name(ret));
274                 return SR_ERR;
275         }
276
277         /* Set default configuration after power on. */
278         if (analyzer_read_status(usb->devhdl) == 0)
279                 analyzer_configure(usb->devhdl);
280
281         analyzer_reset(usb->devhdl);
282         analyzer_initialize(usb->devhdl);
283
284         //analyzer_set_memory_size(MEMORY_SIZE_512K);
285         // analyzer_set_freq(g_freq, g_freq_scale);
286         analyzer_set_trigger_count(1);
287         // analyzer_set_ramsize_trigger_address((((100 - g_pre_trigger)
288         // * get_memory_size(g_memory_size)) / 100) >> 2);
289
290 #if 0
291         if (g_double_mode == 1)
292                 analyzer_set_compression(COMPRESSION_DOUBLE);
293         else if (g_compression == 1)
294                 analyzer_set_compression(COMPRESSION_ENABLE);
295         else
296 #endif
297         analyzer_set_compression(COMPRESSION_NONE);
298
299         if (devc->cur_samplerate == 0) {
300                 /* Samplerate hasn't been set. Default to 1MHz. */
301                 analyzer_set_freq(1, FREQ_SCALE_MHZ);
302                 devc->cur_samplerate = SR_MHZ(1);
303         }
304
305         if (devc->cur_threshold == 0)
306                 set_voltage_threshold(devc, 1.5);
307
308         return SR_OK;
309 }
310
311 static int dev_close(struct sr_dev_inst *sdi)
312 {
313         struct sr_usb_dev_inst *usb;
314
315         usb = sdi->conn;
316
317         if (!usb->devhdl)
318                 return SR_ERR_BUG;
319
320         sr_info("Closing device on %d.%d (logical) / %s (physical) interface %d.",
321                 usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
322         libusb_release_interface(usb->devhdl, USB_INTERFACE);
323         libusb_reset_device(usb->devhdl);
324         libusb_close(usb->devhdl);
325         usb->devhdl = NULL;
326
327         return SR_OK;
328 }
329
330 static int config_get(uint32_t key, GVariant **data,
331         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
332 {
333         struct dev_context *devc;
334         GVariant *range[2];
335
336         (void)cg;
337
338         if (!sdi)
339                 return SR_ERR_ARG;
340
341         devc = sdi->priv;
342
343         switch (key) {
344         case SR_CONF_SAMPLERATE:
345                 *data = g_variant_new_uint64(devc->cur_samplerate);
346                 break;
347         case SR_CONF_CAPTURE_RATIO:
348                 *data = g_variant_new_uint64(devc->capture_ratio);
349                 break;
350         case SR_CONF_VOLTAGE_THRESHOLD:
351                 range[0] = g_variant_new_double(devc->cur_threshold);
352                 range[1] = g_variant_new_double(devc->cur_threshold);
353                 *data = g_variant_new_tuple(range, 2);
354                 break;
355         default:
356                 return SR_ERR_NA;
357         }
358
359         return SR_OK;
360 }
361
362 static int config_set(uint32_t key, GVariant *data,
363         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
364 {
365         struct dev_context *devc;
366         gdouble low, high;
367
368         (void)cg;
369
370         devc = sdi->priv;
371
372         switch (key) {
373         case SR_CONF_SAMPLERATE:
374                 return zp_set_samplerate(devc, g_variant_get_uint64(data));
375         case SR_CONF_LIMIT_SAMPLES:
376                 return set_limit_samples(devc, g_variant_get_uint64(data));
377         case SR_CONF_CAPTURE_RATIO:
378                 return set_capture_ratio(devc, g_variant_get_uint64(data));
379         case SR_CONF_VOLTAGE_THRESHOLD:
380                 g_variant_get(data, "(dd)", &low, &high);
381                 return set_voltage_threshold(devc, (low + high) / 2.0);
382         default:
383                 return SR_ERR_NA;
384         }
385
386         return SR_OK;
387 }
388
389 static int config_list(uint32_t key, GVariant **data,
390         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
391 {
392         struct dev_context *devc;
393
394         switch (key) {
395         case SR_CONF_DEVICE_OPTIONS:
396                 return STD_CONFIG_LIST(key, data, sdi, cg, NULL, drvopts, devopts);
397         case SR_CONF_SAMPLERATE:
398                 devc = sdi->priv;
399                 if (devc->prof->max_sampling_freq == 100)
400                         *data = std_gvar_samplerates(ARRAY_AND_SIZE(samplerates_100));
401                 else if (devc->prof->max_sampling_freq == 200)
402                         *data = std_gvar_samplerates(ARRAY_AND_SIZE(samplerates_200));
403                 else {
404                         sr_err("Internal error: Unknown max. samplerate: %d.",
405                                devc->prof->max_sampling_freq);
406                         return SR_ERR_ARG;
407                 }
408                 break;
409         case SR_CONF_TRIGGER_MATCH:
410                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
411                 break;
412         case SR_CONF_VOLTAGE_THRESHOLD:
413                 *data = std_gvar_min_max_step_thresholds(-6.0, 6.0, 0.1);
414                 break;
415         case SR_CONF_LIMIT_SAMPLES:
416                 if (!sdi)
417                         return SR_ERR_ARG;
418                 devc = sdi->priv;
419                 *data = std_gvar_tuple_u64(0, devc->max_sample_depth);
420                 break;
421         default:
422                 return SR_ERR_NA;
423         }
424
425         return SR_OK;
426 }
427
428 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
429 {
430         struct dev_context *devc;
431         struct sr_usb_dev_inst *usb;
432         struct sr_datafeed_packet packet;
433         struct sr_datafeed_logic logic;
434         unsigned int samples_read;
435         int res;
436         unsigned int packet_num, n;
437         unsigned char *buf;
438         unsigned int status;
439         unsigned int stop_address;
440         unsigned int now_address;
441         unsigned int trigger_address;
442         unsigned int trigger_offset;
443         unsigned int triggerbar;
444         unsigned int ramsize_trigger;
445         unsigned int memory_size;
446         unsigned int valid_samples;
447         unsigned int discard;
448         int trigger_now;
449
450         devc = sdi->priv;
451
452         if (analyzer_add_triggers(sdi) != SR_OK) {
453                 sr_err("Failed to configure triggers.");
454                 return SR_ERR;
455         }
456
457         usb = sdi->conn;
458
459         set_triggerbar(devc);
460
461         /* Push configured settings to device. */
462         analyzer_configure(usb->devhdl);
463
464         analyzer_start(usb->devhdl);
465         sr_info("Waiting for data.");
466         analyzer_wait_data(usb->devhdl);
467
468         status = analyzer_read_status(usb->devhdl);
469         stop_address = analyzer_get_stop_address(usb->devhdl);
470         now_address = analyzer_get_now_address(usb->devhdl);
471         trigger_address = analyzer_get_trigger_address(usb->devhdl);
472
473         triggerbar = analyzer_get_triggerbar_address();
474         ramsize_trigger = analyzer_get_ramsize_trigger_address();
475
476         n = get_memory_size(devc->memory_size);
477         memory_size = n / 4;
478
479         sr_info("Status = 0x%x.", status);
480         sr_info("Stop address       = 0x%x.", stop_address);
481         sr_info("Now address        = 0x%x.", now_address);
482         sr_info("Trigger address    = 0x%x.", trigger_address);
483         sr_info("Triggerbar address = 0x%x.", triggerbar);
484         sr_info("Ramsize trigger    = 0x%x.", ramsize_trigger);
485         sr_info("Memory size        = 0x%x.", memory_size);
486
487         std_session_send_df_header(sdi);
488
489         /* Check for empty capture */
490         if ((status & STATUS_READY) && !stop_address) {
491                 std_session_send_df_end(sdi);
492                 return SR_OK;
493         }
494
495         buf = g_malloc(PACKET_SIZE);
496
497         /* Check if the trigger is in the samples we are throwing away */
498         trigger_now = now_address == trigger_address ||
499                 ((now_address + 1) % memory_size) == trigger_address;
500
501         /*
502          * STATUS_READY doesn't clear until now_address advances past
503          * addr 0, but for our logic, clear it in that case
504          */
505         if (!now_address)
506                 status &= ~STATUS_READY;
507
508         analyzer_read_start(usb->devhdl);
509
510         /* Calculate how much data to discard */
511         discard = 0;
512         if (status & STATUS_READY) {
513                 /*
514                  * We haven't wrapped around, we need to throw away data from
515                  * our current position to the end of the buffer.
516                  * Additionally, the first two samples captured are always
517                  * bogus.
518                  */
519                 discard += memory_size - now_address + 2;
520                 now_address = 2;
521         }
522
523         /* If we have more samples than we need, discard them */
524         valid_samples = (stop_address - now_address) % memory_size;
525         if (valid_samples > ramsize_trigger + triggerbar) {
526                 discard += valid_samples - (ramsize_trigger + triggerbar);
527                 now_address += valid_samples - (ramsize_trigger + triggerbar);
528         }
529
530         sr_info("Need to discard %d samples.", discard);
531
532         /* Calculate how far in the trigger is */
533         if (trigger_now)
534                 trigger_offset = 0;
535         else
536                 trigger_offset = (trigger_address - now_address) % memory_size;
537
538         /* Recalculate the number of samples available */
539         valid_samples = (stop_address - now_address) % memory_size;
540
541         /* Send the incoming transfer to the session bus. */
542         samples_read = 0;
543         for (packet_num = 0; packet_num < n / PACKET_SIZE; packet_num++) {
544                 unsigned int len;
545                 unsigned int buf_offset;
546
547                 res = analyzer_read_data(usb->devhdl, buf, PACKET_SIZE);
548                 sr_info("Tried to read %d bytes, actually read %d bytes.",
549                         PACKET_SIZE, res);
550
551                 if (discard >= PACKET_SIZE / 4) {
552                         discard -= PACKET_SIZE / 4;
553                         continue;
554                 }
555
556                 len = PACKET_SIZE - discard * 4;
557                 buf_offset = discard * 4;
558                 discard = 0;
559
560                 /* Check if we've read all the samples */
561                 if (samples_read + len / 4 >= valid_samples)
562                         len = (valid_samples - samples_read) * 4;
563                 if (!len)
564                         break;
565
566                 if (samples_read < trigger_offset &&
567                     samples_read + len / 4 > trigger_offset) {
568                         /* Send out samples remaining before trigger */
569                         packet.type = SR_DF_LOGIC;
570                         packet.payload = &logic;
571                         logic.length = (trigger_offset - samples_read) * 4;
572                         logic.unitsize = 4;
573                         logic.data = buf + buf_offset;
574                         sr_session_send(sdi, &packet);
575                         len -= logic.length;
576                         samples_read += logic.length / 4;
577                         buf_offset += logic.length;
578                 }
579
580                 if (samples_read == trigger_offset) {
581                         /* Send out trigger */
582                         packet.type = SR_DF_TRIGGER;
583                         packet.payload = NULL;
584                         sr_session_send(sdi, &packet);
585                 }
586
587                 /* Send out data (or data after trigger) */
588                 packet.type = SR_DF_LOGIC;
589                 packet.payload = &logic;
590                 logic.length = len;
591                 logic.unitsize = 4;
592                 logic.data = buf + buf_offset;
593                 sr_session_send(sdi, &packet);
594                 samples_read += len / 4;
595         }
596         analyzer_read_stop(usb->devhdl);
597         g_free(buf);
598
599         std_session_send_df_end(sdi);
600
601         return SR_OK;
602 }
603
604 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
605 {
606         struct sr_usb_dev_inst *usb;
607
608         std_session_send_df_end(sdi);
609
610         usb = sdi->conn;
611         analyzer_reset(usb->devhdl);
612         /* TODO: Need to cancel and free any queued up transfers. */
613
614         return SR_OK;
615 }
616
617 static struct sr_dev_driver zeroplus_logic_cube_driver_info = {
618         .name = "zeroplus-logic-cube",
619         .longname = "ZEROPLUS Logic Cube LAP-C series",
620         .api_version = 1,
621         .init = std_init,
622         .cleanup = std_cleanup,
623         .scan = scan,
624         .dev_list = std_dev_list,
625         .dev_clear = std_dev_clear,
626         .config_get = config_get,
627         .config_set = config_set,
628         .config_list = config_list,
629         .dev_open = dev_open,
630         .dev_close = dev_close,
631         .dev_acquisition_start = dev_acquisition_start,
632         .dev_acquisition_stop = dev_acquisition_stop,
633         .context = NULL,
634 };
635 SR_REGISTER_DEV_DRIVER(zeroplus_logic_cube_driver_info);