]> sigrok.org Git - libsigrok.git/blob - src/hwdriver.c
Don't set _POSIX_C_SOURCE for VXI/RPC related files.
[libsigrok.git] / src / hwdriver.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.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
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <dirent.h>
24 #include <string.h>
25 #include <glib.h>
26 #include "config.h" /* Needed for HAVE_LIBUSB_1_0 and others. */
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29
30 /** @cond PRIVATE */
31 #define LOG_PREFIX "hwdriver"
32 /** @endcond */
33
34 /**
35  * @file
36  *
37  * Hardware driver handling in libsigrok.
38  */
39
40 /**
41  * @defgroup grp_driver Hardware drivers
42  *
43  * Hardware driver handling in libsigrok.
44  *
45  * @{
46  */
47
48 /* Please use the same order/grouping as in enum sr_configkey (libsigrok.h). */
49 static struct sr_key_info sr_key_info_config[] = {
50         /* Device classes */
51         {SR_CONF_LOGIC_ANALYZER, SR_T_STRING, NULL, "Logic analyzer", NULL},
52         {SR_CONF_OSCILLOSCOPE, SR_T_STRING, NULL, "Oscilloscope", NULL},
53         {SR_CONF_MULTIMETER, SR_T_STRING, NULL, "Multimeter", NULL},
54         {SR_CONF_DEMO_DEV, SR_T_STRING, NULL, "Demo device", NULL},
55         {SR_CONF_SOUNDLEVELMETER, SR_T_STRING, NULL, "Sound level meter", NULL},
56         {SR_CONF_THERMOMETER, SR_T_STRING, NULL, "Thermometer", NULL},
57         {SR_CONF_HYGROMETER, SR_T_STRING, NULL, "Hygrometer", NULL},
58         {SR_CONF_ENERGYMETER, SR_T_STRING, NULL, "Energy meter", NULL},
59         {SR_CONF_DEMODULATOR, SR_T_STRING, NULL, "Demodulator", NULL},
60         {SR_CONF_POWER_SUPPLY, SR_T_STRING, NULL, "Power supply", NULL},
61         {SR_CONF_LCRMETER, SR_T_STRING, NULL, "LCR meter", NULL},
62         {SR_CONF_ELECTRONIC_LOAD, SR_T_STRING, NULL, "Electronic load", NULL},
63         {SR_CONF_SCALE, SR_T_STRING, NULL, "Scale", NULL},
64
65         /* Driver scan options */
66         {SR_CONF_CONN, SR_T_STRING, "conn",
67                 "Connection", NULL},
68         {SR_CONF_SERIALCOMM, SR_T_STRING, "serialcomm",
69                 "Serial communication", NULL},
70         {SR_CONF_MODBUSADDR, SR_T_UINT64, "modbusaddr",
71                 "Modbus slave address", NULL},
72
73         /* Device (or channel group) configuration */
74         {SR_CONF_SAMPLERATE, SR_T_UINT64, "samplerate",
75                 "Sample rate", NULL},
76         {SR_CONF_CAPTURE_RATIO, SR_T_UINT64, "captureratio",
77                 "Pre-trigger capture ratio", NULL},
78         {SR_CONF_PATTERN_MODE, SR_T_STRING, "pattern",
79                 "Pattern", NULL},
80         {SR_CONF_RLE, SR_T_BOOL, "rle",
81                 "Run length encoding", NULL},
82         {SR_CONF_TRIGGER_SLOPE, SR_T_STRING, "triggerslope",
83                 "Trigger slope", NULL},
84         {SR_CONF_AVERAGING, SR_T_BOOL, "averaging",
85                 "Averaging", NULL},
86         {SR_CONF_AVG_SAMPLES, SR_T_UINT64, "avg_samples",
87                 "Number of samples to average over", NULL},
88         {SR_CONF_TRIGGER_SOURCE, SR_T_STRING, "triggersource",
89                 "Trigger source", NULL},
90         {SR_CONF_HORIZ_TRIGGERPOS, SR_T_FLOAT, "horiz_triggerpos",
91                 "Horizontal trigger position", NULL},
92         {SR_CONF_BUFFERSIZE, SR_T_UINT64, "buffersize",
93                 "Buffer size", NULL},
94         {SR_CONF_TIMEBASE, SR_T_RATIONAL_PERIOD, "timebase",
95                 "Time base", NULL},
96         {SR_CONF_FILTER, SR_T_BOOL, "filter",
97                 "Filter", NULL},
98         {SR_CONF_VDIV, SR_T_RATIONAL_VOLT, "vdiv",
99                 "Volts/div", NULL},
100         {SR_CONF_COUPLING, SR_T_STRING, "coupling",
101                 "Coupling", NULL},
102         {SR_CONF_TRIGGER_MATCH, SR_T_INT32, "triggermatch",
103                 "Trigger matches", NULL},
104         {SR_CONF_SAMPLE_INTERVAL, SR_T_UINT64, "sample_interval",
105                 "Sample interval", NULL},
106         {SR_CONF_NUM_HDIV, SR_T_INT32, "num_hdiv",
107                 "Number of horizontal divisions", NULL},
108         {SR_CONF_NUM_VDIV, SR_T_INT32, "num_vdiv",
109                 "Number of vertical divisions", NULL},
110         {SR_CONF_SPL_WEIGHT_FREQ, SR_T_STRING, "spl_weight_freq",
111                 "Sound pressure level frequency weighting", NULL},
112         {SR_CONF_SPL_WEIGHT_TIME, SR_T_STRING, "spl_weight_time",
113                 "Sound pressure level time weighting", NULL},
114         {SR_CONF_SPL_MEASUREMENT_RANGE, SR_T_UINT64_RANGE, "spl_meas_range",
115                 "Sound pressure level measurement range", NULL},
116         {SR_CONF_HOLD_MAX, SR_T_BOOL, "hold_max",
117                 "Hold max", NULL},
118         {SR_CONF_HOLD_MIN, SR_T_BOOL, "hold_min",
119                 "Hold min", NULL},
120         {SR_CONF_VOLTAGE_THRESHOLD, SR_T_DOUBLE_RANGE, "voltage_threshold",
121                 "Voltage threshold", NULL },
122         {SR_CONF_EXTERNAL_CLOCK, SR_T_BOOL, "external_clock",
123                 "External clock mode", NULL},
124         {SR_CONF_SWAP, SR_T_BOOL, "swap",
125                 "Swap channel order", NULL},
126         {SR_CONF_CENTER_FREQUENCY, SR_T_UINT64, "center_frequency",
127                 "Center frequency", NULL},
128         {SR_CONF_NUM_LOGIC_CHANNELS, SR_T_INT32, "logic_channels",
129                 "Number of logic channels", NULL},
130         {SR_CONF_NUM_ANALOG_CHANNELS, SR_T_INT32, "analog_channels",
131                 "Number of analog channels", NULL},
132         {SR_CONF_VOLTAGE, SR_T_FLOAT, "voltage",
133                 "Current voltage", NULL},
134         {SR_CONF_VOLTAGE_TARGET, SR_T_FLOAT, "voltage_target",
135                 "Voltage target", NULL},
136         {SR_CONF_CURRENT, SR_T_FLOAT, "current",
137                 "Current current", NULL},
138         {SR_CONF_CURRENT_LIMIT, SR_T_FLOAT, "current_limit",
139                 "Current limit", NULL},
140         {SR_CONF_ENABLED, SR_T_BOOL, "enabled",
141                 "Channel enabled", NULL},
142         {SR_CONF_CHANNEL_CONFIG, SR_T_STRING, "channel_config",
143                 "Channel modes", NULL},
144         {SR_CONF_OVER_VOLTAGE_PROTECTION_ENABLED, SR_T_BOOL, "ovp_enabled",
145                 "Over-voltage protection enabled", NULL},
146         {SR_CONF_OVER_VOLTAGE_PROTECTION_ACTIVE, SR_T_BOOL, "ovp_active",
147                 "Over-voltage protection active", NULL},
148         {SR_CONF_OVER_VOLTAGE_PROTECTION_THRESHOLD, SR_T_FLOAT, "ovp_threshold",
149                 "Over-voltage protection threshold", NULL},
150         {SR_CONF_OVER_CURRENT_PROTECTION_ENABLED, SR_T_BOOL, "ocp_enabled",
151                 "Over-current protection enabled", NULL},
152         {SR_CONF_OVER_CURRENT_PROTECTION_ACTIVE, SR_T_BOOL, "ocp_active",
153                 "Over-current protection active", NULL},
154         {SR_CONF_OVER_CURRENT_PROTECTION_THRESHOLD, SR_T_FLOAT, "ocp_threshold",
155                 "Over-current protection threshold", NULL},
156         {SR_CONF_CLOCK_EDGE, SR_T_STRING, "clock_edge",
157                 "Clock edge", NULL},
158         {SR_CONF_AMPLITUDE, SR_T_FLOAT, "amplitude",
159                 "Amplitude", NULL},
160         {SR_CONF_REGULATION, SR_T_STRING, "regulation",
161                 "Channel regulation", NULL},
162         {SR_CONF_OVER_TEMPERATURE_PROTECTION, SR_T_BOOL, "otp",
163                 "Over-temperature protection", NULL},
164         {SR_CONF_OUTPUT_FREQUENCY, SR_T_FLOAT, "output_frequency",
165                 "Output frequency", NULL},
166         {SR_CONF_OUTPUT_FREQUENCY_TARGET, SR_T_FLOAT, "output_frequency_target",
167                 "Output frequency target", NULL},
168         {SR_CONF_MEASURED_QUANTITY, SR_T_STRING, "measured_quantity",
169                 "Measured quantity", NULL},
170         {SR_CONF_MEASURED_2ND_QUANTITY, SR_T_STRING, "measured_2nd_quantity",
171                 "Measured secondary quantity", NULL},
172         {SR_CONF_EQUIV_CIRCUIT_MODEL, SR_T_STRING, "equiv_circuit_model",
173                 "Equivalent circuit model", NULL},
174         {SR_CONF_OVER_TEMPERATURE_PROTECTION_ACTIVE, SR_T_BOOL, "otp_active",
175                 "Over-temperature protection active", NULL},
176
177         /* Special stuff */
178         {SR_CONF_SCAN_OPTIONS, SR_T_STRING, "scan_options",
179                 "Scan options", NULL},
180         {SR_CONF_DEVICE_OPTIONS, SR_T_STRING, "device_options",
181                 "Device options", NULL},
182         {SR_CONF_SESSIONFILE, SR_T_STRING, "sessionfile",
183                 "Session file", NULL},
184         {SR_CONF_CAPTUREFILE, SR_T_STRING, "capturefile",
185                 "Capture file", NULL},
186         {SR_CONF_CAPTURE_UNITSIZE, SR_T_UINT64, "capture_unitsize",
187                 "Capture unitsize", NULL},
188         {SR_CONF_POWER_OFF, SR_T_BOOL, "power_off",
189                 "Power off", NULL},
190         {SR_CONF_DATA_SOURCE, SR_T_STRING, "data_source",
191                 "Data source", NULL},
192         {SR_CONF_PROBE_FACTOR, SR_T_UINT64, "probe_factor",
193                 "Probe factor", NULL},
194
195         /* Acquisition modes, sample limiting */
196         {SR_CONF_LIMIT_MSEC, SR_T_UINT64, "limit_time",
197                 "Time limit", NULL},
198         {SR_CONF_LIMIT_SAMPLES, SR_T_UINT64, "limit_samples",
199                 "Sample limit", NULL},
200         {SR_CONF_LIMIT_FRAMES, SR_T_UINT64, "limit_frames",
201                 "Frame limit", NULL},
202         {SR_CONF_CONTINUOUS, SR_T_UINT64, "continuous",
203                 "Continuous sampling", NULL},
204         {SR_CONF_DATALOG, SR_T_BOOL, "datalog",
205                 "Datalog", NULL},
206         {SR_CONF_DEVICE_MODE, SR_T_STRING, "device_mode",
207                 "Device mode", NULL},
208         {SR_CONF_TEST_MODE, SR_T_STRING, "test_mode",
209                 "Test mode", NULL},
210
211         {0, 0, NULL, NULL, NULL},
212 };
213
214 /* Please use the same order as in enum sr_mq (libsigrok.h). */
215 static struct sr_key_info sr_key_info_mq[] = {
216         {SR_MQ_VOLTAGE, 0, "voltage", "Voltage", NULL},
217         {SR_MQ_CURRENT, 0, "current", "Current", NULL},
218         {SR_MQ_RESISTANCE, 0, "resistance", "Resistance", NULL},
219         {SR_MQ_CAPACITANCE, 0, "capacitance", "Capacitance", NULL},
220         {SR_MQ_TEMPERATURE, 0, "temperature", "Temperature", NULL},
221         {SR_MQ_FREQUENCY, 0, "frequency", "Frequency", NULL},
222         {SR_MQ_DUTY_CYCLE, 0, "duty_cycle", "Duty cycle", NULL},
223         {SR_MQ_CONTINUITY, 0, "continuity", "Continuity", NULL},
224         {SR_MQ_PULSE_WIDTH, 0, "pulse_width", "Pulse width", NULL},
225         {SR_MQ_CONDUCTANCE, 0, "conductance", "Conductance", NULL},
226         {SR_MQ_POWER, 0, "power", "Power", NULL},
227         {SR_MQ_GAIN, 0, "gain", "Gain", NULL},
228         {SR_MQ_SOUND_PRESSURE_LEVEL, 0, "spl", "Sound pressure level", NULL},
229         {SR_MQ_CARBON_MONOXIDE, 0, "co", "Carbon monoxide", NULL},
230         {SR_MQ_RELATIVE_HUMIDITY, 0, "rh", "Relative humidity", NULL},
231         {SR_MQ_TIME, 0, "time", "Time", NULL},
232         {SR_MQ_WIND_SPEED, 0, "wind_speed", "Wind speed", NULL},
233         {SR_MQ_PRESSURE, 0, "pressure", "Pressure", NULL},
234         {SR_MQ_PARALLEL_INDUCTANCE, 0, "parallel_inductance", "Parallel inductance", NULL},
235         {SR_MQ_PARALLEL_CAPACITANCE, 0, "parallel_capacitance", "Parallel capacitance", NULL},
236         {SR_MQ_PARALLEL_RESISTANCE, 0, "parallel_resistance", "Parallel resistance", NULL},
237         {SR_MQ_SERIES_INDUCTANCE, 0, "series_inductance", "Series inductance", NULL},
238         {SR_MQ_SERIES_CAPACITANCE, 0, "series_capacitance", "Series capacitance", NULL},
239         {SR_MQ_SERIES_RESISTANCE, 0, "series_resistance", "Series resistance", NULL},
240         {SR_MQ_DISSIPATION_FACTOR, 0, "dissipation_factor", "Dissipation factor", NULL},
241         {SR_MQ_QUALITY_FACTOR, 0, "quality_factor", "Quality factor", NULL},
242         {SR_MQ_PHASE_ANGLE, 0, "phase_angle", "Phase angle", NULL},
243         {SR_MQ_DIFFERENCE, 0, "difference", "Difference", NULL},
244         {SR_MQ_COUNT, 0, "count", "Count", NULL},
245         {SR_MQ_POWER_FACTOR, 0, "power_factor", "Power factor", NULL},
246         {SR_MQ_APPARENT_POWER, 0, "apparent_power", "Apparent power", NULL},
247         {SR_MQ_MASS, 0, "mass", "Mass", NULL},
248         ALL_ZERO
249 };
250
251 /* Please use the same order as in enum sr_mqflag (libsigrok.h). */
252 static struct sr_key_info sr_key_info_mqflag[] = {
253         {SR_MQFLAG_AC, 0, "ac", "AC", NULL},
254         {SR_MQFLAG_DC, 0, "dc", "DC", NULL},
255         {SR_MQFLAG_RMS, 0, "rms", "RMS", NULL},
256         {SR_MQFLAG_DIODE, 0, "diode", "Diode", NULL},
257         {SR_MQFLAG_HOLD, 0, "hold", "Hold", NULL},
258         {SR_MQFLAG_MAX, 0, "max", "Max", NULL},
259         {SR_MQFLAG_MIN, 0, "min", "Min", NULL},
260         {SR_MQFLAG_AUTORANGE, 0, "auto_range", "Auto range", NULL},
261         {SR_MQFLAG_RELATIVE, 0, "relative", "Relative", NULL},
262         {SR_MQFLAG_SPL_FREQ_WEIGHT_A, 0, "spl_freq_weight_a",
263                 "Frequency weighted (A)", NULL},
264         {SR_MQFLAG_SPL_FREQ_WEIGHT_C, 0, "spl_freq_weight_c",
265                 "Frequency weighted (C)", NULL},
266         {SR_MQFLAG_SPL_FREQ_WEIGHT_Z, 0, "spl_freq_weight_z",
267                 "Frequency weighted (Z)", NULL},
268         {SR_MQFLAG_SPL_FREQ_WEIGHT_FLAT, 0, "spl_freq_weight_flat",
269                 "Frequency weighted (flat)", NULL},
270         {SR_MQFLAG_SPL_TIME_WEIGHT_S, 0, "spl_time_weight_s",
271                 "Time weighted (S)", NULL},
272         {SR_MQFLAG_SPL_TIME_WEIGHT_F, 0, "spl_time_weight_f",
273                 "Time weighted (F)", NULL},
274         {SR_MQFLAG_SPL_LAT, 0, "spl_time_average", "Time-averaged (LEQ)", NULL},
275         {SR_MQFLAG_SPL_PCT_OVER_ALARM, 0, "spl_pct_over_alarm",
276                 "Percentage over alarm", NULL},
277         {SR_MQFLAG_DURATION, 0, "duration", "Duration", NULL},
278         {SR_MQFLAG_AVG, 0, "average", "Average", NULL},
279         {SR_MQFLAG_REFERENCE, 0, "reference", "Reference", NULL},
280         {SR_MQFLAG_UNSTABLE, 0, "unstable", "Unstable", NULL},
281         ALL_ZERO
282 };
283
284 /* This must handle all the keys from enum sr_datatype (libsigrok.h). */
285 SR_PRIV const GVariantType *sr_variant_type_get(int datatype)
286 {
287         switch (datatype) {
288         case SR_T_INT32:
289                 return G_VARIANT_TYPE_INT32;
290         case SR_T_UINT64:
291                 return G_VARIANT_TYPE_UINT64;
292         case SR_T_STRING:
293                 return G_VARIANT_TYPE_STRING;
294         case SR_T_BOOL:
295                 return G_VARIANT_TYPE_BOOLEAN;
296         case SR_T_FLOAT:
297                 return G_VARIANT_TYPE_DOUBLE;
298         case SR_T_RATIONAL_PERIOD:
299         case SR_T_RATIONAL_VOLT:
300         case SR_T_UINT64_RANGE:
301         case SR_T_DOUBLE_RANGE:
302                 return G_VARIANT_TYPE_TUPLE;
303         case SR_T_KEYVALUE:
304                 return G_VARIANT_TYPE_DICTIONARY;
305         case SR_T_MQLIST:
306                 return G_VARIANT_TYPE_ARRAY;
307         default:
308                 return NULL;
309         }
310 }
311
312 SR_PRIV int sr_variant_type_check(uint32_t key, GVariant *value)
313 {
314         const struct sr_key_info *info;
315         const GVariantType *type, *expected;
316         char *expected_string, *type_string;
317
318         info = sr_key_info_get(SR_KEY_CONFIG, key);
319         if (!info)
320                 return SR_OK;
321
322         expected = sr_variant_type_get(info->datatype);
323         type = g_variant_get_type(value);
324         if (!g_variant_type_equal(type, expected)
325                         && !g_variant_type_is_subtype_of(type, expected)) {
326                 expected_string = g_variant_type_dup_string(expected);
327                 type_string = g_variant_type_dup_string(type);
328                 sr_err("Wrong variant type for key '%s': expected '%s', got '%s'",
329                         info->name, expected_string, type_string);
330                 g_free(expected_string);
331                 g_free(type_string);
332                 return SR_ERR_ARG;
333         }
334
335         return SR_OK;
336 }
337
338 /**
339  * Return the list of supported hardware drivers.
340  *
341  * @param[in] ctx Pointer to a libsigrok context struct. Must not be NULL.
342  *
343  * @retval NULL The ctx argument was NULL, or there are no supported drivers.
344  * @retval Other Pointer to the NULL-terminated list of hardware drivers.
345  *               The user should NOT g_free() this list, sr_exit() will do that.
346  *
347  * @since 0.4.0
348  */
349 SR_API struct sr_dev_driver **sr_driver_list(const struct sr_context *ctx)
350 {
351         if (!ctx)
352                 return NULL;
353
354         return ctx->driver_list;
355 }
356
357 /**
358  * Initialize a hardware driver.
359  *
360  * This usually involves memory allocations and variable initializations
361  * within the driver, but _not_ scanning for attached devices.
362  * The API call sr_driver_scan() is used for that.
363  *
364  * @param ctx A libsigrok context object allocated by a previous call to
365  *            sr_init(). Must not be NULL.
366  * @param driver The driver to initialize. This must be a pointer to one of
367  *               the entries returned by sr_driver_list(). Must not be NULL.
368  *
369  * @retval SR_OK Success
370  * @retval SR_ERR_ARG Invalid parameter(s).
371  * @retval SR_ERR_BUG Internal errors.
372  * @retval other Another negative error code upon other errors.
373  *
374  * @since 0.2.0
375  */
376 SR_API int sr_driver_init(struct sr_context *ctx, struct sr_dev_driver *driver)
377 {
378         int ret;
379
380         if (!ctx) {
381                 sr_err("Invalid libsigrok context, can't initialize.");
382                 return SR_ERR_ARG;
383         }
384
385         if (!driver) {
386                 sr_err("Invalid driver, can't initialize.");
387                 return SR_ERR_ARG;
388         }
389
390         sr_spew("Initializing driver '%s'.", driver->name);
391         if ((ret = driver->init(driver, ctx)) < 0)
392                 sr_err("Failed to initialize the driver: %d.", ret);
393
394         return ret;
395 }
396
397 static int check_options(struct sr_dev_driver *driver, GSList *options,
398                 uint32_t optlist_key, struct sr_dev_inst *sdi,
399                 struct sr_channel_group *cg)
400 {
401         struct sr_config *src;
402         const struct sr_key_info *srci;
403         GVariant *gvar_opts;
404         GSList *l;
405         const uint32_t *opts;
406         gsize num_opts, i;
407         int ret;
408
409         if (sr_config_list(driver, sdi, cg, optlist_key, &gvar_opts) != SR_OK) {
410                 /* Driver publishes no options for this optlist. */
411                 return SR_ERR;
412         }
413
414         ret = SR_OK;
415         opts = g_variant_get_fixed_array(gvar_opts, &num_opts, sizeof(uint32_t));
416         for (l = options; l; l = l->next) {
417                 src = l->data;
418                 for (i = 0; i < num_opts; i++) {
419                         if (opts[i] == src->key)
420                                 break;
421                 }
422                 if (i == num_opts) {
423                         if (!(srci = sr_key_info_get(SR_KEY_CONFIG, src->key)))
424                                 /* Shouldn't happen. */
425                                 sr_err("Invalid option %d.", src->key);
426                         else
427                                 sr_err("Invalid option '%s'.", srci->id);
428                         ret = SR_ERR_ARG;
429                         break;
430                 }
431                 if (sr_variant_type_check(src->key, src->data) != SR_OK) {
432                         ret = SR_ERR_ARG;
433                         break;
434                 }
435         }
436         g_variant_unref(gvar_opts);
437
438         return ret;
439 }
440
441 /**
442  * Tell a hardware driver to scan for devices.
443  *
444  * In addition to the detection, the devices that are found are also
445  * initialized automatically. On some devices, this involves a firmware upload,
446  * or other such measures.
447  *
448  * The order in which the system is scanned for devices is not specified. The
449  * caller should not assume or rely on any specific order.
450  *
451  * Before calling sr_driver_scan(), the user must have previously initialized
452  * the driver by calling sr_driver_init().
453  *
454  * @param driver The driver that should scan. This must be a pointer to one of
455  *               the entries returned by sr_driver_list(). Must not be NULL.
456  * @param options A list of 'struct sr_hwopt' options to pass to the driver's
457  *                scanner. Can be NULL/empty.
458  *
459  * @return A GSList * of 'struct sr_dev_inst', or NULL if no devices were
460  *         found (or errors were encountered). This list must be freed by the
461  *         caller using g_slist_free(), but without freeing the data pointed
462  *         to in the list.
463  *
464  * @since 0.2.0
465  */
466 SR_API GSList *sr_driver_scan(struct sr_dev_driver *driver, GSList *options)
467 {
468         GSList *l;
469
470         if (!driver) {
471                 sr_err("Invalid driver, can't scan for devices.");
472                 return NULL;
473         }
474
475         if (!driver->context) {
476                 sr_err("Driver not initialized, can't scan for devices.");
477                 return NULL;
478         }
479
480         if (options) {
481                 if (check_options(driver, options, SR_CONF_SCAN_OPTIONS, NULL, NULL) != SR_OK)
482                         return NULL;
483         }
484
485         l = driver->scan(driver, options);
486
487         sr_spew("Scan of '%s' found %d devices.", driver->name,
488                 g_slist_length(l));
489
490         return l;
491 }
492
493 /**
494  * Call driver cleanup function for all drivers.
495  *
496  * @param[in] ctx Pointer to a libsigrok context struct. Must not be NULL.
497  *
498  * @private
499  */
500 SR_PRIV void sr_hw_cleanup_all(const struct sr_context *ctx)
501 {
502         int i;
503         struct sr_dev_driver **drivers;
504
505         if (!ctx)
506                 return;
507
508         drivers = sr_driver_list(ctx);
509         for (i = 0; drivers[i]; i++) {
510                 if (drivers[i]->cleanup)
511                         drivers[i]->cleanup(drivers[i]);
512                 drivers[i]->context = NULL;
513         }
514 }
515
516 /** Allocate struct sr_config.
517  *  A floating reference can be passed in for data.
518  *  @private
519  */
520 SR_PRIV struct sr_config *sr_config_new(uint32_t key, GVariant *data)
521 {
522         struct sr_config *src;
523
524         src = g_malloc0(sizeof(struct sr_config));
525         src->key = key;
526         src->data = g_variant_ref_sink(data);
527
528         return src;
529 }
530
531 /** Free struct sr_config.
532  *  @private
533  */
534 SR_PRIV void sr_config_free(struct sr_config *src)
535 {
536
537         if (!src || !src->data) {
538                 sr_err("%s: invalid data!", __func__);
539                 return;
540         }
541
542         g_variant_unref(src->data);
543         g_free(src);
544
545 }
546
547 static void log_key(const struct sr_dev_inst *sdi,
548         const struct sr_channel_group *cg, uint32_t key, int op, GVariant *data)
549 {
550         const char *opstr;
551         const struct sr_key_info *srci;
552
553         /* Don't log SR_CONF_DEVICE_OPTIONS, it's verbose and not too useful. */
554         if (key == SR_CONF_DEVICE_OPTIONS)
555                 return;
556
557         opstr = op == SR_CONF_GET ? "get" : op == SR_CONF_SET ? "set" : "list";
558         srci = sr_key_info_get(SR_KEY_CONFIG, key);
559
560         sr_spew("sr_config_%s(): key %d (%s) sdi %p cg %s -> %s", opstr, key,
561                 srci ? srci->id : "NULL", sdi, cg ? cg->name : "NULL",
562                 data ? g_variant_print(data, TRUE) : "NULL");
563 }
564
565 static int check_key(const struct sr_dev_driver *driver,
566                 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg,
567                 uint32_t key, int op, GVariant *data)
568 {
569         const struct sr_key_info *srci;
570         gsize num_opts, i;
571         GVariant *gvar_opts;
572         const uint32_t *opts;
573         uint32_t pub_opt;
574         char *suffix, *opstr;
575
576         if (sdi && cg)
577                 suffix = " for this device and channel group";
578         else if (sdi)
579                 suffix = " for this device";
580         else
581                 suffix = "";
582
583         if (!(srci = sr_key_info_get(SR_KEY_CONFIG, key))) {
584                 sr_err("Invalid key %d.", key);
585                 return SR_ERR_ARG;
586         }
587         opstr = op == SR_CONF_GET ? "get" : op == SR_CONF_SET ? "set" : "list";
588
589         switch (key) {
590         case SR_CONF_LIMIT_MSEC:
591         case SR_CONF_LIMIT_SAMPLES:
592         case SR_CONF_SAMPLERATE:
593                 /* Setting any of these to 0 is not useful. */
594                 if (op != SR_CONF_SET || !data)
595                         break;
596                 if (g_variant_get_uint64(data) == 0) {
597                         sr_err("Cannot set '%s' to 0.", srci->id);
598                         return SR_ERR_ARG;
599                 }
600                 break;
601         }
602
603         if (sr_config_list(driver, sdi, cg, SR_CONF_DEVICE_OPTIONS, &gvar_opts) != SR_OK) {
604                 /* Driver publishes no options. */
605                 sr_err("No options available%s.", srci->id, suffix);
606                 return SR_ERR_ARG;
607         }
608         opts = g_variant_get_fixed_array(gvar_opts, &num_opts, sizeof(uint32_t));
609         pub_opt = 0;
610         for (i = 0; i < num_opts; i++) {
611                 if ((opts[i] & SR_CONF_MASK) == key) {
612                         pub_opt = opts[i];
613                         break;
614                 }
615         }
616         g_variant_unref(gvar_opts);
617         if (!pub_opt) {
618                 sr_err("Option '%s' not available%s.", srci->id, suffix);
619                 return SR_ERR_ARG;
620         }
621
622         if (!(pub_opt & op)) {
623                 sr_err("Option '%s' not available to %s%s.", srci->id, opstr, suffix);
624                 return SR_ERR_ARG;
625         }
626
627         return SR_OK;
628 }
629
630 /**
631  * Query value of a configuration key at the given driver or device instance.
632  *
633  * @param[in] driver The sr_dev_driver struct to query.
634  * @param[in] sdi (optional) If the key is specific to a device, this must
635  *            contain a pointer to the struct sr_dev_inst to be checked.
636  *            Otherwise it must be NULL.
637  * @param[in] cg The channel group on the device for which to list the
638  *                    values, or NULL.
639  * @param[in] key The configuration key (SR_CONF_*).
640  * @param[in,out] data Pointer to a GVariant where the value will be stored.
641  *             Must not be NULL. The caller is given ownership of the GVariant
642  *             and must thus decrease the refcount after use. However if
643  *             this function returns an error code, the field should be
644  *             considered unused, and should not be unreferenced.
645  *
646  * @retval SR_OK Success.
647  * @retval SR_ERR Error.
648  * @retval SR_ERR_ARG The driver doesn't know that key, but this is not to be
649  *          interpreted as an error by the caller; merely as an indication
650  *          that it's not applicable.
651  *
652  * @since 0.3.0
653  */
654 SR_API int sr_config_get(const struct sr_dev_driver *driver,
655                 const struct sr_dev_inst *sdi,
656                 const struct sr_channel_group *cg,
657                 uint32_t key, GVariant **data)
658 {
659         int ret;
660
661         if (!driver || !data)
662                 return SR_ERR;
663
664         if (!driver->config_get)
665                 return SR_ERR_ARG;
666
667         if (check_key(driver, sdi, cg, key, SR_CONF_GET, NULL) != SR_OK)
668                 return SR_ERR_ARG;
669
670         if ((ret = driver->config_get(key, data, sdi, cg)) == SR_OK) {
671                 log_key(sdi, cg, key, SR_CONF_GET, *data);
672                 /* Got a floating reference from the driver. Sink it here,
673                  * caller will need to unref when done with it. */
674                 g_variant_ref_sink(*data);
675         }
676
677         return ret;
678 }
679
680 /**
681  * Set value of a configuration key in a device instance.
682  *
683  * @param[in] sdi The device instance.
684  * @param[in] cg The channel group on the device for which to list the
685  *                    values, or NULL.
686  * @param[in] key The configuration key (SR_CONF_*).
687  * @param data The new value for the key, as a GVariant with GVariantType
688  *        appropriate to that key. A floating reference can be passed
689  *        in; its refcount will be sunk and unreferenced after use.
690  *
691  * @retval SR_OK Success.
692  * @retval SR_ERR Error.
693  * @retval SR_ERR_ARG The driver doesn't know that key, but this is not to be
694  *          interpreted as an error by the caller; merely as an indication
695  *          that it's not applicable.
696  *
697  * @since 0.3.0
698  */
699 SR_API int sr_config_set(const struct sr_dev_inst *sdi,
700                 const struct sr_channel_group *cg,
701                 uint32_t key, GVariant *data)
702 {
703         int ret;
704
705         g_variant_ref_sink(data);
706
707         if (!sdi || !sdi->driver || !data)
708                 ret = SR_ERR;
709         else if (!sdi->driver->config_set)
710                 ret = SR_ERR_ARG;
711         else if (check_key(sdi->driver, sdi, cg, key, SR_CONF_SET, data) != SR_OK)
712                 return SR_ERR_ARG;
713         else if ((ret = sr_variant_type_check(key, data)) == SR_OK) {
714                 log_key(sdi, cg, key, SR_CONF_SET, data);
715                 ret = sdi->driver->config_set(key, data, sdi, cg);
716         }
717
718         g_variant_unref(data);
719
720         return ret;
721 }
722
723 /**
724  * Apply configuration settings to the device hardware.
725  *
726  * @param sdi The device instance.
727  *
728  * @return SR_OK upon success or SR_ERR in case of error.
729  *
730  * @since 0.3.0
731  */
732 SR_API int sr_config_commit(const struct sr_dev_inst *sdi)
733 {
734         int ret;
735
736         if (!sdi || !sdi->driver)
737                 ret = SR_ERR;
738         else if (!sdi->driver->config_commit)
739                 ret = SR_OK;
740         else
741                 ret = sdi->driver->config_commit(sdi);
742
743         return ret;
744 }
745
746 /**
747  * List all possible values for a configuration key.
748  *
749  * @param[in] driver The sr_dev_driver struct to query.
750  * @param[in] sdi (optional) If the key is specific to a device, this must
751  *            contain a pointer to the struct sr_dev_inst to be checked.
752  * @param[in] cg The channel group on the device for which to list the
753  *                    values, or NULL.
754  * @param[in] key The configuration key (SR_CONF_*).
755  * @param[in,out] data A pointer to a GVariant where the list will be stored.
756  *             The caller is given ownership of the GVariant and must thus
757  *             unref the GVariant after use. However if this function
758  *             returns an error code, the field should be considered
759  *             unused, and should not be unreferenced.
760  *
761  * @retval SR_OK Success.
762  * @retval SR_ERR Error.
763  * @retval SR_ERR_ARG The driver doesn't know that key, but this is not to be
764  *          interpreted as an error by the caller; merely as an indication
765  *          that it's not applicable.
766  *
767  * @since 0.3.0
768  */
769 SR_API int sr_config_list(const struct sr_dev_driver *driver,
770                 const struct sr_dev_inst *sdi,
771                 const struct sr_channel_group *cg,
772                 uint32_t key, GVariant **data)
773 {
774         int ret;
775
776         if (!driver || !data)
777                 return SR_ERR;
778         else if (!driver->config_list)
779                 return SR_ERR_ARG;
780         else if (key != SR_CONF_SCAN_OPTIONS && key != SR_CONF_DEVICE_OPTIONS) {
781                 if (check_key(driver, sdi, cg, key, SR_CONF_LIST, NULL) != SR_OK)
782                         return SR_ERR_ARG;
783         }
784         if ((ret = driver->config_list(key, data, sdi, cg)) == SR_OK) {
785                 log_key(sdi, cg, key, SR_CONF_LIST, *data);
786                 g_variant_ref_sink(*data);
787         }
788
789         return ret;
790 }
791
792 static struct sr_key_info *get_keytable(int keytype)
793 {
794         struct sr_key_info *table;
795
796         switch (keytype) {
797         case SR_KEY_CONFIG:
798                 table = sr_key_info_config;
799                 break;
800         case SR_KEY_MQ:
801                 table = sr_key_info_mq;
802                 break;
803         case SR_KEY_MQFLAGS:
804                 table = sr_key_info_mqflag;
805                 break;
806         default:
807                 sr_err("Invalid keytype %d", keytype);
808                 return NULL;
809         }
810
811         return table;
812 }
813
814 /**
815  * Get information about a key, by key.
816  *
817  * @param[in] keytype The namespace the key is in.
818  * @param[in] key The key to find.
819  *
820  * @return A pointer to a struct sr_key_info, or NULL if the key
821  *         was not found.
822  *
823  * @since 0.3.0
824  */
825 SR_API const struct sr_key_info *sr_key_info_get(int keytype, uint32_t key)
826 {
827         struct sr_key_info *table;
828         int i;
829
830         if (!(table = get_keytable(keytype)))
831                 return NULL;
832
833         for (i = 0; table[i].key; i++) {
834                 if (table[i].key == key)
835                         return &table[i];
836         }
837
838         return NULL;
839 }
840
841 /**
842  * Get information about a key, by name.
843  *
844  * @param[in] keytype The namespace the key is in.
845  * @param[in] keyid The key id string.
846  *
847  * @return A pointer to a struct sr_key_info, or NULL if the key
848  *         was not found.
849  *
850  * @since 0.2.0
851  */
852 SR_API const struct sr_key_info *sr_key_info_name_get(int keytype, const char *keyid)
853 {
854         struct sr_key_info *table;
855         int i;
856
857         if (!(table = get_keytable(keytype)))
858                 return NULL;
859
860         for (i = 0; table[i].key; i++) {
861                 if (!table[i].id)
862                         continue;
863                 if (!strcmp(table[i].id, keyid))
864                         return &table[i];
865         }
866
867         return NULL;
868 }
869
870 /** @} */