]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - tmk_core/protocol/lufa/LUFA-git/Bootloaders/Printer/BootloaderPrinter.c
Merge commit '657d9f23fe47fb88cf221adb23095082f191ba6a'
[max/tmk_keyboard.git] / tmk_core / protocol / lufa / LUFA-git / Bootloaders / Printer / BootloaderPrinter.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  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          = INTERFACE_ID_Printer,
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 /** Indicates if there is data waiting to be written to a physical page of
98  *  memory in FLASH.
99  */
100 static bool PageDirty = false;
101
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.
105  */
106 static bool RunBootloader = true;
107
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.
112  */
113 uint16_t MagicBootKey ATTR_NO_INIT;
114
115
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.
119  */
120 void Application_Jump_Check(void)
121 {
122         /* If the reset source was the bootloader and the key is correct, clear it and jump to the application */
123         if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
124         {
125                 MagicBootKey = 0;
126
127                 // cppcheck-suppress constStatement
128                 ((void (*)(void))0x0000)();
129         }
130 }
131
132 /**
133  * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
134  *
135  * \note Input HEX bytes are expected to be in uppercase only.
136  *
137  * \param[in] Byte  ASCII byte of data to convert
138  *
139  * \return Integer converted value of the input ASCII encoded HEX byte of data, or -1 if the
140  *         input is not valid ASCII encoded HEX.
141  */
142 static int8_t HexToDecimal(const char Byte)
143 {
144         if ((Byte >= 'A') && (Byte <= 'F'))
145           return (10 + (Byte - 'A'));
146         else if ((Byte >= '0') && (Byte <= '9'))
147           return (Byte - '0');
148
149         return -1;
150 }
151
152 /**
153  * Flushes a partially written page of data to physical FLASH, if a page
154  * boundary has been crossed.
155  *
156  * \note If a page flush occurs the global HEX parser state is updated.
157  */
158 static void FlushPageIfRequired(void)
159 {
160         /* Abort if no data has been buffered for writing to the current page */
161         if (!PageDirty)
162           return;
163
164         /* Flush the FLASH page to physical memory if we are crossing a page boundary */
165         uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
166         if (HEXParser.PageStartAddress != NewPageStartAddress)
167         {
168                 boot_page_write(HEXParser.PageStartAddress);
169                 boot_spm_busy_wait();
170
171                 HEXParser.PageStartAddress = NewPageStartAddress;
172
173                 PageDirty = false;
174         }
175 }
176
177 /**
178  * Parses an input Intel HEX formatted stream one character at a time, loading
179  * the data contents into the device's internal FLASH memory.
180  *
181  * \param[in] ReadCharacter  Next input ASCII byte of data to parse
182  */
183 static void ParseIntelHEXByte(const char ReadCharacter)
184 {
185         /* Reset the line parser while waiting for a new line to start */
186         if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
187         {
188                 HEXParser.Checksum     = 0;
189                 HEXParser.CurrAddress  = HEXParser.CurrBaseAddress;
190                 HEXParser.ReadMSB      = false;
191
192                 /* ASCII ':' indicates the start of a new HEX record */
193                 if (ReadCharacter == ':')
194                   HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
195
196                 return;
197         }
198
199         /* Only allow ASCII HEX encoded digits, ignore all other characters */
200         int8_t ReadCharacterDec = HexToDecimal(ReadCharacter);
201         if (ReadCharacterDec < 0)
202           return;
203
204         /* Read and convert the next nibble of data from the current character */
205         HEXParser.Data    = (HEXParser.Data << 4) | ReadCharacterDec;
206         HEXParser.ReadMSB = !HEXParser.ReadMSB;
207
208         /* Only process further when a full byte (two nibbles) have been read */
209         if (HEXParser.ReadMSB)
210           return;
211
212         /* Intel HEX checksum is for all fields except starting character and the
213          * checksum itself
214          */
215         if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
216           HEXParser.Checksum += HEXParser.Data;
217
218         switch (HEXParser.ParserState)
219         {
220                 case HEX_PARSE_STATE_BYTE_COUNT:
221                         HEXParser.DataRem      = HEXParser.Data;
222                         HEXParser.ParserState  = HEX_PARSE_STATE_ADDRESS_HIGH;
223                         break;
224
225                 case HEX_PARSE_STATE_ADDRESS_HIGH:
226                         HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
227                         HEXParser.ParserState  = HEX_PARSE_STATE_ADDRESS_LOW;
228                         break;
229
230                 case HEX_PARSE_STATE_ADDRESS_LOW:
231                         HEXParser.CurrAddress += HEXParser.Data;
232                         HEXParser.ParserState  = HEX_PARSE_STATE_RECORD_TYPE;
233                         break;
234
235                 case HEX_PARSE_STATE_RECORD_TYPE:
236                         HEXParser.RecordType   = HEXParser.Data;
237                         HEXParser.ParserState  = (HEXParser.DataRem ? HEX_PARSE_STATE_READ_DATA : HEX_PARSE_STATE_CHECKSUM);
238                         break;
239
240                 case HEX_PARSE_STATE_READ_DATA:
241                         /* Track the number of read data bytes in the record */
242                         HEXParser.DataRem--;
243
244                         /* Protect the bootloader against being written to */
245                         if (HEXParser.CurrAddress >= BOOT_START_ADDR)
246                         {
247                                 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
248                                 PageDirty = false;
249                                 return;
250                         }
251
252                         /* Wait for a machine word (two bytes) of data to be read */
253                         if (HEXParser.DataRem & 0x01)
254                         {
255                                 HEXParser.PrevData = HEXParser.Data;
256                                 break;
257                         }
258
259                         /* Convert the last two received data bytes into a 16-bit word */
260                         uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
261
262                         switch (HEXParser.RecordType)
263                         {
264                                 case HEX_RECORD_TYPE_Data:
265                                         /* If we are writing to a new page, we need to erase it first */
266                                         if (!(PageDirty))
267                                         {
268                                                 boot_page_erase(HEXParser.PageStartAddress);
269                                                 boot_spm_busy_wait();
270
271                                                 PageDirty = true;
272                                         }
273
274                                         /* Fill the FLASH memory buffer with the new word of data */
275                                         boot_page_fill(HEXParser.CurrAddress, NewDataWord);
276                                         HEXParser.CurrAddress += 2;
277
278                                         /* Flush the FLASH page to physical memory if we are crossing a page boundary */
279                                         FlushPageIfRequired();
280                                         break;
281
282                                 case HEX_RECORD_TYPE_ExtendedSegmentAddress:
283                                         /* Extended address data - store the upper 12-bits of the new address */
284                                         HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 4);
285                                         break;
286
287                                 case HEX_RECORD_TYPE_ExtendedLinearAddress:
288                                         /* Extended address data - store the upper 16-bits of the new address */
289                                         HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 16);
290                                         break;
291                         }
292
293                         if (!HEXParser.DataRem)
294                           HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
295                         break;
296
297                 case HEX_PARSE_STATE_CHECKSUM:
298                         /* Verify checksum of the completed record */
299                         if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
300                           break;
301
302                         /* Flush the FLASH page to physical memory if we are crossing a page boundary */
303                         FlushPageIfRequired();
304
305                         /* If end of the HEX file reached, the bootloader should exit at next opportunity */
306                         if (HEXParser.RecordType == HEX_RECORD_TYPE_EndOfFile)
307                           RunBootloader = false;
308
309                         break;
310
311                 default:
312                         HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
313                         break;
314         }
315 }
316
317 /** Main program entry point. This routine configures the hardware required by the application, then
318  *  enters a loop to run the application tasks in sequence.
319  */
320 int main(void)
321 {
322         SetupHardware();
323
324         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
325         GlobalInterruptEnable();
326
327         while (RunBootloader)
328         {
329                 uint8_t BytesReceived = PRNT_Device_BytesReceived(&TextOnly_Printer_Interface);
330
331                 if (BytesReceived)
332                 {
333                         LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
334
335                         while (BytesReceived--)
336                         {
337                                 int16_t ReceivedByte = PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface);
338
339                                 /* Feed the next byte of data to the HEX parser */
340                                 ParseIntelHEXByte(ReceivedByte);
341                         }
342
343                         LEDs_SetAllLEDs(LEDMASK_USB_READY);
344                 }
345
346                 PRNT_Device_USBTask(&TextOnly_Printer_Interface);
347                 USB_USBTask();
348         }
349
350         /* Disconnect from the host - USB interface will be reset later along with the AVR */
351         USB_Detach();
352
353         /* Unlock the forced application start mode of the bootloader if it is restarted */
354         MagicBootKey = MAGIC_BOOT_KEY;
355
356         /* Enable the watchdog and force a timeout to reset the AVR */
357         wdt_enable(WDTO_250MS);
358
359         for (;;);
360 }
361
362 /** Configures the board hardware and chip peripherals for the demo's functionality. */
363 static void SetupHardware(void)
364 {
365         /* Disable watchdog if enabled by bootloader/fuses */
366         MCUSR &= ~(1 << WDRF);
367         wdt_disable();
368
369         /* Disable clock division */
370         clock_prescale_set(clock_div_1);
371
372         /* Relocate the interrupt vector table to the bootloader section */
373         MCUCR = (1 << IVCE);
374         MCUCR = (1 << IVSEL);
375
376         /* Hardware Initialization */
377         LEDs_Init();
378         USB_Init();
379
380         /* Bootloader active LED toggle timer initialization */
381         TIMSK1 = (1 << TOIE1);
382         TCCR1B = ((1 << CS11) | (1 << CS10));
383 }
384
385 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
386 ISR(TIMER1_OVF_vect, ISR_BLOCK)
387 {
388         LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
389 }
390
391 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
392 void EVENT_USB_Device_Connect(void)
393 {
394         /* Indicate USB enumerating */
395         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
396 }
397
398 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
399  *  the status LEDs and stops the Printer management task.
400  */
401 void EVENT_USB_Device_Disconnect(void)
402 {
403         /* Indicate USB not ready */
404         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
405 }
406
407 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
408  *  of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
409  */
410 void EVENT_USB_Device_ConfigurationChanged(void)
411 {
412         bool ConfigSuccess = true;
413
414         /* Setup Printer Data Endpoints */
415         ConfigSuccess &= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface);
416
417         /* Reset the HEX parser upon successful connection to a host */
418         HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
419
420         /* Indicate endpoint configuration success or failure */
421         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
422 }
423
424 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
425  *  the device from the USB host before passing along unhandled control requests to the library for processing
426  *  internally.
427  */
428 void EVENT_USB_Device_ControlRequest(void)
429 {
430         PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface);
431 }