Repository navigation
Expand file tree
/
Copy pathparse_tigertag.py
More file actions
2516 lines (2124 loc) · 109 KB
/
Copy pathparse_tigertag.py
File metadata and controls
2516 lines (2124 loc) · 109 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) │ yes (full) │ create() │ — │
│ TigerTag Init │ yes (full) │ as_init() │ — │
│ TigerTag+ │ yes (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 Tag index / count u8 high nibble = index, low = count (0=unknown)
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("Error: 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(" Warning: '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: "NO CRYPTO — cryptography not installed, run: pip install cryptography",
NO_KEY: "NO PUBLIC KEY — not found in id_version.json",
NO_UID: "NO UID — 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}
def _https_context():
"""
SSL context for the TigerTag+ API calls.
Uses certifi's CA bundle when it is installed (it comes with ``requests``,
i.e. ``pip install "tigertag[sync]"``): the python.org macOS installer ships
without system CA certificates until "Install Certificates.command" is run,
and every HTTPS call then fails with CERTIFICATE_VERIFY_FAILED. Without
certifi, Python's default certificate store is used.
"""
import ssl
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except ImportError:
return ssl.create_default_context()
def _check_available(measure: int, measure_available: int) -> None:
"""
Refuse a remaining quantity above the initial quantity.
Checked whenever the SDK is about to produce chip bytes (``to_bytes``) or
change the quantities (``patch``). Reading a chip never raises: a chip that
already carries such values parses normally and :meth:`TigerTag.validate`
reports it. An initial quantity of 0 means "not set" and is not checked.
Raises:
ValueError: If ``measure > 0`` and ``measure_available > measure``.
"""
if measure > 0 and measure_available > measure:
raise ValueError(
f"measure_available ({measure_available}) cannot exceed the initial "
f"measure ({measure})."
)
def _encode_tag_info(tag_count: int, tag_index: int) -> int:
"""
Pack a tag count and a tag index into the ``tag_info`` byte (page 0x0D, +39).
High nibble = tag index, low nibble = tag count, so the hex reads like
"index/count" (``0x12`` = tag 1 of 2). Both must fit in 0–15.
Raises:
ValueError: If either value is outside 0–15.
"""
for name, value in (("tag_count", tag_count), ("tag_index", tag_index)):
if not isinstance(value, int) or not 0 <= value <= 15:
raise ValueError(
f"{name} must be an integer between 0 and 15 (got {value!r}). "
"0 = unknown; the value is stored in one nibble of page 0x0D byte 3."
)
return (tag_index << 4) | tag_count
# ══════════════════════════════════════════════════════════════════════════════
# TIGERTAG+ CATALOGUE (same as tigertag/catalog.py in the package)
# ══════════════════════════════════════════════════════════════════════════════
# The official catalogue (id_catalog.json, ~12 MB) is downloaded on first use and
# cached; it is never bundled. RFID_Data mapping, the same for every product type:
# data1 → id_diameter, data2/data3 → nozzle min/max, data4/data5 → dry temp/time,
# data6/data7 → bed min/max; null values → 0 (id_aspect2 null → 0x00 "(none)").
# refresh_catalog() forces an update (ETag / Last-Modified skip unchanged files);
# catalog_info() reports when the cached copy was fetched and how many products it has.
import gzip
import time
import urllib.error
import urllib.request
# Shared with the package's tigertag/db.py: offline switch, data dir, bundled copy.
# Here the bundled copy is the database/ folder next to this file.
BUNDLED_DB_PATH = Path(__file__).parent / "database"
def is_offline(flag: Optional[bool] = None) -> bool:
"""True when ``flag`` is set or ``TIGERTAG_OFFLINE`` is 1 / true / yes / on."""
env = os.environ.get("TIGERTAG_OFFLINE", "").strip().lower() in ("1", "true", "yes", "on")
return bool(flag) or env
def default_data_dir() -> Path:
"""``TIGERTAG_DATA_DIR``, else ``TIGERTAG_CACHE_DIR``, else the user cache directory."""
for var in ("TIGERTAG_DATA_DIR", "TIGERTAG_CACHE_DIR"):
if os.environ.get(var):
return Path(os.environ[var])
if sys.platform == "darwin":
return Path.home() / "Library" / "Caches" / "tigertag"
if os.name == "nt":
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
return Path(base) / "tigertag" / "Cache"
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
return Path(base) / "tigertag"
# ── Catalogue constants ────────────────────────────────────────────────────────
DEFAULT_CATALOG_URL = (
"https://raw.githubusercontent.com/TigerTag-Project/TigerTag-RFID-Guide/"
"refs/heads/main/database/id_catalog.json"
)
CATALOG_FILENAME = "id_catalog.json"
META_FILENAME = "id_catalog.meta.json" # url, fetched_at, checked_at, count, etag, last_modified
DEFAULT_MAX_AGE = 24 * 3600 # refresh the cached copy once a day
DEFAULT_TIMEOUT = 60 # seconds — the file is about 12 MB
BUNDLED_CATALOG = BUNDLED_DB_PATH / "id_catalog.json.gz" # fallback, refreshed at every release
ASPECT_NONE = 0 # no second aspect: 0x00 "(none)", as in the spec examples
Catalog = Dict[int, Dict[str, Any]]
# ── Data directory, offline switch, bundled copy ───────────────────────────────
def default_cache_dir() -> Path:
"""Where the downloaded catalogue is kept — the shared data dir (see :func:`default_data_dir`)."""
return default_data_dir()
def _gzip_mtime(path: Path) -> Optional[float]:
"""Time recorded in a gzip header (when the bundled catalogue content last changed)."""
try:
with open(path, "rb") as f:
head = f.read(8)
if head[:2] != b"\x1f\x8b":
return None
return float(int.from_bytes(head[4:8], "little")) or path.stat().st_mtime
except OSError:
return None
def read_catalog_file(path: Path) -> Catalog:
"""Read ``id_catalog.json`` or ``id_catalog.json.gz`` into ``{product_id: entry}``."""
raw = Path(path).read_bytes()
if str(path).endswith(".gz"):
raw = gzip.decompress(raw)
return _index(raw)
def _epoch(iso: Optional[str]) -> Optional[float]:
try:
return datetime.fromisoformat(iso).timestamp() if iso else None
except ValueError:
return None
def _local_copies(cache: Path) -> Dict[str, Tuple[Path, float]]:
"""Available local copies → ``{"downloaded"|"bundled": (path, content date)}``."""
found: Dict[str, Tuple[Path, float]] = {}
path = cache / CATALOG_FILENAME
if path.exists():
found["downloaded"] = (path, _epoch(_read_meta(cache).get("fetched_at")) or path.stat().st_mtime)
gz = BUNDLED_CATALOG
if gz.exists():
found["bundled"] = (gz, _gzip_mtime(gz) or 0.0)
return found
def _newest(copies: Dict[str, Tuple[Path, float]]) -> Optional[str]:
if not copies:
return None
# On a tie the downloaded copy wins (it may carry an ETag for conditional requests)
return max(copies, key=lambda k: (copies[k][1], k == "downloaded"))
# ── Download / cache ───────────────────────────────────────────────────────────
def _download(
url: str,
timeout: int,
etag: Optional[str] = None,
last_modified: Optional[str] = None,
) -> Optional[Tuple[bytes, Dict[str, Optional[str]]]]:
"""
Fetch ``url`` over HTTPS (certifi CA bundle when installed).
Sends ``If-None-Match`` / ``If-Modified-Since`` when known. Returns ``None``
when the server answers 304 Not Modified, else ``(body, {"etag", "last_modified"})``.
"""
headers = {"User-Agent": "tigertag-sdk-python"}
if etag:
headers["If-None-Match"] = etag
if last_modified:
headers["If-Modified-Since"] = last_modified
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout, context=_https_context()) as resp:
return resp.read(), {"etag": resp.headers.get("ETag"),
"last_modified": resp.headers.get("Last-Modified")}
except urllib.error.HTTPError as exc:
if exc.code == 304:
return None
raise
def _now_iso() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def _read_meta(cache: Path) -> Dict[str, Any]:
try:
return json.loads((cache / META_FILENAME).read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
def _write_meta(cache: Path, meta: Dict[str, Any]) -> None:
try:
(cache / META_FILENAME).write_text(json.dumps(meta, indent=2), encoding="utf-8")
except OSError:
pass
def _index(raw: bytes) -> Catalog:
data = json.loads(raw.decode("utf-8"))
if not isinstance(data, list):
raise ValueError("Catalogue JSON must be a list of products.")
return {int(e["id"]): e for e in data if isinstance(e, dict) and isinstance(e.get("id"), int)}
def load_catalog(
url: str = DEFAULT_CATALOG_URL,
cache_dir: Optional[Path] = None,
max_age: Optional[float] = DEFAULT_MAX_AGE,
force: bool = False,
timeout: int = DEFAULT_TIMEOUT,
offline: Optional[bool] = None,
) -> Catalog:
"""
Load the official TigerTag+ catalogue as ``{product_id: entry}``.
Uses the newest local copy — downloaded (in ``cache_dir``) or bundled with the
package — while it is younger than ``max_age``; otherwise downloads it (a
conditional request: an unchanged file is not downloaded again). Any download
failure falls back to the newest local copy.
Args:
url : Catalogue URL (defaults to the TigerTag-RFID-Guide ``main`` branch).
cache_dir : Where the downloaded JSON is kept (default: the shared data dir).
max_age : Seconds before a local copy is considered stale; ``None`` = never.
force : Check for a new version even when the local copy is fresh.
timeout : Download timeout in seconds.
offline : No network access (also ``TIGERTAG_OFFLINE=1``): the newest local copy.
Returns:
Dict mapping each product ID to its catalogue entry (``title``, ``brand``,
``sku``, ``barcode``, ``img_src``, ``RFID_Data``…).
Raises:
RuntimeError: No local copy at all and the download failed (or offline).
"""
cache = Path(cache_dir) if cache_dir else default_cache_dir()
path = cache / CATALOG_FILENAME
copies = _local_copies(cache)
best = _newest(copies)
if is_offline(offline):
if best is None:
raise RuntimeError(
"Offline mode is on and no TigerTag+ catalogue is available locally "
f"(no {path}, no bundled copy). Turn offline mode off to download it."
)
return read_catalog_file(copies[best][0])
if best is not None and not force:
if best == "downloaded":
age = time.time() - path.stat().st_mtime # restarted on every 304
else:
age = time.time() - copies["bundled"][1]
if max_age is None or age < max_age:
return read_catalog_file(copies[best][0])
meta = _read_meta(cache) if path.exists() else {}
use_validators = meta.get("url") == url and best == "downloaded"
try:
result = _download(url, timeout,
etag=meta.get("etag") if use_validators else None,
last_modified=meta.get("last_modified") if use_validators else None)
if result is None: # 304: the cached copy is current
catalog = _index(path.read_bytes())
meta.update(checked_at=_now_iso(), count=len(catalog))
_write_meta(cache, meta)
try:
os.utime(path) # restart the max_age clock
except OSError:
pass
return catalog
raw, headers = result
catalog = _index(raw) # validate before replacing the cache
except (urllib.error.URLError, OSError, ValueError) as exc:
if best is not None:
return read_catalog_file(copies[best][0]) # offline: newest local copy
raise RuntimeError(
f"Cannot download the TigerTag+ catalogue ({exc}) and no local copy exists "
f"in {cache}. Connect to the internet and retry, or download {url} and pass "
f"its folder as cache_dir."
) from exc
try:
cache.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_bytes(raw)
tmp.replace(path)
now = _now_iso()
_write_meta(cache, {"url": url, "fetched_at": now, "checked_at": now,
"count": len(catalog), "size": len(raw), **headers})
except OSError:
pass # a read-only cache must not prevent using the catalogue
return catalog
def refresh_catalog(
url: str = DEFAULT_CATALOG_URL,
cache_dir: Optional[Path] = None,
timeout: int = DEFAULT_TIMEOUT,
offline: Optional[bool] = None,
) -> Catalog:
"""
Force a catalogue update (same as ``load_catalog(force=True)``).
The cached copy's ``ETag`` / ``Last-Modified`` are sent, so an unchanged file
is not downloaded again (HTTP 304). On failure the newest local copy is returned.
Raises:
RuntimeError: Offline mode is on.
"""
if is_offline(offline):
raise RuntimeError(
"Offline mode is on (offline=True or TIGERTAG_OFFLINE=1): the catalogue cannot "
"be refreshed. Turn offline mode off to update it."
)
return load_catalog(url=url, cache_dir=cache_dir, force=True, timeout=timeout)
_BUNDLED_COUNT: Dict[float, int] = {}
def catalog_info(
cache_dir: Optional[Path] = None,
*,
data_dir: Optional[Path] = None,
offline: Optional[bool] = None,
) -> Dict[str, Any]:
"""
Describe the local catalogue copies without downloading anything.
Returns:
``source`` ("downloaded" or "bundled": the copy :func:`load_catalog` uses
offline), ``downloaded`` (a downloaded copy exists), ``path``, ``url``,
``fetched_at`` (when the copy in use was produced or downloaded), ``checked_at``,
``count``, ``size``, ``etag``, ``last_modified``, and ``bundled`` (the
package's copy: ``path``, ``date``).
Args:
cache_dir: Data dir to inspect (default: the SDK data dir). ``data_dir`` is an
alias, as in the JS SDK's ``catalogInfo({ dataDir, cacheDir })``.
offline: Accepted for symmetry with :func:`load_catalog`; this function only
reads local files, so it never uses the network either way.
"""
del offline # read-only: nothing to disable
cache = Path(data_dir or cache_dir) if (data_dir or cache_dir) else default_cache_dir()
path = cache / CATALOG_FILENAME
copies = _local_copies(cache)
best = _newest(copies)
info: Dict[str, Any] = {"downloaded": path.exists(), "path": str(path), "source": best}
if "bundled" in copies:
gz, date = copies["bundled"]
info["bundled"] = {"path": str(gz), "date": datetime.fromtimestamp(date, tz=timezone.utc)
.replace(microsecond=0).isoformat()}
if best == "downloaded":
meta = _read_meta(cache)
mtime = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc).replace(microsecond=0).isoformat()
info.update({
"url": meta.get("url"),
"fetched_at": meta.get("fetched_at") or mtime,
"checked_at": meta.get("checked_at") or mtime,
"count": meta.get("count"),
"size": meta.get("size") or path.stat().st_size,
"etag": meta.get("etag"),
"last_modified": meta.get("last_modified"),
})
if info["count"] is None: # cache written by hand: count it once
try:
info["count"] = len(_index(path.read_bytes()))
except ValueError:
pass
elif best == "bundled":
gz, date = copies["bundled"]
if date not in _BUNDLED_COUNT:
try:
_BUNDLED_COUNT[date] = len(read_catalog_file(gz))
except (OSError, ValueError):
_BUNDLED_COUNT[date] = 0
info.update({
"url": None, "fetched_at": info["bundled"]["date"], "checked_at": None,
"count": _BUNDLED_COUNT[date], "size": gz.stat().st_size,
"etag": None, "last_modified": None,
})
return info
# ── Entry → chip fields ────────────────────────────────────────────────────────
def catalog_entry(product_id: int, catalog: Optional[Catalog] = None) -> Dict[str, Any]:
"""
Return the catalogue entry for ``product_id`` (title, brand, sku, barcode,
img_src, RFID_Data…). Loads the catalogue when ``catalog`` is omitted.
Raises:
KeyError: The product ID is not in the catalogue.
"""
catalog = load_catalog() if catalog is None else catalog
try:
return catalog[int(product_id)]
except KeyError:
raise KeyError(
f"TigerTag+ product ID {product_id} is not in the official catalogue "
f"({len(catalog)} products). Check the ID on https://tigertag.io or refresh "
f"the catalogue with load_catalog(force=True)."
) from None
def parse_hex_color(value: str) -> Tuple[int, int, int, int]:
"""``"#RRGGBB"`` or ``"#RRGGBBAA"`` → ``(r, g, b, a)``; alpha defaults to 255."""
h = value.strip().lstrip("#")
if len(h) not in (6, 8):