/* * The MIT License (MIT) * * Copyright (c) 2019 Ha Thach (tinyusb.org) * Copyright (c) 2022 King Kévin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include #include #include #include "bsp/board.h" #include "tusb.h" #if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3) // ESP-IDF need "freertos/" prefix in include path. // CFG_TUSB_OS_INC_PATH should be defined accordingly. #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/queue.h" #include "freertos/task.h" #include "freertos/timers.h" #include "esp_log.h" #include "esp_partition.h" #include "esp_ota_ops.h" #define USBD_STACK_SIZE 4096 #else #include "FreeRTOS.h" #include "semphr.h" #include "queue.h" #include "task.h" #include "timers.h" // Increase stack size when debug log is enabled #define USBD_STACK_SIZE (3*configMINIMAL_STACK_SIZE/2) * (CFG_TUSB_DEBUG ? 2 : 1) #endif static const char* TAG = "DFU"; //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF PROTYPES //--------------------------------------------------------------------+ /* Blink pattern (in ms) */ enum { BLINK_IDLE = 1000, BLINK_DOWNLOAD = 250, BLINK_SUSPENDED = 2500, }; // static timer StaticTimer_t blinky_tmdef; TimerHandle_t blinky_tm; // static task StackType_t usb_device_stack[USBD_STACK_SIZE]; StaticTask_t usb_device_taskdef; // static task for cdc #define CDC_STACK_SZIE configMINIMAL_STACK_SIZE StackType_t cdc_stack[CDC_STACK_SZIE]; StaticTask_t cdc_taskdef; void led_blinky_cb(TimerHandle_t xTimer); void usb_device_task(void* param); // used to download image onto OTA partition esp_ota_handle_t ota_handle = 0; // how to program the downloaded data (0 = using OTA tools, 1 = using partition tools) static uint8_t dl_method = 0; // download blocks to program static uint8_t dl_block[CFG_TUD_DFU_XFER_BUFSIZE] = {0}; static uint16_t dl_block_len = 0; static uint16_t dl_block_num = 0; // task taking care of flashing during download // note: esp_ota_begin erase flash, which takes too long to be in tud_dfu_download_cb, causing a USB timeout, thus it's in a task static void dl_task(void* arg) { esp_err_t rc; while (true) { if (dl_block_len) { // we received a new block const esp_partition_t *ota_part = esp_ota_get_next_update_partition(NULL); if (NULL == ota_part) { ESP_LOGE(TAG, "OTA not found"); tud_dfu_finish_flashing(DFU_STATUS_ERR_PROG); continue; } if (0 == dl_method) { // using OTA tools // get handle for OTA update if (0 == ota_handle) { ESP_LOGD(TAG, "init OTA flash"); rc = esp_ota_begin(ota_part, OTA_SIZE_UNKNOWN, &ota_handle); if (ESP_OK != rc) { ESP_LOGE(TAG, "init OTA failed"); esp_ota_abort(ota_handle); ota_handle = 0; tud_dfu_finish_flashing(DFU_STATUS_ERR_ERASE); continue; } } // write data to partition rc = esp_ota_write_with_offset(ota_handle, dl_block, dl_block_len, dl_block_num * CFG_TUD_DFU_XFER_BUFSIZE); if (ESP_OK != rc) { ESP_LOGE(TAG, "writing OTA failed"); esp_ota_abort(ota_handle); ota_handle = 0; tud_dfu_finish_flashing(DFU_STATUS_ERR_WRITE); continue; } tud_dfu_finish_flashing(DFU_STATUS_OK); // flashing op for download complete without error } else if (1 == dl_method) { // using partition tools // read current data uint8_t flash_block[CFG_TUD_DFU_XFER_BUFSIZE]; rc = esp_partition_read(ota_part, dl_block_num * CFG_TUD_DFU_XFER_BUFSIZE, flash_block, dl_block_len); if (ESP_OK != rc) { ESP_LOGE(TAG, "reading range failed"); tud_dfu_finish_flashing(DFU_STATUS_ERR_CHECK_ERASED); continue; } if (0 == memcmp(dl_block, flash_block, dl_block_len)) { // data is the same dl_block_len = 0; // ready for next block tud_dfu_finish_flashing(DFU_STATUS_OK); // flashing op for download complete without error continue; } if (0 == (dl_block_num * CFG_TUD_DFU_XFER_BUFSIZE) % 4096) { // new page rc = esp_partition_erase_range(ota_part, dl_block_num * CFG_TUD_DFU_XFER_BUFSIZE, 4096); // erase page (block is smaller than page if (ESP_OK != rc) { ESP_LOGE(TAG, "erase range failed"); tud_dfu_finish_flashing(DFU_STATUS_ERR_ERASE); continue; } } rc = esp_partition_write(ota_part, dl_block_num * CFG_TUD_DFU_XFER_BUFSIZE, flash_block, dl_block_len); // write new data if (ESP_OK != rc) { ESP_LOGE(TAG, "writing range failed"); tud_dfu_finish_flashing(DFU_STATUS_ERR_WRITE); continue; } ESP_LOGD(TAG, "writing range OK"); dl_block_len = 0; // ready for next block tud_dfu_finish_flashing(DFU_STATUS_OK); // flashing op for download complete without error } else { // unknown method tud_dfu_finish_flashing(DFU_STATUS_ERR_TARGET); } dl_block_len = 0; // ready for next block } else { // no new block vTaskDelay(1); // allow other tasks to run (and watchdog reset) } } } // task to complete flashing, used when entering manifestation static void complete_task(void* arg) { esp_err_t rc; // finish flashing if (ota_handle) { rc = esp_ota_end(ota_handle); ota_handle = 0; if (ESP_OK != rc) { ESP_LOGE(TAG, "close OTA failed"); tud_dfu_finish_flashing(DFU_STATUS_ERR_PROG); vTaskDelete(NULL); // close task } } // switch to OTA app const esp_partition_t *ota = esp_ota_get_next_update_partition(NULL); esp_app_desc_t ota_desc; esp_ota_get_partition_description(ota, &ota_desc); if (ESP_APP_DESC_MAGIC_WORD == ota_desc.magic_word) { ESP_LOGI(TAG, "set boot to valid app"); esp_ota_set_boot_partition(ota); xTimerChangePeriod(blinky_tm, pdMS_TO_TICKS(BLINK_IDLE), 0); tud_dfu_finish_flashing(DFU_STATUS_OK); } else { ESP_LOGI(TAG, "no valid app"); tud_dfu_finish_flashing(DFU_STATUS_ERR_VERIFY); } vTaskDelete(NULL); // close task } //--------------------------------------------------------------------+ // Main //--------------------------------------------------------------------+ int main(void) { board_init(); const esp_partition_t *next = esp_ota_get_next_update_partition(NULL); esp_app_desc_t next_desc; esp_ota_get_partition_description(next, &next_desc); if (ESP_APP_DESC_MAGIC_WORD == next_desc.magic_word) { ESP_LOGI(TAG, "set app for next boot"); esp_ota_set_boot_partition(next); } else { ESP_LOGI(TAG, "no valid app"); } // soft timer for blinky blinky_tm = xTimerCreateStatic(NULL, pdMS_TO_TICKS(BLINK_IDLE), true, NULL, led_blinky_cb, &blinky_tmdef); xTimerStart(blinky_tm, 0); // Create a task for tinyusb device stack (void) xTaskCreateStatic( usb_device_task, "usbd", USBD_STACK_SIZE, NULL, configMAX_PRIORITIES-1, usb_device_stack, &usb_device_taskdef); // skip starting scheduler (and return) for ESP32-S2 or ESP32-S3 #if !TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3) vTaskStartScheduler(); #endif // create task to handle download progress xTaskCreate(dl_task, "dl_task", 2 * 1024, NULL, 8, NULL); ESP_LOGI(TAG, "DFU mode"); return 0; } #if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3) void app_main(void) { main(); } #endif // USB Device Driver task // This top level thread process all usb events and invoke callbacks void usb_device_task(void* param) { (void) param; // This should be called after scheduler/kernel is started. // Otherwise it could cause kernel issue since USB IRQ handler does use RTOS queue API. tusb_init(); // RTOS forever loop while (1) { // tinyusb device task tud_task(); } } //--------------------------------------------------------------------+ // Device callbacks //--------------------------------------------------------------------+ // Invoked when usb bus is suspended // remote_wakeup_en : if host allow us to perform remote wakeup // Within 7ms, device must draw an average of current less than 2.5 mA from bus void tud_suspend_cb(bool remote_wakeup_en) { (void) remote_wakeup_en; xTimerChangePeriod(blinky_tm, pdMS_TO_TICKS(BLINK_SUSPENDED), 0); } // Invoked when usb bus is resumed void tud_resume_cb(void) { xTimerChangePeriod(blinky_tm, pdMS_TO_TICKS(BLINK_IDLE), 0); } //--------------------------------------------------------------------+ // DFU callbacks // Note: alt is used as the partition number, in order to support multiple partitions like FLASH, EEPROM, etc. //--------------------------------------------------------------------+ // Invoked right before tud_dfu_download_cb() (state=DFU_DNBUSY) or tud_dfu_manifest_cb() (state=DFU_MANIFEST) // Application return timeout in milliseconds (bwPollTimeout) for the next download/manifest operation. // During this period, USB host won't try to communicate with us. uint32_t tud_dfu_get_timeout_cb(uint8_t alt, uint8_t state) { if ( state == DFU_DNBUSY ) { return 3; // SPI flash Page Program Time 0.7-3 ms } else if (state == DFU_MANIFEST) { // since we don't buffer entire image and do any flashing in manifest stage return 0; } return 0; } // Invoked when received DFU_DNLOAD (wLength>0) following by DFU_GETSTATUS (state=DFU_DNBUSY) requests // This callback could be returned before flashing op is complete (async). // Once finished flashing, application must call tud_dfu_finish_flashing() void tud_dfu_download_cb(uint8_t alt, uint16_t block_num, uint8_t const* data, uint16_t length) { esp_err_t rc; static bool dl_started = false; ESP_LOGD(TAG, "download, alt=%u block=%u", alt, block_num); if (alt > 1) { ESP_LOGW(TAG, "download to invalid alt %u", alt); tud_dfu_finish_flashing(DFU_STATUS_ERR_ADDRESS); return; } if (0 == length) { // there is nothing to program // finish flashing if (ota_handle) { rc = esp_ota_end(ota_handle); ota_handle = 0; if (ESP_OK != rc) { ESP_LOGE(TAG, "close OTA failed"); tud_dfu_finish_flashing(DFU_STATUS_ERR_PROG); return; } } dl_started = false; tud_dfu_finish_flashing(DFU_STATUS_OK); // flashing op for download complete without error } else if (length > CFG_TUD_DFU_XFER_BUFSIZE) { // more data than we can handle tud_dfu_finish_flashing(DFU_STATUS_ERR_PROG); } else if (dl_block_len) { // there is already a block to program tud_dfu_finish_flashing(DFU_STATUS_ERR_STALLEDPKT); } else { // all is fine to program if (!dl_started) { xTimerChangePeriod(blinky_tm, pdMS_TO_TICKS(BLINK_DOWNLOAD), 0); dl_started = true; } memcpy(dl_block, data, length); // copy data for dl_task dl_method = alt; // remember how to flash dl_block_num = block_num; // remember offset dl_block_len = length; // notify dl_task block is ready } } // Invoked when download process is complete, received DFU_DNLOAD (wLength=0) following by DFU_GETSTATUS (state=Manifest) // Application can do checksum, or actual flashing if buffered entire image previously. // Once finished flashing, application must call tud_dfu_finish_flashing() void tud_dfu_manifest_cb(uint8_t alt) { (void)alt; // not used ESP_LOGI(TAG, "download completed, enter manifestation"); xTaskCreate(complete_task, "complete_task", 3 * 1024, NULL, 8, NULL); } // Invoked when received DFU_UPLOAD request // Application must populate data with up to length bytes and // Return the number of written bytes uint16_t tud_dfu_upload_cb(uint8_t alt, uint16_t block_num, uint8_t* data, uint16_t length) { uint16_t xfer_len = 0; if (alt > 0) { ESP_LOGW(TAG, "upload unknown alt %u", alt); return 0; } ESP_LOGD(TAG, "upload, alt=%u block=%u", alt, block_num); const esp_partition_t * part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL); esp_err_t rc = esp_partition_read(part, block_num * CFG_TUD_DFU_XFER_BUFSIZE, data, length); if (ESP_OK == rc) { xfer_len = length; } else { xfer_len = 0; ESP_LOGW(TAG, "reading flash failed"); } return xfer_len; } // Invoked when the Host has terminated a download or upload transfer void tud_dfu_abort_cb(uint8_t alt) { (void) alt; ESP_LOGI(TAG, "host aborted transfer"); blinky_tm = xTimerCreateStatic(NULL, pdMS_TO_TICKS(BLINK_IDLE), true, NULL, led_blinky_cb, &blinky_tmdef); } // Invoked when a DFU_DETACH request is received void tud_dfu_detach_cb(void) { ESP_LOGI(TAG, "host detach -> reboot"); esp_restart(); } //--------------------------------------------------------------------+ // BLINKING TASK //--------------------------------------------------------------------+ void led_blinky_cb(TimerHandle_t xTimer) { (void) xTimer; static bool led_state = false; board_led_write(led_state); led_state = 1 - led_state; // toggle }