toolchain icon indicating copy to clipboard operation
toolchain copied to clipboard

USB stuck when unplugging the cable

Open MathisLav opened this issue 2 years ago • 0 comments

Hello 👋

I want first to congratulate you all for your amazing work with the CE toolchain, thank you!

I'm getting an issue that happens every time I unplug the USB cable, but only if a configuration has been set beforehand.

The minimal code could be something like this (I tried with the most recent toolchain):

#include <usbdrvce.h>
#include <tice.h>
#include <stdio.h>

int do_configure = 0;
usb_device_t device = NULL;


usb_error_t usbHandler(usb_event_t event, void *event_data, usb_callback_data_t *data) {
	(void)data;
	switch(event)
	{
		case USB_DEVICE_CONNECTED_EVENT:
			device = (usb_device_t)event_data;
			usb_RefDevice(device);
			usb_ResetDevice(device);
			break;
		case USB_DEVICE_ENABLED_EVENT:
			if(!(usb_GetRole() & USB_ROLE_DEVICE)) {
				do_configure = 1;
			} else {
				usb_DisableDevice(device);
			}
			break;
		case USB_DEVICE_DISCONNECTED_EVENT:
			usb_UnrefDevice(device);
			device = NULL;
			break;
		default:
			break;
	}
	return USB_SUCCESS;
}

void configure_usb_device() {
	uint8_t buffer[256] = {0};
	size_t len = 0;
	size_t total_length;

	usb_GetDescriptor(device, USB_CONFIGURATION_DESCRIPTOR, 0, buffer, 9, &len);
	total_length = ((usb_configuration_descriptor_t*)buffer)->wTotalLength;
	if(total_length > 256) {
		printf("No mem\n");
		return;
	}

	usb_GetDescriptor(device, USB_CONFIGURATION_DESCRIPTOR, 0, buffer, total_length, &len);
	if(usb_SetConfiguration(device, (usb_configuration_descriptor_t*)buffer, len) != USB_SUCCESS) {
		printf("Not able to configure\n");
		return;
	}

	printf("Configured!\n");
}

int main(void) {
	os_ClrHome();
	usb_Init(usbHandler, NULL, NULL, USB_DEFAULT_INIT_FLAGS);

	while(!os_GetCSC()) {
		os_SetCursorPos(0, 0);
		os_NewLine();
		printf("%x ", usb_GetFrameNumber());

		if(do_configure) {
			configure_usb_device();
			do_configure = 0;
		}

		usb_HandleEvents();
	}

	usb_Cleanup();
	return 0;
}

Thus, when I unplug the cable the frame number is stopped (that's ok) but when I try to re-plug the device, the latter is powered but the frame number doesn't restart and is still frozen. When I comment out the usb_SetConfiguration line though, it works and I can plug/unplug the cable several times without any problem. It seems that after setting the configuration, unplugging the cable does not trigger any DISCONNECTED_EVENT.

Does aynybody have any idea about this? Is there a known workaround for now?

NB: I'm plugging a smartphone as a device, but acagliano seems to have the same issue with his ECM driver.

MathisLav avatar Apr 02 '24 17:04 MathisLav