-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.html
405 lines (374 loc) · 13.3 KB
/
index.html
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<!doctype html>
<html>
<head>
<title>avr109 test</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="main">
<div class="wrapper">
<div class="bot">
<h1>Upload-o-matic</h1>
<p>Choose a program to upload to an arduino</p>
<form id="uploadForm">
<label>Program:
<div class="fileButtonWrapper">
<button id="fileButton" type="button" aria-controls="fileInput">Choose file</button>
<input id="fileInput" tabindex="-1" type="file"/>
<span id="fileName">no file chosen</span>
</div>
</label>
<button type="submit" id="uploadBtn">Upload!</button>
</form>
<form id="resetForm">
<button type="submit" id="resetBtn">Reset!</button>
</form>
</div>
<div class="board">
<img src="images/Micro.jpg"/>
</div>
<div id="pipe"></div>
<div id="progress"></div>
<div id="gear"><img src="images/gear4.svg"/></div>
</div>
</div>
<!-- HELPER FUNCTIONS -->
<script>
//credits: https://stackoverflow.com/questions/38987784/how-to-convert-a-hexadecimal-string-to-uint8array-and-back-in-javascript
const fromHexString = hexString =>
new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
</script>
<!-- Intel HEX parser by https://github.com/bminer/intel-hex.js -->
<script>
//Intel Hex record types
const DATA = 0,
END_OF_FILE = 1,
EXT_SEGMENT_ADDR = 2,
START_SEGMENT_ADDR = 3,
EXT_LINEAR_ADDR = 4,
START_LINEAR_ADDR = 5;
const EMPTY_VALUE = 0xFF;
/* intel_hex.parse(data)
`data` - Intel Hex file (string in ASCII format or Buffer Object)
`bufferSize` - the size of the Buffer containing the data (optional)
returns an Object with the following properties:
- data - data as a Buffer Object, padded with 0xFF
where data is empty.
- startSegmentAddress - the address provided by the last
start segment address record; null, if not given
- startLinearAddress - the address provided by the last
start linear address record; null, if not given
Special thanks to: http://en.wikipedia.org/wiki/Intel_HEX
*/
function parseIntelHex(data) {
//if(data instanceof Buffer)
data = data.toString("ascii");
//Initialization
var buf = new Uint8Array(32768); //max. words in mega32u4
var bufLength = 0, //Length of data in the buffer
highAddress = 0, //upper address
startSegmentAddress = null,
startLinearAddress = null,
lineNum = 0, //Line number in the Intel Hex string
pos = 0; //Current position in the Intel Hex string
const SMALLEST_LINE = 11;
while(pos + SMALLEST_LINE <= data.length)
{
//Parse an entire line
if(data.charAt(pos++) != ":")
throw new Error("Line " + (lineNum+1) +
" does not start with a colon (:).");
else
lineNum++;
//Number of bytes (hex digit pairs) in the data field
var dataLength = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Get 16-bit address (big-endian)
var lowAddress = parseInt(data.substr(pos, 4), 16);
pos += 4;
//Record type
var recordType = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Data field (hex-encoded string)
var dataField = data.substr(pos, dataLength * 2);
if(dataLength) var dataFieldBuf = fromHexString(dataField);
else var dataFieldBuf = new Uint8Array();
pos += dataLength * 2;
//Checksum
var checksum = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Validate checksum
var calcChecksum = (dataLength + (lowAddress >> 8) +
lowAddress + recordType) & 0xFF;
for(var i = 0; i < dataLength; i++)
calcChecksum = (calcChecksum + dataFieldBuf[i]) & 0xFF;
calcChecksum = (0x100 - calcChecksum) & 0xFF;
if(checksum != calcChecksum)
throw new Error("Invalid checksum on line " + lineNum +
": got " + checksum + ", but expected " + calcChecksum);
//Parse the record based on its recordType
switch(recordType)
{
case DATA:
var absoluteAddress = highAddress + lowAddress;
//Expand buf, if necessary
/*if(absoluteAddress + dataLength >= buf.length)
{
var tmp = Buffer.alloc((absoluteAddress + dataLength) * 2);
buf.copy(tmp, 0, 0, bufLength);
buf = tmp;
}*/
//Write over skipped bytes with EMPTY_VALUE
if(absoluteAddress > bufLength)
buf.fill(EMPTY_VALUE, bufLength, absoluteAddress);
//Write the dataFieldBuf to buf
//dataFieldBuf.copy(buf, absoluteAddress);
dataFieldBuf.forEach( function(val,index) {
buf[absoluteAddress+index] = val;
});
bufLength = Math.max(bufLength, absoluteAddress + dataLength);
break;
case END_OF_FILE:
if(dataLength != 0)
throw new Error("Invalid EOF record on line " +
lineNum + ".");
return {
"data": buf.slice(0, bufLength),
"startSegmentAddress": startSegmentAddress,
"startLinearAddress": startLinearAddress
};
break;
case EXT_SEGMENT_ADDR:
if(dataLength != 2 || lowAddress != 0)
throw new Error("Invalid extended segment address record on line " +
lineNum + ".");
highAddress = parseInt(dataField, 16) << 4;
break;
case START_SEGMENT_ADDR:
if(dataLength != 4 || lowAddress != 0)
throw new Error("Invalid start segment address record on line " +
lineNum + ".");
startSegmentAddress = parseInt(dataField, 16);
break;
case EXT_LINEAR_ADDR:
if(dataLength != 2 || lowAddress != 0)
throw new Error("Invalid extended linear address record on line " +
lineNum + ".");
highAddress = parseInt(dataField, 16) << 16;
break;
case START_LINEAR_ADDR:
if(dataLength != 4 || lowAddress != 0)
throw new Error("Invalid start linear address record on line " +
lineNum + ".");
startLinearAddress = parseInt(dataField, 16);
break;
default:
throw new Error("Invalid record type (" + recordType +
") on line " + lineNum);
break;
}
//Advance to the next line
if(data.charAt(pos) == "\r")
pos++;
if(data.charAt(pos) == "\n")
pos++;
}
throw new Error("Unexpected end of input: missing or invalid EOF record.");
};
</script>
<script>
//credits: https://www.geeksforgeeks.org/how-to-delay-a-loop-in-javascript-using-async-await-with-promise/
function waitforme(milisec) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, milisec);
})
}
//credits: https://www.30secondsofcode.org/articles/s/javascript-array-comparison
const equals = (a, b) =>
a.length === b.length &&
a.every((v, i) => v === b[i]);
/****************/
// 1.) reset mega32u4 into bootloader mode (user interaction required)
/****************/
async function handleReset(e) {
if (!("serial" in navigator)) {
// The Web Serial API is not supported.
alert("Please use Chromium based browsers!");
}
e.preventDefault();
gear.classList.add('spinning');
let filters = [
{ usbVendorId: 0x2341, usbProductId: 0x8037 }
//TODO: I think there are more possible PIDs...
];
port = await navigator.serial.requestPort({filters});
//open & close
// Wait for the serial port to open.
await port.open({ baudRate: 1200 });
await waitforme(500);
await port.close();
await waitforme(500);
gear.classList.remove('spinning');
}
/****************/
// 2.) open the new bootloader USB-serial (new USB-PID!); user interaction required
/****************/
async function handleSubmit(e) {
if (!("serial" in navigator)) {
// The Web Serial API is not supported.
alert("Please use Chromium based browsers!");
}
e.preventDefault();
let filecontents;
const file = fileInput.files[0];
const readerF = new FileReader();
readerF.onload = async function(event) {
filecontents = event.target.result;
gear.classList.add('spinning');
//parse intel hex
let flashData = parseIntelHex(filecontents);
//request serial port
let filters = [
{ usbVendorId: 0x2341, usbProductId: 0x0036 }
//TODO: I think there are more possible PIDs...
];
port = await navigator.serial.requestPort({filters});
//open & close
// Wait for the serial port to open.
await port.open({ baudRate: 57600 });
//open writing facilities (with text encoder -> not good!)
/*const textEncoder = new TextEncoderStream();
const writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
const writer = textEncoder.writable.getWriter();*/
//open writing facilities
const writer = port.writable.getWriter();
//open reading stream
const reader = port.readable.getReader();
//trigger update by sending programmer ID command
await writer.write(new Uint8Array([0x53]));
// Listen to data coming from the serial device.
let state = 0;
let pageStart = 0;
let address = 0;
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
writer.releaseLock();
break;
}
// value is a Uint8Array.
console.log(value);
/****************/
// 3.) flashing the .hex file (event driven by the received data from the ATMega32U4).
// most commands are acknowledged with 13d.
/****************/
if(state == 0) {
//1.) "S" => "CATERIN" - get programmer ID
if(equals(value,[67, 65, 84, 69, 82, 73, 78]))
{
console.log("programmer \"CATERIN\" detected, entering programming mode");
await writer.write(new Uint8Array([0x50]));
await waitforme(5);
state = 1;
} else {
console.log("error: unexpected RX value in state 0, waited for \"CATERIN\"");
}
} else if(state == 1) {
//2.) "P" => 13d - enter programming mode
if(equals(value,[13]))
{
console.log("setting address to: " + address);
data = new Uint8Array([0x41,(address >> 8)&0xFF, address & 0xFF]); // 'A' high low
console.log("O: " + data);
await writer.write(data);
await waitforme(5);
state = 2;
} else {
console.log("error: unexpected RX value in state 1, waited for 13");
}
} else if(state == 2) {
//3.) now flash page
if(equals(value,[13]))
{
cmd = new Uint8Array([0x42,0x00,0x80,0x46]); //flash page write command ('B' + 2bytes size + 'F')
//determine if this is the last page (maybe incomplete -> fill with 0xFF)
if(pageStart + 128 > flashData.data.length)
{
data = flashData.data.slice(pageStart); //take the remaining bit
pad = new Uint8Array(128-data.length); //create a new padding array
pad.fill(0xFF);
txx = Uint8Array.from([...cmd, ...data, ...pad]); //concat command, remaining data and padding
console.log("last page");
state = 3;
} else {
data = flashData.data.slice(pageStart,pageStart+128); //take subarray with 128B
txx = Uint8Array.from([...cmd, ...data]); //concate command with page data
state = 1;
}
console.log("adress set, writing one page: " + data);
pageStart += 128;
address += 64;
//write control + flash data
await writer.write(txx);
console.log("O: " + txx);
await waitforme(5);
} else {
console.log("error: state 2");
}
} else if(state == 3) {
//4.) last page sent, finish update
if(value[0] == 13)
{
console.log("Last page write, leaving programming mode");
//finish flashing and exit bootloader
await writer.write(new Uint8Array([0x4C])); //"L" -> leave programming mode
state = 4;
/*state = -1;
gear.classList.remove('spinning');
console.log("finished!");
reader.cancel();*/
} else {
console.log("NACK");
}
} else if(state == 4) {
//5.) left programming mode, exiting bootloader
if(value[0] == 13)
{
console.log("Exiting bootloader");
//finish flashing and exit bootloader
await writer.write(new Uint8Array([0x45])); //"E" -> exit bootloader
state = -1;
gear.classList.remove('spinning');
console.log("finished!");
reader.cancel();
} else {
console.log("NACK");
}
}
}
await port.close();
};
readerF.readAsText(file);
}
const uploadForm = document.getElementById('uploadForm');
const resetForm = document.getElementById('resetForm');
const fileInput = document.getElementById('fileInput');
const fileButton = document.getElementById('fileButton');
const fileName = document.getElementById('fileName');
const boardType = document.getElementById('boardType');
const uploadBtn = document.getElementById('uploadBtn');
const log = document.getElementById('log');
const progress = document.getElementById('progress');
const gear = document.getElementById('gear');
uploadForm.addEventListener('submit', handleSubmit, false);
resetForm.addEventListener('submit', handleReset, false);
fileButton.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) fileName.textContent = file.name;
});
</script>
</body>
</html>