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 /** Intel HEX parser state machine state information, to track the contents of
39 * a HEX file streamed in as a sequence of arbitrary bytes.
43 /** Current HEX parser state machine state. */
45 /** Previously decoded numerical byte of data. */
47 /** Currently decoded numerical byte of data. */
49 /** Indicates if both bytes that correspond to a single decoded numerical
50 * byte of data (HEX encodes values in ASCII HEX, two characters per byte)
54 /** Intel HEX record type of the current Intel HEX record. */
56 /** Numerical bytes of data remaining to be read in the current record. */
58 /** Checksum of the current record received so far. */
60 /** Starting address of the last addressed FLASH page. */
61 uint32_t PageStartAddress
;
62 /** Current 32-bit byte extended base address in FLASH being targeted. */
63 uint32_t CurrBaseAddress
;
64 /** Current 32-bit byte address in FLASH being targeted. */
68 .ParserState
= HEX_PARSE_STATE_WAIT_LINE
71 /** Indicates if there is data waiting to be written to a physical page of
74 static bool PageDirty
= false;
77 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
78 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
79 * started via a forced watchdog reset.
81 static bool RunBootloader
= true;
83 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
84 * 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
85 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
86 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
88 uint16_t MagicBootKey ATTR_NO_INIT
;
91 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
92 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
93 * this will force the user application to start via a software jump.
95 void Application_Jump_Check(void)
97 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application */
98 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
102 // cppcheck-suppress constStatement
103 ((void (*)(void))0x0000)();
108 * Determines if a given input byte of data is an ASCII encoded HEX value.
110 * \note Input HEX bytes are expected to be in uppercase only.
112 * \param[in] Byte ASCII byte of data to check
114 * \return Boolean \c true if the input data is ASCII encoded HEX, \c false otherwise.
116 static bool IsHex(const char Byte
)
118 return ((Byte
>= 'A') && (Byte
<= 'F')) ||
119 ((Byte
>= '0') && (Byte
<= '9'));
123 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
125 * \note Input HEX bytes are expected to be in uppercase only.
127 * \param[in] Byte ASCII byte of data to convert
129 * \return Integer converted value of the input ASCII encoded HEX byte of data.
131 static uint8_t HexToDecimal(const char Byte
)
133 if ((Byte
>= 'A') && (Byte
<= 'F'))
134 return (10 + (Byte
- 'A'));
135 else if ((Byte
>= '0') && (Byte
<= '9'))
142 * Parses an input Intel HEX formatted stream one character at a time, loading
143 * the data contents into the device's internal FLASH memory.
145 * \param[in] ReadCharacter Next input ASCII byte of data to parse
147 static void ParseIntelHEXByte(const char ReadCharacter
)
149 /* Reset the line parser while waiting for a new line to start */
150 if ((HEXParser
.ParserState
== HEX_PARSE_STATE_WAIT_LINE
) || (ReadCharacter
== ':'))
152 HEXParser
.Checksum
= 0;
153 HEXParser
.CurrAddress
= HEXParser
.CurrBaseAddress
;
154 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
155 HEXParser
.ReadMSB
= false;
157 /* ASCII ':' indicates the start of a new HEX record */
158 if (ReadCharacter
== ':')
159 HEXParser
.ParserState
= HEX_PARSE_STATE_BYTE_COUNT
;
164 /* Only allow ASCII HEX encoded digits, ignore all other characters */
165 if (!IsHex(ReadCharacter
))
168 /* Read and convert the next nibble of data from the current character */
169 HEXParser
.Data
= (HEXParser
.Data
<< 4) | HexToDecimal(ReadCharacter
);
170 HEXParser
.ReadMSB
= !HEXParser
.ReadMSB
;
172 /* Only process further when a full byte (two nibbles) have been read */
173 if (HEXParser
.ReadMSB
)
176 /* Intel HEX checksum is for all fields except starting character and the
179 if (HEXParser
.ParserState
!= HEX_PARSE_STATE_CHECKSUM
)
180 HEXParser
.Checksum
+= HEXParser
.Data
;
182 switch (HEXParser
.ParserState
)
184 case HEX_PARSE_STATE_BYTE_COUNT
:
185 HEXParser
.DataRem
= HEXParser
.Data
;
186 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_HIGH
;
189 case HEX_PARSE_STATE_ADDRESS_HIGH
:
190 HEXParser
.CurrAddress
+= ((uint16_t)HEXParser
.Data
<< 8);
191 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_LOW
;
194 case HEX_PARSE_STATE_ADDRESS_LOW
:
195 HEXParser
.CurrAddress
+= HEXParser
.Data
;
196 HEXParser
.ParserState
= HEX_PARSE_STATE_RECORD_TYPE
;
199 case HEX_PARSE_STATE_RECORD_TYPE
:
200 HEXParser
.RecordType
= HEXParser
.Data
;
201 HEXParser
.ParserState
= (HEXParser
.DataRem ? HEX_PARSE_STATE_READ_DATA
: HEX_PARSE_STATE_CHECKSUM
);
204 case HEX_PARSE_STATE_READ_DATA
:
205 /* Track the number of read data bytes in the record */
208 /* Protect the bootloader against being written to */
209 if (HEXParser
.CurrAddress
>= BOOT_START_ADDR
)
211 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
216 /* Wait for a machine word (two bytes) of data to be read */
217 if (HEXParser
.DataRem
& 0x01)
219 HEXParser
.PrevData
= HEXParser
.Data
;
223 /* Convert the last two received data bytes into a 16-bit word */
224 uint16_t NewDataWord
= ((uint16_t)HEXParser
.Data
<< 8) | HEXParser
.PrevData
;
226 switch (HEXParser
.RecordType
)
228 case HEX_RECORD_TYPE_Data
:
229 /* If we are writing to a new page, we need to erase it
234 boot_page_erase(HEXParser
.PageStartAddress
);
235 boot_spm_busy_wait();
240 /* Fill the FLASH memory buffer with the new word of data */
241 boot_page_fill(HEXParser
.CurrAddress
, NewDataWord
);
242 HEXParser
.CurrAddress
+= 2;
244 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
245 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
246 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
248 boot_page_write(HEXParser
.PageStartAddress
);
249 boot_spm_busy_wait();
251 HEXParser
.PageStartAddress
= NewPageStartAddress
;
257 case HEX_RECORD_TYPE_ExtendedSegmentAddress
:
258 /* Extended address data - store the upper 12-bits of the new address */
259 HEXParser
.CurrBaseAddress
= ((uint32_t)NewDataWord
<< 4);
262 case HEX_RECORD_TYPE_ExtendedLinearAddress
:
263 /* Extended address data - store the upper 16-bits of the new address */
264 HEXParser
.CurrBaseAddress
= ((uint32_t)NewDataWord
<< 16);
268 if (!HEXParser
.DataRem
)
269 HEXParser
.ParserState
= HEX_PARSE_STATE_CHECKSUM
;
272 case HEX_PARSE_STATE_CHECKSUM
:
273 /* Verify checksum of the completed record */
274 if (HEXParser
.Data
!= ((~HEXParser
.Checksum
+ 1) & 0xFF))
277 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
278 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
279 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
281 boot_page_write(HEXParser
.PageStartAddress
);
282 boot_spm_busy_wait();
284 HEXParser
.PageStartAddress
= NewPageStartAddress
;
289 /* If end of the HEX file reached, the bootloader should exit at next opportunity */
290 if (HEXParser
.RecordType
== HEX_RECORD_TYPE_EndOfFile
)
291 RunBootloader
= false;
296 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
301 /** Main program entry point. This routine configures the hardware required by the application, then
302 * enters a loop to run the application tasks in sequence.
308 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
309 GlobalInterruptEnable();
311 while (RunBootloader
)
315 Endpoint_SelectEndpoint(PRINTER_OUT_EPADDR
);
317 /* Check if we have received new printer data from the host */
318 if (Endpoint_IsOUTReceived()) {
319 LEDs_ToggleLEDs(LEDMASK_USB_BUSY
);
321 /* Read all bytes of data from the host and parse them */
322 while (Endpoint_IsReadWriteAllowed())
324 /* Feed the next byte of data to the HEX parser */
325 ParseIntelHEXByte(Endpoint_Read_8());
328 /* Send an ACK to the host, ready for the next data packet */
331 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
335 /* Disconnect from the host - USB interface will be reset later along with the AVR */
338 /* Unlock the forced application start mode of the bootloader if it is restarted */
339 MagicBootKey
= MAGIC_BOOT_KEY
;
341 /* Enable the watchdog and force a timeout to reset the AVR */
342 wdt_enable(WDTO_250MS
);
347 /** Configures the board hardware and chip peripherals for the demo's functionality. */
348 static void SetupHardware(void)
350 /* Disable watchdog if enabled by bootloader/fuses */
351 MCUSR
&= ~(1 << WDRF
);
354 /* Disable clock division */
355 clock_prescale_set(clock_div_1
);
357 /* Relocate the interrupt vector table to the bootloader section */
359 MCUCR
= (1 << IVSEL
);
361 /* Hardware Initialization */
365 /* Bootloader active LED toggle timer initialization */
366 TIMSK1
= (1 << TOIE1
);
367 TCCR1B
= ((1 << CS11
) | (1 << CS10
));
370 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
371 ISR(TIMER1_OVF_vect
, ISR_BLOCK
)
373 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
376 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
377 void EVENT_USB_Device_Connect(void)
379 /* Indicate USB enumerating */
380 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
383 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
384 * the status LEDs and stops the Printer management task.
386 void EVENT_USB_Device_Disconnect(void)
388 /* Indicate USB not ready */
389 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
392 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
393 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
395 void EVENT_USB_Device_ConfigurationChanged(void)
397 bool ConfigSuccess
= true;
399 /* Setup Printer Data Endpoints */
400 ConfigSuccess
&= Endpoint_ConfigureEndpoint(PRINTER_IN_EPADDR
, EP_TYPE_BULK
, PRINTER_IO_EPSIZE
, 1);
401 ConfigSuccess
&= Endpoint_ConfigureEndpoint(PRINTER_OUT_EPADDR
, EP_TYPE_BULK
, PRINTER_IO_EPSIZE
, 1);
403 /* Indicate endpoint configuration success or failure */
404 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY
: LEDMASK_USB_ERROR
);
407 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
408 * the device from the USB host before passing along unhandled control requests to the library for processing
411 void EVENT_USB_Device_ControlRequest(void)
413 /* Process Printer specific control requests */
414 switch (USB_ControlRequest
.bRequest
)
416 case PRNT_REQ_GetDeviceID
:
417 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
419 /* Generic printer IEEE 1284 identification string, will bind to an in-built driver on
420 * Windows systems, and will fall-back to a text-only printer driver on *nix.
422 const char PrinterIDString
[] =
424 "MDL:Generic_/_Text_Only;"
428 Endpoint_ClearSETUP();
430 while (!(Endpoint_IsINReady()))
432 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
436 Endpoint_Write_16_BE(sizeof(PrinterIDString
));
437 Endpoint_Write_Control_Stream_LE(PrinterIDString
, strlen(PrinterIDString
));
438 Endpoint_ClearStatusStage();
442 case PRNT_REQ_GetPortStatus
:
443 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
445 Endpoint_ClearSETUP();
447 while (!(Endpoint_IsINReady()))
449 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
453 Endpoint_Write_8(PRNT_PORTSTATUS_NOTERROR
| PRNT_PORTSTATUS_SELECT
);
454 Endpoint_ClearStatusStage();
458 case PRNT_REQ_SoftReset
:
459 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
461 Endpoint_ClearSETUP();
462 Endpoint_ClearStatusStage();