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