diff options
Diffstat (limited to 'tools/gbhud.py')
| -rwxr-xr-x | tools/gbhud.py | 47 |
1 files changed, 33 insertions, 14 deletions
diff --git a/tools/gbhud.py b/tools/gbhud.py index f9f2c68..cb8b914 100755 --- a/tools/gbhud.py +++ b/tools/gbhud.py @@ -46,17 +46,30 @@ def gb_decode(bs): return o # ---- socket ---- -def resolve_sock(arg): - if arg: return arg - if os.environ.get("GBCTL_SOCK"): return os.environ["GBCTL_SOCK"] - live = [] +def _connectable(path): + if not path or not os.path.exists(path): + return False + try: + t = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + t.settimeout(0.3); t.connect(path); t.close() + return True + except OSError: + return False + +def resolve_sock(pref=None): + """Find a *live* control socket, test-connecting so stale sockets from a dead + instance are skipped. `pref` (e.g. from --sock) is tried first, then the + registry, then $GBCTL_SOCK - so the HUD follows respawns automatically.""" + import json + cands = [] + if pref: cands.append(pref) for p in glob.glob(os.path.join(REGDIR, "*.json")): - import json - try: - d = json.load(open(p)) - if os.path.exists(d.get("sock", "")): live.append(d["sock"]) + try: cands.append(json.load(open(p)).get("sock", "")) except Exception: pass - return live[0] if len(live) == 1 else None + if os.environ.get("GBCTL_SOCK"): cands.append(os.environ["GBCTL_SOCK"]) + for c in cands: + if _connectable(c): return c + return None class Mem: """Batched WRAM reader over the control socket.""" @@ -160,21 +173,27 @@ def main(): sock = None; sym = SYM_DEFAULT if "--sock" in argv: sock = argv[argv.index("--sock")+1] if "--sym" in argv: sym = argv[argv.index("--sym")+1] - sock = resolve_sock(sock) - if not sock: print("no live emulator (run gbctl spawn)"); return + pref = sock S = load_syms(sym); MAPS = load_maps(MAPCONST) sys.stdout.write("\x1b[?25l") # hide cursor try: m = None while True: try: - if m is None: m = Mem(sock) + if m is None: + sk = resolve_sock(pref) # re-resolve every reconnect + if not sk: + sys.stdout.write("\x1b[H\x1b[2J waiting for emulator... " + "(run: gbctl spawn <rom>)\n"); sys.stdout.flush() + time.sleep(0.5); continue + m = Mem(sk) m.refresh() sys.stdout.write("\x1b[H\x1b[2J" + render(m, S, MAPS) + "\n") sys.stdout.flush() - except (OSError, ConnectionError): + except (OSError, ConnectionError, IndexError): m = None - sys.stdout.write("\x1b[H\x1b[2J waiting for emulator...\n"); sys.stdout.flush() + sys.stdout.write("\x1b[H\x1b[2J reconnecting...\n"); sys.stdout.flush() + time.sleep(0.3) time.sleep(0.2) except KeyboardInterrupt: pass |
