]> sigrok.org Git - libsigrok.git/blob - src/hardware/microchip-pickit2/api.c
output/csv: use intermediate time_t var, silence compiler warning
[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         SR_CONF_PROBE_NAMES,
76 };
77
78 static const uint32_t drvopts[] = {
79         SR_CONF_LOGIC_ANALYZER,
80 };
81
82 static const uint32_t devopts[] = {
83         SR_CONF_CONN | SR_CONF_GET,
84         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
85         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
86         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
87         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
88 };
89
90 static const int32_t trigger_matches[] = {
91         SR_TRIGGER_ZERO,
92         SR_TRIGGER_ONE,
93         SR_TRIGGER_RISING,
94         SR_TRIGGER_FALLING,
95 };
96
97 /*
98  * Note that a list of 0, 10, 50, 90, 91, 92, 93, would have been nicer
99  * from a user's perspective, but applications may not support a set of
100  * discrete supported values, and 91+ is as much of a hack to work around
101  * the "0-100%" limitation. So let's map those 0-6 "percent" to the vendor
102  * app's 10/50/90/1W/2W/3W locations.
103  */
104 static const uint64_t captureratios[] = {
105         0, 1, 2, 3, 4, 5, 6,
106 };
107
108 static const uint64_t samplerates[] = {
109         SR_KHZ(5),
110         SR_KHZ(10),
111         SR_KHZ(25),
112         SR_KHZ(50),
113         SR_KHZ(100),
114         SR_KHZ(250),
115         SR_KHZ(500),
116         SR_MHZ(1),
117 };
118
119 static GSList *scan(struct sr_dev_driver *di, GSList *options)
120 {
121         struct drv_context *drvc;
122         const char *conn;
123         const char *probe_names;
124         GSList *l, *devices, *usb_devices;
125         struct sr_config *cfg;
126         struct sr_usb_dev_inst *usb;
127         struct sr_dev_inst *sdi;
128         struct sr_channel_group *cg;
129         size_t ch_count, ch_idx;
130         struct sr_channel *ch;
131         struct dev_context *devc;
132
133         drvc = di->context;
134
135         conn = PICKIT2_DEFAULT_ADDRESS;
136         probe_names = NULL;
137         for (l = options; l; l = l->next) {
138                 cfg = l->data;
139                 switch (cfg->key) {
140                 case SR_CONF_CONN:
141                         conn = g_variant_get_string(cfg->data, NULL);
142                         break;
143                 case SR_CONF_PROBE_NAMES:
144                         probe_names = g_variant_get_string(cfg->data, NULL);
145                         break;
146                 }
147         }
148
149         devices = NULL;
150         usb_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
151         if (!usb_devices)
152                 return NULL;
153
154         for (l = usb_devices; l; l = l->next) {
155                 usb = l->data;
156
157                 /* Create the device instance. */
158                 sdi = g_malloc0(sizeof(*sdi));
159                 devices = g_slist_append(devices, sdi);
160                 sdi->status = SR_ST_INACTIVE;
161                 sdi->vendor = g_strdup(PICKIT2_VENDOR_NAME);
162                 sdi->model = g_strdup(PICKIT2_PRODUCT_NAME);
163                 sdi->inst_type = SR_INST_USB;
164                 sdi->conn = usb;
165                 sdi->connection_id = g_strdup(conn);
166
167                 /*
168                  * Create the device context. Pre-select the highest
169                  * samplerate and the deepest sample count available.
170                  */
171                 devc = g_malloc0(sizeof(*devc));
172                 sdi->priv = devc;
173                 devc->samplerates = samplerates;
174                 devc->num_samplerates = ARRAY_SIZE(samplerates);
175                 devc->curr_samplerate_idx = devc->num_samplerates - 1;
176                 devc->captureratios = captureratios;
177                 devc->num_captureratios = ARRAY_SIZE(captureratios);
178                 devc->curr_captureratio_idx = 0;
179                 devc->sw_limits.limit_samples = PICKIT2_SAMPLE_COUNT;
180                 devc->channel_names = sr_parse_probe_names(probe_names,
181                         channel_names, ARRAY_SIZE(channel_names),
182                         ARRAY_SIZE(channel_names), &ch_count);
183
184                 /* Create the logic channels group. */
185                 cg = sr_channel_group_new(sdi, "Logic", NULL);
186                 for (ch_idx = 0; ch_idx < ch_count; ch_idx++) {
187                         ch = sr_channel_new(sdi, ch_idx, SR_CHANNEL_LOGIC,
188                                 TRUE, devc->channel_names[ch_idx]);
189                         cg->channels = g_slist_append(cg->channels, ch);
190                 }
191         }
192
193         return std_scan_complete(di, devices);
194 }
195
196 static int dev_open(struct sr_dev_inst *sdi)
197 {
198         struct sr_usb_dev_inst *usb;
199         struct dev_context *devc;
200         struct sr_dev_driver *di;
201         struct drv_context *drvc;
202         int ret;
203
204         usb = sdi->conn;
205         devc = sdi->priv;
206         di = sdi->driver;
207         drvc = di->context;
208
209         ret = sr_usb_open(drvc->sr_ctx->libusb_ctx, usb);
210         if (ret < 0)
211                 return SR_ERR;
212
213         if (libusb_kernel_driver_active(usb->devhdl, PICKIT2_USB_INTERFACE) == 1) {
214                 ret = libusb_detach_kernel_driver(usb->devhdl, PICKIT2_USB_INTERFACE);
215                 if (ret < 0) {
216                         sr_err("Canot detach kernel driver: %s.",
217                                 libusb_error_name(ret));
218                         return SR_ERR;
219                 }
220                 devc->detached_kernel_driver = TRUE;
221         }
222
223         ret = libusb_claim_interface(usb->devhdl, PICKIT2_USB_INTERFACE);
224         if (ret < 0) {
225                 sr_err("Cannot claim interface: %s.", libusb_error_name(ret));
226                 return SR_ERR;
227         }
228
229         return SR_OK;
230 }
231
232 static int dev_close(struct sr_dev_inst *sdi)
233 {
234         struct sr_usb_dev_inst *usb;
235         struct dev_context *devc;
236         int ret;
237
238         usb = sdi->conn;
239         devc = sdi->priv;
240
241         if (!usb)
242                 return SR_OK;
243         if (!usb->devhdl)
244                 return SR_OK;
245
246         ret = libusb_release_interface(usb->devhdl, PICKIT2_USB_INTERFACE);
247         if (ret) {
248                 sr_err("Cannot release interface: %s.", libusb_error_name(ret));
249                 return SR_ERR;
250         }
251
252         if (devc->detached_kernel_driver) {
253                 ret = libusb_attach_kernel_driver(usb->devhdl, PICKIT2_USB_INTERFACE);
254                 if (ret) {
255                         sr_err("Cannot attach kernel driver: %s.",
256                                 libusb_error_name(ret));
257                         return SR_ERR;
258                 }
259                 devc->detached_kernel_driver = FALSE;
260         }
261
262         libusb_close(usb->devhdl);
263         sdi->conn = NULL;
264
265         return SR_OK;
266 }
267
268 static int config_get(uint32_t key, GVariant **data,
269         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
270 {
271         struct dev_context *devc;
272         struct sr_usb_dev_inst *usb;
273         uint64_t rate, ratio;
274
275         (void)cg;
276
277         devc = sdi ? sdi->priv : NULL;
278         usb = sdi ? sdi->conn : NULL;
279
280         switch (key) {
281         case SR_CONF_CONN:
282                 if (!usb)
283                         return SR_ERR_ARG;
284                 *data = g_variant_new_printf("%d.%d", usb->bus, usb->address);
285                 return SR_OK;
286         case SR_CONF_SAMPLERATE:
287                 if (!devc)
288                         return SR_ERR_ARG;
289                 rate = devc->samplerates[devc->curr_samplerate_idx];
290                 *data = g_variant_new_uint64(rate);
291                 return SR_OK;
292         case SR_CONF_LIMIT_SAMPLES:
293                 if (!devc)
294                         return SR_ERR_ARG;
295                 return sr_sw_limits_config_get(&devc->sw_limits, key, data);
296         case SR_CONF_CAPTURE_RATIO:
297                 if (!devc)
298                         return SR_ERR_ARG;
299                 ratio = devc->captureratios[devc->curr_captureratio_idx];
300                 *data = g_variant_new_uint64(ratio);
301                 return SR_OK;
302         default:
303                 return SR_ERR_NA;
304         }
305 }
306
307 static int config_set(uint32_t key, GVariant *data,
308         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
309 {
310         struct dev_context *devc;
311         int idx;
312
313         (void)cg;
314
315         devc = sdi ? sdi->priv : NULL;
316
317         switch (key) {
318         case SR_CONF_SAMPLERATE:
319                 if (!devc)
320                         return SR_ERR_ARG;
321                 idx = std_u64_idx(data, devc->samplerates, devc->num_samplerates);
322                 if (idx < 0)
323                         return SR_ERR_ARG;
324                 devc->curr_samplerate_idx = idx;
325                 return SR_OK;
326         case SR_CONF_CAPTURE_RATIO:
327                 if (!devc)
328                         return SR_ERR_ARG;
329                 idx = std_u64_idx(data, devc->captureratios, devc->num_captureratios);
330                 if (idx >= 0)
331                         devc->curr_captureratio_idx = idx;
332                 return SR_OK;
333         case SR_CONF_LIMIT_SAMPLES:
334                 return sr_sw_limits_config_set(&devc->sw_limits, key, data);
335         default:
336                 return SR_ERR_NA;
337         }
338 }
339
340 static int config_list(uint32_t key, GVariant **data,
341         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
342 {
343         struct dev_context *devc;
344
345         devc = sdi ? sdi->priv : NULL;
346
347         switch (key) {
348         case SR_CONF_SCAN_OPTIONS:
349         case SR_CONF_DEVICE_OPTIONS:
350                 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
351         case SR_CONF_SAMPLERATE:
352                 if (!devc)
353                         return SR_ERR_NA;
354                 *data = std_gvar_samplerates(devc->samplerates, devc->num_samplerates);
355                 return SR_OK;
356         case SR_CONF_TRIGGER_MATCH:
357                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
358                 return SR_OK;
359         case SR_CONF_CAPTURE_RATIO:
360                 *data = std_gvar_array_u64(ARRAY_AND_SIZE(captureratios));
361                 return SR_OK;
362         default:
363                 return SR_ERR_NA;
364         }
365 }
366
367 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
368 {
369         struct dev_context *devc;
370         struct sr_trigger *trigger;
371         struct sr_trigger_stage *stage;
372         struct sr_trigger_match *match;
373         GSList *l;
374         size_t idx;
375         int ret;
376
377         devc = sdi->priv;
378
379         /*
380          * Query triggers, translate the more complex caller spec to
381          * "flat" internal variables, to simplify the construction of
382          * the SETUP packet elsewhere. This driver supports a single
383          * stage, with match conditions for one or multiple channels.
384          */
385         memset(&devc->triggers, 0, sizeof(devc->triggers));
386         trigger = sr_session_trigger_get(sdi->session);
387         if (trigger) {
388                 if (g_slist_length(trigger->stages) > 1)
389                         return SR_ERR_NA;
390                 stage = g_slist_nth_data(trigger->stages, 0);
391                 if (!stage)
392                         return SR_ERR_ARG;
393                 for (l = stage->matches; l; l = l->next) {
394                         match = l->data;
395                         if (!match->match)
396                                 continue;
397                         if (!match->channel->enabled)
398                                 continue;
399                         idx = match->channel->index;
400                         devc->triggers[idx] = match->match;
401                 }
402                 sr_dbg("acq start: trigger specs: %x/%x/%x",
403                         devc->triggers[0], devc->triggers[1],
404                         devc->triggers[2]);
405         }
406         devc->trigpos = trigger ? devc->curr_captureratio_idx : 0;
407
408         /* Have the SETUP packet sent, then poll for the status. */
409         devc->state = STATE_CONF;
410         ret = microchip_pickit2_setup_trigger(sdi);
411         if (ret) {
412                 devc->state = STATE_IDLE;
413                 return ret;
414         }
415         devc->state = STATE_WAIT;
416
417         std_session_send_df_header(sdi);
418         sr_session_source_add(sdi->session, -1, 0, 20,
419                 microchip_pickit2_receive_data, (void *)sdi);
420
421         return SR_OK;
422 }
423
424 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
425 {
426         struct dev_context *devc;
427
428         devc = sdi->priv;
429         if (devc->state < STATE_CONF)
430                 return SR_OK;
431
432         /*
433          * Keep up the acquisition until either data becomes available
434          * (according to the previously configured trigger condition),
435          * or until the user cancels the acquisition by pressing the
436          * device's button. This is a firmware limitation which the
437          * vendor software "suffers from" as well.
438          */
439         if (devc->state == STATE_WAIT) {
440                 sr_err("Cannot terminate by software, need either data trigger or cancel button.");
441                 return SR_OK;
442         }
443
444         if (devc->state > STATE_CONF) {
445                 std_session_send_df_end(sdi);
446         }
447         sr_session_source_remove(sdi->session, -1);
448         devc->state = STATE_IDLE;
449
450         return SR_OK;
451 }
452
453 static struct sr_dev_driver microchip_pickit2_driver_info = {
454         .name = "microchip-pickit2",
455         .longname = PICKIT2_VENDOR_NAME " " PICKIT2_PRODUCT_NAME,
456         .api_version = 1,
457         .init = std_init,
458         .cleanup = std_cleanup,
459         .scan = scan,
460         .dev_list = std_dev_list,
461         .dev_clear = std_dev_clear,
462         .config_get = config_get,
463         .config_set = config_set,
464         .config_list = config_list,
465         .dev_open = dev_open,
466         .dev_close = dev_close,
467         .dev_acquisition_start = dev_acquisition_start,
468         .dev_acquisition_stop = dev_acquisition_stop,
469         .context = NULL,
470 };
471 SR_REGISTER_DEV_DRIVER(microchip_pickit2_driver_info);