Jump to main content

##

# 3.4.2.3.2 Detecting Device Attach

The application will need to know when a CDC Device is attached. To receive this attach event from the CDC Host Client Driver, the application must register an Attach Event Handler by calling the USB_HOST_CDC_AttachEventHandlerSet function. This function should be called before the USB_HOST_BusEnable function is called, else the application may miss CDC attach events. It can be called multiple times to register multiple event handlers, each for different application clients that need to know about CDC Device Attach events.

The total number of event handlers that can be registered is defined by USB_HOST_CDC_ATTACH_LISTENERS_NUMBER configuration option in `system_config.h`. When a device is attached, the CDC Host Client Driver will send the attach event to all the registered event handlers. In this event handler, the CDC Host Client Driver will pass a USB_HOST_CDC_OBJ that can be opened to gain access to the device. The following code shows an example of how to register attach event handlers.

## Example:

    /* This code shows an example of CDC Attach Event Handler and how this
     * attach event handler can be registered with the CDC Host Client Driver */
    void APP_USBHostCDCAttachEventListener(USB_HOST_CDC_OBJ cdcObj, uintptr_t context)
    {
        /* This function gets called when the CDC device is attached. In this
         * example we let the application know that a device is attached and we
         * store the CDC device object. This object will be required to open the
         * device. */

        appData.deviceIsAttached = true;
        appData.cdcObj = cdcObj;
    }

    void APP_Tasks(void)
    {
        switch (appData.state)
        {
            case APP_STATE_BUS_ENABLE:

                /* In this state the application enables the USB Host Bus. Note
                 * how the CDC Attach event handler is registered before the bus
                 * is enabled. */

                USB_HOST_CDC_AttachEventHandlerSet(APP_USBHostCDCAttachEventListener, (uintptr_t) 0);
                USB_HOST_BusEnable(0);
                appData.state = APP_STATE_WAIT_FOR_BUS_ENABLE_COMPLETE;
                break;

            case APP_STATE_WAIT_FOR_BUS_ENABLE_COMPLETE:
                /* Here we wait for the bus enable operation to complete. */
                break;
        }
    }