]> sigrok.org Git - libsigrok.git/blob - src/backend.c
serial: prepare serial over HID in common layer and build support
[libsigrok.git] / src / backend.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2012 Peter Stuge <peter@stuge.se>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <glib.h>
23 #ifdef _WIN32
24 #include <winsock2.h>
25 #endif
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "backend"
31 /** @endcond */
32
33 /**
34  * @mainpage libsigrok API
35  *
36  * @section sec_intro Introduction
37  *
38  * The <a href="http://sigrok.org">sigrok</a> project aims at creating a
39  * portable, cross-platform, Free/Libre/Open-Source signal analysis software
40  * suite that supports various device types (such as logic analyzers,
41  * oscilloscopes, multimeters, and more).
42  *
43  * <a href="http://sigrok.org/wiki/Libsigrok">libsigrok</a> is a shared
44  * library written in C which provides the basic API for talking to
45  * <a href="http://sigrok.org/wiki/Supported_hardware">supported hardware</a>
46  * and reading/writing the acquired data into various
47  * <a href="http://sigrok.org/wiki/Input_output_formats">input/output
48  * file formats</a>.
49  *
50  * @section sec_api API reference
51  *
52  * See the "Modules" page for an introduction to various libsigrok
53  * related topics and the detailed API documentation of the respective
54  * functions.
55  *
56  * You can also browse the API documentation by file, or review all
57  * data structures.
58  *
59  * @section sec_mailinglists Mailing lists
60  *
61  * There is one mailing list for sigrok/libsigrok: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a>.
62  *
63  * @section sec_irc IRC
64  *
65  * You can find the sigrok developers in the
66  * <a href="irc://chat.freenode.net/sigrok">\#sigrok</a>
67  * IRC channel on Freenode.
68  *
69  * @section sec_website Website
70  *
71  * <a href="http://sigrok.org/wiki/Libsigrok">sigrok.org/wiki/Libsigrok</a>
72  */
73
74 /**
75  * @file
76  *
77  * Initializing and shutting down libsigrok.
78  */
79
80 /**
81  * @defgroup grp_init Initialization
82  *
83  * Initializing and shutting down libsigrok.
84  *
85  * Before using any of the libsigrok functionality (except for
86  * sr_log_loglevel_set()), sr_init() must be called to initialize the
87  * library, which will return a struct sr_context when the initialization
88  * was successful.
89  *
90  * When libsigrok functionality is no longer needed, sr_exit() should be
91  * called, which will (among other things) free the struct sr_context.
92  *
93  * Example for a minimal program using libsigrok:
94  *
95  * @code{.c}
96  *   #include <stdio.h>
97  *   #include <libsigrok/libsigrok.h>
98  *
99  *   int main(int argc, char **argv)
100  *   {
101  *      int ret;
102  *      struct sr_context *sr_ctx;
103  *
104  *      if ((ret = sr_init(&sr_ctx)) != SR_OK) {
105  *              printf("Error initializing libsigrok (%s): %s.\n",
106  *                     sr_strerror_name(ret), sr_strerror(ret));
107  *              return 1;
108  *      }
109  *
110  *      // Use libsigrok functions here...
111  *
112  *      if ((ret = sr_exit(sr_ctx)) != SR_OK) {
113  *              printf("Error shutting down libsigrok (%s): %s.\n",
114  *                     sr_strerror_name(ret), sr_strerror(ret));
115  *              return 1;
116  *      }
117  *
118  *      return 0;
119  *   }
120  * @endcode
121  *
122  * @{
123  */
124
125 SR_API GSList *sr_buildinfo_libs_get(void)
126 {
127         GSList *l = NULL, *m = NULL;
128 #if defined(HAVE_LIBUSB_1_0) && !defined(__FreeBSD__)
129         const struct libusb_version *lv;
130 #endif
131
132         m = g_slist_append(NULL, g_strdup("glib"));
133         m = g_slist_append(m, g_strdup_printf("%d.%d.%d (rt: %d.%d.%d/%d:%d)",
134                 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION,
135                 glib_major_version, glib_minor_version, glib_micro_version,
136                 glib_binary_age, glib_interface_age));
137         l = g_slist_append(l, m);
138
139         m = g_slist_append(NULL, g_strdup("libzip"));
140         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBZIP_VERSION));
141         l = g_slist_append(l, m);
142
143 #ifdef HAVE_LIBSERIALPORT
144         m = g_slist_append(NULL, g_strdup("libserialport"));
145         m = g_slist_append(m, g_strdup_printf("%s/%s (rt: %s/%s)",
146                 SP_PACKAGE_VERSION_STRING, SP_LIB_VERSION_STRING,
147                 sp_get_package_version_string(), sp_get_lib_version_string()));
148         l = g_slist_append(l, m);
149 #endif
150 #ifdef HAVE_LIBUSB_1_0
151         m = g_slist_append(NULL, g_strdup("libusb-1.0"));
152 #ifdef __FreeBSD__
153         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBUSB_1_0_VERSION));
154 #else
155         lv = libusb_get_version();
156         m = g_slist_append(m, g_strdup_printf("%d.%d.%d.%d%s API 0x%08x",
157                 lv->major, lv->minor, lv->micro, lv->nano, lv->rc,
158 #if defined(LIBUSB_API_VERSION)
159                 LIBUSB_API_VERSION
160 #elif defined(LIBUSBX_API_VERSION)
161                 LIBUSBX_API_VERSION
162 #endif
163                 ));
164 #endif
165         l = g_slist_append(l, m);
166 #endif
167 #ifdef HAVE_LIBHIDAPI
168         m = g_slist_append(NULL, g_strdup("hidapi"));
169         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBHIDAPI_VERSION));
170         l = g_slist_append(l, m);
171 #endif
172 #ifdef HAVE_LIBFTDI
173         m = g_slist_append(NULL, g_strdup("libftdi"));
174         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBFTDI_VERSION));
175         l = g_slist_append(l, m);
176 #endif
177 #ifdef HAVE_LIBGPIB
178         m = g_slist_append(NULL, g_strdup("libgpib"));
179         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBGPIB_VERSION));
180         l = g_slist_append(l, m);
181 #endif
182 #ifdef HAVE_LIBREVISA
183         m = g_slist_append(NULL, g_strdup("librevisa"));
184         m = g_slist_append(m, g_strdup_printf("%s", CONF_LIBREVISA_VERSION));
185         l = g_slist_append(l, m);
186 #endif
187
188         return l;
189 }
190
191 SR_API char *sr_buildinfo_host_get(void)
192 {
193         return g_strdup_printf("%s, %s-endian", CONF_HOST,
194 #ifdef WORDS_BIGENDIAN
195         "big"
196 #else
197         "little"
198 #endif
199         );
200 }
201
202 SR_API char *sr_buildinfo_scpi_backends_get(void)
203 {
204         GString *s;
205         char *str;
206
207         s = g_string_sized_new(200);
208
209         g_string_append_printf(s, "TCP, ");
210 #if HAVE_RPC
211         g_string_append_printf(s, "RPC, ");
212 #endif
213 #ifdef HAVE_SERIAL_COMM
214         g_string_append_printf(s, "serial, ");
215 #endif
216 #ifdef HAVE_LIBREVISA
217         g_string_append_printf(s, "VISA, ");
218 #endif
219 #ifdef HAVE_LIBGPIB
220         g_string_append_printf(s, "GPIB, ");
221 #endif
222 #ifdef HAVE_LIBUSB_1_0
223         g_string_append_printf(s, "USBTMC, ");
224 #endif
225         s->str[s->len - 2] = '\0';
226
227         str = g_strdup(s->str);
228         g_string_free(s, TRUE);
229
230         return str;
231 }
232
233 static void print_versions(void)
234 {
235         GString *s;
236         GSList *l, *l_orig, *m;
237         char *str;
238         const char *lib, *version;
239
240         sr_dbg("libsigrok %s/%s.",
241                 sr_package_version_string_get(), sr_lib_version_string_get());
242
243         s = g_string_sized_new(200);
244         g_string_append(s, "Libs: ");
245         l_orig = sr_buildinfo_libs_get();
246         for (l = l_orig; l; l = l->next) {
247                 m = l->data;
248                 lib = m->data;
249                 version = m->next->data;
250                 g_string_append_printf(s, "%s %s, ", lib, version);
251                 g_slist_free_full(m, g_free);
252         }
253         g_slist_free(l_orig);
254         s->str[s->len - 2] = '.';
255         s->str[s->len - 1] = '\0';
256         sr_dbg("%s", s->str);
257         g_string_free(s, TRUE);
258
259         str = sr_buildinfo_host_get();
260         sr_dbg("Host: %s.", str);
261         g_free(str);
262
263         str = sr_buildinfo_scpi_backends_get();
264         sr_dbg("SCPI backends: %s.", str);
265         g_free(str);
266 }
267
268 static void print_resourcepaths(void)
269 {
270         GSList *l, *l_orig;
271
272         sr_dbg("Firmware search paths:");
273         l_orig = sr_resourcepaths_get(SR_RESOURCE_FIRMWARE);
274         for (l = l_orig; l; l = l->next)
275                 sr_dbg(" - %s", (const char *)l->data);
276         g_slist_free_full(l_orig, g_free);
277 }
278
279 /**
280  * Sanity-check all libsigrok drivers.
281  *
282  * @param[in] ctx Pointer to a libsigrok context struct. Must not be NULL.
283  *
284  * @retval SR_OK All drivers are OK
285  * @retval SR_ERR One or more drivers have issues.
286  * @retval SR_ERR_ARG Invalid argument.
287  */
288 static int sanity_check_all_drivers(const struct sr_context *ctx)
289 {
290         int i, errors, ret = SR_OK;
291         struct sr_dev_driver **drivers;
292         const char *d;
293
294         if (!ctx)
295                 return SR_ERR_ARG;
296
297         sr_spew("Sanity-checking all drivers.");
298
299         drivers = sr_driver_list(ctx);
300         for (i = 0; drivers[i]; i++) {
301                 errors = 0;
302
303                 d = (drivers[i]->name) ? drivers[i]->name : "NULL";
304
305                 if (!drivers[i]->name) {
306                         sr_err("No name in driver %d ('%s').", i, d);
307                         errors++;
308                 }
309                 if (!drivers[i]->longname) {
310                         sr_err("No longname in driver %d ('%s').", i, d);
311                         errors++;
312                 }
313                 if (drivers[i]->api_version < 1) {
314                         sr_err("API version in driver %d ('%s') < 1.", i, d);
315                         errors++;
316                 }
317                 if (!drivers[i]->init) {
318                         sr_err("No init in driver %d ('%s').", i, d);
319                         errors++;
320                 }
321                 if (!drivers[i]->cleanup) {
322                         sr_err("No cleanup in driver %d ('%s').", i, d);
323                         errors++;
324                 }
325                 if (!drivers[i]->scan) {
326                         sr_err("No scan in driver %d ('%s').", i, d);
327                         errors++;
328                 }
329                 if (!drivers[i]->dev_list) {
330                         sr_err("No dev_list in driver %d ('%s').", i, d);
331                         errors++;
332                 }
333                 if (!drivers[i]->dev_clear) {
334                         sr_err("No dev_clear in driver %d ('%s').", i, d);
335                         errors++;
336                 }
337                 /* Note: config_get() is optional. */
338                 if (!drivers[i]->config_set) {
339                         sr_err("No config_set in driver %d ('%s').", i, d);
340                         errors++;
341                 }
342                 /* Note: config_channel_set() is optional. */
343                 /* Note: config_commit() is optional. */
344                 if (!drivers[i]->config_list) {
345                         sr_err("No config_list in driver %d ('%s').", i, d);
346                         errors++;
347                 }
348                 if (!drivers[i]->dev_open) {
349                         sr_err("No dev_open in driver %d ('%s').", i, d);
350                         errors++;
351                 }
352                 if (!drivers[i]->dev_close) {
353                         sr_err("No dev_close in driver %d ('%s').", i, d);
354                         errors++;
355                 }
356                 if (!drivers[i]->dev_acquisition_start) {
357                         sr_err("No dev_acquisition_start in driver %d ('%s').",
358                                i, d);
359                         errors++;
360                 }
361                 if (!drivers[i]->dev_acquisition_stop) {
362                         sr_err("No dev_acquisition_stop in driver %d ('%s').",
363                                i, d);
364                         errors++;
365                 }
366
367                 /* Note: 'priv' is allowed to be NULL. */
368
369                 if (errors == 0)
370                         continue;
371
372                 ret = SR_ERR;
373         }
374
375         return ret;
376 }
377
378 /**
379  * Sanity-check all libsigrok input modules.
380  *
381  * @retval SR_OK All modules are OK
382  * @retval SR_ERR One or more modules have issues.
383  */
384 static int sanity_check_all_input_modules(void)
385 {
386         int i, errors, ret = SR_OK;
387         const struct sr_input_module **inputs;
388         const char *d;
389
390         sr_spew("Sanity-checking all input modules.");
391
392         inputs = sr_input_list();
393         for (i = 0; inputs[i]; i++) {
394                 errors = 0;
395
396                 d = (inputs[i]->id) ? inputs[i]->id : "NULL";
397
398                 if (!inputs[i]->id) {
399                         sr_err("No ID in module %d ('%s').", i, d);
400                         errors++;
401                 }
402                 if (!inputs[i]->name) {
403                         sr_err("No name in module %d ('%s').", i, d);
404                         errors++;
405                 }
406                 if (!inputs[i]->desc) {
407                         sr_err("No description in module %d ('%s').", i, d);
408                         errors++;
409                 }
410                 if (!inputs[i]->init) {
411                         sr_err("No init in module %d ('%s').", i, d);
412                         errors++;
413                 }
414                 if (!inputs[i]->receive) {
415                         sr_err("No receive in module %d ('%s').", i, d);
416                         errors++;
417                 }
418                 if (!inputs[i]->end) {
419                         sr_err("No end in module %d ('%s').", i, d);
420                         errors++;
421                 }
422
423                 if (errors == 0)
424                         continue;
425
426                 ret = SR_ERR;
427         }
428
429         return ret;
430 }
431
432 /**
433  * Sanity-check all libsigrok output modules.
434  *
435  * @retval SR_OK All modules are OK
436  * @retval SR_ERR One or more modules have issues.
437  */
438 static int sanity_check_all_output_modules(void)
439 {
440         int i, errors, ret = SR_OK;
441         const struct sr_output_module **outputs;
442         const char *d;
443
444         sr_spew("Sanity-checking all output modules.");
445
446         outputs = sr_output_list();
447         for (i = 0; outputs[i]; i++) {
448                 errors = 0;
449
450                 d = (outputs[i]->id) ? outputs[i]->id : "NULL";
451
452                 if (!outputs[i]->id) {
453                         sr_err("No ID in module %d ('%s').", i, d);
454                         errors++;
455                 }
456                 if (!outputs[i]->name) {
457                         sr_err("No name in module %d ('%s').", i, d);
458                         errors++;
459                 }
460                 if (!outputs[i]->desc) {
461                         sr_err("No description in module '%s'.", d);
462                         errors++;
463                 }
464                 if (!outputs[i]->receive) {
465                         sr_err("No receive in module '%s'.", d);
466                         errors++;
467                 }
468
469                 if (errors == 0)
470                         continue;
471
472                 ret = SR_ERR;
473         }
474
475         return ret;
476 }
477
478 /**
479  * Sanity-check all libsigrok transform modules.
480  *
481  * @retval SR_OK All modules are OK
482  * @retval SR_ERR One or more modules have issues.
483  */
484 static int sanity_check_all_transform_modules(void)
485 {
486         int i, errors, ret = SR_OK;
487         const struct sr_transform_module **transforms;
488         const char *d;
489
490         sr_spew("Sanity-checking all transform modules.");
491
492         transforms = sr_transform_list();
493         for (i = 0; transforms[i]; i++) {
494                 errors = 0;
495
496                 d = (transforms[i]->id) ? transforms[i]->id : "NULL";
497
498                 if (!transforms[i]->id) {
499                         sr_err("No ID in module %d ('%s').", i, d);
500                         errors++;
501                 }
502                 if (!transforms[i]->name) {
503                         sr_err("No name in module %d ('%s').", i, d);
504                         errors++;
505                 }
506                 if (!transforms[i]->desc) {
507                         sr_err("No description in module '%s'.", d);
508                         errors++;
509                 }
510                 /* Note: options() is optional. */
511                 /* Note: init() is optional. */
512                 if (!transforms[i]->receive) {
513                         sr_err("No receive in module '%s'.", d);
514                         errors++;
515                 }
516                 /* Note: cleanup() is optional. */
517
518                 if (errors == 0)
519                         continue;
520
521                 ret = SR_ERR;
522         }
523
524         return ret;
525 }
526
527 /**
528  * Initialize libsigrok.
529  *
530  * This function must be called before any other libsigrok function.
531  *
532  * @param ctx Pointer to a libsigrok context struct pointer. Must not be NULL.
533  *            This will be a pointer to a newly allocated libsigrok context
534  *            object upon success, and is undefined upon errors.
535  *
536  * @return SR_OK upon success, a (negative) error code otherwise. Upon errors
537  *         the 'ctx' pointer is undefined and should not be used. Upon success,
538  *         the context will be free'd by sr_exit() as part of the libsigrok
539  *         shutdown.
540  *
541  * @since 0.2.0
542  */
543 SR_API int sr_init(struct sr_context **ctx)
544 {
545         int ret = SR_ERR;
546         struct sr_context *context;
547 #ifdef _WIN32
548         WSADATA wsadata;
549 #endif
550
551         print_versions();
552
553         print_resourcepaths();
554
555         if (!ctx) {
556                 sr_err("%s(): libsigrok context was NULL.", __func__);
557                 return SR_ERR;
558         }
559
560         context = g_malloc0(sizeof(struct sr_context));
561
562         sr_drivers_init(context);
563
564         if (sanity_check_all_drivers(context) < 0) {
565                 sr_err("Internal driver error(s), aborting.");
566                 goto done;
567         }
568
569         if (sanity_check_all_input_modules() < 0) {
570                 sr_err("Internal input module error(s), aborting.");
571                 goto done;
572         }
573
574         if (sanity_check_all_output_modules() < 0) {
575                 sr_err("Internal output module error(s), aborting.");
576                 goto done;
577         }
578
579         if (sanity_check_all_transform_modules() < 0) {
580                 sr_err("Internal transform module error(s), aborting.");
581                 goto done;
582         }
583
584 #ifdef _WIN32
585         if ((ret = WSAStartup(MAKEWORD(2, 2), &wsadata)) != 0) {
586                 sr_err("WSAStartup failed with error code %d.", ret);
587                 ret = SR_ERR;
588                 goto done;
589         }
590 #endif
591
592 #ifdef HAVE_LIBUSB_1_0
593         ret = libusb_init(&context->libusb_ctx);
594         if (LIBUSB_SUCCESS != ret) {
595                 sr_err("libusb_init() returned %s.", libusb_error_name(ret));
596                 ret = SR_ERR;
597                 goto done;
598         }
599 #endif
600 #ifdef HAVE_LIBHIDAPI
601         /*
602          * According to <hidapi.h>, the hid_init() routine just returns
603          * zero or non-zero, and hid_error() appears to relate to calls
604          * for a specific device after hid_open(). Which means that there
605          * is no more detailled information available beyond success/fail
606          * at this point in time.
607          */
608         if (hid_init() != 0) {
609                 sr_err("HIDAPI hid_init() failed.");
610                 ret = SR_ERR;
611                 goto done;
612         }
613 #endif
614         sr_resource_set_hooks(context, NULL, NULL, NULL, NULL);
615
616         *ctx = context;
617         context = NULL;
618         ret = SR_OK;
619
620 done:
621         g_free(context);
622         return ret;
623 }
624
625 /**
626  * Shutdown libsigrok.
627  *
628  * @param ctx Pointer to a libsigrok context struct. Must not be NULL.
629  *
630  * @retval SR_OK Success
631  * @retval other Error code SR_ERR, ...
632  *
633  * @since 0.2.0
634  */
635 SR_API int sr_exit(struct sr_context *ctx)
636 {
637         if (!ctx) {
638                 sr_err("%s(): libsigrok context was NULL.", __func__);
639                 return SR_ERR;
640         }
641
642         sr_hw_cleanup_all(ctx);
643
644 #ifdef _WIN32
645         WSACleanup();
646 #endif
647
648 #ifdef HAVE_LIBHIDAPI
649         hid_exit();
650 #endif
651 #ifdef HAVE_LIBUSB_1_0
652         libusb_exit(ctx->libusb_ctx);
653 #endif
654
655         g_free(sr_driver_list(ctx));
656         g_free(ctx);
657
658         return SR_OK;
659 }
660
661 /** @} */