3      Copyright (C) Dean Camera, 2015. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2015  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 
= 
  46                                 .InterfaceNumber          
= INTERFACE_ID_Printer
, 
  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 /** Indicates if there is data waiting to be written to a physical page of 
 100 static bool PageDirty 
= false; 
 102 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run 
 103  *  via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application 
 104  *  started via a forced watchdog reset. 
 106 static bool RunBootloader 
= true; 
 108 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader 
 109  *  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 
 110  *  low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value 
 111  *  \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start. 
 113 uint16_t MagicBootKey ATTR_NO_INIT
; 
 116 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application 
 117  *  start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid, 
 118  *  this will force the user application to start via a software jump. 
 120 void Application_Jump_Check(void) 
 122         bool JumpToApplication 
= false; 
 124         #if (BOARD == BOARD_LEONARDO) 
 125                 /* Enable pull-up on the IO13 pin so we can use it to select the mode */ 
 129                 /* If IO13 is not jumpered to ground, start the user application instead */ 
 130                 JumpToApplication 
= ((PINC 
& (1 << 7)) != 0); 
 132                 /* Disable pull-up after the check has completed */ 
 134         #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1)) 
 135                 /* Disable JTAG debugging */ 
 138                 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */ 
 142                 /* If the TCK pin is not jumpered to ground, start the user application instead */ 
 143                 JumpToApplication 
= ((PINF 
& (1 << 4)) != 0); 
 145                 /* Re-enable JTAG debugging */ 
 148                 /* Check if the device's BOOTRST fuse is set */ 
 149                 if (boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS
) & FUSE_BOOTRST
) 
 151                         /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */ 
 152                         if (!(MCUSR 
& (1 << EXTRF
)) || (MagicBootKey 
== MAGIC_BOOT_KEY
)) 
 153                           JumpToApplication 
= true; 
 155                         /* Clear reset source */ 
 156                         MCUSR 
&= ~(1 << EXTRF
); 
 160                         /* If the reset source was the bootloader and the key is correct, clear it and jump to the application; 
 161                          * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */ 
 162                         if ((MCUSR 
& (1 << WDRF
)) && (MagicBootKey 
== MAGIC_BOOT_KEY
)) 
 163                                 JumpToApplication 
= true; 
 165                         /* Clear reset source */ 
 166                         MCUSR 
&= ~(1 << WDRF
); 
 170         /* Don't run the user application if the reset vector is blank (no app loaded) */ 
 171         bool ApplicationValid 
= (pgm_read_word_near(0) != 0xFFFF); 
 173         /* If a request has been made to jump to the user application, honor it */ 
 174         if (JumpToApplication 
&& ApplicationValid
) 
 176                 /* Turn off the watchdog */ 
 177                 MCUSR 
&= ~(1 << WDRF
); 
 180                 /* Clear the boot key and jump to the user application */ 
 183                 // cppcheck-suppress constStatement 
 184                 ((void (*)(void))0x0000)(); 
 189  * Converts a given input byte of data from an ASCII encoded HEX value to an integer value. 
 191  * \note Input HEX bytes are expected to be in uppercase only. 
 193  * \param[in] Byte  ASCII byte of data to convert 
 195  * \return Integer converted value of the input ASCII encoded HEX byte of data, or -1 if the 
 196  *         input is not valid ASCII encoded HEX. 
 198 static int8_t HexToDecimal(const char Byte
) 
 200         if ((Byte 
>= 'A') && (Byte 
<= 'F')) 
 201           return (10 + (Byte 
- 'A')); 
 202         else if ((Byte 
>= '0') && (Byte 
<= '9')) 
 209  * Flushes a partially written page of data to physical FLASH, if a page 
 210  * boundary has been crossed. 
 212  * \note If a page flush occurs the global HEX parser state is updated. 
 214 static void FlushPageIfRequired(void) 
 216         /* Abort if no data has been buffered for writing to the current page */ 
 220         /* Flush the FLASH page to physical memory if we are crossing a page boundary */ 
 221         uint32_t NewPageStartAddress 
= (HEXParser
.CurrAddress 
& ~(SPM_PAGESIZE 
- 1)); 
 222         if (HEXParser
.PageStartAddress 
!= NewPageStartAddress
) 
 224                 boot_page_write(HEXParser
.PageStartAddress
); 
 225                 boot_spm_busy_wait(); 
 227                 HEXParser
