3 Copyright (C) Dean Camera, 2021.
5 dean [at] fourwalledcubicle [dot] com
10 Copyright 2021 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
33 * Main source file for the DFU class bootloader. This file contains the complete bootloader logic.
36 #define INCLUDE_FROM_BOOTLOADER_C
37 #include "BootloaderDFU.h"
39 /** Flag to indicate if the bootloader is currently running in secure mode, disallowing memory operations
40 * other than erase. This is initially set to the value set by SECURE_MODE, and cleared by the bootloader
41 * once a memory erase has completed in a bootloader session.
43 static bool IsSecure
= SECURE_MODE
;
45 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
46 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
47 * jumped to via an indirect jump to location 0x0000 (or other location specified by the host).
48 * Use volatile to prevent compiler to do optimization, because we change this variable from interrupt context.
50 static volatile bool RunBootloader
= true;
52 /** Flag to indicate if the bootloader is waiting to exit. When the host requests the bootloader to exit and
53 * jump to the application address it specifies, it sends two sequential commands which must be properly
54 * acknowledged. Upon reception of the first the RunBootloader flag is cleared and the WaitForExit flag is set,
55 * causing the bootloader to wait for the final exit command before shutting down.
57 static bool WaitForExit
= false;
59 /** Minimum time in seconds stay forced into bootloader mode before application will be started. This especially
60 * helpful if the application does not support any update or reflashing or jumping back into bootloader. It prevents
61 * to brick the device if now ISP programmer is available.
64 #define BL_TIME 5 /* seconds */
67 /** Minimum time ticks stay in bootloader before application is started or negative value to prevent leaving
68 * bootloader. Timer 1 is a 16 bit timer, which overflows after 65536 cycles if it is load with zero. The
69 * timer 1 prescaler is programmed to divide by 64 and the prescaler engine uses a clock_div_1 divisor, means
70 * no divisor of the CPU clock frequency F_CPU.
72 static int8_t ForceBootloaderTime
= ((BL_TIME
) > 0) ?
(F_CPU
/ 64 * (BL_TIME
) / 65536 + 1) : -1;
74 /** Current DFU state machine state, one of the values in the DFU_State_t enum. */
75 static uint8_t DFU_State
= dfuIDLE
;
77 /** Status code of the last executed DFU command. This is set to one of the values in the DFU_Status_t enum after
78 * each operation, and returned to the host when a Get Status DFU request is issued.
80 static uint8_t DFU_Status
= OK
;
82 /** Data containing the DFU command sent from the host. */
83 static DFU_Command_t SentCommand
;
85 /** Response to the last issued Read Data DFU command. Unlike other DFU commands, the read command
86 * requires a single byte response from the bootloader containing the read data when the next DFU_UPLOAD command
87 * is issued by the host.
89 static uint8_t ResponseByte
;
91 /** Pointer to the start of the user application. By default this is 0x0000 (the reset vector), however the host
92 * may specify an alternate address when issuing the application soft-start command.
94 static AppPtr_t AppStartPtr
= (AppPtr_t
)0x0000;
96 /** 64-bit flash page number. This is concatenated with the current 16-bit address on USB AVRs containing more than
97 * 64KB of flash memory.
99 static uint8_t Flash64KBPage
= 0;
101 /** Memory start address, indicating the current address in the memory being addressed (either FLASH or EEPROM
102 * depending on the issued command from the host).
104 static uint16_t StartAddr
= 0x0000;
106 /** Memory end address, indicating the end address to read from/write to in the memory being addressed (either FLASH
107 * of EEPROM depending on the issued command from the host).
109 static uint16_t EndAddr
= 0x0000;
111 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
112 * 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
113 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
114 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
116 uint16_t MagicBootKey ATTR_NO_INIT
;
119 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
120 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
121 * this will force the user application to start via a software jump.
123 void Application_Jump_Check(void)
125 bool JumpToApplication
= false;
127 #if (BOARD == BOARD_LEONARDO)
128 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
132 /* If IO13 is not jumpered to ground, start the user application instead */
133 JumpToApplication
= ((PINC
& (1 << 7)) != 0);
135 /* Disable pull-up after the check has completed */
137 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
138 /* Disable JTAG debugging */
141 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
145 /* If the TCK pin is not jumpered to ground, start the user application instead */
146 JumpToApplication
= ((PINF
& (1 << 4)) != 0);
148 /* Re-enable JTAG debugging */
150 #elif ((BOARD == BOARD_PROMICRO) || (BOARD == BOARD_MICRO))
151 /* Pro-Micro and Arduino Micro board use power-on reset, but no external reset. Both boards have
152 * the hardware bootloader pin HWBE enabled. Unfortunately only the external reset allows together
153 * with an enabled HWBE that the CPU start at the bootloader address independent of the FUSE_BOOTRST.
154 * That means the power-on reset will start just controlled by the FUSE_BOOTRST the bootloader or
155 * direct in the application and cannot be overridden by HWBE signal. Therfore FUSE_BOOTRST shall
156 * be enabled, otherwise the bootloader will not be reached for these boards.
157 * The bootloader checks FUSE_HWBE as *unprogammed* instead of FUSE_BOOTRST as programmed on other
158 * board variants to decide fast application start, without waiting the dedicted bootloader timeout
159 * in case of a USB, watchdog, brown-out or JTAG reset. If the watchdog reset was initiated from
160 * the bootloader marked with the MAGIC_BOOT_KEY this reset flag is reset. All other reset flags
161 * are left untouched to allow the application code checking the reset signals, especially in case
162 * of application fast start.
163 * The bootloader is entered always for external reset and power-on reset. But the bootloader is
164 * anyway exited after that dedicted timeout, if a reset-vector to the application is programmed.
165 * Once a DFU program interacts this the bootloader during this dedicted timeout, the timer stops
166 * and the application needs to be started by DFU bootloader command manually or using a reset.
169 /* Check if the device's forced Bootloader via Hardware Bootenable is unprogrammed */
170 if (BootloaderAPI_ReadFuse(GET_EXTENDED_FUSE_BITS
) & ~FUSE_HWBE
)
172 /* If the reset source was not an external or power-on reset jump to the application */
173 if (!(MCUSR
& ((1 << EXTRF
) || (1 << PORF
))))
174 JumpToApplication
= true;
176 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
177 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
178 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
180 JumpToApplication
= true;
182 /* Clear reset source */
183 MCUSR
&= ~(1 << WDRF
);
186 /* Check if the device's BOOTRST fuse is set */
187 if (!(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS
) & ~FUSE_BOOTRST
))
189 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
190 if (!(MCUSR
& (1 << EXTRF
)) || (MagicBootKey
== MAGIC_BOOT_KEY
))
191 JumpToApplication
= true;
193 /* Clear reset source */
194 MCUSR
&= ~(1 << EXTRF
);
198 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
199 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
200 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
201 JumpToApplication
= true;
203 /* Clear reset source */
204 MCUSR
&= ~(1 << WDRF
);
208 /* Clear the boot key in any case */
211 /* Don't run the user application if the reset vector is blank (no app loaded) */
212 bool ApplicationValid
= (pgm_read_word_near(0) != 0xFFFF);
214 /* If a request has been made to jump to the user application, honor it */
215 if (JumpToApplication
&& ApplicationValid
)
217 /* Turn off the watchdog */
220 // cppcheck-suppress constStatement
221 ((void (*)(void))0x0000)();
225 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
226 * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
227 * the loaded application code.
231 /* Configure hardware required by the bootloader */
234 /* Turn on first LED on the board to indicate that the bootloader has started */
235 LEDs_SetAllLEDs(LEDS_LED1
);
237 /* Enable global interrupts so that the USB stack can function */
238 GlobalInterruptEnable();
240 /* Run the USB management task while the bootloader is supposed to be running */
241 while (RunBootloader
|| WaitForExit
)
244 /* Wait a short time to end all USB transactions and then disconnect */
247 /* Reset configured hardware back to their original states for the user application */
250 /* Start the user application */
254 /** Configures all hardware required for the bootloader. */
255 static void SetupHardware(void)
257 /* Disable watchdog if enabled by bootloader/fuses */
258 MCUSR
&= ~(1 << WDRF
);
261 /* Disable clock division */
262 clock_prescale_set(clock_div_1
);
264 /* Relocate the interrupt vector table to the bootloader section */
266 MCUCR
= (1 << IVSEL
);
268 /* Initialize the USB and other board hardware drivers */
272 /* Bootloader active LED toggle timer initialization */
273 TIMSK1
= (1 << TOIE1
);
274 /* config timer 1 prescaler to F_CPU / clock_div_1 / 64 */
275 TCCR1B
= ((1 << CS11
) | (1 << CS10
));
278 /** Resets all configured hardware required for the bootloader back to their original states. */
279 static void ResetHardware(void)
281 /* Shut down the USB and other board hardware drivers */
285 /* Disable Bootloader active LED toggle timer */
289 /* Relocate the interrupt vector table back to the application section */
294 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
295 ISR(TIMER1_OVF_vect
, ISR_BLOCK
)
297 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
298 /* Count number for forced ticks not below zero */
299 if (ForceBootloaderTime
> 0)
300 ForceBootloaderTime
--;
301 /* check if it is time to leave the bootloader and a valid application exists */
302 if ((ForceBootloaderTime
== 0) && (pgm_read_word_near(0) != 0xFFFF))
303 RunBootloader
= false;
306 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
307 * the device from the USB host before passing along unhandled control requests to the library for processing
310 void EVENT_USB_Device_ControlRequest(void)
312 /* Ignore any requests that aren't directed to the DFU interface */
313 if ((USB_ControlRequest
.bmRequestType
& (CONTROL_REQTYPE_TYPE
| CONTROL_REQTYPE_RECIPIENT
)) !=
314 (REQTYPE_CLASS
| REQREC_INTERFACE
))
319 /* prevent counter to reach zero */
320 ForceBootloaderTime
= -1;
322 /* Activity - toggle indicator LEDs */
323 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
325 /* Get the size of the command and data from the wLength value */
326 SentCommand
.DataSize
= USB_ControlRequest
.wLength
;
328 switch (USB_ControlRequest
.bRequest
)
331 Endpoint_ClearSETUP();
333 /* Check if bootloader is waiting to terminate */
336 /* Bootloader is terminating - process last received command */
337 ProcessBootloaderCommand();
339 /* Indicate that the last command has now been processed - free to exit bootloader */
343 /* If the request has a data stage, load it into the command struct */
344 if (SentCommand
.DataSize
)
346 while (!(Endpoint_IsOUTReceived()))
348 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
352 /* First byte of the data stage is the DNLOAD request's command */
353 SentCommand
.Command
= Endpoint_Read_8();
355 /* One byte of the data stage is the command, so subtract it from the total data bytes */
356 SentCommand
.DataSize
--;
358 /* Load in the rest of the data stage as command parameters */
359 for (uint8_t DataByte
= 0; (DataByte
< sizeof(SentCommand
.Data
)) &&
360 Endpoint_BytesInEndpoint(); DataByte
++)
362 SentCommand
.Data
[DataByte
] = Endpoint_Read_8();
363 SentCommand
.DataSize
--;
366 /* Process the command */
367 ProcessBootloaderCommand();
370 /* Check if currently downloading firmware */
371 if (DFU_State
== dfuDNLOAD_IDLE
)
373 if (!(SentCommand
.DataSize
))
379 /* Throw away the filler bytes before the start of the firmware */
380 DiscardFillerBytes(DFU_FILLER_BYTES_SIZE
);
382 /* Throw away the packet alignment filler bytes before the start of the firmware */
383 DiscardFillerBytes(StartAddr
% FIXED_CONTROL_ENDPOINT_SIZE
);
385 /* Calculate the number of bytes remaining to be written */
386 uint16_t BytesRemaining
= ((EndAddr
- StartAddr
) + 1);
388 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Write flash
390 /* Calculate the number of words to be written from the number of bytes to be written */
391 uint16_t WordsRemaining
= (BytesRemaining
>> 1);
397 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
399 uint32_t CurrFlashPageStartAddress
= CurrFlashAddress
.Long
;
400 uint8_t WordsInFlashPage
= 0;
402 while (WordsRemaining
--)
404 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
405 if (!(Endpoint_BytesInEndpoint()))
409 while (!(Endpoint_IsOUTReceived()))
411 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
416 /* Write the next word into the current flash page */
417 BootloaderAPI_FillWord(CurrFlashAddress
.Long
, Endpoint_Read_16_LE());
419 /* Adjust counters */
420 WordsInFlashPage
+= 1;
421 CurrFlashAddress
.Long
+= 2;
423 /* See if an entire page has been written to the flash page buffer */
424 if ((WordsInFlashPage
== (SPM_PAGESIZE
>> 1)) || !(WordsRemaining
))
426 /* Commit the flash page to memory */
427 BootloaderAPI_WritePage(CurrFlashPageStartAddress
);
429 /* Check if programming incomplete */
432 CurrFlashPageStartAddress
= CurrFlashAddress
.Long
;
433 WordsInFlashPage
= 0;
435 /* Erase next page's temp buffer */
436 BootloaderAPI_ErasePage(CurrFlashAddress
.Long
);
441 /* Once programming complete, start address equals the end address */
446 while (BytesRemaining
--)
448 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
449 if (!(Endpoint_BytesInEndpoint()))
453 while (!(Endpoint_IsOUTReceived()))
455 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
460 /* Read the byte from the USB interface and write to to the EEPROM */
461 eeprom_update_byte((uint8_t*)StartAddr
, Endpoint_Read_8());
463 /* Adjust counters */
468 /* Throw away the currently unused DFU file suffix */
469 DiscardFillerBytes(DFU_FILE_SUFFIX_SIZE
);
475 Endpoint_ClearStatusStage();
479 Endpoint_ClearSETUP();
481 while (!(Endpoint_IsINReady()))
483 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
487 if (DFU_State
!= dfuUPLOAD_IDLE
)
489 if ((DFU_State
== dfuERROR
) && IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Blank Check
491 /* Blank checking is performed in the DFU_DNLOAD request - if we get here we've told the host
492 that the memory isn't blank, and the host is requesting the first non-blank address */
493 Endpoint_Write_16_LE(StartAddr
);
497 /* Idle state upload - send response to last issued command */
498 Endpoint_Write_8(ResponseByte
);
503 /* Determine the number of bytes remaining in the current block */
504 uint16_t BytesRemaining
= ((EndAddr
- StartAddr
) + 1);
506 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Read FLASH
508 /* Calculate the number of words to be written from the number of bytes to be written */
509 uint16_t WordsRemaining
= (BytesRemaining
>> 1);
515 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
517 while (WordsRemaining
--)
519 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
520 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE
)
524 while (!(Endpoint_IsINReady()))
526 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
531 /* Read the flash word and send it via USB to the host */
532 #if (FLASHEND > 0xFFFF)
533 Endpoint_Write_16_LE(pgm_read_word_far(CurrFlashAddress
.Long
));
535 Endpoint_Write_16_LE(pgm_read_word(CurrFlashAddress
.Long
));
538 /* Adjust counters */
539 CurrFlashAddress
.Long
+= 2;
542 /* Once reading is complete, start address equals the end address */
545 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x02)) // Read EEPROM
547 while (BytesRemaining
--)
549 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
550 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE
)
554 while (!(Endpoint_IsINReady()))
556 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
561 /* Read the EEPROM byte and send it via USB to the host */
562 Endpoint_Write_8(eeprom_read_byte((uint8_t*)StartAddr
));
564 /* Adjust counters */
569 /* Return to idle state */
575 Endpoint_ClearStatusStage();
577 case DFU_REQ_GETSTATUS
:
578 Endpoint_ClearSETUP();
580 while (!(Endpoint_IsINReady()))
582 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
586 /* Write 8-bit status value */
587 Endpoint_Write_8(DFU_Status
);
589 /* Write 24-bit poll timeout value */
591 Endpoint_Write_16_LE(0);
593 /* Write 8-bit state value */
594 Endpoint_Write_8(DFU_State
);
596 /* Write 8-bit state string ID number */
601 Endpoint_ClearStatusStage();
603 case DFU_REQ_CLRSTATUS
:
604 Endpoint_ClearSETUP();
606 /* Reset the status value variable to the default OK status */
609 Endpoint_ClearStatusStage();
611 case DFU_REQ_GETSTATE
:
612 Endpoint_ClearSETUP();
614 while (!(Endpoint_IsINReady()))
616 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
620 /* Write the current device state to the endpoint */
621 Endpoint_Write_8(DFU_State
);
625 Endpoint_ClearStatusStage();
628 Endpoint_ClearSETUP();
630 /* Reset the current state variable to the default idle state */
633 Endpoint_ClearStatusStage();
638 /** Routine to discard the specified number of bytes from the control endpoint stream. This is used to
639 * discard unused bytes in the stream from the host, including the memory program block suffix.
641 * \param[in] NumberOfBytes Number of bytes to discard from the host from the control endpoint
643 static void DiscardFillerBytes(uint8_t NumberOfBytes
)
645 while (NumberOfBytes
--)
647 if (!(Endpoint_BytesInEndpoint()))
651 /* Wait until next data packet received */
652 while (!(Endpoint_IsOUTReceived()))
654 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
660 Endpoint_Discard_8();
665 /** Routine to process an issued command from the host, via a DFU_DNLOAD request wrapper. This routine ensures
666 * that the command is allowed based on the current secure mode flag value, and passes the command off to the
667 * appropriate handler function.
669 static void ProcessBootloaderCommand(void)
671 /* Check if device is in secure mode */
674 /* Don't process command unless it is a READ or chip erase command */
675 if (!(((SentCommand
.Command
== COMMAND_WRITE
) &&
676 IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x00, 0xFF)) ||
677 (SentCommand
.Command
== COMMAND_READ
)))
679 /* Set the state and status variables to indicate the error */
680 DFU_State
= dfuERROR
;
681 DFU_Status
= errWRITE
;
684 Endpoint_StallTransaction();
686 /* Don't process the command */
691 /* Dispatch the required command processing routine based on the command type */
692 switch (SentCommand
.Command
)
694 case COMMAND_PROG_START
:
695 ProcessMemProgCommand();
697 case COMMAND_DISP_DATA
:
698 ProcessMemReadCommand();
701 ProcessWriteCommand();
704 ProcessReadCommand();
706 case COMMAND_CHANGE_BASE_ADDR
:
707 if (IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x03, 0x00)) // Set 64KB flash page command
708 Flash64KBPage
= SentCommand
.Data
[2];
714 /** Routine to concatenate the given pair of 16-bit memory start and end addresses from the host, and store them
715 * in the StartAddr and EndAddr global variables.
717 static void LoadStartEndAddresses(void)
723 } Address
[2] = {{.Bytes
= {SentCommand
.Data
[2], SentCommand
.Data
[1]}},
724 {.Bytes
= {SentCommand
.Data
[4], SentCommand
.Data
[3]}}};
726 /* Load in the start and ending read addresses from the sent data packet */
727 StartAddr
= Address
[0].Word
;
728 EndAddr
= Address
[1].Word
;
731 /** Handler for a Memory Program command issued by the host. This routine handles the preparations needed
732 * to write subsequent data from the host into the specified memory.
734 static void ProcessMemProgCommand(void)
736 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00) || // Write FLASH command
737 IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Write EEPROM command
739 /* Load in the start and ending read addresses */
740 LoadStartEndAddresses();
742 /* If FLASH is being written to, we need to pre-erase the first page to write to */
743 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00))
749 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
751 /* Erase the current page's temp buffer */
752 BootloaderAPI_ErasePage(CurrFlashAddress
.Long
);
755 /* Set the state so that the next DNLOAD requests reads in the firmware */
756 DFU_State
= dfuDNLOAD_IDLE
;
760 /** Handler for a Memory Read command issued by the host. This routine handles the preparations needed
761 * to read subsequent data from the specified memory out to the host, as well as implementing the memory
762 * blank check command.
764 static void ProcessMemReadCommand(void)
766 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00) || // Read FLASH command
767 IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x02)) // Read EEPROM command
769 /* Load in the start and ending read addresses */
770 LoadStartEndAddresses();
772 /* Set the state so that the next UPLOAD requests read out the firmware */
773 DFU_State
= dfuUPLOAD_IDLE
;
775 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Blank check FLASH command
777 uint32_t CurrFlashAddress
= 0;
779 while (CurrFlashAddress
< (uint32_t)BOOT_START_ADDR
)
781 /* Check if the current byte is not blank */
782 #if (FLASHEND > 0xFFFF)
783 if (pgm_read_byte_far(CurrFlashAddress
) != 0xFF)
785 if (pgm_read_byte(CurrFlashAddress
) != 0xFF)
788 /* Save the location of the first non-blank byte for response back to the host */
789 Flash64KBPage
= (CurrFlashAddress
>> 16);
790 StartAddr
= CurrFlashAddress
;
792 /* Set state and status variables to the appropriate error values */
793 DFU_State
= dfuERROR
;
794 DFU_Status
= errCHECK_ERASED
;
804 /** Handler for a Data Write command issued by the host. This routine handles non-programming commands such as
805 * bootloader exit (both via software jumps and hardware watchdog resets) and flash memory erasure.
807 static void ProcessWriteCommand(void)
809 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x03)) // Start application
811 /* Indicate that the bootloader is terminating */
814 /* Check if data supplied for the Start Program command - no data executes the program */
815 if (SentCommand
.DataSize
)
817 if (SentCommand
.Data
[1] == 0x01) // Start via jump
823 } Address
= {.Bytes
= {SentCommand
.Data
[4], SentCommand
.Data
[3]}};
825 /* Load in the jump address into the application start address pointer */
826 AppStartPtr
= Address
.FuncPtr
;
831 if (SentCommand
.Data
[1] == 0x00) // Start via watchdog
833 /* Unlock the forced application start mode of the bootloader if it is restarted */
834 MagicBootKey
= MAGIC_BOOT_KEY
;
836 /* Start the watchdog to reset the AVR once the communications are finalized */
837 wdt_enable(WDTO_250MS
);
839 else // Start via jump
841 /* Set the flag to terminate the bootloader at next opportunity if a valid application has been loaded */
842 if (pgm_read_word_near(0) != 0xFFFF)
843 RunBootloader
= false;
847 else if (IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x00, 0xFF)) // Erase flash
849 /* Clear the application section of flash */
850 for (uint32_t CurrFlashAddress
= 0; CurrFlashAddress
< (uint32_t)BOOT_START_ADDR
; CurrFlashAddress
+= SPM_PAGESIZE
)
851 BootloaderAPI_ErasePage(CurrFlashAddress
);
853 /* Memory has been erased, reset the security bit so that programming/reading is allowed */
858 /** Handler for a Data Read command issued by the host. This routine handles bootloader information retrieval
859 * commands such as device signature and bootloader version retrieval.
861 static void ProcessReadCommand(void)
863 const uint8_t BootloaderInfo
[3] = {BOOTLOADER_VERSION
, BOOTLOADER_ID_BYTE1
, BOOTLOADER_ID_BYTE2
};
864 const uint8_t SignatureInfo
[4] = {0x58, AVR_SIGNATURE_1
, AVR_SIGNATURE_2
, AVR_SIGNATURE_3
};
866 uint8_t DataIndexToRead
= SentCommand
.Data
[1];
867 bool ReadAddressInvalid
= false;
869 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Read bootloader info
871 if (DataIndexToRead
< 3)
872 ResponseByte
= BootloaderInfo
[DataIndexToRead
];
874 ReadAddressInvalid
= true;
876 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Read signature byte
878 switch (DataIndexToRead
)
881 ResponseByte
= SignatureInfo
[0];
884 ResponseByte
= SignatureInfo
[1];
887 ResponseByte
= SignatureInfo
[2];
890 ResponseByte
= SignatureInfo
[3];
893 ReadAddressInvalid
= true;
898 if (ReadAddressInvalid
)
900 /* Set the state and status variables to indicate the error */
901 DFU_State
= dfuERROR
;
902 DFU_Status
= errADDRESS
;