-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathflash.py
More file actions
executable file
·1711 lines (1443 loc) · 66.1 KB
/
Copy pathflash.py
File metadata and controls
executable file
·1711 lines (1443 loc) · 66.1 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
#!/usr/bin/env python3
"""
RTNode-HeltecV4 Flash Utility
Flash the RTNode-HeltecV4 transport node firmware to a Heltec WiFi LoRa 32 V3 or V4.
No PlatformIO required — just Python 3 and a USB cable.
By default, downloads the latest Beta firmware from GitHub Releases (if newer than
the local cache) and flashes the app partition only, preserving bootloader,
partition table, NVS, and EEPROM settings. For reproducible flashing, the
script prefers the bundled esptool in Release/ over any host-installed copy.
Usage:
# Update firmware — V4 (default)
python flash.py
# Legacy alias for an app-only update flow
python flash.py --update
# Use a host-installed esptool instead of the bundled copy
python flash.py --use-system-esptool
# Update firmware — V3
python flash.py --board v3
# Flash a specific Beta release version
python flash.py --release v1.0.12
# Full flash with merged binary (overwrites everything)
python flash.py --full
# Flash a specific file (auto-detects merged vs app-only)
python flash.py --file firmware.bin
# Specify serial port manually
python flash.py --port /dev/ttyACM0
# Skip online check — use cached/local firmware only
python flash.py --offline
# Just build the merged binary (for GitHub Releases)
python flash.py --merge-only
"""
import argparse
import glob
import hashlib
import os
import platform
import shutil
import subprocess
import sys
import time
# ── Configuration ──────────────────────────────────────────────────────────────
VERSION = "1.0.18"
RELEASE_CHANNEL = "Beta"
RELEASE_NOTE = "lightly tested unless explicitly marked stable"
CHIP = "esp32s3"
FLASH_MODE = "qio" # Global default; overridden by board profile
FLASH_FREQ = "80m"
GITHUB_REPO = "jrl290/RTNode-HeltecV4"
# Runtime state (set automatically during main())
_flash_mode_override = None # CLI --flash-mode sets this; otherwise board profile wins
_detected_flash_size = None # Actual flash size read from device; overrides board profile
_esptool_write_verify_support = {}
# Flash addresses for ESP32-S3 Arduino framework
BOOTLOADER_ADDR = 0x0000
PARTITIONS_ADDR = 0x8000
BOOT_APP0_ADDR = 0xe000
APP_ADDR = 0x10000
# ── Board profiles ─────────────────────────────────────────────────────────────
# Each board defines its PIO env, flash size, baud rate, firmware binary name,
# and merged binary name.
# Single archive name released on GitHub — contains every board/flash-size variant.
FIRMWARE_ARCHIVE = "rtnode_firmware.zip"
# Conservative default when flash size can't be detected: 8MB firmware runs on
# any device (8MB or larger); a 16MB image on an 8MB device crashes at boot.
DEFAULT_FLASH_SIZE = "8MB"
BOARD_PROFILES = {
"v4": {
"name": "Heltec WiFi LoRa 32 V4",
"chip": "ESP32-S3", # matches esptool "Chip is ESP32-S3 ..."
"baud_rate": "921600",
# Image header is built as DIO (works on every ESP32-S3 flash variant).
# The IDF 2nd-stage bootloader auto-upgrades the SPI controller to QIO at
# runtime via bootloader_enable_qio_mode() when the chip's SFDP indicates
# support. Hard-coding qio here would brick boards whose flash isn't
# wired/strapped for QIO. Must match platformio.ini board_build.flash_mode.
"flash_mode": "dio",
"flash_variants": {
"16MB": {
"pio_env": "rtnode_heltec_v4",
"build_dir": ".pio/build/rtnode_heltec_v4",
"firmware_bin": "rtnode_heltec_v4.bin",
"merged_bin": "rtnode_heltec_v4_merged.bin",
},
},
},
"v3": {
"name": "Heltec WiFi LoRa 32 V3",
"chip": "ESP32", # matches esptool "Chip is ESP32 ..."
"baud_rate": "460800",
"flash_mode": "dio",
"flash_variants": {
"8MB": {
"pio_env": "rtnode_heltec_v3",
"build_dir": ".pio/build/rtnode_heltec_v3",
"firmware_bin": "rtnode_heltec_v3.bin",
"merged_bin": "rtnode_heltec_v3_merged.bin",
},
},
},
}
DEFAULT_BOARD = "v4"
# Active board profile (set in main() from --board arg)
_board = None
def board_profile():
return BOARD_PROFILES[_board or DEFAULT_BOARD]
def flash_variant():
"""Return the flash variant dict for the active board and detected flash size.
Falls back to the smallest (safest) available variant when the exact size is
unknown — a smaller-flash firmware runs on any larger device, but not vice versa.
"""
variants = board_profile()["flash_variants"]
size = _detected_flash_size or DEFAULT_FLASH_SIZE
if size in variants:
return variants[size]
# Fallback: smallest available variant
available = sorted(variants.keys(), key=lambda s: int(s.replace("MB", "")))
return variants[available[0]]
def BUILD_DIR():
return flash_variant()["build_dir"]
def MERGED_BIN():
"""Return the path to the pre-merged binary in the PlatformIO build dir."""
merged = flash_variant().get("merged_bin")
if not merged:
return None
return os.path.join(BUILD_DIR(), merged)
def find_local_firmware():
"""Look for pre-built firmware binaries adjacent to flash.py.
This is the primary path when the user has extracted the release ZIP.
Prefers the pre-merged binary (full-flash-ready, no merge step needed)
over the app-only binary.
Returns the path if found, or None.
"""
script_dir = os.path.dirname(os.path.abspath(__file__))
fv = flash_variant()
# Prefer merged binary — works for both full flash and app-only update
merged = fv.get("merged_bin")
if merged:
path = os.path.join(script_dir, merged)
if os.path.isfile(path):
return path
# Fall back to app-only binary
path = os.path.join(script_dir, fv["firmware_bin"])
if os.path.isfile(path):
return path
return None
def BOOTLOADER_BIN():
return os.path.join(BUILD_DIR(), "bootloader.bin")
def PARTITIONS_BIN():
return os.path.join(BUILD_DIR(), "partitions.bin")
def FIRMWARE_BIN():
return os.path.join(BUILD_DIR(), flash_variant()["firmware_bin"])
def FLASH_SIZE():
"""Return the effective flash size: detected from device, or conservative default."""
return _detected_flash_size or DEFAULT_FLASH_SIZE
def BAUD_RATE():
return board_profile()["baud_rate"]
def BOARD_FLASH_MODE():
"""Return the effective flash mode for the current board.
Priority: CLI override > board profile > global default.
"""
return _flash_mode_override or board_profile().get("flash_mode", FLASH_MODE)
def PIO_ENV():
return flash_variant()["pio_env"]
# ESP32 partition table magic bytes (first two bytes of a partition table entry)
PARTITION_TABLE_MAGIC = b'\xaa\x50'
PARTITION_TABLE_SIZE = 0xC00 # 3072 bytes
def is_merged_binary(firmware_path):
"""Check whether a firmware file is a merged binary (contains bootloader +
partition table) or an app-only binary.
Returns True for merged, False for app-only.
"""
try:
size = os.path.getsize(firmware_path)
if size > 0x8002:
with open(firmware_path, "rb") as f:
f.seek(0x8000)
return f.read(2) == PARTITION_TABLE_MAGIC
except Exception:
pass
return False
def extract_app_from_merged(merged_path):
"""Extract the app-only portion from a merged binary.
A merged binary starts at 0x0000 and includes bootloader, partition table,
boot_app0, and the app firmware. The region between the partition table
(0x8000-0x8BFF) and boot_app0 (0xE000) contains the NVS partition
(0x9000-0xDFFF) which is filled with 0xFF padding by esptool merge_bin.
Flashing a merged binary therefore wipes all saved settings.
This function extracts bytes from APP_ADDR (0x10000) to the end of the
file, producing an app-only binary that can be flashed at 0x10000 without
touching NVS/EEPROM.
Returns the path to the extracted app-only binary, or None on failure.
"""
try:
file_size = os.path.getsize(merged_path)
if file_size <= APP_ADDR:
print(f" Warning: Merged binary too small ({file_size} bytes) to contain app data.")
return None
with open(merged_path, "rb") as f:
f.seek(APP_ADDR)
app_data = f.read()
if not app_data:
return None
base, ext = os.path.splitext(merged_path)
app_path = f"{base}_app{ext}"
with open(app_path, "wb") as f:
f.write(app_data)
return app_path
except Exception as e:
print(f" Warning: Could not extract app from merged binary: {e}")
return None
def _find_in_platformio_or_release(build_path, release_name):
"""Find a file in the PlatformIO build output.
The Release/ directory no longer ships pre-built boot component binaries.
All boot components come from PlatformIO build output. Call
ensure_firmware_built() first to trigger a build when needed.
"""
if os.path.isfile(build_path):
return build_path
return None
# Forward-compatible aliases (these are now functions, not constants)
def _bootloader_bin():
return BOOTLOADER_BIN()
def _partitions_bin():
return PARTITIONS_BIN()
def _firmware_bin():
return FIRMWARE_BIN()
def find_boot_app0():
"""Find boot_app0.bin from PlatformIO framework packages.
Handles versioned package directories (e.g. framework-arduinoespressif32@3.20009.0).
"""
pio_dir = os.path.expanduser("~/.platformio/packages")
# Try exact name first
exact = os.path.join(pio_dir, "framework-arduinoespressif32",
"tools", "partitions", "boot_app0.bin")
if os.path.isfile(exact):
return exact
# Try versioned directories
if os.path.isdir(pio_dir):
for name in sorted(os.listdir(pio_dir), reverse=True):
if name.startswith("framework-arduinoespressif32"):
candidate = os.path.join(pio_dir, name, "tools", "partitions", "boot_app0.bin")
if os.path.isfile(candidate):
return candidate
return None
def find_bootloader():
"""Find bootloader.bin from PlatformIO build output or Release/ bundle."""
return _find_in_platformio_or_release(BOOTLOADER_BIN(), "bootloader.bin")
def find_partitions():
"""Find partitions.bin from PlatformIO build output or Release/ bundle."""
return _find_in_platformio_or_release(PARTITIONS_BIN(), "partitions.bin")
BOOT_APP0_BIN = find_boot_app0()
# ── Board auto-detection ───────────────────────────────────────────────────────
# Map chip type to board keys. Chip string comes from esptool "Chip is <type>".
# Sorted longest-first in detect_board so "ESP32-S3" wins over "ESP32".
_CHIP_TO_BOARD = {
"ESP32-S3": "v4",
"ESP32": "v3",
}
def read_flash_info(port, esptool_cmd):
"""Read device flash metadata using ``esptool.py flash_id``.
Returns ``(info_dict, None)`` on success, or ``(None, reason)`` on failure.
"""
cmd = esptool_cmd + ["--port", port, "flash_id"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
except subprocess.TimeoutExpired:
return None, "esptool timed out (device not responding?)"
except Exception as e:
return None, str(e)
output = result.stdout + result.stderr
if result.returncode != 0:
return None, f"esptool flash_id failed:\n{output.strip()}"
# Parse key fields
info = {}
for line in output.splitlines():
line = line.strip()
if line.startswith("Chip is "):
info["chip"] = line[len("Chip is "):]
elif line.startswith("Features:"):
info["features"] = line[len("Features:"):].strip()
elif line.startswith("Detected flash size:"):
info["flash_size"] = line.split(":")[-1].strip()
elif line.startswith("MAC:"):
info["mac"] = line.split(":")[-5:] # last 5 colon-groups
info["mac"] = line[len("MAC:"):].strip()
elif line.startswith("Crystal is"):
info["crystal"] = line[len("Crystal is"):].strip()
flash_size = info.get("flash_size")
if not flash_size:
return None, f"Could not parse flash size from esptool output:\n{output.strip()}"
return info, None
def detect_board(port, esptool_cmd):
"""Auto-detect which Heltec board is connected.
Uses chip type as the primary discriminator (ESP32-S3 → V4, ESP32 → V3),
so a V4 device with 8MB flash is correctly identified as V4, not V3.
Flash size is stored in the returned info dict and used to select the
correct firmware variant.
Returns a tuple (board_key, info_dict) on success, or (None, reason) on
failure. ``board_key`` is "v3" or "v4".
"""
info, err = read_flash_info(port, esptool_cmd)
if not info:
return None, err
chip_str = info.get("chip", "")
features = info.get("features", "")
if "ESP32-S3" in chip_str:
# Both V3 and V4 are ESP32-S3. Distinguish by PSRAM presence.
# V4 (ESP32-S3FH4R2): features includes "Embedded PSRAM"
# V3 (ESP32-S3FN8): features has no PSRAM entry
if "PSRAM" in features.upper():
board_key = "v4"
else:
board_key = "v3"
elif "ESP32" in chip_str:
board_key = "v3"
else:
return None, (
f"Unknown chip '{chip_str}' — expected ESP32-S3 (V3/V4) or ESP32.\n"
f"Use --board v3 or --board v4 to specify manually."
)
return board_key, info
# ── Helpers ────────────────────────────────────────────────────────────────────
def find_esptool(prefer_system=False):
"""Find esptool, preferring the bundled standalone binary for reproducibility.
Default search order:
1. Release/esptool/esptool (standalone binary — no Python/pyserial needed)
2. PlatformIO packaged esptool.py (dev environments)
3. Host-installed esptool (PATH / ~/.local/bin)
Pass ``prefer_system=True`` (--use-system-esptool) to move the host
installation to the front, useful when you want to use a newer system
esptool for debugging.
The standalone binary MUST remain first in repo_candidates.
"""
# Check if pyserial is available — needed for script-based (*.py) fallbacks
try:
import serial # noqa: F401
has_pyserial = True
except ImportError:
has_pyserial = False
# Platform-aware standalone binary name
exe_name = "esptool.exe" if platform.system() == "Windows" else "esptool"
script_dir = os.path.dirname(os.path.abspath(__file__))
# Two possible locations for the standalone binary:
# 1. <script_dir>/esptool/esptool — flat ZIP extraction (user-facing release)
# 2. <script_dir>/Release/esptool/esptool — git repo / nested ZIP
bundled_bin = (
os.path.join(script_dir, "esptool", exe_name)
if os.path.isfile(os.path.join(script_dir, "esptool", exe_name))
else os.path.join(script_dir, "Release", "esptool", exe_name)
)
pio_esptool = os.path.expanduser(
"~/.platformio/packages/tool-esptoolpy/esptool.py"
)
pio_python = os.path.expanduser("~/.platformio/penv/bin/python")
pio_python_cmd = pio_python if os.path.isfile(pio_python) and os.access(pio_python, os.X_OK) else sys.executable
repo_candidates = []
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# DO NOT CHANGE THIS ORDER.
# The bundled Release/esptool binary is INTENTIONALLY first.
# It is a platform-native standalone executable — no Python or pyserial
# required. Users flashing from the release archive get a consistent,
# pinned esptool regardless of what is installed on their machine.
# PlatformIO esptool.py is a fallback for dev environments only.
# NEVER reorder these lines. NEVER "prefer" PlatformIO over bundled.
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if os.path.isfile(bundled_bin) and os.access(bundled_bin, os.X_OK):
# Standalone binary — invoke directly, no Python interpreter prefix
repo_candidates.append(([bundled_bin], f"bundled esptool binary: {bundled_bin}"))
if has_pyserial and os.path.isfile(pio_esptool):
repo_candidates.append(([pio_python_cmd, pio_esptool], f"PlatformIO esptool: {pio_esptool}"))
system_candidates = []
if shutil.which("esptool.py"):
system_candidates.append((["esptool.py"], "system esptool.py from PATH"))
if shutil.which("esptool"):
system_candidates.append((["esptool"], "system esptool from PATH"))
for candidate in [
os.path.expanduser("~/.local/bin/esptool"),
os.path.expanduser("~/.local/bin/esptool.py"),
]:
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
system_candidates.append(([candidate], f"user-local esptool: {candidate}"))
search_order = system_candidates + repo_candidates if prefer_system else repo_candidates + system_candidates
for command, source in search_order:
print(f" Found {source}")
return command
if not has_pyserial and os.path.isfile(pio_esptool):
print("Found PlatformIO esptool.py but pyserial is not installed.")
print("Install it with: pip install pyserial")
print("Or place the standalone esptool binary at: Release/esptool/esptool")
sys.exit(1)
return None
def esptool_supports_write_verify(esptool_cmd):
"""Return True if this esptool build accepts ``write_flash --verify``.
esptool v5 removed ``--verify`` from write-flash, while older releases
still accept it. Probe once and cache the result so flashing can choose
the compatible verification path.
"""
cache_key = tuple(esptool_cmd)
if cache_key in _esptool_write_verify_support:
return _esptool_write_verify_support[cache_key]
try:
result = subprocess.run(
esptool_cmd + ["write_flash", "-h"],
capture_output=True,
text=True,
timeout=10,
)
output = (result.stdout or "") + (result.stderr or "")
supported = "--verify" in output
except Exception:
supported = False
_esptool_write_verify_support[cache_key] = supported
return supported
def find_serial_port():
"""List available serial ports and let the user choose."""
system = platform.system()
# Gather ports from glob patterns
if system == "Darwin":
patterns = ["/dev/cu.usbmodem*", "/dev/tty.usbmodem*",
"/dev/cu.usbserial*", "/dev/cu.SLAB*"]
elif system == "Linux":
patterns = ["/dev/ttyACM*", "/dev/ttyUSB*"]
else:
patterns = []
ports = []
for pattern in patterns:
ports.extend(glob.glob(pattern))
# Also try pyserial's port enumeration (works on all platforms including Windows)
try:
import serial.tools.list_ports
for port in serial.tools.list_ports.comports():
if port.device not in ports:
ports.append(port.device)
except ImportError:
pass
# Sort for consistent ordering
ports.sort()
if not ports:
return None
print("\nAvailable serial ports:")
for i, p in enumerate(ports):
print(f" [{i+1}] {p}")
print()
while True:
try:
choice = input(f"Select port [1-{len(ports)}]: ").strip()
idx = int(choice) - 1
if 0 <= idx < len(ports):
return ports[idx]
except (ValueError, EOFError):
pass
print("Invalid selection, try again.")
def sha256_file(path):
"""Compute SHA-256 hash of a file."""
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def _cache_dir():
"""Return the firmware cache directory (next to flash.py)."""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), ".firmware_cache")
def _archive_cache_path():
"""Return path to the cached firmware archive zip."""
return os.path.join(_cache_dir(), FIRMWARE_ARCHIVE)
def _extracted_firmware_path(firmware_name):
"""Return path to an extracted firmware binary in the flat cache dir."""
return os.path.join(_cache_dir(), firmware_name)
def _cache_meta_path():
"""Return path to the archive cache metadata JSON (single file for all variants)."""
return os.path.join(_cache_dir(), "meta.json")
def _read_cache_meta():
"""Read archive cache metadata, returning dict or None if not cached."""
import json
path = _cache_meta_path()
if os.path.isfile(path):
try:
with open(path) as f:
return json.load(f)
except Exception:
pass
return None
def _write_cache_meta(tag, sha256):
"""Write archive cache metadata after a successful download."""
import json
os.makedirs(_cache_dir(), exist_ok=True)
with open(_cache_meta_path(), "w") as f:
json.dump({"tag": tag, "sha256": sha256}, f, indent=2)
def _parse_version_tag(tag):
"""Parse a version tag like 'v1.0.13' into a tuple (1, 0, 13) for comparison.
Returns None if the tag doesn't match the expected format."""
import re
m = re.match(r"v?(\d+)\.(\d+)\.(\d+)", tag)
if m:
return tuple(int(x) for x in m.groups())
return None
def _format_release_label(tag=None):
if tag:
return f"{tag} ({RELEASE_CHANNEL})"
return f"latest {RELEASE_CHANNEL} release"
def _fetch_release_info(tag=None):
"""Fetch release info from GitHub. If tag is None, fetches latest."""
try:
from urllib.request import urlopen, Request
import json
except ImportError:
return None, "Python urllib not available"
if tag:
# Normalize: ensure tag starts with 'v'
if not tag.startswith("v"):
tag = f"v{tag}"
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/tags/{tag}"
else:
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/latest"
try:
req = Request(api_url, headers={"Accept": "application/vnd.github+json"})
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read()), None
except Exception as e:
return None, str(e)
def fetch_firmware(board_key, flash_size, release_tag=None):
"""Fetch firmware from the GitHub release archive, using cache when possible.
Downloads ``rtnode_firmware.zip`` once and extracts the correct binary for
the given board/flash-size combination. Falls back gracefully to the old
per-board binary if the archive is not present in the release (backward compat).
Returns (firmware_path, release_tag) on success, (None, reason) on failure.
"""
import zipfile
from urllib.request import urlretrieve
# Resolve variant (fallback to smallest/safest if exact size missing)
variants = BOARD_PROFILES[board_key]["flash_variants"]
if flash_size not in variants:
flash_size = sorted(variants, key=lambda s: int(s.replace("MB", "")))[0]
print(f" ⚠ No {flash_size} variant for {board_key} — using {flash_size}")
variant = variants[flash_size]
firmware_name = variant["firmware_bin"]
extracted_path = _extracted_firmware_path(firmware_name)
archive_path = _archive_cache_path()
cache_meta = _read_cache_meta()
# 1. Fetch release info
label = _format_release_label(release_tag)
print(f"Checking {label} from {GITHUB_REPO}...")
release, err = _fetch_release_info(release_tag)
if not release:
print(f" Could not reach GitHub: {err}")
if cache_meta and os.path.isfile(extracted_path):
print(f" Using cached firmware: {cache_meta.get('tag', '?')}")
return extracted_path, cache_meta.get("tag", "cached")
return None, f"No cached firmware and GitHub unreachable: {err}"
remote_tag = release.get("tag_name", "unknown")
# 2. Check whether cached archive is still valid
need_download = True
if cache_meta and os.path.isfile(archive_path):
cached_tag = cache_meta.get("tag")
if cached_tag == remote_tag:
if sha256_file(archive_path) == cache_meta.get("sha256"):
print(f" Cached firmware archive is up-to-date: {_format_release_label(remote_tag)}")
need_download = False
else:
print(f" Cache integrity mismatch — re-downloading")
else:
cached_ver = _parse_version_tag(cached_tag) if cached_tag else None
remote_ver = _parse_version_tag(remote_tag)
if cached_ver and remote_ver and remote_ver > cached_ver:
print(f" Newer {RELEASE_CHANNEL} release available: {_format_release_label(cached_tag)} → {_format_release_label(remote_tag)}")
elif cached_ver and remote_ver and remote_ver < cached_ver:
print(f" Requested {_format_release_label(remote_tag)} is older than cached {_format_release_label(cached_tag)}")
else:
print(f" Version changed: {_format_release_label(cached_tag)} → {_format_release_label(remote_tag)}")
if need_download:
# 3. Locate the archive asset (with per-board fallback for old releases)
asset_url = None
fallback_url = None
fallback_name = None
for asset in release.get("assets", []):
if asset["name"] == FIRMWARE_ARCHIVE:
asset_url = asset["browser_download_url"]
if asset["name"] == firmware_name:
fallback_url = asset["browser_download_url"]
fallback_name = asset["name"]
os.makedirs(_cache_dir(), exist_ok=True)
if asset_url:
print(f" Downloading {_format_release_label(remote_tag)} / {FIRMWARE_ARCHIVE}...")
try:
urlretrieve(asset_url, archive_path)
except Exception as e:
return None, f"Download failed: {e}"
file_sha = sha256_file(archive_path)
_write_cache_meta(remote_tag, file_sha)
print(f" Downloaded {os.path.getsize(archive_path):,} bytes SHA-256: {file_sha[:16]}...")
elif fallback_url:
# Old-style release — download the individual binary directly
print(f" Archive '{FIRMWARE_ARCHIVE}' not in release — downloading {fallback_name}")
try:
urlretrieve(fallback_url, extracted_path)
except Exception as e:
return None, f"Download failed: {e}"
file_sha = sha256_file(extracted_path)
_write_cache_meta(remote_tag, file_sha)
print(f" Downloaded {os.path.getsize(extracted_path):,} bytes SHA-256: {file_sha[:16]}...")
return extracted_path, remote_tag
else:
available = [a["name"] for a in release.get("assets", [])]
return None, (
f"Neither '{FIRMWARE_ARCHIVE}' nor '{firmware_name}' found in {_format_release_label(remote_tag)}.\n"
f" Available assets: {available}"
)
# 4. Extract the correct variant from the archive.
# Prefer the pre-merged binary — it is self-contained (bootloader + partitions
# + app in one file) so flash.py never needs PlatformIO or boot components.
# Fall back to the app-only binary for backward compat with old archives.
if not os.path.isfile(archive_path):
return None, f"Archive not found: {archive_path}"
try:
with zipfile.ZipFile(archive_path) as zf:
names = zf.namelist()
# Try merged binary first
merged_name = variant.get("merged_bin")
merged_path = _extracted_firmware_path(merged_name) if merged_name else None
if merged_name and merged_name in names:
with zf.open(merged_name) as src, open(merged_path, "wb") as dst:
dst.write(src.read())
print(f" Extracted {merged_name} (pre-merged, full-flash-ready)")
return merged_path, remote_tag
# Fall back to app-only binary
if firmware_name not in names:
return None, (
f"Neither '{merged_name or '?'}' nor '{firmware_name}' found in archive.\n"
f" Archive contains: {names}"
)
with zf.open(firmware_name) as src, open(extracted_path, "wb") as dst:
dst.write(src.read())
print(f" Extracted {firmware_name}")
except Exception as e:
return None, f"Failed to extract firmware from archive: {e}"
return extracted_path, remote_tag
def _do_merge(output_path, esptool_cmd, bootloader, partitions, boot_app0, firmware):
"""Low-level merge: combine the four components into a single binary."""
print("Merging firmware components...")
print(f" Bootloader: {bootloader} @ 0x{BOOTLOADER_ADDR:04x}")
print(f" Partitions: {partitions} @ 0x{PARTITIONS_ADDR:04x}")
print(f" boot_app0: {boot_app0} @ 0x{BOOT_APP0_ADDR:04x}")
print(f" Firmware: {firmware} @ 0x{APP_ADDR:05x}")
flash_mode = BOARD_FLASH_MODE()
print(f" Flash mode: {flash_mode.upper()}")
cmd = esptool_cmd + [
"--chip", CHIP,
"merge_bin",
"--flash_mode", flash_mode,
"--flash_freq", FLASH_FREQ,
"--flash_size", FLASH_SIZE(),
"-o", output_path,
f"0x{BOOTLOADER_ADDR:x}", bootloader,
f"0x{PARTITIONS_ADDR:x}", partitions,
f"0x{BOOT_APP0_ADDR:x}", boot_app0,
f"0x{APP_ADDR:x}", firmware,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"Error merging: {result.stderr}{result.stdout}")
return False
size = os.path.getsize(output_path)
print(f"\nMerged binary: {output_path} ({size:,} bytes)")
print(f"SHA-256: {sha256_file(output_path)[:16]}...")
return True
def ensure_firmware_built():
"""Ensure PlatformIO firmware and boot components exist, building if needed.
Returns True if all build artifacts are available (existing or freshly
built), False if PlatformIO is not installed or the build fails.
"""
firmware = FIRMWARE_BIN()
if os.path.isfile(firmware):
return True
print(f"\n Firmware not found: {firmware}")
print(f" Building with PlatformIO (env: {PIO_ENV()})...")
pio = shutil.which("pio") or shutil.which("platformio")
if not pio:
print(" Error: PlatformIO not found. Install from https://platformio.org")
return False
result = subprocess.run([pio, "run", "-e", PIO_ENV()],
cwd=os.path.dirname(os.path.abspath(__file__)))
if result.returncode != 0:
print(" PlatformIO build failed.")
return False
if not os.path.isfile(firmware):
print(f" Error: Build succeeded but firmware not found: {firmware}")
return False
print(" Build complete.")
return True
def merge_firmware(output_path, esptool_cmd):
"""Merge bootloader + partitions + boot_app0 + app into a single binary.
Uses PlatformIO build output. Triggers a build automatically if the
firmware binary is not present.
"""
ensure_firmware_built()
bootloader = find_bootloader()
partitions = find_partitions()
boot_app0 = BOOT_APP0_BIN
firmware = FIRMWARE_BIN()
missing = []
if not bootloader: missing.append(("bootloader", BOOTLOADER_BIN()))
if not partitions: missing.append(("partitions", PARTITIONS_BIN()))
if not boot_app0: missing.append(("boot_app0", "(not found)"))
if not os.path.isfile(firmware):
missing.append(("firmware", firmware))
if missing:
for name, path in missing:
print(f"Error: {name} not found: {path}")
print(f"Run 'pio run -e {PIO_ENV()}' to build first.")
return False
return _do_merge(output_path, esptool_cmd, bootloader, partitions, boot_app0, firmware)
def auto_merge_app_binary(app_binary_path, esptool_cmd):
"""Auto-merge an app-only binary with boot components for a full flash.
Finds bootloader, partitions, and boot_app0 from PlatformIO build output.
Triggers a PlatformIO build automatically if firmware is not yet built,
since bootloader.bin and partitions.bin come from the same build.
Returns the path to the merged binary on success, or None on failure.
"""
ensure_firmware_built()
bootloader = find_bootloader()
partitions = find_partitions()
boot_app0 = BOOT_APP0_BIN
missing = []
if not bootloader: missing.append("bootloader.bin")
if not partitions: missing.append("partitions.bin")
if not boot_app0: missing.append("boot_app0.bin")
if missing:
print(f"Cannot auto-merge: missing {', '.join(missing)}")
print(f"Build with PlatformIO first: pio run -e {PIO_ENV()}")
return None
# Create merged binary next to the app binary
base, ext = os.path.splitext(app_binary_path)
merged_path = f"{base}_merged{ext}"
print("Auto-merging app-only binary with boot components...")
if _do_merge(merged_path, esptool_cmd, bootloader, partitions, boot_app0, app_binary_path):
return merged_path
return None
def read_device_partitions(port, esptool_cmd, baud=None):
"""Read the partition table from the connected device.
Uses esptool read_flash to read PARTITION_TABLE_SIZE bytes from
PARTITIONS_ADDR (0x8000).
Returns the raw bytes on success, or None on failure.
"""
import tempfile
if baud is None:
baud = BAUD_RATE()
tmp = tempfile.NamedTemporaryFile(suffix=".bin", delete=False)
tmp.close()
try:
cmd = esptool_cmd + [
"--chip", CHIP,
"--port", port,
"--baud", baud,
"read_flash",
f"0x{PARTITIONS_ADDR:x}",
str(PARTITION_TABLE_SIZE),
tmp.name,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
return None
with open(tmp.name, "rb") as f:
return f.read()
except Exception:
return None
finally:
try:
os.unlink(tmp.name)
except OSError:
pass
def check_partition_table(port, esptool_cmd, baud=None):
"""Compare the device's partition table against the expected one.
Returns:
True — partition table matches (or no expected table to compare against)
False — partition table mismatch or unreadable state (device needs full flash)
"""
expected_path = find_partitions()
if not expected_path:
# Can't check — no reference partition table available
return True
with open(expected_path, "rb") as f:
expected = f.read()
print("Checking device partition table...")
device_data = read_device_partitions(port, esptool_cmd, baud)
if device_data is None:
print(" Could not read partition table from device")
return False
# Compare only the meaningful portion (both should be PARTITION_TABLE_SIZE)
if device_data[:len(expected)] == expected:
print(" Partition table OK ✓")
return True
# Check if device has any valid partition table at all
if device_data[:2] != PARTITION_TABLE_MAGIC:
print(" No valid partition table found on device (blank or corrupted)")
else:
print(" Partition table MISMATCH — device has a different layout")
return False
def check_app_on_device(port, esptool_cmd, baud=None):
"""Check whether app firmware is present on the device.
Reads a small chunk from APP_ADDR (0x10000). If the region is all 0xFF
(erased flash), no app is present and the device needs a full flash.
Returns True if app firmware is detected, False if blank/absent or unreadable.
"""
import tempfile
if baud is None:
baud = BAUD_RATE()
read_size = 256 # enough to distinguish blank from real firmware