forked from malc0mn/amiigo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
395 lines (340 loc) · 11 KB
/
app.js
File metadata and controls
395 lines (340 loc) · 11 KB
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
// app.js — State machine, UI logic, amiibo parsing, hex dump, download
import { Portal } from "./portal.js";
const SERIES_NAMES = {
0x00: "Super Smash Bros.",
0x01: "Super Mario",
0x02: "Chibi-Robo",
0x03: "Yoshi's Woolly World",
0x04: "Splatoon",
0x05: "Animal Crossing",
0x06: "8-Bit Mario",
0x07: "Skylanders",
0x09: "The Legend of Zelda",
0x0a: "Shovel Knight",
0x0c: "Kirby",
0x0d: "Pokemon",
0x0e: "Mario Sports Superstars",
0x0f: "Monster Hunter",
0x10: "BoxBoy!",
0x11: "Pikmin",
0x12: "Fire Emblem",
0x13: "Metroid",
0x14: "Others",
0x15: "Mega Man",
0x16: "Diablo",
};
const FIGURE_TYPES = { 0: "Figure", 1: "Card", 2: "Yarn" };
// --- Amiibo data parsing ---
function parseAmiiboData(buffer) {
const uid = new Uint8Array([
buffer[0], buffer[1], buffer[2],
buffer[4], buffer[5], buffer[6], buffer[7],
]);
const bcc0 = buffer[3];
const bcc1 = buffer[8];
const expectedBcc0 = 0x88 ^ buffer[0] ^ buffer[1] ^ buffer[2];
const expectedBcc1 = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7];
const uidValid = bcc0 === expectedBcc0 && bcc1 === expectedBcc1;
// ModelInfo: bytes 84-95 (unencrypted)
const mi = buffer.slice(84, 96);
// Detect whether this is actually an Amiibo: byte 91 is always 0x02 on real
// Amiibo, and the figure type (byte 87) must be 0x00, 0x01, or 0x02.
const isAmiibo = mi[7] === 0x02 && mi[3] <= 0x02;
let modelInfo = null;
if (isAmiibo) {
const idWord = (mi[0] << 8) | mi[1];
modelInfo = {
id: toHex(mi.slice(0, 8)),
gameId: idWord & 0x3ff,
characterId: (idWord >> 10) & 0x3f,
characterVariant: mi[2],
figureType: mi[3],
figureTypeName: FIGURE_TYPES[mi[3]],
modelNumber: (mi[4] << 8) | mi[5],
series: mi[6],
seriesName: SERIES_NAMES[mi[6]] ?? `Unknown (0x${mi[6].toString(16)})`,
};
}
return {
uid,
uidHex: toHex(uid),
uidValid,
isAmiibo,
modelInfo,
};
}
// --- Hex dump ---
function formatHexDump(buffer) {
const lines = [];
for (let offset = 0; offset < buffer.length; offset += 16) {
const hex = [];
let ascii = "";
for (let i = 0; i < 16; i++) {
if (offset + i < buffer.length) {
const b = buffer[offset + i];
hex.push(b.toString(16).padStart(2, "0"));
ascii += b >= 0x20 && b <= 0x7e ? String.fromCharCode(b) : ".";
} else {
hex.push(" ");
ascii += " ";
}
}
const addr = offset.toString(16).padStart(8, "0");
lines.push(`${addr} ${hex.slice(0, 8).join(" ")} ${hex.slice(8).join(" ")} |${ascii}|`);
}
return lines.join("\n");
}
// --- Amiibo database (IndexedDB + GitHub fallback) ---
const AMIIBO_DB_URL = "https://raw.githubusercontent.com/N3evin/AmiiboAPI/master/database/amiibo.json";
const IDB_NAME = "amiigo";
const IDB_STORE = "amiibo";
function openIdb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(IDB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(IDB_STORE);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function idbGet(db, key) {
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_STORE, "readonly");
const req = tx.objectStore(IDB_STORE).get(key);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function idbPutAll(db, entries) {
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_STORE, "readwrite");
const store = tx.objectStore(IDB_STORE);
for (const [key, value] of entries) store.put(value, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
let idb = null;
let dbPopulated = false;
async function ensureDb() {
idb ??= await openIdb();
if (!dbPopulated) {
// Check if we already have data from a previous session
const sample = await idbGet(idb, "_populated");
if (sample) {
dbPopulated = true;
} else {
// Fetch from GitHub and populate IndexedDB
const resp = await fetch(AMIIBO_DB_URL, { signal: AbortSignal.timeout(10000) });
if (!resp.ok) return false;
const json = await resp.json();
const entries = Object.entries(json.amiibos)
.map(([k, v]) => [k.slice(2).toLowerCase(), v.name]);
entries.push(["_populated", true]);
await idbPutAll(idb, entries);
dbPopulated = true;
}
}
return true;
}
async function fetchAmiiboName(amiiboId) {
if (!await ensureDb()) return null;
return await idbGet(idb, amiiboId.toLowerCase()) ?? null;
}
// --- File download ---
function downloadBin(buffer, uid, name) {
const safeName = name
? name.replace(/[^a-zA-Z0-9_\- ]/g, "").replace(/\s+/g, "_")
: null;
const filename = safeName
? `${safeName}_${toHex(uid)}.bin`
: `amiibo_${toHex(uid)}.bin`;
const blob = new Blob([buffer], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// --- Helpers ---
function toHex(bytes) {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
}
// --- UI ---
const $ = (id) => document.getElementById(id);
function setStatus(message, type = "info") {
const el = $("status");
el.textContent = message;
el.className = `status-${type}`;
}
function setInfo(parsed) {
$("info-uid").textContent = formatUid(parsed.uid);
$("info-uid-valid").textContent = parsed.uidValid ? "Valid" : "INVALID";
$("info-uid-valid").className = parsed.uidValid ? "valid" : "invalid";
if (parsed.isAmiibo) {
$("info-name").textContent = "Looking up...";
$("info-series").textContent = parsed.modelInfo.seriesName;
$("info-type").textContent = parsed.modelInfo.figureTypeName;
$("info-model").textContent = parsed.modelInfo.modelNumber;
$("info-amiibo-id").textContent = parsed.modelInfo.id;
$("amiibo-fields").classList.remove("hidden");
} else {
$("amiibo-fields").classList.add("hidden");
}
$("info-panel").classList.remove("hidden");
$("info-placeholder").classList.add("hidden");
}
function clearInfo() {
$("info-panel").classList.add("hidden");
$("info-placeholder").classList.remove("hidden");
$("hex-dump").textContent = "";
}
function formatUid(uid) {
return Array.from(uid, (b) => b.toString(16).padStart(2, "0").toUpperCase()).join(":");
}
function addLog(message) {
const el = $("log");
const time = new Date().toLocaleTimeString();
el.textContent += `[${time}] ${message}\n`;
el.scrollTop = el.scrollHeight;
}
// --- State machine ---
const portal = new Portal();
let state = "disconnected";
let pollTimer = null;
let currentData = null;
let currentParsed = null;
let currentName = null;
let failedUid = null; // UID that failed to read — skip until removed
async function onConnect() {
try {
$("btn-connect").disabled = true;
setStatus("Connecting...", "info");
await portal.connect({
onDisconnect: () => {
stopPolling();
state = "disconnected";
currentData = null;
currentParsed = null;
currentName = null;
setStatus("Disconnected", "error");
clearInfo();
$("btn-connect").disabled = false;
$("btn-download").disabled = true;
},
onLog: addLog,
});
state = "polling";
setStatus("Waiting for Amiibo...", "info");
startPolling();
} catch (e) {
setStatus(`Connection failed: ${e.message}`, "error");
$("btn-connect").disabled = false;
addLog(`Error: ${e.message}`);
}
}
function startPolling() {
stopPolling();
poll();
}
function stopPolling() {
if (pollTimer !== null) {
clearTimeout(pollTimer);
pollTimer = null;
}
}
async function poll() {
if (!portal.device) return;
try {
if (state === "polling") {
const { found, uid } = await portal.pollOnce();
if (found && toHex(uid) !== failedUid) {
state = "reading";
setStatus("Token detected! Reading...", "success");
addLog(`Token detected: ${toHex(uid)}`);
await readAmiibo(uid);
} else if (!found && failedUid) {
// Token removed — clear the failed UID so it can be retried
failedUid = null;
setStatus("Waiting for Amiibo...", "info");
pollTimer = setTimeout(poll, 100);
} else {
pollTimer = setTimeout(poll, 100);
}
} else if (state === "done") {
// Background poll to detect token removal
const { found } = await portal.pollOnce();
if (!found) {
addLog("Token removed.");
await portal.ledOff();
currentData = null;
currentParsed = null;
currentName = null;
clearInfo();
$("btn-download").disabled = true;
state = "polling";
setStatus("Waiting for Amiibo...", "info");
}
pollTimer = setTimeout(poll, 200);
}
} catch (e) {
addLog(`Poll error: ${e.message}`);
// If device is gone, the disconnect handler will fire. Otherwise retry.
if (portal.device) {
pollTimer = setTimeout(poll, 500);
}
}
}
async function readAmiibo(uid) {
try {
await portal.initDance(uid);
const data = await portal.readTokenWithValidation();
currentData = data;
currentParsed = parseAmiiboData(data);
setInfo(currentParsed);
$("hex-dump").textContent = formatHexDump(data);
$("btn-download").disabled = false;
if (currentParsed.isAmiibo) {
addLog(`Read complete: ${currentParsed.modelInfo.seriesName} ${currentParsed.modelInfo.figureTypeName} (${currentParsed.uidHex})`);
} else {
addLog(`Read complete: NFC tag (not an Amiibo) (${currentParsed.uidHex})`);
}
setStatus("Read successful!", "success");
state = "done";
pollTimer = setTimeout(poll, 200);
// Look up character name (non-blocking — only for real Amiibo)
if (currentParsed.isAmiibo) {
fetchAmiiboName(currentParsed.modelInfo.id).then((name) => {
currentName = name;
$("info-name").textContent = name ?? "Unknown";
if (name) addLog(`AmiiboAPI: ${name}`);
}).catch(() => {
$("info-name").textContent = "Lookup failed";
});
}
} catch (e) {
addLog(`Read error: ${e.message}`);
failedUid = toHex(uid);
state = "polling";
setStatus("Unreadable tag. Remove and try another.", "error");
startPolling();
}
}
function onDownload() {
if (currentData && currentParsed) {
downloadBin(currentData, currentParsed.uid, currentName);
const filename = currentName
? `${currentName.replace(/[^a-zA-Z0-9_\- ]/g, "").replace(/\s+/g, "_")}_${currentParsed.uidHex}.bin`
: `amiibo_${currentParsed.uidHex}.bin`;
addLog(`Downloaded ${filename}`);
}
}
// --- Init ---
document.addEventListener("DOMContentLoaded", () => {
$("btn-connect").addEventListener("click", onConnect);
$("btn-download").addEventListener("click", onDownload);
if (!navigator.hid) {
setStatus("WebHID not available. Use Chrome 89+ over HTTPS or localhost.", "error");
$("btn-connect").disabled = true;
}
});