Repository navigation
Expand file tree
/
Copy pathextra_scripts.py
More file actions
124 lines (115 loc) · 6.17 KB
/
Copy pathextra_scripts.py
File metadata and controls
124 lines (115 loc) · 6.17 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
"""
LuxDMX pre-build script.
Converts src/pages/*.html and src/assets/*.{png,css} into C PROGMEM headers
under src/generated/ — runs at script-load time (before compilation).
Also writes src/generated/version.h from the LUXDMX_VERSION env var.
"""
Import("env")
import os
import sys
import gzip
import pathlib
import subprocess
def escape_c(s: str) -> str:
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\r", "")
# Large static pages are gzip-compressed (served with Content-Encoding: gzip)
# to slash per-connection heap/airtime. They must contain no {{placeholders}}
# (dynamic values are fetched client-side from /info.json).
GZIP_PAGES = {"index", "config", "rdm", "bridge", "remote"}
def html_to_header(path: pathlib.Path, out_dir: pathlib.Path, version: str, nav_html: str = ""):
var = path.stem.upper().replace("-", "_").replace(".", "_") + "_HTML"
out = out_dir / (path.stem + "_html.h")
# Cache-bust static asset URLs (?v=__FWVER__) with the build's firmware version so a
# new firmware always serves fresh css/logo/favicon while still caching them hard.
content = path.read_text(encoding="utf-8").replace("__FWVER__", version)
# Inject the one shared navbar fragment (src/pages/_nav.html) at its marker, so every
# page carries the identical bar without maintaining three copies.
content = content.replace("<!--NAVBAR-->", nav_html)
if path.stem in GZIP_PAGES:
gz = gzip.compress(content.encode("utf-8"), compresslevel=9)
rows = [" " + ", ".join(f"0x{b:02x}" for b in gz[i:i+16]) + ","
for i in range(0, len(gz), 16)]
h = f"// Auto-generated from {path.name} (gzip) — do not edit\n"
h += f"static const uint8_t {var}[] PROGMEM = {{\n"
h += "\n".join(rows) + "\n};\n"
h += f"static const size_t {var}_LEN = {len(gz)};\n"
out.write_text(h, encoding="utf-8")
print(f" [embed] {path.name} -> {out.name} gzip {len(content.encode('utf-8'))} -> {len(gz)} bytes")
return
lines = content.split("\n")
body = "\n".join(f' "{escape_c(l)}\\n"' for l in lines)
h = f"// Auto-generated from {path.name} — do not edit\n"
h += f"static const char {var}[] PROGMEM =\n{body};\n"
out.write_text(h, encoding="utf-8")
print(f" [embed] {path.name} -> {out.name} ({len(content)} chars)")
def binary_to_header(path: pathlib.Path, out_dir: pathlib.Path, type_suffix: str):
data = path.read_bytes()
safe = path.stem.upper().replace("-", "_").replace(".", "_")
var = safe + "_" + type_suffix
rows = [" " + ", ".join(f"0x{b:02x}" for b in data[i:i+16]) + ","
for i in range(0, len(data), 16)]
h = f"// Auto-generated from {path.name} — do not edit\n"
h += f"static const uint8_t {var}[] PROGMEM = {{\n"
h += "\n".join(rows) + "\n};\n"
h += f"static const size_t {var}_LEN = {len(data)};\n"
out_name = path.stem.replace(".", "_") + "_" + type_suffix.lower() + ".h"
out = out_dir / out_name
out.write_text(h, encoding="utf-8")
print(f" [embed] {path.name} -> {out.name} ({len(data)} bytes)")
def generate_config_templates(root: pathlib.Path, gen_dir: pathlib.Path):
"""Embed templates/*.ini into src/generated/config_templates.gen.h (the board
default values the config engine applies). Single source of truth = the .ini
files; see tools/gen_config_templates.py. The header is pulled into the build by
the committed wrapper src/config_templates_gen.cpp. Emitting a *header* (not a
.cpp) is deliberate: PlatformIO globs src/ before this script runs, so a
generated source file is absent from a clean first build's glob and the link
fails with 'undefined reference to CONFIG_TEMPLATES'. Every other generated
asset here is already a header for the same reason."""
script = root / "tools" / "gen_config_templates.py"
out = gen_dir / "config_templates.gen.h"
# Drop the pre-split generated .cpp if an older build left one behind, so it
# can't be globbed alongside the wrapper and double-define CONFIG_TEMPLATES.
(gen_dir / "config_templates.cpp").unlink(missing_ok=True)
subprocess.run([sys.executable, str(script), str(root), str(out)], check=True)
def generate_version(gen_dir: pathlib.Path) -> str:
version = os.environ.get("LUXDMX_VERSION", "dev")
(gen_dir / "version.h").write_text(
f'static const char FIRMWARE_VERSION[] = "{version}";\n',
encoding="utf-8"
)
print(f" [version] FIRMWARE_VERSION = {version}")
return version
def generate():
root = pathlib.Path(env.subst("$PROJECT_DIR"))
gen_dir = root / "src" / "generated"
gen_dir.mkdir(exist_ok=True)
print("LuxDMX: generating embedded assets...")
generate_config_templates(root, gen_dir)
version = generate_version(gen_dir)
# The shared navbar fragment (name starts with "_") is injected into every page, not served.
nav_file = root / "src" / "pages" / "_nav.html"
nav_html = nav_file.read_text(encoding="utf-8").replace("__FWVER__", version) if nav_file.exists() else ""
for f in sorted((root / "src" / "pages").glob("*.html")):
if f.stem.startswith("_"):
continue
html_to_header(f, gen_dir, version, nav_html)
for f in sorted((root / "src" / "assets").glob("*.png")):
binary_to_header(f, gen_dir, "PNG")
for f in sorted((root / "src" / "assets").glob("*.svg")):
binary_to_header(f, gen_dir, "SVG")
for f in sorted((root / "src" / "assets").glob("*.webp")):
binary_to_header(f, gen_dir, "WEBP")
for f in sorted((root / "src" / "assets").glob("*.css")):
# Gzip-compress CSS before embedding — reduces 232 KB bootstrap to ~40 KB
raw = f.read_bytes()
compressed = gzip.compress(raw, compresslevel=9)
# Write to a temp file with the original name so the header/variable
# names stay identical (BOOTSTRAP_MIN_CSS / bootstrap_min_css.h)
tmp = gen_dir / f.name
tmp.write_bytes(compressed)
binary_to_header(tmp, gen_dir, "CSS")
tmp.unlink()
print(f" [gzip] {f.name}: {len(raw)} -> {len(compressed)} bytes ({100*len(compressed)//len(raw)}%)")
print("LuxDMX: done.")
# Run immediately so headers exist before main.cpp is compiled
generate()