In the two scenarios you talked about, a USB device can find out if it should be a host or a device via cable. USB cables (not Type-C) are not balanced. One side is the host and the other is the device. There is a pin on the connector, called an identifier pin, which floats on the device side and is grounded on the host side. This allows the USB controller on each side to know which side of the cable it is connected to, and therefore what role (host or device) it should have when connecting. These types of devices are called dual-user devices.
If you have such a device, you can connect it to ordinary hosts (for example, a laptop), and it will act as a device. And you can connect it to ordinary devices (for example, to a printer), and it will act as a host. All of this is cable based.
If you connect two dual-processor OTG devices to each other. Their initial roles are defined by the cable in the same way.
After defining the initial roles, they can then change roles from their original frame-defined roles using the Host-Negotiation Protocol (HNP).
Regarding the implementation of this. There is no short way to explain this. Each controller is different, and you will need to read the controller database and programming model to implement all of these procedures. They also understand the specifications of USB and OTG well.
A good place to start is http://usb.org , where you can find all the specifications.
source share