-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_tigertag.py
More file actions
1883 lines (1584 loc) · 82.7 KB
/
Copy pathparse_tigertag.py
File metadata and controls
1883 lines (1584 loc) · 82.7 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
# SPDX-License-Identifier: Apache-2.0
#
# TigerTag SDK
# Copyright (c) 2025-2026 TigerTag Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Implementing the TigerTag protocol requires no licence and no payment.
# https://github.com/TigerTag-Project/TigerTag-RFID-Guide/blob/main/LICENSING.md
"""
parse_tigertag.py — TigerTag Python SDK (v1.1)
================================================
Single-file, self-contained SDK for reading, writing, and syncing TigerTag RFID chips.
Spec : https://github.com/TigerTag-Project/TigerTag-RFID-Guide
SDK repo: https://github.com/TigerTag-Project/tigertag-sdk-python
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SCOPE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
All material data (temperatures, material, brand, colors…) is stored directly
on the chip. No API call is required to read a tag.
TigerTag+ chips carry a cloud product ID (id_product ≠ 0xFFFFFFFF).
This SDK reads all chip fields identically for every tag type.
Use diff_api() / patch_from_api() to compare chip data against the
TigerTag+ cloud API and apply manufacturer updates.
┌─────────────────────────────────────────────────────────────────────┐
│ TigerTag type │ Read │ Write │ Cloud sync │
├───────────────────┼───────────────┼───────────────┼─────────────────┤
│ TigerTag (Maker) │ ✅ full │ ✅ create() │ — │
│ TigerTag Init │ ✅ full │ ✅ as_init() │ — │
│ TigerTag+ │ ✅ full │ ✅ create() │ ✅ diff_api() │
└───────────────────┴───────────────┴───────────────┴─────────────────┘
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
QUICK START
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Parse a tag from binary dump
from parse_tigertag import TigerTag
tag = TigerTag.from_dump(open("dump.bin", "rb").read())
tag.sync_db() # download/update reference databases (optional)
print(tag.pretty()) # human-readable output
print(tag.to_dict()) # dict for JSON / API
print(tag.verify()) # ECDSA signature verification
# Create a new tag from scratch
tag = TigerTag.create(id_material=38219, nozzle_temp_min=190, nozzle_temp_max=230)
chip.write_pages(4, tag.to_bytes())
# Surgical update (immutable — returns a new TigerTag)
updated = tag.patch(dry_temp=55, nozzle_temp_max=240)
# TigerTag+ cloud sync
diffs = tag.diff_api()
new_tag, applied = tag.patch_from_api()
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DEPENDENCIES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
REQUIRED — core parsing (Python stdlib, no install needed):
struct, json, os, sys, pathlib, dataclasses, datetime, typing
OPTIONAL for database sync (auto-download reference JSON files):
pip install requests
→ Without this, databases must be present locally before use.
OPTIONAL for ECDSA signature verification:
pip install cryptography
→ Without this, verify() returns SignatureResult.NO_CRYPTO.
Install everything at once:
pip install requests cryptography
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BINARY LAYOUT — pages 0x04-0x27 (144 bytes)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Page Offset Size Field Type
──────── ────── ──── ────────────────────── ────────
0x04 +0 4B ID TigerTag u32 BE
0x05 +4 4B ID Product u32 BE
0x06 +8 2B ID Material u16 BE
0x06 +10 1B ID Aspect 1 u8
0x06 +11 1B ID Aspect 2 u8
0x07 +12 1B ID Type u8
0x07 +13 1B ID Diameter u8
0x07 +14 2B ID Brand u16 BE
0x08 +16 4B Color 1 (RGBA) bytes
0x09 +20 3B Measure u24 BE
0x09 +23 1B ID Unit u8
0x0A +24 2B Nozzle Temp Min u16 BE °C
0x0A +26 2B Nozzle Temp Max u16 BE °C
0x0B +28 1B Dry Temp u8 °C
0x0B +29 1B Dry Time u8 hours
0x0B +30 1B Bed Temp Min u8 °C
0x0B +31 1B Bed Temp Max u8 °C
0x0C +32 4B Twin Tag ID+Timestamp u32 BE sec since 2000-01-01 GMT
0x0D +36 3B Color 2 (RGB) bytes
0x0D +39 1B Reserved u8 = 0x00
0x0E +40 3B Color 3 (RGB) bytes
0x0E +43 1B Reserved u8 = 0x00
0x0F +44 2B TD HueForge u16 BE value / 10
0x0F +46 2B Reserved u16 = 0x0000
0x10-0x16 +48 28B Custom Message UTF-8
0x17 +76 3B Measure Available u24 BE
0x17 +79 1B Reserved u8 = 0x00
0x18-0x1F +80 32B Signature R (ECDSA) bytes optional
0x20-0x27 +112 32B Signature S (ECDSA) bytes optional
Capacity : 80B user data + 64B signature = 144B = full user memory
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNATURE ALGORITHM
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Algorithm : ECDSA SECP256R1 (P-256)
Hash : SHA-256
Message : SHA-256( UID_bytes + block4 + block5 )
Where:
UID_bytes = 7 raw bytes from chip pages 0-1 (NOT hex string, NOT decimal)
page0[0:3] + page1[0:4]
block4 = page 0x04 bytes 0-3 (ID TigerTag, u32 BE)
block5 = page 0x05 bytes 4-7 (ID Product, u32 BE)
The public key is stored in id_version.json ("public_key" field).
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ACCEPTED DUMP FORMATS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
180 bytes — full chip dump (pages 0-44): UID auto-extracted → signature verifiable
144 bytes — user data + signature (pages 0x04-0x27): signature NOT verifiable (no UID)
80 bytes — user data only (pages 0x04-0x17)
"""
from __future__ import annotations
# ──────────────────────────────────────────────────────────────────────────────
# Standard library (no install required)
# ──────────────────────────────────────────────────────────────────────────────
import json
import os
import struct
import sys
from dataclasses import dataclass, field, fields as _dc_fields, replace as _dc_replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ──────────────────────────────────────────────────────────────────────────────
# Optional: requests (pip install requests)
# Required for auto-downloading reference JSON databases
# ──────────────────────────────────────────────────────────────────────────────
try:
import requests as _requests
_REQUESTS_AVAILABLE = True
except ImportError:
_REQUESTS_AVAILABLE = False
# ──────────────────────────────────────────────────────────────────────────────
# Optional: cryptography (pip install cryptography)
# Required for ECDSA signature verification
# ──────────────────────────────────────────────────────────────────────────────
try:
from cryptography.hazmat.primitives.asymmetric import ec as _ec
from cryptography.hazmat.primitives import hashes as _hashes
from cryptography.hazmat.primitives.serialization import load_pem_public_key as _load_pem_public_key
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature as _encode_dss_signature
from cryptography.exceptions import InvalidSignature as _InvalidSignature
_CRYPTO_AVAILABLE = True
except ImportError:
_CRYPTO_AVAILABLE = False
# ══════════════════════════════════════════════════════════════════════════════
# CONSTANTS
# ══════════════════════════════════════════════════════════════════════════════
# Database sources
_API_BASE = "https://api.tigertag.io/api:tigertag"
_GITHUB_RAW_BASE = "https://raw.githubusercontent.com/TigerTag-Project/TigerTag-RFID-Guide/main/database"
_HTTP_TIMEOUT = 30
# Database files: last_update key → (API endpoint, local filename)
_DATASETS: Dict[str, tuple] = {
"versions": ("version/get/all", "id_version.json"),
"types": ("type/get/all", "id_type.json"),
"brands": ("brand/get/all", "id_brand.json"),
"filament_diameters": ("diameter/filament/get/all", "id_diameter.json"),
"filament_materials": ("material/get/all", "id_material.json"),
"aspects": ("aspect/get/all", "id_aspect.json"),
"measure_units": ("measure_unit/get/all", "id_measure_unit.json"),
}
# NTAG-compatible memory layout
CHIP_DUMP_LEN = 180 # full chip: 45 pages × 4B (pages 0-44)
FULL_DATA_LEN = 144 # user data + signature (pages 0x04-0x27)
MIN_DATA_LEN = 80 # user data only (pages 0x04-0x17)
# Epoch for TigerTag timestamps (seconds since this date)
_TIGERTAG_EPOCH = datetime(2000, 1, 1, tzinfo=timezone.utc)
# Product ID sentinel values
MAKER_PRODUCT_ID = 0xFFFFFFFF # offline Maker tag
INIT_PRODUCT_ID = 0x00000000 # blank / uninitialized tag
# Protocol version identifiers (id_tigertag field)
ID_TIGERTAG = 0x5BF59264 # TigerTag v1.0 (Maker / offline)
ID_TIGERTAG_PLUS = 0xBC0FCB97 # TigerTag+ v1.0 (cloud product)
ID_TIGERTAG_INIT = 0x6C41A2E1 # TigerTag Init (reserved, not yet programmed)
_PRODUCT_PAGE_BASE = "https://tigertag.io/pages/product-infos"
_API_PRODUCT_BASE = "https://api.tigertag.io/api:tigertag/product/get"
# Fields covered by the ECDSA signature — must never be modified after signing.
_PROTECTED_FIELDS: frozenset = frozenset({
"id_tigertag", "id_product", "uid", "signature_r", "signature_s", "_db",
})
# ══════════════════════════════════════════════════════════════════════════════
# DATABASE SYNC
# ══════════════════════════════════════════════════════════════════════════════
def sync_databases(
db_path: Path,
force: bool = False,
verbose: bool = True,
) -> List[str]:
"""
Download or update TigerTag reference JSON databases.
Tries the live TigerTag API first; falls back to the GitHub mirror if the
API is unreachable. Only downloads files whose timestamp has changed.
Args:
db_path : Folder where JSON files are stored (created if missing).
force : Re-download all files even if already up to date.
verbose : Print progress to stdout.
Returns:
List of filenames that were downloaded/updated.
Raises:
RuntimeError : if both API and GitHub mirror are unreachable.
ImportError : if 'requests' is not installed.
Example:
sync_databases(Path("./database"))
"""
if not _REQUESTS_AVAILABLE:
raise ImportError(
"Database sync requires 'requests'.\n"
"Install it with: pip install requests"
)
db_path = Path(db_path)
db_path.mkdir(parents=True, exist_ok=True)
last_update_path = db_path / "last_update.json"
def _get(url: str):
r = _requests.get(url, timeout=_HTTP_TIMEOUT)
r.raise_for_status()
return r.json(), r.text
def _log(msg: str):
if verbose:
print(msg)
# Pick source: API first, GitHub fallback
try:
remote_data, remote_text = _get(f"{_API_BASE}/all/last_update")
source = "api"
def _dataset_url(endpoint: str, filename: str) -> str:
return f"{_API_BASE}/{endpoint}"
except Exception as exc:
_log(f"[warn] TigerTag API unreachable ({exc}), falling back to GitHub mirror")
try:
remote_data, remote_text = _get(f"{_GITHUB_RAW_BASE}/last_update.json")
except Exception as exc2:
raise RuntimeError(
f"Both API and GitHub mirror are unreachable.\n"
f"API error: {exc}\n"
f"GitHub error: {exc2}\n"
f"Check your internet connection."
) from exc2
source = "github"
def _dataset_url(endpoint: str, filename: str) -> str:
return f"{_GITHUB_RAW_BASE}/{filename}"
_log(f"[info] source: {source}")
# Load local timestamps
local_data: Dict = {}
if last_update_path.exists():
try:
local_data = json.loads(last_update_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
updated: List[str] = []
for key, (endpoint, filename) in _DATASETS.items():
remote_ts = remote_data.get(key)
local_ts = local_data.get(key)
local_file = db_path / filename
if remote_ts is None:
_log(f"[skip] {key}: not in last_update payload")
continue
if not force and remote_ts == local_ts and local_file.exists():
_log(f"[ok] {filename}: up to date")
continue
_log(f"[sync] {filename}: {local_ts} → {remote_ts}")
r = _requests.get(_dataset_url(endpoint, filename), timeout=_HTTP_TIMEOUT)
r.raise_for_status()
data = r.json()
local_file.write_text(
json.dumps(data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
updated.append(filename)
if updated or local_data != remote_data:
last_update_path.write_text(remote_text, encoding="utf-8")
if "last_update.json" not in updated:
updated.append("last_update.json")
return updated
# ══════════════════════════════════════════════════════════════════════════════
# DATABASE LOADER
# ══════════════════════════════════════════════════════════════════════════════
class TigerTagDB:
"""
Loads and exposes TigerTag JSON reference databases.
All ID lookups return the full JSON entry dict (or None if not found).
The JSON files are the single source of truth — no hardcoded ID mappings.
Args:
db_path : Folder containing the JSON files.
auto_sync : Download missing/stale files automatically (requires requests).
verbose : Print sync progress.
Example:
db = TigerTagDB(Path("./database"), auto_sync=True)
mat = db.material(38219)
print(mat["label"]) # "PLA"
print(mat["density"]) # 1.24
"""
REQUIRED_FILES = list(_DATASETS.values()) # list of (endpoint, filename) tuples
def __init__(
self,
db_path: Path = None,
auto_sync: bool = True,
verbose: bool = True,
):
self._path = Path(db_path) if db_path else Path(__file__).parent / "database"
self._auto_sync = auto_sync
self._verbose = verbose
self._ensure_db()
self._versions = self._load("id_version.json")
self._materials = self._load("id_material.json")
self._aspects = self._load("id_aspect.json")
self._types = self._load("id_type.json")
self._diameters = self._load("id_diameter.json")
self._brands = self._load("id_brand.json")
self._units = self._load("id_measure_unit.json")
def _ensure_db(self) -> None:
"""Check for missing files; auto-sync or print clear error."""
missing = [fn for _, fn in self.REQUIRED_FILES if not (self._path / fn).exists()]
if not missing:
return
if self._auto_sync and _REQUESTS_AVAILABLE:
print(f"[info] Missing {len(missing)} database file(s) — downloading now...")
try:
sync_databases(self._path, verbose=self._verbose)
return
except Exception as exc:
print(f"[warn] Auto-sync failed: {exc}", file=sys.stderr)
# Still missing after sync attempt (or auto_sync=False / no requests)
missing_still = [fn for _, fn in self.REQUIRED_FILES if not (self._path / fn).exists()]
if not missing_still:
return
print("", file=sys.stderr)
print("❌ TigerTag database files not found.", file=sys.stderr)
print(f" Expected folder: {self._path.resolve()}", file=sys.stderr)
print("", file=sys.stderr)
print(" Missing files:", file=sys.stderr)
for fn in missing_still:
print(f" • {fn}", file=sys.stderr)
print("", file=sys.stderr)
if not _REQUESTS_AVAILABLE:
print(" ⚠️ 'requests' is not installed — cannot auto-download.", file=sys.stderr)
print(" Install it first: pip install requests", file=sys.stderr)
print("", file=sys.stderr)
print(" ➜ Run: python parse_tigertag.py --sync-only", file=sys.stderr)
print("", file=sys.stderr)
sys.exit(1)
def _load(self, filename: str) -> List[Dict]:
fp = self._path / filename
if not fp.exists():
return []
with open(fp, encoding="utf-8") as f:
return json.load(f)
def _find(self, table: List[Dict], id_value: int) -> Optional[Dict]:
return next((e for e in table if e.get("id") == id_value), None)
def sync(self, force: bool = False) -> List[str]:
"""Manually trigger a database update. Returns list of updated files."""
updated = sync_databases(self._path, force=force, verbose=self._verbose)
# Reload updated files
self._versions = self._load("id_version.json")
self._materials = self._load("id_material.json")
self._aspects = self._load("id_aspect.json")
self._types = self._load("id_type.json")
self._diameters = self._load("id_diameter.json")
self._brands = self._load("id_brand.json")
self._units = self._load("id_measure_unit.json")
return updated
# ── Lookups (return full JSON entry or None) ──────────────────────────────
def version(self, id_value: int) -> Optional[Dict]:
"""id_version.json — includes public_key for signature verification."""
return self._find(self._versions, id_value)
def material(self, id_value: int) -> Optional[Dict]:
"""id_material.json — includes density, recommended temps, bambuID…"""
return self._find(self._materials, id_value)
def aspect(self, id_value: int) -> Optional[Dict]:
"""id_aspect.json — includes color_count."""
return self._find(self._aspects, id_value)
def type_(self, id_value: int) -> Optional[Dict]:
"""id_type.json."""
return self._find(self._types, id_value)
def diameter(self, id_value: int) -> Optional[Dict]:
"""id_diameter.json."""
return self._find(self._diameters, id_value)
def brand(self, id_value: int) -> Optional[Dict]:
"""id_brand.json."""
return self._find(self._brands, id_value)
def unit(self, id_value: int) -> Optional[Dict]:
"""id_measure_unit.json."""
return self._find(self._units, id_value)
@staticmethod
def label(entry: Optional[Dict]) -> str:
"""Safe label from any DB entry dict."""
if entry is None:
return "Unknown"
return entry.get("label") or entry.get("name") or "Unknown"
# ══════════════════════════════════════════════════════════════════════════════
# API DIFF
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class ApiDiff:
"""
A single field difference between chip data and the TigerTag+ cloud API.
Returned by TigerTag.diff_api().
Attributes:
field : Field name (e.g. "nozzle_min").
chip_value : Value currently stored on the chip.
api_value : Value returned by the cloud API.
Example:
from parse_tigertag import ApiDiff, TigerTag
diffs = tag.diff_api()
for d in diffs:
print(f"{d.field}: chip={d.chip_value!r} → api={d.api_value!r}")
"""
field: str
chip_value: Any
api_value: Any
def __repr__(self) -> str:
return f" {self.field}: chip={self.chip_value!r} → api={self.api_value!r}"
# ══════════════════════════════════════════════════════════════════════════════
# SIGNATURE RESULT
# ══════════════════════════════════════════════════════════════════════════════
class SignatureResult:
"""
Result of an ECDSA signature verification.
Attributes:
status : One of the class constants (VALID, INVALID, UNSIGNED, …)
ok : True only when status == VALID
detail : Human-readable explanation for failures
Example:
result = tag.verify()
if result.ok:
print("Authentic TigerTag")
else:
print(f"Problem: {result}")
"""
VALID = "valid" # ✅ signature present and cryptographically correct
INVALID = "invalid" # ❌ signature present but verification failed
UNSIGNED = "unsigned" # ⬜ no signature (all zeros in pages 0x18-0x27)
NO_CRYPTO = "no_crypto" # ⚠️ 'cryptography' package not installed
NO_KEY = "no_key" # ⚠️ public key missing from id_version.json
NO_UID = "no_uid" # ⚠️ UID unavailable (partial dump, not 180 bytes)
_ICONS = {
VALID: "✅ VALID",
INVALID: "❌ INVALID",
UNSIGNED: "⬜ NOT SIGNED",
NO_CRYPTO: "⚠️ cryptography not installed — run: pip install cryptography",
NO_KEY: "⚠️ public key not found in id_version.json",
NO_UID: "⚠️ UID unavailable — provide a full 180-byte chip dump",
}
def __init__(self, status: str, detail: str = ""):
self.status = status
self.detail = detail
self.ok = (status == self.VALID)
def __str__(self) -> str:
base = self._ICONS.get(self.status, f"? {self.status}")
return f"{base} {self.detail}".rstrip()
def __repr__(self) -> str:
return f"SignatureResult(status={self.status!r}, ok={self.ok})"
def to_dict(self) -> Dict:
return {"status": self.status, "ok": self.ok, "detail": self.detail}
# ══════════════════════════════════════════════════════════════════════════════
# TIGERTAG — MAIN CLASS
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class TigerTag:
"""
TigerTag chip payload — full CRUD interface.
All fields are plain integers/bytes/strings. Use a TigerTagDB instance
(via .db property or pass one to to_dict()) to get human-readable labels.
Create:
tag = TigerTag.create(id_material=38219, nozzle_temp_min=190, ...)
chip.write_pages(4, tag.to_bytes())
Read:
tag = TigerTag.from_pages(uid, payload)
tag = TigerTag.from_dump(data)
tag = TigerTag.from_file("dump.bin")
Update (surgical, immutable):
new_tag = tag.patch(dry_temp=55, nozzle_temp_max=240)
Update (auto-sync from cloud API — TigerTag+ only):
new_tag, applied = tag.patch_from_api()
Init (mark chip as reserved without full programming):
chip.write_pages(4, TigerTag.as_init().to_bytes())
Delete (wipe back to blank):
chip.write_pages(4, TigerTag.erase())
"""
# ── Identity ──────────────────────────────────────────────────────────────
id_tigertag : int # u32 BE — format/version identifier (see id_version.json)
id_product : int # u32 BE — 0xFFFFFFFF=Maker, 0=Init, else cloud product ID
# ── Material (all IDs resolve via TigerTagDB) ──────────────────────────────
id_material : int # u16 BE — see id_material.json
id_aspect_1 : int # u8 — see id_aspect.json
id_aspect_2 : int # u8 — see id_aspect.json
id_type : int # u8 — see id_type.json (0x8E=Filament, 0xAD=Resin)
id_diameter : int # u8 — see id_diameter.json (0x38=1.75mm, 0xDD=2.85mm)
id_brand : int # u16 BE — see id_brand.json
# ── Colors ─────────────────────────────────────────────────────────────────
color1_r : int # Color 1 Red (page 0x08)
color1_g : int # Color 1 Green
color1_b : int # Color 1 Blue
color1_a : int # Color 1 Alpha
color2_r : int # Color 2 Red (page 0x0D)
color2_g : int # Color 2 Green
color2_b : int # Color 2 Blue
color3_r : int # Color 3 Red (page 0x0E)
color3_g : int # Color 3 Green
color3_b : int # Color 3 Blue
# ── Quantity ───────────────────────────────────────────────────────────────
measure : int # u24 BE — quantity at manufacturing
id_unit : int # u8 — see id_measure_unit.json
measure_available : int # u24 BE — remaining (updated by Tiger Scale)
# ── Temperatures (°C) ─────────────────────────────────────────────────────
nozzle_temp_min : int # u16 BE — minimum nozzle temperature
nozzle_temp_max : int # u16 BE — maximum nozzle temperature
dry_temp : int # u8
dry_time : int # u8 hours
bed_temp_min : int # u8
bed_temp_max : int # u8
# ── Traceability ──────────────────────────────────────────────────────────
timestamp : int # u32 BE — seconds since 2000-01-01 GMT + twin tag pairing ID
custom_message : str # UTF-8, max 28 bytes (emoji allowed)
# ── HueForge ──────────────────────────────────────────────────────────────
td_raw : int # u16 BE — actual TD = td_raw / 10 (0=undefined, 1-1000 valid)
# ── Signature (optional, pages 0x18-0x27) ─────────────────────────────────
signature_r : bytes = field(default_factory=lambda: bytes(32))
signature_s : bytes = field(default_factory=lambda: bytes(32))
# ── Chip UID (auto-extracted from full 180-byte dump, else None) ───────────
uid : Optional[bytes] = field(default=None)
# ── Internal: lazily loaded DB ────────────────────────────────────────────
_db : Optional[TigerTagDB] = field(default=None, repr=False, compare=False)
# ── Derived properties ────────────────────────────────────────────────────
@property
def is_maker(self) -> bool:
"""True when id_product == 0xFFFFFFFF (offline Maker tag)."""
return self.id_product == MAKER_PRODUCT_ID
@property
def is_init(self) -> bool:
"""True when id_product == 0x00000000 (blank/uninitialized tag)."""
return self.id_product == INIT_PRODUCT_ID
@property
def is_plus(self) -> bool:
"""True when the tag has a cloud product ID (TigerTag+)."""
return not self.is_maker and not self.is_init
@property
def is_signed(self) -> bool:
"""True when the tag carries an ECDSA signature (pages 0x18-0x27 non-zero)."""
return self.signature_r != bytes(32) or self.signature_s != bytes(32)
@property
def uid_hex(self) -> Optional[str]:
"""UID as uppercase hex string (e.g. '04AABBCCDDEE11'), or None."""
return self.uid.hex().upper() if self.uid else None
@property
def td_value(self) -> float:
"""HueForge TD as float. 0.0=undefined, valid range 0.1–100.0."""
return self.td_raw / 10.0
@property
def manufacturing_date(self) -> datetime:
"""Manufacturing timestamp as UTC datetime."""
return datetime.fromtimestamp(
_TIGERTAG_EPOCH.timestamp() + self.timestamp,
tz=timezone.utc,
)
@property
def color1_hex(self) -> str:
"""Primary color as #RRGGBB hex string."""
return f"#{self.color1_r:02X}{self.color1_g:02X}{self.color1_b:02X}"
@property
def color2_hex(self) -> str:
"""Secondary color as #RRGGBB hex string."""
return f"#{self.color2_r:02X}{self.color2_g:02X}{self.color2_b:02X}"
@property
def color3_hex(self) -> str:
"""Tertiary color as #RRGGBB hex string."""
return f"#{self.color3_r:02X}{self.color3_g:02X}{self.color3_b:02X}"
@property
def stock_percent(self) -> Optional[float]:
"""Remaining material as a percentage, or None if measure is zero."""
if self.measure == 0:
return None
return round((self.measure_available / self.measure) * 100, 1)
@property
def product_page_url(self) -> Optional[str]:
"""Public product page URL (TigerTag+ only, None otherwise)."""
if self.is_maker or self.is_init:
return None
return f"{_PRODUCT_PAGE_BASE}/{self.id_product}"
@property
def api_url(self) -> Optional[str]:
"""Direct API URL returning the full enriched product JSON (TigerTag+ only)."""
if self.is_maker or self.is_init:
return None
uid_part = f"uid={int(self.uid_hex, 16)}&" if self.uid_hex else ""
return f"{_API_PRODUCT_BASE}?{uid_part}product_id={self.id_product}"
# ── Database ──────────────────────────────────────────────────────────────
@property
def db(self) -> TigerTagDB:
"""Lazily loaded database (auto-downloads if needed)."""
if self._db is None:
self._db = TigerTagDB()
return self._db
def sync_db(self, db_path: Path = None, force: bool = False) -> List[str]:
"""Download or update reference databases. Returns list of updated files."""
path = Path(db_path) if db_path else Path(__file__).parent / "database"
self._db = TigerTagDB(path, auto_sync=True)
return self._db.sync(force=force)
# ── Cloud API (TigerTag+ only) ────────────────────────────────────────────
def raw_api(self, timeout: int = 5) -> Optional[Dict[str, Any]]:
"""
Fetch the raw TigerTag+ cloud product data from the API.
Returns the unmodified API JSON as a Python dict.
Only meaningful for TigerTag+ chips (returns None for Maker/Init tags).
Uses stdlib urllib — no extra dependency required.
Args:
timeout : Request timeout in seconds (default: 5).
Returns:
Raw API response dict, or None if not a TigerTag+ chip.
Raises:
RuntimeError : If the network request fails.
Example:
data = tag.raw_api()
if data:
print(data["title"])
"""
if self.is_maker or self.is_init:
return None
import json as _json
import urllib.error
import urllib.request
try:
with urllib.request.urlopen(self.api_url, timeout=timeout) as resp:
return _json.loads(resp.read().decode("utf-8"))
except urllib.error.URLError as exc:
raise RuntimeError(
f"TigerTag+ API request failed ({exc}). "
f"Verify network access or browse: {self.product_page_url}"
) from exc
def diff_api(
self,
api_data: Optional[Dict[str, Any]] = None,
db: Optional[TigerTagDB] = None,
) -> List[ApiDiff]:
"""
Compare chip data against the TigerTag+ cloud API.
Returns a list of ApiDiff entries for every field whose value on the chip
differs from what the API currently reports. Empty list = fully in sync.
Args:
api_data : Pre-fetched result of raw_api(). Fetched automatically when None.
db : Optional TigerTagDB.
Returns:
List of ApiDiff. Empty = in sync.
Raises:
RuntimeError : If api_data is None and the network request fails.
Example:
diffs = tag.diff_api()
for d in diffs:
print(d)
"""
if self.is_maker or self.is_init:
return []
_db = db or self.db
data = api_data if api_data is not None else self.raw_api()
if not data:
return []
diffs: List[ApiDiff] = []
def _lbl(entry: Any) -> str:
return (TigerTagDB.label(entry) or "").strip().lower()
def _check(fname: str, chip_val: Any, api_val: Any) -> None:
if api_val is None:
return
if str(chip_val).strip().lower() != str(api_val).strip().lower():
diffs.append(ApiDiff(fname, chip_val, api_val))
fil = data.get("filament") or {}
nozzle = data.get("nozzle") or {}
bed = data.get("bed") or {}
dryer = data.get("dryer") or {}
# Temperatures
_check("nozzle_min", self.nozzle_temp_min, nozzle.get("temp_min"))
_check("nozzle_max", self.nozzle_temp_max, nozzle.get("temp_max"))
_check("bed_min", self.bed_temp_min, bed.get("temp_min"))
_check("bed_max", self.bed_temp_max, bed.get("temp_max"))
_check("dry_temp", self.dry_temp, dryer.get("temp"))
_check("dry_time", self.dry_time, dryer.get("time"))
# Material identification
_check("type", _lbl(_db.type_(self.id_type)), (data.get("product_type") or "").lower())
_check("material", _lbl(_db.material(self.id_material)), (fil.get("material") or "").lower())
_check("brand", _lbl(_db.brand(self.id_brand)), (data.get("brand") or "").lower())
_check("diameter", TigerTagDB.label(_db.diameter(self.id_diameter)) or "",
str(fil.get("diameter") or ""))
_EMPTY_ASPECT = {"", "unknown", "-", "none"}
def _check_aspect(fname: str, chip_id: int, api_val: Optional[str]) -> None:
chip_lbl = _lbl(_db.aspect(chip_id))
api_norm = (api_val or "").strip().lower()
if chip_lbl in _EMPTY_ASPECT and api_norm in _EMPTY_ASPECT:
return
if chip_lbl != api_norm:
diffs.append(ApiDiff(fname, chip_lbl or "none", api_val or "none"))
_check_aspect("aspect_1", self.id_aspect_1, fil.get("aspect1"))
_check_aspect("aspect_2", self.id_aspect_2, fil.get("aspect2"))
# Colors
def _parse_api_color(hex_str: str) -> Optional[Tuple[int, int, int, int]]:
h = (hex_str or "").lstrip("#")
try:
if len(h) == 8:
return int(h[0:2],16), int(h[2:4],16), int(h[4:6],16), int(h[6:8],16)
if len(h) == 6:
return int(h[0:2],16), int(h[2:4],16), int(h[4:6],16), 255
except ValueError:
pass
return None
api_colors: List[str] = []
color_info = fil.get("color_info") or {}
if color_info.get("colors"):
api_colors = [c for c in color_info["colors"] if c]
elif fil.get("color"):
api_colors = [fil["color"]]
if api_colors:
c = _parse_api_color(api_colors[0])
if c:
chip_hex = f"#{self.color1_r:02X}{self.color1_g:02X}{self.color1_b:02X}{self.color1_a:02X}"
api_hex = f"#{c[0]:02X}{c[1]:02X}{c[2]:02X}{c[3]:02X}"
if chip_hex.lower() != api_hex.lower():
diffs.append(ApiDiff("color_1", chip_hex, api_hex))
if len(api_colors) > 1:
c = _parse_api_color(api_colors[1])
if c:
chip_hex = f"#{self.color2_r:02X}{self.color2_g:02X}{self.color2_b:02X}"
api_hex = f"#{c[0]:02X}{c[1]:02X}{c[2]:02X}"
if chip_hex.lower() != api_hex.lower():
diffs.append(ApiDiff("color_2", chip_hex, api_hex))
if len(api_colors) > 2:
c = _parse_api_color(api_colors[2])
if c:
chip_hex = f"#{self.color3_r:02X}{self.color3_g:02X}{self.color3_b:02X}"
api_hex = f"#{c[0]:02X}{c[1]:02X}{c[2]:02X}"
if chip_hex.lower() != api_hex.lower():
diffs.append(ApiDiff("color_3", chip_hex, api_hex))
if fil.get("grams") is not None:
_check("measure_g", self.measure, int(fil["grams"]))
if fil.get("measure_unit"):
_check("measure_unit",
TigerTagDB.label(_db.unit(self.id_unit)) or "",
(fil["measure_unit"] or "").strip())
return diffs
def patch(self, **kwargs: Any) -> "TigerTag":
"""
Return a new TigerTag with selected fields replaced (immutable).
Protected fields (id_tigertag, id_product, uid, signature_r, signature_s)
are covered by the ECDSA signature and cannot be modified.
Args:
**kwargs: Field names and their new values.
Returns:
A new TigerTag instance with the requested fields updated.
The original instance is unchanged.
Raises:
ValueError: If any protected or unknown field is requested.
Example:
updated = tag.patch(nozzle_temp_min=200, dry_temp=55)
"""
protected = set(kwargs.keys()) & _PROTECTED_FIELDS
if protected:
raise ValueError(
f"Cannot modify protected field(s): {', '.join(sorted(protected))}. "
"These fields are covered by the ECDSA signature and must never change."
)
valid = {f.name for f in _dc_fields(self)} - _PROTECTED_FIELDS
unknown = set(kwargs.keys()) - valid
if unknown:
raise ValueError(
f"Unknown field(s): {', '.join(sorted(unknown))}. "
f"Valid patchable fields: {', '.join(sorted(valid))}"
)
return _dc_replace(self, **kwargs)
def patch_from_api(
self,
api_data: Optional[Dict[str, Any]] = None,
db: Optional[TigerTagDB] = None,
) -> Tuple["TigerTag", List[ApiDiff]]:
"""
Apply API-sourced field updates surgically, without touching the signature.
Fetches current product data from the TigerTag+ cloud API (or uses
api_data if supplied), computes the diff, and patches all numeric fields
that differ (temperatures, drying parameters, weight).
Args:
api_data : Pre-fetched API dict. If None, calls raw_api().
db : Override the database used for label resolution.
Returns:
(updated_tag, applied_diffs) — a patched TigerTag and the list of
ApiDiff entries that were applied. Returns (self, []) for Maker/Init.
Raises:
RuntimeError: If the network request fails (only when api_data is None).
Example:
new_tag, applied = tag.patch_from_api()
if applied:
print(f"Updated {len(applied)} field(s).")
chip.write_pages(4, new_tag.to_bytes())
"""
if self.is_maker or self.is_init:
return self, []
_db = db or self.db
data = api_data if api_data is not None else self.raw_api()
if not data:
return self, []
diffs = self.diff_api(api_data=data, db=_db)
if not diffs:
return self, []