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