USB Libraries Help > USB Device Libraries > USB Device Layer Library > Using the Library > How the Library Works > Application Client Interaction
MPLAB Harmony USB Stack
Application Client Interaction

Once initialized, Device Layer becomes ready for operation. The application must open the Device Layer by calling the USB_DEVICE_Open() function. Opening the Device Layer makes the application a Device Layer client. The Device Layer returns a valid Device Layer Handle when opened successfully. It will return an invalid Device Layer Handle when the open function fails. The application in this case should try opening the Device Layer again. The application needs a valid Device Layer handle (a handle that is not invalid) to access the Device Layer functionality. 

The client must now register a Device Layer Event Handler with the Device Layer. This is a mandatory step. It enables USB Device Layer Events and is required for proper functioning of the USB Device Stack. The application must use the USB_DEVICE_EventHandlerSet() function to register the event handler. The Application Event Handler should be of the type USB_DEVICE_EVENT_HANDLER. The Device Layer, when an event needs to be generated, calls this event handler function with the event type and event relevant information. The application must register an event handler for proper functioning of the USB Device. Not registering an event handler may cause the USB Device to malfunction and become non-compliant. 

The client can now attach the USB Device on the bus. The application must attach the in response to the USB_DEVICE_EVENT_POWER_DETECTED event. Attaching the device on the bus makes the device visible to the host (if it is already attached to the bus) and will cause the host to interact with the device. 

The following code shows an example of the application opening the Device Layer and registering the event handler.

/******************************************************
 * Here the application tries to open the Device Layer
 * and then register an event handler and then attach
 * the device on the bus.
 ******************************************************/
void APP_Tasks(void)
{
    switch(appData.state)
    {
        case APP_STATE_INIT:

            /* Open the device layer */
            appData.deviceHandle = USB_DEVICE_Open( USB_DEVICE_INDEX_0,DRV_IO_INTENT_READWRITE );

            if(appData.deviceHandle != USB_DEVICE_HANDLE_INVALID)
            {
                /* Register a callback with device layer to get event notification */
                USB_DEVICE_EventHandlerSet(appData.deviceHandle, APP_USBDeviceEventCallBack, 0);

                appData.state = APP_STATE_WAIT_FOR_CONFIGURATION;
            }
            else
            {
                /* The Device Layer is not ready to be opened. We should try
                 * again later. */
            }

            break;
    }
}