Add documentation to the incomplete Mass Storage class bootloader, update the virtual...
[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 * Determines if a given input byte of data is an ASCII encoded HEX value.
78 *
79 * \note Input HEX bytes are expected to be in uppercase only.
80 *
81 * \param[in] Byte ASCII byte of data to check
82 *
83 * \return Boolean \c true if the input data is ASCII encoded HEX, false otherwise.
84 */
85 static bool IsHex(const char Byte)
86 {
87 return ((Byte >= 'A') && (Byte <= 'F')) ||
88 ((Byte >= '0') && (Byte <= '9'));
89 }
90
91 /**
92 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
93 *
94 * \note Input HEX bytes are expected to be in uppercase only.
95 *
96 * \param[in] Byte ASCII byte of data to convert
97 *
98 * \return Integer converted value of the input ASCII encoded HEX byte of data.
99 */
100 static uint8_t HexToDecimal(const char Byte)
101 {
102 if ((Byte >= 'A') && (Byte <= 'F'))
103 return (10 + (Byte - 'A'));
104 else if ((Byte >= '0') && (Byte <= '9'))
105 return (Byte - '0');
106
107 return 0;
108 }
109
110 /**
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.
113 *
114 * \param[in] ReadCharacter Next input ASCII byte of data to parse
115 */
116 static void ParseIntelHEXByte(const char ReadCharacter)
117 {
118 /* Reset the line parser while waiting for a new line to start */
119 if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
120 {
121 HEXParser.Checksum = 0;
122 HEXParser.CurrAddress = HEXParser.CurrBaseAddress;
123 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
124 HEXParser.ReadMSB = false;
125
126 /* ASCII ':' indicates the start of a new HEX record */
127 if (ReadCharacter == ':')
128 HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
129
130 return;
131 }
132
133 /* Only allow ASCII HEX encoded digits, ignore all other characters */
134 if (!IsHex(ReadCharacter))
135 return;
136
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;
140
141 /* Only process further when a full byte (two nibbles) have been read */
142 if (HEXParser.ReadMSB)
143 return;
144
145 /* Intel HEX checksum is for all fields except starting character and the
146 * checksum itself
147 */
148 if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
149 HEXParser.Checksum += HEXParser.Data;
150
151 switch (HEXParser.ParserState)
152 {
153 case HEX_PARSE_STATE_BYTE_COUNT:
154 HEXParser.DataRem = HEXParser.Data;
155 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_HIGH;
156 break;
157
158 case HEX_PARSE_STATE_ADDRESS_HIGH:
159 HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
160 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_LOW;
161 break;
162
163 case HEX_PARSE_STATE_ADDRESS_LOW:
164 HEXParser.CurrAddress += HEXParser.Data;
165 HEXParser.ParserState = HEX_PARSE_STATE_RECORD_TYPE;
166 break;
167
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);
171 break;
172
173 case HEX_PARSE_STATE_READ_DATA:
174 /* Track the number of read data bytes in the record */
175 HEXParser.DataRem--;
176
177 /* Protect the bootloader against being written to */
178 if (HEXParser.CurrAddress >= BOOT_START_ADDR)
179 {
180 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
181 PageDirty = false;
182 return;
183 }
184
185 /* Wait for a machine word (two bytes) of data to be read */
186 if (HEXParser.DataRem & 0x01)
187 {
188 HEXParser.PrevData = HEXParser.Data;
189 break;
190 }
191
192 /* Convert the last two received data bytes into a 16-bit word */
193 uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
194
195 switch (HEXParser.RecordType)
196 {
197 case HEX_RECORD_TYPE_Data:
198 /* If we are writing to a new page, we need to erase it
199 * first
200 */
201 if (!(PageDirty))
202 {
203 boot_page_erase(HEXParser.PageStartAddress);
204 boot_spm_busy_wait();
205
206 PageDirty = true;
207 }
208
209 /* Fill the FLASH memory buffer with the new word of data */
210 boot_page_fill(HEXParser.CurrAddress, NewDataWord);
211 HEXParser.CurrAddress += 2;
212
213 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
214 uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
215 if (PageDirty && (HEXParser.PageStartAddress != NewPageStartAddress))
216 {
217 boot_page_write(HEXParser.PageStartAddress);
218 boot_spm_busy_wait();
219
220 HEXParser.PageStartAddress = NewPageStartAddress;
221
222 PageDirty = false;
223 }
224 break;
225
226 case HEX_RECORD_TYPE_ExtendedSegmentAddress:
227 /* Extended address data - store the upper 12-bits of the new address */
228 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 4);
229 break;
230
231 case HEX_RECORD_TYPE_ExtendedLinearAddress:
232 /* Extended address data - store the upper 16-bits of the new address */
233 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 16);
234 break;
235 }
236
237 if (!HEXParser.DataRem)
238 HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
239 break;
240
241 case HEX_PARSE_STATE_CHECKSUM:
242 /* Verify checksum of the completed record */
243 if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
244 break;
245
246 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
247 uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
248 if (PageDirty && (HEXParser.PageStartAddress != NewPageStartAddress))
249 {
250 boot_page_write(HEXParser.PageStartAddress);
251 boot_spm_busy_wait();
252
253 HEXParser.PageStartAddress = NewPageStartAddress;
254
255 PageDirty = false;
256 }
257
258 break;
259
260 default:
261 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
262 break;
263 }
264 }
265
266 /** Main program entry point. This routine configures the hardware required by the application, then
267 * enters a loop to run the application tasks in sequence.
268 */
269 int main(void)
270 {
271 SetupHardware();
272
273 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
274 GlobalInterruptEnable();
275
276 for (;;)
277 {
278 USB_USBTask();
279
280 Endpoint_SelectEndpoint(PRINTER_OUT_EPADDR);
281
282 /* Check if we have received new printer data from the host */
283 if (Endpoint_IsOUTReceived()) {
284 LEDs_ToggleLEDs(LEDMASK_USB_BUSY);
285
286 /* Read all bytes of data from the host and parse them */
287 while (Endpoint_IsReadWriteAllowed())
288 {
289 /* Feed the next byte of data to the HEX parser */
290 ParseIntelHEXByte(Endpoint_Read_8());
291 }
292
293 /* Send an ACK to the host, ready for the next data packet */
294 Endpoint_ClearOUT();
295
296 LEDs_SetAllLEDs(LEDMASK_USB_READY);
297 }
298 }
299 }
300
301 /** Configures the board hardware and chip peripherals for the demo's functionality. */
302 void SetupHardware(void)
303 {
304 /* Disable watchdog if enabled by bootloader/fuses */
305 MCUSR &= ~(1 << WDRF);
306 wdt_disable();
307
308 /* Disable clock division */
309 clock_prescale_set(clock_div_1);
310
311 /* Relocate the interrupt vector table to the bootloader section */
312 MCUCR = (1 << IVCE);
313 MCUCR = (1 << IVSEL);
314
315 /* Hardware Initialization */
316 LEDs_Init();
317 USB_Init();
318
319 /* Bootloader active LED toggle timer initialization */
320 TIMSK1 = (1 << TOIE1);
321 TCCR1B = ((1 << CS11) | (1 << CS10));
322 }
323
324 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
325 ISR(TIMER1_OVF_vect, ISR_BLOCK)
326 {
327 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
328 }
329
330 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
331 void EVENT_USB_Device_Connect(void)
332 {
333 /* Indicate USB enumerating */
334 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
335 }
336
337 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
338 * the status LEDs and stops the Printer management task.
339 */
340 void EVENT_USB_Device_Disconnect(void)
341 {
342 /* Indicate USB not ready */
343 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
344 }
345
346 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
347 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
348 */
349 void EVENT_USB_Device_ConfigurationChanged(void)
350 {
351 bool ConfigSuccess = true;
352
353 /* Setup Printer Data Endpoints */
354 ConfigSuccess &= Endpoint_ConfigureEndpoint(PRINTER_IN_EPADDR, EP_TYPE_BULK, PRINTER_IO_EPSIZE, 1);
355 ConfigSuccess &= Endpoint_ConfigureEndpoint(PRINTER_OUT_EPADDR, EP_TYPE_BULK, PRINTER_IO_EPSIZE, 1);
356
357 /* Indicate endpoint configuration success or failure */
358 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
359 }
360
361 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
362 * the device from the USB host before passing along unhandled control requests to the library for processing
363 * internally.
364 */
365 void EVENT_USB_Device_ControlRequest(void)
366 {
367 /* Process Printer specific control requests */
368 switch (USB_ControlRequest.bRequest)
369 {
370 case PRNT_REQ_GetDeviceID:
371 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
372 {
373 /* Generic printer IEEE 1284 identification string, will bind to an in-built driver on
374 * Windows systems, and will fall-back to a text-only printer driver on *nix.
375 */
376 const char PrinterIDString[] =
377 "MFG:Generic;"
378 "MDL:Generic_/_Text_Only;"
379 "CMD:1284.4;"
380 "CLS:PRINTER";
381
382 Endpoint_ClearSETUP();
383 Endpoint_Write_16_BE(sizeof(PrinterIDString));
384 Endpoint_Write_Control_Stream_LE(PrinterIDString, strlen(PrinterIDString));
385 Endpoint_ClearStatusStage();
386 }
387
388 break;
389 case PRNT_REQ_GetPortStatus:
390 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
391 {
392 Endpoint_ClearSETUP();
393 Endpoint_Write_8(PRNT_PORTSTATUS_NOTERROR | PRNT_PORTSTATUS_SELECT);
394 Endpoint_ClearStatusStage();
395 }
396
397 break;
398 case PRNT_REQ_SoftReset:
399 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
400 {
401 Endpoint_ClearSETUP();
402 Endpoint_ClearStatusStage();
403 }
404
405 break;
406 }
407 }