]> sigrok.org Git - libsigrok.git/blame - src/hardware/raspberrypi-pico/api.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / src / hardware / raspberrypi-pico / api.c
CommitLineData
dc90146e
A
1/*
2 * This file is part of the libsigrok project.
3 *
bac2a8b8 4 * Copyright (C) 2022 Shawn Walker <ac0bi00@gmail.com>
dc90146e
A
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 */
dc90146e 19#include <config.h>
bac2a8b8
A
20#include <fcntl.h>
21#include <glib.h>
22#include <math.h>
23#include <stdlib.h>
24#include <string.h>
25#include <strings.h>
26#include <unistd.h>
27#include <libsigrok/libsigrok.h>
28#include "libsigrok-internal.h"
dc90146e
A
29#include "protocol.h"
30
c5776ef7
SA
31/* Baud rate is really a don't care because we run USB CDC, dtr must be 1.
32 * flow should be zero since we don't use xon/xoff */
ae54069c 33#define SERIALCOMM "115200/8n1/dtr=1/rts=0/flow=0"
c5776ef7
SA
34
35/* Use the force_detect scan option as a way to pass user information to the
36 * device the string must use only 0-9,a-z,A-Z,'.','=' and '-'* and be less than
37 * 60 characters */
dc90146e 38
bac2a8b8 39static const uint32_t scanopts[] = {
c5776ef7
SA
40 SR_CONF_CONN, /* Required OS name for the port, i.e. /dev/ttyACM0 */
41 SR_CONF_SERIALCOMM, /* Optional config of the port, i.e. 115200/8n1 */
42 SR_CONF_FORCE_DETECT
bac2a8b8 43};
c5776ef7
SA
44
45/* Sample rate can either provide a std_gvar_samplerates_steps or a
46 * std_gvar_samplerates. The latter is just a long list of every supported rate.
47 * For the steps, pulseview/pv/toolbars/mainbar.cpp will do a min,max,step. If
48 * step is 1 then it provides a 1,2,5,10 select otherwise it allows a spin box.
49 * Going with the full list because while the spin box is more flexible, it is
50 * harder to read */
0c792900
A
51static const uint64_t samplerates[] = {
52 SR_KHZ(5),
53 SR_KHZ(6),
54 SR_KHZ(8),
55 SR_KHZ(10),
56 SR_KHZ(20),
57 SR_KHZ(30),
58 SR_KHZ(40),
59 SR_KHZ(50),
60 SR_KHZ(60),
61 SR_KHZ(80),
62 SR_KHZ(100),
63 SR_KHZ(125),
64 SR_KHZ(150),
c5776ef7 65 SR_KHZ(160), /* max rate of 3 ADC chans that has integer divisor/dividend */
0c792900 66 SR_KHZ(200),
c5776ef7 67 SR_KHZ(250), /* max rate of 2 ADC chans */
0c792900
A
68 SR_KHZ(300),
69 SR_KHZ(400),
70 SR_KHZ(500),
71 SR_KHZ(600),
72 SR_KHZ(800),
c5776ef7
SA
73 /* Give finer granularity near the thresholds of RLE effectiveness ~1-4Msps
74 * Also use 1.2 and 2.4 as likely max values for ADC overclocking */
0c792900 75 SR_MHZ(1),
b9890a32 76 SR_MHZ(1.2),
0c792900
A
77 SR_MHZ(1.5),
78 SR_MHZ(2),
b9890a32 79 SR_MHZ(2.4),
0c792900
A
80 SR_MHZ(3),
81 SR_MHZ(4),
82 SR_MHZ(5),
83 SR_MHZ(6),
84 SR_MHZ(8),
85 SR_MHZ(10),
86 SR_MHZ(15),
87 SR_MHZ(20),
88 SR_MHZ(30),
89 SR_MHZ(40),
90 SR_MHZ(60),
c5776ef7
SA
91 /* The baseline 120Mhz PICO clock won't support an 80 or 100
92 * with non fractional divisor, but an overclocked version or one
93 * that modified sysclk could */
b9890a32 94 SR_MHZ(80),
c5776ef7
SA
95 SR_MHZ(100),
96 SR_MHZ(120),
97 /* These may not be practically useful, but someone might want to
98 * try to make it work with overclocking */
99 SR_MHZ(150),
100 SR_MHZ(200),
101 SR_MHZ(240),
0c792900 102};
dc90146e 103
bac2a8b8 104static const uint32_t drvopts[] = {
ac132f83
A
105 SR_CONF_OSCILLOSCOPE,
106 SR_CONF_LOGIC_ANALYZER,
bac2a8b8 107};
ac132f83 108
bac2a8b8 109static const int32_t trigger_matches[] = {
ac132f83
A
110 SR_TRIGGER_ZERO,
111 SR_TRIGGER_ONE,
112 SR_TRIGGER_RISING,
113 SR_TRIGGER_FALLING,
114 SR_TRIGGER_EDGE,
bac2a8b8 115};
dc90146e 116
dc90146e 117
bac2a8b8 118static const uint32_t devopts[] = {
ac132f83
A
119 SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
120 SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
121 SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
ac132f83 122 SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
bac2a8b8 123};
dc90146e 124
bac2a8b8 125static struct sr_dev_driver raspberrypi_pico_driver_info;
dc90146e 126
dc90146e 127
ac132f83 128static GSList *scan(struct sr_dev_driver *di, GSList * options)
dc90146e 129{
ac132f83
A
130 struct sr_config *src;
131 struct sr_dev_inst *sdi;
132 struct sr_serial_dev_inst *serial;
133 struct dev_context *devc;
134 struct sr_channel *ch;
135 GSList *l;
136 int num_read;
dbf599ec 137 int i;
c5776ef7 138 const char *conn, *serialcomm, *force_detect;
ac132f83 139 char buf[32];
dbf599ec 140 char ustr[64];
ac132f83
A
141 int len;
142 uint8_t num_a, num_d, a_size;
143 gchar *channel_name;
144
dbf599ec 145 conn = serialcomm = force_detect = NULL;
ac132f83
A
146 for (l = options; l; l = l->next) {
147 src = l->data;
148 switch (src->key) {
149 case SR_CONF_CONN:
150 conn = g_variant_get_string(src->data, NULL);
151 break;
152 case SR_CONF_SERIALCOMM:
153 serialcomm = g_variant_get_string(src->data, NULL);
154 break;
dbf599ec
A
155 case SR_CONF_FORCE_DETECT:
156 force_detect = g_variant_get_string(src->data, NULL);
c5776ef7 157 sr_info("Force detect string %s", force_detect);
dbf599ec 158 break;
ac132f83
A
159 }
160 }
161 if (!conn)
162 return NULL;
163
164 if (!serialcomm)
165 serialcomm = SERIALCOMM;
166
167 serial = sr_serial_dev_inst_new(conn, serialcomm);
168 sr_info("Opening %s.", conn);
169 if (serial_open(serial, SERIAL_RDWR) != SR_OK) {
170 sr_err("1st serial open fail");
171 return NULL;
172 }
173
ae54069c 174 sr_info("Resetting device with *s at %s.", conn);
ac132f83
A
175 send_serial_char(serial, '*');
176 g_usleep(10000);
ac132f83
A
177 do {
178 sr_warn("Drain reads");
179 len = serial_read_blocking(serial, buf, 32, 100);
180 sr_warn("Drain reads done");
181 if (len)
182 sr_dbg("Dropping in flight serial data");
183 } while (len > 0);
c5776ef7
SA
184 /* Send the user string with the identify */
185 if (force_detect && (strlen(force_detect) <= 60)) {
186 sprintf(ustr,"i%s\n", force_detect);
187 sr_info("User string %s", ustr);
188 num_read = send_serial_w_resp(serial, ustr, buf, 17);
189 } else {
190 num_read = send_serial_w_resp(serial, "i\n", buf, 17);
191 }
ac132f83
A
192 if (num_read < 16) {
193 sr_err("1st identify failed");
194 serial_close(serial);
195 g_usleep(100000);
196 if (serial_open(serial, SERIAL_RDWR) != SR_OK) {
b9890a32 197 sr_err("2nd serial open fail");
ac132f83
A
198 return NULL;
199 }
200 g_usleep(100000);
201 sr_err("Send second *");
202 send_serial_char(serial, '*');
203 g_usleep(100000);
204 num_read = send_serial_w_resp(serial, "i\n", buf, 17);
205 if (num_read < 10) {
206 sr_err("Second attempt failed");
207 return NULL;
208 }
209 }
c5776ef7
SA
210
211 /* Expected ID response is SRPICO,AxxyDzz,VV
212 * where xx are number of analog channels, y is bytes per analog sample
213 * (7 bits per byte), zz is number of digital channels, and VV is two digit
214 * version# which must be 02 */
215 if ((num_read < 16) || (strncmp(buf, "SRPICO,A", 8)) \
216 || (buf[11] != 'D') || (buf[15] != '0') || (buf[16] != '2')) {
217 sr_err("ERROR: Bad response string %s %d", buf, num_read);
ac132f83
A
218 return NULL;
219 }
c5776ef7 220
ac132f83 221 a_size = buf[10] - '0';
dbf599ec
A
222 buf[10] = '\0'; /*Null to end the str for atois */
223 buf[14] = '\0';
ac132f83
A
224 num_a = atoi(&buf[8]);
225 num_d = atoi(&buf[12]);
226
227 sdi = g_malloc0(sizeof(struct sr_dev_inst));
228 sdi->status = SR_ST_INACTIVE;
229 sdi->vendor = g_strdup("Raspberry Pi");
230 sdi->model = g_strdup("PICO");
231 sdi->version = g_strdup("00");
232 sdi->conn = serial;
233 sdi->driver = &raspberrypi_pico_driver_info;
234 sdi->inst_type = SR_INST_SERIAL;
235 sdi->serial_num = g_strdup("N/A");
c5776ef7
SA
236
237 if (((num_a == 0) && (num_d == 0)) \
238 || (num_a > MAX_ANALOG_CHANNELS) || (num_d > MAX_DIGITAL_CHANNELS)
239 || (a_size < 1) || (a_size > 4)) {
ac132f83 240 sr_err("ERROR: invalid channel config a %d d %d asz %d",
c5776ef7 241 num_a, num_d, a_size);
ac132f83
A
242 return NULL;
243 }
c5776ef7 244
ac132f83
A
245 devc = g_malloc0(sizeof(struct dev_context));
246 devc->a_size = a_size;
ac132f83
A
247 devc->num_a_channels = num_a;
248 devc->num_d_channels = num_d;
249 devc->a_chan_mask = ((1 << num_a) - 1);
250 devc->d_chan_mask = ((1 << num_d) - 1);
c5776ef7
SA
251
252 /* The number of bytes that each digital sample in the buffers sent to the
253 * session. All logical channels are packed together, where a slice of N
254 * channels takes roundup(N/8) bytes. This never changes even if channels
255 * are disabled because PV expects disabled channels to still be accounted
256 * for in the packing */
ac132f83 257 devc->dig_sample_bytes = ((devc->num_d_channels + 7) / 8);
c5776ef7
SA
258 /* These are the slice sizes of the data on the wire
259 * 1 7 bit field per byte */
ac132f83 260 devc->bytes_per_slice = (devc->num_a_channels * devc->a_size);
c5776ef7 261
ac132f83 262 if (devc->num_d_channels > 0) {
c5776ef7 263 /* logic sent in groups of 7*/
ac132f83
A
264 devc->bytes_per_slice += (devc->num_d_channels + 6) / 7;
265 }
266 sr_dbg("num channels a %d d %d bps %d dsb %d", num_a, num_d,
c5776ef7
SA
267 devc->bytes_per_slice, devc->dig_sample_bytes);
268
269 /* Each analog channel is its own group; digital are just channels;
270 * Grouping of channels is rather arbitrary as parameters like sample rate
271 * and number of samples apply to all channels. Analog channels do have a
272 * scale and offset, but that is applied automatically. */
ac132f83 273 devc->analog_groups = g_malloc0(sizeof(struct sr_channel_group *) *
c5776ef7 274 devc->num_a_channels);
ac132f83
A
275 for (i = 0; i < devc->num_a_channels; i++) {
276 channel_name = g_strdup_printf("A%d", i);
c5776ef7
SA
277 ch = sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_name);
278 devc->analog_groups[i] = g_malloc0(sizeof(struct sr_channel_group));
ac132f83 279 devc->analog_groups[i]->name = channel_name;
c5776ef7
SA
280 devc->analog_groups[i]->channels = g_slist_append(NULL, ch);
281 sdi->channel_groups = g_slist_append(sdi->channel_groups,
282 devc->analog_groups[i]);
ac132f83
A
283 }
284
285 if (devc->num_d_channels > 0) {
286 for (i = 0; i < devc->num_d_channels; i++) {
c5776ef7 287 /* Name digital channels starting at D2 to match pico board names */
ac132f83 288 channel_name = g_strdup_printf("D%d", i + 2);
c5776ef7 289 sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name);
ac132f83
A
290 g_free(channel_name);
291 }
ac132f83 292 }
c5776ef7
SA
293
294 /* In large sample usages we get the call to receive with large transfers.
295 * Since the CDC serial implemenation can silenty lose data as it gets close
296 * to full, allocate storage for a half buffer which in a worst case
297 * scenario has 2x ratio of transmitted bytes to storage bytes.
298 * Note: The intent of making this buffer large is to prevent CDC serial
299 * buffer overflows. However, it is likely that if the host is running slow
300 * (i.e. it's a raspberry pi model 3) that it becomes compute bound and
301 * doesn't service CDC serial responses in time to not overflow the internal
302 * CDC buffers. Thus no serial buffer is large enough.
303 * But, it's only 32K... */
0c792900 304 devc->serial_buffer_size = 32000;
ac132f83 305 devc->buffer = NULL;
c5776ef7
SA
306 sr_dbg("Setting serial buffer size: %i.", devc->serial_buffer_size);
307
ac132f83 308 devc->cbuf_wrptr = 0;
c5776ef7
SA
309 /* While slices are sent as a group of one sample across all channels,
310 * sigrok wants analog channel data sent as separate packets. Logical trace
311 * values are packed together. An RLE byte in normal mode can represent up
312 * to 1640 samples. In D4 an RLE byte can represent up to 640 samples.
313 * Rather than making the sample_buf_size 1640x the size of serial buffer,
314 * we require that the process loops push samples to the session as we get
315 * anywhere close to full. */
0c792900
A
316
317 devc->sample_buf_size = devc->serial_buffer_size;
ac132f83
A
318 for (i = 0; i < devc->num_a_channels; i++) {
319 devc->a_data_bufs[i] = NULL;
320 devc->a_pretrig_bufs[i] = NULL;
321 }
322 devc->d_data_buf = NULL;
323 devc->sample_rate = 5000;
324 devc->capture_ratio = 10;
325 devc->rxstate = RX_IDLE;
c5776ef7 326 /*Set an initial value as various code relies on an inital value. */
ac132f83
A
327 devc->limit_samples = 1000;
328
c5776ef7
SA
329 sdi->priv = devc;
330
ac132f83
A
331 if (raspberrypi_pico_get_dev_cfg(sdi) != SR_OK) {
332 return NULL;
333 };
334
ac132f83
A
335 serial_close(serial);
336 return std_scan_complete(di, g_slist_append(NULL, sdi));
dc90146e
A
337}
338
c5776ef7
SA
339/* Note that on the initial driver load we pull all values into local storage.
340 * Thus gets can return local data, but sets have to issue commands to device. */
ac132f83 341static int config_set(uint32_t key, GVariant * data,
c5776ef7 342 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
dc90146e 343{
ac132f83
A
344 struct dev_context *devc;
345 int ret;
346 (void) cg;
c5776ef7 347
ac132f83
A
348 if (!sdi)
349 return SR_ERR_ARG;
c5776ef7 350
ac132f83
A
351 devc = sdi->priv;
352 ret = SR_OK;
c5776ef7 353
ac132f83
A
354 sr_dbg("Got config_set key %d \n", key);
355 switch (key) {
356 case SR_CONF_SAMPLERATE:
357 devc->sample_rate = g_variant_get_uint64(data);
e35beb6f 358 sr_dbg("config_set sr %lu\n", devc->sample_rate);
ac132f83
A
359 break;
360 case SR_CONF_LIMIT_SAMPLES:
361 devc->limit_samples = g_variant_get_uint64(data);
b9890a32 362 sr_dbg("config_set slimit %" PRIu64 "\n", devc->limit_samples);
ac132f83
A
363 break;
364 case SR_CONF_CAPTURE_RATIO:
365 devc->capture_ratio = g_variant_get_uint64(data);
366 break;
367
368 default:
c5776ef7 369 sr_err("ERROR: config_set given undefined key %d\n", key);
ac132f83
A
370 ret = SR_ERR_NA;
371 }
372
373 return ret;
bac2a8b8 374}
dc90146e 375
ac132f83 376static int config_get(uint32_t key, GVariant ** data,
c5776ef7 377 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
bac2a8b8 378{
ac132f83 379 struct dev_context *devc;
c5776ef7
SA
380
381 sr_dbg("config_get given key %d", key);
382
ac132f83 383 (void) cg;
c5776ef7 384
ac132f83
A
385 if (!sdi)
386 return SR_ERR_ARG;
387
388 devc = sdi->priv;
389 switch (key) {
390 case SR_CONF_SAMPLERATE:
391 *data = g_variant_new_uint64(devc->sample_rate);
b9890a32 392 sr_spew("sample rate get of %" PRIu64 "", devc->sample_rate);
ac132f83
A
393 break;
394 case SR_CONF_CAPTURE_RATIO:
395 if (!sdi)
396 return SR_ERR;
397 devc = sdi->priv;
398 *data = g_variant_new_uint64(devc->capture_ratio);
399 break;
400 case SR_CONF_LIMIT_SAMPLES:
c5776ef7 401 sr_spew("config_get limit_samples of %lu", devc->limit_samples);
ac132f83
A
402 *data = g_variant_new_uint64(devc->limit_samples);
403 break;
404 default:
c5776ef7 405 sr_spew("unsupported config_get key %d", key);
ac132f83
A
406 return SR_ERR_NA;
407 }
408 return SR_OK;
dc90146e
A
409}
410
ac132f83 411static int config_list(uint32_t key, GVariant ** data,
c5776ef7 412 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
dc90146e 413{
ac132f83 414 (void) cg;
c5776ef7
SA
415
416 /* Scan or device options are the only ones that can be called without a
417 * defined instance */
418 if ((key == SR_CONF_SCAN_OPTIONS) || (key == SR_CONF_DEVICE_OPTIONS)) {
419 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
ac132f83 420 }
c5776ef7 421
ac132f83 422 if (!sdi) {
c5776ef7 423 sr_err("ERROR: Call to config list with null sdi");
ac132f83
A
424 return SR_ERR_ARG;
425 }
c5776ef7
SA
426
427 sr_dbg("Start config_list with key %X", key);
ac132f83 428 switch (key) {
ac132f83 429 case SR_CONF_SAMPLERATE:
c5776ef7 430 *data = std_gvar_samplerates(ARRAY_AND_SIZE(samplerates));
ac132f83 431 break;
c5776ef7 432 /* This must be set to get SW trigger support */
ac132f83 433 case SR_CONF_TRIGGER_MATCH:
c5776ef7 434 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
ac132f83
A
435 break;
436 case SR_CONF_LIMIT_SAMPLES:
c5776ef7
SA
437 /* Really this limit is up to the memory capacity of the host,
438 * and users that pick huge values deserve what they get.
439 * But setting this limit to prevent really crazy things. */
ac132f83 440 *data = std_gvar_tuple_u64(1LL, 1000000000LL);
ac132f83
A
441 break;
442 default:
c5776ef7 443 sr_dbg("Reached default statement of config_list");
ac132f83
A
444
445 return SR_ERR_NA;
446 }
447
448 return SR_OK;
dc90146e
A
449}
450
451static int dev_acquisition_start(const struct sr_dev_inst *sdi)
452{
ac132f83
A
453 struct sr_serial_dev_inst *serial;
454 struct dev_context *devc;
455 struct sr_channel *ch;
456 struct sr_trigger *trigger;
457 char tmpstr[20];
b9890a32 458 char buf[32];
ac132f83
A
459 GSList *l;
460 int a_enabled = 0, d_enabled = 0, len;
461 serial = sdi->conn;
c5776ef7
SA
462 int i, num_read;
463
ac132f83
A
464 devc = sdi->priv;
465 sr_dbg("Enter acq start");
466 sr_dbg("dsbstart %d", devc->dig_sample_bytes);
c5776ef7 467
ac132f83
A
468 devc->buffer = g_malloc(devc->serial_buffer_size);
469 if (!(devc->buffer)) {
c5776ef7 470 sr_err("ERROR: serial buffer malloc fail");
ac132f83
A
471 return SR_ERR_MALLOC;
472 }
c5776ef7
SA
473
474 /* Get device in idle state */
ac132f83 475 if (serial_drain(serial) != SR_OK) {
c5776ef7 476 sr_err("Initial Drain Failed");
ac132f83
A
477 return SR_ERR;
478 }
c5776ef7 479
ac132f83
A
480 send_serial_char(serial, '*');
481 if (serial_drain(serial) != SR_OK) {
c5776ef7 482 sr_err("Second Drain Failed");
ac132f83
A
483 return SR_ERR;
484 }
485
486 for (l = sdi->channels; l; l = l->next) {
487 ch = l->data;
c5776ef7 488 sr_dbg("c %d enabled %d name %s\n", ch->index, ch->enabled, ch->name);
ac132f83
A
489
490 if (ch->name[0] == 'A') {
491 devc->a_chan_mask &= ~(1 << ch->index);
492 if (ch->enabled) {
c5776ef7 493 devc->a_chan_mask |= (ch->enabled << ch->index);
ac132f83
A
494 a_enabled++;
495 }
ac132f83
A
496 }
497 if (ch->name[0] == 'D') {
498 devc->d_chan_mask &= ~(1 << ch->index);
499 if (ch->enabled) {
c5776ef7 500 devc->d_chan_mask |= (ch->enabled << ch->index);
ac132f83 501 d_enabled++;
ac132f83
A
502 }
503 }
c5776ef7 504
ac132f83
A
505 sr_info("Channel enable masks D 0x%X A 0x%X",
506 devc->d_chan_mask, devc->a_chan_mask);
c5776ef7 507 sprintf(tmpstr, "%c%d%d\n", ch->name[0], ch->enabled, ch->index);
ac132f83 508 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
c5776ef7 509 sr_err("ERROR: Channel enable fail");
ac132f83 510 return SR_ERR;
ac132f83 511 }
c5776ef7
SA
512 }
513
514 /* Ensure data channels are continuous */
ac132f83
A
515 int invalid = 0;
516 for (i = 0; i < 32; i++) {
517 if ((devc->d_chan_mask >> i) & 1) {
518 if (invalid) {
c5776ef7
SA
519 sr_err("Digital channel mask 0x%X not continous",
520 devc->d_chan_mask);
ac132f83
A
521 return SR_ERR;
522 }
c5776ef7 523 } else
ac132f83 524 invalid = 1;
ac132f83 525 }
c5776ef7
SA
526
527 /* Recalculate bytes_per_slice based on which analog channels are enabled */
ac132f83
A
528 devc->bytes_per_slice = (a_enabled * devc->a_size);
529
c5776ef7
SA
530 for (i = 0; i < devc->num_d_channels; i += 7)
531 if (((devc->d_chan_mask) >> i) & (0x7F))
ac132f83 532 (devc->bytes_per_slice)++;
c5776ef7 533
ac132f83
A
534 if ((a_enabled == 0) && (d_enabled == 0)) {
535 sr_err("ERROR:No channels enabled");
536 return SR_ERR;
537 }
c5776ef7 538
ac132f83
A
539 sr_dbg("bps %d\n", devc->bytes_per_slice);
540
c5776ef7
SA
541 /* Apply sample rate limits; while earlier versions forced a lower sample
542 * rate, the PICO seems to allow ADC overclocking, and by not enforcing
543 * these limits it may support other devices. Thus call sr_err to get
544 * something into the device logs, but allowing it to progress. */
545 if ((a_enabled == 3) && (devc->sample_rate > 160000))
546 sr_err("WARN: 3 channel ADC sample rate above 160khz");
547 if ((a_enabled == 2) && (devc->sample_rate > 250000))
548 sr_err("WARN: 2 channel ADC sample rate above 250khz");
549 if ((a_enabled == 1) && (devc->sample_rate > 500000))
550 sr_err("WARN: 1 channel ADC sample rate above 500khz");
551
552 /* Depending on channel configs, rates below 5ksps are possible but such a
553 * low rate can easily stream and this eliminates a lot of special cases. */
ac132f83
A
554 if (devc->sample_rate < 5000) {
555 sr_err("Sample rate override to min of 5ksps");
556 devc->sample_rate = 5000;
557 }
c5776ef7
SA
558
559 /* While PICO specs a max clock ~120-125Mhz, it does overclock in many cases
560 * so leaving a warning. */
561 if (devc->sample_rate > 120000000)
562 sr_warn("WARN: Sample rate above 120Msps");
563
564 /* It may take a very large number of samples to notice, but if digital and
565 * analog are enabled and either PIO or ADC are fractional the samples will
566 * skew over time. 24Mhz is the max common divisor to the 120Mhz and 48Mhz
567 * ADC clock so force an integer divisor to 24Mhz. */
ac132f83
A
568 if ((a_enabled > 0) && (d_enabled > 0)) {
569 if (24000000ULL % (devc->sample_rate)) {
c5776ef7
SA
570 uint32_t commondivint = 24000000ULL / (devc->sample_rate);
571 /* Always increment the divisor so that we go down in frequency to
572 * avoid max sample rate issues */
ac132f83
A
573 commondivint++;
574 devc->sample_rate = 24000000ULL / commondivint;
c5776ef7
SA
575 /* Make sure the divisor increment didn't make us go too low. */
576 if (devc->sample_rate < 5000)
ac132f83 577 devc->sample_rate = 50000;
c5776ef7
SA
578 sr_warn("WARN: Forcing common integer divisor sample rate of " \
579 "%lu div %u", devc->sample_rate, commondivint);
ac132f83
A
580 }
581 }
582
c5776ef7
SA
583 /* If we are only digital or only analog print a warning that the fractional
584 * divisors aren't a true PLL fractional feedback loop and thus could have
585 * sample to sample variation. These warnings of course assume that the
586 * device is programmed with the expected ratios but non PICO
587 * implementations, or PICO implementations that use different divisors
588 * could avoid. This generally won't be a problem because most of the
589 * sample_rate pulldown values are integer divisors. */
590 if ((a_enabled > 0) && (48000000ULL % (devc->sample_rate * a_enabled)))
591 sr_warn("WARN: Non integer ADC divisor of 48Mhz clock for sample " \
592 "rate %lu may cause sample to sample variability.",
593 devc->sample_rate);
594 if ((d_enabled > 0) && (120000000ULL % (devc->sample_rate)))
595 sr_warn("WARN: Non integer PIO divisor of 120Mhz for sample rate " \
596 "%lu may cause sample to sample variability.", devc->sample_rate);
597
b9890a32 598 sprintf(tmpstr, "L%" PRIu64 "\n", devc->limit_samples);
ac132f83 599 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
b9890a32 600 sr_err("Sample limit to device failed");
ac132f83
A
601 return SR_ERR;
602 }
c5776ef7
SA
603
604 /* To support future devices that may allow the analog scale/offset to
605 * change, call get_dev_cfg again to get new values */
606 if (raspberrypi_pico_get_dev_cfg(sdi) != SR_OK) {
607 sr_err("get_dev_cfg failure on start");
608 return SR_ERR;
b9890a32
A
609 }
610
c5776ef7
SA
611 /* With all other params set, we use the final sample rate setting as an
612 * opportunity for the device to communicate any errors in configuration.
613 * A single "*" indicates success.
614 * A "*" with subsequent data is success, but allows for the device to
615 * print something to the error console without aborting.
616 * A non "*" in the first character blocks the start. */
e35beb6f 617 sprintf(tmpstr, "R%lu\n", devc->sample_rate);
b9890a32 618 num_read = send_serial_w_resp(serial, tmpstr, buf, 30);
c5776ef7
SA
619 buf[num_read] = 0;
620 if ((num_read > 1) && (buf[0] == '*'))
621 sr_dbg("Sample rate to device success with resp %s", buf);
622 else if (!((num_read == 1) && (buf[0] == '*'))) {
b9890a32 623 sr_err("Sample rate to device failed");
c5776ef7
SA
624 if (num_read > 0) {
625 buf[num_read]=0;
626 sr_err("sample_rate error string %s",buf);
b9890a32 627 }
ac132f83
A
628 return SR_ERR;
629 }
c5776ef7 630
ac132f83
A
631 devc->sent_samples = 0;
632 devc->byte_cnt = 0;
633 devc->bytes_avail = 0;
634 devc->wrptr = 0;
635 devc->cbuf_wrptr = 0;
c5776ef7
SA
636 len = serial_read_blocking(serial, devc->buffer, devc->serial_buffer_size,
637 serial_timeout(serial, 4));
638
ac132f83
A
639 if (len > 0) {
640 sr_info("Pre-ARM drain had %d characters:", len);
641 devc->buffer[len] = 0;
642 sr_info("%s", devc->buffer);
643 }
644
645 for (i = 0; i < devc->num_a_channels; i++) {
c5776ef7 646 devc->a_data_bufs[i] = g_malloc(devc->sample_buf_size * sizeof(float));
ac132f83 647 if (!(devc->a_data_bufs[i])) {
c5776ef7 648 sr_err("ERROR: analog buffer malloc fail");
ac132f83
A
649 return SR_ERR_MALLOC;
650 }
651 }
c5776ef7 652
ac132f83 653 if (devc->num_d_channels > 0) {
c5776ef7
SA
654 devc->d_data_buf = g_malloc(devc->sample_buf_size *
655 devc->dig_sample_bytes);
ac132f83 656 if (!(devc->d_data_buf)) {
c5776ef7 657 sr_err("ERROR: logic buffer malloc fail");
ac132f83
A
658 return SR_ERR_MALLOC;
659 }
660 }
c5776ef7
SA
661
662 devc->pretrig_entries = (devc->capture_ratio * devc->limit_samples) / 100;
663 /* While the driver supports the passing of trigger info to the device
664 * it has been found that the sw overhead of supporting triggering and
665 * pretrigger buffer entries etc.. ends up slowing the cores down enough
666 * that the effective continous sample rate isn't much higher than that of
667 * sending untriggered samples across USB. Thus this code will remain but
668 * likely may not be used by the device, unless HW based triggers are
669 * implemented */
ac132f83 670 if ((trigger = sr_session_trigger_get(sdi->session))) {
c5776ef7
SA
671 if (g_slist_length(trigger->stages) > 1)
672 return SR_ERR_NA;
0c792900 673
c5776ef7
SA
674 struct sr_trigger_stage *stage;
675 struct sr_trigger_match *match;
0c792900
A
676 GSList *l;
677 stage = g_slist_nth_data(trigger->stages, 0);
c5776ef7
SA
678 if (!stage)
679 return SR_ERR_ARG;
680 for (l = stage->matches; l; l = l->next) {
681 match = l->data;
682 if (!match->match)
683 continue;
684 if (!match->channel->enabled)
685 continue;
686 int idx = match->channel->index;
687 int8_t val;
688 switch(match->match) {
689 case SR_TRIGGER_ZERO:
690 val = 0; break;
691 case SR_TRIGGER_ONE:
692 val = 1; break;
693 case SR_TRIGGER_RISING:
694 val = 2; break;
695 case SR_TRIGGER_FALLING:
696 val = 3; break;
697 case SR_TRIGGER_EDGE:
698 val = 4; break;
699 default:
700 val = -1;
0c792900 701 }
c5776ef7
SA
702 sr_info("Trigger value idx %d match %d", idx, match->match);
703 /* Only set trigger on enabled channels */
704 if ((val >= 0) && ((devc->d_chan_mask >> idx) & 1)) {
705 sprintf(&tmpstr[0], "t%d%02d\n", val, idx+2);
706 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
707 sr_err("Trigger cfg to device failed");
708 return SR_ERR;
709 }
0c792900 710 }
c5776ef7
SA
711 }
712
713 sprintf(&tmpstr[0], "p%d\n", devc->pretrig_entries);
0c792900 714 if (send_serial_w_ack(serial, tmpstr) != SR_OK) {
c5776ef7
SA
715 sr_err("Pretrig to device failed");
716 return SR_ERR;
717 }
718
719 devc->stl = soft_trigger_logic_new(sdi, trigger, devc->pretrig_entries);
ac132f83
A
720 if (!devc->stl)
721 return SR_ERR_MALLOC;
c5776ef7 722
ac132f83
A
723 devc->trigger_fired = FALSE;
724 if (devc->pretrig_entries > 0) {
c5776ef7 725 sr_dbg("Allocating pretrig buffers size %d", devc->pretrig_entries);
ac132f83
A
726 for (i = 0; i < devc->num_a_channels; i++) {
727 if ((devc->a_chan_mask >> i) & 1) {
c5776ef7
SA
728 devc->a_pretrig_bufs[i] = g_malloc0(sizeof(float) *
729 devc->pretrig_entries);
ac132f83 730 if (!devc->a_pretrig_bufs[i]) {
c5776ef7
SA
731 sr_err("ERROR:Analog pretrigger buffer malloc " \
732 "failure, disabling");
ac132f83
A
733 devc->trigger_fired = TRUE;
734 }
c5776ef7
SA
735 }
736 }
737 }
738
ac132f83 739 sr_info("Entering sw triggered mode");
c5776ef7
SA
740 /* Post the receive before starting the device to ensure we are ready
741 * to receive data ASAP */
ac132f83 742 serial_source_add(sdi->session, serial, G_IO_IN, 200,
c5776ef7
SA
743 raspberrypi_pico_receive, (void*)sdi);
744
ac132f83
A
745 sprintf(tmpstr, "C\n");
746 if (send_serial_str(serial, tmpstr) != SR_OK)
747 return SR_ERR;
748
749 } else {
750 devc->trigger_fired = TRUE;
751 devc->pretrig_entries = 0;
752 sr_info("Entering fixed sample mode");
753 serial_source_add(sdi->session, serial, G_IO_IN, 200,
c5776ef7
SA
754 raspberrypi_pico_receive, (void*)sdi);
755
ac132f83
A
756 sprintf(tmpstr, "F\n");
757 if (send_serial_str(serial, tmpstr) != SR_OK)
758 return SR_ERR;
759 }
c5776ef7 760
ac132f83
A
761 std_session_send_df_header(sdi);
762
763 sr_dbg("dsbstartend %d", devc->dig_sample_bytes);
764
765 if (devc->trigger_fired)
766 std_session_send_df_trigger(sdi);
c5776ef7
SA
767
768 /* Keep this at the end as we don't want to be RX_ACTIVE unless everything
769 * is ok */
ac132f83
A
770 devc->rxstate = RX_ACTIVE;
771
772 return SR_OK;
dc90146e 773}
ac132f83 774
c5776ef7
SA
775/* This function is called either by the protocol code if we reached all of the
776 * samples or an error condition, and also by the user clicking stop in
777 * pulseview. It must always be called for any acquistion that was started to
778 * free memory. */
dc90146e
A
779static int dev_acquisition_stop(struct sr_dev_inst *sdi)
780{
ac132f83
A
781 struct dev_context *devc;
782 struct sr_serial_dev_inst *serial;
ac132f83
A
783 int len;
784 devc = sdi->priv;
785 serial = sdi->conn;
786
c5776ef7
SA
787 sr_dbg("At dev_acquisition_stop");
788
ac132f83 789 std_session_send_df_end(sdi);
c5776ef7
SA
790
791 /* If we reached this while still active it is likely because the stop
792 * button was pushed in pulseview. That is generally some kind of error
793 * condition, so we don't try to check the bytenct */
794 if (devc->rxstate == RX_ACTIVE)
ac132f83 795 sr_err("Reached dev_acquisition_stop in RX_ACTIVE");
c5776ef7 796
ac132f83 797 if (devc->rxstate != RX_IDLE) {
c5776ef7 798 sr_err("Sending plus to stop device stream");
ac132f83
A
799 send_serial_char(serial, '+');
800 }
c5776ef7
SA
801
802 /* In case we get calls to receive force it to exit */
ac132f83 803 devc->rxstate = RX_IDLE;
c5776ef7
SA
804
805 /* Drain data from device so that it doesn't confuse subsequent commands */
ac132f83 806 do {
c5776ef7
SA
807 len = serial_read_blocking(serial, devc->buffer,
808 devc->serial_buffer_size, 100);
ac132f83 809 if (len)
c5776ef7 810 sr_err("Dropping %d device bytes", len);
ac132f83 811 } while (len > 0);
c5776ef7 812
ac132f83
A
813 if (devc->buffer) {
814 g_free(devc->buffer);
815 devc->buffer = NULL;
816 }
c5776ef7 817
ac132f83
A
818 for (int i = 0; i < devc->num_a_channels; i++) {
819 if (devc->a_data_bufs[i]) {
820 g_free(devc->a_data_bufs[i]);
821 devc->a_data_bufs[i] = NULL;
822 }
823 }
ac132f83
A
824 if (devc->d_data_buf) {
825 g_free(devc->d_data_buf);
826 devc->d_data_buf = NULL;
827 }
c5776ef7 828
ac132f83
A
829 for (int i = 0; i < devc->num_a_channels; i++) {
830 if (devc->a_pretrig_bufs[i])
831 g_free(devc->a_pretrig_bufs[i]);
832 devc->a_pretrig_bufs[i] = NULL;
833 }
c5776ef7 834
ac132f83
A
835 serial = sdi->conn;
836 serial_source_remove(sdi->session, serial);
c5776ef7 837
ac132f83 838 return SR_OK;
dc90146e
A
839}
840
841static struct sr_dev_driver raspberrypi_pico_driver_info = {
ac132f83
A
842 .name = "raspberrypi-pico",
843 .longname = "RaspberryPI PICO",
844 .api_version = 1,
845 .init = std_init,
846 .cleanup = std_cleanup,
847 .scan = scan,
848 .dev_list = std_dev_list,
849 .dev_clear = std_dev_clear,
850 .config_get = config_get,
851 .config_set = config_set,
852 .config_list = config_list,
853 .dev_open = std_serial_dev_open,
854 .dev_close = std_serial_dev_close,
855 .dev_acquisition_start = dev_acquisition_start,
856 .dev_acquisition_stop = dev_acquisition_stop,
857 .context = NULL,
dc90146e 858};
ac132f83 859
dc90146e 860SR_REGISTER_DEV_DRIVER(raspberrypi_pico_driver_info);