SLAU533D September 2013 – April 2017
In USB, it is important to consider that the bus may suddenly become unavailable. For example, the USB cable can be removed by the user at any time. If the developer does not keep this in mind, it is easy to write code that can hang up indefinitely when it happens.
For example, suppose the bUsbSendComplete flag had been polled until it was set to TRUE. If the cable was then removed between the call to USBHID_sendReport() and the time the host fetches the report, the flag would never become TRUE, and execution would freeze. Granted, with a 1-ms polling interval, this is a very small window. But if this code went into a product, with thousands of users in the field, eventually it would occur. (The default LaunchPad development kit configuration is bus-powered, losing power when detached from the host. So this error won't occur unless external power is used. However, the code was written this way to show good USB coding practices.)
Another thing that can go wrong is if the host becomes unresponsive. This is more problematic for MSC and CDC interfaces than for HID interfaces, because the former use USB bulk transfers, which are more subject to host and bus conditions. In contrast, HID is guaranteed to be polled at the polling interval, as long as the host is functioning properly. But even so, if the host crashes, it is undesirable for the USB device to hang. Therefore, good coding practice requires considering what happens if the USBHID_handleSendCompleted() event never occurs, or if USBHID_sendReport() returns kUSBHID_intfBusyError.
The application deals with these problems by never depending on the bUsbSendComplete flag for execution fluidity. Whatever USBHID_sendReport() returns, the next line of code is always USB_connectionState(). So if the cable has been detached, execution shifts to the switch() case that shuts down all string sending and enters LPM3. If instead USB remains connected, but the host has crashed, then the application functions as it always had, with fluid execution; the only difference is that USBHID_sendReport() always returns kUSBHID_intfBusyError and no characters are actually sent.