.PageStartAddress 
= NewPageStartAddress
; 
 234  * Parses an input Intel HEX formatted stream one character at a time, loading 
 235  * the data contents into the device's internal FLASH memory. 
 237  * \param[in] ReadCharacter  Next input ASCII byte of data to parse 
 239 static void ParseIntelHEXByte(const char ReadCharacter
) 
 241         /* Reset the line parser while waiting for a new line to start */ 
 242         if ((HEXParser
.ParserState 
== HEX_PARSE_STATE_WAIT_LINE
) || (ReadCharacter 
== ':')) 
 244                 HEXParser
.Checksum     
= 0; 
 245                 HEXParser
.CurrAddress  
= HEXParser
.CurrBaseAddress
; 
 246                 HEXParser
.ReadMSB      
= false; 
 248                 /* ASCII ':' indicates the start of a new HEX record */ 
 249                 if (ReadCharacter 
== ':') 
 250                   HEXParser
.ParserState 
= HEX_PARSE_STATE_BYTE_COUNT
; 
 255         /* Only allow ASCII HEX encoded digits, ignore all other characters */ 
 256         int8_t ReadCharacterDec 
= HexToDecimal(ReadCharacter
); 
 257         if (ReadCharacterDec 
< 0) 
 260         /* Read and convert the next nibble of data from the current character */ 
 261         HEXParser
.Data    
= (HEXParser
.Data 
<< 4) | ReadCharacterDec
; 
 262         HEXParser
.ReadMSB 
= !HEXParser
.ReadMSB
; 
 264         /* Only process further when a full byte (two nibbles) have been read */ 
 265         if (HEXParser
.ReadMSB
) 
 268         /* Intel HEX checksum is for all fields except starting character and the 
 271         if (HEXParser
.ParserState 
!= HEX_PARSE_STATE_CHECKSUM
) 
 272           HEXParser
.Checksum 
+= HEXParser
.Data
; 
 274         switch (HEXParser
.ParserState
) 
 276                 case HEX_PARSE_STATE_BYTE_COUNT
: 
 277                         HEXParser
.DataRem      
= HEXParser
.Data
; 
 278                         HEXParser
.ParserState  
= HEX_PARSE_STATE_ADDRESS_HIGH
; 
 281                 case HEX_PARSE_STATE_ADDRESS_HIGH
: 
 282                         HEXParser
.CurrAddress 
+= ((uint16_t)HEXParser
.Data 
<< 8); 
 283                         HEXParser
.ParserState  
= HEX_PARSE_STATE_ADDRESS_LOW
; 
 286                 case HEX_PARSE_STATE_ADDRESS_LOW
: 
 287                         HEXParser
.CurrAddress 
+= HEXParser
.Data
; 
 288                         HEXParser
.ParserState  
= HEX_PARSE_STATE_RECORD_TYPE
; 
 291                 case HEX_PARSE_STATE_RECORD_TYPE
: 
 292                         HEXParser
.RecordType   
= HEXParser
.Data
; 
 293                         HEXParser
.ParserState  
= (HEXParser
.DataRem ? HEX_PARSE_STATE_READ_DATA 
: HEX_PARSE_STATE_CHECKSUM
); 
 296                 case HEX_PARSE_STATE_READ_DATA
: 
 297                         /* Track the number of read data bytes in the record */ 
 300                         /* Protect the bootloader against being written to */ 
 301                         if (HEXParser
.CurrAddress 
>= BOOT_START_ADDR
) 
 303                                 HEXParser
.ParserState 
= HEX_PARSE_STATE_WAIT_LINE
; 
 308                         /* Wait for a machine word (two bytes) of data to be read */ 
 309                         if (HEXParser
.DataRem 
& 0x01) 
 311                                 HEXParser
.PrevData 
= HEXParser
.Data
; 
 315                         /* Convert the last two received data bytes into a 16-bit word */ 
 316                         uint16_t NewDataWord 
= ((uint16_t)HEXParser
.Data 
<< 8) | HEXParser
.PrevData
; 
 318                         switch (HEXParser
.RecordType
) 
 320                                 case HEX_RECORD_TYPE_Data
: 
 321                                         /* If we are writing to a new page, we need to erase it first */ 
 324                                                 boot_page_erase(HEXParser
.PageStartAddress
); 
 325                                                 boot_spm_busy_wait(); 
 330                                         /* Fill the FLASH memory buffer with the new word of data */ 
 331                                         boot_page_fill(HEXParser
.CurrAddress
, NewDataWord
); 
 332                                         HEXParser
.CurrAddress 
+= 2; 
 334                                         /* Flush the FLASH page to physical memory if we are crossing a page boundary */ 
 335                                         FlushPageIfRequired(); 
 338                                 case HEX_RECORD_TYPE_ExtendedSegmentAddress
