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