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