Update the Printer class bootloader to use the new Printer Device Class driver, rathe...
[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 /** 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.
41 */
42 USB_ClassInfo_PRNT_Device_t TextOnly_Printer_Interface =
43 {
44 .Config =
45 {
46 .InterfaceNumber = 0,
47 .DataINEndpoint =
48 {
49 .Address = PRINTER_IN_EPADDR,
50 .Size = PRINTER_IO_EPSIZE,
51 .Banks = 1,
52 },
53 .DataOUTEndpoint =
54 {
55 .Address = PRINTER_OUT_EPADDR,
56 .Size = PRINTER_IO_EPSIZE,
57 .Banks = 1,
58 },
59 .IEEE1284String =
60 "MFG:Generic;"
61 "MDL:Generic_/_Text_Only;"
62 "CMD:1284.4;"
63 "CLS:PRINTER",
64 },
65 };
66
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.
69 */
70 struct
71 {
72 /** Current HEX parser state machine state. */
73 uint8_t ParserState;
74 /** Previously decoded numerical byte of data. */
75 uint8_t PrevData;
76 /** Currently decoded numerical byte of data. */
77 uint8_t 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)
80 * have been read.
81 */
82 bool ReadMSB;
83 /** Intel HEX record type of the current Intel HEX record. */
84 uint8_t RecordType;
85 /** Numerical bytes of data remaining to be read in the current record. */
86 uint8_t DataRem;
87 /** Checksum of the current record received so far. */
88 uint8_t Checksum;
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. */
94 uint32_t CurrAddress;
95 } HEXParser =
96 {
97 .ParserState = HEX_PARSE_STATE_WAIT_LINE
98 };
99
100 /** Indicates if there is data waiting to be written to a physical page of
101 * memory in FLASH.
102 */
103 static bool PageDirty = false;
104
105
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.
109 */
110 static bool RunBootloader = true;
111
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.
116 */
117 uint16_t MagicBootKey ATTR_NO_INIT;
118
119
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.
123 */
124 void Application_Jump_Check(void)
125 {
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))
128 {
129 MagicBootKey = 0;
130
131 // cppcheck-suppress constStatement
132 ((void (*)(void))0x0000)();
133 }
134 }
135
136 /**
137 * Determines if a given input byte of data is an ASCII encoded HEX value.
138 *
139 * \note Input HEX bytes are expected to be in uppercase only.
140 *
141 * \param[in] Byte ASCII byte of data to check
142 *
143 * \return Boolean \c true if the input data is ASCII encoded HEX, \c false otherwise.
144 */
145 static bool IsHex(const char Byte)
146 {
147 return ((Byte >= 'A') && (Byte <= 'F')) ||
148 ((Byte >= '0') && (Byte <= '9'));
149 }
150
151 /**
152 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
153 *
154 * \note Input HEX bytes are expected to be in uppercase only.
155 *
156 * \param[in] Byte ASCII byte of data to convert
157 *
158 * \return Integer converted value of the input ASCII encoded HEX byte of data.
159 */
160 static uint8_t HexToDecimal(const char Byte)
161 {
162 if ((Byte >= 'A') && (Byte <= 'F'))
163 return (10 + (Byte - 'A'));
164 else if ((Byte >= '0') && (Byte <= '9'))
165 return (Byte - '0');
166
167 return 0;
168 }
169
170 /**
171 * Parses an input Intel HEX formatted stream one character at a time, loading
172 * the data contents into the device's internal FLASH memory.
173 *
174 * \param[in] ReadCharacter Next input ASCII byte of data to parse
175 */
176 static void ParseIntelHEXByte(const char ReadCharacter)
177 {
178 /* Reset the line parser while waiting for a new line to start */
179 if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
180 {
181 HEXParser.Checksum = 0;
182 HEXParser.CurrAddress = HEXParser.CurrBaseAddress;
183 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
184 HEXParser.ReadMSB = false;
185
186 /* ASCII ':' indicates the start of a new HEX record */
187 if (ReadCharacter == ':')
188 HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
189
190 return;
191 }
192
193 /* Only allow ASCII HEX encoded digits, ignore all other characters */
194 if (!IsHex(ReadCharacter))
195 return;
196
197 /* Read and convert the next nibble of data from the current character */
198 HEXParser.Data = (HEXParser.Data << 4) | HexToDecimal(ReadCharacter);
199 HEXParser.ReadMSB = !HEXParser.ReadMSB;
200
201 /* Only process further when a full byte (two nibbles) have been read */
202 if (HEXParser.ReadMSB)
203 return;
204
205 /* Intel HEX checksum is for all fields except starting character and the
206 * checksum itself
207 */
208 if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
209 HEXParser.Checksum += HEXParser.Data;
210
211 switch (HEXParser.ParserState)
212 {
213 case HEX_PARSE_STATE_BYTE_COUNT:
214 HEXParser.DataRem = HEXParser.Data;
215 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_HIGH;
216 break;
217
218 case HEX_PARSE_STATE_ADDRESS_HIGH:
219 HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
220 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_LOW;
221 break;
222
223 case HEX_PARSE_STATE_ADDRESS_LOW:
224 HEXParser.CurrAddress += HEXParser.Data;
225 HEXParser.ParserState = HEX_PARSE_STATE_RECORD_TYPE;
226 break;
227
228 case HEX_PARSE_STATE_RECORD_TYPE:
229 HEXParser.RecordType = HEXParser.Data;
230 HEXParser.ParserState = (HEXParser.DataRem ? HEX_PARSE_STATE_READ_DATA : HEX_PARSE_STATE_CHECKSUM);
231 break;
232
233 case HEX_PARSE_STATE_READ_DATA:
234 /* Track the number of read data bytes in the record */
235 HEXParser.DataRem--;
236
237 /* Protect the bootloader against being written to */
238 if (HEXParser.CurrAddress >= BOOT_START_ADDR)
239 {
240 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
241 PageDirty = false;
242 return;
243 }
244
245 /* Wait for a machine word (two bytes) of data to be read */
246 if (HEXParser.DataRem & 0x01)
247 {
248 HEXParser.PrevData = HEXParser.Data;
249 break;
250 }
251
252 /* Convert the last two received data bytes into a 16-bit word */
253 uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
254
255 switch (HEXParser.RecordType)
256 {
257 case HEX_RECORD_TYPE_Data:
258 /* If we are writing to a new page, we need to erase it
259 * first
260 */
261 if (!(PageDirty))
262 {
263 boot_page_erase(HEXParser.PageStartAddress);
264 boot_spm_busy_wait();
265
266 PageDirty = true;
267 }
268
269 /* Fill the FLASH memory buffer with the new word of data */
270 boot_page_fill(HEXParser.CurrAddress, NewDataWord);
271 HEXParser.CurrAddress += 2;
272
273 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
274 uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
275 if (PageDirty && (HEXParser.PageStartAddress != NewPageStartAddress))
276 {
277 boot_page_write(HEXParser.PageStartAddress);
278 boot_spm_busy_wait();
279
280 HEXParser.PageStartAddress = NewPageStartAddress;
281
282 PageDirty = false;
283 }
284 break;
285
286 case HEX_RECORD_TYPE_ExtendedSegmentAddress:
287 /* Extended address data - store the upper 12-bits of the new address */
288 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 4);
289 break;
290
291 case HEX_RECORD_TYPE_ExtendedLinearAddress:
292 /* Extended address data - store the upper 16-bits of the new address */
293 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 16);
294 break;
295 }
296
297 if (!HEXParser.DataRem)
298 HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
299 break;
300
301 case HEX_PARSE_STATE_CHECKSUM:
302 /* Verify checksum of the completed record */
303 if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
304 break;
305
306 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
307 uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
308 if (PageDirty && (HEXParser.PageStartAddress != NewPageStartAddress))
309 {
310 boot_page_write(HEXParser.PageStartAddress);
311 boot_spm_busy_wait();
312
313 HEXParser.PageStartAddress = NewPageStartAddress;
314
315 PageDirty = false;
316 }
317
318 /* If end of the HEX file reached, the bootloader should exit at next opportunity */
319 if (HEXParser.RecordType == HEX_RECORD_TYPE_EndOfFile)
320 RunBootloader = false;
321
322 break;
323
324 default:
325 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
326 break;
327 }
328 }
329
330 /** Main program entry point. This routine configures the hardware required by the application, then
331 * enters a loop to run the application tasks in sequence.
332 */
333 int main(void)
334 {
335 SetupHardware();
336
337 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
338 GlobalInterruptEnable();
339
340 while (RunBootloader)
341 {
342 uint8_t BytesReceived = PRNT_Device_BytesReceived(&TextOnly_Printer_Interface);
343
344 if (BytesReceived)
345 {
346 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
347
348 while (BytesReceived--)
349 {
350 int16_t ReceivedByte = PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface);
351
352 /* Feed the next byte of data to the HEX parser */
353 ParseIntelHEXByte(ReceivedByte);
354 }
355
356 LEDs_SetAllLEDs(LEDMASK_USB_READY);
357 }
358
359 PRNT_Device_USBTask(&TextOnly_Printer_Interface);
360 USB_USBTask();
361 }
362
363 /* Disconnect from the host - USB interface will be reset later along with the AVR */
364 USB_Detach();
365
366 /* Unlock the forced application start mode of the bootloader if it is restarted */
367 MagicBootKey = MAGIC_BOOT_KEY;
368
369 /* Enable the watchdog and force a timeout to reset the AVR */
370 wdt_enable(WDTO_250MS);
371
372 for (;;);
373 }
374
375 /** Configures the board hardware and chip peripherals for the demo's functionality. */
376 static void SetupHardware(void)
377 {
378 /* Disable watchdog if enabled by bootloader/fuses */
379 MCUSR &= ~(1 << WDRF);
380 wdt_disable();
381
382 /* Disable clock division */
383 clock_prescale_set(clock_div_1);
384
385 /* Relocate the interrupt vector table to the bootloader section */
386 MCUCR = (1 << IVCE);
387 MCUCR = (1 << IVSEL);
388
389 /* Hardware Initialization */
390 LEDs_Init();
391 USB_Init();
392
393 /* Bootloader active LED toggle timer initialization */
394 TIMSK1 = (1 << TOIE1);
395 TCCR1B = ((1 << CS11) | (1 << CS10));
396 }
397
398 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
399 ISR(TIMER1_OVF_vect, ISR_BLOCK)
400 {
401 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
402 }
403
404 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
405 void EVENT_USB_Device_Connect(void)
406 {
407 /* Indicate USB enumerating */
408 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
409 }
410
411 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
412 * the status LEDs and stops the Printer management task.
413 */
414 void EVENT_USB_Device_Disconnect(void)
415 {
416 /* Indicate USB not ready */
417 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
418 }
419
420 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
421 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
422 */
423 void EVENT_USB_Device_ConfigurationChanged(void)
424 {
425 bool ConfigSuccess = true;
426
427 /* Setup Printer Data Endpoints */
428 ConfigSuccess &= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface);
429
430 /* Indicate endpoint configuration success or failure */
431 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
432 }
433
434 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
435 * the device from the USB host before passing along unhandled control requests to the library for processing
436 * internally.
437 */
438 void EVENT_USB_Device_ControlRequest(void)
439 {
440 PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface);
441 }