]> sigrok.org Git - libsigrok.git/blob - src/hardware/raspberrypi-pico/api.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / src / hardware / raspberrypi-pico / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2022 Shawn Walker <ac0bi00@gmail.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 #include <config.h>
20 #include <fcntl.h>
21 #include <glib.h>
22 #include <math.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <strings.h>
26 #include <unistd.h>
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29 #include "protocol.h"
30
31 /* Baud rate is really a don't care because we run USB CDC, dtr must be 1.
32  * flow should be zero since we don't use xon/xoff */
33 #define SERIALCOMM "115200/8n1/dtr=1/rts=0/flow=0"
34
35 /* Use the force_detect scan option as a way to pass user information to the
36  * device the string must use only 0-9,a-z,A-Z,'.','=' and '-'* and be less than
37  * 60 characters */
38
39 static const uint32_t scanopts[] = {
40         SR_CONF_CONN,           /* Required OS name for the port, i.e. /dev/ttyACM0 */
41         SR_CONF_SERIALCOMM,     /* Optional config of the port, i.e. 115200/8n1 */
42         SR_CONF_FORCE_DETECT
43 };
44
45 /* Sample rate can either provide a std_gvar_samplerates_steps or a
46  * std_gvar_samplerates. The latter is just a long list of every supported rate.
47  * For the steps, pulseview/pv/toolbars/mainbar.cpp will do a min,max,step. If
48  * step is 1 then it provides a 1,2,5,10 select otherwise it allows a spin box.
49  * Going with the full list because while the spin box is more flexible, it is
50  * harder to read */
51 static const uint64_t samplerates[] = {
52         SR_KHZ(5),
53         SR_KHZ(6),
54         SR_KHZ(8),
55         SR_KHZ(10),
56         SR_KHZ(20),
57         SR_KHZ(30),
58         SR_KHZ(40),
59         SR_KHZ(50),
60         SR_KHZ(60),
61         SR_KHZ(80),
62         SR_KHZ(100),
63         SR_KHZ(125),
64         SR_KHZ(150),
65         SR_KHZ(160), /* max rate of 3 ADC chans that has integer divisor/dividend */
66         SR_KHZ(200),
67         SR_KHZ(250), /* max rate of 2 ADC chans */
68         SR_KHZ(300),
69         SR_KHZ(400),
70         SR_KHZ(500),
71         SR_KHZ(600),
72         SR_KHZ(800),
73         /* Give finer granularity near the thresholds of RLE effectiveness ~1-4Msps
74          * Also use 1.2 and 2.4 as likely max values for ADC overclocking */
75         SR_MHZ(1),
76         SR_MHZ(1.2),
77         SR_MHZ(1.5),
78         SR_MHZ(2),
79         SR_MHZ(2.4),
80         SR_MHZ(3),
81         SR_MHZ(4),
82         SR_MHZ(5),
83         SR_MHZ(6),
84         SR_MHZ(8),
85         SR_MHZ(10),
86         SR_MHZ(15),
87         SR_MHZ(20),
88         SR_MHZ(30),
89         SR_MHZ(40),
90         SR_MHZ(60),
91         /* The baseline 120Mhz PICO clock won't support an 80 or 100
92          * with non fractional divisor, but an overclocked version or one
93          * that modified sysclk could */
94         SR_MHZ(80),
95         SR_MHZ(100),
96         SR_MHZ(120),
97         /* These may not be practically useful, but someone might want to
98          * try to make it work with overclocking */
99         SR_MHZ(150),
100         SR_MHZ(200),
101         SR_MHZ(240),
102 };
103
104 static const uint32_t drvopts[] = {
105         SR_CONF_OSCILLOSCOPE,
106         SR_CONF_LOGIC_ANALYZER,
107 };
108
109 static const int32_t trigger_matches[] = {
110         SR_TRIGGER_ZERO,
111         SR_TRIGGER_ONE,
112         SR_TRIGGER_RISING,
113         SR_TRIGGER_FALLING,
114         SR_TRIGGER_EDGE,
115 };
116
117
118 static const uint32_t devopts[] = {
119         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
120         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
121         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
122         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
123 };
124
125 static struct sr_dev_driver raspberrypi_pico_driver_info;
126
127
128 static GSList *scan(struct sr_dev_driver *di, GSList * options)
129 {
130         struct sr_config *src;
131         struct sr_dev_inst *sdi;
132         struct sr_serial_dev_inst *serial;
133         struct dev_context *devc;
134         struct sr_channel *ch;
135         GSList *l;
136         int num_read;
137         int i;
138         const char *conn, *serialcomm, *force_detect;
139         char buf[32];
140         char ustr[64];
141         int len;
142         uint8_t num_a, num_d, a_size;
143         gchar *channel_name;
144
145         conn = serialcomm = force_detect = NULL;
146         for (l = options; l; l = l->next) {
147                 src = l->data;
148                 switch (src->key) {
149                 case SR_CONF_CONN:
150                         conn = g_variant_get_string(src->data, NULL);
151                         break;
152                 case SR_CONF_SERIALCOMM:
153                         serialcomm = g_variant_get_string(src->data, NULL);
154                         break;
155                 case SR_CONF_FORCE_DETECT:
156                         force_detect = g_variant_get_string(src->data, NULL);
157                         sr_info("Force detect string %s", force_detect);
158                         break;
159                 }
160         }
161         if (!conn)
162                 return NULL;
163
164         if (!serialcomm)
165                 serialcomm = SERIALCOMM;
166
167         serial = sr_serial_dev_inst_new(conn, serialcomm);
168         sr_info("Opening %s.", conn);
169         if (serial_open(serial, SERIAL_RDWR) != SR_OK) {
170                 sr_err("1st serial open fail");
171                 return NULL;
172         }
173
174         sr_info("Resetting device with *s at %s.", conn);
175         send_serial_char(serial, '*');
176         g_usleep(10000);
177         do {
178                 sr_warn("Drain reads");
179                 len = serial_read_blocking(serial, buf, 32, 100);
180                 sr_warn("Drain reads done");
181                 if (len)
182                         sr_dbg("Dropping in flight serial data");
183         } while (len > 0);
184         /* Send the user string with the identify */
185         if (force_detect && (strlen(force_detect) <= 60)) {
186                 sprintf(ustr,"i%s\n", force_detect);
187                 sr_info("User string %s", ustr);
188                 num_read = send_serial_w_resp(serial, ustr, buf, 17);
189         } else {
190                 num_read = send_serial_w_resp(serial, "i\n", buf, 17);
191         }
192         if (num_read < 16) {
193                 sr_err("1st identify failed");
194                 serial_close(serial);
195                 g_usleep(100000);
196                 if (serial_open(serial, SERIAL_RDWR) != SR_OK) {
197                         sr_err("2nd serial open fail");
198                         return NULL;
199                 }
200                 g_usleep(100000);
201                 sr_err("Send second *");
202                 send_serial_char(serial, '*');
203                 g_usleep(100000);
204                 num_read = send_serial_w_resp(serial, "i\n", buf, 17);
205                 if (num_read < 10) {
206                         sr_err("Second attempt failed");
207                         return NULL;
208                 }
209         }
210
211         /* Expected ID response is SRPICO,AxxyDzz,VV
212          * where xx are number of analog channels, y is bytes per analog sample
213          * (7 bits per byte), zz is number of digital channels, and VV is two digit
214          * version# which must be 02 */
215         if ((num_read < 16) || (strncmp(buf, "SRPICO,A", 8)) \
216                 || (buf[11] != 'D') || (buf[15] != '0') || (buf[16] != '2')) {
217                 sr_err("ERROR: Bad response string %s %d", buf, num_read);
218                 return NULL;
219         }
220
221         a_size = buf[10] - '0';
222         buf[10] = '\0';         /*Null to end the str for atois */
223         buf[14] = '\0';         
224         num_a = atoi(&buf[8]);
225         num_d = atoi(&buf[12]);
226
227         sdi = g_malloc0(sizeof(struct sr_dev_inst));
228         sdi->status = SR_ST_INACTIVE;
229         sdi->vendor = g_strdup("Raspberry Pi");
230         sdi->model = g_strdup("PICO");
231         sdi->version = g_strdup("00");
232         sdi->conn = serial;
233         sdi->driver = &raspberrypi_pico_driver_info;
234         sdi->inst_type = SR_INST_SERIAL;
235         sdi->serial_num = g_strdup("N/A");
236
237         if (((num_a == 0) && (num_d == 0)) \
238                 || (num_a > MAX_ANALOG_CHANNELS) || (num_d > MAX_DIGITAL_CHANNELS)
239                 || (a_size < 1) || (a_size > 4)) {
240                 sr_err("ERROR: invalid channel config a %d d %d asz %d",
241                         num_a, num_d, a_size);
242                 return NULL;
243         }
244
245         devc = g_malloc0(sizeof(struct dev_context));
246         devc->a_size = a_size;
247         devc->num_a_channels = num_a;
248         devc->num_d_channels = num_d;
249         devc->a_chan_mask = ((1 << num_a) - 1);
250         devc->d_chan_mask = ((1 << num_d) - 1);
251
252         /* The number of bytes that each digital sample in the buffers sent to the
253          * session. All logical channels are packed together, where a slice of N
254          * channels takes roundup(N/8) bytes. This never changes even if channels
255          * are disabled because PV expects disabled channels to still be accounted
256          * for in the packing */
257         devc->dig_sample_bytes = ((devc->num_d_channels + 7) / 8);
258         /* These are the slice sizes of the data on the wire
259          * 1 7 bit field per byte */
260         devc->bytes_per_slice = (devc->num_a_channels * devc->a_size);
261
262         if (devc->num_d_channels > 0) {
263                 /* logic sent in groups of 7*/
264                 devc->bytes_per_slice += (devc->num_d_channels + 6) / 7;
265         }
266         sr_dbg("num channels a %d d %d bps %d dsb %d", num_a, num_d,
267                 devc->bytes_per_slice, devc->dig_sample_bytes);
268
269         /* Each analog channel is its own group; digital are just channels;
270          * Grouping of channels is rather arbitrary as parameters like sample rate
271          * and number of samples apply to all channels. Analog channels do have a
272          * scale and offset, but that is applied automatically. */
273         devc->analog_groups = g_malloc0(sizeof(struct sr_channel_group *) *
274                 devc->num_a_channels);
275         for (i = 0; i < devc->num_a_channels; i++) {
276                 channel_name = g_strdup_printf("A%d", i);
277                 ch = sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_name);
278                 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
279                 devc->analog_groups[i]->name = channel_name;
280                 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
281                 sdi->channel_groups = g_slist_append(sdi->channel_groups,
282                         devc->analog_groups[i]);
283         }
284
285         if (devc->num_d_channels > 0) {
286                 for (i = 0; i < devc->num_d_channels; i++) {
287                         /* Name digital channels starting at D2 to match pico board names */
288                         channel_name = g_strdup_printf("D%d", i + 2);
289                         sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name);
290                         g_free(channel_name);
291                 }
292         }
293
294         /* In large sample usages we get the call to receive with large transfers.
295          * Since the CDC serial implemenation can silenty lose data as it gets close
296          * to full, allocate storage for a half buffer which in a worst case
297          * scenario has 2x ratio of transmitted bytes to storage bytes.
298          * Note: The intent of making this buffer large is to prevent CDC serial
299          * buffer overflows. However, it is likely that if the host is running slow
300          * (i.e. it's a raspberry pi model 3) that it becomes compute bound and
301          * doesn't service CDC serial responses in time to not overflow the internal
302          * CDC buffers. Thus no serial buffer is large enough.
303          * But, it's only 32K... */
304         devc->serial_buffer_size = 32000;
305         devc->buffer = NULL;
306         sr_dbg("Setting serial buffer size: %i.", devc->serial_buffer_size);
307
308         devc->cbuf_wrptr = 0;
309         /* While slices are sent as a group of one sample across all channels,
310          * sigrok wants analog channel data sent as separate packets. Logical trace
311          * values are packed together. An RLE byte in normal mode can represent up
312          * to 1640 samples. In D4 an RLE byte can represent up to 640 samples.
313          * Rather than making the sample_buf_size 1640x the size of serial buffer,
314          * we require that the process loops push samples to the session as we get
315          * anywhere close to full. */
316
317         devc->sample_buf_size = devc->serial_buffer_size;
318         for (i = 0; i < devc->num_a_channels; i++) {
319                 devc->a_data_bufs[i] = NULL;
320                 devc->a_pretrig_bufs[i] = NULL;
321         }
322         devc->d_data_buf = NULL;
323         devc->sample_rate = 5000;
324         devc->capture_ratio = 10;
325         devc->rxstate = RX_IDLE;
326         /*Set an initial value as various code relies on an inital value. */
327         devc->limit_samples = 1000;
328
329         sdi->priv = devc;
330
331         if (raspberrypi_pico_get_dev_cfg(sdi) != SR_OK) {
332                 return NULL;
333         };
334
335         serial_close(serial);
336         return std_scan_complete(di, g_slist_append(NULL, sdi));
337 }
338
339 /* Note that on the initial driver load we pull all values into local storage.
340  * Thus gets can return local data, but sets have to issue commands to device. */
341 static int config_set(uint32_t key, GVariant * data,
342         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
343 {
344         struct dev_context *devc;
345         int ret;
346         (void) cg;
347
348         if (!sdi)
349                 return SR_ERR_ARG;
350
351         devc = sdi->priv;
352         ret = SR_OK;
353
354         sr_dbg("Got config_set key %d \n", key);
355         switch (key) {
356         case SR_CONF_SAMPLERATE:
357                 devc->sample_rate = g_variant_get_uint64(data);
358                 sr_dbg("config_set sr %lu\n", devc->sample_rate);
359                 break;
360         case SR_CONF_LIMIT_SAMPLES:
361                 devc->limit_samples = g_variant_get_uint64(data);
362                 sr_dbg("config_set slimit %" PRIu64 "\n", devc->limit_samples);
363                 break;
364         case SR_CONF_CAPTURE_RATIO:
365                 devc->capture_ratio = g_variant_get_uint64(data);
366                 break;
367
368         default:
369                 sr_err("ERROR: config_set given undefined key %d\n", key);
370                 ret = SR_ERR_NA;
371         }
372
373         return ret;
374 }
375
376 static int config_get(uint32_t key, GVariant ** data,
377         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
378 {
379         struct dev_context *devc;
380
381         sr_dbg("config_get given key %d", key);
382
383         (void) cg;
384
385         if (!sdi)
386                 return SR_ERR_ARG;
387
388         devc = sdi->priv;
389         switch (key) {
390         case SR_CONF_SAMPLERATE:
391                 *data = g_variant_new_uint64(devc->sample_rate);
392                 sr_spew("sample rate get of %" PRIu64 "", devc->sample_rate);
393                 break;
394         case SR_CONF_CAPTURE_RATIO:
395                 if (!sdi)
396                         return SR_ERR;
397                 devc = sdi->priv;
398                 *data = g_variant_new_uint64(devc->capture_ratio);
399                 break;
400         case SR_CONF_LIMIT_SAMPLES:
401                 sr_spew("config_get limit_samples of %lu", devc->limit_samples);
402                 *data = g_variant_new_uint64(devc->limit_samples);
403                 break;
404         default:
405                 sr_spew("unsupported config_get key %d", key);
406                 return SR_ERR_NA;
407         }
408         return SR_OK;
409 }
410
411 static int config_list(uint32_t key, GVariant ** data,
412         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
413 {
414         (void) cg;
415
416         /* Scan or device options are the only ones that can be called without a
417          * defined instance */
418         if ((key == SR_CONF_SCAN_OPTIONS) || (key == SR_CONF_DEVICE_OPTIONS)) {
419                 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
420         }
421
422         if (!sdi) {
423                 sr_err("ERROR: Call to config list with null sdi");
424                 return SR_ERR_ARG;
425         }
426
427         sr_dbg("Start config_list with key %X", key);
428         switch (key) {
429         case SR_CONF_SAMPLERATE:
430                 *data = std_gvar_samplerates(ARRAY_AND_SIZE(samplerates));
431                 break;
432         /* This must be set to get SW trigger support */
433         case SR_CONF_TRIGGER_MATCH:
434                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
435                 break;
436         case SR_CONF_LIMIT_SAMPLES:
437                 /* Really this limit is up to the memory capacity of the host,
438                  * and users that pick huge values deserve what they get.
439                  * But setting this limit to prevent really crazy things. */
440                 *data = std_gvar_tuple_u64(1LL, 1000000000LL);
441                 break;
442         default:
443                 sr_dbg("Reached default statement of config_list");
444
445                 return SR_ERR_NA;
446         }
447
448         return SR_OK;
449 }
450
451 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
452 {
453         struct sr_serial_dev_inst *serial;
454         struct dev_context *devc;
455         struct sr_channel *ch;
456         struct sr_trigger *trigger;
457         char tmpstr[20];
458         char buf[32];
459         GSList *l;
460         int a_enabled = 0, d_enabled = 0, len;
461         serial = sdi->conn;
462         int i, num_read;
463
464         devc = sdi->priv;
465         sr_dbg("Enter acq start");
466         sr_dbg("dsbstart %d", devc->dig_sample_bytes);
467
468         devc->buffer = g_malloc(devc->serial_buffer_size);
469         if (!(devc->buffer)) {
470                 sr_err("ERROR: serial buffer malloc fail");
471                 return SR_ERR_MALLOC;
472         }
473
474         /* Get device in idle state */
475         if (serial_drain(serial) != SR_OK) {
476                 sr_err("Initial Drain Failed");
477                 return SR_ERR;
478         }
479
480         send_serial_char(serial, '*');
481         if (serial_drain(serial) != SR_OK) {
482                 sr_err("Second Drain Failed");
483                 return SR_ERR;
484         }
485
486         for (l = sdi->channels; l; l = l->next) {
487                 ch = l->data;
488                 sr_dbg("c %d enabled %d name %s\n", ch->index, ch->enabled, ch->name);
489
490                 if (ch->name[0] == 'A') {
491                         devc->a_chan_mask &= ~(1 << ch->index);
492                         if (ch->enabled) {
493                                 devc->a_chan_mask |= (ch->enabled << ch->index);
494                                 a_enabled++;
495                         }
496                 }
497                 if (ch->name[0] == 'D') {
498                         devc->d_chan_mask &= ~(1 << ch->index);
499                         if (ch->enabled) {
500                                 devc->d_chan_mask |= (ch->enabled << ch->index);
501                                 d_enabled++;
502                         }
503                 }
504
505                 sr_info("Channel enable masks D 0x%X A 0x%X",
506                         devc->d_chan_mask, devc->a_chan_mask);
507                 sprintf(tmpstr, "%c%d%d\n", ch->name[0], ch->enabled, ch->index);
508                 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
509                         sr_err("ERROR: Channel enable fail");
510                         return SR_ERR;
511                 }
512         }
513
514         /* Ensure data channels are continuous */
515         int invalid = 0;
516         for (i = 0; i < 32; i++) {
517                 if ((devc->d_chan_mask >> i) & 1) {
518                         if (invalid) {
519                                 sr_err("Digital channel mask 0x%X not continous",
520                                         devc->d_chan_mask);
521                                 return SR_ERR;
522                         }
523                 } else
524                         invalid = 1;
525         }
526
527         /* Recalculate bytes_per_slice based on which analog channels are enabled */
528         devc->bytes_per_slice = (a_enabled * devc->a_size);
529
530         for (i = 0; i < devc->num_d_channels; i += 7)
531                 if (((devc->d_chan_mask) >> i) & (0x7F))
532                         (devc->bytes_per_slice)++;
533
534         if ((a_enabled == 0) && (d_enabled == 0)) {
535                 sr_err("ERROR:No channels enabled");
536                 return SR_ERR;
537         }
538
539         sr_dbg("bps %d\n", devc->bytes_per_slice);
540
541         /* Apply sample rate limits; while earlier versions forced a lower sample
542          * rate, the PICO seems to allow ADC overclocking, and by not enforcing
543          * these limits it may support other devices. Thus call sr_err to get
544          * something into the device logs, but allowing it to progress. */
545         if ((a_enabled == 3) && (devc->sample_rate > 160000))
546                 sr_err("WARN: 3 channel ADC sample rate above 160khz");
547         if ((a_enabled == 2) && (devc->sample_rate > 250000))
548                 sr_err("WARN: 2 channel ADC sample rate above 250khz");
549         if ((a_enabled == 1) && (devc->sample_rate > 500000))
550                 sr_err("WARN: 1 channel ADC sample rate above 500khz");
551
552         /* Depending on channel configs, rates below 5ksps are possible but such a
553          * low rate can easily stream and this eliminates a lot of special cases. */
554         if (devc->sample_rate < 5000) {
555                 sr_err("Sample rate override to min of 5ksps");
556                 devc->sample_rate = 5000;
557         }
558
559         /* While PICO specs a max clock ~120-125Mhz, it does overclock in many cases
560          * so leaving a warning. */
561         if (devc->sample_rate > 120000000)
562                 sr_warn("WARN: Sample rate above 120Msps");
563
564         /* It may take a very large number of samples to notice, but if digital and
565          * analog are enabled and either PIO or ADC are fractional the samples will
566          * skew over time. 24Mhz is the max common divisor to the 120Mhz and 48Mhz
567          * ADC clock so force an integer divisor to 24Mhz. */
568         if ((a_enabled > 0) && (d_enabled > 0)) {
569                 if (24000000ULL % (devc->sample_rate)) {
570                         uint32_t commondivint = 24000000ULL / (devc->sample_rate);
571                         /* Always increment the divisor so that we go down in frequency to
572                          * avoid max sample rate issues */
573                         commondivint++;
574                         devc->sample_rate = 24000000ULL / commondivint;
575                         /* Make sure the divisor increment didn't make us go too low. */
576                         if (devc->sample_rate < 5000)
577                                 devc->sample_rate = 50000;
578                         sr_warn("WARN: Forcing common integer divisor sample rate of " \
579                                 "%lu div %u", devc->sample_rate, commondivint);
580                 }
581         }
582
583         /* If we are only digital or only analog print a warning that the fractional
584          * divisors aren't a true PLL fractional feedback loop and thus could have
585          * sample to sample variation. These warnings of course assume that the
586          * device is programmed with the expected ratios but non PICO
587          * implementations, or PICO implementations that use different divisors
588          * could avoid. This generally won't be a problem because most of the
589          * sample_rate pulldown values are integer divisors. */
590         if ((a_enabled > 0) && (48000000ULL % (devc->sample_rate * a_enabled)))
591                 sr_warn("WARN: Non integer ADC divisor of 48Mhz clock for sample " \
592                         "rate %lu may cause sample to sample variability.",
593                         devc->sample_rate);
594         if ((d_enabled > 0) && (120000000ULL % (devc->sample_rate)))
595                 sr_warn("WARN: Non integer PIO divisor of 120Mhz for sample rate " \
596                         "%lu may cause sample to sample variability.", devc->sample_rate);
597
598         sprintf(tmpstr, "L%" PRIu64 "\n", devc->limit_samples);
599         if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
600                 sr_err("Sample limit to device failed");
601                 return SR_ERR;
602         }
603
604         /* To support future devices that may allow the analog scale/offset to
605          * change, call get_dev_cfg again to get new values */
606         if (raspberrypi_pico_get_dev_cfg(sdi) != SR_OK) {
607                 sr_err("get_dev_cfg failure on start");
608                 return SR_ERR;
609         }
610
611         /* With all other params set, we use the final sample rate setting as an
612          * opportunity for the device to communicate any errors in configuration.
613          * A single  "*" indicates success.
614          * A "*" with subsequent data is success, but allows for the device to
615          * print something to the error console without aborting.
616          * A non "*" in the first character blocks the start. */
617         sprintf(tmpstr, "R%lu\n", devc->sample_rate);
618         num_read = send_serial_w_resp(serial, tmpstr, buf, 30);
619         buf[num_read] = 0;
620         if ((num_read > 1) && (buf[0] == '*'))
621                 sr_dbg("Sample rate to device success with resp %s", buf);
622         else if (!((num_read == 1) && (buf[0] == '*'))) {
623                 sr_err("Sample rate to device failed");
624                 if (num_read > 0) {
625                         buf[num_read]=0;
626                         sr_err("sample_rate error string %s",buf);
627                 }
628                 return SR_ERR;
629         }
630
631         devc->sent_samples = 0;
632         devc->byte_cnt = 0;
633         devc->bytes_avail = 0;
634         devc->wrptr = 0;
635         devc->cbuf_wrptr = 0;
636         len = serial_read_blocking(serial, devc->buffer, devc->serial_buffer_size,
637                 serial_timeout(serial, 4));
638
639         if (len > 0) {
640                 sr_info("Pre-ARM drain had %d characters:", len);
641                 devc->buffer[len] = 0;
642                 sr_info("%s", devc->buffer);
643         }
644
645         for (i = 0; i < devc->num_a_channels; i++) {
646                 devc->a_data_bufs[i] = g_malloc(devc->sample_buf_size * sizeof(float));
647                 if (!(devc->a_data_bufs[i])) {
648                         sr_err("ERROR: analog buffer malloc fail");
649                         return SR_ERR_MALLOC;
650                 }
651         }
652
653         if (devc->num_d_channels > 0) {
654                 devc->d_data_buf = g_malloc(devc->sample_buf_size *
655                         devc->dig_sample_bytes);
656                 if (!(devc->d_data_buf)) {
657                         sr_err("ERROR: logic buffer malloc fail");
658                         return SR_ERR_MALLOC;
659                 }
660         }
661
662         devc->pretrig_entries = (devc->capture_ratio * devc->limit_samples) / 100;
663         /* While the driver supports the passing of trigger info to the device
664          * it has been found that the sw overhead of supporting triggering and
665          * pretrigger buffer entries etc.. ends up slowing the cores down enough
666          * that the effective continous sample rate isn't much higher than that of
667          * sending untriggered samples across USB.  Thus this code will remain but
668          * likely may not be used by the device, unless HW based triggers are
669          * implemented */
670         if ((trigger = sr_session_trigger_get(sdi->session))) {
671                 if (g_slist_length(trigger->stages) > 1)
672                         return SR_ERR_NA;
673
674                 struct sr_trigger_stage *stage;
675                 struct sr_trigger_match *match;
676                 GSList *l;
677                 stage = g_slist_nth_data(trigger->stages, 0);
678                 if (!stage)
679                         return SR_ERR_ARG;
680                 for (l = stage->matches; l; l = l->next) {
681                         match = l->data;
682                         if (!match->match)
683                                 continue;
684                         if (!match->channel->enabled)
685                                 continue;
686                         int idx = match->channel->index;
687                         int8_t val;
688                         switch(match->match) {
689                         case SR_TRIGGER_ZERO:
690                                 val = 0; break;
691                         case SR_TRIGGER_ONE:
692                                 val = 1; break;
693                         case SR_TRIGGER_RISING:
694                                 val = 2; break;
695                         case SR_TRIGGER_FALLING:
696                                 val = 3; break;
697                         case SR_TRIGGER_EDGE:
698                                 val = 4; break;
699                         default:
700                                 val = -1;
701                         }
702                         sr_info("Trigger value idx %d match %d", idx, match->match);
703                         /* Only set trigger on enabled channels */
704                         if ((val >= 0) && ((devc->d_chan_mask >> idx) & 1)) {
705                                 sprintf(&tmpstr[0], "t%d%02d\n", val, idx+2);
706                                 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
707                                         sr_err("Trigger cfg to device failed");
708                                         return SR_ERR;
709                                 }
710                         }
711                 }
712
713                 sprintf(&tmpstr[0], "p%d\n", devc->pretrig_entries);
714                 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
715                         sr_err("Pretrig to device failed");
716                         return SR_ERR;
717                 }
718
719                 devc->stl = soft_trigger_logic_new(sdi, trigger, devc->pretrig_entries);
720                 if (!devc->stl)
721                         return SR_ERR_MALLOC;
722
723                 devc->trigger_fired = FALSE;
724                 if (devc->pretrig_entries > 0) {
725                         sr_dbg("Allocating pretrig buffers size %d", devc->pretrig_entries);
726                         for (i = 0; i < devc->num_a_channels; i++) {
727                                 if ((devc->a_chan_mask >> i) & 1) {
728                                         devc->a_pretrig_bufs[i] = g_malloc0(sizeof(float) *
729                                                 devc->pretrig_entries);
730                                         if (!devc->a_pretrig_bufs[i]) {
731                                                 sr_err("ERROR:Analog pretrigger buffer malloc " \
732                                                         "failure, disabling");
733                                                 devc->trigger_fired = TRUE;
734                                         }
735                                 }
736                         }
737                 }
738
739                 sr_info("Entering sw triggered mode");
740                 /* Post the receive before starting the device to ensure we are ready
741                  * to receive data ASAP */
742                 serial_source_add(sdi->session, serial, G_IO_IN, 200,
743                         raspberrypi_pico_receive, (void*)sdi);
744
745                 sprintf(tmpstr, "C\n");
746                 if (send_serial_str(serial, tmpstr) != SR_OK)
747                         return SR_ERR;
748
749         } else {
750                 devc->trigger_fired = TRUE;
751                 devc->pretrig_entries = 0;
752                 sr_info("Entering fixed sample mode");
753                 serial_source_add(sdi->session, serial, G_IO_IN, 200,
754                         raspberrypi_pico_receive, (void*)sdi);
755
756                 sprintf(tmpstr, "F\n");
757                 if (send_serial_str(serial, tmpstr) != SR_OK)
758                         return SR_ERR;
759         }
760
761         std_session_send_df_header(sdi);
762
763         sr_dbg("dsbstartend %d", devc->dig_sample_bytes);
764
765         if (devc->trigger_fired)
766                 std_session_send_df_trigger(sdi);
767
768         /* Keep this at the end as we don't want to be RX_ACTIVE unless everything
769          * is ok */
770         devc->rxstate = RX_ACTIVE;
771
772         return SR_OK;
773 }
774
775 /* This function is called either by the protocol code if we reached all of the
776  * samples or an error condition, and also by the user clicking stop in
777  * pulseview. It must always be called for any acquistion that was started to
778  * free memory. */
779 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
780 {
781         struct dev_context *devc;
782         struct sr_serial_dev_inst *serial;
783         int len;
784         devc = sdi->priv;
785         serial = sdi->conn;
786
787         sr_dbg("At dev_acquisition_stop");
788
789         std_session_send_df_end(sdi);
790
791         /* If we reached this while still active it is likely because the stop
792          * button was pushed in pulseview. That is generally some kind of error
793          * condition, so we don't try to check the bytenct */
794         if (devc->rxstate == RX_ACTIVE)
795                 sr_err("Reached dev_acquisition_stop in RX_ACTIVE");
796
797         if (devc->rxstate != RX_IDLE) {
798                 sr_err("Sending plus to stop device stream");
799                 send_serial_char(serial, '+');
800         }
801
802         /* In case we get calls to receive force it to exit */
803         devc->rxstate = RX_IDLE;
804
805         /* Drain data from device so that it doesn't confuse subsequent commands */
806         do {
807                 len = serial_read_blocking(serial, devc->buffer,
808                         devc->serial_buffer_size, 100);
809                 if (len)
810                         sr_err("Dropping %d device bytes", len);
811         } while (len > 0);
812
813         if (devc->buffer) {
814                 g_free(devc->buffer);
815                 devc->buffer = NULL;
816         }
817
818         for (int i = 0; i < devc->num_a_channels; i++) {
819                 if (devc->a_data_bufs[i]) {
820                         g_free(devc->a_data_bufs[i]);
821                         devc->a_data_bufs[i] = NULL;
822                 }
823         }
824         if (devc->d_data_buf) {
825                 g_free(devc->d_data_buf);
826                 devc->d_data_buf = NULL;
827         }
828
829         for (int i = 0; i < devc->num_a_channels; i++) {
830                 if (devc->a_pretrig_bufs[i])
831                         g_free(devc->a_pretrig_bufs[i]);
832                 devc->a_pretrig_bufs[i] = NULL;
833         }
834
835         serial = sdi->conn;
836         serial_source_remove(sdi->session, serial);
837
838         return SR_OK;
839 }
840
841 static struct sr_dev_driver raspberrypi_pico_driver_info = {
842         .name = "raspberrypi-pico",
843         .longname = "RaspberryPI PICO",
844         .api_version = 1,
845         .init = std_init,
846         .cleanup = std_cleanup,
847         .scan = scan,
848         .dev_list = std_dev_list,
849         .dev_clear = std_dev_clear,
850         .config_get = config_get,
851         .config_set = config_set,
852         .config_list = config_list,
853         .dev_open = std_serial_dev_open,
854         .dev_close = std_serial_dev_close,
855         .dev_acquisition_start = dev_acquisition_start,
856         .dev_acquisition_stop = dev_acquisition_stop,
857         .context = NULL,
858 };
859
860 SR_REGISTER_DEV_DRIVER(raspberrypi_pico_driver_info);