3 Copyright (C) Dean Camera, 2013.
5 dean [at] fourwalledcubicle [dot] com
10 Copyright 2013 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
21 The author disclaims all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
33 * Main source file for the Printer class bootloader. This file contains the complete bootloader logic.
36 #include "BootloaderPrinter.h"
38 /** LUFA Printer Class driver interface configuration and state information. This structure is
39 * passed to all Printer Class driver functions, so that multiple instances of the same class
40 * within a device can be differentiated from one another.
42 USB_ClassInfo_PRNT_Device_t TextOnly_Printer_Interface
=
49 .Address
= PRINTER_IN_EPADDR
,
50 .Size
= PRINTER_IO_EPSIZE
,
55 .Address
= PRINTER_OUT_EPADDR
,
56 .Size
= PRINTER_IO_EPSIZE
,
61 "MDL:Generic_/_Text_Only;"
67 /** Intel HEX parser state machine state information, to track the contents of
68 * a HEX file streamed in as a sequence of arbitrary bytes.
72 /** Current HEX parser state machine state. */
74 /** Previously decoded numerical byte of data. */
76 /** Currently decoded numerical byte of data. */
78 /** Indicates if both bytes that correspond to a single decoded numerical
79 * byte of data (HEX encodes values in ASCII HEX, two characters per byte)
83 /** Intel HEX record type of the current Intel HEX record. */
85 /** Numerical bytes of data remaining to be read in the current record. */
87 /** Checksum of the current record received so far. */
89 /** Starting address of the last addressed FLASH page. */
90 uint32_t PageStartAddress
;
91 /** Current 32-bit byte extended base address in FLASH being targeted. */
92 uint32_t CurrBaseAddress
;
93 /** Current 32-bit byte address in FLASH being targeted. */
97 .ParserState
= HEX_PARSE_STATE_WAIT_LINE
100 /** Indicates if there is data waiting to be written to a physical page of
103 static bool PageDirty
= false;
106 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
107 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
108 * started via a forced watchdog reset.
110 static bool RunBootloader
= true;
112 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
113 * 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
114 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
115 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
117 uint16_t MagicBootKey ATTR_NO_INIT
;
120 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
121 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
122 * this will force the user application to start via a software jump.
124 void Application_Jump_Check(void)
126 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application */
127 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
131 // cppcheck-suppress constStatement
132 ((void (*)(void))0x0000)();
137 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
139 * \note Input HEX bytes are expected to be in uppercase only.
141 * \param[in] Byte ASCII byte of data to convert
143 * \return Integer converted value of the input ASCII encoded HEX byte of data, or -1 if the
144 * input is not valid ASCII encoded HEX.
146 static int8_t HexToDecimal(const char Byte
)
148 if ((Byte
>= 'A') && (Byte
<= 'F'))
149 return (10 + (Byte
- 'A'));
150 else if ((Byte
>= '0') && (Byte
<= '9'))
157 * Parses an input Intel HEX formatted stream one character at a time, loading
158 * the data contents into the device's internal FLASH memory.
160 * \param[in] ReadCharacter Next input ASCII byte of data to parse
162 static void ParseIntelHEXByte(const char ReadCharacter
)
164 /* Reset the line parser while waiting for a new line to start */
165 if ((HEXParser
.ParserState
== HEX_PARSE_STATE_WAIT_LINE
) || (ReadCharacter
== ':'))
167 HEXParser
.Checksum
= 0;
168 HEXParser
.CurrAddress
= HEXParser
.CurrBaseAddress
;
169 HEXParser
.ReadMSB
= false;
171 /* ASCII ':' indicates the start of a new HEX record */
172 if (ReadCharacter
== ':')
173 HEXParser
.ParserState
= HEX_PARSE_STATE_BYTE_COUNT
;
178 /* Only allow ASCII HEX encoded digits, ignore all other characters */
179 int8_t ReadCharacterDec
= HexToDecimal(ReadCharacter
);
180 if (ReadCharacterDec
< 0)
183 /* Read and convert the next nibble of data from the current character */
184 HEXParser
.Data
= (HEXParser
.Data
<< 4) | ReadCharacterDec
;
185 HEXParser
.ReadMSB
= !HEXParser
.ReadMSB
;
187 /* Only process further when a full byte (two nibbles) have been read */
188 if (HEXParser
.ReadMSB
)
191 /* Intel HEX checksum is for all fields except starting character and the
194 if (HEXParser
.ParserState
!= HEX_PARSE_STATE_CHECKSUM
)
195 HEXParser
.Checksum
+= HEXParser
.Data
;
197 switch (HEXParser
.ParserState
)
199 case HEX_PARSE_STATE_BYTE_COUNT
:
200 HEXParser
.DataRem
= HEXParser
.Data
;
201 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_HIGH
;
204 case HEX_PARSE_STATE_ADDRESS_HIGH
:
205 HEXParser
.CurrAddress
+= ((uint16_t)HEXParser
.Data
<< 8);
206 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_LOW
;
209 case HEX_PARSE_STATE_ADDRESS_LOW
:
210 HEXParser
.CurrAddress
+= HEXParser
.Data
;
211 HEXParser
.ParserState
= HEX_PARSE_STATE_RECORD_TYPE
;
214 case HEX_PARSE_STATE_RECORD_TYPE
:
215 HEXParser
.RecordType
= HEXParser
.Data
;
216 HEXParser
.ParserState
= (HEXParser
.DataRem ? HEX_PARSE_STATE_READ_DATA
: HEX_PARSE_STATE_CHECKSUM
);
219 case HEX_PARSE_STATE_READ_DATA
:
220 /* Track the number of read data bytes in the record */
223 /* Protect the bootloader against being written to */
224 if (HEXParser
.CurrAddress
>= BOOT_START_ADDR
)
226 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
231 /* Wait for a machine word (two bytes) of data to be read */
232 if (HEXParser
.DataRem
& 0x01)
234 HEXParser
.PrevData
= HEXParser
.Data
;
238 /* Convert the last two received data bytes into a 16-bit word */
239 uint16_t NewDataWord
= ((uint16_t)HEXParser
.Data
<< 8) | HEXParser
.PrevData
;
241 switch (HEXParser
.RecordType
)
243 case HEX_RECORD_TYPE_Data
:
244 /* If we are writing to a new page, we need to erase it
249 boot_page_erase(HEXParser
.PageStartAddress
);
250 boot_spm_busy_wait();
255 /* Fill the FLASH memory buffer with the new word of data */
256 boot_page_fill(HEXParser
.CurrAddress
, NewDataWord
);
257 HEXParser
.CurrAddress
+= 2;
259 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
260 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
261 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
263 boot_page_write(HEXParser
.PageStartAddress
);
264 boot_spm_busy_wait();
266 HEXParser
.PageStartAddress
= NewPageStartAddress
;
272 case HEX_RECORD_TYPE_ExtendedSegmentAddress
:
273 /* Extended address data - store the upper 12-bits of the new address */
274 HEXParser
.CurrBaseAddress
= ((uint32_t)NewDataWord
<< 4);
277 case HEX_RECORD_TYPE_ExtendedLinearAddress
:
278 /* Extended address data - store the upper 16-bits of the new address */
279 HEXParser
.CurrBaseAddress
= ((uint32_t)NewDataWord
<< 16);
283 if (!HEXParser
.DataRem
)
284 HEXParser
.ParserState
= HEX_PARSE_STATE_CHECKSUM
;
287 case HEX_PARSE_STATE_CHECKSUM
:
288 /* Verify checksum of the completed record */
289 if (HEXParser
.Data
!= ((~HEXParser
.Checksum
+ 1) & 0xFF))
292 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
293 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
294 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
296 boot_page_write(HEXParser
.PageStartAddress
);
297 boot_spm_busy_wait();
299 HEXParser
.PageStartAddress
= NewPageStartAddress
;
304 /* If end of the HEX file reached, the bootloader should exit at next opportunity */
305 if (HEXParser
.RecordType
== HEX_RECORD_TYPE_EndOfFile
)
306 RunBootloader
= false;
311 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
316 /** Main program entry point. This routine configures the hardware required by the application, then
317 * enters a loop to run the application tasks in sequence.
323 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
324 GlobalInterruptEnable();
326 while (RunBootloader
)
328 uint8_t BytesReceived
= PRNT_Device_BytesReceived(&TextOnly_Printer_Interface
);
332 LEDs_SetAllLEDs(LEDMASK_USB_BUSY
);
334 while (BytesReceived
--)
336 int16_t ReceivedByte
= PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface
);
338 /* Feed the next byte of data to the HEX parser */
339 ParseIntelHEXByte(ReceivedByte
);
342 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
345 PRNT_Device_USBTask(&TextOnly_Printer_Interface
);
349 /* Disconnect from the host - USB interface will be reset later along with the AVR */
352 /* Unlock the forced application start mode of the bootloader if it is restarted */
353 MagicBootKey
= MAGIC_BOOT_KEY
;
355 /* Enable the watchdog and force a timeout to reset the AVR */
356 wdt_enable(WDTO_250MS
);
361 /** Configures the board hardware and chip peripherals for the demo's functionality. */
362 static void SetupHardware(void)
364 /* Disable watchdog if enabled by bootloader/fuses */
365 MCUSR
&= ~(1 << WDRF
);
368 /* Disable clock division */
369 clock_prescale_set(clock_div_1
);
371 /* Relocate the interrupt vector table to the bootloader section */
373 MCUCR
= (1 << IVSEL
);
375 /* Hardware Initialization */
379 /* Bootloader active LED toggle timer initialization */
380 TIMSK1
= (1 << TOIE1
);
381 TCCR1B
= ((1 << CS11
) | (1 << CS10
));
384 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
385 ISR(TIMER1_OVF_vect
, ISR_BLOCK
)
387 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
390 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
391 void EVENT_USB_Device_Connect(void)
393 /* Indicate USB enumerating */
394 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
397 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
398 * the status LEDs and stops the Printer management task.
400 void EVENT_USB_Device_Disconnect(void)
402 /* Indicate USB not ready */
403 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
406 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
407 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
409 void EVENT_USB_Device_ConfigurationChanged(void)
411 bool ConfigSuccess
= true;
413 /* Setup Printer Data Endpoints */
414 ConfigSuccess
&= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface
);
416 /* Indicate endpoint configuration success or failure */
417 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY
: LEDMASK_USB_ERROR
);
420 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
421 * the device from the USB host before passing along unhandled control requests to the library for processing
424 void EVENT_USB_Device_ControlRequest(void)
426 PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface
);