Better USB plug/unplug handling.

This commit is contained in:
Joe Kearney 2025-11-22 16:51:33 -06:00
parent c979c38fd7
commit 0dcbae7ec6
3 changed files with 32 additions and 16 deletions

View file

@ -57,6 +57,7 @@ static const char *OTA_FILE = "/usb/esp/OTA_URL.txt";
const char *CONFIG_FILE = "/usb/esp/config.txt";
__NOINIT_ATTR uint_fast8_t Restarts;
static bool Device_Connected_This_Power_Cycle = false;
typedef enum
{
@ -274,8 +275,6 @@ static void usb_host_task(void *args)
static void app_usb_task(void *args)
{
SemaphoreHandle_t init_complete = args;
static USB_State_T Current_State = USB_STATE_UNINITIALIZED;
static msc_host_device_handle_t msc_device = NULL;
static msc_host_vfs_handle_t vfs_handle = NULL;
@ -311,10 +310,14 @@ static void app_usb_task(void *args)
{
device_address = msg.data.new_dev_address;
Current_State = USB_STATE_DEVICE_CONNECTED;
Device_Connected_This_Power_Cycle = true;
Restarts = 0;
KLOG_INFO(TAG, "Device connected.");
}
}
else
{
if (Device_Connected_This_Power_Cycle == false)
{
if (Restarts <= 3)
{
@ -323,8 +326,15 @@ static void app_usb_task(void *args)
esp_restart();
}
else
{
static bool warning_sent = false;
if (warning_sent == false)
{
KLOG_WARN(TAG, "No flash drive detected after multiple attempts.");
warning_sent = true;
}
}
}
}
}
@ -356,7 +366,6 @@ static void app_usb_task(void *args)
{
Current_State = USB_STATE_VFS_REGISTERED;
xEventGroupSetBits(Get_System_Events(), SYS_USB_FS_PRESENT);
xSemaphoreGive(init_complete);
}
}
}
@ -401,7 +410,7 @@ static void app_usb_task(void *args)
}
}
void Initialize_USB(SemaphoreHandle_t init_complete)
void Initialize_USB(void)
{
KLOG_INFO(TAG, "Initializing USB file system...");
@ -416,7 +425,7 @@ void Initialize_USB(SemaphoreHandle_t init_complete)
app_usb_task, // Function that implements the task.
"USB NVM", // Text name for the task.
STACK_SIZE, // Stack size in bytes, not words.
(void *)init_complete, // Parameter passed into the task.
NULL, // Parameter passed into the task.
tskIDLE_PRIORITY + 2, // Priority at which the task is created.
xStack, // Array to use as the task's stack.
&xTaskBuffer, // Variable to hold the task's data structure.

View file

@ -21,7 +21,7 @@
#pragma once
void Initialize_USB(SemaphoreHandle_t init_complete);
void Initialize_USB(void);
extern const char *CONFIG_FILE;

View file

@ -93,8 +93,15 @@ void app_main(void)
KLOG_ERROR(TAG, "Timeout initializing SPIFFS!");
}
Initialize_USB(init_complete_semaphore);
if (xSemaphoreTake(init_complete_semaphore, pdMS_TO_TICKS(INITIALIZATION_TIMEOUT_IN_ms)) != pdTRUE)
Initialize_USB();
EventBits_t bits = xEventGroupWaitBits(
Get_System_Events(),
SYS_USB_FS_PRESENT,
pdFALSE,
pdTRUE,
pdMS_TO_TICKS(INITIALIZATION_TIMEOUT_IN_ms));
if ((bits & SYS_USB_FS_PRESENT) == 0)
{
KLOG_ERROR(TAG, "Timeout initializing USB!");
}