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