Minor documentation improvements.
[pub/USBasp.git] / Bootloaders / Printer / BootloaderPrinter.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2013.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2013 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
33 * Main source file for the Printer class bootloader. This file contains the complete bootloader logic.
34 */
35
36 #include "BootloaderPrinter.h"
37
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.
40 */
41 struct
42 {
43 /** Current HEX parser state machine state. */
44 uint8_t ParserState;
45 /** Previously decoded numerical byte of data. */
46 uint8_t PrevData;
47 /** Currently decoded numerical byte of data. */
48 uint8_t 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)
51 * have been read.
52 */
53 bool ReadMSB;
54 /** Intel HEX record type of the current Intel HEX record. */
55 uint8_t RecordType;
56 /** Numerical bytes of data remaining to be read in the current record. */
57 uint8_t DataRem;
58 /** Checksum of the current record received so far. */
59 uint8_t Checksum;
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. */
65 uint32_t CurrAddress;
66 } HEXParser =
67 {
68 .ParserState = HEX_PARSE_STATE_WAIT_LINE
69 };
70
71 /** Indicates if there is data waiting to be written to a physical page of
72 * memory in FLASH.
73 */
74 static bool PageDirty = false;
75
76
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.
80 */
81 static bool RunBootloader = true;
82
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.
87 */
88 uint16_t MagicBootKey ATTR_NO_INIT;
89
90
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.
94 */
95 void Application_Jump_Check(void)
96 {
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))
99 {
100 MagicBootKey = 0;
101
102 // cppcheck-suppress constStatement
103 ((void (*)(void))0x0000)();
104 }
105 }
106
107 /**
108 * Determines if a given input byte of data is an ASCII encoded HEX value.
109 *
110 * \note Input HEX bytes are expected to be in uppercase only.
111 *
112 * \param[in] Byte ASCII byte of data to check
113 *
114 * \return Boolean \c true if the input data is ASCII encoded HEX, \c false otherwise.
115 */
116 static bool IsHex(const char Byte)
117 {
118 return ((Byte >= 'A') && (Byte <= 'F')) ||
119 ((Byte >= '0') && (Byte <= '9'));
120 }
121
122 /**
123 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
124 *
125 * \note Input HEX bytes are expected to be in uppercase only.
126 *
127 * \param[in] Byte ASCII byte of data to convert
128 *
129 * \return Integer converted value of the input ASCII encoded HEX byte of data.
130 */
131 static uint8_t HexToDecimal(const char Byte)
132 {
133 if ((Byte >= 'A') && (Byte <= 'F'))
134 return (10 + (Byte - 'A'));
135 else if ((Byte >= '0') && (Byte <= '9'))
136 return (Byte - '0');
137
138 return 0;
139 }
140
141 /**
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.
144 *
145 * \param[in] ReadCharacter Next input ASCII byte of data to parse
146 */
147 static void ParseIntelHEXByte(const char ReadCharacter)
148 {
149 /* Reset the line parser while waiting for a new line to start */
150 if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
151 {
152 HEXParser.Checksum = 0;
153 HEXParser.CurrAddress = HEXParser.CurrBaseAddress;
154 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
155 HEXParser.ReadMSB = false;
156
157 /* ASCII ':' indicates the start of a new HEX record */
158 if (ReadCharacter == ':')
159 HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
160
161 return;
162 }
163
164 /* Only allow ASCII HEX encoded digits, ignore all other characters */
165 if (!IsHex(ReadCharacter))
166 return;
167
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;
171
172 /* Only process further when a full byte (two nibbles) have been read */
173 if (HEXParser.ReadMSB)
174 return;
175
176 /* Intel HEX checksum is for all fields except starting character and the
177 * checksum itself
178 */
179 if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
180 HEXParser.Checksum += HEXParser.Data;
181
182 switch (HEXParser.ParserState)
183 {
184 case HEX_PARSE_STATE_BYTE_COUNT:
185 HEXParser.DataRem = HEXParser.Data;
186 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_HIGH;
187 break;
188
189 case HEX_PARSE_STATE_ADDRESS_HIGH:
190 HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
191 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_LOW;
192 break;
193
194 case HEX_PARSE_STATE_ADDRESS_LOW:
195 HEXParser.CurrAddress += HEXParser.Data;
196 HEXParser.ParserState = HEX_PARSE_STATE_RECORD_TYPE;
197 break;
198
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);
202 break;
203
204 case HEX_PARSE_STATE_READ_DATA:
205 /* Track the number of read data bytes in the record */
206 HEXParser.DataRem--;
207
208 /* Protect the bootloader against being written to */
209 if (HEXParser.CurrAddress >= BOOT_START_ADDR)
210 {
211 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
212 PageDirty = false;
213 return;
214 }
215
216 /* Wait for a machine word (two bytes) of data to be read */
217 if (HEXParser.DataRem & 0x01)
218 {
219 HEXParser.PrevData = HEXParser.Data;
220 break;
221 }
222
223 /* Convert the last two received data bytes into a 16-bit word */
224 uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
225
226 switch (HEXParser.RecordType)
227 {
228 case HEX_RECORD_TYPE_Data:
229 /* If we are writing to a new page, we need to erase it
230 * first
231 */
232 if (!(PageDirty))
233 {
234 boot_page_erase(HEXParser.PageStartAddress);
235 boot_spm_busy_wait();
236
237 PageDirty = true;
238 }
239
240 /* Fill the FLASH memory buffer with the new word of data */
241 boot_page_fill(HEXParser.CurrAddress, NewDataWord);
242 HEXParser.CurrAddress += 2;
243
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))
247 {
248 boot_page_write(HEXParser.PageStartAddress);
249 boot_spm_busy_wait();
250
251 HEXParser.PageStartAddress = NewPageStartAddress;
252
253 PageDirty = false;
254 }
255 break;
256
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);
260 break;
261
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);
265 break;
266 }
267
268 if (!HEXParser.DataRem)
269 HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
270 break;
271
272 case HEX_PARSE_STATE_CHECKSUM:
273 /* Verify checksum of the completed record */
274 if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
275 break;
276
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))
280 {
281 boot_page_write(HEXParser.PageStartAddress);
282 boot_spm_busy_wait();
283
284 HEXParser.PageStartAddress = NewPageStartAddress;
285
286 PageDirty = false;
287 }
288
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;
292
293 break;
294
295 default:
296 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
297 break;
298 }
299 }
300
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.
303 */
304 int main(void)
305 {
306 SetupHardware();
307
308 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
309 GlobalInterruptEnable();
310
311 while (RunBootloader)
312 {
313 USB_USBTask();
314
315 Endpoint_SelectEndpoint(PRINTER_OUT_EPADDR);
316
317 /* Check if we have received new printer data from the host */
318 if (Endpoint_IsOUTReceived()) {
319 LEDs_ToggleLEDs(LEDMASK_USB_BUSY);
320
321 /* Read all bytes of data from the host and parse them */
322 while (Endpoint_IsReadWriteAllowed())
323 {
324 /* Feed the next byte of data to the HEX parser */
325 ParseIntelHEXByte(Endpoint_Read_8());
326 }
327
328 /* Send an ACK to the host, ready for the next data packet */
329 Endpoint_ClearOUT();
330
331 LEDs_SetAllLEDs(LEDMASK_USB_READY);
332 }
333 }
334
335 /* Disconnect from the host - USB interface will be reset later along with the AVR */
336 USB_Detach();
337
338 /* Unlock the forced application start mode of the bootloader if it is restarted */
339 MagicBootKey = MAGIC_BOOT_KEY;
340
341 /* Enable the watchdog and force a timeout to reset the AVR */
342 wdt_enable(WDTO_250MS);
343
344 for (;;);
345 }
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
354 /* Disable clock division */
355 clock_prescale_set(clock_div_1);
356
357 /* Relocate the interrupt vector table to the bootloader section */
358 MCUCR = (1 << IVCE);
359 MCUCR = (1 << IVSEL);
360
361 /* Hardware Initialization */
362 LEDs_Init();
363 USB_Init();
364
365 /* Bootloader active LED toggle timer initialization */
366 TIMSK1 = (1 << TOIE1);
367 TCCR1B = ((1 << CS11) | (1 << CS10));
368 }
369
370 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
371 ISR(TIMER1_OVF_vect, ISR_BLOCK)
372 {
373 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
374 }
375
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)
378 {
379 /* Indicate USB enumerating */
380 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
381 }
382
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.
385 */
386 void EVENT_USB_Device_Disconnect(void)
387 {
388 /* Indicate USB not ready */
389 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
390 }
391
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.
394 */
395 void EVENT_USB_Device_ConfigurationChanged(void)
396 {
397 bool ConfigSuccess = true;
398
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);
402
403 /* Indicate endpoint configuration success or failure */
404 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
405 }
406
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
409 * internally.
410 */
411 void EVENT_USB_Device_ControlRequest(void)
412 {
413 /* Process Printer specific control requests */
414 switch (USB_ControlRequest.bRequest)
415 {
416 case PRNT_REQ_GetDeviceID:
417 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
418 {
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.
421 */
422 const char PrinterIDString[] =
423 "MFG:Generic;"
424 "MDL:Generic_/_Text_Only;"
425 "CMD:1284.4;"
426 "CLS:PRINTER";
427
428 Endpoint_ClearSETUP();
429
430 while (!(Endpoint_IsINReady()))
431 {
432 if (USB_DeviceState == DEVICE_STATE_Unattached)
433 return;
434 }
435
436 Endpoint_Write_16_BE(sizeof(PrinterIDString));
437 Endpoint_Write_Control_Stream_LE(PrinterIDString, strlen(PrinterIDString));
438 Endpoint_ClearStatusStage();
439 }
440
441 break;
442 case PRNT_REQ_GetPortStatus:
443 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
444 {
445 Endpoint_ClearSETUP();
446
447 while (!(Endpoint_IsINReady()))
448 {
449 if (USB_DeviceState == DEVICE_STATE_Unattached)
450 return;
451 }
452
453 Endpoint_Write_8(PRNT_PORTSTATUS_NOTERROR | PRNT_PORTSTATUS_SELECT);
454 Endpoint_ClearStatusStage();
455 }
456
457 break;
458 case PRNT_REQ_SoftReset:
459 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
460 {
461 Endpoint_ClearSETUP();
462 Endpoint_ClearStatusStage();
463 }
464
465 break;
466 }
467 }