forked from coredevices/PebbleOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpbl
More file actions
executable file
·793 lines (618 loc) · 27.2 KB
/
pbl
File metadata and controls
executable file
·793 lines (618 loc) · 27.2 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
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Core Devices LLC
# SPDX-License-Identifier: Apache-2.0
"""PebbleOS developer CLI.
Hosts the operational commands (flash, qemu, console, debug, screenshot,
openocd, reset, bork, image_*, make_lang, pack_lang, pack_all_langs) that used
to live in the root ``wscript``but are not build steps, and provides thin
pass-through wrappers for the everyday ``./waf`` commands so there is a single entry point.
Build state is read directly from the configured build dir
(``build/c4che/_cache.py``); no waf process is spawned for operational
commands. Run ``./waf configure --board BOARD`` first.
"""
import argparse
import importlib.util
import os
import platform
import shlex
import string
import subprocess
import sys
REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
BUILD_DIR = os.path.join(REPO_ROOT, "build")
LANG_DIR_REL = "resources/normal/base/lang"
# Commands forwarded verbatim to ./waf (no build env / waflib needed).
WAF_PASSTHROUGH = ("configure", "build", "bundle", "clean", "test", "waf")
# QEMU SDL decorations per board. The first entry is used as the default.
QEMU_DECORATIONS = {
"qemu_emery": ["pt2-br", "pt2-sb"],
"qemu_flint": ["p2d-bk", "p2d-wh"],
"qemu_gabbro": ["pr2-bk20", "pr2-gd14"],
}
QEMU_DECORATION_CHOICES = sorted({d for ds in QEMU_DECORATIONS.values() for d in ds}) + ["none"]
# Set by setup(); the reused waftools runner modules and config snapshot.
_DRY_RUN = False
# --- Colored output -------------------------------------------------------
def _pprint(color, msg):
codes = {"RED": "31", "GREEN": "32", "YELLOW": "33", "CYAN": "36"}
sys.stdout.write("\033[%sm%s\033[0m\n" % (codes.get(color, "0"), msg))
def _fatal(msg):
_pprint("RED", msg)
sys.exit(1)
def _run_shell(cmd):
"""Run a shell command string, honoring --dry-run."""
if _DRY_RUN:
_pprint("YELLOW", "[dry-run] " + cmd)
return 0
return subprocess.call(cmd, shell=True)
def _run_waf(*args):
"""Run a ./waf subcommand for build steps that pbl orchestrates but does
not perform itself (e.g. the QEMU flash images)."""
if _DRY_RUN:
_pprint("YELLOW", "[dry-run] ./waf " + " ".join(args))
return 0
return subprocess.call([sys.executable, "waf"] + list(args), cwd=REPO_ROOT)
# --- Configured build env -------------------------------------------------
class Env:
"""Mimics ``ctx.env``: attribute/item access returns ``[]`` when missing,
matching waf's ConfigSet semantics that the runner helpers rely on."""
def __init__(self, data):
self._data = data
def __getattr__(self, key):
return self._data.get(key, [])
def __getitem__(self, key):
return self._data.get(key, [])
def __contains__(self, key):
return key in self._data
def load_env():
cache = os.path.join(BUILD_DIR, "c4che", "_cache.py")
if not os.path.isfile(cache):
_fatal("Build not configured -- run ./waf configure --board BOARD first.")
spec = importlib.util.spec_from_file_location("_waf_cache", cache)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
data = {k: v for k, v in vars(mod).items() if not k.startswith("__")}
return Env(data)
# --- waftools runner reuse ------------------------------------------------
# Reused waftools runner modules; populated by setup(). These are plain helper
# modules (no waf runtime needed) -- openocd/pebble_sdk_locator fall back to a
# stub logger when waflib is absent.
openocd = sftool = nrfutil = None
def setup(options):
"""Bootstrap for operational commands: resolve build env, import the reused
runner modules, and activate an installed SDK. Returns (env, shim)."""
global openocd, sftool, nrfutil, _DRY_RUN
_DRY_RUN = getattr(options, "dry_run", False)
# The reused waftools modules and tools/ helpers live under the repo root.
if REPO_ROOT not in sys.path:
sys.path.insert(0, REPO_ROOT)
import waftools.openocd as _openocd
import waftools.sftool as _sftool
import waftools.nrfutil as _nrfutil
openocd, sftool, nrfutil = _openocd, _sftool, _nrfutil
# Prefer an installed PebbleOS SDK's binaries (toolchain, QEMU, sftool).
try:
from waftools.pebble_sdk_locator import activate_sdk
activate_sdk(REPO_ROOT)
except Exception:
pass
env = load_env()
shim = WafShim(env, options)
return env, shim
class WafShim:
"""Minimal stand-in for a waf BuildContext, passed to the reused
waftools.{openocd,sftool,nrfutil} helpers."""
def __init__(self, env, options):
self.env = env
self.options = options
def exec_command(self, cmd, stdout=None, stderr=None):
if _DRY_RUN:
_pprint("YELLOW", "[dry-run] " + cmd)
return 0
return subprocess.call(cmd, shell=True)
def cmd_and_log(self, args, quiet=None, output=None):
return subprocess.run(args, capture_output=True, text=True, check=True).stdout
def fatal(self, msg):
_fatal(msg)
# --- Artifact paths (relative to repo root; cwd is REPO_ROOT) --------------
def fw_bin():
return "build/src/fw/tintin_fw.bin"
def fw_hex():
return "build/src/fw/tintin_fw.hex"
def fw_elf():
return "build/src/fw/tintin_fw.elf"
def pbpack():
return "build/system_resources.pbpack"
# --- Shared helpers (moved from wscript) -----------------------------------
class FirmwareTooLargeException(Exception):
pass
def _check_firmware_image_size(env, path):
BYTES_PER_K = 1024
firmware_size = os.path.getsize(path)
if env.CONFIG_SOC_NRF52:
if env.VARIANT == "prf" and not env.IS_MFG:
max_firmware_size = 512 * BYTES_PER_K
else:
max_firmware_size = (1024 - 32) * BYTES_PER_K
elif env.CONFIG_SOC_SF32LB52:
if env.VARIANT == "prf" and not env.IS_MFG:
max_firmware_size = 576 * BYTES_PER_K
else:
max_firmware_size = 3072 * BYTES_PER_K
elif env.CONFIG_QEMU:
max_firmware_size = 4096 * BYTES_PER_K
else:
_fatal("Cannot check firmware size against unknown micro family")
if firmware_size > max_firmware_size:
raise FirmwareTooLargeException(
"Firmware is too large! Size is 0x%x should be less than 0x%x"
% (firmware_size, max_firmware_size)
)
return "%d / %d bytes used (%d free)" % (
firmware_size, max_firmware_size, max_firmware_size - firmware_size)
def _is_pulse_everywhere(env):
return "PULSE_EVERYWHERE=1" in env["DEFINES"]
def _get_pulse_flash_tool(env, options):
if env.CONFIG_SOC_SF32LB52 and not options.force_pulse:
return "sftool_flash_imaging"
if _is_pulse_everywhere(env) or options.force_pulse:
return "pulse_flash_imaging"
return "pulse_legacy_flash_imaging"
def run_arm_gdb(elf_path, cmd_str="", target_server_port=3333):
from tools.gdb_driver import find_gdb_path
arm_none_eabi_path = find_gdb_path()
if arm_none_eabi_path is None:
_fatal("pebble-gdb not found!")
os.system('{} {} {} --ex="target remote :{}"'.format(
arm_none_eabi_path, elf_path, cmd_str, target_server_port))
# --- Operational commands --------------------------------------------------
def cmd_flash(env, shim, options):
_check_firmware_image_size(env, fw_bin())
hex_path = fw_hex()
flash_resources = options.resources and env.VARIANT != "prf"
if flash_resources and env.RUNNER != "sftool":
_fatal("--resources is only supported on the sftool runner")
if env.RUNNER == "openocd":
openocd.run_command(
shim,
"init; reset halt; program {} reset;".format(hex_path),
expect=["Programming Finished", "Programming Finished", "shutdown"],
enforce_expect=True,
)
elif env.RUNNER == "sftool":
files = [hex_path]
if flash_resources:
files.append("{}@0x12620000".format(pbpack()))
sftool.write_flash(shim, *files)
elif env.RUNNER == "nrfutil":
nrfutil.program(shim, hex_path)
nrfutil.reset(shim)
else:
_fatal("Unsupported operation on: {}".format(env.RUNNER))
def cmd_console(env, shim, options):
if env.CONFIG_QEMU:
tty = "socket://%s" % (options.qemu_host or "localhost:12345")
else:
tty = options.tty
if not tty:
_fatal("Error: --tty not specified")
if _is_pulse_everywhere(env):
inner = "%s ./tools/pulse_console.py -t %s" % (sys.executable, tty)
elif env.CONFIG_QEMU:
inner = "%s ./tools/log_hashing/miniterm_co.py %s" % (sys.executable, tty)
else:
baudrate = options.baudrate or 230400
# Force RTS de-asserted: on some boards RTS resets the SoC.
inner = "%s ./tools/log_hashing/miniterm_co.py %s %d --rts 0" % (
sys.executable, tty, baudrate)
if options.reconnect:
_run_shell("%s ./tools/console_keepalive.py -t %s -- %s" % (sys.executable, tty, inner))
else:
_run_shell(inner)
def cmd_debug(env, shim, options):
elf = fw_elf()
if env.CONFIG_QEMU:
import pexpect
cmd_line = "%s ./tools/qemu/qemu_gdb_proxy.py --port=1233 --target=localhost:1234" % sys.executable
proc = pexpect.spawn(cmd_line, logfile=sys.stdout, encoding="utf-8")
proc.expect(["Connected to target", pexpect.TIMEOUT], timeout=10)
run_arm_gdb(elf, target_server_port=1233)
return
if env.RUNNER != "openocd":
_fatal("debug only supported with openocd runner")
with openocd.daemon(shim, "openocd.cfg", use_swd="swd" in env.OPENOCD_JTAG):
run_arm_gdb(elf, cmd_str='--init-command=".gdbinit"')
def _qemu_launch(env, options):
qemu_bin = os.getenv("PEBBLE_QEMU_BIN")
if not qemu_bin or not (os.path.isfile(qemu_bin) and os.access(qemu_bin, os.X_OK)):
qemu_bin = "qemu-pebble"
qemu_machine = env.CONFIG_QEMU_MACHINE
if not qemu_machine or qemu_machine == "unknown":
raise Exception("Board type '{}' not supported by QEMU".format(env.BOARD))
spi_flash_args = ["-drive", "if=mtd,format=raw,file=build/qemu_spi_flash.bin"]
# Load firmware as kernel (ELF for proper vector table handling).
has_audio = env.CONFIG_PLATFORM_EMERY or env.CONFIG_PLATFORM_FLINT
if has_audio:
audio_driver = "coreaudio" if platform.system() == "Darwin" else "sdl"
machine_dep_args = ["-machine", "%s,audiodev=snd0" % qemu_machine,
"-audiodev", "%s,id=snd0" % audio_driver,
"-kernel", fw_elf()] + spi_flash_args
else:
machine_dep_args = ["-machine", qemu_machine,
"-kernel", fw_elf()] + spi_flash_args
decoration = options.qemu_decoration
if decoration is None:
decoration = QEMU_DECORATIONS.get(env.BOARD, [None])[0]
if decoration and decoration != "none":
display_type = "sdl,decoration=%s" % decoration
else:
display_type = "sdl"
machine_dep_args.extend(["-display", "%s,show-cursor=on" % display_type])
mon_sock = os.path.join(BUILD_DIR, "qemu-mon.sock")
if os.path.exists(mon_sock):
os.unlink(mon_sock)
cmd_line = (
shlex.quote(qemu_bin) + " "
"-rtc base=localtime "
"-monitor stdio "
"-monitor unix:{mon_sock},server=on,wait=off "
"-s "
"-serial file:uart1.log "
"-serial tcp::12344,server=on,wait=off " # pebble-tool
"-serial tcp::12345,server=on,wait=off " # console
).format(mon_sock=shlex.quote(mon_sock)) + " ".join(machine_dep_args)
_pprint("CYAN", "QEMU command: {}".format(cmd_line))
_run_shell(cmd_line)
def cmd_qemu(env, shim, options):
# The flash images are build artifacts, so let waf produce them. Always
# rebuild the micro-flash image; by default rebuild the SPI flash too
# (--keep-flash-image keeps the stored apps/data from a previous run).
if _run_waf("qemu_image_micro") != 0:
_fatal("Failed to build QEMU micro flash image")
spi_flash = os.path.join(BUILD_DIR, "qemu_spi_flash.bin")
if not options.keep_flash_image or not os.path.isfile(spi_flash):
if _run_waf("qemu_image_spi") != 0:
_fatal("Failed to build QEMU SPI flash image")
_qemu_launch(env, options)
def cmd_screenshot(env, shim, options):
import socket
sock_path = os.path.join(BUILD_DIR, "qemu-mon.sock")
if not os.path.exists(sock_path):
_fatal("QEMU monitor socket not found at {} -- is './pbl qemu' "
"running?".format(sock_path))
out_path = options.screenshot_output
if not out_path:
out_path = os.path.join(BUILD_DIR, "screenshot.png")
if not out_path.lower().endswith(".png"):
_fatal("--screenshot-output must end with .png")
if os.path.exists(out_path):
os.unlink(out_path)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect(sock_path)
def read_until_prompt():
buf = b""
while b"(qemu) " not in buf:
chunk = sock.recv(4096)
if not chunk:
break
buf += chunk
return buf
read_until_prompt()
sock.sendall("screendump {} -f png\n".format(out_path).encode())
response = read_until_prompt().decode(errors="replace")
if not os.path.exists(out_path) or os.path.getsize(out_path) == 0:
_fatal("QEMU did not write screenshot to {}\nMonitor response:\n{}"
.format(out_path, response))
_pprint("CYAN", "Wrote screenshot to {}".format(out_path))
def cmd_openocd(env, shim, options):
"""Starts openocd and leaves it running, resetting the board to improve the
chances of attaching successfully."""
openocd.run_command(shim, "init; reset", shutdown=False)
def cmd_reset(env, shim, options):
"""Resets a connected device."""
if env.RUNNER == "openocd":
openocd.run_command(shim, "init; reset;", expect=["found"])
else:
_fatal("Unsupported operation on: {}".format(env.RUNNER))
def cmd_bork(env, shim, options):
"""Resets and wipes a connected device."""
if env.RUNNER == "openocd":
openocd.run_command(shim, "init; reset halt;", ignore_fail=True)
openocd.run_command(shim, "init; flash erase_sector 0 0 1;", ignore_fail=True)
elif env.RUNNER == "sftool":
sftool.erase_flash(shim)
elif env.RUNNER == "nrfutil":
nrfutil.erase(shim)
else:
_fatal("Unsupported operation on: {}".format(env.RUNNER))
def cmd_image_resources(env, shim, options):
tty = options.tty
if tty is None:
_fatal("Error: --tty not specified")
pbpack_path = os.path.join(BUILD_DIR, "system_resources.pbpack")
tool_name = _get_pulse_flash_tool(env, options)
_pprint("CYAN", 'Writing pbpack "%s" to tty %s' % (pbpack_path, tty))
ret = _run_shell("%s ./tools/%s.py -t %s -p resources %s"
% (sys.executable, tool_name, tty, pbpack_path))
if ret != 0:
_fatal("Imaging failed")
def cmd_image_recovery(env, shim, options):
tty = options.tty
if tty is None:
_fatal("Error: --tty not specified")
tool_name = _get_pulse_flash_tool(env, options)
recovery_bin_path = options.file or fw_bin()
_pprint("CYAN", 'Writing recovery bin "%s" to tty %s' % (recovery_bin_path, tty))
ret = _run_shell("%s ./tools/%s.py -t %s -p firmware %s"
% (sys.executable, tool_name, tty, recovery_bin_path))
if ret != 0:
_fatal("Imaging failed")
# --- Language pack commands ---
# Template for a new language's lang_map.json (only the strings entry is
# populated; fonts are added by hand once the language needs extended glyphs).
FILE_LANG_MAP = string.Template("""
{
"strings": {
"lang": "${lang}",
"name": "STRINGS",
"file": "tintin.po"
},
"fonts": [{
"name": "GOTHIC_14_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_14_BOLD_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_18_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_18_BOLD_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_24_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_24_BOLD_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_28_EXTENDED",
"file": ""
}, {
"name": "GOTHIC_28_BOLD_EXTENDED",
"file": ""
}, {
"name": "BITHAM_18_LIGHT_SUBSET_EXTENDED",
"file": ""
}, {
"name": "BITHAM_30_BLACK_EXTENDED",
"file": ""
}, {
"name": "BITHAM_34_LIGHT_SUBSET_EXTENDED",
"file": ""
}, {
"name": "BITHAM_34_MEDIUM_NUMBERS_EXTENDED",
"file": ""
}, {
"name": "BITHAM_42_BOLD_EXTENDED",
"file": ""
}, {
"name": "BITHAM_42_LIGHT_EXTENDED",
"file": ""
}, {
"name": "BITHAM_42_MEDIUM_NUMBERS_EXTENDED",
"file": ""
}, {
"name": "ROBOTO_CONDENSED_21_EXTENDED",
"file": ""
}, {
"name": "ROBOTO_BOLD_SUBSET_49_EXTENDED",
"file": ""
}, {
"name": "DROID_SERIF_28_BOLD_EXTENDED",
"file": ""
}],
"images": []
}
""")
def _ensure_lang_imports():
"""Put tools/ on sys.path so the reused resource/font modules resolve.
Inserted ahead of REPO_ROOT so 'resources' binds to tools/resources rather
than the firmware resources/ namespace dir."""
tools = os.path.join(REPO_ROOT, "tools")
if tools not in sys.path:
sys.path.insert(0, tools)
def _pack_lang_code(env, lang_code):
import json
from collections import OrderedDict
import pbpack
from resources.resource_map.resource_generator_font import FontResourceGenerator
lang_path = os.path.join(REPO_ROOT, LANG_DIR_REL, lang_code)
build_path = os.path.join(BUILD_DIR, LANG_DIR_REL, lang_code)
with open(os.path.join(lang_path, "lang_map.json")) as f:
resource_map = json.load(f)
resource_data = OrderedDict()
if not os.path.exists(build_path):
os.makedirs(build_path)
# The "strings" entry, if any, holds the compiled .mo translation catalog.
strings = resource_map["strings"]
name = strings["name"]
ui_codepoints_path = None
if strings["file"] == "":
resource_data[name] = b""
else:
po_path = os.path.join(lang_path, strings["file"])
# Warn (don't fail) if the catalog still has untranslated strings.
if subprocess.check_output(["msgattrib", "--untranslated", po_path]) != b"":
_pprint("RED", "Warning: This PO file contains untranslated strings!")
mo_path = os.path.join(build_path, strings["file"] + "." + name + ".mo")
os.system("msgfmt -c -v -o {} {}".format(mo_path, po_path))
_pprint("CYAN", "Created mo at {}".format(mo_path))
with open(mo_path, "rb") as f:
resource_data[name] = f.read()
ui_codepoints_path = os.path.join(build_path, "codepoints.json")
os.system("{} ./tools/generate_codepoint_requirements.py {} --output={}".format(
sys.executable, po_path, ui_codepoints_path))
# Build a resource for each font entry, reusing the normal resource build's
# font generator.
for entry in resource_map["fonts"]:
name = entry["name"]
if "alias" in entry:
# Aliases reuse another resource's bytes; the pbpack dedups them.
_pprint("CYAN", "Aliasing {} to {}".format(entry["alias"], name))
resource_data[name] = resource_data[entry["alias"]]
elif entry["file"] == "":
_pprint("CYAN", "Building empty resource {}".format(name))
resource_data[name] = b""
else:
_pprint("CYAN", "Building font resource {}".format(name))
# Make the entry look like a normal resource_map.json font entry.
entry["type"] = "font"
d = FontResourceGenerator.font_definition_from_dict(env, entry)
if d.character_list is None:
# Default to the codepoints the UI needs unless overridden.
d.character_list = ui_codepoints_path
else:
d.character_list = os.path.join(lang_path, d.character_list)
font_path = os.path.join(lang_path, entry["file"])
resource_data[name] = FontResourceGenerator.build_font_data(font_path, d)
lp = pbpack.ResourcePack(False)
for r in resource_data.values():
lp.add_resource(r)
language_pack = os.path.join(build_path, lang_code + ".pbl")
with open(language_pack, "wb+") as lp_file:
lp.serialize(lp_file)
_pprint("CYAN", "Created language pack at {}".format(language_pack))
def cmd_make_lang(env, shim, options):
"""Generate a new language's translation files and update existing ones."""
import polib
_ensure_lang_imports()
lang_code = options.lang
lang_path = os.path.join(REPO_ROOT, LANG_DIR_REL, lang_code)
pot_path = os.path.join(REPO_ROOT, "build/src/fw/tintin.pot")
if not os.path.exists(pot_path):
_fatal("Error: could not find tintin.pot. Please run ./pbl build first")
po_path = os.path.join(lang_path, "tintin.po")
msginit_cmd = ["msginit", "-l", lang_code, "--no-translator", "-i", pot_path]
if not os.path.exists(lang_path):
# New language: create the folder and seed lang_map.json from template.
os.mkdir(lang_path)
with open(os.path.join(lang_path, "lang_map.json"), "w") as f:
f.write(FILE_LANG_MAP.substitute({"lang": lang_code}))
if not os.path.exists(po_path):
msginit_cmd += ["-o", po_path]
subprocess.call(msginit_cmd)
else:
# Preserve the existing header, regenerate, then merge in new strings.
po_file_header = str(polib.pofile(po_path).metadata_as_entry())
with open(po_path, "w") as po_file:
po_file.write(po_file_header)
import tempfile
new_po_file = tempfile.NamedTemporaryFile(delete=True)
msginit_cmd += ["-o", new_po_file.name]
subprocess.call(msginit_cmd)
subprocess.call(["msgmerge", "--lang=" + lang_code, "--update",
po_path, new_po_file.name])
def cmd_pack_lang(env, shim, options):
"""Generate the language pack (pbpack) for a single language."""
_ensure_lang_imports()
_pack_lang_code(env, options.lang)
def cmd_pack_all_langs(env, shim, options):
"""Generate language packs (pbpacks) for every language."""
_ensure_lang_imports()
lang_root = os.path.join(REPO_ROOT, LANG_DIR_REL)
for lang_code in sorted(next(os.walk(lang_root))[1]):
_pack_lang_code(env, lang_code)
OPERATIONAL = {
"flash": cmd_flash,
"console": cmd_console,
"debug": cmd_debug,
"qemu": cmd_qemu,
"screenshot": cmd_screenshot,
"openocd": cmd_openocd,
"reset": cmd_reset,
"bork": cmd_bork,
"image_resources": cmd_image_resources,
"image_recovery": cmd_image_recovery,
"make_lang": cmd_make_lang,
"pack_lang": cmd_pack_lang,
"pack_all_langs": cmd_pack_all_langs,
}
# --- Argument parsing ------------------------------------------------------
def build_parser():
parser = argparse.ArgumentParser(
prog="pbl", description="PebbleOS developer CLI")
sub = parser.add_subparsers(dest="command", metavar="<command>")
dry = argparse.ArgumentParser(add_help=False)
dry.add_argument("--dry-run", action="store_true",
help="Print the runner command instead of executing it")
p = sub.add_parser("flash", parents=[dry], help="Flash firmware to a device")
p.add_argument("--tty", help="tty for the sftool runner")
p.add_argument("--resources", action="store_true",
help="Also flash system resources alongside the firmware")
p = sub.add_parser("console", help="Open the serial console")
p.add_argument("--tty", help="tty to use for the console")
p.add_argument("--baudrate", type=int, help="Baudrate for the target uart")
p.add_argument("--qemu-host", default="localhost:12345",
help="host:port for the emulator console connection")
p.add_argument("--reconnect", action="store_true",
help="Wrap the console in a keep-alive driver that reconnects")
sub.add_parser("debug", help="Attach gdb to the target")
p = sub.add_parser("qemu", help="Launch the firmware under QEMU")
p.add_argument("--keep-flash-image", action="store_true",
help="Keep the existing QEMU SPI flash image instead of rebuilding it")
p.add_argument("--qemu-decoration", default=None, choices=QEMU_DECORATION_CHOICES,
help="SDL decoration for QEMU (defaults to the per-board default)")
p = sub.add_parser("screenshot", help="Capture a screenshot of running QEMU")
p.add_argument("--screenshot-output", default=None,
help="Output path (must end in .png). Defaults to build/screenshot.png")
sub.add_parser("openocd", parents=[dry], help="Start openocd and leave it running")
sub.add_parser("reset", parents=[dry], help="Reset a connected device")
sub.add_parser("bork", parents=[dry], help="Reset and wipe a connected device")
p = sub.add_parser("image_resources", parents=[dry],
help="UART-image system resources")
p.add_argument("--tty", help="tty for serial imaging")
p.add_argument("--force-pulse", action="store_true",
help="Force PULSE-based flashing even on SF32LB52")
p = sub.add_parser("image_recovery", parents=[dry],
help="UART-image recovery firmware")
p.add_argument("--tty", help="tty for serial imaging")
p.add_argument("--file", help="Recovery binary to flash (defaults to built firmware)")
p.add_argument("--force-pulse", action="store_true",
help="Force PULSE-based flashing even on SF32LB52")
p = sub.add_parser("make_lang",
help="Generate/update a language's translation files")
p.add_argument("--lang", default="en_US", help="Language to package (isocode)")
p = sub.add_parser("pack_lang", help="Generate the pbpack for one language")
p.add_argument("--lang", default="en_US", help="Language to package (isocode)")
sub.add_parser("pack_all_langs", help="Generate pbpacks for all languages")
# ./waf pass-through wrappers.
for name in WAF_PASSTHROUGH:
sp = sub.add_parser(name, help="Forward to ./waf %s" % (
name if name != "waf" else "<args...>"))
sp.add_argument("args", nargs=argparse.REMAINDER)
return parser
def main(argv):
# Pass-through commands forward verbatim to ./waf (handled before argparse so
# flags like --board reach waf untouched).
if argv and argv[0] in WAF_PASSTHROUGH:
cmd, rest = argv[0], argv[1:]
waf_cmd = [] if cmd == "waf" else [cmd]
return subprocess.call([sys.executable, "waf"] + waf_cmd + rest, cwd=REPO_ROOT)
parser = build_parser()
options = parser.parse_args(argv)
if not options.command:
parser.print_help()
return 1
# Absolutize user-supplied path options before changing cwd.
for attr in ("file", "screenshot_output"):
val = getattr(options, attr, None)
if val:
setattr(options, attr, os.path.abspath(val))
os.chdir(REPO_ROOT)
env, shim = setup(options)
OPERATIONAL[options.command](env, shim, options)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))