]> sigrok.org Git - libsigrok.git/blob - src/hardware/raspberrypi-pico/protocol.c
99971ed05b2c67e6077b5d98f3980964b7a5532e
[libsigrok.git] / src / hardware / raspberrypi-pico / protocol.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 #define _GNU_SOURCE
20
21 #include <config.h>
22 #include <errno.h>
23 #include <glib.h>
24 #include <math.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <time.h>
29 #include <unistd.h>
30 #include <libsigrok/libsigrok.h>
31 #include "libsigrok-internal.h"
32 #include "protocol.h"
33
34 SR_PRIV int send_serial_str(struct sr_serial_dev_inst *serial, char *str)
35 {
36         int len = strlen(str);
37         if ((len > 15) || (len < 1)) {  //limit length to catch errant strings
38                 sr_err("ERROR:Serial string len %d invalid ", len);
39                 return SR_ERR;
40         }
41         //100ms timeout. With USB CDC serial we can't define the timeout
42         //based on link rate, so just pick something large as we shouldn't normally see them
43         if (serial_write_blocking(serial, str, len, 100) != len) {
44                 sr_err("ERROR:Serial str write failed");
45                 return SR_ERR;
46         }
47
48         return SR_OK;
49 }
50
51 SR_PRIV int send_serial_char(struct sr_serial_dev_inst *serial, char ch)
52 {
53         char buf[1];
54         buf[0] = ch;
55         if (serial_write_blocking(serial, buf, 1, 100) != 1) {  //100ms
56                 sr_err("ERROR:Serial char write failed");
57                 return SR_ERR;
58         }
59         return SR_OK;
60 }
61
62 //Issue a command that expects a string return that is less than 30 characters.
63 //returns the length of string
64 int send_serial_w_resp(struct sr_serial_dev_inst *serial, char *str,
65                        char *resp, size_t cnt)
66 {
67         int num_read, i;
68         send_serial_str(serial, str);
69         //Using the serial_read_blocking function when reading a response of unknown length requires 
70         //a long worst case timeout to always be taken.  So, instead loop waiting for a first byte, and
71         //then a final small delay for the rest. 
72         for (i = 0; i < 1000; i++) {    //wait up to 1 second in ms increments
73                 num_read = serial_read_blocking(serial, resp, cnt, 1);
74                 if (num_read > 0)
75                         break;
76         }
77         //Since the serial port is usb CDC we can't calculate timeouts based on baud rate but
78         //even if the response is split between two USB transfers 10ms should be plenty.
79         num_read +=
80             serial_read_blocking(serial, &(resp[num_read]), cnt - num_read,
81                                  10);
82         if ((num_read < 1) || (num_read > 30)) {
83                 sr_err("ERROR:Serial_w_resp failed (%d).", num_read);
84                 return -1;
85         } else {
86                 return num_read;
87         }
88 }
89
90 //Issue a command that expects a single char ack 
91 SR_PRIV int send_serial_w_ack(struct sr_serial_dev_inst *serial, char *str)
92 {
93         char buf[2];
94         int num_read;
95         //In case we have left over transfer from the device, drain them
96         //These should not exist in normal operation
97         while ((num_read = serial_read_blocking(serial, buf, 2, 10))) {
98                 sr_dbg("swack drops 2 bytes %d %d",buf[0],buf[1]);
99         }
100         send_serial_str(serial, str);
101         //1000ms timeout
102         num_read = serial_read_blocking(serial, buf, 1, 1000);
103         if ((num_read == 1) && (buf[0] == '*')) {
104                 return SR_OK;
105         } else {
106                 sr_err("ERROR:Serial_w_ack %s failed (%d).", str,
107                        num_read);
108                 if (num_read) {
109                         sr_err("ack resp char %c d %d\n\r", buf[0],
110                                buf[0]);
111                 }
112                 return SR_ERR;
113         }
114 }
115
116 //Process incoming data stream assuming it is optimized packing of 4 channels or less
117 //Each byte is 4 channels of data and a 3 bit rle value, or a larger rle value, or a control signal.
118 //This also checks for aborts and ends.
119 //If an end is seen we stop processing but do not check the byte_cnt
120 //The output is a set of samples fed to process group to perform sw triggering and sending of data to the session
121 //as well as maintenance of the serial rx byte cnt.
122 //Since we can get huge rle values we chop them up for processing into smaller groups
123 //In this mode we can always consume all bytes because there are no cases where the processing of one 
124 //byte requires the one after it.
125 void process_D4(struct sr_dev_inst *sdi, struct dev_context *d)
126 {
127         uint32_t j;
128         uint8_t cbyte;
129         uint8_t cval;
130         uint32_t rlecnt = 0;
131         while (d->ser_rdptr < d->bytes_avail) {
132                 cbyte = d->buffer[(d->ser_rdptr)];
133                 //RLE only byte
134                 if (cbyte >= 48 && cbyte <= 127) {
135                         rlecnt += (cbyte - 47) * 8;
136                         d->byte_cnt++;
137                 } else if (cbyte >= 0x80) {     //sample with possible rle
138                         rlecnt += (cbyte & 0x70) >> 4;
139                         if (rlecnt) {
140                                 //On a value change, duplicate the previous values first.
141                                 rle_memset(d, rlecnt);
142                                 rlecnt = 0;
143                         }
144                         //Finally add in the new values
145                         cval = cbyte & 0xF;
146                         uint32_t didx=(d->cbuf_wrptr) * (d->dig_sample_bytes);
147                         d->d_data_buf[didx] = cval;
148                         //pad in all other bytes since the sessions even wants disabled channels reported
149                         for (j = 1; j < d->dig_sample_bytes; j++) {
150                                 d->d_data_buf[didx+j] = 0;
151                         }
152                         d->byte_cnt++;
153                         sr_spew
154                             ("Dchan4 rdptr %d wrptr %d bytein 0x%X rle %d cval 0x%X didx %d\n",
155                              (d->ser_rdptr) - 1, d->cbuf_wrptr, cbyte,
156                              rlecnt, cval,didx);
157                         d->cbuf_wrptr++;
158                         rlecnt = 0;
159                         d->d_last[0] = cval;
160                 }
161                 //Any other character ends parsing - it could be a frame error or a start of the final byte cnt
162                 else {
163                         if (cbyte == '$') {
164                                 sr_info
165                                     ("D4 Data stream stops with cbyte %d char %c rdidx %d cnt %llu",
166                                      cbyte, cbyte, d->ser_rdptr,
167                                      d->byte_cnt);
168                                 d->rxstate = RX_STOPPED;
169                         } else {
170                                 sr_err
171                                     ("D4 Data stream aborts with cbyte %d char %c rdidx %d cnt %llu",
172                                      cbyte, cbyte, d->ser_rdptr,
173                                      d->byte_cnt);
174                                 d->rxstate = RX_ABORT;
175                         }
176                         break;  //break from while loop
177                 }
178                 (d->ser_rdptr)++;
179                 //To ensure we don't overflow the sample buffer, but still send it large chunks of data 
180                 //(to make the packet sends to the session efficient) only call process group after
181                 //a large number of samples have been seen.
182                 //cbuf_wrptr counts slices, so shift right by 2 to create a worst case x4 multiple ratio of
183                 //cbuf_wrptr value to the depth of the sample buffer.
184                 //Likely we could use the max rle value of 640 but 1024 gives some extra room.
185                 //Also do a simple check of rlecnt>2000 since that is a reasonable minimal value to send to the session
186                 if ((rlecnt>=2000)
187                      ||((rlecnt + ((d->cbuf_wrptr)<<2))) > (d->sample_buf_size - 1024)) {
188                          sr_spew("D4 preoverflow wrptr %d bufsize %d rlecnt %d\n\r",d->cbuf_wrptr,d->sample_buf_size,rlecnt);
189                          rle_memset(d, rlecnt);
190                          process_group(sdi, d, d->cbuf_wrptr);
191                          rlecnt=0;
192                      }
193
194         }//while rdptr < wrptr
195         sr_spew("D4 while done rdptr %d", d->ser_rdptr);
196         //If we reach the end of the serial input stream send any remaining values or rles to the session
197         if (rlecnt) {
198                 sr_spew("Residual D4 slice rlecnt %d", rlecnt);
199                 rle_memset(d, rlecnt);
200         }
201         if (d->cbuf_wrptr) {
202                 sr_spew("Residual D4 data wrptr %d", d->cbuf_wrptr);
203                 process_group(sdi, d, d->cbuf_wrptr);
204
205         }
206
207 } //Process_D4
208
209 //Process incoming data stream and forward to trigger processing with process_group
210 //The final value of ser_rdptr indicates how many bytes were processed.
211 //This version handles all other enabled channel configurations that Process_D4 doesn't
212 void process_slice(struct sr_dev_inst *sdi, struct dev_context *devc)
213 {
214         int32_t i;
215         uint32_t tmp32;
216         uint8_t cbyte;
217         uint32_t cword;
218         uint32_t slice_bytes;   //number of bytes that have legal slice values including RLE
219         //Only process legal data values for this mode which are 0x32-0x7F for RLE and 0x80 to 0xFF for data
220         for (slice_bytes = 1; (slice_bytes < devc->bytes_avail)
221              && (devc->buffer[slice_bytes - 1] >= 0x30); slice_bytes++);
222         if (slice_bytes != devc->bytes_avail) {
223                 cbyte = devc->buffer[slice_bytes - 1];
224                 slice_bytes--;  //Don't process the ending character
225                 if (cbyte == '$') {
226                         sr_info
227                             ("Data stream stops with cbyte %d char %c rdidx %d sbytes %d cnt %llu",
228                              cbyte, cbyte, devc->ser_rdptr, slice_bytes,
229                              devc->byte_cnt);
230                         devc->rxstate = RX_STOPPED;
231                 } else {
232                         sr_err
233                             ("Data stream aborts with cbyte %d char %c rdidx %d sbytes %d cnt %llu",
234                              cbyte, cbyte, devc->ser_rdptr, slice_bytes,
235                              devc->byte_cnt);
236                         devc->rxstate = RX_ABORT;
237                 }
238         }
239         //If the wrptr is non-zero due to a residual from the previous serial transfer don't double count it towards byte_cnt
240         devc->byte_cnt += slice_bytes - (devc->wrptr);
241         sr_spew("process slice avail %d rdptr %d sb %d byte_cnt %" PRIu64 "",
242                 devc->bytes_avail, devc->ser_rdptr, slice_bytes,
243                 devc->byte_cnt);
244         //Must have a full slice or one rle byte
245         while (((devc->ser_rdptr + devc->bytes_per_slice) <= slice_bytes) 
246                ||((devc->ser_rdptr  < slice_bytes)&&(devc->buffer[devc->ser_rdptr] < 0x80))) { 
247
248           if(devc->buffer[devc->ser_rdptr] < 0x80){
249              int16_t rlecnt;
250              if(devc->buffer[devc->ser_rdptr]<=79){
251                 rlecnt=devc->buffer[devc->ser_rdptr]-47;
252              }else{ 
253                rlecnt=(devc->buffer[devc->ser_rdptr]-78)*32;
254              }
255              sr_info("RLEcnt of %d in %d",rlecnt,devc->buffer[devc->ser_rdptr]);
256              if((rlecnt < 1)||(rlecnt>1568)){
257                 sr_err("Bad rlecnt val %d in %d",rlecnt,devc->buffer[devc->ser_rdptr]);
258              }else{
259                 rle_memset(devc,rlecnt);
260              }
261              devc->ser_rdptr++;
262
263           }else{
264                 cword = 0;
265                 //build up a word 7 bits at a time, using only enabled channels
266                 for (i = 0; i < devc->num_d_channels; i += 7) {
267                         if (((devc->d_chan_mask) >> i) & 0x7F) {
268                                 cword |=
269                                     ((devc->buffer[devc->ser_rdptr]) &
270                                      0x7F) << i;
271                                 (devc->ser_rdptr)++;
272                         }
273                 }
274                 //and then distribute 8 bits at a time to all possible channels
275                 //but first save of cword for rle
276                 devc->d_last[0]=cword&0xFF;
277                 devc->d_last[1]=(cword>>8)&0xFF;
278                 devc->d_last[2]=(cword>>16)&0xFF;
279                 devc->d_last[3]=(cword>>24)&0xFF;
280                 for (i = 0; i < devc->num_d_channels; i += 8) {
281                         uint32_t idx =
282                             ((devc->cbuf_wrptr) * devc->dig_sample_bytes) +
283                             (i >> 3);
284                         devc->d_data_buf[idx] = cword & 0xFF;
285                         sr_spew
286                             ("Dchan i %d wrptr %d idx %d char 0x%X cword 0x%X",
287                              i, devc->cbuf_wrptr, idx,
288                              devc->d_data_buf[idx], cword);
289                         cword >>= 8;
290                 }
291
292                 //Each analog value is a 7 bit value
293                 for (i = 0; i < devc->num_a_channels; i++) {
294                         if ((devc->a_chan_mask >> i) & 1) {
295                                 //a_size is depracted and must always be 1B
296                                 tmp32 =
297                                     devc->buffer[devc->ser_rdptr] - 0x80;
298                                 devc->a_data_bufs[i][devc->cbuf_wrptr] =
299                                     ((float) tmp32 * devc->a_scale[i]) +
300                                     devc->a_offset[i];
301                                 devc->a_last[i] =
302                                     devc->a_data_bufs[i][devc->cbuf_wrptr];
303                                 sr_spew
304                                     ("AChan %d t32 %d value %f wrptr %d rdptr %d sc %f off %f",
305                                      i, tmp32,
306                                      devc->
307                                      a_data_bufs[i][devc->cbuf_wrptr],
308                                      devc->cbuf_wrptr, devc->ser_rdptr,
309                                      devc->a_scale[i], devc->a_offset[i]);
310                                 devc->ser_rdptr++;
311                         }       //if channel enabled
312                 }               //for num_a_channels
313                 devc->cbuf_wrptr++;
314            }//Not an RLE
315            //RLEs can create a large number of samples relative to the incoming serial buffer
316            //To prevent overflow of the sample data buffer we call process_group.
317            //cbuf_wrptr and sample_buf_size are both in terms of slices
318            //2048 is more than needed for a max rle of 1640 on the next incoming character
319            if((devc->cbuf_wrptr +2048) >  devc->sample_buf_size){
320               sr_spew("Drain large buff %d %d\n\r",devc->cbuf_wrptr,devc->sample_buf_size);
321               process_group(sdi, devc, devc->cbuf_wrptr);
322
323            }
324         }//While another slice or RLE available
325         if (devc->cbuf_wrptr){
326                 process_group(sdi, devc, devc->cbuf_wrptr);
327         }
328
329 }
330
331 //Send the processed analog values to the session
332 int send_analog(struct sr_dev_inst *sdi, struct dev_context *devc,
333                 uint32_t num_samples, uint32_t offset)
334 {
335         struct sr_datafeed_packet packet;
336         struct sr_datafeed_analog analog;
337         struct sr_analog_encoding encoding;
338         struct sr_analog_meaning meaning;
339         struct sr_analog_spec spec;
340         struct sr_channel *ch;
341         uint32_t i;
342         float *fptr;
343
344         sr_analog_init(&analog, &encoding, &meaning, &spec, ANALOG_DIGITS);
345         for (i = 0; i < devc->num_a_channels; i++) {
346                 if ((devc->a_chan_mask >> i) & 1) {
347                         ch = devc->analog_groups[i]->channels->data;
348                         analog.meaning->channels =
349                             g_slist_append(NULL, ch);
350                         analog.num_samples = num_samples;
351                         analog.data = (devc->a_data_bufs[i]) + offset;
352                         fptr = analog.data;
353                         sr_spew
354                             ("send analog num %d offset %d first %f 2 %f",
355                              num_samples, offset, *(devc->a_data_bufs[i]),
356                              *fptr);
357                         analog.meaning->mq = SR_MQ_VOLTAGE;
358                         analog.meaning->unit = SR_UNIT_VOLT;
359                         analog.meaning->mqflags = 0;
360                         packet.type = SR_DF_ANALOG;
361                         packet.payload = &analog;
362                         sr_session_send(sdi, &packet);
363                         g_slist_free(analog.meaning->channels);
364                 }//if enabled
365         }//for channels
366         return 0;
367
368 }
369
370 //Send the ring buffer of pre-trigger analog samples.
371 //  The entire buffer is sent (as long as it filled once), but need send two payloads split at the 
372 //  the writeptr 
373 int send_analog_ring(struct sr_dev_inst *sdi, struct dev_context *devc,
374                      uint32_t num_samples)
375 {
376         struct sr_datafeed_packet packet;
377         struct sr_datafeed_analog analog;
378         struct sr_analog_encoding encoding;
379         struct sr_analog_meaning meaning;
380         struct sr_analog_spec spec;
381         struct sr_channel *ch;
382         int i;
383         uint32_t num_pre, start_pre;
384         uint32_t num_post, start_post;
385         num_pre =
386             (num_samples >=
387              devc->pretrig_wr_ptr) ? devc->pretrig_wr_ptr : num_samples;
388         start_pre = devc->pretrig_wr_ptr - num_pre;
389         num_post = num_samples - num_pre;
390         start_post = devc->pretrig_entries - num_post;
391         sr_spew
392             ("send_analog ring wrptr %u ns %d npre %u spre %u npost %u spost %u",
393              devc->pretrig_wr_ptr, num_samples, num_pre, start_pre,
394              num_post, start_post);
395         float *fptr;
396         sr_analog_init(&analog, &encoding, &meaning, &spec, ANALOG_DIGITS);
397         for (i = 0; i < devc->num_a_channels; i++) {
398                 if ((devc->a_chan_mask >> i) & 1) {
399                         ch = devc->analog_groups[i]->channels->data;
400                         analog.meaning->channels =
401                             g_slist_append(NULL, ch);
402                         analog.meaning->mq = SR_MQ_VOLTAGE;
403                         analog.meaning->unit = SR_UNIT_VOLT;
404                         analog.meaning->mqflags = 0;
405                         packet.type = SR_DF_ANALOG;
406                         packet.payload = &analog;
407                         //First send what is after the write pointer because it is oldest
408                         if (num_post) {
409                                 analog.num_samples = num_post;
410                                 analog.data =
411                                     (devc->a_pretrig_bufs[i]) + start_post;
412                                 for (uint32_t j = 0;
413                                      j < analog.num_samples; j++) {
414                                         fptr =
415                                             analog.data +
416                                             (j * sizeof(float));
417                                 }
418                                 sr_session_send(sdi, &packet);
419                         }
420                         if (num_pre) {
421                                 analog.num_samples = num_pre;
422                                 analog.data =
423                                     (devc->a_pretrig_bufs[i]) + start_pre;
424                                 sr_dbg("Sending A%d ring buffer newest ",
425                                        i);
426                                 for (uint32_t j = 0;
427                                      j < analog.num_samples; j++) {
428                                         fptr =
429                                             analog.data +
430                                             (j * sizeof(float));
431                                         sr_spew("RNGDCW%d j %d %f %p", i,
432                                                 j, *fptr, (void *) fptr);
433                                 }
434                                 sr_session_send(sdi, &packet);
435                         }
436                         g_slist_free(analog.meaning->channels);
437                         sr_dbg("Sending A%d ring buffer done ", i);
438                 }//if enabled
439         }//for channels
440         return 0;
441
442 }
443
444 //Given a chunk of slices forward to trigger check or session as appropriate and update state
445 //these could be real slices or those generated by rles
446 int process_group(struct sr_dev_inst *sdi, struct dev_context *devc,
447                   uint32_t num_slices)
448 {
449         int trigger_offset;
450         int pre_trigger_samples;
451         //These are samples sent to session and are less than num_slices if we reach limit_samples
452         size_t num_samples;
453         struct sr_datafeed_logic logic;
454         struct sr_datafeed_packet packet;
455         int i;
456         size_t cbuf_wrptr_cpy;
457         cbuf_wrptr_cpy = devc->cbuf_wrptr;
458         //regardless of whether we forward samples on or not (because we aren't triggered), always reset the 
459         //pointer into the device data buffers 
460         devc->cbuf_wrptr = 0;
461         if (devc->trigger_fired) {      //send directly to session
462                 if (devc->limit_samples &&
463                     num_slices >
464                     devc->limit_samples - devc->sent_samples) {
465                         num_samples =
466                             devc->limit_samples - devc->sent_samples;
467                 } else {
468                         num_samples = num_slices;
469                 }
470                 if (num_samples > 0) {
471                         sr_spew
472                             ("Process_group sending %d post trig samples dsb %d",
473                              num_samples, devc->dig_sample_bytes);
474                         if (devc->num_d_channels) {
475                                 packet.type = SR_DF_LOGIC;
476                                 packet.payload = &logic;
477                                 //Size the number of bytes required to fit all of the channels
478                                 logic.unitsize = devc->dig_sample_bytes;
479                                 //The total length of the array sent
480                                 logic.length =
481                                     num_samples * logic.unitsize;
482                                 logic.data = devc->d_data_buf;
483                                 sr_session_send(sdi, &packet);
484                         }
485                         send_analog(sdi, devc, num_samples, 0);
486                 }//num_samples >0
487                 devc->sent_samples += num_samples;
488                 return 0;
489         }//trigger_fired
490         else {
491                 size_t num_ring_samples;
492                 size_t sptr;
493                 size_t eptr;
494                 size_t numtail;
495                 size_t numwrap;
496                 size_t srcptr;
497                 //The trigger_offset is -1 if no trigger is found, but if a trigger is found
498                 //then trigger_offset is the offset into the data buffer sent to it.
499                 //The pre_trigger_samples is the total number of samples before the trigger, but limited to
500                 //the size of the ring buffer set by the capture_ratio. So the pre_trigger_samples can include both the new samples
501                 //and the ring buffer, but trigger_offset is only in relation to the new samples
502                 trigger_offset = soft_trigger_logic_check(devc->stl,
503                                                           devc->d_data_buf,
504                                                           num_slices *
505                                                           devc->dig_sample_bytes,
506                                                           &pre_trigger_samples);
507                 //A trigger offset >=0 indicates a trigger was seen.  The stl will isue the trigger to the session
508                 //and will forward all pre trigger logic samples, but we must send any post trigger logic 
509                 //and all pre and post trigger analog signals
510                 if (trigger_offset > -1) {
511                         devc->trigger_fired = TRUE;
512                         devc->sent_samples += pre_trigger_samples;
513                         packet.type = SR_DF_LOGIC;
514                         packet.payload = &logic;
515                         num_samples = num_slices - trigger_offset;
516 //Since we are in continuous mode for SW triggers it is possible to get more samples than limit_samples, so
517 //once the trigger fires make sure we don't get beyond limit samples. At this point sent_samples should
518 //be equal to pre_trigger_samples (just added above) because without being triggered we'd never increment
519 //sent_samples.
520 //This number is the number of post trigger logic samples to send to the session, the number of floats
521 //is larger because of the analog ring buffer we track.
522                         if (devc->limit_samples &&
523                             num_samples >
524                             devc->limit_samples - devc->sent_samples)
525                                 num_samples =
526                                     devc->limit_samples -
527                                     devc->sent_samples;
528                         //The soft trigger logic issues the trigger and sends packest for all logic data that was pretrigger
529                         //so only send what is left
530                         if (num_samples > 0) {
531                                 sr_dbg
532                                     ("Sending post trigger logical remainder of %d",
533                                      num_samples);
534                                 logic.length =
535                                     num_samples * devc->dig_sample_bytes;
536                                 logic.unitsize = devc->dig_sample_bytes;
537                                 logic.data =
538                                     devc->d_data_buf +
539                                     (trigger_offset *
540                                      devc->dig_sample_bytes);
541                                 devc->sent_samples += num_samples;
542                                 sr_session_send(sdi, &packet);
543                         }
544                         size_t new_start, new_end, new_samples,
545                             ring_samples;
546                         //Figure out the analog data to send.
547                         //We might need to send:
548                         //-some or all of incoming data
549                         //-all of incoming data and some of ring buffer
550                         //-all of incoming data and all of ring buffer (and still might be short)
551                         //We don't need to compare to limit_samples because pretrig_entries can never be more than limit_samples
552                         //trigger offset indicatese where in the new samples the trigger was, but we need to go back pretrig_entries before it             
553                         new_start =
554                             (trigger_offset >
555                              (int) devc->pretrig_entries) ? trigger_offset
556                             - devc->pretrig_entries : 0;
557                         //Note that we might not have gotten all the pre triggerstore data we were looking for. In such a case the sw trigger
558                         //logic seems to fill up to the limit_samples and thus the ratio is off, but we get the full number of samples
559                         //The number of entries in the ring buffer is pre_trigger_samples-trigger_offset so subtract that from limit samples
560                         //as a threshold
561                         new_end =
562                             MIN(num_slices - 1,
563                                 devc->limit_samples -
564                                 (pre_trigger_samples - trigger_offset) -
565                                 1);
566                         //This includes pre and post trigger storage.
567                         new_samples = new_end - new_start + 1;
568                         //pre_trigger_samples can never be greater than trigger_offset by more than the ring buffer depth (pretrig entries) 
569                         ring_samples =
570                             (pre_trigger_samples >
571                              trigger_offset) ? pre_trigger_samples -
572                             trigger_offset : 0;
573                         sr_spew
574                             ("SW trigger float info newstart %zu new_end %zu new_samp %zu ring_samp %zu",
575                              new_start, new_end, new_samples,
576                              ring_samples);
577                         if (ring_samples > 0) {
578                                 send_analog_ring(sdi, devc, ring_samples);
579                         }
580                         if (new_samples) {
581                                 send_analog(sdi, devc, new_samples,
582                                             new_start);
583                         }
584
585                 }               //if trigger_offset 
586                 else {          //We didn't trigger but need to copy to ring buffer
587                         if ((devc->a_chan_mask) && (devc->pretrig_entries)) {
588                                 //The incoming data buffer could be much larger than the ring buffer, so never copy more than 
589                                 //the size of the ring buffer
590                                 num_ring_samples =
591                                     num_slices >
592                                     devc->
593                                     pretrig_entries ? devc->pretrig_entries
594                                     : num_slices;
595                                 sptr = devc->pretrig_wr_ptr;    //starting pointer to copy to
596                                 //endptr can't go past the end
597                                 eptr =
598                                     (sptr + num_ring_samples) >=
599                                     devc->
600                                     pretrig_entries ? devc->pretrig_entries
601                                     - 1 : sptr + num_ring_samples - 1;
602                                 numtail = (eptr - sptr) + 1;    //number of samples to copy to the tail of ring buffer without wrapping
603                                 numwrap =
604                                     (num_ring_samples >
605                                      numtail) ? num_ring_samples -
606                                     numtail : 0;
607                                 //cbuf_wrptr points to where the next write should go, not  theactual write data
608                                 srcptr = cbuf_wrptr_cpy - num_ring_samples;
609                                 sr_spew("RNG num %zu sptr %zu eptr %zu ",
610                                         num_ring_samples, sptr, eptr);
611                                 for (i = 0; i < devc->num_a_channels; i++) {
612                                         if ((devc->a_chan_mask >> i) & 1) {
613                                                 //copy tail
614                                                 for (uint32_t j = 0;
615                                                      j < numtail; j++) {
616                                                         devc->a_pretrig_bufs
617                                                             [i][sptr + j] =
618                                                             devc->a_data_bufs
619                                                             [i]
620                                                             [srcptr + j];
621                                                 }       //for j
622                                         }       //if chan_mask
623                                 }       //for channels
624                                 //Copy wrap
625                                 srcptr += numtail;
626                                 for (i = 0; i < devc->num_a_channels; i++) {
627                                         if ((devc->a_chan_mask >> i) & 1) {
628                                                 for (uint32_t j = 0;
629                                                      j < numwrap; j++) {
630                                                         devc->a_pretrig_bufs
631                                                             [i][j] =
632                                                             devc->a_data_bufs
633                                                             [i]
634                                                             [srcptr + j];
635                                                 }       //for j
636                                         }       //if chan_mask
637                                 }       //for channels
638                                 devc->pretrig_wr_ptr =
639                                     (numwrap) ? numwrap : (eptr +
640                                                            1) %
641                                     devc->pretrig_entries;
642                         }       //if any analog channel enabled and pretrig_entries
643                 }               //else (trigger not detected)
644         }                       //trigger not set on function entry
645         return 0;
646 }                               //process_group
647
648
649 //Duplicate previous sample values
650 //This function relies on the caller to ensure d_data_buf has samples to handle the full value of the rle
651 void rle_memset(struct dev_context *devc, uint32_t num_slices)
652 {
653         uint32_t j, k,didx;
654         sr_spew("rle_memset vals 0x%X, 0x%X, 0x%X slices %d dsb %d\n", devc->d_last[0],devc->d_last[1],devc->d_last[2],
655                 num_slices, devc->dig_sample_bytes);
656         //Even if a channel is disabled, PV expects the same location and size for the enabled
657         // channels as if the channel were enabled.
658         for (j = 0; j < num_slices; j++) {
659                 didx=devc->cbuf_wrptr*devc->dig_sample_bytes;
660                 for (k = 0; k < devc->dig_sample_bytes; k++) {
661                         devc->d_data_buf[didx + k] =  devc->d_last[k];
662                 }
663                 // cbuf_wrptr always counts slices/samples (and not the bytes in the buffer)
664                 // regardless of mode
665                 devc->cbuf_wrptr++;
666         }
667         
668 }
669
670 //This callback function is mapped from api.c with serial_source_add and is created after a capture
671 //has been setup and is responsible for querying the device trigger status, downloading data
672 //and forwarding packets
673 SR_PRIV int raspberrypi_pico_receive(int fd, int revents, void *cb_data)
674 {
675         struct sr_dev_inst *sdi;
676         struct dev_context *devc;
677         struct sr_serial_dev_inst *serial;
678         uint32_t i;
679         int len;
680         uint32_t bytes_rem;
681         uint32_t residual_bytes;
682         (void) fd;
683
684         if (!(sdi = cb_data))
685                 return TRUE;
686
687         if (!(devc = sdi->priv))
688                 return TRUE;
689         if (devc->rxstate != RX_ACTIVE) {
690                 //This condition is normal operation and expected to happen 
691                 //but printed as information
692                 sr_dbg("Reached non active state in receive %d",
693                        devc->rxstate);
694                 //don't return - we may be waiting for a final bytecnt
695         }
696         if (devc->rxstate == RX_IDLE) {
697                 //This is the normal end condition where we do one more receive
698                 //to make sure we get the full byte_cnt
699                 sr_dbg("Reached idle state in receive %d", devc->rxstate);
700                 return FALSE;
701         }
702
703         serial = sdi->conn;
704         //return true if it is some kind of event we don't handle
705         if (!(revents == G_IO_IN || revents == 0))
706                 return TRUE;
707         //Fill the buffer, note the end may have partial slices
708         bytes_rem = devc->serial_buffer_size - devc->wrptr;
709         //Read one byte less so that we can null it and print as a string
710         //Do a small 10ms timeout, if we get nothing, we'll always come back again
711         len =
712             serial_read_blocking(serial, &(devc->buffer[devc->wrptr]),
713                                  bytes_rem - 1, 10);
714         sr_spew("Entry wrptr %u bytes_rem %u len %d", devc->wrptr,
715                 bytes_rem, len);
716
717         if (len > 0) {
718                 devc->buffer[devc->wrptr + len] = 0;
719                 //Add the "#" so that spaces are clearly seen
720                 sr_dbg("rx string %s#", devc->buffer);
721                 devc->bytes_avail = (devc->wrptr + len);
722                 sr_spew
723                     ("rx len %d bytes_avail %ul sent_samples %ul wrptr %u",
724                      len, devc->bytes_avail, devc->sent_samples,
725                      devc->wrptr);
726         } else if (len == 0) {
727                 return TRUE;
728         } else {
729                 sr_err("ERROR:Negative serial read code %d", len);
730                 sdi->driver->dev_acquisition_stop(sdi);
731                 return FALSE;
732         }// if len>0
733
734         //Process the serial read data
735         devc->ser_rdptr = 0;
736         if (devc->rxstate == RX_ACTIVE) {
737                 if ((devc->a_chan_mask == 0)
738                     && ((devc->d_chan_mask & 0xFFFFFFF0) == 0)) {
739                         process_D4(sdi, devc);
740                 } else {
741                         process_slice(sdi, devc);
742                 }
743         }
744         //process_slice/process_D4 increment ser_rdptr as bytes of the serial buffer are used
745         //But they may not use all of it, and thus the residual unused bytes are shifted to the start of the buffer
746         //for the next call.
747         residual_bytes = devc->bytes_avail - devc->ser_rdptr;
748         if (residual_bytes) {
749                 for (i = 0; i < residual_bytes; i++) {
750                         devc->buffer[i] =
751                             devc->buffer[i + devc->ser_rdptr];
752                 }
753                 devc->ser_rdptr = 0;
754                 devc->wrptr = residual_bytes;
755                 sr_spew("Residual shift rdptr %u wrptr %u",
756                         devc->ser_rdptr, devc->wrptr);
757         } else {
758                 //If there are no residuals shifted then zero the wrptr since all data is used
759                 devc->wrptr = 0;
760         }
761         //ABORT ends immediately
762         if (devc->rxstate == RX_ABORT) {
763                 sr_err("Ending receive on abort");
764                 sdi->driver->dev_acquisition_stop(sdi);
765                 return FALSE;   //
766         }
767         //if stopped look for final '+' indicating the full byte_cnt is received
768         if (devc->rxstate == RX_STOPPED) {
769                 sr_dbg("Stopped, checking byte_cnt");
770                 if (devc->buffer[0] != '$') {
771                         //If this happens it means that we got a set of data that was not processed as
772                         //whole groups of slice bytes. So either we lost data or are not parsing it correctly.
773                         sr_err("ERROR: Stop marker should be byte zero");
774                         devc->rxstate = RX_ABORT;
775                         sdi->driver->dev_acquisition_stop(sdi);
776                         return FALSE;
777                 }
778                 for (i = 1; i < devc->wrptr; i++) {
779                         if (devc->buffer[i] == '+') {
780                                 devc->buffer[i] = 0;
781                                 uint64_t rxbytecnt;
782                                 rxbytecnt = atol((char *)&(devc->buffer[1]));
783                                 sr_dbg
784                                     ("Byte_cnt check device cnt %llu host cnt %llu",
785                                      rxbytecnt, devc->byte_cnt);
786                                 if (rxbytecnt != devc->byte_cnt) {
787                                         sr_err
788                                             ("ERROR: received %llu and counted %llu bytecnts don't match, data may be lost",
789                                              rxbytecnt, devc->byte_cnt);
790                                 }
791                                 //Since we got the bytecnt we know the device is done sending data
792                                 devc->rxstate = RX_IDLE;
793                                 //We must always call acquisition_stop on all completed runs
794                                 sdi->driver->dev_acquisition_stop(sdi);
795                                 return TRUE;
796                         }
797                 }
798                 //It's possible we need one more serial transfer to get the byte_cnt, so print that here
799                 sr_dbg("Haven't seen byte_cnt + yet");
800         } //if RX_STOPPED
801         //If at the sample limit, send a "+" in case we are in continuous mode and need
802         //to stop the device.  Not that even in non continous mode there might be cases where get an extra
803         //sample or two...
804
805         if ((devc->sent_samples >= devc->limit_samples)
806             && (devc->rxstate == RX_ACTIVE)) {
807                 sr_dbg
808                     ("Ending: sent %u of limit %llu samples byte_cnt %llu",
809                      devc->sent_samples, devc->limit_samples,
810                      devc->byte_cnt);
811                 send_serial_char(serial, '+');
812
813         }
814         sr_spew
815             ("Receive function done: sent %u limit %llu wrptr %u len %d",
816              devc->sent_samples, devc->limit_samples, devc->wrptr, len);
817         return TRUE;
818 }                               //raspberrypi_pico_receive
819
820 //Read device specific information from the device
821 SR_PRIV int raspberrypi_pico_get_dev_cfg(const struct sr_dev_inst *sdi)
822 {
823         struct dev_context *devc;
824         struct sr_serial_dev_inst *serial;
825         char *cmd, response[20];
826         gchar **tokens;
827         unsigned int i;
828         int ret, num_tokens;
829
830         devc = sdi->priv;
831         sr_dbg("At get_dev_cfg");
832         serial = sdi->conn;
833         for (i = 0; i < devc->num_a_channels; i++) {
834                 cmd = g_strdup_printf("a%d\n", i);
835                 ret = send_serial_w_resp(serial, cmd, response, 20);
836                 if (ret <= 0) {
837                         sr_err
838                             ("ERROR:No response from device for analog channel query");
839                         return SR_ERR;
840                 }
841                 //null end of string for strsplit
842                 response[ret] = 0;
843                 tokens = NULL;
844                 tokens = g_strsplit(response, "x", 0);
845                 num_tokens = g_strv_length(tokens);
846                 if (num_tokens == 2) {
847                         devc->a_scale[i] =
848                             ((float) atoi(tokens[0])) / 1000000.0;
849                         devc->a_offset[i] =
850                             ((float) atoi(tokens[1])) / 1000000.0;
851                         sr_dbg
852                             ("A%d scale %f offset %f response #%s# tokens #%s# #%s#\n",
853                              i, devc->a_scale[i], devc->a_offset[i],
854                              response, tokens[0], tokens[1]);
855                 } else {
856                         sr_err
857                             ("ERROR:Ascale read c%d got unparseable response %s tokens %d",
858                              i, response, num_tokens);
859                         //force a legal fixed value assuming a 3.3V scale
860                         //a failue in parsing the scale
861                         devc->a_scale[i] = 0.0257;
862                         devc->a_offset[i] = 0.0;
863                 }
864                 g_strfreev(tokens);
865                 g_free(cmd);
866         }
867
868
869         return SR_OK;
870
871 }