]> sigrok.org Git - libsigrok.git/blob - src/hardware/microchip-pickit2/api.c
rigol-ds: improve robustness in samplerate getting code path
[libsigrok.git] / src / hardware / microchip-pickit2 / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2018 Gerhard Sittig <gerhard.sittig@gmx.net>
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
20 /*
21  * TODO
22  * - Data acquisition works, but triggers either seem to not take effect,
23  *   or the trigger position is not in the expected spot according to the
24  *   user provided acquisition parameters. More research is required. The
25  *   bitmasks for enable/level/edge as well as the magic 16bit values for
26  *   position may need adjustment.
27  * - The trigger position logic assumes that capture ratio specs are in
28  *   the range of 0-6%, which gets mapped to none/10%/50%/90%/+1W/+2W/+3W
29  *   choices. This avoids issues with applications which lack support for
30  *   non-contiguous discrete supported values, and values outside of the
31  *   0-100% range. This is considered acceptable, to avoid the necessity
32  *   to extend common infrastructure to an unusual feature of a single
33  *   device of limited popularity. Just needs to get communicated to users.
34  * - When a formula for the trigger position values in the SETUP packet
35  *   is found, the driver may accept arbitrary values between 0-100%, but
36  *   still could not express the "plus N windows" settings. Though that'd
37  *   be a rather useful feature considering the very short memory depth.
38  * - The current implementation assumes externally provided Vdd, without
39  *   which input levels won't get detected. A future implementation could
40  *   optionally power Vdd from the PICkit2 itself, according to a user
41  *   provided configuration value.
42  * - The current implementation silently accepts sample count limits beyond
43  *   1024, just won't provide more than 1024 samples to the session. A
44  *   future implementation could cap the settings upon reception. Apps
45  *   like PulseView may not be able to specify 1024, and pass 1000 or
46  *   2000 instead (the latter results in 1024 getting used).
47  * - The manual suggests that users can assign names to devices. The
48  *   current implementation supports conn= specs with USB VID:PID pairs
49  *   or bus/address numbers. A future implementation could scan for user
50  *   assigned names as well (when the opcode to query the name was found).
51  * - The "attach kernel driver" support code probably should move to a
52  *   common location, instead of getting repeated across several drivers.
53  * - Diagnostics may benefit from cleanup.
54  */
55
56 #include <config.h>
57 #include <libusb.h>
58 #include <string.h>
59 #include "protocol.h"
60
61 #define PICKIT2_VENDOR_NAME     "Microchip"
62 #define PICKIT2_PRODUCT_NAME    "PICkit2"
63
64 #define PICKIT2_DEFAULT_ADDRESS "04d8.0033"
65 #define PICKIT2_USB_INTERFACE   0
66
67 static struct sr_dev_driver microchip_pickit2_driver_info;
68
69 static const char *channel_names[] = {
70         "pin4", "pin5", "pin6",
71 };
72
73 static const uint32_t scanopts[] = {
74         SR_CONF_CONN,
75 };
76
77 static const uint32_t drvopts[] = {
78         SR_CONF_LOGIC_ANALYZER,
79 };
80
81 static const uint32_t devopts[] = {
82         SR_CONF_CONN | SR_CONF_GET,
83         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
84         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
85         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
86         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
87 };
88
89 static const int32_t trigger_matches[] = {
90         SR_TRIGGER_ZERO,
91         SR_TRIGGER_ONE,
92         SR_TRIGGER_RISING,
93         SR_TRIGGER_FALLING,
94 };
95
96 /*
97  * Note that a list of 0, 10, 50, 90, 91, 92, 93, would have been nicer
98  * from a user's perspective, but applications may not support a set of
99  * discrete supported values, and 91+ is as much of a hack to work around
100  * the "0-100%" limitation. So let's map those 0-6 "percent" to the vendor
101  * app's 10/50/90/1W/2W/3W locations.
102  */
103 static const uint64_t captureratios[] = {
104         0, 1, 2, 3, 4, 5, 6,
105 };
106
107 static const uint64_t samplerates[] = {
108         SR_KHZ(5),
109         SR_KHZ(10),
110         SR_KHZ(25),
111         SR_KHZ(50),
112         SR_KHZ(100),
113         SR_KHZ(250),
114         SR_KHZ(500),
115         SR_MHZ(1),
116 };
117
118 static GSList *scan(struct sr_dev_driver *di, GSList *options)
119 {
120         struct drv_context *drvc;
121         const char *conn;
122         GSList *l, *devices, *usb_devices;
123         struct sr_config *cfg;
124         struct sr_usb_dev_inst *usb;
125         struct sr_dev_inst *sdi;
126         struct sr_channel_group *cg;
127         size_t ch_count, ch_idx;
128         struct sr_channel *ch;
129         struct dev_context *devc;
130
131         drvc = di->context;
132
133         conn = PICKIT2_DEFAULT_ADDRESS;
134         for (l = options; l; l = l->next) {
135                 cfg = l->data;
136                 switch (cfg->key) {
137                 case SR_CONF_CONN:
138                         conn = g_variant_get_string(cfg->data, NULL);
139                         break;
140                 }
141         }
142
143         devices = NULL;
144         usb_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
145         if (!usb_devices)
146                 return NULL;
147
148         for (l = usb_devices; l; l = l->next) {
149                 usb = l->data;
150
151                 /* Create the device instance. */
152                 sdi = g_malloc0(sizeof(*sdi));
153                 devices = g_slist_append(devices, sdi);
154                 sdi->status = SR_ST_INACTIVE;
155                 sdi->vendor = g_strdup(PICKIT2_VENDOR_NAME);
156                 sdi->model = g_strdup(PICKIT2_PRODUCT_NAME);
157                 sdi->inst_type = SR_INST_USB;
158                 sdi->conn = usb;
159                 sdi->connection_id = g_strdup(conn);
160
161                 /* Create the logic channels group. */
162                 cg = g_malloc0(sizeof(*cg));
163                 sdi->channel_groups = g_slist_append(NULL, cg);
164                 cg->name = g_strdup("Logic");
165                 ch_count = ARRAY_SIZE(channel_names);
166                 for (ch_idx = 0; ch_idx < ch_count; ch_idx++) {
167                         ch = sr_channel_new(sdi, ch_idx, SR_CHANNEL_LOGIC,
168                                 TRUE, channel_names[ch_idx]);
169                         cg->channels = g_slist_append(cg->channels, ch);
170                 }
171
172                 /*
173                  * Create the device context. Pre-select the highest
174                  * samplerate and the deepest sample count available.
175                  */
176                 devc = g_malloc0(sizeof(*devc));
177                 sdi->priv = devc;
178                 devc->samplerates = samplerates;
179                 devc->num_samplerates = ARRAY_SIZE(samplerates);
180                 devc->curr_samplerate_idx = devc->num_samplerates - 1;
181                 devc->captureratios = captureratios;
182                 devc->num_captureratios = ARRAY_SIZE(captureratios);
183                 devc->curr_captureratio_idx = 0;
184                 devc->sw_limits.limit_samples = PICKIT2_SAMPLE_COUNT;
185         }
186
187         return std_scan_complete(di, devices);
188 }
189
190 static int dev_open(struct sr_dev_inst *sdi)
191 {
192         struct sr_usb_dev_inst *usb;
193         struct dev_context *devc;
194         struct sr_dev_driver *di;
195         struct drv_context *drvc;
196         int ret;
197
198         usb = sdi->conn;
199         devc = sdi->priv;
200         di = sdi->driver;
201         drvc = di->context;
202
203         ret = sr_usb_open(drvc->sr_ctx->libusb_ctx, usb);
204         if (ret < 0)
205                 return SR_ERR;
206
207         if (libusb_kernel_driver_active(usb->devhdl, PICKIT2_USB_INTERFACE) == 1) {
208                 ret = libusb_detach_kernel_driver(usb->devhdl, PICKIT2_USB_INTERFACE);
209                 if (ret < 0) {
210                         sr_err("Canot detach kernel driver: %s.",
211                                 libusb_error_name(ret));
212                         return SR_ERR;
213                 }
214                 devc->detached_kernel_driver = TRUE;
215         }
216
217         ret = libusb_claim_interface(usb->devhdl, PICKIT2_USB_INTERFACE);
218         if (ret < 0) {
219                 sr_err("Cannot claim interface: %s.", libusb_error_name(ret));
220                 return SR_ERR;
221         }
222
223         return SR_OK;
224 }
225
226 static int dev_close(struct sr_dev_inst *sdi)
227 {
228         struct sr_usb_dev_inst *usb;
229         struct dev_context *devc;
230         int ret;
231
232         usb = sdi->conn;
233         devc = sdi->priv;
234
235         if (!usb)
236                 return SR_OK;
237         if (!usb->devhdl)
238                 return SR_OK;
239
240         ret = libusb_release_interface(usb->devhdl, PICKIT2_USB_INTERFACE);
241         if (ret) {
242                 sr_err("Cannot release interface: %s.", libusb_error_name(ret));
243                 return SR_ERR;
244         }
245
246         if (devc->detached_kernel_driver) {
247                 ret = libusb_attach_kernel_driver(usb->devhdl, PICKIT2_USB_INTERFACE);
248                 if (ret) {
249                         sr_err("Cannot attach kernel driver: %s.",
250                                 libusb_error_name(ret));
251                         return SR_ERR;
252                 }
253                 devc->detached_kernel_driver = FALSE;
254         }
255
256         libusb_close(usb->devhdl);
257         sdi->conn = NULL;
258
259         return SR_OK;
260 }
261
262 static int config_get(uint32_t key, GVariant **data,
263         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
264 {
265         struct dev_context *devc;
266         struct sr_usb_dev_inst *usb;
267         uint64_t rate, ratio;
268
269         (void)cg;
270
271         devc = sdi ? sdi->priv : NULL;
272
273         switch (key) {
274         case SR_CONF_CONN:
275                 if (!sdi->conn)
276                         return SR_ERR_ARG;
277                 usb = sdi->conn;
278                 *data = g_variant_new_printf("%d.%d", usb->bus, usb->address);
279                 return SR_OK;
280         case SR_CONF_SAMPLERATE:
281                 rate = devc->samplerates[devc->curr_samplerate_idx];
282                 *data = g_variant_new_uint64(rate);
283                 return SR_OK;
284         case SR_CONF_LIMIT_SAMPLES:
285                 return sr_sw_limits_config_get(&devc->sw_limits, key, data);
286         case SR_CONF_CAPTURE_RATIO:
287                 ratio = devc->captureratios[devc->curr_captureratio_idx];
288                 *data = g_variant_new_uint64(ratio);
289                 return SR_OK;
290         default:
291                 return SR_ERR_NA;
292         }
293 }
294
295 static int config_set(uint32_t key, GVariant *data,
296         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
297 {
298         struct dev_context *devc;
299         int idx;
300
301         (void)cg;
302
303         devc = sdi ? sdi->priv : NULL;
304
305         switch (key) {
306         case SR_CONF_SAMPLERATE:
307                 if (!devc)
308                         return SR_ERR_ARG;
309                 idx = std_u64_idx(data, devc->samplerates, devc->num_samplerates);
310                 if (idx < 0)
311                         return SR_ERR_ARG;
312                 devc->curr_samplerate_idx = idx;
313                 return SR_OK;
314         case SR_CONF_CAPTURE_RATIO:
315                 if (!devc)
316                         return SR_ERR_ARG;
317                 idx = std_u64_idx(data, devc->captureratios, devc->num_captureratios);
318                 if (idx >= 0)
319                         devc->curr_captureratio_idx = idx;
320                 return SR_OK;
321         case SR_CONF_LIMIT_SAMPLES:
322                 return sr_sw_limits_config_set(&devc->sw_limits, key, data);
323         default:
324                 return SR_ERR_NA;
325         }
326 }
327
328 static int config_list(uint32_t key, GVariant **data,
329         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
330 {
331         struct dev_context *devc;
332
333         devc = sdi ? sdi->priv : NULL;
334
335         switch (key) {
336         case SR_CONF_SCAN_OPTIONS:
337         case SR_CONF_DEVICE_OPTIONS:
338                 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
339         case SR_CONF_SAMPLERATE:
340                 if (!devc)
341                         return SR_ERR_NA;
342                 *data = std_gvar_samplerates(devc->samplerates, devc->num_samplerates);
343                 return SR_OK;
344         case SR_CONF_TRIGGER_MATCH:
345                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
346                 return SR_OK;
347         case SR_CONF_CAPTURE_RATIO:
348                 *data = std_gvar_array_u64(ARRAY_AND_SIZE(captureratios));
349                 return SR_OK;
350         default:
351                 return SR_ERR_NA;
352         }
353 }
354
355 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
356 {
357         struct dev_context *devc;
358         struct sr_trigger *trigger;
359         struct sr_trigger_stage *stage;
360         struct sr_trigger_match *match;
361         GSList *l;
362         size_t idx;
363         int ret;
364
365         devc = sdi->priv;
366
367         /*
368          * Query triggers, translate the more complex caller spec to
369          * "flat" internal variables, to simplify the construction of
370          * the SETUP packet elsewhere. This driver supports a single
371          * stage, with match conditions for one or multiple channels.
372          */
373         memset(&devc->triggers, 0, sizeof(devc->triggers));
374         trigger = sr_session_trigger_get(sdi->session);
375         if (trigger) {
376                 if (g_slist_length(trigger->stages) > 1)
377                         return SR_ERR_NA;
378                 stage = g_slist_nth_data(trigger->stages, 0);
379                 if (!stage)
380                         return SR_ERR_ARG;
381                 for (l = stage->matches; l; l = l->next) {
382                         match = l->data;
383                         if (!match->match)
384                                 continue;
385                         if (!match->channel->enabled)
386                                 continue;
387                         idx = match->channel->index;
388                         devc->triggers[idx] = match->match;
389                 }
390                 sr_dbg("acq start: trigger specs: %x/%x/%x",
391                         devc->triggers[0], devc->triggers[1],
392                         devc->triggers[2]);
393         }
394         devc->trigpos = trigger ? devc->curr_captureratio_idx : 0;
395
396         /* Have the SETUP packet sent, then poll for the status. */
397         devc->state = STATE_CONF;
398         ret = microchip_pickit2_setup_trigger(sdi);
399         if (ret) {
400                 devc->state = STATE_IDLE;
401                 return ret;
402         }
403         devc->state = STATE_WAIT;
404
405         std_session_send_df_header(sdi);
406         sr_session_source_add(sdi->session, -1, 0, 20,
407                 microchip_pickit2_receive_data, (void *)sdi);
408
409         return SR_OK;
410 }
411
412 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
413 {
414         struct dev_context *devc;
415
416         devc = sdi->priv;
417         if (devc->state < STATE_CONF)
418                 return SR_OK;
419
420         /*
421          * Keep up the acquisition until either data becomes available
422          * (according to the previously configured trigger condition),
423          * or until the user cancels the acquisition by pressing the
424          * device's button. This is a firmware limitation which the
425          * vendor software "suffers from" as well.
426          */
427         if (devc->state == STATE_WAIT) {
428                 sr_err("Cannot terminate by software, need either data trigger or cancel button.");
429                 return SR_OK;
430         }
431
432         if (devc->state > STATE_CONF) {
433                 std_session_send_df_end(sdi);
434         }
435         sr_session_source_remove(sdi->session, -1);
436         devc->state = STATE_IDLE;
437
438         return SR_OK;
439 }
440
441 static struct sr_dev_driver microchip_pickit2_driver_info = {
442         .name = "microchip-pickit2",
443         .longname = PICKIT2_VENDOR_NAME " " PICKIT2_PRODUCT_NAME,
444         .api_version = 1,
445         .init = std_init,
446         .cleanup = std_cleanup,
447         .scan = scan,
448         .dev_list = std_dev_list,
449         .dev_clear = std_dev_clear,
450         .config_get = config_get,
451         .config_set = config_set,
452         .config_list = config_list,
453         .dev_open = dev_open,
454         .dev_close = dev_close,
455         .dev_acquisition_start = dev_acquisition_start,
456         .dev_acquisition_stop = dev_acquisition_stop,
457         .context = NULL,
458 };
459 SR_REGISTER_DEV_DRIVER(microchip_pickit2_driver_info);