How to create a simple Linux USB device to "echo" whatever is sent to it from the host?

Viewed 353

As a web developer, I am new to USB and gadget development. I am creating a Windows Desktop application that communicates, using the Node-USB library, with a USB Device. To start, I am trying to create a mock USB device using Linux on my Raspberry Pi 4. I have set it up to boot as a USB device using this script, which is based on this guide, which sets the usb provider/vendor IDs, a rndis function, and more. Windows recognizes the device when plugging it into the computer, and I am able to open a connection to it using the NodeJS library.

I am now stuck on how to configure the device to set up a function that simply listens to data sent to it on a "bulk in" endpoint from the host, and echo it back automatically to the host, so that the Windows application receives it. I have been advised that there are many scripts available to set up a simple "demo" gadget like this on Linux, but I cannot find any.

It's not clear to me,

  1. How to set up a usb function on the device to listen to a bulk "out" endpoint
  2. How to set up a "driver" or a custom-made application to "listen" to the aforementioned function
  3. How to make the listening application itself. The node-usb library says it's made for communicating with USB devices, not for devices itself, so it seems I can't use it?
  4. Is there a simple bash script or built-in linux command that can automatically echo data to the host from the "in" endpoint?

I'd appreciate any guidance to point me in the right direction!

1 Answers
  1. You need to write a USB function driver in kernel or use functionfs to do it in userspace. Either way you'll need to prepare USB descriptors which are presented to the host during enumeration (when your device is being plugged in) and then handle incoming USB requests on registered endpoints.

  2. To setup one of the drivers already existing in kernel you can do it through configfs or using libusbgx wrapper library. There are also legacy function drivers which activate automatically after loading the module.

  3. The node-usb library is wrapper for libusb, which is host-side library. So you're right, you cannot use it to create device-side function driver.

  4. There is f_loopback function in kernel which does exactly what you need. This is probably the best starting point if you want to create your own USB function driver.

Related