Caterina.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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. // MAH 8/15/12- change so timeouts work properly when the chip is running at 8MHz instead of 16.
  55. #define TIMEOUT_PERIOD 8000
  56. #define EXT_RESET_TIMEOUT_PERIOD 750
  57. /*********************************************************************************************************
  58. LilyPadUSB bootloader code
  59. The LilyPadUSB bootloader has been changed to remove the 8-second delay after external reset which is in
  60. the Leonardo. To enter the bootloader, the user should execute TWO external resets within 750 ms; that is,
  61. press the reset button twice, quickly.\
  62. Some other changes were made to allow this code to compile tightly enough to fit in the alloted 4k of
  63. bootloader space.
  64. */
  65. // MAH 8/15/12- added this flag to replace the bulky program memory reads to check for the presence of a sketch
  66. // at the top of the memory space.
  67. static bool sketchPresent = false;
  68. // MAH 8/15/12- make this volatile, since we modify it in one place and read it in another, we want to make
  69. // sure we're always working on the copy in memory and not an erroneous value stored in a cache somewhere.
  70. // This variable stores the length of time we've been in the bootloader when waiting for the 8 second delay.
  71. volatile uint16_t Timeout = 0;
  72. // MAH 8/15/12- added this for delay during startup. Did not use existing Timeout value b/c it only increments
  73. // when there's a sketch at the top of the memory.
  74. volatile uint16_t resetTimeout = 0;
  75. // MAH 8/15/12- let's make this an 8-bit value instead of 16- that saves on memory because 16-bit addition and
  76. // comparison compiles to bulkier code. Note that this does *not* require a change to the Arduino core- we're
  77. // just sort of ignoring the extra byte that the Arduino core puts at the next location.
  78. uint8_t bootKey = 0x77;
  79. volatile uint8_t *const bootKeyPtr = (volatile uint8_t *)0x0800;
  80. // StartSketch() is called to clean up our mess before passing execution to the sketch.
  81. void StartSketch(void)
  82. {
  83. cli();
  84. /* Undo TIMER1 setup and clear the count before running the sketch */
  85. TIMSK1 = 0;
  86. TCCR1B = 0;
  87. /* Relocate the interrupt vector table to the application section */
  88. MCUCR = (1 << IVCE);
  89. MCUCR = 0;
  90. L_LED_OFF();
  91. TX_LED_OFF();
  92. RX_LED_OFF();
  93. /* jump to beginning of application space */
  94. __asm__ volatile("jmp 0x0000");
  95. }
  96. uint16_t LLEDPulse;
  97. /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
  98. * runs the bootloader processing routine until it times out or is instructed to exit.
  99. */
  100. int main(void)
  101. {
  102. /* Save the value of the boot key memory before it is overwritten */
  103. uint8_t bootKeyPtrVal = *bootKeyPtr;
  104. *bootKeyPtr = 0;
  105. /* Check the reason for the reset so we can act accordingly */
  106. uint8_t mcusr_state = MCUSR; // store the initial state of the Status register
  107. MCUSR = 0; // clear all reset flags
  108. /* Watchdog may be configured with a 15 ms period so must disable it before going any further */
  109. // MAH 8/15/12- I removed this because wdt_disable() is the first thing SetupHardware() does- why
  110. // do it twice right in a row?
  111. //wdt_disable();
  112. /* Setup hardware required for the bootloader */
  113. // MAH 8/15/12- Moved this up to before the bootloader go/no-go decision tree so I could use the
  114. // timer in that decision tree. Removed the USBInit() call from it; if I'm not going to stay in
  115. // the bootloader, there's no point spending the time initializing the USB.
  116. // SetupHardware();
  117. wdt_disable();
  118. // Disable clock division
  119. clock_prescale_set(clock_div_1);
  120. // Relocate the interrupt vector table to the bootloader section
  121. MCUCR = (1 << IVCE);
  122. MCUCR = (1 << IVSEL);
  123. LED_SETUP();
  124. CPU_PRESCALE(0);
  125. L_LED_OFF();
  126. TX_LED_OFF();
  127. RX_LED_OFF();
  128. // Initialize TIMER1 to handle bootloader timeout and LED tasks.
  129. // With 16 MHz clock and 1/64 prescaler, timer 1 is clocked at 250 kHz
  130. // Our chosen compare match generates an interrupt every 1 ms.
  131. // This interrupt is disabled selectively when doing memory reading, erasing,
  132. // or writing since SPM has tight timing requirements.
  133. OCR1AH = 0;
  134. OCR1AL = 250;
  135. TIMSK1 = (1 << OCIE1A); // enable timer 1 output compare A match interrupt
  136. TCCR1B = ((1 << CS11) | (1 << CS10)); // 1/64 prescaler on timer 1 input
  137. // MAH 8/15/12- this replaces bulky pgm_read_word(0) calls later on, to save memory.
  138. if (pgm_read_word(0) != 0xFFFF) sketchPresent = true;
  139. // MAH 26 Oct 2012- The "bootload or not?" section has been modified since the code released
  140. // with Arduino 1.0.1. The simplest modification is the replacement of equivalence checks on
  141. // the reset bits with masked checks, so if more than one reset occurs before the register is
  142. // checked, the check doesn't fail and fall through to the bootloader unnecessarily.
  143. // The second, more in depth modification addresses behavior after an external reset (i.e.,
  144. // user pushes the reset button). The Leonardo treats all external resets as requests to
  145. // re-enter the bootloader and wait for code to be loaded. It remains in bootloader mode for
  146. // 8 seconds before continuing on to the sketch (if one is present). By defining RESET_DELAY
  147. // equal to 1, this behavior will persist.
  148. // However, if RESET_DELAY is defined to 0, the reset timeout before loading the sketch drops
  149. // to 750ms. If, during that 750ms, another external reset occurs, THEN an 8-second delay
  150. // in the bootloader will occur.
  151. // This is the "no-8-second-delay" code. If this is the first time through the loop, we
  152. // don't expect to see the bootKey in memory.
  153. if ( (mcusr_state & (1<<EXTRF)) && (bootKeyPtrVal != bootKey) ) {
  154. *bootKeyPtr = bootKey; // Put the bootKey in memory so if we get back to this
  155. // point again, we know to jump into the bootloader
  156. sei(); // Enable interrupts, so we can use timer1 to track our time in the bootloader
  157. while (RunBootloader)
  158. {
  159. if (resetTimeout > EXT_RESET_TIMEOUT_PERIOD) // resetTimeout is getting incremeted
  160. RunBootloader = false; // in the timer1 ISR.
  161. }
  162. // If we make it past that while loop, it's sketch loading time!
  163. *bootKeyPtr = 0; // clear out the bootKey; from now on, we want to treat a reset like
  164. // a normal reset.
  165. cli(); // Disable interrupts, in case no sketch is present.
  166. RunBootloader = true; // We want to hang out in the bootloader if no sketch is present.
  167. if (sketchPresent) StartSketch(); // If a sketch is present, go! Otherwise, wait around
  168. // in the bootloader until one is uploaded.
  169. }
  170. // On a power-on reset, we ALWAYS want to go to the sketch. If there is one.
  171. // This is a place where the old code had an equivalence and now there is a mask.
  172. else if ( (mcusr_state & (1<<PORF)) && sketchPresent) {
  173. StartSketch();
  174. }
  175. // On a watchdog reset, if the bootKey isn't set, and there's a sketch, we should just
  176. // go straight to the sketch.
  177. // This is a place where the old code had an equivalence and now there is a mask.
  178. else if ( (mcusr_state & (1<<WDRF) ) && (bootKeyPtrVal != bootKey) && sketchPresent) {
  179. // If it looks like an "accidental" watchdog reset then start the sketch.
  180. StartSketch();
  181. }
  182. /* Initialize USB Subsystem */
  183. USB_Init();
  184. /* Enable global interrupts so that the USB stack can function */
  185. sei();
  186. Timeout = 0;
  187. while (RunBootloader)
  188. {
  189. CDC_Task();
  190. USB_USBTask();
  191. /* Time out and start the sketch if one is present */
  192. if (Timeout > TIMEOUT_PERIOD)
  193. RunBootloader = false;
  194. // MAH 8/15/12- This used to be a function call- inlining it saves a few bytes.
  195. LLEDPulse++;
  196. uint8_t p = LLEDPulse >> 8;
  197. if (p > 127)
  198. p = 254-p;
  199. p += p;
  200. if (((uint8_t)LLEDPulse) > p)
  201. L_LED_OFF();
  202. else
  203. L_LED_ON();
  204. }
  205. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  206. USB_Detach();
  207. /* Jump to beginning of application space to run the sketch - do not reset */
  208. StartSketch();
  209. }
  210. // Timer1 is set up to provide periodic interrupts. This is used to flicker the LEDs during
  211. // programming as well as to generate the clock counts which determine how long the board should
  212. // remain in bootloading mode.
  213. ISR(TIMER1_COMPA_vect, ISR_BLOCK)
  214. {
  215. /* Reset counter */
  216. TCNT1H = 0;
  217. TCNT1L = 0;
  218. /* Check whether the TX or RX LED one-shot period has elapsed. if so, turn off the LED */
  219. if (TxLEDPulse && !(--TxLEDPulse))
  220. TX_LED_OFF();
  221. if (RxLEDPulse && !(--RxLEDPulse))
  222. RX_LED_OFF();
  223. resetTimeout++; // Needed for the "short reset delay" mode- governs the time the board waits
  224. // for a second reset before loading the sketch.
  225. if (pgm_read_word(0) != 0xFFFF)
  226. Timeout++;
  227. }
  228. // MAH 29 Oct 2012 Nothing below this point has to change for the LilyPadUSB support
  229. /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
  230. * to relay data to and from the attached USB host.
  231. */
  232. void EVENT_USB_Device_ConfigurationChanged(void)
  233. {
  234. /* Setup CDC Notification, Rx and Tx Endpoints */
  235. Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
  236. ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
  237. ENDPOINT_BANK_SINGLE);
  238. Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
  239. ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
  240. ENDPOINT_BANK_SINGLE);
  241. Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
  242. ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
  243. ENDPOINT_BANK_SINGLE);
  244. }
  245. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  246. * the device from the USB host before passing along unhandled control requests to the library for processing
  247. * internally.
  248. */
  249. void EVENT_USB_Device_ControlRequest(void)
  250. {
  251. /* Ignore any requests that aren't directed to the CDC interface */
  252. if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
  253. (REQTYPE_CLASS | REQREC_INTERFACE))
  254. {
  255. return;
  256. }
  257. /* Process CDC specific control requests */
  258. switch (USB_ControlRequest.bRequest)
  259. {
  260. case CDC_REQ_GetLineEncoding:
  261. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  262. {
  263. Endpoint_ClearSETUP();
  264. /* Write the line coding data to the control endpoint */
  265. Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  266. Endpoint_ClearOUT();
  267. }
  268. break;
  269. case CDC_REQ_SetLineEncoding:
  270. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  271. {
  272. Endpoint_ClearSETUP();
  273. /* Read the line coding data in from the host into the global struct */
  274. Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
  275. Endpoint_ClearIN();
  276. }
  277. break;
  278. }
  279. }
  280. #if !defined(NO_BLOCK_SUPPORT)
  281. /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
  282. * on the AVR910 protocol command issued.
  283. *
  284. * \param[in] Command Single character AVR910 protocol command indicating what memory operation to perform
  285. */
  286. static void ReadWriteMemoryBlock(const uint8_t Command)
  287. {
  288. uint16_t BlockSize;
  289. char MemoryType;
  290. bool HighByte = false;
  291. uint8_t LowByte = 0;
  292. BlockSize = (FetchNextCommandByte() << 8);
  293. BlockSize |= FetchNextCommandByte();
  294. MemoryType = FetchNextCommandByte();
  295. if ((MemoryType != 'E') && (MemoryType != 'F'))
  296. {
  297. /* Send error byte back to the host */
  298. WriteNextResponseByte('?');
  299. return;
  300. }
  301. /* Disable timer 1 interrupt - can't afford to process nonessential interrupts
  302. * while doing SPM tasks */
  303. TIMSK1 = 0;
  304. /* Check if command is to read memory */
  305. if (Command == 'g')
  306. {
  307. /* Re-enable RWW section */
  308. boot_rww_enable();
  309. while (BlockSize--)
  310. {
  311. if (MemoryType == 'F')
  312. {
  313. /* Read the next FLASH byte from the current FLASH page */
  314. #if (FLASHEND > 0xFFFF)
  315. WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte));
  316. #else
  317. WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte));
  318. #endif
  319. /* If both bytes in current word have been read, increment the address counter */
  320. if (HighByte)
  321. CurrAddress += 2;
  322. HighByte = !HighByte;
  323. }
  324. else
  325. {
  326. /* Read the next EEPROM byte into the endpoint */
  327. WriteNextResponseByte(eeprom_read_byte((uint8_t*)(intptr_t)(CurrAddress >> 1)));
  328. /* Increment the address counter after use */
  329. CurrAddress += 2;
  330. }
  331. }
  332. }
  333. else
  334. {
  335. uint32_t PageStartAddress = CurrAddress;
  336. if (MemoryType == 'F')
  337. {
  338. boot_page_erase(PageStartAddress);
  339. boot_spm_busy_wait();
  340. }
  341. while (BlockSize--)
  342. {
  343. if (MemoryType == 'F')
  344. {
  345. /* If both bytes in current word have been written, increment the address counter */
  346. if (HighByte)
  347. {
  348. /* Write the next FLASH word to the current FLASH page */
  349. boot_page_fill(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte));
  350. /* Increment the address counter after use */
  351. CurrAddress += 2;
  352. }
  353. else
  354. {
  355. LowByte = FetchNextCommandByte();
  356. }
  357. HighByte = !HighByte;
  358. }
  359. else
  360. {
  361. /* Write the next EEPROM byte from the endpoint */
  362. eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  363. /* Increment the address counter after use */
  364. CurrAddress += 2;
  365. }
  366. }
  367. /* If in FLASH programming mode, commit the page after writing */
  368. if (MemoryType == 'F')
  369. {
  370. /* Commit the flash page to memory */
  371. boot_page_write(PageStartAddress);
  372. /* Wait until write operation has completed */
  373. boot_spm_busy_wait();
  374. }
  375. /* Send response byte back to the host */
  376. WriteNextResponseByte('\r');
  377. }
  378. /* Re-enable timer 1 interrupt disabled earlier in this routine */
  379. TIMSK1 = (1 << OCIE1A);
  380. }
  381. #endif
  382. /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
  383. * to allow reception of the next data packet from the host.
  384. *
  385. * \return Next received byte from the host in the CDC data OUT endpoint
  386. */
  387. static uint8_t FetchNextCommandByte(void)
  388. {
  389. /* Select the OUT endpoint so that the next data byte can be read */
  390. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  391. /* If OUT endpoint empty, clear it and wait for the next packet from the host */
  392. while (!(Endpoint_IsReadWriteAllowed()))
  393. {
  394. Endpoint_ClearOUT();
  395. while (!(Endpoint_IsOUTReceived()))
  396. {
  397. if (USB_DeviceState == DEVICE_STATE_Unattached)
  398. return 0;
  399. }
  400. }
  401. /* Fetch the next byte from the OUT endpoint */
  402. return Endpoint_Read_8();
  403. }
  404. /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
  405. * bank when full ready for the next byte in the packet to the host.
  406. *
  407. * \param[in] Response Next response byte to send to the host
  408. */
  409. static void WriteNextResponseByte(const uint8_t Response)
  410. {
  411. /* Select the IN endpoint so that the next data byte can be written */
  412. Endpoint_SelectEndpoint(CDC_TX_EPNUM);
  413. /* If IN endpoint full, clear it and wait until ready for the next packet to the host */
  414. if (!(Endpoint_IsReadWriteAllowed()))
  415. {
  416. Endpoint_ClearIN();
  417. while (!(Endpoint_IsINReady()))
  418. {
  419. if (USB_DeviceState == DEVICE_STATE_Unattached)
  420. return;
  421. }
  422. }
  423. /* Write the next byte to the IN endpoint */
  424. Endpoint_Write_8(Response);
  425. TX_LED_ON();
  426. TxLEDPulse = TX_RX_LED_PULSE_PERIOD;
  427. }
  428. #define STK_OK 0x10
  429. #define STK_INSYNC 0x14 // ' '
  430. #define CRC_EOP 0x20 // 'SPACE'
  431. #define STK_GET_SYNC 0x30 // '0'
  432. #define STK_GET_PARAMETER 0x41 // 'A'
  433. #define STK_SET_DEVICE 0x42 // 'B'
  434. #define STK_SET_DEVICE_EXT 0x45 // 'E'
  435. #define STK_LOAD_ADDRESS 0x55 // 'U'
  436. #define STK_UNIVERSAL 0x56 // 'V'
  437. #define STK_PROG_PAGE 0x64 // 'd'
  438. #define STK_READ_PAGE 0x74 // 't'
  439. #define STK_READ_SIGN 0x75 // 'u'
  440. /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions
  441. * and send the appropriate response back to the host.
  442. */
  443. void CDC_Task(void)
  444. {
  445. /* Select the OUT endpoint */
  446. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  447. /* Check if endpoint has a command in it sent from the host */
  448. if (!(Endpoint_IsOUTReceived()))
  449. return;
  450. RX_LED_ON();
  451. RxLEDPulse = TX_RX_LED_PULSE_PERIOD;
  452. /* Read in the bootloader command (first byte sent from host) */
  453. uint8_t Command = FetchNextCommandByte();
  454. if (Command == 'E')
  455. {
  456. /* We nearly run out the bootloader timeout clock,
  457. * leaving just a few hundred milliseconds so the
  458. * bootloder has time to respond and service any
  459. * subsequent requests */
  460. Timeout = TIMEOUT_PERIOD - 500;
  461. /* Re-enable RWW section - must be done here in case
  462. * user has disabled verification on upload. */
  463. boot_rww_enable_safe();
  464. // Send confirmation byte back to the host
  465. WriteNextResponseByte('\r');
  466. }
  467. else if (Command == 'T')
  468. {
  469. FetchNextCommandByte();
  470. // Send confirmation byte back to the host
  471. WriteNextResponseByte('\r');
  472. }
  473. else if ((Command == 'L') || (Command == 'P'))
  474. {
  475. // Send confirmation byte back to the host
  476. WriteNextResponseByte('\r');
  477. }
  478. else if (Command == 't')
  479. {
  480. // Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader
  481. WriteNextResponseByte(0x44);
  482. WriteNextResponseByte(0x00);
  483. }
  484. else if (Command == 'a')
  485. {
  486. // Indicate auto-address increment is supported
  487. WriteNextResponseByte('Y');
  488. }
  489. else if (Command == 'A')
  490. {
  491. // Set the current address to that given by the host
  492. CurrAddress = (FetchNextCommandByte() << 9);
  493. CurrAddress |= (FetchNextCommandByte() << 1);
  494. // Send confirmation byte back to the host
  495. WriteNextResponseByte('\r');
  496. }
  497. else if (Command == 'p')
  498. {
  499. // Indicate serial programmer back to the host
  500. WriteNextResponseByte('S');
  501. }
  502. else if (Command == 'S')
  503. {
  504. // Write the 7-byte software identifier to the endpoint
  505. for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++)
  506. WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]);
  507. }
  508. else if (Command == 'V')
  509. {
  510. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR);
  511. WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR);
  512. }
  513. else if (Command == 's')
  514. {
  515. WriteNextResponseByte(AVR_SIGNATURE_3);
  516. WriteNextResponseByte(AVR_SIGNATURE_2);
  517. WriteNextResponseByte(AVR_SIGNATURE_1);
  518. }
  519. else if (Command == 'e')
  520. {
  521. // Clear the application section of flash
  522. for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
  523. {
  524. boot_page_erase(CurrFlashAddress);
  525. boot_spm_busy_wait();
  526. boot_page_write(CurrFlashAddress);
  527. boot_spm_busy_wait();
  528. }
  529. // Send confirmation byte back to the host
  530. WriteNextResponseByte('\r');
  531. }
  532. #if !defined(NO_LOCK_BYTE_WRITE_SUPPORT)
  533. else if (Command == 'l')
  534. {
  535. // Set the lock bits to those given by the host
  536. boot_lock_bits_set(FetchNextCommandByte());
  537. // Send confirmation byte back to the host
  538. WriteNextResponseByte('\r');
  539. }
  540. #endif
  541. else if (Command == 'r')
  542. {
  543. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS));
  544. }
  545. else if (Command == 'F')
  546. {
  547. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS));
  548. }
  549. else if (Command == 'N')
  550. {
  551. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS));
  552. }
  553. else if (Command == 'Q')
  554. {
  555. WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS));
  556. }
  557. #if !defined(NO_BLOCK_SUPPORT)
  558. else if (Command == 'b')
  559. {
  560. WriteNextResponseByte('Y');
  561. // Send block size to the host
  562. WriteNextResponseByte(SPM_PAGESIZE >> 8);
  563. WriteNextResponseByte(SPM_PAGESIZE & 0xFF);
  564. }
  565. else if ((Command == 'B') || (Command == 'g'))
  566. {
  567. // Keep resetting the timeout counter if we're receiving self-programming instructions
  568. Timeout = 0;
  569. // Delegate the block write/read to a separate function for clarity
  570. ReadWriteMemoryBlock(Command);
  571. }
  572. #endif
  573. #if !defined(NO_FLASH_BYTE_SUPPORT)
  574. else if (Command == 'C')
  575. {
  576. // Write the high byte to the current flash page
  577. boot_page_fill(CurrAddress, FetchNextCommandByte());
  578. // Send confirmation byte back to the host
  579. WriteNextResponseByte('\r');
  580. }
  581. else if (Command == 'c')
  582. {
  583. // Write the low byte to the current flash page
  584. boot_page_fill(CurrAddress | 0x01, FetchNextCommandByte());
  585. // Increment the address
  586. CurrAddress += 2;
  587. // Send confirmation byte back to the host
  588. WriteNextResponseByte('\r');
  589. }
  590. else if (Command == 'm')
  591. {
  592. // Commit the flash page to memory
  593. boot_page_write(CurrAddress);
  594. // Wait until write operation has completed
  595. boot_spm_busy_wait();
  596. // Send confirmation byte back to the host
  597. WriteNextResponseByte('\r');
  598. }
  599. else if (Command == 'R')
  600. {
  601. #if (FLASHEND > 0xFFFF)
  602. uint16_t ProgramWord = pgm_read_word_far(CurrAddress);
  603. #else
  604. uint16_t ProgramWord = pgm_read_word(CurrAddress);
  605. #endif
  606. WriteNextResponseByte(ProgramWord >> 8);
  607. WriteNextResponseByte(ProgramWord & 0xFF);
  608. }
  609. #endif
  610. #if !defined(NO_EEPROM_BYTE_SUPPORT)
  611. else if (Command == 'D')
  612. {
  613. // Read the byte from the endpoint and write it to the EEPROM
  614. eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress >> 1)), FetchNextCommandByte());
  615. // Increment the address after use
  616. CurrAddress += 2;
  617. // Send confirmation byte back to the host
  618. WriteNextResponseByte('\r');
  619. }
  620. else if (Command == 'd')
  621. {
  622. // Read the EEPROM byte and write it to the endpoint
  623. WriteNextResponseByte(eeprom_read_byte((uint8_t*)((intptr_t)(CurrAddress >> 1))));
  624. // Increment the address after use
  625. CurrAddress += 2;
  626. }
  627. #endif
  628. else if (Command != 27)
  629. {
  630. // Unknown (non-sync) command, return fail code
  631. WriteNextResponseByte('?');
  632. }
  633. /* Select the IN endpoint */
  634. Endpoint_SelectEndpoint(CDC_TX_EPNUM);
  635. /* Remember if the endpoint is completely full before clearing it */
  636. bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
  637. /* Send the endpoint data to the host */
  638. Endpoint_ClearIN();
  639. /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
  640. if (IsEndpointFull)
  641. {
  642. while (!(Endpoint_IsINReady()))
  643. {
  644. if (USB_DeviceState == DEVICE_STATE_Unattached)
  645. return;
  646. }
  647. Endpoint_ClearIN();
  648. }
  649. /* Wait until the data has been sent to the host */
  650. while (!(Endpoint_IsINReady()))
  651. {
  652. if (USB_DeviceState == DEVICE_STATE_Unattached)
  653. return;
  654. }
  655. /* Select the OUT endpoint */
  656. Endpoint_SelectEndpoint(CDC_RX_EPNUM);
  657. /* Acknowledge the command from the host */
  658. Endpoint_ClearOUT();
  659. }