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