Search code examples
embeddedusbclient-serverprotocols

USB software loopback device on Linux


I have a need to write an client-server application where a tiny server rests on a USB gadget and communicates with a client application on the host.

I've not done this sort of thing before but I have done webapps and usually, they're all developed and debugged on the local machine using the lo loopback network interface. This has perhaps influenced my way of thinking and I'm looking for a way to simulate a USB host and gadget on my machine so that I can build both ends of the application completely on my PC before I dive into the actual gadget and get the thing going.

Is this the right way to go about it? I realise that the USB protocol is asymmetrical and found some references to this over here but it seems to most natural way to go about it.

If it is the right way, how do I start off with something like this and are there any potential problems that others are aware of which I might stumble over?

Update

References which I found from Googling earlier. There are Linux Kernel modules (part of my Ubuntu Install too) which seem to be able to simulate the host and gadget sides (viz. dummy_hcd and gadgetfs respectively). My idea is to simply have something like

Host application (client) on PC <-> device file 0 <-> Loopback device <-> device file 1 <-> Gadget application (server) also on PC (will be moved to gadget).

Solution

  • Don't over-think it.

    You don't need to fancy "loopback" device.

    You're right about simulating the USB host. You don't need to create a fancy USB loopback device or any silliness like that.

    1. Design your client.

    2. Design a "generic" USB interface layer that would simply passes requests to a real USB device driver. Don't code this yet.

    3. Code a USB interface layer that mocks the host instead of using the real USB device. This has the same interface as your generic USB interface. It's a proper subclass. However, it doesn't actually use the USB device driver. Instead it acts like it's the web server on the USB device.

      Clearly, it's not a complete simulation. It's just enough for you to test your client. Each key feature that the client must interact with is represented with enough canned responses that you're sure the client works.

    4. When your client works, code the real USB interface layer that really passes requests from client to device. This is that you'll use in production and to do integration tests with the real USB device.

    Your client software now has two configurations -- all handled in software:

    • The real driver -- for production.

    • The mock driver -- for unit testing.

    It shouldn't be any more complex than this. And, you can now unit test your entire client using your mock host.