: 
 339                                         /* Extended address data - store the upper 12-bits of the new address */ 
 340                                         HEXParser
.CurrBaseAddress 
= ((uint32_t)NewDataWord 
<< 4); 
 343                                 case HEX_RECORD_TYPE_ExtendedLinearAddress
: 
 344                                         /* Extended address data - store the upper 16-bits of the new address */ 
 345                                         HEXParser
.CurrBaseAddress 
= ((uint32_t)NewDataWord 
<< 16); 
 349                         if (!HEXParser
.DataRem
) 
 350                           HEXParser
.ParserState 
= HEX_PARSE_STATE_CHECKSUM
; 
 353                 case HEX_PARSE_STATE_CHECKSUM
: 
 354                         /* Verify checksum of the completed record */ 
 355                         if (HEXParser
.Data 
!= ((~HEXParser
.Checksum 
+ 1) & 0xFF)) 
 358                         /* Flush the FLASH page to physical memory if we are crossing a page boundary */ 
 359                         FlushPageIfRequired(); 
 361                         /* If end of the HEX file reached, the bootloader should exit at next opportunity */ 
 362                         if (HEXParser
.RecordType 
== HEX_RECORD_TYPE_EndOfFile
) 
 363                           RunBootloader 
= false; 
 368                         HEXParser
.ParserState 
= HEX_PARSE_STATE_WAIT_LINE
; 
 373 /** Main program entry point. This routine configures the hardware required by the application, then 
 374  *  enters a loop to run the application tasks in sequence. 
 380         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 381         GlobalInterruptEnable(); 
 383         while (RunBootloader
) 
 385                 uint8_t BytesReceived 
= PRNT_Device_BytesReceived(&TextOnly_Printer_Interface
); 
 389                         LEDs_SetAllLEDs(LEDMASK_USB_BUSY
); 
 391                         while (BytesReceived
--) 
 393                                 int16_t ReceivedByte 
= PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface
); 
 395                                 /* Feed the next byte of data to the HEX parser */ 
 396                                 ParseIntelHEXByte(ReceivedByte
); 
 399                         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 402                 PRNT_Device_USBTask(&TextOnly_Printer_Interface
); 
 406         /* Disconnect from the host - USB interface will be reset later along with the AVR */ 
 409         /* Unlock the forced application start mode of the bootloader if it is restarted */ 
 410         MagicBootKey 
= MAGIC_BOOT_KEY
; 
 412         /* Enable the watchdog and force a timeout to reset the AVR */ 
 413         wdt_enable(WDTO_250MS
); 
 418 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
 419 static void SetupHardware(void) 
 421         /* Disable watchdog if enabled by bootloader/fuses */ 
 422         MCUSR 
&= ~(1 << WDRF
); 
 425         /* Disable clock division */ 
 426         clock_prescale_set(clock_div_1
); 
 428         /* Relocate the interrupt vector table to the bootloader section */ 
 430         MCUCR 
= (1 << IVSEL
); 
 432         /* Hardware Initialization */ 
 436         /* Bootloader active LED toggle timer initialization */ 
 437         TIMSK1 
= (1 << TOIE1
); 
 438         TCCR1B 
= ((1 << CS11
) | (1 << CS10
)); 
 441 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */ 
 442 ISR(TIMER1_OVF_vect
, ISR_BLOCK
) 
 444         LEDs_ToggleLEDs(LEDS_LED1 
| LEDS_LED2
); 
 447 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */ 
 448 void EVENT_USB_Device_Connect(void) 
 450         /* Indicate USB enumerating */ 
 451         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
 454 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 455  *  the status LEDs and stops the Printer management task. 
 457 void EVENT_USB_Device_Disconnect(void) 
 459         /* Indicate USB not ready */ 
 460         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 463 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 464  *  of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started. 
 466 void EVENT_USB_Device_ConfigurationChanged(void) 
 468         bool ConfigSuccess 
= true; 
 470         /* Setup Printer Data Endpoints */ 
 471         ConfigSuccess 
&= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface
); 
 473         /* Reset the HEX parser upon successful connection to a host */ 
 474         HEXParser
.ParserState 
= HEX_PARSE_STATE_WAIT_LINE
; 
 476         /* Indicate endpoint configuration success or failure */ 
 477         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY 
: LEDMASK_USB_ERROR
); 
 480 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to 
 481  *  the device from the USB host before passing along unhandled control requests to the library for processing 
 484 void EVENT_USB_Device_ControlRequest(void) 
 486         PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface
);