-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake.html
More file actions
1126 lines (1048 loc) · 31.8 KB
/
make.html
File metadata and controls
1126 lines (1048 loc) · 31.8 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Make a Tag
layout: single
description: A tool to make the RFID tag data for an OpenTag3D tag.
---
<style>
:root {
--card: #131822;
--muted: #a9b5c9;
--error: #ff6b6b;
--accent: #7aa2ff;
--line: #1f2733;
}
* {
box-sizing: border-box;
}
.card {
background: var(--card);
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
padding: 16px;
overflow: hidden;
}
.card h2 {
margin: 0;
padding: 14px 16px;
border-bottom: 1px solid var(--line);
font-size: 16px;
color: #cfe0ff;
}
label {
display: block;
font-size: 12px;
color: var(--muted);
margin-bottom: 6px;
}
input,
select,
textarea {
width: 100%;
padding: 10px 12px;
border-radius: 12px;
background: #0e1420;
border: 1px solid #1e2a3a;
outline: none;
}
input:focus,
select:focus,
textarea:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(122, 162, 255, 0.15);
}
input[type="color"] {
height: 45px;
background-size: cover;
}
.row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.color-input-row {
grid-template-columns: 1fr 4em;
}
.help {
font-size: 12px;
color: var(--muted);
margin-top: 6px;
}
.pill {
display: inline-flex;
gap: 8px;
align-items: center;
background: #0c1220;
border: 1px solid var(--line);
padding: 6px 10px;
border-radius: 999px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
.divider {
height: 1px;
background: var(--line);
margin: 12px 0;
}
.flex {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.muted {
color: var(--muted);
}
.kv {
display: grid;
grid-template-columns: 160px 1fr;
gap: 8px;
}
.scroll {
max-height: 420px;
overflow: auto;
}
pre {
margin: 0;
padding: 12px;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px 10px;
border-bottom: 1px solid var(--line);
text-align: left;
font-size: 13px;
}
th {
position: sticky;
top: 0;
background: #0e1420;
}
.field-row {
border: 1px dashed #243049;
padding: 10px;
border-radius: 10px;
transition: border-color 0.2s;
}
.chip {
display: inline-block;
background: #0f1a2b;
border: 1px solid #22304a;
border-radius: 8px;
padding: 2px 6px;
font-size: 12px;
margin-right: 6px;
}
div[hidden] {
display: none;
}
.invalid {
border-color: var(--error);
}
#controls {
margin-top: 1em;
}
#messages {
min-height: 1em;
}
@media screen and (max-width: 900px), screen and (max-device-width: 900px) {
.grid {
grid-template-columns: 1fr 1fr;
}
}
@media screen and (max-width: 600px), screen and (max-device-width: 600px) {
.grid {
grid-template-columns: 1fr;
}
}
</style>
<p>This is a utility to create RFID tag data to be written to your tags.</p>
<main>
<div id="controls">
<button class="btn" id="downloadBin">Download .bin</button>
<!-- <button class="btn" id="downloadFlipper">Download Flipper .nfc</button> -->
<!-- <button class="btn" id="downloadMap">Download address map (.csv)</button> -->
<button class="btn" id="writeWebNFC" disabled>Write via Web NFC</button>
<button class="btn btn--warning" id="loadFileBtn">Load File</button>
<button class="btn btn--warning" id="readWebNFC" disabled>
Read via Web NFC
</button>
<input
type="file"
id="uploadFile"
accept=".bin,.nfc,.txt,.hex"
style="display: none"
/>
</div>
<div id="messages" class="help"></div>
<details class="scroll" id="hexdumpBox">
<summary>Show hex dump</summary>
<pre id="hexdump" class="mono"></pre>
</details>
<br />
<section class="card">
<div class="pad">
<div class="flex">
<button class="btn btn--danger" id="resetBtn">Reset form</button>
<button class="btn btn--info" id="exampleBtn">
Fill placeholders (core only)
</button>
<button class="btn btn--info" id="allExampleBtn">
Fill placeholders (all data)
</button>
</div>
<div class="divider"></div>
<div id="formHost">
<!-- Dynamic form renders here -->
</div>
</div>
</section>
</main>
<script>
/* prettier-ignore-start */
// Spec comes from site.data.spec (Jekyll).
const SPEC = {{site.data.spec | jsonify}};
/* prettier-ignore-end */
</script>
<script>
const state = {
values: new Map(),
};
// --- Utils ---
const h = (tag, attrs = {}, ...kids) => {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") {
el.className = v;
} else if (k === "for") {
el.htmlFor = v;
} else if (k === "required") {
el.setAttribute("aria-required", "true");
el.required = true;
} else if (k.startsWith("on")) {
el.addEventListener(k.slice(2), v);
} else {
el.setAttribute(k, v);
}
}
for (const k of kids) el.append(k);
return el;
};
const clamp = (n, min, max) => Math.max(min, Math.min(max, n));
const hex = (n, w = 2) =>
Number(n).toString(16).toUpperCase().padStart(w, "0");
const addrHex = (a) => "0x" + hex(a);
const parseHex = (s) => (typeof s === "number" ? s : parseInt(s, 16));
const textEncoder = new TextEncoder();
function packInt(n, len, be = true) {
n = Math.floor(n || 0);
const b = new Uint8Array(len);
for (let i = 0; i < len; i++) {
const shift = be ? len - 1 - i : i;
b[i] = (n >> (8 * shift)) & 0xff;
}
return b;
}
function encodeAscii(str, len) {
const out = new Uint8Array(len);
const s = String(str || "");
for (let i = 0; i < Math.min(len, s.length); i++) {
const code = s.charCodeAt(i);
if (code > 0x7f) throw new Error("Non-ASCII character detected");
out[i] = code;
}
return out;
}
function encodeUtf8(str, len) {
const enc = textEncoder.encode(String(str || ""));
const out = new Uint8Array(len);
out.set(enc.subarray(0, len));
return out;
}
function rgbaFromHex(hexStr) {
const v = String(hexStr || "#00000000").replace("#", "");
return [
parseInt(v.slice(0, 2) || "00", 16),
parseInt(v.slice(2, 4) || "00", 16),
parseInt(v.slice(4, 6) || "00", 16),
parseInt(v.slice(6, 8) || "00", 16),
];
}
// --- Rendering ---
function renderForm() {
const host = document.getElementById("formHost");
host.innerHTML = "";
const sections = [
{ id: "core", title: "Core" },
{ id: "extended", title: "Extended" },
];
for (const sec of sections) {
const def = SPEC[sec.id];
if (!def) continue;
const box = h("div", { class: `grid section-${sec.id}` });
host.append(h("h3", { class: `muted section-${sec.id}` }, sec.title));
for (const f of def.fields) {
if (f.id == "tag_version") continue;
const row = h("div", {
class: "field-row",
"data-field": f.id,
"data-section": sec.id,
});
const left = h("div");
const label = h("label", {}, `${f.name}`);
if (f.required) label.append(h("span", { class: "text--danger" }, "*"));
left.append(label);
left.append(renderInputForField(f, sec.id));
row.append(left);
const meta = h(
"div",
{ class: "help" },
h("span", { class: "chip mono" }, `id:${f.id}`),
h("span", { class: "chip mono" }, `addr:${f.start}`),
h("span", { class: "chip mono" }, `len:${f.length}`),
f.unit && !["string", "version"].includes(f.unit)
? h("span", { class: "chip" }, `unit:${f.unit}`)
: "",
f.scaling ? h("span", { class: "chip" }, `scaling:${f.scaling}`) : "",
);
row.append(meta);
if (f.description) {
row.append(h("div", { class: "help" }, f.description));
}
box.append(row);
}
host.append(box);
}
}
function renderInputForField(f, section) {
// Calculate placeholder
let placeholder = "";
const firstExample = f.examples?.[0];
if (firstExample) {
if (f.type === "int") {
placeholder = firstExample * (f.scaling || 1);
} else {
placeholder = firstExample || "";
}
}
// Generic by type
if (f.type === "ascii" || f.type === "utf8") {
const inp = h("input", {
id: f.id,
"data-section": section,
type: "text",
placeholder,
required: f.required,
});
inp.addEventListener("input", () => {
state.values.set(f.id, inp.value);
buildMemory();
});
return inp;
}
if (f.type === "rgba") {
const initial_value = f.id === "color_1" ? "#FFFFFF" : "#000000";
const initial_alpha = f.id === "color_1" ? 255 : 0;
const row = h("div", { class: "row color-input-row" });
const color = h("input", {
type: "color",
id: f.id + "_rgb",
"data-section": section,
value: initial_value,
placeholder: initial_value,
required: f.required,
});
const alpha = h("input", {
type: "number",
id: f.id + "_a",
"data-section": section,
min: 0,
max: 255,
step: 1,
value: initial_alpha,
placeholder: initial_alpha,
required: f.required,
});
const out = h("input", {
type: "hidden",
id: f.id,
"data-section": section,
readonly: true,
});
const update = () => {
const alphaValue = parseInt(alpha.value || "255", 10);
const hex = color.value + alphaValue.toString(16).padStart(2, "0");
const rgba = rgbaFromHex(hex);
out.value = `[${rgba.join(",")}]`;
color.style.backgroundImage = `
linear-gradient(135deg, ${color.value} 0%, ${color.value} 50%, ${hex} 50%, ${hex} 100%),
url(/assets/images/transparency-grid.jpg)
`;
state.values.set(f.id, rgba);
buildMemory();
};
color.addEventListener("input", update);
alpha.addEventListener("input", update);
update();
row.append(color, alpha);
const box = h("div");
box.append(row, out);
return box;
}
if (f.type === "int") {
const scale = f.scaling || 1;
const inp = h("input", {
id: f.id,
"data-section": section,
type: "number",
min: 0,
max: 255 * length,
step: scale,
placeholder,
required: f.required,
});
const sync = () => {
const val = Math.round(parseFloat(inp.value || "0") / scale);
state.values.set(f.id, val);
buildMemory();
};
inp.addEventListener("input", sync);
sync();
return inp;
}
if (f.type === "date") {
const ph = new Date().toISOString().split("T")[0];
const inp = h("input", {
id: f.id,
"data-section": section,
type: "date",
placeholder: ph,
required: f.required,
});
const sync = () => {
state.values.set(f.id, inp.value);
buildMemory();
};
inp.addEventListener("input", sync);
sync();
return inp;
}
if (f.type === "time") {
const ph = new Date().toISOString().split("T")[1].split(".")[0];
const inp = h("input", {
id: f.id,
"data-section": section,
type: "time",
step: 1,
placeholder: ph,
required: f.required,
});
const sync = () => {
state.values.set(f.id, inp.value);
buildMemory();
};
inp.addEventListener("input", sync);
sync();
return inp;
}
// Text fallback
const inp = h("input", {
id: f.id,
"data-section": section,
type: "text",
placeholder,
required: f.required,
});
inp.addEventListener("input", () => {
state.values.set(f.id, inp.value);
buildMemory();
});
return inp;
}
function hexdump(buf, startAddr = 0x00) {
const lines = [];
for (let i = startAddr; i < buf.length; i += 16) {
const slice = buf.subarray(i, i + 16);
const hexs = [...slice].map((b) => hex(b)).join(" ");
const ascii = [...slice]
.map((b) => (b >= 32 && b <= 126 ? String.fromCharCode(b) : "."))
.join("");
lines.push(`${addrHex(i)} ${hexs.padEnd(16 * 3 - 1, " ")} |${ascii}|`);
}
return lines.join("\n");
}
// --- Building ---
function hasExtendedSet() {
const els = document.querySelectorAll("[data-section='extended']");
for (const el of els) {
if (el.value) {
return true;
}
}
return false;
}
function buildMemory() {
let extended = hasExtendedSet();
const size =
parseHex(SPEC[extended ? "extended" : "core"].address_range.end) + 1;
const buf = new Uint8Array(size + 1);
buf.fill(0x00);
const fields = [];
for (const set of extended ? ["core", "extended"] : ["core"]) {
fields.push(...SPEC[set].fields.map((f) => ({ set, ...f })));
}
// --- required validation helpers ---
const isPresent = (f, val) => {
if (!f.required) return true;
if (f.type === "ascii" || f.type === "utf8")
return typeof val === "string" && val.trim().length > 0;
if (f.type === "rgba") return Array.isArray(val) && val.length === 4;
if (f.type === "int" || f.type === "date" || f.type === "time") {
if (val === undefined || val === null) return false;
const n = typeof val === "number" ? val : Number(val);
return Number.isFinite(n) && n != 0;
}
return val !== undefined && val !== null && String(val).length > 0;
};
state.values.set(
"tag_version",
Math.round(parseFloat(SPEC.version) * 1000),
);
const missing = fields.filter(
(f) => f.required && !isPresent(f, state.values.get(f.id)),
);
// highlight missing rows
document
.querySelectorAll("[data-field]")
.forEach((el) => el.classList.remove("invalid"));
for (const f of missing) {
const row = document.querySelector(`[data-field="${f.id}"]`);
if (row) row.classList.add("invalid");
}
const rows = [];
const be = true; // big-endian storage for multi-byte ints
const push = (f, addr, bytes, note = "") => {
if (addr < 0 || addr + bytes.length > buf.length) {
rows.push([
f.name,
f.id,
addrHex(addr),
f.length,
"-",
`Out of range: ${addr} > ${buf.length}`,
]);
return;
}
buf.set(bytes, addr);
rows.push([
f.name,
f.id,
addrHex(addr),
bytes.length,
[...bytes].map((b) => hex(b)).join(" "),
note,
]);
};
for (const f of fields) {
if (f.type === "-") continue;
const addr = parseHex(f.start);
const val = state.values.get(f.id);
try {
if (f.type === "int" && f.id === "tag_version") {
const num =
state.values.get("tag_version") ??
Math.round(parseFloat(SPEC.version || "0") * 1000);
push(
f,
addr,
packInt(num, f.length, be),
`version ${SPEC.version ?? "—"}`,
);
} else if (f.type === "ascii") {
const s = (f.const ?? val ?? "") + "";
push(f, addr, encodeAscii(s, f.length));
} else if (f.type === "utf8") {
push(f, addr, encodeUtf8((val ?? "") + "", f.length));
} else if (f.type === "rgba") {
const rgba = Array.isArray(val) ? val : [255, 255, 255, 255];
push(f, addr, new Uint8Array(rgba.slice(0, 4)));
} else if (f.type === "int") {
const n = Number(val || 0);
push(f, addr, packInt(n, f.length, be));
} else if (f.type === "date") {
const d = (val || "").split("-");
let y = 0,
m = 0,
dd = 0;
if (d.length === 3) {
y = +d[0];
m = +d[1];
dd = +d[2];
}
const bytes = new Uint8Array([
...packInt(y, 2, be),
m & 0xff,
dd & 0xff,
]);
push(f, addr, bytes);
} else if (f.type === "time") {
const t = (val || "00:00:00").split(":");
let hh = 0,
mm = 0,
ss = 0;
if (t.length >= 2) {
hh = +t[0];
mm = +t[1];
ss = +(t[2] || "0").split(".")[0];
}
const bytes = new Uint8Array([hh & 0xff, mm & 0xff, ss & 0xff]);
push(f, addr, bytes);
} else {
if (typeof val === "number")
push(f, addr, packInt(val, f.length, be));
else push(f, addr, encodeUtf8(String(val || ""), f.length));
}
} catch (e) {
rows.push([
f.name,
addrHex(addr),
f.length,
"-",
`Error: ${e.message}`,
]);
}
}
// Update hexdump
document.getElementById("hexdump").textContent = hexdump(buf);
const checkMissing = () => {
if (missing.length > 0) {
msg(
`Please fill required fields: ${missing.map((m) => m.name || m.id).join(", ")}`,
true,
);
return true;
} else {
msg("");
return false;
}
};
const filename = `OpenTag3D_${state.values.get("manufacturer")}_${state.values.get("color_name")}`;
// Wire export actions (fresh closures)
document.getElementById("downloadBin").onclick = () => {
if (!checkMissing()) {
downloadBin(buf, `${filename}.bin`);
}
};
// document.getElementById("downloadMap").onclick = () => {
// if (!checkMissing()) {
// downloadMap(rows, `${filename}_map.csv`);
// }
// };
// document.getElementById("downloadFlipper").onclick = () => {
// if (!checkMissing()) {
// downloadFlipperNfc(buf, start, `${filename}.nfc`);
// }
// };
document.getElementById("writeWebNFC").onclick = () => {
if (!checkMissing()) {
writeViaWebNFC(buf, state.tagType).catch((e) =>
msg("Web NFC error: " + e.message, true),
);
}
};
return { buf, rows };
}
function downloadBin(buf, name) {
const blob = new Blob([buf], { type: "application/octet-stream" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
function downloadMap(rows, name) {
const head = ["Field", "ID", "Address", "Length", "Bytes", "Notes"];
const csv = [head.join(",")]
.concat(
rows.map((r) =>
r.map((x) => `"${String(x).replaceAll('"', '""')}"`).join(","),
),
)
.join("\n");
const blob = new Blob([csv], { type: "text/csv" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
function msg(message, isErr = false) {
const m = document.getElementById("messages");
m.textContent = message;
m.style.color = isErr ? "var(--error)" : "var(--muted)";
(isErr ? console.error : console.log)(message);
}
// --- Web NFC export (NDEF) ---
async function writeViaWebNFC(buf) {
if (!("NDEFReader" in window)) {
throw new Error("Web NFC is not supported in this browser");
}
msg("Waiting to write tag...");
const reader = new NDEFReader();
await reader.write({
records: [
{
recordType: "mime",
mediaType: "{{ site.data.spec.mime_type }}",
data: buf,
},
],
});
msg("Wrote NDEF payload to tag");
}
async function readViaWebNFC() {
if (!("NDEFReader" in window)) {
throw new Error("Web NFC is not supported in this browser");
}
msg("Waiting to read tag...");
const controller = new AbortController();
const reader = new NDEFReader();
await reader.scan({ signal: controller.signal });
reader.onreading = (event) => {
controller.abort();
let found = false;
for (const record of event.message.records) {
if (record.recordType == "mime" && record.mediaType == SPEC.mime_type) {
found = true;
msg("Found and loaded OpenTag3D record");
loadBufferIntoForm(record.data.buffer, 0x00);
break;
}
}
if (!found) {
msg("Read tag does not have any OpenTag3D records", true);
}
};
reader.onreadingerror = (event) => {
msg("Error reading tag, try again or try another tag", true);
};
}
// --- Flipper Zero export (.nfc minimal dump of user pages) ---
function downloadFlipperNfc(buf, startAddr, name) {
const header = [
"Filetype: Flipper NFC device",
"Version: 4",
"# Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, ISO14443-4B, ISO15693-3, FeliCa, NTAG/Ultralight, Mifare Classic, Mifare Plus, Mifare DESFire, SLIX, ST25TB",
"Device type: NTAG/Ultralight",
"# UID is common for all formats",
"UID: 00 00 00 00 00 00",
"# ISO14443-3A specific data",
"ATQA: 00 44",
"SAK: 00",
"# NTAG/Ultralight specific data",
"Data format version: 2",
"NTAG/Ultralight type: NTAG215",
"Signature: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
"Mifare version: 00 04 04 02 01 00 11 03",
"Counter 0: 0",
"Tearing 0: 00",
"Counter 1: 0",
"Tearing 1: 00",
"Counter 2: 0",
"Tearing 2: 00",
"Pages total: 135",
"Pages read: 135",
];
const ndefHeaderBytes = [
0x77, 0x48, 0x00, 0x00, 0xe1, 0x11, 0x3e, 0x00, 0x03, 0x90, 0xd2, 0x15,
0x78,
];
const offset = 0x08 + ndefHeaderBytes.length + SPEC.mime_type.length;
const newbuf = new Uint8Array(offset + buf.length + 1);
newbuf.fill(0x00);
// NDEF header stuff
newbuf.set(ndefHeaderBytes, 0x08);
newbuf.set(
encodeAscii(SPEC.mime_type, SPEC.mime_type.length),
0x08 + ndefHeaderBytes.length,
);
newbuf.set(buf, offset);
// Build page-aligned dump for user area only (each page = 4 bytes)
const lines = [];
for (let off = 0; off < newbuf.length; off += 4) {
const page = off / 4; // lower byte for display
const slice = newbuf.subarray(off, off + 4);
const b = [...slice].map((x) => hex(x)).join(" ");
lines.push(`Page ${page}: ${b}`);
}
const content = header.concat(lines).join("\n") + "\n";
const blob = new Blob([content], { type: "text/plain" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
// --- IMPORTERS ---
// Parse our hexdump lines, Flipper "Page XX:" lines, or plain hex bytes.
function parseBytesFromText(text) {
const lines = text
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
const byteMap = new Map();
let minAddr = Infinity,
maxAddr = -Infinity,
sawAddressed = false;
for (const line of lines) {
// App hexdump: "0x10 AA BB ... |....|"
let m = line.match(
/^0x([0-9A-Fa-f]+)\s+((?:[0-9A-Fa-f]{2}\s+){0,15}[0-9A-Fa-f]{2})(?:\s+\|.*)?$/,
);
if (m) {
const base = parseInt(m[1], 16);
const bytes = m[2]
.trim()
.split(/\s+/)
.map((h) => parseInt(h, 16));
bytes.forEach((b, i) => byteMap.set(base + i, b));
minAddr = Math.min(minAddr, base);
maxAddr = Math.max(maxAddr, base + bytes.length - 1);
sawAddressed = true;
continue;
}
// Flipper: "Page 10: AA BB CC DD"
m = line.match(
/^Page\s+([0-9A-Fa-f]{2}):\s+((?:[0-9A-Fa-f]{2}\s+){0,3}[0-9A-Fa-f]{2})$/,
);
if (m) {
const page = parseInt(m[1], 16);
const base = page * 4; // 4 bytes/page
const bytes = m[2]
.trim()
.split(/\s+/)
.map((h) => parseInt(h, 16));
bytes.forEach((b, i) => byteMap.set(base + i, b));
minAddr = Math.min(minAddr, base);
maxAddr = Math.max(maxAddr, base + bytes.length - 1);
sawAddressed = true;
continue;
}
}
if (sawAddressed) {
const start = isFinite(minAddr) ? minAddr : 0x10;
const out = new Uint8Array(maxAddr - start + 1);
out.fill(0);
for (let a = minAddr; a <= maxAddr; a++) {
const b = byteMap.get(a);
if (typeof b === "number") out[a - minAddr] = b;
}
return { startAddr: start, data: out };
}
// Plain hex bytes
const all = text
.replace(/[^0-9A-Fa-f]/g, " ")
.trim()
.split(/\s+/)
.filter(Boolean);
if (all.length) {
return {
startAddr: 0x10,
data: new Uint8Array(all.map((h) => parseInt(h, 16))),
};
}
throw new Error("No recognizable hex format found");
}
// Decode imported buffer back into the form (reverse the human↔stored scalings where we can).
function loadBufferIntoForm(buf, startAddr) {
const data = new Uint8Array(buf);
document.getElementById("hexdump").textContent = hexdump(data, startAddr);
const parseHex = (s) => (typeof s === "number" ? s : parseInt(s, 16));
const read = (addr, len) => {
const off = addr - startAddr;
if (off < 0 || off + len > data.length) return new Uint8Array(len);
return data.subarray(off, off + len);
};
const readInt = (bytes) => bytes.reduce((n, b) => (n << 8) | b, 0) >>> 0;
const setVal = (id, val) => {
const el = document.getElementById(id);
if (!el) return;
el.value = val;
el.dispatchEvent(new Event("input", { bubbles: true }));
};
const allFields = [...SPEC.core.fields, ...SPEC.extended.fields];
for (const f of allFields) {
const addr = parseHex(f.start);
if (addr > data.length) {
break;
}
const bytes = read(addr, f.length);
try {
if (f.id === "tag_version") {
const v = readInt(bytes) / 1000.0;
const ev = parseFloat(SPEC.version);
if (v != ev) {
msg(
`Warning: loaded tag version is mismatched (got ${v}, expected ${ev})`,
true,
);
}
} else if (f.type === "ascii" || f.type === "utf8") {
const s = String.fromCharCode(...bytes).replace(/\u0000+$/, "");
setVal(f.id, s);
} else if (f.type === "rgba") {
const [r = 0, g = 0, b = 0, a = 255] = bytes;
const color = document.getElementById(f.id + "_rgb");
if (color) {
color.value =
"#" +
[r, g, b]
.map((x) => x.toString(16).toUpperCase().padStart(2, "0"))
.join("");
color.dispatchEvent(new Event("input", { bubbles: true }));
}
const alpha = document.getElementById(f.id + "_a");
if (alpha) alpha.value = a;
const out = document.getElementById(f.id);
if (out) out.value = `[${r},${g},${b},${a}]`;
state.values.set(f.id, [r, g, b, a]);
} else if (f.type === "int") {
const n = readInt(bytes);
const holder = document.getElementById(f.id);
const number = holder?.parentElement?.querySelector(
'input[type="number"]',
);
if (number) {
number.value = String(n * (f.scaling || 1));
number.dispatchEvent(new Event("input", { bubbles: true }));
} else {
state.values.set(f.id, n);
}
} else if (f.type === "date") {
const y = (bytes[0] << 8) | bytes[1],
m = bytes[2],
d = bytes[3];
setVal(
f.id,
`${y.toString().padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`,
);
} else if (f.type === "time") {
const [hh = 0, mm = 0, ss = 0] = bytes;
setVal(
f.id,
`${String(hh).padStart(2, "0")}:${String(mm).padStart(2, "0")}:${String(ss).padStart(2, "0")}`,