BootloaderPrinter.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 Printer class bootloader. This file contains the complete bootloader logic.
  29. */
  30. #include "BootloaderPrinter.h"
  31. /** LUFA Printer Class driver interface configuration and state information. This structure is
  32. * passed to all Printer Class driver functions, so that multiple instances of the same class
  33. * within a device can be differentiated from one another.
  34. */
  35. USB_ClassInfo_PRNT_Device_t TextOnly_Printer_Interface =
  36. {
  37. .Config =
  38. {
  39. .InterfaceNumber = INTERFACE_ID_Printer,
  40. .DataINEndpoint =
  41. {
  42. .Address = PRINTER_IN_EPADDR,
  43. .Size = PRINTER_IO_EPSIZE,
  44. .Banks = 1,
  45. },
  46. .DataOUTEndpoint =
  47. {
  48. .Address = PRINTER_OUT_EPADDR,
  49. .Size = PRINTER_IO_EPSIZE,
  50. .Banks = 1,
  51. },
  52. .IEEE1284String =
  53. "MFG:Generic;"
  54. "MDL:Generic_/_Text_Only;"
  55. "CMD:1284.4;"
  56. "CLS:PRINTER",
  57. },
  58. };
  59. /** Intel HEX parser state machine state information, to track the contents of
  60. * a HEX file streamed in as a sequence of arbitrary bytes.
  61. */
  62. struct
  63. {
  64. /** Current HEX parser state machine state. */
  65. uint8_t ParserState;
  66. /** Previously decoded numerical byte of data. */
  67. uint8_t PrevData;
  68. /** Currently decoded numerical byte of data. */
  69. uint8_t Data;
  70. /** Indicates if both bytes that correspond to a single decoded numerical
  71. * byte of data (HEX encodes values in ASCII HEX, two characters per byte)
  72. * have been read.
  73. */
  74. bool ReadMSB;
  75. /** Intel HEX record type of the current Intel HEX record. */
  76. uint8_t RecordType;
  77. /** Numerical bytes of data remaining to be read in the current record. */
  78. uint8_t DataRem;
  79. /** Checksum of the current record received so far. */
  80. uint8_t Checksum;
  81. /** Starting address of the last addressed FLASH page. */
  82. uint32_t PageStartAddress;
  83. /** Current 32-bit byte extended base address in FLASH being targeted. */
  84. uint32_t CurrBaseAddress;
  85. /** Current 32-bit byte address in FLASH being targeted. */
  86. uint32_t CurrAddress;
  87. } HEXParser;
  88. /** Indicates if there is data waiting to be written to a physical page of
  89. * memory in FLASH.
  90. */
  91. static bool PageDirty = false;
  92. /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
  93. * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
  94. * started via a forced watchdog reset.
  95. */
  96. static bool RunBootloader = true;
  97. /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
  98. * 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
  99. * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
  100. * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
  101. */
  102. uint16_t MagicBootKey ATTR_NO_INIT;
  103. /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
  104. * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
  105. * this will force the user application to start via a software jump.
  106. */
  107. void Application_Jump_Check(void)
  108. {
  109. bool JumpToApplication = false;
  110. #if (BOARD == BOARD_LEONARDO)
  111. /* Enable pull-up on the IO13 pin so we can use it to select the mode */
  112. PORTC |= (1 << 7);
  113. Delay_MS(10);
  114. /* If IO13 is not jumpered to ground, start the user application instead */
  115. JumpToApplication = ((PINC & (1 << 7)) != 0);
  116. /* Disable pull-up after the check has completed */
  117. PORTC &= ~(1 << 7);
  118. #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
  119. /* Disable JTAG debugging */
  120. JTAG_DISABLE();
  121. /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
  122. PORTF |= (1 << 4);
  123. Delay_MS(10);
  124. /* If the TCK pin is not jumpered to ground, start the user application instead */
  125. JumpToApplication = ((PINF & (1 << 4)) != 0);
  126. /* Re-enable JTAG debugging */
  127. JTAG_ENABLE();
  128. #else
  129. /* Check if the device's BOOTRST fuse is set */
  130. if (BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & FUSE_BOOTRST)
  131. {
  132. /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
  133. if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
  134. JumpToApplication = true;
  135. /* Clear reset source */
  136. MCUSR &= ~(1 << EXTRF);
  137. }
  138. else
  139. {
  140. /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
  141. * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
  142. if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
  143. JumpToApplication = true;
  144. /* Clear reset source */
  145. MCUSR &= ~(1 << WDRF);
  146. }
  147. #endif
  148. /* Don't run the user application if the reset vector is blank (no app loaded) */
  149. bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
  150. /* If a request has been made to jump to the user application, honor it */
  151. if (JumpToApplication && ApplicationValid)
  152. {
  153. /* Turn off the watchdog */
  154. MCUSR &= ~(1 << WDRF);
  155. wdt_disable();
  156. /* Clear the boot key and jump to the user application */
  157. MagicBootKey = 0;
  158. // cppcheck-suppress constStatement
  159. ((void (*)(void))0x0000)();
  160. }
  161. }
  162. /**
  163. * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
  164. *
  165. * \note Input HEX bytes are expected to be in uppercase only.
  166. *
  167. * \param[in] Byte ASCII byte of data to convert
  168. *
  169. * \return Integer converted value of the input ASCII encoded HEX byte of data, or -1 if the
  170. * input is not valid ASCII encoded HEX.
  171. */
  172. static int8_t HexToDecimal(const char Byte)
  173. {
  174. if ((Byte >= 'A') && (Byte <= 'F'))
  175. return (10 + (Byte - 'A'));
  176. else if ((Byte >= '0') && (Byte <= '9'))
  177. return (Byte - '0');
  178. return -1;
  179. }
  180. /**
  181. * Flushes a partially written page of data to physical FLASH, if a page
  182. * boundary has been crossed.
  183. *
  184. * \note If a page flush occurs the global HEX parser state is updated.
  185. */
  186. static void FlushPageIfRequired(void)
  187. {
  188. /* Abort if no data has been buffered for writing to the current page */
  189. if (!PageDirty)
  190. return;
  191. /* Flush the FLASH page to physical memory if we are crossing a page boundary */
  192. uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
  193. if (HEXParser.PageStartAddress != NewPageStartAddress)
  194. {
  195. BootloaderAPI_WritePage(HEXParser.PageStartAddress);
  196. HEXParser.PageStartAddress = NewPageStartAddress;
  197. PageDirty = false;
  198. }
  199. }
  200. /**
  201. * Parses an input Intel HEX formatted stream one character at a time, loading
  202. * the data contents into the device's internal FLASH memory.
  203. *
  204. * \param[in] ReadCharacter Next input ASCII byte of data to parse
  205. */
  206. static void ParseIntelHEXByte(const char ReadCharacter)
  207. {
  208. /* Reset the line parser while waiting for a new line to start */
  209. if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
  210. {
  211. HEXParser.Checksum = 0;
  212. HEXParser.CurrAddress = HEXParser.CurrBaseAddress;
  213. HEXParser.ReadMSB = false;
  214. /* ASCII ':' indicates the start of a new HEX record */
  215. if (ReadCharacter == ':')
  216. HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
  217. return;
  218. }
  219. /* Only allow ASCII HEX encoded digits, ignore all other characters */
  220. int8_t ReadCharacterDec = HexToDecimal(ReadCharacter);
  221. if (ReadCharacterDec < 0)
  222. return;
  223. /* Read and convert the next nibble of data from the current character */
  224. HEXParser.Data = (HEXParser.Data << 4) | ReadCharacterDec;
  225. HEXParser.ReadMSB = !HEXParser.ReadMSB;
  226. /* Only process further when a full byte (two nibbles) have been read */
  227. if (HEXParser.ReadMSB)
  228. return;
  229. /* Intel HEX checksum is for all fields except starting character and the
  230. * checksum itself
  231. */
  232. if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
  233. HEXParser.Checksum += HEXParser.Data;
  234. switch (HEXParser.ParserState)
  235. {
  236. case HEX_PARSE_STATE_BYTE_COUNT:
  237. HEXParser.DataRem = HEXParser.Data;
  238. HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_HIGH;
  239. break;
  240. case HEX_PARSE_STATE_ADDRESS_HIGH:
  241. HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
  242. HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_LOW;
  243. break;
  244. case HEX_PARSE_STATE_ADDRESS_LOW:
  245. HEXParser.CurrAddress += HEXParser.Data;
  246. HEXParser.ParserState = HEX_PARSE_STATE_RECORD_TYPE;
  247. break;
  248. case HEX_PARSE_STATE_RECORD_TYPE:
  249. HEXParser.RecordType = HEXParser.Data;
  250. HEXParser.ParserState = (HEXParser.DataRem ? HEX_PARSE_STATE_READ_DATA : HEX_PARSE_STATE_CHECKSUM);
  251. break;
  252. case HEX_PARSE_STATE_READ_DATA:
  253. /* Track the number of read data bytes in the record */
  254. HEXParser.DataRem--;
  255. /* Protect the bootloader against being written to */
  256. if (HEXParser.CurrAddress >= BOOT_START_ADDR)
  257. {
  258. HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
  259. PageDirty = false;
  260. return;
  261. }
  262. /* Wait for a machine word (two bytes) of data to be read */
  263. if (HEXParser.DataRem & 0x01)
  264. {
  265. HEXParser.PrevData = HEXParser.Data;
  266. break;
  267. }
  268. /* Convert the last two received data bytes into a 16-bit word */
  269. uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
  270. switch (HEXParser.RecordType)
  271. {
  272. case HEX_RECORD_TYPE_Data:
  273. /* If we are writing to a new page, we need to erase it first */
  274. if (!(PageDirty))
  275. {
  276. BootloaderAPI_ErasePage(HEXParser.PageStartAddress);
  277. PageDirty = true;
  278. }
  279. /* Fill the FLASH memory buffer with the new word of data */
  280. BootloaderAPI_FillWord(HEXParser.CurrAddress, NewDataWord);
  281. HEXParser.CurrAddress += 2;
  282. /* Flush the FLASH page to physical memory if we are crossing a page boundary */
  283. FlushPageIfRequired();
  284. break;
  285. case HEX_RECORD_TYPE_ExtendedSegmentAddress:
  286. /* Extended address data - store the upper 12-bits of the new address */
  287. HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 4);
  288. break;
  289. case HEX_RECORD_TYPE_ExtendedLinearAddress:
  290. /* Extended address data - store the upper 16-bits of the new address */
  291. HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 16);
  292. break;
  293. }
  294. if (!HEXParser.DataRem)
  295. HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
  296. break;
  297. case HEX_PARSE_STATE_CHECKSUM:
  298. /* Verify checksum of the completed record */
  299. if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
  300. break;
  301. /* Flush the FLASH page to physical memory if we are crossing a page boundary */
  302. FlushPageIfRequired();
  303. /* If end of the HEX file reached, the bootloader should exit at next opportunity */
  304. if (HEXParser.RecordType == HEX_RECORD_TYPE_EndOfFile)
  305. RunBootloader = false;
  306. break;
  307. default:
  308. HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
  309. break;
  310. }
  311. }
  312. /** Main program entry point. This routine configures the hardware required by the application, then
  313. * enters a loop to run the application tasks in sequence.
  314. */
  315. int main(void)
  316. {
  317. SetupHardware();
  318. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  319. GlobalInterruptEnable();
  320. while (RunBootloader)
  321. {
  322. uint8_t BytesReceived = PRNT_Device_BytesReceived(&TextOnly_Printer_Interface);
  323. if (BytesReceived)
  324. {
  325. LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
  326. while (BytesReceived--)
  327. {
  328. int16_t ReceivedByte = PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface);
  329. /* Feed the next byte of data to the HEX parser */
  330. ParseIntelHEXByte(ReceivedByte);
  331. }
  332. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  333. }
  334. PRNT_Device_USBTask(&TextOnly_Printer_Interface);
  335. USB_USBTask();
  336. }
  337. /* Wait a short time to end all USB transactions and then disconnect */
  338. _delay_us(1000);
  339. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  340. USB_Detach();
  341. /* Unlock the forced application start mode of the bootloader if it is restarted */
  342. MagicBootKey = MAGIC_BOOT_KEY;
  343. /* Enable the watchdog and force a timeout to reset the AVR */
  344. wdt_enable(WDTO_250MS);
  345. for (;;);
  346. }
  347. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  348. static void SetupHardware(void)
  349. {
  350. /* Disable watchdog if enabled by bootloader/fuses */
  351. MCUSR &= ~(1 << WDRF);
  352. wdt_disable();
  353. /* Disable clock division */
  354. clock_prescale_set(clock_div_1);
  355. /* Relocate the interrupt vector table to the bootloader section */
  356. MCUCR = (1 << IVCE);
  357. MCUCR = (1 << IVSEL);
  358. /* Hardware Initialization */
  359. LEDs_Init();
  360. USB_Init();
  361. /* Bootloader active LED toggle timer initialization */
  362. TIMSK1 = (1 << TOIE1);
  363. TCCR1B = ((1 << CS11) | (1 << CS10));
  364. }
  365. /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
  366. ISR(TIMER1_OVF_vect, ISR_BLOCK)
  367. {
  368. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  369. }
  370. /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
  371. void EVENT_USB_Device_Connect(void)
  372. {
  373. /* Indicate USB enumerating */
  374. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  375. }
  376. /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
  377. * the status LEDs and stops the Printer management task.
  378. */
  379. void EVENT_USB_Device_Disconnect(void)
  380. {
  381. /* Indicate USB not ready */
  382. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  383. }
  384. /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
  385. * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
  386. */
  387. void EVENT_USB_Device_ConfigurationChanged(void)
  388. {
  389. bool ConfigSuccess = true;
  390. /* Setup Printer Data Endpoints */
  391. ConfigSuccess &= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface);
  392. /* Reset the HEX parser upon successful connection to a host */
  393. HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
  394. /* Indicate endpoint configuration success or failure */
  395. LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
  396. }
  397. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  398. * the device from the USB host before passing along unhandled control requests to the library for processing
  399. * internally.
  400. */
  401. void EVENT_USB_Device_ControlRequest(void)
  402. {
  403. PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface);
  404. }