]> sigrok.org Git - libsigrok.git/blob - src/hardware/asix-sigma/api.c
0a829794754157b9b28653d998a5f6dfac31437e
[libsigrok.git] / src / hardware / asix-sigma / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 Håvard Espeland <gus@ping.uio.no>,
5  * Copyright (C) 2010 Martin Stensgård <mastensg@ping.uio.no>
6  * Copyright (C) 2010 Carl Henrik Lunde <chlunde@ping.uio.no>
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include "protocol.h"
24
25 /*
26  * Channel numbers seem to go from 1-16, according to this image:
27  * http://tools.asix.net/img/sigma_sigmacab_pins_720.jpg
28  * (the cable has two additional GND pins, and a TI and TO pin)
29  */
30 static const char *channel_names[] = {
31         "1", "2", "3", "4", "5", "6", "7", "8",
32         "9", "10", "11", "12", "13", "14", "15", "16",
33 };
34
35 static const uint32_t scanopts[] = {
36         SR_CONF_CONN,
37 };
38
39 static const uint32_t drvopts[] = {
40         SR_CONF_LOGIC_ANALYZER,
41 };
42
43 static const uint32_t devopts[] = {
44         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
45         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
46         SR_CONF_CONN | SR_CONF_GET,
47         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
48 #if ASIX_SIGMA_WITH_TRIGGER
49         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
50         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
51 #endif
52 };
53
54 #if ASIX_SIGMA_WITH_TRIGGER
55 static const int32_t trigger_matches[] = {
56         SR_TRIGGER_ZERO,
57         SR_TRIGGER_ONE,
58         SR_TRIGGER_RISING,
59         SR_TRIGGER_FALLING,
60 };
61 #endif
62
63 static void clear_helper(struct dev_context *devc)
64 {
65         ftdi_deinit(&devc->ftdic);
66 }
67
68 static int dev_clear(const struct sr_dev_driver *di)
69 {
70         return std_dev_clear_with_callback(di,
71                 (std_dev_clear_callback)clear_helper);
72 }
73
74 static gboolean bus_addr_in_devices(int bus, int addr, GSList *devs)
75 {
76         struct sr_usb_dev_inst *usb;
77
78         for (/* EMPTY */; devs; devs = devs->next) {
79                 usb = devs->data;
80                 if (usb->bus == bus && usb->address == addr)
81                         return TRUE;
82         }
83
84         return FALSE;
85 }
86
87 static gboolean known_vid_pid(const struct libusb_device_descriptor *des)
88 {
89         gboolean is_sigma, is_omega;
90
91         if (des->idVendor != USB_VENDOR_ASIX)
92                 return FALSE;
93         is_sigma = des->idProduct == USB_PRODUCT_SIGMA;
94         is_omega = des->idProduct == USB_PRODUCT_OMEGA;
95         if (!is_sigma && !is_omega)
96                 return FALSE;
97         return TRUE;
98 }
99
100 static GSList *scan(struct sr_dev_driver *di, GSList *options)
101 {
102         struct drv_context *drvc;
103         libusb_context *usbctx;
104         const char *conn;
105         GSList *l, *conn_devices;
106         struct sr_config *src;
107         GSList *devices;
108         libusb_device **devlist, *devitem;
109         int bus, addr;
110         struct libusb_device_descriptor des;
111         struct libusb_device_handle *hdl;
112         int ret;
113         char conn_id[20];
114         char serno_txt[16];
115         char *end;
116         long serno_num, serno_pre;
117         enum asix_device_type dev_type;
118         const char *dev_text;
119         struct sr_dev_inst *sdi;
120         struct dev_context *devc;
121         size_t devidx, chidx;
122
123         drvc = di->context;
124         usbctx = drvc->sr_ctx->libusb_ctx;
125
126         /* Find all devices which match an (optional) conn= spec. */
127         conn = NULL;
128         for (l = options; l; l = l->next) {
129                 src = l->data;
130                 switch (src->key) {
131                 case SR_CONF_CONN:
132                         conn = g_variant_get_string(src->data, NULL);
133                         break;
134                 }
135         }
136         conn_devices = NULL;
137         if (conn)
138                 conn_devices = sr_usb_find(usbctx, conn);
139         if (conn && !conn_devices)
140                 return NULL;
141
142         /* Find all ASIX logic analyzers (which match the connection spec). */
143         devices = NULL;
144         libusb_get_device_list(usbctx, &devlist);
145         for (devidx = 0; devlist[devidx]; devidx++) {
146                 devitem = devlist[devidx];
147
148                 /* Check for connection match if a user spec was given. */
149                 bus = libusb_get_bus_number(devitem);
150                 addr = libusb_get_device_address(devitem);
151                 if (conn && !bus_addr_in_devices(bus, addr, conn_devices))
152                         continue;
153                 snprintf(conn_id, sizeof(conn_id), "%d.%d", bus, addr);
154
155                 /*
156                  * Check for known VID:PID pairs. Get the serial number,
157                  * to then derive the device type from it.
158                  */
159                 libusb_get_device_descriptor(devitem, &des);
160                 if (!known_vid_pid(&des))
161                         continue;
162                 if (!des.iSerialNumber) {
163                         sr_warn("Cannot get serial number (index 0).");
164                         continue;
165                 }
166                 ret = libusb_open(devitem, &hdl);
167                 if (ret < 0) {
168                         sr_warn("Cannot open USB device %04x.%04x: %s.",
169                                 des.idVendor, des.idProduct,
170                                 libusb_error_name(ret));
171                         continue;
172                 }
173                 ret = libusb_get_string_descriptor_ascii(hdl,
174                         des.iSerialNumber,
175                         (unsigned char *)serno_txt, sizeof(serno_txt));
176                 if (ret < 0) {
177                         sr_warn("Cannot get serial number (%s).",
178                                 libusb_error_name(ret));
179                         libusb_close(hdl);
180                         continue;
181                 }
182                 libusb_close(hdl);
183
184                 /*
185                  * All ASIX logic analyzers have a serial number, which
186                  * reads as a hex number, and tells the device type.
187                  */
188                 ret = sr_atol_base(serno_txt, &serno_num, &end, 16);
189                 if (ret != SR_OK || !end || *end) {
190                         sr_warn("Cannot interpret serial number %s.", serno_txt);
191                         continue;
192                 }
193                 dev_type = ASIX_TYPE_NONE;
194                 dev_text = NULL;
195                 serno_pre = serno_num >> 16;
196                 switch (serno_pre) {
197                 case 0xa601:
198                         dev_type = ASIX_TYPE_SIGMA;
199                         dev_text = "SIGMA";
200                         sr_info("Found SIGMA, serno %s.", serno_txt);
201                         break;
202                 case 0xa602:
203                         dev_type = ASIX_TYPE_SIGMA;
204                         dev_text = "SIGMA2";
205                         sr_info("Found SIGMA2, serno %s.", serno_txt);
206                         break;
207                 case 0xa603:
208                         dev_type = ASIX_TYPE_OMEGA;
209                         dev_text = "OMEGA";
210                         sr_info("Found OMEGA, serno %s.", serno_txt);
211                         if (!ASIX_WITH_OMEGA) {
212                                 sr_warn("OMEGA support is not implemented yet.");
213                                 continue;
214                         }
215                         break;
216                 default:
217                         sr_warn("Unknown serno %s, skipping.", serno_txt);
218                         continue;
219                 }
220
221                 /* Create a device instance, add it to the result set. */
222
223                 sdi = g_malloc0(sizeof(*sdi));
224                 devices = g_slist_append(devices, sdi);
225                 sdi->status = SR_ST_INITIALIZING;
226                 sdi->vendor = g_strdup("ASIX");
227                 sdi->model = g_strdup(dev_text);
228                 sdi->serial_num = g_strdup(serno_txt);
229                 sdi->connection_id = g_strdup(conn_id);
230                 for (chidx = 0; chidx < ARRAY_SIZE(channel_names); chidx++)
231                         sr_channel_new(sdi, chidx, SR_CHANNEL_LOGIC,
232                                 TRUE, channel_names[chidx]);
233
234                 devc = g_malloc0(sizeof(*devc));
235                 sdi->priv = devc;
236                 devc->id.vid = des.idVendor;
237                 devc->id.pid = des.idProduct;
238                 devc->id.serno = serno_num;
239                 devc->id.prefix = serno_pre;
240                 devc->id.type = dev_type;
241                 devc->samplerate = samplerates[0];
242                 sr_sw_limits_init(&devc->cfg_limits);
243                 devc->firmware_idx = SIGMA_FW_NONE;
244                 devc->capture_ratio = 50;
245                 devc->use_triggers = 0;
246         }
247         libusb_free_device_list(devlist, 1);
248         g_slist_free_full(conn_devices, (GDestroyNotify)sr_usb_dev_inst_free);
249
250         return std_scan_complete(di, devices);
251 }
252
253 static int dev_open(struct sr_dev_inst *sdi)
254 {
255         struct dev_context *devc;
256         long vid, pid;
257         const char *serno;
258         int ret;
259
260         devc = sdi->priv;
261
262         if (devc->id.type == ASIX_TYPE_OMEGA && !ASIX_WITH_OMEGA) {
263                 sr_err("OMEGA support is not implemented yet.");
264                 return SR_ERR_NA;
265         }
266         vid = devc->id.vid;
267         pid = devc->id.pid;
268         serno = sdi->serial_num;
269
270         ret = ftdi_init(&devc->ftdic);
271         if (ret < 0) {
272                 sr_err("Cannot initialize FTDI context (%d): %s.",
273                         ret, ftdi_get_error_string(&devc->ftdic));
274                 return SR_ERR_IO;
275         }
276         ret = ftdi_usb_open_desc_index(&devc->ftdic, vid, pid, NULL, serno, 0);
277         if (ret < 0) {
278                 sr_err("Cannot open device (%d): %s.",
279                         ret, ftdi_get_error_string(&devc->ftdic));
280                 return SR_ERR_IO;
281         }
282
283         return SR_OK;
284 }
285
286 static int dev_close(struct sr_dev_inst *sdi)
287 {
288         struct dev_context *devc;
289         int ret;
290
291         devc = sdi->priv;
292
293         ret = ftdi_usb_close(&devc->ftdic);
294         ftdi_deinit(&devc->ftdic);
295
296         return (ret == 0) ? SR_OK : SR_ERR;
297 }
298
299 static int config_get(uint32_t key, GVariant **data,
300         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
301 {
302         struct dev_context *devc;
303
304         (void)cg;
305
306         if (!sdi)
307                 return SR_ERR;
308         devc = sdi->priv;
309
310         switch (key) {
311         case SR_CONF_CONN:
312                 *data = g_variant_new_string(sdi->connection_id);
313                 break;
314         case SR_CONF_SAMPLERATE:
315                 *data = g_variant_new_uint64(devc->samplerate);
316                 break;
317         case SR_CONF_LIMIT_MSEC:
318         case SR_CONF_LIMIT_SAMPLES:
319                 return sr_sw_limits_config_get(&devc->cfg_limits, key, data);
320 #if ASIX_SIGMA_WITH_TRIGGER
321         case SR_CONF_CAPTURE_RATIO:
322                 *data = g_variant_new_uint64(devc->capture_ratio);
323                 break;
324 #endif
325         default:
326                 return SR_ERR_NA;
327         }
328
329         return SR_OK;
330 }
331
332 static int config_set(uint32_t key, GVariant *data,
333         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
334 {
335         struct dev_context *devc;
336         int ret;
337         uint64_t want_rate, have_rate;
338
339         (void)cg;
340
341         devc = sdi->priv;
342
343         switch (key) {
344         case SR_CONF_SAMPLERATE:
345                 want_rate = g_variant_get_uint64(data);
346                 ret = sigma_normalize_samplerate(want_rate, &have_rate);
347                 if (ret != SR_OK)
348                         return ret;
349                 if (have_rate != want_rate) {
350                         char *text_want, *text_have;
351                         text_want = sr_samplerate_string(want_rate);
352                         text_have = sr_samplerate_string(have_rate);
353                         sr_info("Adjusted samplerate %s to %s.",
354                                 text_want, text_have);
355                         g_free(text_want);
356                         g_free(text_have);
357                 }
358                 devc->samplerate = have_rate;
359                 break;
360         case SR_CONF_LIMIT_MSEC:
361         case SR_CONF_LIMIT_SAMPLES:
362                 return sr_sw_limits_config_set(&devc->cfg_limits, key, data);
363 #if ASIX_SIGMA_WITH_TRIGGER
364         case SR_CONF_CAPTURE_RATIO:
365                 devc->capture_ratio = g_variant_get_uint64(data);
366                 break;
367 #endif
368         default:
369                 return SR_ERR_NA;
370         }
371
372         return SR_OK;
373 }
374
375 static int config_list(uint32_t key, GVariant **data,
376         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
377 {
378         switch (key) {
379         case SR_CONF_SCAN_OPTIONS:
380         case SR_CONF_DEVICE_OPTIONS:
381                 if (cg)
382                         return SR_ERR_NA;
383                 return STD_CONFIG_LIST(key, data, sdi, cg,
384                         scanopts, drvopts, devopts);
385         case SR_CONF_SAMPLERATE:
386                 *data = std_gvar_samplerates(samplerates, samplerates_count);
387                 break;
388 #if ASIX_SIGMA_WITH_TRIGGER
389         case SR_CONF_TRIGGER_MATCH:
390                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
391                 break;
392 #endif
393         default:
394                 return SR_ERR_NA;
395         }
396
397         return SR_OK;
398 }
399
400 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
401 {
402         struct dev_context *devc;
403         struct clockselect_50 clockselect;
404         int triggerpin, ret;
405         uint8_t triggerselect;
406         struct triggerinout triggerinout_conf;
407         struct triggerlut lut;
408         uint8_t regval, trgconf_bytes[2], clock_bytes[4], *wrptr;
409         size_t count;
410
411         devc = sdi->priv;
412
413         /*
414          * Setup the device's samplerate from the value which up to now
415          * just got checked and stored. As a byproduct this can pick and
416          * send firmware to the device, reduce the number of available
417          * logic channels, etc.
418          *
419          * Determine an acquisition timeout from optionally configured
420          * sample count or time limits. Which depends on the samplerate.
421          */
422         ret = sigma_set_samplerate(sdi);
423         if (ret != SR_OK)
424                 return ret;
425         ret = sigma_set_acquire_timeout(devc);
426         if (ret != SR_OK)
427                 return ret;
428
429         if (sigma_convert_trigger(sdi) != SR_OK) {
430                 sr_err("Failed to configure triggers.");
431                 return SR_ERR;
432         }
433
434         /* Enter trigger programming mode. */
435         sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x20);
436
437         triggerselect = 0;
438         if (devc->samplerate >= SR_MHZ(100)) {
439                 /* 100 and 200 MHz mode. */
440                 sigma_set_register(devc, WRITE_TRIGGER_SELECT2, 0x81);
441
442                 /* Find which pin to trigger on from mask. */
443                 for (triggerpin = 0; triggerpin < 8; triggerpin++) {
444                         if (devc->trigger.risingmask & (1 << triggerpin))
445                                 break;
446                         if (devc->trigger.fallingmask & (1 << triggerpin))
447                                 break;
448                 }
449
450                 /* Set trigger pin and light LED on trigger. */
451                 triggerselect = TRGSEL2_LEDSEL1 | (triggerpin & 0x7);
452
453                 /* Default rising edge. */
454                 if (devc->trigger.fallingmask)
455                         triggerselect |= 1 << 3;
456
457         } else if (devc->samplerate <= SR_MHZ(50)) {
458                 /* All other modes. */
459                 sigma_build_basic_trigger(devc, &lut);
460
461                 sigma_write_trigger_lut(devc, &lut);
462
463                 triggerselect = TRGSEL2_LEDSEL1 | TRGSEL2_LEDSEL0;
464         }
465
466         /* Setup trigger in and out pins to default values. */
467         memset(&triggerinout_conf, 0, sizeof(struct triggerinout));
468         triggerinout_conf.trgout_bytrigger = 1;
469         triggerinout_conf.trgout_enable = 1;
470         /* TODO
471          * Verify the correctness of this implementation. The previous
472          * version used to assign to a C language struct with bit fields
473          * which is highly non-portable and hard to guess the resulting
474          * raw memory layout or wire transfer content. The C struct's
475          * field names did not match the vendor documentation's names.
476          * Which means that I could not verify "on paper" either. Let's
477          * re-visit this code later during research for trigger support.
478          */
479         wrptr = trgconf_bytes;
480         regval = 0;
481         if (triggerinout_conf.trgout_bytrigger)
482                 regval |= TRGOPT_TRGOOUTEN;
483         write_u8_inc(&wrptr, regval);
484         regval &= ~TRGOPT_CLEAR_MASK;
485         if (triggerinout_conf.trgout_enable)
486                 regval |= TRGOPT_TRGOEN;
487         write_u8_inc(&wrptr, regval);
488         count = wrptr - trgconf_bytes;
489         sigma_write_register(devc, WRITE_TRIGGER_OPTION, trgconf_bytes, count);
490
491         /* Leave trigger programming mode. */
492         sigma_set_register(devc, WRITE_TRIGGER_SELECT2, triggerselect);
493
494         /* Set clock select register. */
495         clockselect.async = 0;
496         clockselect.fraction = 1;               /* Divider 1. */
497         clockselect.disabled_channels = 0x0000; /* All channels enabled. */
498         if (devc->samplerate == SR_MHZ(200)) {
499                 /* Enable 4 channels. */
500                 clockselect.disabled_channels = 0xfff0;
501         } else if (devc->samplerate == SR_MHZ(100)) {
502                 /* Enable 8 channels. */
503                 clockselect.disabled_channels = 0xff00;
504         } else {
505                 /*
506                  * 50 MHz mode, or fraction thereof. The 50MHz reference
507                  * can get divided by any integer in the range 1 to 256.
508                  * Divider minus 1 gets written to the hardware.
509                  * (The driver lists a discrete set of sample rates, but
510                  * all of them fit the above description.)
511                  */
512                 clockselect.fraction = SR_MHZ(50) / devc->samplerate;
513         }
514         wrptr = clock_bytes;
515         write_u8_inc(&wrptr, clockselect.async);
516         write_u8_inc(&wrptr, clockselect.fraction - 1);
517         write_u16be_inc(&wrptr, clockselect.disabled_channels);
518         count = wrptr - clock_bytes;
519         sigma_write_register(devc, WRITE_CLOCK_SELECT, clock_bytes, count);
520
521         /* Setup maximum post trigger time. */
522         sigma_set_register(devc, WRITE_POST_TRIGGER,
523                 (devc->capture_ratio * 255) / 100);
524
525         /* Start acqusition. */
526         regval = WMR_TRGRES | WMR_SDRAMWRITEEN;
527 #if ASIX_SIGMA_WITH_TRIGGER
528         regval |= WMR_TRGEN;
529 #endif
530         sigma_set_register(devc, WRITE_MODE, regval);
531
532         std_session_send_df_header(sdi);
533
534         /* Add capture source. */
535         sr_session_source_add(sdi->session, -1, 0, 10,
536                 sigma_receive_data, (void *)sdi);
537
538         devc->state.state = SIGMA_CAPTURE;
539
540         return SR_OK;
541 }
542
543 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
544 {
545         struct dev_context *devc;
546
547         devc = sdi->priv;
548
549         /*
550          * When acquisition is currently running, keep the receive
551          * routine registered and have it stop the acquisition upon the
552          * next invocation. Else unregister the receive routine here
553          * already. The detour is required to have sample data retrieved
554          * for forced acquisition stops.
555          */
556         if (devc->state.state == SIGMA_CAPTURE) {
557                 devc->state.state = SIGMA_STOPPING;
558         } else {
559                 devc->state.state = SIGMA_IDLE;
560                 sr_session_source_remove(sdi->session, -1);
561         }
562
563         return SR_OK;
564 }
565
566 static struct sr_dev_driver asix_sigma_driver_info = {
567         .name = "asix-sigma",
568         .longname = "ASIX SIGMA/SIGMA2",
569         .api_version = 1,
570         .init = std_init,
571         .cleanup = std_cleanup,
572         .scan = scan,
573         .dev_list = std_dev_list,
574         .dev_clear = dev_clear,
575         .config_get = config_get,
576         .config_set = config_set,
577         .config_list = config_list,
578         .dev_open = dev_open,
579         .dev_close = dev_close,
580         .dev_acquisition_start = dev_acquisition_start,
581         .dev_acquisition_stop = dev_acquisition_stop,
582         .context = NULL,
583 };
584 SR_REGISTER_DEV_DRIVER(asix_sigma_driver_info);