-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiotstack.sh
More file actions
executable file
·5739 lines (5099 loc) · 199 KB
/
Copy pathiotstack.sh
File metadata and controls
executable file
·5739 lines (5099 loc) · 199 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
#!/bin/bash
# iotstack.sh -- CLI tool for managing iotstack ESPHome devices
# Wrapper around update_devices.sh with a cleaner interface
set -euo pipefail
# Top-level invocation PID; subshells (e.g. profile=$(bootstrap_resolve_profile))
# use a different $$ but must not be treated as a stale flash session.
export IOTSTACK_FLASH_ROOT_PID=$$
# Global configuration
VERBOSE=0
QUIET=0
IOTSTACK_TIMESTAMP=0
# ENV_FILE is defined in config.sh
# Colors (using ANSI-C quoting to properly interpret escape sequences)
RED=$'\033[0;31m'
GRN=$'\033[0;32m'
YLW=$'\033[0;33m'
BLU=$'\033[0;34m'
DIM=$'\033[2m'
RST=$'\033[0m'
err() { echo -e "${RED}[ERROR]${RST} $*" >&2; exit 1; }
ok() { [[ $QUIET -eq 0 ]] && echo -e "${GRN}[OK]${RST} $*"; return 0; }
warn() { [[ $QUIET -eq 0 ]] && echo -e "${YLW}[WARN]${RST} $*"; return 0; }
info() { [[ $QUIET -eq 0 ]] && echo -e "${BLU}[INFO]${RST} $*"; return 0; }
debug() { [[ $VERBOSE -eq 1 ]] && [[ $QUIET -eq 0 ]] && echo -e "${DIM}[DEBUG]${RST} $*" >&2; return 0; }
# Forward iotstack global flags to update_devices.sh.
_update_devices_inherited_flags() {
[[ $VERBOSE -eq 1 ]] && printf '%s\n' --verbose
iotstack_compilation_output_enabled && printf '%s\n' --compilation-output
}
# Print a table separator rule aligned to the header columns. Each argument is
# a column width; prints that many '-' per column with single-space gaps,
# wrapped in DIM. Dashes are built by space-padding then substitution so the
# width is correct -- printf '%-Ns' counts bytes and would mis-pad the
# multibyte '-' (U+2500) characters.
_print_table_rule() {
local first=1 w dashes
printf ' %s' "$DIM"
for w in "$@"; do
(( first )) || printf ' '
printf -v dashes '%*s' "$w" ''
printf '%s' "${dashes// /-}"
first=0
done
printf '%s\n' "$RST"
}
# -- Compile skip (config_hash) -----------------------------------------------
# Skip esphome compile when `esphome config-hash` matches build_info.json and
# firmware.bin exists. The config_hash helpers (_current_config_hash_for_yaml,
# _build_matches_config_hash, _config_hash_from_build_dir, ...) live in
# scripts/iotstack-version.sh so iotstack.sh and update_devices.sh share the exact
# same logic. Only the iotstack.sh-specific miss-reason logger stays here.
_compile_skip_miss_reason() {
local yaml_file="$1"
local device_name="${2:-}"
local yaml_name current_hash built_hash firmware_bin resolved_device
yaml_name=$(iotstack_compilation_cache_yaml_name "$yaml_file")
resolved_device=$(_compile_skip_device_name "$yaml_file" "$device_name")
built_hash=$(_config_hash_from_build_dir "$resolved_device" 2>/dev/null) || built_hash=""
if [[ -z "$built_hash" ]]; then
echo "no build_info.json for ${resolved_device}"
return 0
fi
current_hash=$(_current_config_hash_for_yaml "$yaml_file" "$resolved_device" 2>/dev/null) || current_hash=""
if [[ -z "$current_hash" ]]; then
echo "${yaml_name} config_hash unavailable (esphome config-hash failed)"
return 0
fi
if [[ "$built_hash" != "$current_hash" ]]; then
echo "${yaml_name} config_hash mismatch (built ${built_hash}, current ${current_hash})"
return 0
fi
firmware_bin="${YAMLS_DIR}/.esphome/build/${resolved_device}/.pioenvs/${resolved_device}/firmware.bin"
if [[ ! -f "$firmware_bin" ]]; then
echo "${yaml_name} config_hash matched but firmware.bin missing"
return 0
fi
echo "${yaml_name} compile skip check failed"
}
_check_serial_port_in_use() {
# Free the port from stale iotstack captures, then fail on non-iotstack holders.
local tty_device="$1"
local processes pid cmd kill_cmd
debug "_check_serial_port_in_use: checking $tty_device"
if [[ -n "${IOTSTACK_FLASH_SERIAL_TTY:-}" && "$IOTSTACK_FLASH_SERIAL_TTY" == "$tty_device" \
&& -n "${IOTSTACK_SERIAL_LOG_PID:-}" ]]; then
debug "Pausing device serial log capture for esptool on $tty_device..."
create_log_serial_capture_pause
sleep 1
return 0
fi
esp_serial_clear_tty_interference "$tty_device" "${IOTSTACK_FLASH_SESSION_PID:-}"
if command -v lsof &>/dev/null; then
processes=$(esp_serial_tty_blocked_processes "$tty_device" || true)
if [[ -n "$processes" ]]; then
pid=$(awk '{print $2}' <<<"$processes" | head -1)
cmd=$(awk '{print $1}' <<<"$processes" | head -1)
if [[ "$cmd" == "screen" ]]; then
kill_cmd="screen -X -S $pid quit"
else
kill_cmd="kill -9 $pid"
fi
err "Serial port $tty_device is already in use:
$processes
Quick fix (copy/paste):
$kill_cmd
Or manually: press Ctrl+A then D to detach screen, then run the command above."
fi
return 0
fi
if command -v fuser &>/dev/null; then
if fuser "$tty_device" >/dev/null 2>&1; then
warn "Serial port $tty_device may be in use. Close any open terminal sessions before flashing."
fi
fi
}
_hex_sizes_equal() {
local a="${1,,}" b="${2,,}"
[[ -n "$a" && "$a" == "$b" ]]
}
_partition_table_bootstrap_size() {
# Bootstrap (ota_0) size from the persisted partition table artifact (~/.iotstack/artifacts/).
# Survives `iotstack clean` so pass 1 can start exact.
[[ -f "$PARTITION_TABLE" ]] || return 1
local size label
label=$(iotstack_bootstrap_role)
size=$(awk -F, -v label="$label" '
$1 ~ ("^" label "[[:space:]]*$") {
gsub(/ /, "", $5)
print $5
exit
}
' "$PARTITION_TABLE")
[[ -n "$size" && "$size" =~ ^0x[0-9a-fA-F]+$ ]] || return 1
printf '%s' "$size"
}
_sync_bootstrap_partition_table_from_build() {
local build_csv="${YAMLS_DIR}/.esphome/build/$(iotstack_bootstrap_role)/partitions.csv"
if [[ -f "$build_csv" ]] && grep -qE '^production,' "$build_csv" 2>/dev/null; then
cp "$build_csv" "$PARTITION_TABLE"
_ensure_partition_table_symlink "$PARTITION_TABLE"
debug "Partition table synced from bootstrap build (production offset $(flash_partition_offset production 2>/dev/null))"
fi
}
_bootstrap_part_size() {
# Echo the bootstrap (ota_0) partition size as hex for a given firmware.bin:
# round_up_64KB(firmware_size + IOTSTACK_BOOTSTRAP_MARGIN). Falls back to
# IOTSTACK_BOOTSTRAP_PART_SIZE if the binary cannot be measured.
local bin="$1"
local margin="${IOTSTACK_BOOTSTRAP_MARGIN:-0x10000}"
local sz
sz=$(stat -c%s "$bin" 2>/dev/null || stat -f%z "$bin" 2>/dev/null || echo 0)
if (( sz <= 0 )); then
printf '%s' "${IOTSTACK_BOOTSTRAP_PART_SIZE:-0xe0000}"
return
fi
local total=$(( sz + margin ))
(( total % 0x10000 != 0 )) && total=$(( (total / 0x10000 + 1) * 0x10000 ))
printf '0x%x' "$total"
}
_esphome_compile_show_failure() {
local compile_yaml="$1"
local compile_log="$2"
local line
[[ -f "$compile_log" && -s "$compile_log" ]] || return 0
warn "Compile failed for $(basename "$compile_yaml") (last lines):"
if declare -F create_log_stamp_line &>/dev/null && create_log_enabled; then
create_log_stamp_line "esphome:compile" "--- compile failed: $(basename "$compile_yaml") ---"
while IFS= read -r line; do
create_log_stamp_line "esphome:compile" "$line"
done <"$compile_log"
fi
tail -40 "$compile_log" >&2
}
_esphome_compile() {
# Run esphome compile; one INFO line names the compile YAML. By default compiler
# output is captured and shown only on failure. --compilation-output streams it live.
local yaml_file="$1"
local compile_yaml compile_log rc=0
compile_yaml=$(iotstack_prepare_compile_yaml "$yaml_file") || return 1
compile_log=$(mktemp)
info "Compiling $(basename "$compile_yaml")..."
if iotstack_compilation_output_enabled; then
local -a compile_tee_targets=("$compile_log")
[[ -e /dev/tty && -w /dev/tty ]] && compile_tee_targets+=("/dev/tty")
if create_log_child_output_piped; then
create_log_subprocess_indent_env
if ! env PYTHONUNBUFFERED=1 stdbuf -oL -eL esphome compile "$compile_yaml" 2>&1 \
| stdbuf -oL -eL tee "${compile_tee_targets[@]}" \
| create_log_tee_console "esphome:compile"; then
rc=1
fi
elif ! env PYTHONUNBUFFERED=1 stdbuf -oL -eL esphome compile "$compile_yaml" 2>&1 \
| stdbuf -oL -eL tee "$compile_log"; then
rc=1
fi
[[ $rc -eq 1 ]] && _esphome_compile_show_failure "$compile_yaml" "$compile_log"
elif ! esphome compile "$compile_yaml" >"$compile_log" 2>&1; then
rc=1
_esphome_compile_show_failure "$compile_yaml" "$compile_log"
fi
rm -f "$compile_log"
iotstack_cleanup_compile_yaml "$compile_yaml" "$yaml_file"
return $rc
}
declare -gA _IOTSTACK_COMPILE_CACHE_HIT_NOTIFIED=()
declare -gA _IOTSTACK_SMART_COMPILE_DONE=()
_smart_compile_already_done() {
local yaml_file="$1"
local cache_key
cache_key=$(iotstack_compilation_cache_yaml_name "$yaml_file")
[[ -n "${_IOTSTACK_SMART_COMPILE_DONE[$cache_key]:-}" ]]
}
_smart_compile_mark_done() {
local yaml_file="$1"
local cache_key
cache_key=$(iotstack_compilation_cache_yaml_name "$yaml_file")
_IOTSTACK_SMART_COMPILE_DONE[$cache_key]=1
}
_smart_compile_repeat_satisfied() {
local yaml_file="$1"
local device_name="$2"
local firmware_bin="${YAMLS_DIR}/.esphome/build/${device_name}/.pioenvs/${device_name}/firmware.bin"
debug "Build already prepared for $(iotstack_compilation_cache_yaml_name "$yaml_file")"
if _is_bootstrap_yaml "$yaml_file"; then
_sync_bootstrap_partition_table_from_build \
|| { local fs_size; fs_size=$(_bootstrap_part_size "$firmware_bin")
IOTSTACK_BOOTSTRAP_PART_SIZE="$fs_size" _update_partition_table_file; }
else
ensure_partition_table_artifact
fi
}
_smart_compile_cache_hit_notice() {
local yaml_file="$1"
local device_name="$2"
local firmware_kind="$3" # e.g. production, bootstrap
local notify_key
notify_key="${firmware_kind}:$(iotstack_compilation_cache_yaml_name "$yaml_file")"
[[ -n "${_IOTSTACK_COMPILE_CACHE_HIT_NOTIFIED[$notify_key]:-}" ]] && return 0
_IOTSTACK_COMPILE_CACHE_HIT_NOTIFIED[$notify_key]=1
info "Compilation cache hit -- ${firmware_kind} firmware (${device_name}) already built; compile skipped"
}
_smart_compile_cache_miss_notice() {
# Log why smart_compile cannot reuse a cached build (called before esphome compile).
local yaml_file="$1"
local device_name="$2"
local firmware_kind="$3" # e.g. production, bootstrap
local reason
reason=$(_compile_skip_miss_reason "$yaml_file" "$device_name")
info "Compilation cache miss -- ${firmware_kind} firmware (${device_name}): ${reason}"
}
_flash_sync_update_devices_cache() {
# After smart_compile, write update_devices.sh's build cache so --reassign skips recompile.
local yaml_file="$1"
local yaml_name
yaml_name=$(basename "$yaml_file" .yaml)
local cache_file="${IOTSTACK_HOME}/logs/${yaml_name}.build.cache"
local build_info="${YAMLS_DIR}/.esphome/build/${yaml_name}/build_info.json"
[[ -f "$build_info" ]] || return 0
local esphome_version config_hash
esphome_version=$(esphome version 2>/dev/null | grep -o '[0-9][0-9]*\.[0-9.]*' | head -1) || return 0
config_hash=$(python3 -c \
"import json,sys; print(format(json.load(open(sys.argv[1]))['config_hash'], '08x'))" \
"$build_info" 2>/dev/null) || return 0
mkdir -p "$(dirname "$cache_file")"
printf 'esphome_version=%s\nconfig_hash=%s\n' \
"$esphome_version" "$config_hash" > "$cache_file"
debug "Synced update_devices build cache for ${yaml_name}"
}
smart_compile() {
# Smart compilation that skips a rebuild when the current esphome config_hash
# already matches the built one. config_hash is the sole build-identity key
# (it reflects YAML + packages + common/ + external_components/ + git tag via
# the project_version fingerprint), so there is no force/disable escape hatch.
# Usage: smart_compile <yaml_file> [device_name_for_logging]
local yaml_file="$1"
local device_name="${2:-unknown}"
if _smart_compile_already_done "$yaml_file"; then
_smart_compile_repeat_satisfied "$yaml_file" "$device_name"
return 0
fi
local firmware_bin="${YAMLS_DIR}/.esphome/build/${device_name}/.pioenvs/${device_name}/firmware.bin"
local cached=0
_build_matches_config_hash "$yaml_file" "$device_name" && cached=1
# -- Non-bootstrap builds ----------------------------------------------------
# Production firmware is OTA'd into the production partition and uses ESPHome's
# default partition table for its build-size check, so the custom table size
# is irrelevant to it. Just make sure a table exists, then compile.
if ! _is_bootstrap_yaml "$yaml_file"; then
if [[ $cached -eq 1 ]]; then
ensure_partition_table_artifact
_smart_compile_cache_hit_notice "$yaml_file" "$device_name" "production"
_smart_compile_mark_done "$yaml_file"
return 0
fi
_update_partition_table_file
_smart_compile_cache_miss_notice "$yaml_file" "$device_name" "production"
_esphome_compile "$yaml_file" || return 1
_smart_compile_mark_done "$yaml_file"
return 0
fi
# -- Bootstrap: size its partition dynamically to the actual firmware ---------
# The bootstrap partition is sized to exactly what bootstrap needs (+ margin);
# production absorbs the rest. The partition size affects the flashed
# partitions.bin (not the position-independent app image), so we compile,
# measure, regenerate the table, then recompile so partitions.bin matches.
if [[ $cached -eq 1 && -f "$firmware_bin" ]]; then
_smart_compile_cache_hit_notice "$yaml_file" "$device_name" "bootstrap"
_sync_bootstrap_partition_table_from_build \
|| { local fs_size; fs_size=$(_bootstrap_part_size "$firmware_bin")
IOTSTACK_BOOTSTRAP_PART_SIZE="$fs_size" _update_partition_table_file; }
_smart_compile_mark_done "$yaml_file"
return 0
fi
# Pass 1: compile (prefer persisted partition size; fall back to generous default).
local pass1_size fs_size fw_bytes partitions_bin
_smart_compile_cache_miss_notice "$yaml_file" "$device_name" "bootstrap"
local generous_size="${IOTSTACK_BOOTSTRAP_PART_SIZE_GENEROUS:-0x180000}"
pass1_size=$(_partition_table_bootstrap_size 2>/dev/null) \
|| pass1_size="${IOTSTACK_BOOTSTRAP_PART_SIZE:-0xe0000}"
export IOTSTACK_BOOTSTRAP_PART_SIZE="$pass1_size"
_update_partition_table_file
if _hex_sizes_equal "$pass1_size" "$generous_size"; then
debug "Bootstrap compile pass 1/2: measuring firmware size (partition ${pass1_size})"
else
debug "Bootstrap compile pass 1: partition table ${pass1_size}"
fi
if ! _esphome_compile "$yaml_file"; then
if _hex_sizes_equal "$pass1_size" "$generous_size"; then
return 1
fi
warn "Bootstrap compile failed with partition ${pass1_size} -- retrying with generous ${generous_size}"
export IOTSTACK_BOOTSTRAP_PART_SIZE="$generous_size"
_update_partition_table_file
debug "Bootstrap compile pass 1/2: measuring firmware size (partition ${generous_size})"
_esphome_compile "$yaml_file" || return 1
fi
fs_size=$(_bootstrap_part_size "$firmware_bin")
fw_bytes=$(stat -c%s "$firmware_bin" 2>/dev/null || echo "?")
info "Bootstrap firmware ${fw_bytes} bytes -> bootstrap partition ${fs_size}"
partitions_bin="${YAMLS_DIR}/.esphome/build/$(iotstack_bootstrap_role)/.pioenvs/$(iotstack_bootstrap_role)/partitions.bin"
if _hex_sizes_equal "$fs_size" "$IOTSTACK_BOOTSTRAP_PART_SIZE" && [[ -f "$partitions_bin" ]]; then
_sync_bootstrap_partition_table_from_build
info "Bootstrap partition table already exact (${fs_size}) -- skipping pass 2"
else
export IOTSTACK_BOOTSTRAP_PART_SIZE="$fs_size"
_update_partition_table_file
debug "Bootstrap compile pass 2/2: applying exact partition table (${fs_size})"
_esphome_compile "$yaml_file" || return 1
_sync_bootstrap_partition_table_from_build
fi
_smart_compile_mark_done "$yaml_file"
return 0
}
# Prompt for multi-device operations
confirm_multi_device() {
local count="$1"
local devices_desc="$2"
if [[ $count -le 1 ]]; then
return 0 # Single device, no prompt needed
fi
echo ""
warn "This operation will affect $count device(s):"
echo " $devices_desc"
echo ""
read -p "Continue? (y/N) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
return 0
else
info "Operation cancelled."
exit 0
fi
}
SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
# Source centralized configuration (now under scripts/). config.sh exports
# SCRIPTS_DIR, PROJECT_ROOT, ROLES_CONF and UPDATE_SCRIPT.
# shellcheck source=scripts/config.sh
source "${SCRIPT_DIR}/scripts/config.sh"
# shellcheck source=scripts/create-log.sh
source "${SCRIPT_DIR}/scripts/create-log.sh"
# --create-log: stamp iotstack messages to the session log (implies --timestamp);
# stdout stays on the tty. --create-log generates a GUID log id; implies --timestamp and -v.
_iotstack_log_plain() {
local tag="$1"
shift
if create_log_enabled; then
create_log_stamp_line "iotstack.sh" "[$tag] ${IOTSTACK_LOG_INDENT:-}$*"
fi
}
_iotstack_echo() {
local stream="$1"
shift
local ts indent="${IOTSTACK_LOG_INDENT:-}"
ts=$(iotstack_timestamp_prefix)
if [[ "$stream" == "stderr" ]]; then
echo -e "${ts}${indent}$*" >&2
else
echo -e "${ts}${indent}$*"
fi
}
# Flash workflow step banners; nested log lines use IOTSTACK_LOG_INDENT (2 spaces).
declare -g IOTSTACK_LOG_INDENT=""
declare -g _IOTSTACK_FLASH_STEP_NUM=0
declare -g IOTSTACK_FLASH_SUPPRESS_STEPS=0
_flash_step_reset() {
_IOTSTACK_FLASH_STEP_NUM=0
_IOTSTACK_FLASH_SERIAL_STEP=0
_IOTSTACK_FLASH_NVS_STEP=0
_IOTSTACK_FLASH_OTA_STEP=0
export IOTSTACK_LOG_INDENT=""
}
_flash_step_begin_at() {
local num="$1"
local title="$2"
[[ "${IOTSTACK_FLASH_SUPPRESS_STEPS:-0}" == "1" ]] && return 0
_IOTSTACK_FLASH_STEP_NUM=$num
export IOTSTACK_LOG_INDENT=""
echo ""
_iotstack_echo stdout "${BLU}[INFO]${RST} Step ${num}: ${title}"
export IOTSTACK_LOG_INDENT=" "
}
_flash_preflight_step_begin() {
_flash_step_begin_at 0 "Preflight checks"
}
_flash_step_begin() {
local title="$1"
_flash_step_begin_at $((_IOTSTACK_FLASH_STEP_NUM + 1)) "$title"
}
_flash_step_end() {
export IOTSTACK_LOG_INDENT=""
}
declare -g _IOTSTACK_FLASH_SERIAL_STEP=0
declare -g _IOTSTACK_FLASH_NVS_STEP=0
declare -g _IOTSTACK_FLASH_OTA_STEP=0
_flash_serial_step_begin() {
# USB/esptool: bootloader, partition table, boot_app0, bootstrap partition only.
[[ "${_IOTSTACK_FLASH_SERIAL_STEP:-0}" == "1" ]] && return 0
_IOTSTACK_FLASH_SERIAL_STEP=1
_flash_step_begin "Flashing production partition table and bootstrap image via serial"
}
_flash_nvs_step_begin() {
# WiFi credentials and device secrets (API when bootstrap is online, else USB).
[[ "${_IOTSTACK_FLASH_NVS_STEP:-0}" == "1" ]] && return 0
_IOTSTACK_FLASH_NVS_STEP=1
_flash_step_begin "Write device-specific secrets to NVS"
}
_flash_ota_step_begin() {
# Production partition updates use the same path as: iotstack update <role> <mac>
[[ "${_IOTSTACK_FLASH_OTA_STEP:-0}" == "1" ]] && return 0
_IOTSTACK_FLASH_OTA_STEP=1
_flash_step_begin "iotstack update (production OTA)"
}
err() { _iotstack_log_plain "ERROR" "$@"; _iotstack_echo stderr "${RED}[ERROR]${RST} $*"; exit 1; }
ok() { [[ $QUIET -eq 0 ]] && { _iotstack_log_plain "OK" "$@"; _iotstack_echo stdout "${GRN}[OK]${RST} $*"; }; return 0; }
warn() { [[ $QUIET -eq 0 ]] && { _iotstack_log_plain "WARN" "$@"; _iotstack_echo stdout "${YLW}[WARN]${RST} $*"; }; return 0; }
info() { [[ $QUIET -eq 0 ]] && { _iotstack_log_plain "INFO" "$@"; _iotstack_echo stdout "${BLU}[INFO]${RST} $*"; }; return 0; }
debug() { [[ $VERBOSE -eq 1 && $QUIET -eq 0 ]] && { _iotstack_log_plain "DEBUG" "$@"; _iotstack_echo stderr "${DIM}[DEBUG]${RST} $*"; }; return 0; }
_run_update_devices() {
if create_log_child_output_piped; then
create_log_run "update_devices.sh" bash "$UPDATE_SCRIPT" "$@"
return $?
fi
"$UPDATE_SCRIPT" "$@"
}
# partition-table.sh is sourced by config.sh (generate_partition_table, update_partition_table_file)
# shellcheck source=scripts/bootstrap-yaml.sh
source "${SCRIPT_DIR}/scripts/bootstrap-yaml.sh"
# shellcheck source=scripts/flash-compare.sh
source "${SCRIPT_DIR}/scripts/flash-compare.sh"
_is_bootstrap_yaml() {
bootstrap_is_artifact_yaml "$1" || [[ "$(basename "$1")" == "bootstrap.yaml" ]]
}
_update_partition_table_file() {
debug "Generating local build partition table CSV: $PARTITION_TABLE"
update_partition_table_file
debug "Build partition table CSV ready (bootstrap + production layout for compile -- not read from device)"
}
# UPDATE_SCRIPT is provided by config.sh (scripts/update_devices.sh)
_load_ha_credentials_optional() {
# shellcheck source=scripts/ensure-integration-secrets.sh
source "${SCRIPT_DIR}/scripts/ensure-integration-secrets.sh"
load_ha_credentials_optional
}
_ensure_chip_tool_storage() {
command -v chip-tool &>/dev/null || return 0
# shellcheck source=scripts/ensure-chip-tool-storage.sh
source "${SCRIPT_DIR}/scripts/ensure-chip-tool-storage.sh"
setup_chip_tool_storage
}
_ha_websocket_call_service() {
local domain="$1"
local service="$2"
local target_json="$3"
python3 "${SCRIPT_DIR}/scripts/ha_websocket.py" \
--ha-url "$HA_URL" \
--ha-token "$HA_TOKEN" \
call-service "$domain" "$service" \
--target "$target_json" \
>/dev/null 2>&1
}
# Check if update_devices.sh exists
if [[ ! -f "$UPDATE_SCRIPT" ]]; then
err "update_devices.sh not found at $UPDATE_SCRIPT"
fi
if [[ ! -d "$YAMLS_DIR" ]]; then
err "yamls directory not found at $YAMLS_DIR"
fi
# -- Dynamic Role Discovery --------------------------------------------------
# Roles are discovered from YAML filenames in yamls/ directory
# File: yamls/bleproxy.yaml -> Role: bleproxy
# Resolve role name to YAML path
# If given "bleproxy", returns "yamls/bleproxy.yaml"
resolve_device() {
local role_name="$1"
# Check if role is defined in roles.conf
if ! is_valid_role "$role_name"; then
local available_roles
available_roles=$(list_roles_from_conf | tr '\n' ', ' | sed 's/,$//')
err "Unknown role: '$role_name'
Available roles:
$available_roles
Run 'iotstack roles' for details."
fi
local yaml_file="${YAMLS_DIR}/${role_name}.yaml"
# Verify YAML file exists
if [[ ! -f "$yaml_file" ]]; then
err "Role '$role_name' defined in roles.conf but YAML not found: $yaml_file"
fi
echo "$yaml_file"
}
# Extract device_type and network_type from YAML file
# Returns: "device_type|network_type" (e.g., "esp32c6|wifi")
get_yaml_device_info() {
local yaml_file="$1"
local board=""
local variant=""
local network_type=""
if [[ -f "$yaml_file" ]]; then
# Extract board and variant from esp32 section
board=$(grep -A5 "^esp32:" "$yaml_file" | grep -E "^\s*board:\s*" | head -1 | sed 's/.*board:\s*//; s/\s*$//')
variant=$(grep -A5 "^esp32:" "$yaml_file" | grep -E "^\s*variant:\s*" | head -1 | sed 's/.*variant:\s*//; s/\s*$//')
# Determine network_type from presence of wifi or openthread sections
if grep -q "^wifi:" "$yaml_file" 2>/dev/null; then
network_type="wifi"
elif grep -q "^openthread:" "$yaml_file" 2>/dev/null; then
network_type="thread"
fi
fi
echo "${board}|${variant}|${network_type}"
}
# List available role names from roles.conf
# Returns: role names (one per line)
list_roles_from_conf() {
grep -v "^#\|^$" "$ROLES_CONF" | cut -d= -f1 | sort
}
# Validate that a role name exists in roles.conf
# Returns: 0 if valid, 1 if invalid
is_valid_role() {
local role_name="$1"
list_roles_from_conf | grep -q "^${role_name}$"
}
# List available role names (YAML filenames without extension,)
# DEPRECATED: Use list_roles_from_conf() instead - this scans all YAML files, not official roles
list_device_names() {
for yaml_file in "$YAMLS_DIR"/*.yaml; do
if [[ -f "$yaml_file" ]]; then
local basename_only
basename_only=$(basename "$yaml_file" .yaml)
[[ "$basename_only" == "secrets" ]] && continue
echo "$basename_only"
fi
done | sort
}
# Query Home Assistant for device areas via WebSocket
# Returns JSON with device_name -> area_name mapping
get_ha_device_areas() {
_load_ha_credentials_optional || return 1
local ha_token="$HA_TOKEN"
local ha_url="$HA_URL"
# Convert HTTP/HTTPS to WS/WSS
local ws_url="${ha_url//http:/ws:}"
ws_url="${ws_url//https:/wss:}"
ws_url="${ws_url}/api/websocket"
# Query device registry and area registry via WebSocket (with timeout)
timeout 5 bash -c "{
echo '{\"type\": \"auth\", \"access_token\": \"'$ha_token'\"}'
sleep 0.5
echo '{\"id\": 1, \"type\": \"config/device_registry/list\"}'
sleep 0.5
echo '{\"id\": 2, \"type\": \"config/area_registry/list\"}'
sleep 2
} | websocat -n '$ws_url' 2>/dev/null" | jq -s '
# Handle case where responses might not be in expected order
map(select(.result != null)) |
# Find device and area registries
(map(select(.id == 1) | .result) | .[0] // []) as $devices |
(map(select(.id == 2) | .result) | .[0] // []) as $areas |
# Build area lookup map (area_id -> name)
($areas | map({(.id): .name}) | add // {}) as $area_map |
# Map device names to area (handle multiple formats)
($devices | map(
.name as $name |
($name | sub("-[0-9a-fA-F]{6}$"; "")) as $name_base |
($name | capture("(?<suffix>[0-9a-fA-F]{6})$") | .suffix // "") as $mac_suffix |
{
($name): ($area_map[.area_id] // "-"),
($name_base): ($area_map[.area_id] // "-")
} +
if ($mac_suffix != "") then {($mac_suffix): ($area_map[.area_id] // "-")} else {} end
) | add // {})
' 2>/dev/null || echo '{}'
}
# -- Parallel Job Queue --------------------------------------------------------
# Helper to run multiple commands in parallel with job limiting
# Usage: run_parallel_jobs <max_jobs> <"cmd1" "cmd2" ...>
# Each command is executed in background, with at most max_jobs running
# Returns array job_results[i] with exit code of command i
run_parallel_jobs() {
local max_jobs=$1
shift
local commands=("$@")
local slot_count=0
declare -a job_pids=()
for i in "${!commands[@]}"; do
# Wait for a slot to free up
while [[ $slot_count -ge $max_jobs ]]; do
wait -n 2>/dev/null || true
slot_count=$((slot_count - 1))
done
# Start job in background
local cmd="${commands[$i]}"
eval "$cmd" &
job_pids[i]=$!
slot_count=$((slot_count + 1))
done
# Wait for all remaining jobs
job_results=()
for i in "${!job_pids[@]}"; do
local pid="${job_pids[$i]}"
wait "$pid" 2>/dev/null
job_results[i]=$?
done
}
# -- Subcommands --------------------------------------------------------------
usage() {
cat "${SCRIPT_DIR}/docs/help/iotstack.txt"
}
help_update() {
cat "${SCRIPT_DIR}/docs/help/iotstack-update.txt"
}
help_verify() {
cat "${SCRIPT_DIR}/docs/help/iotstack-verify.txt"
}
help_verify_flash() {
cat "${SCRIPT_DIR}/docs/help/iotstack-verify-flash.txt"
}
help_devices() {
cat "${SCRIPT_DIR}/docs/help/iotstack-devices.txt"
}
help_bootstrap() {
cat "${SCRIPT_DIR}/docs/help/iotstack-bootstrap.txt"
}
help_roles() {
cat "${SCRIPT_DIR}/docs/help/iotstack-roles.txt"
}
_ROLE_HELP_DIR="${SCRIPT_DIR}/docs/help/roles"
role_help_file() {
printf '%s/%s.txt' "$_ROLE_HELP_DIR" "$1"
}
_iotstack_extract_role_from_args() {
# First production role in argv (skip help, flags, MACs, paths, tty devices).
local arg
for arg in "$@"; do
[[ "$arg" == "help" ]] && continue
[[ "$arg" =~ ^-- ]] && continue
[[ "$arg" =~ ^/dev/ ]] && continue
[[ "$arg" =~ ^[0-9a-fA-F]{6}$ ]] && continue
[[ -f "$arg" ]] && continue
[[ "$arg" == "all" ]] && continue
if is_valid_role "$arg"; then
printf '%s\n' "$arg"
return 0
fi
done
return 1
}
_iotstack_command_help_if_requested() {
# Usage: _iotstack_command_help_if_requested <flash|update|reassign|verify> "$@"
# Shows per-role help when help + role are present; else generic command help.
local cmd="$1"
shift
local arg role="" want_help=0
for arg in "$@"; do
[[ "$arg" == "help" ]] && want_help=1
done
[[ $want_help -eq 1 ]] || return 1
role=$(_iotstack_extract_role_from_args "$@") || role=""
if [[ -n "$role" ]]; then
help_role "$role"
else
case "$cmd" in
flash) help_flash ;;
update) help_update ;;
reassign) help_reassign ;;
verify) help_verify ;;
*) return 1 ;;
esac
fi
return 0
}
help_role() {
local role="${1:-}"
local yaml_file info board variant network friendly f
if [[ -z "$role" ]]; then
err "Usage: iotstack help <role>"
fi
if ! is_valid_role "$role"; then
err "Unknown role: $role. Run 'iotstack roles' for available roles."
fi
f=$(role_help_file "$role")
if [[ -f "$f" ]]; then
cat "$f"
return 0
fi
yaml_file=$(resolve_device "$role")
info=$(get_yaml_device_info "$yaml_file")
IFS='|' read -r board variant network <<< "$info"
friendly=$(yaml_friendly_name_from_file "$yaml_file" 2>/dev/null) || friendly="$role"
cat <<EOF
iotstack ${role} -- ${friendly}
Config: yamls/${role}.yaml
Chip: ${variant:-unknown}${board:+ (${board})}
Network: ${network:-unknown}
iotstack flash ${role} [/dev/ttyACM0]
iotstack update ${role}
iotstack reassign <MAC> ${role}
iotstack verify ${role}
Role help file not found: docs/help/roles/${role}.txt
EOF
}
help_reassign() {
cat "${SCRIPT_DIR}/docs/help/iotstack-reassign.txt"
}
help_flash() {
cat "${SCRIPT_DIR}/docs/help/iotstack-flash.txt"
}
help_logs() {
cat "${SCRIPT_DIR}/docs/help/iotstack-logs.txt"
}
help_query() {
cat "${SCRIPT_DIR}/docs/help/iotstack-query.txt"
}
help_secret() {
cat "${SCRIPT_DIR}/docs/help/iotstack-secret.txt"
}
help_rotate_secrets() {
cat "${SCRIPT_DIR}/docs/help/iotstack-rotate-secrets.txt"
}
help_device() {
cat "${SCRIPT_DIR}/docs/help/iotstack-device.txt"
}
_iotstack_require_jq() {
command -v jq &>/dev/null || err "jq is required for --json output"
}
_iotstack_format_json() {
# Validate and pretty-print a complete JSON document from stdin.
_iotstack_require_jq
jq '.'
}
_iotstack_json_slurp() {
# Slurp newline-delimited JSON objects into one array, then pretty-print.
_iotstack_require_jq
jq -s '.'
}
_list_devices_flush_parsed_mdns_row() {
local device_data="$1"
local hostname="$2"
local friendly="$3"
local project="$4"
local version="$5"
local bootstrap_hash="$6"
local production_hash="$7"
[[ -z "$hostname" ]] && return 0
local bootstrap_prefix
bootstrap_prefix="$(iotstack_bootstrap_role)-"
if [[ "$hostname" == "${bootstrap_prefix}"* ]]; then
[[ -z "$friendly" ]] && friendly="$(iotstack_bootstrap_friendly_name)"
[[ -z "$project" ]] && project="iotstack.$(iotstack_bootstrap_role)-prod"
fi
echo "$hostname|$friendly|$project|$version|$bootstrap_hash|$production_hash" >> "$device_data"
}
_list_devices_append_parsed_mdns() {
# Append hostname|friendly|project|version|bootstrap_hash|production_hash rows.
local device_data="$1"
local current_hostname=""
local current_friendly=""
local current_project=""
local current_version=""
local current_bootstrap_hash=""
local current_production_hash=""
local current_config_hash=""
while IFS= read -r line; do
# avahi-browse -r emits "= interface IPv4 <hostname> ..." (resolved) and
# "+ ..." (announced). When resolution is slow, only "+" lines may appear.
if [[ $line =~ ^[=+][[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+([^[:space:]]+) ]]; then
local parsed_host="${BASH_REMATCH[1]%.local}"
if [[ -n "$current_hostname" && "$current_hostname" != "$parsed_host" ]]; then
_list_devices_flush_parsed_mdns_row "$device_data" "$current_hostname" "$current_friendly" \
"$current_project" "$current_version" "$current_bootstrap_hash" "$current_production_hash"
current_friendly=""
current_project=""
current_version=""
current_bootstrap_hash=""
current_production_hash=""
current_config_hash=""
fi
current_hostname="$parsed_host"
elif [[ $line =~ hostname\ =\ \[([^\]]+)\] ]]; then
local resolved_host="${BASH_REMATCH[1]%.local}"
if [[ -n "$current_hostname" && "$current_hostname" != "$resolved_host" ]]; then
_list_devices_flush_parsed_mdns_row "$device_data" "$current_hostname" "$current_friendly" \
"$current_project" "$current_version" "$current_bootstrap_hash" "$current_production_hash"
current_friendly=""
current_project=""
current_version=""
current_bootstrap_hash=""
current_production_hash=""
current_config_hash=""
fi
current_hostname="$resolved_host"
fi
if [[ $line =~ txt\ = ]]; then
if [[ $line =~ friendly_name=([^\"]*) ]]; then
current_friendly="${BASH_REMATCH[1]}"
current_friendly="${current_friendly% [0-9a-f][0-9a-f]*}"
fi
[[ $line =~ project_name=([^\"]*) ]] && current_project="${BASH_REMATCH[1]}"
[[ $line =~ project_version=([^\"]*) ]] && current_version="${BASH_REMATCH[1]}"
[[ $line =~ bootstrap_image_hash=([^\"]*) ]] && current_bootstrap_hash="${BASH_REMATCH[1]}"
[[ $line =~ production_image_hash=([^\"]*) ]] && current_production_hash="${BASH_REMATCH[1]}"
[[ $line =~ config_hash=([^\"]*) ]] && current_config_hash="${BASH_REMATCH[1]}"
if [[ -n "$current_hostname" && -n "$current_config_hash" ]]; then
if [[ "$current_hostname" == "$(iotstack_bootstrap_role)-"* ]]; then
[[ -z "$current_bootstrap_hash" ]] && current_bootstrap_hash="$current_config_hash"
else
[[ -z "$current_production_hash" ]] && current_production_hash="$current_config_hash"
fi
fi
fi
done
_list_devices_flush_parsed_mdns_row "$device_data" "$current_hostname" "$current_friendly" \
"$current_project" "$current_version" "$current_bootstrap_hash" "$current_production_hash"
}
_list_devices_merge_by_mac() {
# Collapse rows that share a MAC suffix; prefer production hostnames for identity fields.
local input="$1"
local output="$2"
declare -A merged_bs merged_prod merged_friendly merged_project merged_version
declare -A merged_host_prod merged_host_bs
local -a macs=()
while IFS='|' read -r hostname friendly project version bootstrap_hash production_hash; do
[[ -z "$hostname" ]] && continue
local mac="${hostname##*-}"
[[ -z "$mac" ]] && continue