forked from DanTheMan827/amiibolink-amiloop-webbluetooth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amiloop.html
390 lines (325 loc) · 13.2 KB
/
amiloop.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
<!DOCTYPE html>
<html>
<head>
<title>AmiLoop WebBluetooth</title>
<meta charset="UTF-8" />
<style type="text/css">
body {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";
}
</style>
</head>
<body>
<h1>AmiLoop Management</h1>
<p>This page uses WebBluetooth to manage the AmiLoop.</p>
<p><a id="connectDisconnect" href="#">Connect</a></p>
<div id="connectedStuff" style="display: none;">
<p><strong>Firmware:</strong> <span id="firmware"></span></p>
<ul>
<li><a id="uploadTag" href="#">Upload tag data</a></li>
<li><a id="clearTag" href="#">Write blank tag</a></li>
<li><a id="manualMode" href="#">Set manual mode</a></li>
<li><a id="sequentialMode" href="#">Set sequential mode</a></li>
<li><a id="automaticMode" href="#">Set automatic mode</a></li>
<li><a id="resetAmiloop" href="#">Reset AmiLoop</a></li>
</ul>
</div>
<script>
var blockerElement = document.createElement("div");
blockerElement.style = "background-color: rgba(0, 0, 0, 0.5); align-items: center; justify-content: center; position: fixed; inset: 0px; backdrop-filter: blur(4px); color: white; font-weight: bold; font-size: 2rem; display: none; transition: all 0.3s ease 0s; opacity: 0;";
document.body.append(blockerElement);
var amiLoop = null;
/**
* Prompts the user to select a file and returns its contents as a Uint8Array.
* @returns {Promise<Uint8Array>} A promise that resolves with the file contents as a Uint8Array.
* @throws {Error} If no file is selected or if there is an error reading the file.
*/
function promptForFileAndGetContents() {
return new Promise((resolve, reject) => {
// Create an input element
const input = document.createElement('input');
input.type = 'file';
// Handle file selection
input.onchange = (event) => {
var _a;
const target = event.target;
const file = (_a = target.files) === null || _a === void 0 ? void 0 : _a[0];
if (file) {
const reader = new FileReader();
reader.onload = (loadEvent) => {
var _a;
const result = (_a = loadEvent.target) === null || _a === void 0 ? void 0 : _a.result;
if (result instanceof ArrayBuffer) {
resolve(new Uint8Array(result));
} else {
reject(new Error('Failed to read file contents.'));
}
};
reader.onerror = () => {
reject(new Error('Failed to read file.'));
};
reader.readAsArrayBuffer(file);
} else {
reject(new Error('No file selected.'));
}
};
// Trigger file selection
input.click();
});
}
/**
* Performs bitwise XOR operation on a byte array and returns the result.
* @param {Uint8Array} byteArray - The input byte array.
* @returns {number} The result of XOR operation.
* @throws {Error} If the input byte array is empty.
*/
function xorByteArray(byteArray) {
if (!byteArray || byteArray.length === 0) {
throw new Error("Empty collection can't be reduced.");
}
let result = byteArray[0];
for (let i = 1; i < byteArray.length; i++) {
result ^= byteArray[i];
}
return result & 0xff;
}
/**
* Processes a Uint8Array by splitting it into chunks and adding header and footer bytes to each chunk.
* @param {Uint8Array} input - The input Uint8Array to process.
* @returns {Uint8Array[]} An array of processed chunks.
*/
function processUint8Array(input) {
const output = [];
let start = 0;
while (start < input.length) {
const chunkSize = Math.min(128, input.length - start);
const chunk = input.slice(start, start + chunkSize);
const newData = new Uint8Array(5 + chunk.length + 2);
newData[0] = 0x02;
newData[1] = chunk.length + 3;
newData[2] = 0x87;
newData[3] = chunk.length < 128 ? 1 : 0;
newData[4] = output.length;
newData.set(chunk, 5);
const xorValue = xorByteArray(newData.slice(1, newData.length - 2));
newData[newData.length - 2] = xorValue;
newData[newData.length - 1] = 0x03;
output.push(newData);
start += chunkSize;
}
return output;
}
/**
* Converts an ArrayBuffer to a hexadecimal string.
* @param {ArrayBuffer} buffer - The input ArrayBuffer to convert.
* @returns {string} The hexadecimal representation of the input buffer.
*/
function buf2hex(buffer) {
buffer = new Uint8Array(buffer);
let result = '';
for (let i = 0; i < buffer.length; i++) {
const hex = buffer[i].toString(16).padStart(2, '0');
result += hex.toUpperCase() + ' ';
if ((i + 1) % 8 === 0) {
result += '\n';
}
}
return result.trim();
}
async function connectToAmiLoop(onDisconnect, deviceIdentifier) {
try {
let device;
// Check if deviceIdentifier is provided and reconnect if available
if (deviceIdentifier && navigator.bluetooth.getDevices) {
const devices = await navigator.bluetooth.getDevices();
device = devices.find(d => d.id === deviceIdentifier);
}
// If device not found or deviceIdentifier not provided, perform a new scan
if (!device) {
device = await navigator.bluetooth.requestDevice({
filters: [{
name: 'AmiLoop'
}],
optionalServices: ['6e400001-b5a3-f393-e0a9-e50e24dcca9e']
});
}
await device.gatt.disconnect();
const server = await device.gatt.connect();
const service = await server.getPrimaryService('6e400001-b5a3-f393-e0a9-e50e24dcca9e');
const characteristicTX = await service.getCharacteristic('6e400002-b5a3-f393-e0a9-e50e24dcca9e');
const characteristicRX = await service.getCharacteristic('6e400003-b5a3-f393-e0a9-e50e24dcca9e');
// Add disconnect event listener
device.addEventListener('gattserverdisconnected', () => {
if (typeof onDisconnect === 'function') {
onDisconnect();
}
});
characteristicRX.addEventListener('characteristicvaluechanged', function(event) {
const data = event.target.value;
// Handle received data here
console.log(`\x1B[1mRead data\x1B[m\n${buf2hex(data.buffer)}`);
});
await characteristicRX.startNotifications();
const characteristics = {
device,
service,
server,
characteristicTX,
characteristicRX,
firmware: undefined
}
// Some kind of handshake, maybe?
const handshakeResponse = new Uint8Array((await sendAndWait(characteristics, Uint8Array.from([0x02, 0x01, 0x89, 0x88, 0x03]))).buffer);
characteristics.firmware = new TextDecoder().decode(handshakeResponse.slice(3, 3 + handshakeResponse[1]));
return characteristics;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
function sendAndWait(characteristics, data) {
return new Promise(async (resolve, reject) => {
try {
const { characteristicTX, characteristicRX } = characteristics;
function innerResolve(event) {
characteristicRX.removeEventListener('characteristicvaluechanged', innerResolve)
resolve(event.target.value)
}
characteristicRX.addEventListener('characteristicvaluechanged', innerResolve);
await characteristicTX.writeValueWithResponse(data);
} catch (error) {
console.error('Error:', error);
reject(error);
}
})
}
async function sendDataToAmiLoop(characteristics, data, noWait) {
let i = 0;
try {
const { characteristicTX, characteristicRX } = characteristics;
for (const byteArray of data) {
blockerElement.innerText = `Sending ${++i} / ${data.length}`;
console.log(`\x1B[1mWrite data\x1B[m\n${buf2hex(byteArray)}`);
if (noWait) {
await characteristicTX.writeValueWithResponse(byteArray);
} else {
await sendAndWait(characteristics, byteArray);
}
}
} catch (error) {
console.error('Error:', error);
throw error;
}
}
async function setModeManual() {
await sendDataToAmiLoop(amiLoop, [Uint8Array.from([0x02, 0x02, 0x8a, 0x00, 0x88, 0x03])])
}
async function setModeSequential() {
await sendDataToAmiLoop(amiLoop, [Uint8Array.from([0x02, 0x02, 0x8a, 0x01, 0x89, 0x03])])
}
async function setModeAutomatic() {
await sendDataToAmiLoop(amiLoop, [Uint8Array.from([0x02, 0x02, 0x8a, 0x02, 0x8a, 0x03])])
}
async function resetAmiLoop() {
await sendDataToAmiLoop(amiLoop, [Uint8Array.from([0x12, 0x0d, 0x00, 0x02, 0x01, 0x8f, 0x8e, 0x03])], true)
}
/**
* This function generates and returns a 572-byte array populated with the data of a blank NTAG215 with a random UID.
* @returns An array with blank NTAG215 data.
*/
function getBlankNtag() {
const tag = new Uint8Array(572)
tag[0] = 0x04
tag[1] = Math.round(Math.random() * 255)
tag[2] = Math.round(Math.random() * 255)
tag[3] = tag[0] ^ tag[1] ^ tag[2] ^ 0x88
tag[4] = Math.round(Math.random() * 255)
tag[5] = Math.round(Math.random() * 255)
tag[6] = Math.round(Math.random() * 255)
tag[7] = Math.round(Math.random() * 255)
tag[8] = tag[4] ^ tag[5] ^ tag[6] ^ tag[7]
tag.set([0x48, 0x00, 0x00, 0xE1, 0x10, 0x3E, 0x00, 0x03, 0x00, 0xFE], 0x09)
tag.set([0xBD, 0x04, 0x00, 0x00, 0xFF, 0x00, 0x05], 0x20B)
return tag
}
function onConnected() {
document.getElementById("connectedStuff").style.display = "";
document.getElementById("firmware").innerText = amiLoop.firmware.toString();
}
function onDisconnected() {
document.getElementById("connectedStuff").style.display = "none";
}
function showBlocker() {
blockerElement.innerText = "";
blockerElement.style.display = "flex";
setTimeout(() => blockerElement.style.opacity = "1.0", 1);
}
function hideBlocker() {
blockerElement.style.opacity = 0;
setTimeout(() => blockerElement.style.display = "none", 300);
}
document.getElementById("connectDisconnect").addEventListener("click", async function(e) {
e.preventDefault();
if (amiLoop) {
await amiLoop.server.disconnect();
amiLoop = null;
return;
}
amiLoop = await connectToAmiLoop(() => {
amiLoop = null;
this.innerText = "Connect";
onDisconnected();
}, this.dataset.previousDevice);
this.innerText = "Disconnect"
onConnected();
});
document.getElementById("uploadTag").addEventListener("click", async function(e) {
e.preventDefault();
var fileData = await promptForFileAndGetContents();
var tagData = new Uint8Array(540);
tagData.set(fileData.slice(0, Math.min(540, fileData.length)), 0);
tagData[536] = 0x80;
tagData[537] = 0x80;
var chunkedData = processUint8Array(tagData);
showBlocker();
await sendDataToAmiLoop(amiLoop, chunkedData);
hideBlocker();
})
document.getElementById("clearTag").addEventListener("click", async function(e) {
e.preventDefault();
var tagData = new Uint8Array(540);
tagData.set(getBlankNtag().slice(0, 540), 0);
tagData[536] = 0x80;
tagData[537] = 0x80;
var chunkedData = processUint8Array(tagData);
showBlocker();
await sendDataToAmiLoop(amiLoop, chunkedData);
hideBlocker();
})
document.getElementById("manualMode").addEventListener("click", async function(e) {
e.preventDefault();
showBlocker();
await setModeManual();
hideBlocker();
})
document.getElementById("sequentialMode").addEventListener("click", async function(e) {
e.preventDefault();
showBlocker();
await setModeSequential();
hideBlocker();
})
document.getElementById("automaticMode").addEventListener("click", async function(e) {
e.preventDefault();
showBlocker();
await setModeAutomatic();
hideBlocker();
})
document.getElementById("resetAmiloop").addEventListener("click", async function(e) {
e.preventDefault();
showBlocker();
await resetAmiLoop();
hideBlocker();
})
</script>
</body>
</html>