Caterina.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2011.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2011 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 disclaim 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_CATERINA_C
  31. #include "Caterina.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. /* Pulse generation counters to keep track of the time remaining for each pulse type */
  50. #define TX_RX_LED_PULSE_PERIOD 100
  51. uint16_t TxLEDPulse = 0; // time remaining for Tx LED pulse
  52. uint16_t RxLEDPulse = 0; // time remaining for Rx LED pulse
  53. /* Bootloader timeout timer */
  54. #define TIMEOUT_PERIOD 8000
  55. uint16_t Timeout = 0;
  56. uint16_t bootKey = 0x7777;
  57. volatile uint16_t *const bootKeyPtr = (volatile uint16_t *)0x0800;
  58. void StartSketch(void)
  59. {
  60. cli();
  61. /* Undo TIMER1 setup and clear the count before running the sketch */
  62. TIMSK1 = 0;
  63. TCCR1B = 0;
  64. TCNT1H = 0; // 16-bit write to TCNT1 requires high byte be written first
  65. TCNT1L = 0;
  66. /* Relocate the interrupt vector table to the application section */
  67. MCUCR = (1 << IVCE);
  68. MCUCR = 0;
  69. L_LED_OFF();
  70. TX_LED_OFF();
  71. RX_LED_OFF();
  72. /* jump to beginning of application space */
  73. __asm__ volatile("jmp 0x0000");
  74. }
  75. /* Breathing animation on L LED indicates bootloader is running */
  76. uint16_t LLEDPulse;
  77. void LEDPulse(void)
  78. {
  79. LLEDPulse++;
  80. uint8_t p = LLEDPulse >> 8;
  81. if (p > 127)
  82. p = 254-p;
  83. p += p;
  84. if (((uint8_t)LLEDPulse) > p)
  85. L_LED_OFF();
  86. else
  87. L_LED_ON();
  88. }
  89. /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
  90. * runs the bootloader processing routine until it times out or is instructed to exit.
  91. */
  92. int main(void)
  93. {
  94. /* Save the value of the boot key memory before it is overwritten */
  95. uint16_t bootKeyPtrVal = *bootKeyPtr;
  96. *bootKeyPtr = 0;
  97. /* Check the reason for the reset so we can act accordingly */
  98. uint8_t mcusr_state = MCUSR; // store the initial state of the Status register
  99. MCUSR = 0; // clear all reset flags
  100. /* Watchdog may be configured with a 15 ms period so must disable it before going any further */
  101. wdt_disable();
  102. if (mcusr_state & (1<<EXTRF)) {
  103. // External reset - we should continue to self-programming mode.
  104. } else if ((mcusr_state & (1<<PORF)) && (pgm_read_word(0) != 0xFFFF)) {
  105. // After a power-on reset skip the bootloader and jump straight to sketch
  106. // if one exists.
  107. StartSketch();
  108. } else if ((mcusr_state & (1<<WDRF)) && (bootKeyPtrVal != bootKey) && (pgm_read_word(0) != 0xFFFF)) {
  109. // If it looks like an "accidental" watchdog reset then start the sketch.
  110. StartSketch();
  111. }
  112. /* Setup hardware required for the bootloader */
  113. SetupHardware();
  114. /* Enable global interrupts so that the USB stack can function */
  115. sei();
  116. Timeout = 0;
  117. while (RunBootloader)
  118. {
  119. CDC_Task();
  120. USB_USBTask();
  121. /* Time out and start the sketch if one is present */
  122. if (Timeout > TIMEOUT_PERIOD)
  123. RunBootloader = false;
  124. LEDPulse();
  125. }
  126. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  127. USB_Detach();
  128. /* Jump to beginning of application space to run the sketch - do not reset */
  129. StartSketch();
  130. }
  131. /** Configures all hardware required for the bootloader. */
  132. void SetupHardware(void)
  133. {
  134. /* Disable watchdog if enabled by bootloader/fuses */
  135. MCUSR &= ~(1 << WDRF);
  136. wdt_disable();
  137. /* Disable clock division */
  138. clock_prescale_set(clock_div_1);
  139. /* Relocate the interrupt vector table to the bootloader section */
  140. MCUCR = (1 << IVCE);
  141. MCUCR = (1 << IVSEL);
  142. LED_SETUP();
  143. CPU_PRESCALE(0);
  144. L_LED_OFF();
  145. TX_LED_OFF();
  146. RX_LED_OFF();
  147. /* Initialize TIMER1 to handle bootloader timeout and LED tasks.
  148. * With 16 MHz clock and 1/64 prescaler, timer 1 is clocked at 250 kHz
  149. * Our chosen compare match generates an interrupt every 1 ms.
  150. * This interrupt is disabled selectively when doing memory reading, erasing,
  151. * or writing since SPM has tight timing requirements.
  152. */
  153. OCR1AH = 0;
  154. OCR1AL = 250;
  155. TIMSK1 = (1 << OCIE1A); // enable timer 1 output compare A match interrupt
  156. TCCR1B = ((1 << CS11) | (1 << CS10)); // 1/64 prescaler on timer 1 input
  157. /* Initialize USB Subsystem */
  158. USB_Init();
  159. }
  160. //uint16_t ctr = 0;
  161. ISR(TIMER1_COMPA_vect, ISR_BLOCK)
  162. {
  163. /* Reset counter */
  164. TCNT1H = 0;
  165. TCNT1L = 0;
  166. /* Check whether the TX or RX LED one-shot period has elapsed. if so, turn off the LED */
  167. if (TxLEDPulse && !(--TxLEDPulse))
  168. TX_LED_OFF();
  169. if (RxLEDPulse && !(--RxLEDPulse))
  170. RX_LED_OFF();
  171. if (pgm_read_word(0) != 0xFFFF)
  172. Timeout++;
  173. }
  174. /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
  175. * to relay data to and from the attached USB host.
  176. */
  177. void EVENT_USB_Device_ConfigurationChanged(void)
  178. {
  179. /* Setup CDC Notification, Rx and Tx Endpoints */
  180. Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
  181. ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
  182. ENDPOINT_BANK_SINGLE);
  183. Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
  184. ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
  185. ENDPOINT_BANK_SINGLE);
  186. Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
  187. ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
  188. ENDPOINT_BANK_SINGLE);
  189. }
  190. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  191. * the device from the USB host before passing along unhandled control requests to the library for processing
  192. * internally.
  193. */
  194. void EVENT_USB_Device_ControlRequest(void)
  195. {
  196. /* Ignore any requests that aren't directed to the CDC interface */
  197. if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
  198. (REQTYPE_CLASS | REQREC_INTERFACE))
  199. {
  200. return;
  201. }
  202. /* Process CDC specific control requests */
  203. switch (USB_ControlRequest.bRequest)
  204. {
  205. case CDC_REQ_GetLineEncoding:
  206. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  207. {
  208. Endpoint_ClearSETUP();
  209. /* Write the line coding data to the control endpoint */
  210. Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  211. Endpoint_ClearOUT();
  212. }
  213. break;
  214. case CDC_REQ_SetLineEncoding:
  215. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  216. {
  217. Endpoint_ClearSETUP();
  218. /* Read the line coding data in from the host into the global struct */
  219. Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  220. Endpoint_ClearIN();
  221. }
  222. break;
  223. }
  224. }
  225. #if !defined(NO_BLOCK_SUPPORT)
  226. /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
  227. * on the AVR910 protocol command issued.
  228. *
  229. * \param[in] Command Single character AVR910 protocol command indicating what memory operation to perform
  230. */
  231. static void ReadWriteMemoryBlock(const uint8_t Command)
  232. {
  233. uint16_t BlockSize;
  234. char MemoryType;
  235. bool HighByte = false;
  236. uint8_t LowByte = 0;
  237. BlockSize = (FetchNextCommandByte() << 8);
  238. BlockSize |= FetchNextCommandByte();
  239. MemoryType = FetchNextCommandByte();
  240. if ((MemoryType != 'E') && (MemoryType != 'F'))
  241. {
  242. /* Send error byte back to the host */
  243. WriteNextResponseByte('?');
  244. return;
  245. }
  246. /* Disable timer 1 interrupt - can't afford to process nonessential interrupts
  247. * while doing SPM tasks */
  248. TIMSK1 = 0;
  249. /* Check if command is to read memory */
  250. if (Command == 'g')
  251. {
  252. /* Re-enable RWW section */
  253. boot_rww_enable();
  254. while (BlockSize--)
  255. {
  256. if (MemoryType == 'F')
  257. {
  258. /* Read the next FLASH byte from the current FLASH page */
  259. #if (FLASHEND > 0xFFFF)
  260. WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte));
  261. #else
  262. WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte));
  263. #endif
  264. /* If both bytes in current word have been read, increment the address counter */
  265. if (HighByte)
  266. CurrAddress += 2;
  267. HighByte = !HighByte;
  268. }
  269. else
  270. {
  271. /* Read the next EEPROM byte into the endpoint */
  272. WriteNextResponseByte(eeprom_read_byte((uint8_t*)(intptr_t)(CurrAddress >> 1)));
  273. /* Increment the address counter after use */
  274. CurrAddress += 2;
  275. }
  276. }
  277. }
  278. else
  279. {
  280. uint32_t PageStartAddress = CurrAddress;
  281. if (MemoryType == 'F')
  282. {
  283. boot_page_erase(PageStartAddress);
  284. boot_spm_busy_wait();
  285. }
  286. while (BlockSize--)
  287. {
  288. if (MemoryType == 'F')
  289. {
  290. /* If both bytes in current word have been written, increment the address counter */
  291. if (HighByte)
  292. {
  293. /* Write the next FLASH word to the current FLASH page */
  294. boot_page_fill(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte));
  295. /* Increment the address counter after use */
  296. CurrAddress += 2;
  297. }
  298. else
  299. {
  300. LowByte = FetchNextCommandByte();
  301. }
  302. HighByte = !HighByte;
  303. }
  304. else
  305. {
  306. /* Write the next EEPROM byte from the endpoint */
  307. eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  308. /* Increment the address counter after use */
  309. CurrAddress += 2;
  310. }
  311. }
  312. /* If in FLASH programming mode, commit the page after writing */
  313. if (MemoryType == 'F')
  314. {
  315. /* Commit the flash page to memory */
  316. boot_page_write(PageStartAddress);
  317. /* Wait until write operation has completed */
  318. boot_spm_busy_wait();
  319. }
  320. /* Send response byte back to the host */
  321. WriteNextResponseByte('\r');
  322. }
  323. /* Re-enable timer 1 interrupt disabled earlier in this routine */
  324. TIMSK1 = (1 << OCIE1A);
  325. }
  326. #endif
  327. /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
  328. * to allow reception of the next data packet from the host.
  329. *
  330. * \return Next received byte from the host in the CDC data OUT endpoint
  331. */
  332. static uint8_t FetchNextCommandByte(void)
  333. {
  334. /* Select the OUT endpoint so that the next data byte can be read */
  335. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  336. /* If OUT endpoint empty, clear it and wait for the next packet from the host */
  337. while (!(Endpoint_IsReadWriteAllowed()))
  338. {
  339. Endpoint_ClearOUT();
  340. while (!(Endpoint_IsOUTReceived()))
  341. {
  342. if (USB_DeviceState == DEVICE_STATE_Unattached)
  343. return 0;
  344. }
  345. }
  346. /* Fetch the next byte from the OUT endpoint */
  347. return Endpoint_Read_8();
  348. }
  349. /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
  350. * bank when full ready for the next byte in the packet to the host.
  351. *
  352. * \param[in] Response Next response byte to send to the host
  353. */
  354. static void WriteNextResponseByte(const uint8_t Response)
  355. {
  356. /* Select the IN endpoint so that the next data byte can be written */
  357. Endpoint_SelectEndpoint(CDC_TX_EPNUM);
  358. /* If IN endpoint full, clear it and wait until ready for the next packet to the host */
  359. if (!(Endpoint_IsReadWriteAllowed()))
  360. {
  361. Endpoint_ClearIN();
  362. while (!(Endpoint_IsINReady()))
  363. {
  364. if (USB_DeviceState == DEVICE_STATE_Unattached)
  365. return;
  366. }
  367. }
  368. /* Write the next byte to the IN endpoint */
  369. Endpoint_Write_8(Response);
  370. TX_LED_ON();
  371. TxLEDPulse = TX_RX_LED_PULSE_PERIOD;
  372. }
  373. #define STK_OK 0x10
  374. #define STK_INSYNC 0x14 // ' '
  375. #define CRC_EOP 0x20 // 'SPACE'
  376. #define STK_GET_SYNC 0x30 // '0'
  377. #define STK_GET_PARAMETER 0x41 // 'A'
  378. #define STK_SET_DEVICE 0x42 // 'B'
  379. #define STK_SET_DEVICE_EXT 0x45 // 'E'
  380. #define STK_LOAD_ADDRESS 0x55 // 'U'
  381. #define STK_UNIVERSAL 0x56 // 'V'
  382. #define STK_PROG_PAGE 0x64 // 'd'
  383. #define STK_READ_PAGE 0x74 // 't'
  384. #define STK_READ_SIGN 0x75 // 'u'
  385. /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions
  386. * and send the appropriate response back to the host.
  387. */
  388. void CDC_Task(void)
  389. {
  390. /* Select the OUT endpoint */
  391. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  392. /* Check if endpoint has a command in it sent from the host */
  393. if (!(Endpoint_IsOUTReceived()))
  394. return;
  395. RX_LED_ON();
  396. RxLEDPulse = TX_RX_LED_PULSE_PERIOD;
  397. /* Read in the bootloader command (first byte sent from host) */
  398. uint8_t Command = FetchNextCommandByte();
  399. if (Command == 'E')
  400. {
  401. /* We nearly run out the bootloader timeout clock,
  402. * leaving just a few hundred milliseconds so the
  403. * bootloder has time to respond and service any
  404. * subsequent requests */
  405. Timeout = TIMEOUT_PERIOD - 500;
  406. /* Re-enable RWW section - must be done here in case
  407. * user has disabled verification on upload. */
  408. boot_rww_enable_safe();
  409. // Send confirmation byte back to the host
  410. WriteNextResponseByte('\r');
  411. }
  412. else if (Command == 'T')
  413. {
  414. FetchNextCommandByte();
  415. // Send confirmation byte back to the host
  416. WriteNextResponseByte('\r');
  417. }
  418. else if ((Command == 'L') || (Command == 'P'))
  419. {
  420. // Send confirmation byte back to the host
  421. WriteNextResponseByte('\r');
  422. }
  423. else if (Command == 't')
  424. {
  425. // Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader
  426. WriteNextResponseByte(0x44);
  427. WriteNextResponseByte(0x00);
  428. }
  429. else if (Command == 'a')
  430. {
  431. // Indicate auto-address increment is supported
  432. WriteNextResponseByte('Y');
  433. }
  434. else if (Command == 'A')
  435. {
  436. // Set the current address to that given by the host
  437. CurrAddress = (FetchNextCommandByte() << 9);
  438. CurrAddress |= (FetchNextCommandByte() << 1);
  439. // Send confirmation byte back to the host
  440. WriteNextResponseByte('\r');
  441. }
  442. else if (Command == 'p')
  443. {
  444. // Indicate serial programmer back to the host
  445. WriteNextResponseByte('S');
  446. }
  447. else if (Command == 'S')
  448. {
  449. // Write the 7-byte software identifier to the endpoint
  450. for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++)
  451. WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]);
  452. }
  453. else if (Command == 'V')
  454. {
  455. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR);
  456. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR);
  457. }
  458. else if (Command == 's')
  459. {
  460. WriteNextResponseByte(AVR_SIGNATURE_3);
  461. WriteNextResponseByte(AVR_SIGNATURE_2);
  462. WriteNextResponseByte(AVR_SIGNATURE_1);
  463. }
  464. else if (Command == 'e')
  465. {
  466. // Clear the application section of flash
  467. for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
  468. {
  469. boot_page_erase(CurrFlashAddress);
  470. boot_spm_busy_wait();
  471. boot_page_write(CurrFlashAddress);
  472. boot_spm_busy_wait();
  473. }
  474. // Send confirmation byte back to the host
  475. WriteNextResponseByte('\r');
  476. }
  477. #if !defined(NO_LOCK_BYTE_WRITE_SUPPORT)
  478. else if (Command == 'l')
  479. {
  480. // Set the lock bits to those given by the host
  481. boot_lock_bits_set(FetchNextCommandByte());
  482. // Send confirmation byte back to the host
  483. WriteNextResponseByte('\r');
  484. }
  485. #endif
  486. else if (Command == 'r')
  487. {
  488. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS));
  489. }
  490. else if (Command == 'F')
  491. {
  492. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS));
  493. }
  494. else if (Command == 'N')
  495. {
  496. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS));
  497. }
  498. else if (Command == 'Q')
  499. {
  500. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS));
  501. }
  502. #if !defined(NO_BLOCK_SUPPORT)
  503. else if (Command == 'b')
  504. {
  505. WriteNextResponseByte('Y');
  506. // Send block size to the host
  507. WriteNextResponseByte(SPM_PAGESIZE >> 8);
  508. WriteNextResponseByte(SPM_PAGESIZE & 0xFF);
  509. }
  510. else if ((Command == 'B') || (Command == 'g'))
  511. {
  512. // Keep resetting the timeout counter if we're receiving self-programming instructions
  513. Timeout = 0;
  514. // Delegate the block write/read to a separate function for clarity
  515. ReadWriteMemoryBlock(Command);
  516. }
  517. #endif
  518. #if !defined(NO_FLASH_BYTE_SUPPORT)
  519. else if (Command == 'C')
  520. {
  521. // Write the high byte to the current flash page
  522. boot_page_fill(CurrAddress, FetchNextCommandByte());
  523. // Send confirmation byte back to the host
  524. WriteNextResponseByte('\r');
  525. }
  526. else if (Command == 'c')
  527. {
  528. // Write the low byte to the current flash page
  529. boot_page_fill(CurrAddress | 0x01, FetchNextCommandByte());
  530. // Increment the address
  531. CurrAddress += 2;
  532. // Send confirmation byte back to the host
  533. WriteNextResponseByte('\r');
  534. }
  535. else if (Command == 'm')
  536. {
  537. // Commit the flash page to memory
  538. boot_page_write(CurrAddress);
  539. // Wait until write operation has completed
  540. boot_spm_busy_wait();
  541. // Send confirmation byte back to the host
  542. WriteNextResponseByte('\r');
  543. }
  544. else if (Command == 'R')
  545. {
  546. #if (FLASHEND > 0xFFFF)
  547. uint16_t ProgramWord = pgm_read_word_far(CurrAddress);
  548. #else
  549. uint16_t ProgramWord = pgm_read_word(CurrAddress);
  550. #endif
  551. WriteNextResponseByte(ProgramWord >> 8);
  552. WriteNextResponseByte(ProgramWord & 0xFF);
  553. }
  554. #endif
  555. #if !defined(NO_EEPROM_BYTE_SUPPORT)
  556. else if (Command == 'D')
  557. {
  558. // Read the byte from the endpoint and write it to the EEPROM
  559. eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  560. // Increment the address after use
  561. CurrAddress += 2;
  562. // Send confirmation byte back to the host
  563. WriteNextResponseByte('\r');
  564. }
  565. else if (Command == 'd')
  566. {
  567. // Read the EEPROM byte and write it to the endpoint
  568. WriteNextResponseByte(eeprom_read_byte((uint8_t*)((intptr_t)(CurrAddress >> 1))));
  569. // Increment the address after use
  570. CurrAddress += 2;
  571. }
  572. #endif
  573. else if (Command != 27)
  574. {
  575. // Unknown (non-sync) command, return fail code
  576. WriteNextResponseByte('?');
  577. }
  578. /* Select the IN endpoint */
  579. Endpoint_SelectEndpoint(CDC_TX_EPNUM);
  580. /* Remember if the endpoint is completely full before clearing it */
  581. bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
  582. /* Send the endpoint data to the host */
  583. Endpoint_ClearIN();
  584. /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
  585. if (IsEndpointFull)
  586. {
  587. while (!(Endpoint_IsINReady()))
  588. {
  589. if (USB_DeviceState == DEVICE_STATE_Unattached)
  590. return;
  591. }
  592. Endpoint_ClearIN();
  593. }
  594. /* Wait until the data has been sent to the host */
  595. while (!(Endpoint_IsINReady()))
  596. {
  597. if (USB_DeviceState == DEVICE_STATE_Unattached)
  598. return;
  599. }
  600. /* Select the OUT endpoint */
  601. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  602. /* Acknowledge the command from the host */
  603. Endpoint_ClearOUT();
  604. }