2 * This file is part of the libsigrok project.
4 * Copyright (C) 2022 Shawn Walker <ac0bi00@gmail.com>
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.
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.
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/>.
19 //debug print levels are err/warn/info/dbg/spew
28 #include <libsigrok/libsigrok.h>
29 #include "libsigrok-internal.h"
33 #define SERIALCOMM "115200/8n1"
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
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[] = {
49 static const uint32_t drvopts[] = {
51 SR_CONF_LOGIC_ANALYZER,
53 //SW trigger requires this
54 static const int32_t trigger_matches[] = {
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,
72 static struct sr_dev_driver raspberrypi_pico_driver_info;
75 static GSList *scan(struct sr_dev_driver *di, GSList *options)
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;
85 const char *conn, *serialcomm;
88 uint8_t num_a,num_d,a_size;
91 conn = serialcomm = NULL;
92 for (l = options; l; l = l->next) {
96 conn = g_variant_get_string(src->data, NULL);
98 case SR_CONF_SERIALCOMM:
99 serialcomm = g_variant_get_string(src->data, NULL);
107 serialcomm = SERIALCOMM;
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");
116 sr_info("Reseting device with *s at %s.", conn);
117 send_serial_char(serial,'*');
119 //drain any inflight data
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");
129 num_read=send_serial_w_resp(serial,"i\n",buf,17);
131 sr_err("1st identify failed");
132 serial_close(serial);
134 if (serial_open(serial, SERIAL_RDWR) != SR_OK){
135 sr_err("2st serial open fail");
139 sr_err("Send second *");
140 send_serial_char(serial,'*');
142 num_read=send_serial_w_resp(serial,"i\n",buf,17);
144 sr_err("Second attempt failed");
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
152 ||(strncmp(buf,"SRPICO,A",8))
156 sr_err("ERROR:Bad response string %s %d",buf,num_read);
160 buf[10]='\0'; //Null to end the str for atois
161 buf[14]='\0'; //Null to end the str for atois
163 num_d=atoi(&buf[12]);
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");
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)
179 sr_err("ERROR: invalid channel config a %d d %d asz %d",num_a,num_d,a_size);
182 devc = g_malloc0(sizeof(struct dev_context));
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");
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;
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]);
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,
230 g_free(channel_name);
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
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;
244 sr_dbg("Setting serial buffer size: %i.", devc->serial_buffer_size);
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;
258 devc->d_data_buf=NULL;
259 devc->sample_rate=5000;
260 devc->capture_ratio=10;
261 devc->rxstate=RX_IDLE;
263 //Set an initial value as various code relies on an inital value.
264 devc->limit_samples=1000;
266 if(raspberrypi_pico_get_dev_cfg(sdi)!=SR_OK){
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");
276 return std_scan_complete(di, g_slist_append(NULL, sdi));
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)
287 struct dev_context *devc;
294 sr_dbg("Got config_set key %d \n",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);
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);
304 case SR_CONF_CAPTURE_RATIO:
305 devc->capture_ratio = g_variant_get_uint64(data);
309 sr_err("ERROR:config_set undefine %d\n",key);
316 static int config_get(uint32_t key, GVariant **data,
317 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
319 struct dev_context *devc;
320 sr_dbg("at config_get key %d",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);
331 case SR_CONF_CAPTURE_RATIO:
335 *data = g_variant_new_uint64(devc->capture_ratio);
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);
342 sr_spew("unsupported cfg_get key %d",key);
348 static int config_list(uint32_t key, GVariant **data,
349 const struct sr_dev_inst *sdi, const struct sr_channel_group *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);
357 sr_err("ERROR:\n\r\n\r\n\r Call to config list with null sdi\n\r\n\r");
360 sr_dbg("start config_list with key %X\n",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));
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));
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 ");
380 sr_dbg("reached default statement of config_list");
388 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
390 struct sr_serial_dev_inst *serial;
391 struct dev_context *devc;
392 struct sr_channel *ch;
393 struct sr_trigger *trigger;
396 int a_enabled=0,d_enabled=0,len;
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;}
409 for (l = sdi->channels; l; l = l->next) {
411 sr_dbg("c %d enabled %d name %s\n",ch->index,ch->enabled,ch->name);
413 if(ch->name[0]=='A'){
414 devc->a_chan_mask&=~(1<<ch->index);
416 devc->a_chan_mask|=(ch->enabled<<ch->index);
419 // sr_dbg("A%d en %d mask 0x%X",ch->index,ch->enabled,devc->a_chan_mask);
422 if(ch->name[0]=='D'){
423 devc->d_chan_mask&=~(1<<ch->index);
425 devc->d_chan_mask|=(ch->enabled<<ch->index);
427 // sr_dbg("D%d en %d mask 0x%X",ch->index,ch->enabled,devc->d_chan_mask);
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");
439 //ensure data channels are continuous
442 if((devc->d_chan_mask>>i)&1){
444 sr_err("Digital channel mask 0x%X not continous\n\r",devc->d_chan_mask);
452 //recalculate bytes_per_slice.
453 devc->bytes_per_slice=(a_enabled*devc->a_size);
455 for(i=0;i<devc->num_d_channels;i+=7){
456 if(((devc->d_chan_mask)>>i)&(0x7F)){(devc->bytes_per_slice)++;}
458 if((a_enabled==0)&&(d_enabled==0)){
459 sr_err("ERROR:No channels enabled");
462 sr_dbg("bps %d\n",devc->bytes_per_slice);
464 //Apply sample rate limits
465 //Save off the lower rate values which are hacked way of getting configs to the device
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;
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;
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;
482 //Depending on channel configs, rates below 5ksps are possible
483 //but such a low rate can easily stream and this eliminates a lot
485 if(devc->sample_rate<5000){
486 sr_err("Sample rate override to min of 5ksps");
487 devc->sample_rate=5000;
489 if(devc->sample_rate>120000000){
490 sr_err("Sample rate override to max of 120Msps");
491 devc->sample_rate=12000000;
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
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)){
507 devc->sample_rate=24000000ULL/commondivint;
508 //sr_err(" sample rate of %llu div %u\n\r",devc->sample_rate,commondivint);
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);
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.
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);
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);
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;
538 devc->sample_rate+=cfg_bits;
540 sr_warn("Embedding cfg_bits of 0x%X in sample_rate %lld\n\r",cfg_bits,devc->sample_rate);
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");
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");
554 devc->sent_samples=0;
559 len=serial_read_blocking(serial, devc->buffer, devc->serial_buffer_size,serial_timeout(serial, 4));
561 sr_info("Pre-ARM drain had %d characters:",len);
563 sr_info("%s",devc->buffer);
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;}
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;}
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);
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;
591 }//for num_a_channels
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)
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)
609 std_session_send_df_header(sdi);
611 sr_dbg("dsbstartend %d",devc->dig_sample_bytes);
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;
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)
624 struct dev_context *devc;
625 struct sr_serial_dev_inst *serial;
626 sr_dbg("****at dev_acquisition_stop");
631 std_session_send_df_end(sdi);
632 //If we reached this while still active it is likely because the stop button was pushed
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");
638 if(devc->rxstate!=RX_IDLE){
639 sr_err("Sending plus to stop device stream\n\r");
640 send_serial_char(serial,'+');
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
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);
652 if(devc->buffer){g_free(devc->buffer);devc->buffer=NULL;}
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;
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;
668 serial_source_remove(sdi->session, serial);
673 static struct sr_dev_driver raspberrypi_pico_driver_info = {
674 .name = "raspberrypi-pico",
675 .longname = "RaspberryPI PICO",
678 .cleanup = std_cleanup,
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,
691 SR_REGISTER_DEV_DRIVER(raspberrypi_pico_driver_info);