Set configuration following http://libusb.sourceforge.net/api-1.0/caveats.html
authorAntonio Ospite <ao2@ao2.it>
Wed, 10 Jun 2015 09:57:37 +0000 (11:57 +0200)
committerAntonio Ospite <ao2@ao2.it>
Wed, 10 Jun 2015 09:57:37 +0000 (11:57 +0200)
src/visomat-data-downloader.c

index f93757d..818473f 100644 (file)
@@ -317,6 +317,7 @@ int main(void)
 {
        int ret;
        libusb_device_handle *dev;
+       int current_configuration;
 
        ret = libusb_init(NULL);
        if (ret < 0) {
@@ -335,15 +336,25 @@ int main(void)
                goto out_libusb_exit;
        }
 
-       ret = libusb_set_configuration(dev, VISOMAT_CONFIGURATION);
+       current_configuration = -1;
+       ret = libusb_get_configuration(dev, &current_configuration);
        if (ret < 0) {
-               fprintf(stderr, "libusb_set_configuration failed: %s\n",
+               fprintf(stderr, "libusb_get_configuration failed: %s\n",
                        libusb_error_name(ret));
-               fprintf(stderr, "Cannot set configuration %hhu\n",
-                       VISOMAT_CONFIGURATION);
                goto out_libusb_close;
        }
 
+       if (current_configuration != VISOMAT_CONFIGURATION) {
+               ret = libusb_set_configuration(dev, VISOMAT_CONFIGURATION);
+               if (ret < 0) {
+                       fprintf(stderr, "libusb_set_configuration failed: %s\n",
+                               libusb_error_name(ret));
+                       fprintf(stderr, "Cannot set configuration %hhu\n",
+                               VISOMAT_CONFIGURATION);
+                       goto out_libusb_close;
+               }
+       }
+
        libusb_set_auto_detach_kernel_driver(dev, 1);
 
        ret = libusb_claim_interface(dev, VISOMAT_INTERFACE);
@@ -355,6 +366,24 @@ int main(void)
                goto out_libusb_close;
        }
 
+       /* Checking that the configuration has not changed, as suggested in
+        * http://libusb.sourceforge.net/api-1.0/caveats.html
+        */
+       current_configuration = -1;
+       ret = libusb_get_configuration(dev, &current_configuration);
+       if (ret < 0) {
+               fprintf(stderr, "libusb_get_configuration after claim failed: %s\n",
+                       libusb_error_name(ret));
+               goto out_libusb_release_interface;
+       }
+
+       if (current_configuration != VISOMAT_CONFIGURATION) {
+               fprintf(stderr, "libusb configuration changed (expected: %hhu, current: %hhu\n",
+                       VISOMAT_CONFIGURATION, current_configuration);
+               ret = -EINVAL;
+               goto out_libusb_release_interface;
+       }
+
        ret = visomat_get_datetime(dev);
        if (ret < 0)
                goto out_libusb_release_interface;