BootloaderCDC.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2018.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the CDC class bootloader. This file contains the complete bootloader logic.
  29. */
  30. #define INCLUDE_FROM_BOOTLOADERCDC_C
  31. #include "BootloaderCDC.h"
  32. /** Contains the current baud rate and other settings of the first virtual serial port. This must be retained as some
  33. * operating systems will not open the port unless the settings can be set successfully.
  34. */
  35. static CDC_LineEncoding_t LineEncoding = { .BaudRateBPS = 0,
  36. .CharFormat = CDC_LINEENCODING_OneStopBit,
  37. .ParityType = CDC_PARITY_None,
  38. .DataBits = 8 };
  39. /** Current address counter. This stores the current address of the FLASH or EEPROM as set by the host,
  40. * and is used when reading or writing to the AVRs memory (either FLASH or EEPROM depending on the issued
  41. * command.)
  42. */
  43. static uint32_t CurrAddress;
  44. /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
  45. * via a watchdog reset. When cleared the bootloader will exit, starting the watchdog and entering an infinite
  46. * loop until the AVR restarts and the application runs.
  47. */
  48. static bool RunBootloader = true;
  49. /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
  50. * will start if the /HWB line of the AVR is held low and the system is reset. However, if the /HWB line is still held
  51. * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
  52. * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
  53. */
  54. uint16_t MagicBootKey ATTR_NO_INIT;
  55. /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
  56. * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
  57. * this will force the user application to start via a software jump.
  58. */
  59. void Application_Jump_Check(void)
  60. {
  61. bool JumpToApplication = false;
  62. #if (BOARD == BOARD_LEONARDO)
  63. /* Enable pull-up on the IO13 pin so we can use it to select the mode */
  64. PORTC |= (1 << 7);
  65. Delay_MS(10);
  66. /* If IO13 is not jumpered to ground, start the user application instead */
  67. JumpToApplication = ((PINC & (1 << 7)) != 0);
  68. /* Disable pull-up after the check has completed */
  69. PORTC &= ~(1 << 7);
  70. #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
  71. /* Disable JTAG debugging */
  72. JTAG_DISABLE();
  73. /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
  74. PORTF |= (1 << 4);
  75. Delay_MS(10);
  76. /* If the TCK pin is not jumpered to ground, start the user application instead */
  77. JumpToApplication = ((PINF & (1 << 4)) != 0);
  78. /* Re-enable JTAG debugging */
  79. JTAG_ENABLE();
  80. #else
  81. /* Check if the device's BOOTRST fuse is set */
  82. if (BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & FUSE_BOOTRST)
  83. {
  84. /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
  85. if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
  86. JumpToApplication = true;
  87. /* Clear reset source */
  88. MCUSR &= ~(1 << EXTRF);
  89. }
  90. else
  91. {
  92. /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
  93. * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
  94. if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
  95. JumpToApplication = true;
  96. /* Clear reset source */
  97. MCUSR &= ~(1 << WDRF);
  98. }
  99. #endif
  100. /* Don't run the user application if the reset vector is blank (no app loaded) */
  101. bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
  102. /* If a request has been made to jump to the user application, honor it */
  103. if (JumpToApplication && ApplicationValid)
  104. {
  105. /* Turn off the watchdog */
  106. MCUSR &= ~(1 << WDRF);
  107. wdt_disable();
  108. /* Clear the boot key and jump to the user application */
  109. MagicBootKey = 0;
  110. // cppcheck-suppress constStatement
  111. ((void (*)(void))0x0000)();
  112. }
  113. }
  114. /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
  115. * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
  116. * the loaded application code.
  117. */
  118. int main(void)
  119. {
  120. /* Setup hardware required for the bootloader */
  121. SetupHardware();
  122. /* Turn on first LED on the board to indicate that the bootloader has started */
  123. LEDs_SetAllLEDs(LEDS_LED1);
  124. /* Enable global interrupts so that the USB stack can function */
  125. GlobalInterruptEnable();
  126. while (RunBootloader)
  127. {
  128. CDC_Task();
  129. USB_USBTask();
  130. }
  131. /* Wait a short time to end all USB transactions and then disconnect */
  132. _delay_us(1000);
  133. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  134. USB_Detach();
  135. /* Unlock the forced application start mode of the bootloader if it is restarted */
  136. MagicBootKey = MAGIC_BOOT_KEY;
  137. /* Enable the watchdog and force a timeout to reset the AVR */
  138. wdt_enable(WDTO_250MS);
  139. for (;;);
  140. }
  141. /** Configures all hardware required for the bootloader. */
  142. static void SetupHardware(void)
  143. {
  144. /* Disable watchdog if enabled by bootloader/fuses */
  145. MCUSR &= ~(1 << WDRF);
  146. wdt_disable();
  147. /* Disable clock division */
  148. clock_prescale_set(clock_div_1);
  149. /* Relocate the interrupt vector table to the bootloader section */
  150. MCUCR = (1 << IVCE);
  151. MCUCR = (1 << IVSEL);
  152. /* Initialize the USB and other board hardware drivers */
  153. USB_Init();
  154. LEDs_Init();
  155. /* Bootloader active LED toggle timer initialization */
  156. TIMSK1 = (1 << TOIE1);
  157. TCCR1B = ((1 << CS11) | (1 << CS10));
  158. }
  159. /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
  160. ISR(TIMER1_OVF_vect, ISR_BLOCK)
  161. {
  162. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  163. }
  164. /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
  165. * to relay data to and from the attached USB host.
  166. */
  167. void EVENT_USB_Device_ConfigurationChanged(void)
  168. {
  169. /* Setup CDC Notification, Rx and Tx Endpoints */
  170. Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT,
  171. CDC_NOTIFICATION_EPSIZE, 1);
  172. Endpoint_ConfigureEndpoint(CDC_TX_EPADDR, EP_TYPE_BULK, CDC_TXRX_EPSIZE, 1);
  173. Endpoint_ConfigureEndpoint(CDC_RX_EPADDR, EP_TYPE_BULK, CDC_TXRX_EPSIZE, 1);
  174. }
  175. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  176. * the device from the USB host before passing along unhandled control requests to the library for processing
  177. * internally.
  178. */
  179. void EVENT_USB_Device_ControlRequest(void)
  180. {
  181. /* Ignore any requests that aren't directed to the CDC interface */
  182. if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
  183. (REQTYPE_CLASS | REQREC_INTERFACE))
  184. {
  185. return;
  186. }
  187. /* Activity - toggle indicator LEDs */
  188. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  189. /* Process CDC specific control requests */
  190. switch (USB_ControlRequest.bRequest)
  191. {
  192. case CDC_REQ_GetLineEncoding:
  193. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  194. {
  195. Endpoint_ClearSETUP();
  196. /* Write the line coding data to the control endpoint */
  197. Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  198. Endpoint_ClearOUT();
  199. }
  200. break;
  201. case CDC_REQ_SetLineEncoding:
  202. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  203. {
  204. Endpoint_ClearSETUP();
  205. /* Read the line coding data in from the host into the global struct */
  206. Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  207. Endpoint_ClearIN();
  208. }
  209. break;
  210. case CDC_REQ_SetControlLineState:
  211. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  212. {
  213. Endpoint_ClearSETUP();
  214. Endpoint_ClearStatusStage();
  215. }
  216. break;
  217. }
  218. }
  219. #if !defined(NO_BLOCK_SUPPORT)
  220. /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
  221. * on the AVR109 protocol command issued.
  222. *
  223. * \param[in] Command Single character AVR109 protocol command indicating what memory operation to perform
  224. */
  225. static void ReadWriteMemoryBlock(const uint8_t Command)
  226. {
  227. uint16_t BlockSize;
  228. char MemoryType;
  229. uint8_t HighByte = 0;
  230. uint8_t LowByte = 0;
  231. BlockSize = (FetchNextCommandByte() << 8);
  232. BlockSize |= FetchNextCommandByte();
  233. MemoryType = FetchNextCommandByte();
  234. if ((MemoryType != MEMORY_TYPE_FLASH) && (MemoryType != MEMORY_TYPE_EEPROM))
  235. {
  236. /* Send error byte back to the host */
  237. WriteNextResponseByte('?');
  238. return;
  239. }
  240. /* Check if command is to read a memory block */
  241. if (Command == AVR109_COMMAND_BlockRead)
  242. {
  243. while (BlockSize--)
  244. {
  245. if (MemoryType == MEMORY_TYPE_FLASH)
  246. {
  247. /* Read the next FLASH byte from the current FLASH page */
  248. #if (FLASHEND > 0xFFFF)
  249. WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte));
  250. #else
  251. WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte));
  252. #endif
  253. /* If both bytes in current word have been read, increment the address counter */
  254. if (HighByte)
  255. CurrAddress += 2;
  256. HighByte = !HighByte;
  257. }
  258. else
  259. {
  260. /* Read the next EEPROM byte into the endpoint */
  261. WriteNextResponseByte(eeprom_read_byte((uint8_t*)(intptr_t)(CurrAddress >> 1)));
  262. /* Increment the address counter after use */
  263. CurrAddress += 2;
  264. }
  265. }
  266. }
  267. else
  268. {
  269. uint32_t PageStartAddress = CurrAddress;
  270. if (MemoryType == MEMORY_TYPE_FLASH)
  271. BootloaderAPI_ErasePage(PageStartAddress);
  272. while (BlockSize--)
  273. {
  274. if (MemoryType == MEMORY_TYPE_FLASH)
  275. {
  276. /* If both bytes in current word have been written, increment the address counter */
  277. if (HighByte)
  278. {
  279. /* Write the next FLASH word to the current FLASH page */
  280. BootloaderAPI_FillWord(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte));
  281. /* Increment the address counter after use */
  282. CurrAddress += 2;
  283. }
  284. else
  285. {
  286. LowByte = FetchNextCommandByte();
  287. }
  288. HighByte = !HighByte;
  289. }
  290. else
  291. {
  292. /* Write the next EEPROM byte from the endpoint */
  293. eeprom_update_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  294. /* Increment the address counter after use */
  295. CurrAddress += 2;
  296. }
  297. }
  298. /* If in FLASH programming mode, commit the page after writing */
  299. if (MemoryType == MEMORY_TYPE_FLASH)
  300. {
  301. /* Commit the flash page to memory */
  302. BootloaderAPI_WritePage(PageStartAddress);
  303. }
  304. /* Send response byte back to the host */
  305. WriteNextResponseByte('\r');
  306. }
  307. }
  308. #endif
  309. /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
  310. * to allow reception of the next data packet from the host.
  311. *
  312. * \return Next received byte from the host in the CDC data OUT endpoint
  313. */
  314. static uint8_t FetchNextCommandByte(void)
  315. {
  316. /* Select the OUT endpoint so that the next data byte can be read */
  317. Endpoint_SelectEndpoint(CDC_RX_EPADDR);
  318. /* If OUT endpoint empty, clear it and wait for the next packet from the host */
  319. while (!(Endpoint_IsReadWriteAllowed()))
  320. {
  321. Endpoint_ClearOUT();
  322. while (!(Endpoint_IsOUTReceived()))
  323. {
  324. if (USB_DeviceState == DEVICE_STATE_Unattached)
  325. return 0;
  326. }
  327. }
  328. /* Fetch the next byte from the OUT endpoint */
  329. return Endpoint_Read_8();
  330. }
  331. /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
  332. * bank when full ready for the next byte in the packet to the host.
  333. *
  334. * \param[in] Response Next response byte to send to the host
  335. */
  336. static void WriteNextResponseByte(const uint8_t Response)
  337. {
  338. /* Select the IN endpoint so that the next data byte can be written */
  339. Endpoint_SelectEndpoint(CDC_TX_EPADDR);
  340. /* If IN endpoint full, clear it and wait until ready for the next packet to the host */
  341. if (!(Endpoint_IsReadWriteAllowed()))
  342. {
  343. Endpoint_ClearIN();
  344. while (!(Endpoint_IsINReady()))
  345. {
  346. if (USB_DeviceState == DEVICE_STATE_Unattached)
  347. return;
  348. }
  349. }
  350. /* Write the next byte to the IN endpoint */
  351. Endpoint_Write_8(Response);
  352. }
  353. /** Task to read in AVR109 commands from the CDC data OUT endpoint, process them, perform the required actions
  354. * and send the appropriate response back to the host.
  355. */
  356. static void CDC_Task(void)
  357. {
  358. /* Select the OUT endpoint */
  359. Endpoint_SelectEndpoint(CDC_RX_EPADDR);
  360. /* Check if endpoint has a command in it sent from the host */
  361. if (!(Endpoint_IsOUTReceived()))
  362. return;
  363. /* Read in the bootloader command (first byte sent from host) */
  364. uint8_t Command = FetchNextCommandByte();
  365. if (Command == AVR109_COMMAND_ExitBootloader)
  366. {
  367. RunBootloader = false;
  368. /* Send confirmation byte back to the host */
  369. WriteNextResponseByte('\r');
  370. }
  371. else if ((Command == AVR109_COMMAND_SetLED) || (Command == AVR109_COMMAND_ClearLED) ||
  372. (Command == AVR109_COMMAND_SelectDeviceType))
  373. {
  374. FetchNextCommandByte();
  375. /* Send confirmation byte back to the host */
  376. WriteNextResponseByte('\r');
  377. }
  378. else if ((Command == AVR109_COMMAND_EnterProgrammingMode) || (Command == AVR109_COMMAND_LeaveProgrammingMode))
  379. {
  380. /* Send confirmation byte back to the host */
  381. WriteNextResponseByte('\r');
  382. }
  383. else if (Command == AVR109_COMMAND_ReadPartCode)
  384. {
  385. /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */
  386. WriteNextResponseByte(0x44);
  387. WriteNextResponseByte(0x00);
  388. }
  389. else if (Command == AVR109_COMMAND_ReadAutoAddressIncrement)
  390. {
  391. /* Indicate auto-address increment is supported */
  392. WriteNextResponseByte('Y');
  393. }
  394. else if (Command == AVR109_COMMAND_SetCurrentAddress)
  395. {
  396. /* Set the current address to that given by the host (translate 16-bit word address to byte address) */
  397. CurrAddress = (FetchNextCommandByte() << 9);
  398. CurrAddress |= (FetchNextCommandByte() << 1);
  399. /* Send confirmation byte back to the host */
  400. WriteNextResponseByte('\r');
  401. }
  402. else if (Command == AVR109_COMMAND_ReadBootloaderInterface)
  403. {
  404. /* Indicate serial programmer back to the host */
  405. WriteNextResponseByte('S');
  406. }
  407. else if (Command == AVR109_COMMAND_ReadBootloaderIdentifier)
  408. {
  409. /* Write the 7-byte software identifier to the endpoint */
  410. for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++)
  411. WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]);
  412. }
  413. else if (Command == AVR109_COMMAND_ReadBootloaderSWVersion)
  414. {
  415. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR);
  416. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR);
  417. }
  418. else if (Command == AVR109_COMMAND_ReadSignature)
  419. {
  420. WriteNextResponseByte(AVR_SIGNATURE_3);
  421. WriteNextResponseByte(AVR_SIGNATURE_2);
  422. WriteNextResponseByte(AVR_SIGNATURE_1);
  423. }
  424. else if (Command == AVR109_COMMAND_EraseFLASH)
  425. {
  426. /* Clear the application section of flash */
  427. for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < (uint32_t)BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
  428. BootloaderAPI_ErasePage(CurrFlashAddress);
  429. /* Send confirmation byte back to the host */
  430. WriteNextResponseByte('\r');
  431. }
  432. #if !defined(NO_LOCK_BYTE_WRITE_SUPPORT)
  433. else if (Command == AVR109_COMMAND_WriteLockbits)
  434. {
  435. /* Set the lock bits to those given by the host */
  436. BootloaderAPI_WriteLock(FetchNextCommandByte());
  437. /* Send confirmation byte back to the host */
  438. WriteNextResponseByte('\r');
  439. }
  440. #endif
  441. else if (Command == AVR109_COMMAND_ReadLockbits)
  442. {
  443. WriteNextResponseByte(BootloaderAPI_ReadLock());
  444. }
  445. else if (Command == AVR109_COMMAND_ReadLowFuses)
  446. {
  447. WriteNextResponseByte(BootloaderAPI_ReadFuse(GET_LOW_FUSE_BITS));
  448. }
  449. else if (Command == AVR109_COMMAND_ReadHighFuses)
  450. {
  451. WriteNextResponseByte(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS));
  452. }
  453. else if (Command == AVR109_COMMAND_ReadExtendedFuses)
  454. {
  455. WriteNextResponseByte(BootloaderAPI_ReadFuse(GET_EXTENDED_FUSE_BITS));
  456. }
  457. #if !defined(NO_BLOCK_SUPPORT)
  458. else if (Command == AVR109_COMMAND_GetBlockWriteSupport)
  459. {
  460. WriteNextResponseByte('Y');
  461. /* Send block size to the host */
  462. WriteNextResponseByte(SPM_PAGESIZE >> 8);
  463. WriteNextResponseByte(SPM_PAGESIZE & 0xFF);
  464. }
  465. else if ((Command == AVR109_COMMAND_BlockWrite) || (Command == AVR109_COMMAND_BlockRead))
  466. {
  467. /* Delegate the block write/read to a separate function for clarity */
  468. ReadWriteMemoryBlock(Command);
  469. }
  470. #endif
  471. #if !defined(NO_FLASH_BYTE_SUPPORT)
  472. else if (Command == AVR109_COMMAND_FillFlashPageWordHigh)
  473. {
  474. /* Write the high byte to the current flash page */
  475. BootloaderAPI_FillWord(CurrAddress, FetchNextCommandByte());
  476. /* Send confirmation byte back to the host */
  477. WriteNextResponseByte('\r');
  478. }
  479. else if (Command == AVR109_COMMAND_FillFlashPageWordLow)
  480. {
  481. /* Write the low byte to the current flash page */
  482. BootloaderAPI_FillWord(CurrAddress | 0x01, FetchNextCommandByte());
  483. /* Increment the address */
  484. CurrAddress += 2;
  485. /* Send confirmation byte back to the host */
  486. WriteNextResponseByte('\r');
  487. }
  488. else if (Command == AVR109_COMMAND_WriteFlashPage)
  489. {
  490. /* Commit the flash page to memory */
  491. BootloaderAPI_WritePage(CurrAddress);
  492. /* Send confirmation byte back to the host */
  493. WriteNextResponseByte('\r');
  494. }
  495. else if (Command == AVR109_COMMAND_ReadFLASHWord)
  496. {
  497. #if (FLASHEND > 0xFFFF)
  498. uint16_t ProgramWord = pgm_read_word_far(CurrAddress);
  499. #else
  500. uint16_t ProgramWord = pgm_read_word(CurrAddress);
  501. #endif
  502. WriteNextResponseByte(ProgramWord >> 8);
  503. WriteNextResponseByte(ProgramWord & 0xFF);
  504. }
  505. #endif
  506. #if !defined(NO_EEPROM_BYTE_SUPPORT)
  507. else if (Command == AVR109_COMMAND_WriteEEPROM)
  508. {
  509. /* Read the byte from the endpoint and write it to the EEPROM */
  510. eeprom_update_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  511. /* Increment the address after use */
  512. CurrAddress += 2;
  513. /* Send confirmation byte back to the host */
  514. WriteNextResponseByte('\r');
  515. }
  516. else if (Command == AVR109_COMMAND_ReadEEPROM)
  517. {
  518. /* Read the EEPROM byte and write it to the endpoint */
  519. WriteNextResponseByte(eeprom_read_byte((uint8_t*)((intptr_t)(CurrAddress >> 1))));
  520. /* Increment the address after use */
  521. CurrAddress += 2;
  522. }
  523. #endif
  524. else if (Command != AVR109_COMMAND_Sync)
  525. {
  526. /* Unknown (non-sync) command, return fail code */
  527. WriteNextResponseByte('?');
  528. }
  529. /* Select the IN endpoint */
  530. Endpoint_SelectEndpoint(CDC_TX_EPADDR);
  531. /* Remember if the endpoint is completely full before clearing it */
  532. bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
  533. /* Send the endpoint data to the host */
  534. Endpoint_ClearIN();
  535. /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
  536. if (IsEndpointFull)
  537. {
  538. while (!(Endpoint_IsINReady()))
  539. {
  540. if (USB_DeviceState == DEVICE_STATE_Unattached)
  541. return;
  542. }
  543. Endpoint_ClearIN();
  544. }
  545. /* Wait until the data has been sent to the host */
  546. while (!(Endpoint_IsINReady()))
  547. {
  548. if (USB_DeviceState == DEVICE_STATE_Unattached)
  549. return;
  550. }
  551. /* Select the OUT endpoint */
  552. Endpoint_SelectEndpoint(CDC_RX_EPADDR);
  553. /* Acknowledge the command from the host */
  554. Endpoint_ClearOUT();
  555. }