forked from rhulme/pico-flashloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.c
308 lines (256 loc) · 8.81 KB
/
app.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//****************************************************************************
// Copyright 2021 Richard Hulme
//
// SPDX-License-Identifier: BSD-3-Clause
//
// Demo application to test the flashloader.
// Listens on the default UART for an Intel hex file containing a new
// application. This is stored in flash and the system is rebooted into the
// flashloader which overwrites the existing application with the new image
// and boots into it.
// Because the flashloader is not overwriting itself, it is power-fail safe.
//
// This code is for demonstration purposes. There is not very much
// error-checking and attempts have been made to keep the final code size
// small (e.g. not using printf)
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/sync.h"
#include "hardware/flash.h"
#include "hardware/watchdog.h"
#include "hardware/structs/watchdog.h"
#include "flashloader.h"
#ifndef PICO_DEFAULT_LED_PIN
#error This example needs a board with an LED
#endif
#ifndef LED_DELAY_MS
#error LED_DELAY_MS must be defined!
#endif
#define STRINGIFY(x) #x
#define TO_TEXT(x) STRINGIFY(x)
// Intel HEX record
typedef struct
{
uint8_t count;
uint16_t addr;
uint8_t type;
uint8_t data[256];
}tRecord;
// Intel HEX record types
static const uint8_t TYPE_DATA = 0x00;
static const uint8_t TYPE_EOF = 0x01;
static const uint8_t TYPE_EXTSEG = 0x02;
static const uint8_t TYPE_STARTSEG = 0x03;
static const uint8_t TYPE_EXTLIN = 0x04;
static const uint8_t TYPE_STARTLIN = 0x05;
// Offset within flash of the new app image to be flashed by the flashloader
static const uint32_t FLASH_IMAGE_OFFSET = 128 * 1024;
// Buffer to hold the incoming data before flashing
static union
{
tFlashHeader header;
uint8_t buffer[sizeof(tFlashHeader) + 65536];
} flashbuf;
//****************************************************************************
bool repeating_timer_callback(struct repeating_timer *t)
{
(void)t;
gpio_xor_mask(1 << PICO_DEFAULT_LED_PIN);
return true;
}
//****************************************************************************
// Simple CRC32 (no reflection, no final XOR) implementation.
// This can be done with a lookup table or using the DMA sniffer too.
uint32_t crc32(const uint8_t *data, uint32_t len, uint32_t crc)
{
while(len--)
{
crc ^= (*data++ << 24);
for(int bit = 0; bit < 8; bit++)
{
if(crc & (1L << 31))
crc = (crc << 1) ^ 0x04C11DB7;
else
crc = (crc << 1);
}
}
return crc;
}
//****************************************************************************
// Converts an ASCII hex character into its binary representation.
// The existing value is shifted across one nibble before the new value is
// stored in the lower nibble.
// Returns non-zero if the character could be converted
int hex2nibble(char c, uint8_t* value)
{
int success = 0;
if(c >= '0' && c <= '9')
{
*value <<= 4;
*value |= (uint8_t)(c - '0');
success = 1;
}
else
{
c |= 32;
if(c >= 'a' && c <= 'z')
{
*value <<= 4;
*value |= (uint8_t)(c - 'a') + 10;
success = 1;
}
}
return success;
}
//****************************************************************************
// Converts two ASCII hex characters to an 8-bit binary value.
// Returns non-zero if valid hex characters were found
int parseHex(const char* str, uint8_t* value)
{
int success;
*value = 0;
success = hex2nibble(*str++, value) && hex2nibble(*str, value);
return success;
}
//****************************************************************************
// Converts an Intel hex record in text form to a binary representation.
// Returns non-zero if the text could be parsed successfully
int processRecord(const char* line, tRecord* record)
{
int success = 0;
int offset = 0;
uint8_t value;
uint8_t data[256 + 5]; // Max payload 256 bytes plus 5 for fields
uint8_t checksum = 0;
while(*line && (*line != ':'))
line++;
if(*line++ == ':')
{
while(parseHex(line, &value) && (offset < sizeof(data)))
{
data[offset++] = value;
checksum += value;
line += 2;
}
}
// Checksum is two's-complement of the sum of the previous bytes so
// final checksum should be zero if everything was OK.
if((offset > 0) && (checksum == 0))
{
record->count = data[0];
record->addr = data[2] | (data[1] << 8);
record->type = data[3];
memcpy(record->data, &data[4], data[0]);
success = 1;
}
return success;
}
//****************************************************************************
// Store the given image in flash then reboot into the flashloader to replace
// the current application with the new image.
void flashImage(tFlashHeader* header, uint32_t length)
{
// Calculate length of header plus length of data
uint32_t totalLength = sizeof(tFlashHeader) + length;
// Round erase length up to next 4096 byte boundary
uint32_t eraseLength = (totalLength + 4095) & 0xfffff000;
uint32_t status;
header->magic1 = FLASH_MAGIC1;
header->magic2 = FLASH_MAGIC2;
header->length = length;
header->crc32 = crc32(header->data, length, 0xffffffff);
uart_puts(PICO_DEFAULT_UART_INSTANCE, "Storing new image in flash and then rebooting\r\n");
status = save_and_disable_interrupts();
flash_range_erase(FLASH_IMAGE_OFFSET, eraseLength);
flash_range_program(FLASH_IMAGE_OFFSET, (uint8_t*)header, totalLength);
restore_interrupts(status);
uart_puts(PICO_DEFAULT_UART_INSTANCE, "Rebooting into flashloader in 1 second\r\n");
// Set up watchdog scratch registers so that the flashloader knows
// what to do after the reset
watchdog_hw->scratch[0] = FLASH_MAGIC1;
watchdog_hw->scratch[1] = XIP_BASE + FLASH_IMAGE_OFFSET;
watchdog_reboot(0x00000000, 0x00000000, 1000);
// Wait for the reset
while(true)
tight_loop_contents();
}
//****************************************************************************
// Reads a line of text from the standard UART into the given buffer and
// returns when a line-feed or carriage-return is detected.
char* getLine(char* buffer)
{
char c;
char* ptr = buffer;
do
{
c = uart_getc(PICO_DEFAULT_UART_INSTANCE);
if((c != '\n') && (c != '\r'))
*ptr++ = c;
else
*ptr++ = 0;
}while((c != '\n') && (c != '\r'));
return buffer;
}
//****************************************************************************
// Reads an Intel hex file from the standard UART, stores it in flash then
// triggers the flashloader to overwrite the existing application with the
// new image.
void readIntelHex()
{
uint32_t offset = 0;
char line[1024];
uint32_t count = 0;
while (true)
{
tRecord rec;
if(processRecord(getLine(line), &rec))
{
switch(rec.type)
{
case TYPE_DATA:
memcpy(&flashbuf.header.data[offset], rec.data, rec.count);
offset += rec.count;
offset %= 65536;
if((offset % 1024) == 0)
uart_puts(PICO_DEFAULT_UART_INSTANCE, "Received block\r\n");
break;
case TYPE_EOF:
flashImage(&flashbuf.header, offset);
break;
case TYPE_EXTSEG:
case TYPE_STARTSEG:
case TYPE_STARTLIN:
// Ignore these types. They aren't important for this demo
break;
case TYPE_EXTLIN:
// Move to the start of the data buffer
offset = 0;
break;
default:
break;
}
count++;
}
}
}
//****************************************************************************
// Entry point - start flashing the on-board LED and wait for a new
// application image.
int main()
{
gpio_set_function(PICO_DEFAULT_UART_TX_PIN, GPIO_FUNC_UART);
gpio_set_function(PICO_DEFAULT_UART_RX_PIN, GPIO_FUNC_UART);
uart_init(PICO_DEFAULT_UART_INSTANCE, 115200);
gpio_init(PICO_DEFAULT_LED_PIN);
gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);
struct repeating_timer timer;
add_repeating_timer_ms(LED_DELAY_MS, repeating_timer_callback, NULL, &timer);
if(watchdog_hw->scratch[0] == FLASH_APP_UPDATED)
{
uart_puts(PICO_DEFAULT_UART_INSTANCE, "Application just updated!\r\n");
watchdog_hw->scratch[0] = 0;
}
uart_puts(PICO_DEFAULT_UART_INSTANCE, "Flashing LED every " TO_TEXT(LED_DELAY_MS) " milliseconds\r\n");
readIntelHex();
return 0;
}