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 * Determines if a given input byte of data is an ASCII encoded HEX value.
79 * \note Input HEX bytes are expected to be in uppercase only.
81 * \param[in] Byte ASCII byte of data to check
83 * \return Boolean \c true if the input data is ASCII encoded HEX, false otherwise.
85 static bool IsHex(const char Byte
)
87 return ((Byte
>= 'A') && (Byte
<= 'F')) ||
88 ((Byte
>= '0') && (Byte
<= '9'));
92 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
94 * \note Input HEX bytes are expected to be in uppercase only.
96 * \param[in] Byte ASCII byte of data to convert
98 * \return Integer converted value of the input ASCII encoded HEX byte of data.
100 static uint8_t HexToDecimal(const char Byte
)
102 if ((Byte
>= 'A') && (Byte
<= 'F'))
103 return (10 + (Byte
- 'A'));
104 else if ((Byte
>= '0') && (Byte
<= '9'))
111 * Parses an input Intel HEX formatted stream one character at a time, loading
112 * the data contents into the device's internal FLASH memory.
114 * \param[in] ReadCharacter Next input ASCII byte of data to parse
116 static void ParseIntelHEXByte(const char ReadCharacter
)
118 /* Reset the line parser while waiting for a new line to start */
119 if ((HEXParser
.ParserState
== HEX_PARSE_STATE_WAIT_LINE
) || (ReadCharacter
== ':'))
121 HEXParser
.Checksum
= 0;
122 HEXParser
.CurrAddress
= HEXParser
.CurrBaseAddress
;
123 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
124 HEXParser
.ReadMSB
= false;
126 /* ASCII ':' indicates the start of a new HEX record */
127 if (ReadCharacter
== ':')
128 HEXParser
.ParserState
= HEX_PARSE_STATE_BYTE_COUNT
;
133 /* Only allow ASCII HEX encoded digits, ignore all other characters */
134 if (!IsHex(ReadCharacter
))
137 /* Read and convert the next nibble of data from the current character */
138 HEXParser
.Data
= (HEXParser
.Data
<< 4) | HexToDecimal(ReadCharacter
);
139 HEXParser
.ReadMSB
= !HEXParser
.ReadMSB
;
141 /* Only process further when a full byte (two nibbles) have been read */
142 if (HEXParser
.ReadMSB
)
145 /* Intel HEX checksum is for all fields except starting character and the
148 if (HEXParser
.ParserState
!= HEX_PARSE_STATE_CHECKSUM
)
149 HEXParser
.Checksum
+= HEXParser
.Data
;
151 switch (HEXParser
.ParserState
)
153 case HEX_PARSE_STATE_BYTE_COUNT
:
154 HEXParser
.DataRem
= HEXParser
.Data
;
155 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_HIGH
;
158 case HEX_PARSE_STATE_ADDRESS_HIGH
:
159 HEXParser
.CurrAddress
+= ((uint16_t)HEXParser
.Data
<< 8);
160 HEXParser
.ParserState
= HEX_PARSE_STATE_ADDRESS_LOW
;
163 case HEX_PARSE_STATE_ADDRESS_LOW
:
164 HEXParser
.CurrAddress
+= HEXParser
.Data
;
165 HEXParser
.ParserState
= HEX_PARSE_STATE_RECORD_TYPE
;
168 case HEX_PARSE_STATE_RECORD_TYPE
:
169 HEXParser
.RecordType
= HEXParser
.Data
;
170 HEXParser
.ParserState
= (HEXParser
.DataRem ? HEX_PARSE_STATE_READ_DATA
: HEX_PARSE_STATE_CHECKSUM
);
173 case HEX_PARSE_STATE_READ_DATA
:
174 /* Track the number of read data bytes in the record */
177 /* Protect the bootloader against being written to */
178 if (HEXParser
.CurrAddress
>= BOOT_START_ADDR
)
180 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
185 /* Wait for a machine word (two bytes) of data to be read */
186 if (HEXParser
.DataRem
& 0x01)
188 HEXParser
.PrevData
= HEXParser
.Data
;
192 switch (HEXParser
.RecordType
)
194 case HEX_RECORD_TYPE_Data
:
195 /* If we are writing to a new page, we need to erase it
200 boot_page_erase(HEXParser
.PageStartAddress
);
201 boot_spm_busy_wait();
206 /* Fill the FLASH memory buffer with the new word of data */
207 boot_page_fill(HEXParser
.CurrAddress
, ((uint16_t)HEXParser
.Data
<< 8) | HEXParser
.PrevData
);
208 HEXParser
.CurrAddress
+= 2;
210 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
211 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
212 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
214 boot_page_write(HEXParser
.PageStartAddress
);
215 boot_spm_busy_wait();
217 HEXParser
.PageStartAddress
= NewPageStartAddress
;
223 case HEX_RECORD_TYPE_ExtendedSegmentAddress
:
224 /* Extended address data - store the upper 12-bits of the new address */
225 HEXParser
.CurrBaseAddress
= (((uint32_t)HEXParser
.PrevData
<< 8) | HEXParser
.Data
) << 4;
228 case HEX_RECORD_TYPE_ExtendedLinearAddress
:
229 /* Extended address data - store the upper 16-bits of the new address */
230 HEXParser
.CurrBaseAddress
= (((uint32_t)HEXParser
.PrevData
<< 8) | HEXParser
.Data
) << 16;
234 if (!HEXParser
.DataRem
)
235 HEXParser
.ParserState
= HEX_PARSE_STATE_CHECKSUM
;
238 case HEX_PARSE_STATE_CHECKSUM
:
239 /* Verify checksum of the completed record */
240 if (HEXParser
.Data
!= ((~HEXParser
.Checksum
+ 1) & 0xFF))
243 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
244 uint32_t NewPageStartAddress
= (HEXParser
.CurrAddress
& ~(SPM_PAGESIZE
- 1));
245 if (PageDirty
&& (HEXParser
.PageStartAddress
!= NewPageStartAddress
))
247 boot_page_write(HEXParser
.PageStartAddress
);
248 boot_spm_busy_wait();
250 HEXParser
.PageStartAddress
= NewPageStartAddress
;
258 HEXParser
.ParserState
= HEX_PARSE_STATE_WAIT_LINE
;
263 /** Main program entry point. This routine configures the hardware required by the application, then
264 * enters a loop to run the application tasks in sequence.
270 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
271 GlobalInterruptEnable();
277 Endpoint_SelectEndpoint(PRINTER_OUT_EPADDR
);
279 /* Check if we have received new printer data from the host */
280 if (Endpoint_IsOUTReceived()) {
281 LEDs_ToggleLEDs(LEDMASK_USB_BUSY
);
283 /* Read all bytes of data from the host and parse them */
284 while (Endpoint_IsReadWriteAllowed())
286 /* Feed the next byte of data to the HEX parser */
287 ParseIntelHEXByte(Endpoint_Read_8());
290 /* Send an ACK to the host, ready for the next data packet */
293 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
298 /** Configures the board hardware and chip peripherals for the demo's functionality. */
299 void SetupHardware(void)
301 /* Disable watchdog if enabled by bootloader/fuses */
302 MCUSR
&= ~(1 << WDRF
);
305 /* Disable clock division */
306 clock_prescale_set(clock_div_1
);
308 /* Relocate the interrupt vector table to the bootloader section */
310 MCUCR
= (1 << IVSEL
);
312 /* Hardware Initialization */
316 /* Bootloader active LED toggle timer initialization */
317 TIMSK1
= (1 << TOIE1
);
318 TCCR1B
= ((1 << CS11
) | (1 << CS10
));
321 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
322 ISR(TIMER1_OVF_vect
, ISR_BLOCK
)
324 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
327 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
328 void EVENT_USB_Device_Connect(void)
330 /* Indicate USB enumerating */
331 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
334 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
335 * the status LEDs and stops the Mass Storage management task.
337 void EVENT_USB_Device_Disconnect(void)
339 /* Indicate USB not ready */
340 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
343 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
344 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
346 void EVENT_USB_Device_ConfigurationChanged(void)
348 bool ConfigSuccess
= true;
350 /* Setup Printer Data Endpoints */
351 ConfigSuccess
&= Endpoint_ConfigureEndpoint(PRINTER_IN_EPADDR
, EP_TYPE_BULK
, PRINTER_IO_EPSIZE
, 1);
352 ConfigSuccess
&= Endpoint_ConfigureEndpoint(PRINTER_OUT_EPADDR
, EP_TYPE_BULK
, PRINTER_IO_EPSIZE
, 1);
354 /* Indicate endpoint configuration success or failure */
355 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY
: LEDMASK_USB_ERROR
);
358 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
359 * the device from the USB host before passing along unhandled control requests to the library for processing
362 void EVENT_USB_Device_ControlRequest(void)
364 /* Process Printer specific control requests */
365 switch (USB_ControlRequest
.bRequest
)
367 case PRNT_REQ_GetDeviceID
:
368 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
370 /* Generic printer IEEE 1284 identification string, will bind to an in-built driver on
371 * Windows systems, and will fall-back to a text-only printer driver on *nix.
373 const char PrinterIDString
[] =
375 "MDL:Generic_/_Text_Only;"
379 Endpoint_ClearSETUP();
380 Endpoint_Write_16_BE(sizeof(PrinterIDString
));
381 Endpoint_Write_Control_Stream_LE(PrinterIDString
, strlen(PrinterIDString
));
382 Endpoint_ClearStatusStage();
386 case PRNT_REQ_GetPortStatus
:
387 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
389 Endpoint_ClearSETUP();
390 Endpoint_Write_8(PRNT_PORTSTATUS_NOTERROR
| PRNT_PORTSTATUS_SELECT
);
391 Endpoint_ClearStatusStage();
395 case PRNT_REQ_SoftReset
:
396 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
398 Endpoint_ClearSETUP();
399 Endpoint_ClearStatusStage();