-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloader.js
280 lines (235 loc) · 6.79 KB
/
loader.js
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
#!/usr/bin/env node
const { withPad } = require('./loader/utils');
const { prepareCommand, commands } = require('./loader/commands');
const SerialPort = require('serialport');
const fs = require('fs');
const ACK = Buffer.from('cmdr\0', 'ascii');
const TEST_TIMEOUT = 1000;
const MEG = 1024 * 1024;
// This should be a multiple of 512
const STATUS_UPDATE_AT = MEG;
const STATUS_TIMEOUT = 2000;
const ROM_START_ADDRESS = 0x10000000;
const CRC_AREA = 0x100000 + 4096;
const STATUS_ERROR = 1;
const STATUS_BAD_PARAM = 1;
/**
* Waits for an ack from the Everdrive
* @param port
* @returns true if achnowledged on time
*/
function test(port) {
return new Promise((resolve) => {
const portTimeout = setTimeout(() => {
resolve(false);
port.close();
}, TEST_TIMEOUT);
let buffer = Buffer.alloc(0);
function wait(data) {
buffer = Buffer.concat([buffer, data]);
if (buffer.includes(ACK)) {
clearTimeout(portTimeout);
port.removeListener('data', wait);
resolve(true);
}
}
port.on('data', wait);
});
}
function writeToPort(port, data) {
return new Promise((resolve, reject) => {
port.write(data, (err) => {
if (err) {
reject(err);
return;
}
resolve(true);
});
});
}
async function sendData(port, data) {
async function continueUpload(size, offset = 0) {
const remainingBytes = size - offset;
if (remainingBytes > 0) {
const timeout = new Promise((_, reject) =>
setTimeout(() => {
reject(new Error('Upload timed out.'));
}, STATUS_TIMEOUT)
);
const amount = Math.min(STATUS_UPDATE_AT, remainingBytes);
const nextOffset = offset + amount;
await Promise.race([
timeout,
writeToPort(port, data.slice(offset, nextOffset)),
]);
console.log(`Uploaded ${((nextOffset / size) * 100).toFixed(2)}%`);
await continueUpload(size, nextOffset);
}
}
try {
data = withPad(data, 512);
const size = data.byteLength;
if (size < CRC_AREA) {
console.log('Start fill');
await writeToPort(
port,
prepareCommand(commands.ROM_FILL, ROM_START_ADDRESS, CRC_AREA)
);
console.log('Fill complete.');
}
await writeToPort(
port,
prepareCommand(commands.ROM_WRITE, ROM_START_ADDRESS, size)
);
console.log('Sending...');
await continueUpload(size);
console.log('Now booting...');
await writeToPort(port, prepareCommand(commands.ROM_START, 0, 0, 1));
const buffer = Buffer.alloc(256);
await writeToPort(port, buffer);
console.log('Done uploading.');
} catch (e) {
port.close();
throw e;
}
}
const DATATYPE_TEXT = 0x01;
const DATATYPE_RAWBINARY = 0x02;
const DATATYPE_HEADER = 0x03;
const DATATYPE_SCREENSHOT = 0x04;
function startListening(port) {
let buffer = Buffer.alloc(0);
let headerData = Buffer.alloc(16);
port.on('data', (d) => {
buffer = Buffer.concat([buffer, d]);
let headerMarker = -1;
while ((headerMarker = buffer.indexOf(Buffer.from('DMA@', 'ascii'))) >= 0) {
let read = headerMarker + 4;
if (read + 4 > buffer.length) {
// Don't have enough data for header yet
break;
}
// We can read the 4 byte header now
const header = buffer.readInt32BE(read);
const size = header & 0x00ffffff;
const type = (header & 0xff000000) >> 24;
read += 4;
if (read + size + 4 > buffer.length) {
// Don't have enough data yet for data + cmp
break;
}
const data = buffer.slice(read, read + size);
read += size;
if (
buffer.slice(read, read + 4).compare(Buffer.from('CMPH', 'ascii')) !== 0
) {
console.error('Incomplete packet was received: ' + data.toString());
}
read += 4;
switch (type) {
case DATATYPE_TEXT:
process.stdout.write(data);
break;
case DATATYPE_HEADER:
console.assert(
data.length == 16,
`Header size was not correct expected 16 received: ${data.length}`
);
data.copy(headerData);
break;
case DATATYPE_SCREENSHOT: {
const headerType = headerData.readInt32BE(0);
// const depth = headerData.readInt32BE(1);
// const width = headerData.readInt32BE(2);
// const height = headerData.readInt32BE(3);
console.assert(
headerType == DATATYPE_SCREENSHOT,
`Last received header was not ${DATATYPE_SCREENSHOT}, received: ${headerType}`
);
headerData.fill(0);
// TODO: handle screenshot
break;
}
case DATATYPE_RAWBINARY:
// TODO: handle binary file
break;
}
const newBuf = Buffer.alloc(buffer.length - read);
buffer.copy(newBuf, 0, read);
buffer = newBuf;
}
});
}
async function findPortAndUpload(options) {
try {
const { fileName, keepAlive } = options;
// Enumarate ports and invoke sendData
const ports = await SerialPort.list();
let found = false;
for (let { path } of ports) {
const port = new SerialPort(path, {
baudRate: 9600,
});
// Open errors will be emitted as an error event, just let user know
port.on('error', function (err) {
console.error('Port Error: ', err.message);
});
await writeToPort(port, prepareCommand(commands.TEST));
found = await test(port);
if (found) {
console.log('Found ED64 on', path);
const contents = fs.readFileSync(fileName);
await sendData(port, contents);
if (keepAlive) {
startListening(port, options.port);
} else {
port.close();
}
break;
}
}
if (!found) {
console.error('No everdrive found!');
process.exit(STATUS_ERROR);
}
} catch (e) {
console.error(`Error occurred: ${e.message}`);
process.exit(STATUS_ERROR);
}
}
const options = {
keepAlive: false,
port: 1337,
};
// TODO: add shorthand syntax
process.argv.forEach(function (val, index) {
if (index < 2) {
return;
}
switch (val) {
case '--keep-alive':
options.keepAlive = true;
return;
}
if (val.indexOf('--') === 0) {
console.error(`encountered unknown flag: ${val}`);
process.exit(STATUS_BAD_PARAM);
}
if (options.fileName || !val) {
console.error('You must provide only a single ROM file to read from');
process.exit(STATUS_BAD_PARAM);
}
options.fileName = val;
});
if (!options.fileName) {
console.error('You must provide a ROM file');
process.exit(STATUS_BAD_PARAM);
}
if (
!fs.existsSync(options.fileName) ||
fs.statSync(options.fileName).isDirectory()
) {
console.error(`${options.fileName} is not a ROM`);
process.exit(STATUS_BAD_PARAM);
}
findPortAndUpload(options);