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).
49 static bool RunBootloader
= true;
51 /** Flag to indicate if the bootloader is waiting to exit. When the host requests the bootloader to exit and
52 * jump to the application address it specifies, it sends two sequential commands which must be properly
53 * acknowledged. Upon reception of the first the RunBootloader flag is cleared and the WaitForExit flag is set,
54 * causing the bootloader to wait for the final exit command before shutting down.
56 static bool WaitForExit
= false;
58 /** Current DFU state machine state, one of the values in the DFU_State_t enum. */
59 static uint8_t DFU_State
= dfuIDLE
;
61 /** Status code of the last executed DFU command. This is set to one of the values in the DFU_Status_t enum after
62 * each operation, and returned to the host when a Get Status DFU request is issued.
64 static uint8_t DFU_Status
= OK
;
66 /** Data containing the DFU command sent from the host. */
67 static DFU_Command_t SentCommand
;
69 /** Response to the last issued Read Data DFU command. Unlike other DFU commands, the read command
70 * requires a single byte response from the bootloader containing the read data when the next DFU_UPLOAD command
71 * is issued by the host.
73 static uint8_t ResponseByte
;
75 /** Pointer to the start of the user application. By default this is 0x0000 (the reset vector), however the host
76 * may specify an alternate address when issuing the application soft-start command.
78 static AppPtr_t AppStartPtr
= (AppPtr_t
)0x0000;
80 /** 64-bit flash page number. This is concatenated with the current 16-bit address on USB AVRs containing more than
81 * 64KB of flash memory.
83 static uint8_t Flash64KBPage
= 0;
85 /** Memory start address, indicating the current address in the memory being addressed (either FLASH or EEPROM
86 * depending on the issued command from the host).
88 static uint16_t StartAddr
= 0x0000;
90 /** Memory end address, indicating the end address to read from/write to in the memory being addressed (either FLASH
91 * of EEPROM depending on the issued command from the host).
93 static uint16_t EndAddr
= 0x0000;
95 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
96 * 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
97 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
98 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
100 uint16_t MagicBootKey ATTR_NO_INIT
;
103 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
104 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
105 * this will force the user application to start via a software jump.
107 void Application_Jump_Check(void)
109 bool JumpToApplication
= false;
111 #if (BOARD == BOARD_LEONARDO)
112 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
116 /* If IO13 is not jumpered to ground, start the user application instead */
117 JumpToApplication
= ((PINC
& (1 << 7)) != 0);
119 /* Disable pull-up after the check has completed */
121 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
122 /* Disable JTAG debugging */
125 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
129 /* If the TCK pin is not jumpered to ground, start the user application instead */
130 JumpToApplication
= ((PINF
& (1 << 4)) != 0);
132 /* Re-enable JTAG debugging */
134 #elif ((BOARD == BOARD_PROMICRO) || (BOARD == BOARD_MICRO))
135 /* Pro-Micro and Arduino Micro board use power-on reset, but no external reset. Both boards have
136 * the hardware bootloader pin HWBE enabled. Unfortunately only the external reset allows together
137 * with an enabled HWBE that the CPU start at the bootloader address independent of the FUSE_BOOTRST.
138 * That means the power-on reset will start just controlled by the FUSE_BOOTRST the bootloader or
139 * direct in the application and cannot be overridden by HWBE signal. Therfore FUSE_BOOTRST shall
140 * be enabled, otherwise the bootloader will not be reached for these boards.
141 * The bootloader checks FUSE_HWBE as *unprogammed* instead of FUSE_BOOTRST as programmed on other
142 * board variants to decide fast application start, without waiting the dedicted bootloader timeout
143 * in case of a USB, watchdog, brown-out or JTAG reset. If the watchdog reset was initiated from
144 * the bootloader marked with the MAGIC_BOOT_KEY this reset flag is reset. All other reset flags
145 * are left untouched to allow the application code checking the reset signals, especially in case
146 * of application fast start.
147 * The bootloader is entered always for external reset and power-on reset. But the bootloader is
148 * anyway exited after that dedicted timeout, if a reset-vector to the application is programmed.
149 * Once a DFU program interacts this the bootloader during this dedicted timeout, the timer stops
150 * and the application needs to be started by DFU bootloader command manually or using a reset.
153 /* Check if the device's forced Bootloader via Hardware Bootenable is unprogrammed */
154 if (BootloaderAPI_ReadFuse(GET_EXTENDED_FUSE_BITS
) & ~FUSE_HWBE
)
156 /* If the reset source was not an external or power-on reset jump to the application */
157 if (!(MCUSR
& ((1 << EXTRF
) || (1 << PORF
))))
158 JumpToApplication
= true;
160 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
161 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
162 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
164 JumpToApplication
= true;
166 /* Clear reset source */
167 MCUSR
&= ~(1 << WDRF
);
170 /* Check if the device's BOOTRST fuse is set */
171 if (!(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS
) & ~FUSE_BOOTRST
))
173 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
174 if (!(MCUSR
& (1 << EXTRF
)) || (MagicBootKey
== MAGIC_BOOT_KEY
))
175 JumpToApplication
= true;
177 /* Clear reset source */
178 MCUSR
&= ~(1 << EXTRF
);
182 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
183 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
184 if ((MCUSR
& (1 << WDRF
)) && (MagicBootKey
== MAGIC_BOOT_KEY
))
185 JumpToApplication
= true;
187 /* Clear reset source */
188 MCUSR
&= ~(1 << WDRF
);
192 /* Clear the boot key in any case */
195 /* Don't run the user application if the reset vector is blank (no app loaded) */
196 bool ApplicationValid
= (pgm_read_word_near(0) != 0xFFFF);
198 /* If a request has been made to jump to the user application, honor it */
199 if (JumpToApplication
&& ApplicationValid
)
201 /* Turn off the watchdog */
204 // cppcheck-suppress constStatement
205 ((void (*)(void))0x0000)();
210 static volatile bool stayinbootloader
;
212 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
213 * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
214 * the loaded application code.
218 /* Configure hardware required by the bootloader */
221 /* Turn on first LED on the board to indicate that the bootloader has started */
222 LEDs_SetAllLEDs(LEDS_LED1
);
224 /* Enable global interrupts so that the USB stack can function */
225 GlobalInterruptEnable();
227 /* Run the USB management task while the bootloader is supposed to be running */
228 /*if bit_is_clear(PINB,PB5) // PB5 is Digital 9 on Arduino Pro Micro
230 loop_until_bit_is_set(PINB,PB5);
232 while ((RunBootloader || WaitForExit) && bit_is_set(PINB,PB5))
235 loop_until_bit_is_clear(PINB,PB5);
238 stayinbootloader
= false;
241 while (RunBootloader
|| WaitForExit
)
245 if (!stayinbootloader
)
259 /* Wait a short time to end all USB transactions and then disconnect */
262 /* Reset configured hardware back to their original states for the user application */
265 /* Start the user application */
269 /** Configures all hardware required for the bootloader. */
270 static void SetupHardware(void)
272 /* Disable watchdog if enabled by bootloader/fuses */
273 MCUSR
&= ~(1 << WDRF
);
276 /* Disable clock division */
277 clock_prescale_set(clock_div_1
);
279 /* Relocate the interrupt vector table to the bootloader section */
281 MCUCR
= (1 << IVSEL
);
283 /* Initialize the USB and other board hardware drivers */
287 /* Bootloader active LED toggle timer initialization */
288 TIMSK1
= (1 << TOIE1
);
289 TCCR1B
= ((1 << CS11
) | (1 << CS10
));
292 /** Resets all configured hardware required for the bootloader back to their original states. */
293 static void ResetHardware(void)
295 /* Shut down the USB and other board hardware drivers */
299 /* Disable Bootloader active LED toggle timer */
303 /* Relocate the interrupt vector table back to the application section */
308 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
309 ISR(TIMER1_OVF_vect
, ISR_BLOCK
)
311 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
314 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
315 * the device from the USB host before passing along unhandled control requests to the library for processing
318 void EVENT_USB_Device_ControlRequest(void)
320 /* Ignore any requests that aren't directed to the DFU interface */
321 if ((USB_ControlRequest
.bmRequestType
& (CONTROL_REQTYPE_TYPE
| CONTROL_REQTYPE_RECIPIENT
)) !=
322 (REQTYPE_CLASS
| REQREC_INTERFACE
))
327 stayinbootloader
= true;
329 /* Activity - toggle indicator LEDs */
330 LEDs_ToggleLEDs(LEDS_LED1
| LEDS_LED2
);
332 /* Get the size of the command and data from the wLength value */
333 SentCommand
.DataSize
= USB_ControlRequest
.wLength
;
335 switch (USB_ControlRequest
.bRequest
)
338 Endpoint_ClearSETUP();
340 /* Check if bootloader is waiting to terminate */
343 /* Bootloader is terminating - process last received command */
344 ProcessBootloaderCommand();
346 /* Indicate that the last command has now been processed - free to exit bootloader */
350 /* If the request has a data stage, load it into the command struct */
351 if (SentCommand
.DataSize
)
353 while (!(Endpoint_IsOUTReceived()))
355 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
359 /* First byte of the data stage is the DNLOAD request's command */
360 SentCommand
.Command
= Endpoint_Read_8();
362 /* One byte of the data stage is the command, so subtract it from the total data bytes */
363 SentCommand
.DataSize
--;
365 /* Load in the rest of the data stage as command parameters */
366 for (uint8_t DataByte
= 0; (DataByte
< sizeof(SentCommand
.Data
)) &&
367 Endpoint_BytesInEndpoint(); DataByte
++)
369 SentCommand
.Data
[DataByte
] = Endpoint_Read_8();
370 SentCommand
.DataSize
--;
373 /* Process the command */
374 ProcessBootloaderCommand();
377 /* Check if currently downloading firmware */
378 if (DFU_State
== dfuDNLOAD_IDLE
)
380 if (!(SentCommand
.DataSize
))
386 /* Throw away the filler bytes before the start of the firmware */
387 DiscardFillerBytes(DFU_FILLER_BYTES_SIZE
);
389 /* Throw away the packet alignment filler bytes before the start of the firmware */
390 DiscardFillerBytes(StartAddr
% FIXED_CONTROL_ENDPOINT_SIZE
);
392 /* Calculate the number of bytes remaining to be written */
393 uint16_t BytesRemaining
= ((EndAddr
- StartAddr
) + 1);
395 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Write flash
397 /* Calculate the number of words to be written from the number of bytes to be written */
398 uint16_t WordsRemaining
= (BytesRemaining
>> 1);
404 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
406 uint32_t CurrFlashPageStartAddress
= CurrFlashAddress
.Long
;
407 uint8_t WordsInFlashPage
= 0;
409 while (WordsRemaining
--)
411 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
412 if (!(Endpoint_BytesInEndpoint()))
416 while (!(Endpoint_IsOUTReceived()))
418 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
423 /* Write the next word into the current flash page */
424 BootloaderAPI_FillWord(CurrFlashAddress
.Long
, Endpoint_Read_16_LE());
426 /* Adjust counters */
427 WordsInFlashPage
+= 1;
428 CurrFlashAddress
.Long
+= 2;
430 /* See if an entire page has been written to the flash page buffer */
431 if ((WordsInFlashPage
== (SPM_PAGESIZE
>> 1)) || !(WordsRemaining
))
433 /* Commit the flash page to memory */
434 BootloaderAPI_WritePage(CurrFlashPageStartAddress
);
436 /* Check if programming incomplete */
439 CurrFlashPageStartAddress
= CurrFlashAddress
.Long
;
440 WordsInFlashPage
= 0;
442 /* Erase next page's temp buffer */
443 BootloaderAPI_ErasePage(CurrFlashAddress
.Long
);
448 /* Once programming complete, start address equals the end address */
453 while (BytesRemaining
--)
455 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
456 if (!(Endpoint_BytesInEndpoint()))
460 while (!(Endpoint_IsOUTReceived()))
462 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
467 /* Read the byte from the USB interface and write to to the EEPROM */
468 eeprom_update_byte((uint8_t*)StartAddr
, Endpoint_Read_8());
470 /* Adjust counters */
475 /* Throw away the currently unused DFU file suffix */
476 DiscardFillerBytes(DFU_FILE_SUFFIX_SIZE
);
482 Endpoint_ClearStatusStage();
486 Endpoint_ClearSETUP();
488 while (!(Endpoint_IsINReady()))
490 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
494 if (DFU_State
!= dfuUPLOAD_IDLE
)
496 if ((DFU_State
== dfuERROR
) && IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Blank Check
498 /* Blank checking is performed in the DFU_DNLOAD request - if we get here we've told the host
499 that the memory isn't blank, and the host is requesting the first non-blank address */
500 Endpoint_Write_16_LE(StartAddr
);
504 /* Idle state upload - send response to last issued command */
505 Endpoint_Write_8(ResponseByte
);
510 /* Determine the number of bytes remaining in the current block */
511 uint16_t BytesRemaining
= ((EndAddr
- StartAddr
) + 1);
513 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Read FLASH
515 /* Calculate the number of words to be written from the number of bytes to be written */
516 uint16_t WordsRemaining
= (BytesRemaining
>> 1);
522 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
524 while (WordsRemaining
--)
526 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
527 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE
)
531 while (!(Endpoint_IsINReady()))
533 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
538 /* Read the flash word and send it via USB to the host */
539 #if (FLASHEND > 0xFFFF)
540 Endpoint_Write_16_LE(pgm_read_word_far(CurrFlashAddress
.Long
));
542 Endpoint_Write_16_LE(pgm_read_word(CurrFlashAddress
.Long
));
545 /* Adjust counters */
546 CurrFlashAddress
.Long
+= 2;
549 /* Once reading is complete, start address equals the end address */
552 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x02)) // Read EEPROM
554 while (BytesRemaining
--)
556 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
557 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE
)
561 while (!(Endpoint_IsINReady()))
563 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
568 /* Read the EEPROM byte and send it via USB to the host */
569 Endpoint_Write_8(eeprom_read_byte((uint8_t*)StartAddr
));
571 /* Adjust counters */
576 /* Return to idle state */
582 Endpoint_ClearStatusStage();
584 case DFU_REQ_GETSTATUS
:
585 Endpoint_ClearSETUP();
587 while (!(Endpoint_IsINReady()))
589 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
593 /* Write 8-bit status value */
594 Endpoint_Write_8(DFU_Status
);
596 /* Write 24-bit poll timeout value */
598 Endpoint_Write_16_LE(0);
600 /* Write 8-bit state value */
601 Endpoint_Write_8(DFU_State
);
603 /* Write 8-bit state string ID number */
608 Endpoint_ClearStatusStage();
610 case DFU_REQ_CLRSTATUS
:
611 Endpoint_ClearSETUP();
613 /* Reset the status value variable to the default OK status */
616 Endpoint_ClearStatusStage();
618 case DFU_REQ_GETSTATE
:
619 Endpoint_ClearSETUP();
621 while (!(Endpoint_IsINReady()))
623 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
627 /* Write the current device state to the endpoint */
628 Endpoint_Write_8(DFU_State
);
632 Endpoint_ClearStatusStage();
635 Endpoint_ClearSETUP();
637 /* Reset the current state variable to the default idle state */
640 Endpoint_ClearStatusStage();
645 /** Routine to discard the specified number of bytes from the control endpoint stream. This is used to
646 * discard unused bytes in the stream from the host, including the memory program block suffix.
648 * \param[in] NumberOfBytes Number of bytes to discard from the host from the control endpoint
650 static void DiscardFillerBytes(uint8_t NumberOfBytes
)
652 while (NumberOfBytes
--)
654 if (!(Endpoint_BytesInEndpoint()))
658 /* Wait until next data packet received */
659 while (!(Endpoint_IsOUTReceived()))
661 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
667 Endpoint_Discard_8();
672 /** Routine to process an issued command from the host, via a DFU_DNLOAD request wrapper. This routine ensures
673 * that the command is allowed based on the current secure mode flag value, and passes the command off to the
674 * appropriate handler function.
676 static void ProcessBootloaderCommand(void)
678 /* Check if device is in secure mode */
681 /* Don't process command unless it is a READ or chip erase command */
682 if (!(((SentCommand
.Command
== COMMAND_WRITE
) &&
683 IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x00, 0xFF)) ||
684 (SentCommand
.Command
== COMMAND_READ
)))
686 /* Set the state and status variables to indicate the error */
687 DFU_State
= dfuERROR
;
688 DFU_Status
= errWRITE
;
691 Endpoint_StallTransaction();
693 /* Don't process the command */
698 /* Dispatch the required command processing routine based on the command type */
699 switch (SentCommand
.Command
)
701 case COMMAND_PROG_START
:
702 ProcessMemProgCommand();
704 case COMMAND_DISP_DATA
:
705 ProcessMemReadCommand();
708 ProcessWriteCommand();
711 ProcessReadCommand();
713 case COMMAND_CHANGE_BASE_ADDR
:
714 if (IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x03, 0x00)) // Set 64KB flash page command
715 Flash64KBPage
= SentCommand
.Data
[2];
721 /** Routine to concatenate the given pair of 16-bit memory start and end addresses from the host, and store them
722 * in the StartAddr and EndAddr global variables.
724 static void LoadStartEndAddresses(void)
730 } Address
[2] = {{.Bytes
= {SentCommand
.Data
[2], SentCommand
.Data
[1]}},
731 {.Bytes
= {SentCommand
.Data
[4], SentCommand
.Data
[3]}}};
733 /* Load in the start and ending read addresses from the sent data packet */
734 StartAddr
= Address
[0].Word
;
735 EndAddr
= Address
[1].Word
;
738 /** Handler for a Memory Program command issued by the host. This routine handles the preparations needed
739 * to write subsequent data from the host into the specified memory.
741 static void ProcessMemProgCommand(void)
743 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00) || // Write FLASH command
744 IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Write EEPROM command
746 /* Load in the start and ending read addresses */
747 LoadStartEndAddresses();
749 /* If FLASH is being written to, we need to pre-erase the first page to write to */
750 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00))
756 } CurrFlashAddress
= {.Words
= {StartAddr
, Flash64KBPage
}};
758 /* Erase the current page's temp buffer */
759 BootloaderAPI_ErasePage(CurrFlashAddress
.Long
);
762 /* Set the state so that the next DNLOAD requests reads in the firmware */
763 DFU_State
= dfuDNLOAD_IDLE
;
767 /** Handler for a Memory Read command issued by the host. This routine handles the preparations needed
768 * to read subsequent data from the specified memory out to the host, as well as implementing the memory
769 * blank check command.
771 static void ProcessMemReadCommand(void)
773 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00) || // Read FLASH command
774 IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x02)) // Read EEPROM command
776 /* Load in the start and ending read addresses */
777 LoadStartEndAddresses();
779 /* Set the state so that the next UPLOAD requests read out the firmware */
780 DFU_State
= dfuUPLOAD_IDLE
;
782 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Blank check FLASH command
784 uint32_t CurrFlashAddress
= 0;
786 while (CurrFlashAddress
< (uint32_t)BOOT_START_ADDR
)
788 /* Check if the current byte is not blank */
789 #if (FLASHEND > 0xFFFF)
790 if (pgm_read_byte_far(CurrFlashAddress
) != 0xFF)
792 if (pgm_read_byte(CurrFlashAddress
) != 0xFF)
795 /* Save the location of the first non-blank byte for response back to the host */
796 Flash64KBPage
= (CurrFlashAddress
>> 16);
797 StartAddr
= CurrFlashAddress
;
799 /* Set state and status variables to the appropriate error values */
800 DFU_State
= dfuERROR
;
801 DFU_Status
= errCHECK_ERASED
;
811 /** Handler for a Data Write command issued by the host. This routine handles non-programming commands such as
812 * bootloader exit (both via software jumps and hardware watchdog resets) and flash memory erasure.
814 static void ProcessWriteCommand(void)
816 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x03)) // Start application
818 /* Indicate that the bootloader is terminating */
821 /* Check if data supplied for the Start Program command - no data executes the program */
822 if (SentCommand
.DataSize
)
824 if (SentCommand
.Data
[1] == 0x01) // Start via jump
830 } Address
= {.Bytes
= {SentCommand
.Data
[4], SentCommand
.Data
[3]}};
832 /* Load in the jump address into the application start address pointer */
833 AppStartPtr
= Address
.FuncPtr
;
838 if (SentCommand
.Data
[1] == 0x00) // Start via watchdog
840 /* Unlock the forced application start mode of the bootloader if it is restarted */
841 MagicBootKey
= MAGIC_BOOT_KEY
;
843 /* Start the watchdog to reset the AVR once the communications are finalized */
844 wdt_enable(WDTO_250MS
);
846 else // Start via jump
848 /* Set the flag to terminate the bootloader at next opportunity if a valid application has been loaded */
849 if (pgm_read_word_near(0) == 0xFFFF)
850 RunBootloader
= false;
854 else if (IS_TWOBYTE_COMMAND(SentCommand
.Data
, 0x00, 0xFF)) // Erase flash
856 /* Clear the application section of flash */
857 for (uint32_t CurrFlashAddress
= 0; CurrFlashAddress
< (uint32_t)BOOT_START_ADDR
; CurrFlashAddress
+= SPM_PAGESIZE
)
858 BootloaderAPI_ErasePage(CurrFlashAddress
);
860 /* Memory has been erased, reset the security bit so that programming/reading is allowed */
865 /** Handler for a Data Read command issued by the host. This routine handles bootloader information retrieval
866 * commands such as device signature and bootloader version retrieval.
868 static void ProcessReadCommand(void)
870 const uint8_t BootloaderInfo
[3] = {BOOTLOADER_VERSION
, BOOTLOADER_ID_BYTE1
, BOOTLOADER_ID_BYTE2
};
871 const uint8_t SignatureInfo
[4] = {0x58, AVR_SIGNATURE_1
, AVR_SIGNATURE_2
, AVR_SIGNATURE_3
};
873 uint8_t DataIndexToRead
= SentCommand
.Data
[1];
874 bool ReadAddressInvalid
= false;
876 if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x00)) // Read bootloader info
878 if (DataIndexToRead
< 3)
879 ResponseByte
= BootloaderInfo
[DataIndexToRead
];
881 ReadAddressInvalid
= true;
883 else if (IS_ONEBYTE_COMMAND(SentCommand
.Data
, 0x01)) // Read signature byte
885 switch (DataIndexToRead
)
888 ResponseByte
= SignatureInfo
[0];
891 ResponseByte
= SignatureInfo
[1];
894 ResponseByte
= SignatureInfo
[2];
897 ResponseByte
= SignatureInfo
[3];
900 ReadAddressInvalid
= true;
905 if (ReadAddressInvalid
)
907 /* Set the state and status variables to indicate the error */
908 DFU_State
= dfuERROR
;
909 DFU_Status
= errADDRESS
;