[systemd-devel] Scan all USB devices from Linux service

Vadim Lebedev vadiml1024 at gmail.com
Wed Feb 14 16:56:31 UTC 2024


This is what ChatGPT proposes:
#include <libusb-1.0/libusb.h>
#include <stdio.h>

void scan_devices(const char* target_string) {
    libusb_device **devs;
    libusb_context *ctx = NULL;
    int r;
    ssize_t cnt;

    r = libusb_init(&ctx);
    if (r < 0) return;

    cnt = libusb_get_device_list(ctx, &devs);
    if (cnt < 0) return;

    for (ssize_t i = 0; i < cnt; i++) {
        libusb_device *dev = devs[i];
        libusb_device_handle *handle = NULL;

        if (libusb_open(dev, &handle) == 0) {
            // Iterate through all configurations and interfaces
            struct libusb_config_descriptor *config;
            libusb_get_config_descriptor(dev, 0, &config);

            for (int j = 0; j < config->bNumInterfaces; j++) {
                const struct libusb_interface *inter =
&config->interface[j];
                const struct libusb_interface_descriptor *interdesc =
&inter->altsetting[0];
                if (interdesc->iInterface) {
                    unsigned char buffer[256];
                    int len = libusb_get_string_descriptor_ascii(handle,
interdesc->iInterface, buffer, sizeof(buffer));
                    if (len > 0) {
                        printf("Interface %d: %s\n", j, buffer);
                        if (strcmp((char*)buffer, target_string) == 0) {
                            // Match found
                            printf("Match found for interface %d\n", j);
                        }
                    }
                }
            }
            libusb_free_config_descriptor(config);
            libusb_close(handle);
        }
    }

    libusb_free_device_list(devs, 1);
    libusb_exit(ctx);
}

int main() {
    scan_devices("Particular String");
    return 0;
}


On Wed, Feb 14, 2024 at 3:54 PM Muni Sekhar <munisekharrms at gmail.com> wrote:

> HI all,
>
> USB devices can have multiple interfaces (functional units) that serve
> different purposes (e.g., data transfer, control, audio, etc.).
>
> Each interface can have an associated string descriptor (referred to
> as iInterface). The string descriptor provides a human-readable name
> or description for the interface.
>
> From user space service utility, How to scan all the USB devices
> connected to the system and read each interface string
> descriptor(iInterface)  and check whether it matches "Particular
> String" or not.
>
> The service program should trigger scanning all the USB devices on any
> USB device detection or removal. Can libusb be used for it?
>
> Any input would be appreciated.
>
> --
> Thanks,
> Sekhar
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.freedesktop.org/archives/systemd-devel/attachments/20240214/ceca4a2a/attachment.htm>


More information about the systemd-devel mailing list