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