-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroku_control.py
More file actions
executable file
·2605 lines (2281 loc) · 82.4 KB
/
roku_control.py
File metadata and controls
executable file
·2605 lines (2281 loc) · 82.4 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
import sys
import os
import time
import json
import re
import socket
import subprocess
import xml.etree.ElementTree as ET
import difflib
import copy
import random
from pathlib import Path
from urllib.parse import quote
from datetime import datetime
import requests
if __name__ == "__main__" and not __file__:
raise SystemExit("roku_control.py loaded without a file path")
# ------------------------------------------------------
# Subcommand: `roku remote` -> open curses TUI remote
# ------------------------------------------------------
if len(sys.argv) > 1 and sys.argv[1] in ("remote", "tui"):
import os as _os
import sys as _sys
import subprocess as _subprocess
root = _os.path.dirname(_os.path.realpath(__file__))
env = dict(_os.environ)
env["PYTHONPATH"] = root + (_os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
raise SystemExit(_subprocess.call([_sys.executable, "-m", "roku_remote_tui"], cwd=root, env=env))
# ======================================================
# Roku Control (expanded)
# - Safe defaults: no lights, no auto wake, no daemon loops
# - Shorthand: unknown command => launch target
# - Config, cache, state, macros, discovery, follow mode
# ======================================================
# ------------------------------------------------------
# Defaults (used if config not found)
# ------------------------------------------------------
DEFAULT_CONFIG = {
"default_device": "livingroom",
"devices": {
"livingroom": {
"ip": "192.168.86.25",
"port": 8060,
"timeout": 3.0,
"rate_delay": 0.15,
}
},
"behavior": {
"default_wake": False,
"default_lights": False,
"assume_input_switch_success": True,
"apps_cache_ttl_seconds": 6 * 60 * 60,
"max_state_actions": 50,
"max_state_errors": 50,
"max_vol_presses_per_command": 12,
"max_volume_set_target": 12,
"volume_chunk": 2,
"volume_chunk_pause": 1.75,
"volume_chunk_pause_up": 3.75,
"volume_chunk_pause_down": 1.75,
"volume_jitter_min": 0.0,
"volume_jitter_max": 0.0,
"nav_jitter_min": 0.0,
"nav_jitter_max": 0.0,
"type_char_delay": 0.06,
"type_jitter_min": 0.0,
"type_jitter_max": 0.0,
# Minimum time between consecutive volume presses (seconds).
# Helps prevent the TV from "jumping" when multiple presses happen fast.
"volume_press_gap": 0.28, # fallback for both directions
"volume_up_press_gap": 0.28, # optional override
"volume_down_press_gap": 0.28, # optional override
# Zero-out preferences
# If set (>0), vol zero holds VolumeDown for this many ms.
# If not set, falls back to repeated VolumeDown presses (zero_out_down_presses).
"zero_out_hold_ms": 1600,
"zero_out_down_presses": 8,
},
"aliases": {
"switch": "nintendo switch",
"console": "nintendo switch",
"pc": "computer",
"computer": "computer",
"tv": "live tv",
"live": "live tv",
"audio": "soundbar",
"pluto": "pluto tv - free movies/shows",
"pluto_tv": "pluto tv - free movies/shows",
"plutotv": "pluto tv - free movies/shows",
},
"failback_inputs": {
"nintendo switch": ["nintendo switch", "computer", "live tv"],
"computer": ["computer", "live tv"],
},
"light_scenes": {
"netflix": ["cozy"],
"youtube": ["cozy"],
"nintendo switch": ["cozy"],
"computer": ["cozy"],
"live tv": ["off"],
},
"lights": {
"bin": "/home/pi/projects/wiz_lights/lights.py",
},
"follow": {
"poll_seconds": 2.0,
"min_seconds_between_light_changes": 6.0,
"ignore_apps": ["roku", "screensaver"],
},
"macros": {
"movie": {
"steps": [
{"action": "assert_or_wake_power_on"},
{"action": "launch", "target": "netflix"},
{"action": "scene_for", "target": "netflix", "requires_lights": True},
]
},
"console": {
"steps": [
{"action": "assert_or_wake_power_on"},
{"action": "launch", "target": "nintendo switch"},
{"action": "scene_for", "target": "nintendo switch", "requires_lights": True},
]
},
"work": {
"steps": [
{"action": "ensure_power_on", "wait": 2.5},
{"action": "lights", "mode": "embers"},
{"action": "launch", "target": "pluto"},
{"action": "vol_hold", "dir": "down", "ms": 1600},
{"action": "vol_up", "n": 1},
]
},
"shutdown": {
"steps": [
{"action": "lights", "mode": "off"},
{"action": "key", "key": "Power"},
]
},
"vol_normalize_night": {
"steps": [
{"action": "vol_down", "n": 20},
{"action": "vol_up", "n": 4},
]
},
"vol_normalize_day": {
"steps": [
{"action": "vol_down", "n": 20},
{"action": "vol_up", "n": 8},
]
},
},
}
# ------------------------------------------------------
# Paths
# ------------------------------------------------------
CONFIG_PATH = Path.home() / ".config" / "roku_control" / "config.json"
CACHE_DIR = Path.home() / ".cache" / "roku_control"
STATE_PATH = Path.home() / ".local" / "state" / "roku_control" / "state.json"
FOLLOW_PID_PATH = Path.home() / ".local" / "state" / "roku_control" / "follow.pid"
# ------------------------------------------------------
# Commands
# ------------------------------------------------------
KNOWN_COMMANDS = {
"status", "diag", "ping",
"apps", "list", "cache",
"launch",
"power", "home",
"key", "nav", "ok", "back", "info", "replay", "play", "pause", "fwd", "rev", "mute", "type",
"keydown", "keyup",
"vol", "volup", "voldown",
"movie", "console", "scene", "work", "shutdown",
"follow",
"macro",
"device", "discover",
"help", "-h", "--help",
"config",
}
# Key aliases to actual Roku keypress endpoints
KEY_ALIASES = {
"home": "Home",
"back": "Back",
"select": "Select",
"ok": "Select",
"up": "Up",
"down": "Down",
"left": "Left",
"right": "Right",
"replay": "InstantReplay",
"info": "Info",
"play": "Play",
"pause": "Play",
"fwd": "Fwd",
"ff": "Fwd",
"rev": "Rev",
"rw": "Rev",
"power": "Power",
"poweroff": "PowerOff",
"mute": "VolumeMute",
"volumemute": "VolumeMute",
"volumeup": "VolumeUp",
"volumedown": "VolumeDown",
"enter": "Enter",
"search": "Search",
}
# ------------------------------------------------------
# Globals set by CLI flags
# ------------------------------------------------------
G = {
"device": None,
"ip": None,
"port": None,
"timeout": None,
"retries": None,
"rate_delay": None,
"wake": None,
"lights": None,
"no_lights": False,
"json": False,
"quiet": False,
"debug": False,
"dry_run": False,
}
# ------------------------------------------------------
# Small utils
# ------------------------------------------------------
def now_iso():
return datetime.now().isoformat(timespec="seconds")
def eprint(msg):
sys.stderr.write(str(msg) + "\n")
def out(msg):
if not G["quiet"]:
print(msg)
def debug(msg):
if G["debug"] and not G["quiet"]:
print(msg)
def normalize(s):
return " ".join(str(s).replace("\xa0", " ").split()).strip()
def safe_int(s, default=None):
try:
return int(s)
except Exception:
return default
def mkdirp(p: Path):
p.parent.mkdir(parents=True, exist_ok=True)
def read_json_file(path: Path, default=None):
try:
if not path.exists():
return default
return json.loads(path.read_text())
except Exception:
return default
def write_json_file(path: Path, data):
mkdirp(path)
path.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")
def _pid_alive(pid: int) -> bool:
try:
os.kill(int(pid), 0)
return True
except Exception:
return False
def keydown(dev, retries, keyname):
keyname = normalize(keyname).lower()
real = KEY_ALIASES.get(keyname, None)
if real is None:
real = normalize(keyname)
real = real[:1].upper() + real[1:]
if G["dry_run"]:
out(f"[DRY] keydown {real}")
return
http_post(dev, f"/keydown/{real}", retries)
def keyup(dev, retries, keyname):
keyname = normalize(keyname).lower()
real = KEY_ALIASES.get(keyname, None)
if real is None:
real = normalize(keyname)
real = real[:1].upper() + real[1:]
if G["dry_run"]:
out(f"[DRY] keyup {real}")
return
http_post(dev, f"/keyup/{real}", retries)
def hold_key(dev, retries, keyname, ms):
ms = int(ms)
if ms < 1:
ms = 1
keydown(dev, retries, keyname)
if G["dry_run"]:
out(f"[DRY] sleep {ms/1000.0}")
else:
time.sleep(ms / 1000.0)
keyup(dev, retries, keyname)
def type_text(cfg, dev, retries, text):
if G["dry_run"]:
out(f"[DRY] type {text}")
return
# Behavior source: cfg if provided, else load_config()
if not isinstance(cfg, dict):
try:
cfg = load_config()
except Exception:
cfg = {}
beh = (cfg.get("behavior", {}) or {}) if isinstance(cfg, dict) else {}
# Base delay between characters (seconds)
base = beh.get("type_char_delay", beh.get("type_delay", 0.06))
try:
base = float(base)
except Exception:
base = 0.06
if base < 0:
base = 0.0
# Optional jitter per character (defaults OFF)
jmin = beh.get("type_jitter_min", 0.0)
jmax = beh.get("type_jitter_max", 0.0)
try:
jmin = float(jmin)
jmax = float(jmax)
except Exception:
jmin = 0.0
jmax = 0.0
# Roku ECP: /keypress/Lit_<char> with URL encoding for special characters
for ch in text:
encoded = quote(ch, safe="")
http_post(dev, f"/keypress/Lit_{encoded}", retries)
_sleep_jitter(base, jmin, jmax)
# ------------------------------------------------------
# Config/state loading
# ------------------------------------------------------
def load_config():
cfg = copy.deepcopy(DEFAULT_CONFIG)
on_disk = read_json_file(CONFIG_PATH, default=None)
if isinstance(on_disk, dict):
cfg = deep_merge(cfg, on_disk)
return cfg
def deep_merge(a, b):
if not isinstance(a, dict) or not isinstance(b, dict):
return b
outd = dict(a)
for k, v in b.items():
if k in outd and isinstance(outd[k], dict) and isinstance(v, dict):
outd[k] = deep_merge(outd[k], v)
else:
outd[k] = v
return outd
def load_state(cfg):
st = read_json_file(STATE_PATH, default=None)
if not isinstance(st, dict):
st = {"actions": [], "errors": []}
st.setdefault("actions", [])
st.setdefault("errors", [])
return st
def record_action(cfg, st, action, details=None):
maxn = cfg["behavior"].get("max_state_actions", 50)
entry = {"ts": now_iso(), "action": action}
if details is not None:
entry["details"] = details
st["actions"].append(entry)
st["actions"] = st["actions"][-maxn:]
write_json_file(STATE_PATH, st)
def record_error(cfg, st, where, msg, details=None):
maxn = cfg["behavior"].get("max_state_errors", 50)
entry = {"ts": now_iso(), "where": where, "error": str(msg)}
if details is not None:
entry["details"] = details
st["errors"].append(entry)
st["errors"] = st["errors"][-maxn:]
write_json_file(STATE_PATH, st)
# ------------------------------------------------------
# Device selection
# ------------------------------------------------------
def get_device_cfg(cfg):
dev_name = G["device"] or cfg.get("default_device")
devs = cfg.get("devices", {})
dev = devs.get(dev_name)
if not dev:
raise RuntimeError(f"Unknown device: {dev_name}")
ip = G["ip"] or dev.get("ip")
port = G["port"] or dev.get("port", 8060)
timeout = G["timeout"] if G["timeout"] is not None else dev.get("timeout", 3.0)
rate_delay = G["rate_delay"] if G["rate_delay"] is not None else dev.get("rate_delay", 0.15)
base_url = f"http://{ip}:{port}"
return {
"name": dev_name,
"ip": ip,
"port": port,
"timeout": float(timeout),
"rate_delay": float(rate_delay),
"base_url": base_url,
}
# ------------------------------------------------------
# HTTP with retries
# ------------------------------------------------------
def should_retry_exception(ex):
return isinstance(ex, (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.RequestException))
def _sleep_rate(dev):
time.sleep(dev["rate_delay"])
def http_get(dev, path, retries):
url = dev["base_url"] + path
last_ex = None
for attempt in range(retries + 1):
try:
debug(f"[HTTP] GET {path} (attempt {attempt+1}/{retries+1})")
r = requests.get(url, timeout=dev["timeout"])
if r.status_code >= 500 and attempt < retries:
time.sleep(0.15 * (attempt + 1))
continue
r.raise_for_status()
return r.text
except Exception as ex:
last_ex = ex
if attempt >= retries or not should_retry_exception(ex):
raise
time.sleep(0.15 * (attempt + 1))
raise last_ex
def http_post(dev, path, retries):
url = dev["base_url"] + path
last_ex = None
for attempt in range(retries + 1):
try:
debug(f"[HTTP] POST {path} (attempt {attempt+1}/{retries+1})")
r = requests.post(url, timeout=dev["timeout"])
if r.status_code >= 500 and attempt < retries:
time.sleep(0.15 * (attempt + 1))
continue
r.raise_for_status()
_sleep_rate(dev)
return
except Exception as ex:
last_ex = ex
if attempt >= retries or not should_retry_exception(ex):
raise
time.sleep(0.15 * (attempt + 1))
raise last_ex
# ------------------------------------------------------
# Roku queries
# ------------------------------------------------------
def query_device_info(dev, retries):
xml = http_get(dev, "/query/device-info", retries)
root = ET.fromstring(xml)
return root
def tv_power_state(dev, retries):
root = query_device_info(dev, retries)
return root.findtext("power-mode", "unknown")
def active_app(dev, retries):
xml = http_get(dev, "/query/active-app", retries)
root = ET.fromstring(xml)
app = root.find("app")
if app is None or app.text is None:
return "unknown"
return normalize(app.text.strip().lower())
# ------------------------------------------------------
# Reachability
# ------------------------------------------------------
def socket_ping(ip, port, timeout=1.2):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
s.connect((ip, int(port)))
return True, None
except Exception as ex:
return False, str(ex)
finally:
try:
s.close()
except Exception:
pass
# ------------------------------------------------------
# Apps cache
# ------------------------------------------------------
def cache_path_for(dev_name):
CACHE_DIR.mkdir(parents=True, exist_ok=True)
return CACHE_DIR / f"apps_{dev_name}.json"
def load_apps_cached(cfg, dev, retries, refresh=False):
ttl = cfg["behavior"].get("apps_cache_ttl_seconds", 21600)
cpath = cache_path_for(dev["name"])
if not refresh and cpath.exists():
try:
blob = json.loads(cpath.read_text())
ts = blob.get("ts", 0)
age = time.time() - float(ts)
if age <= ttl and isinstance(blob.get("apps"), dict):
return blob["apps"], {"source": "cache", "age_seconds": age, "count": len(blob["apps"])}
except Exception:
pass
apps = fetch_apps(cfg, dev, retries)
save_apps_cache(dev["name"], apps)
return apps, {"source": "live", "age_seconds": 0, "count": len(apps)}
def save_apps_cache(dev_name, apps):
cpath = cache_path_for(dev_name)
blob = {"ts": time.time(), "apps": apps}
cpath.write_text(json.dumps(blob, indent=2, sort_keys=False) + "\n")
def fetch_apps(cfg, dev, retries):
xml = http_get(dev, "/query/apps", retries)
root = ET.fromstring(xml)
outd = {}
for app in root.findall("app"):
name = normalize((app.text or "").strip()).lower()
app_id = app.get("id", "")
if name and app_id:
outd[name] = app_id
return outd
# ------------------------------------------------------
# Matching: aliases, exact, partial, fuzzy
# ------------------------------------------------------
def canonical_name(cfg, name):
name = normalize(name).lower()
return cfg.get("aliases", {}).get(name, name)
def find_app_match(cfg, apps, raw_name):
"""
Returns (matched_name, reason, candidates)
- matched_name: exact app name in `apps` keys, or None
- reason: string
- candidates: list of possible matches (for did-you-mean)
"""
q = canonical_name(cfg, raw_name)
if q in apps:
return q, "exact", []
# partial matches
partial = [k for k in apps.keys() if q in k]
if len(partial) == 1:
return partial[0], "partial", []
if len(partial) > 1:
# try "starts with" to narrow
starts = [k for k in partial if k.startswith(q)]
if len(starts) == 1:
return starts[0], "starts_with", []
candidates = sorted(partial)[:10]
return None, "ambiguous_partial", candidates
# fuzzy matches
close = difflib.get_close_matches(q, list(apps.keys()), n=5, cutoff=0.76)
if len(close) == 1:
return close[0], "fuzzy", []
if len(close) > 1:
return None, "ambiguous_fuzzy", close
return None, "not_found", []
# ------------------------------------------------------
# Lights
# ------------------------------------------------------
def lights_allowed(cfg):
if G["no_lights"]:
return False
if G["lights"] is True:
return True
if G["lights"] is False:
return False
return bool(cfg["behavior"].get("default_lights", False))
def lights_bin(cfg):
return cfg.get("lights", {}).get("bin", DEFAULT_CONFIG["lights"]["bin"])
def run_lights(cfg, args, quiet=True, force=False):
# --no-lights blocks everything, even work/shutdown
if G["no_lights"]:
return 0
# Normal behavior: only allowed when --lights (or default_lights=true)
if not force and not lights_allowed(cfg):
return 0
lb = lights_bin(cfg)
cmd = [lb] + list(args)
debug(f"[LIGHTS] run: {' '.join(cmd)}")
if G["dry_run"]:
out(f"[DRY] lights {' '.join(args)}")
return 0
kwargs = {}
if quiet or G["quiet"]:
kwargs["stdout"] = subprocess.DEVNULL
kwargs["stderr"] = subprocess.DEVNULL
try:
r = subprocess.run(cmd, **kwargs)
return r.returncode
except Exception as ex:
eprint(f"[LIGHTS] failed: {ex}")
return 1
def apply_light_scene(cfg, app_name, force=False):
if not force and not lights_allowed(cfg):
return
scene_map = cfg.get("light_scenes", {})
cmd = scene_map.get(app_name)
if not cmd:
out(f"[ROKU] No light scene mapped for: {app_name}")
return
out(f"[ROKU] Applying light scene for: {app_name}")
run_lights(cfg, cmd, quiet=True)
# ------------------------------------------------------
# Wake / assert power
# ------------------------------------------------------
def wake_enabled(cfg):
if G["wake"] is True:
return True
if G["wake"] is False:
return False
return bool(cfg["behavior"].get("default_wake", False))
def ensure_or_exit_awake(cfg, dev, retries, context_cmd):
p = tv_power_state(dev, retries)
if p == "PowerOn":
return True
if wake_enabled(cfg):
out("[ROKU] TV is off or asleep. Powering on because --wake is enabled.")
keypress(dev, retries, "Power")
time.sleep(2.5)
return True
if context_cmd == "power":
return True
out("[ROKU] TV is off or asleep. Skipping command. Use --wake to power on automatically.")
return False
def _sleep(seconds: float):
if seconds <= 0:
return
if G["dry_run"]:
out(f"[DRY] sleep {seconds}")
else:
time.sleep(seconds)
def _sleep_jitter(base: float, jmin: float, jmax: float):
"""
Sleep for base seconds, plus an optional uniform random jitter in [jmin, jmax].
If jitter is disabled (<=0 or max < min), behaves like a normal base sleep.
"""
base = float(base or 0.0)
try:
jmin = float(jmin or 0.0)
jmax = float(jmax or 0.0)
except Exception:
jmin = 0.0
jmax = 0.0
extra = 0.0
if jmax > 0.0 and jmax >= jmin:
extra = random.uniform(jmin, jmax)
_sleep(base + extra)
# ------------------------------------------------------
# Keypress / typing
# ------------------------------------------------------
def keypress(*args, **kwargs):
"""
Backward compatible keypress.
Supports BOTH:
- keypress(dev, retries, keyname, n=1, cfg=None)
- keypress(cfg, dev, retries, keyname, n=1)
Disambiguation:
- If args[0] looks like a Roku dev dict (has base_url), treat as old style.
- If args[0] looks like a config dict (has behavior/devices) AND args[1] looks like dev dict, treat as new style.
"""
if len(args) < 3:
raise TypeError("keypress() missing required arguments")
def looks_like_dev(x):
return isinstance(x, dict) and ("base_url" in x or ("ip" in x and "port" in x))
def looks_like_cfg(x):
return isinstance(x, dict) and ("behavior" in x or "devices" in x or "macros" in x)
cfg = None
# OLD style: keypress(dev, retries, keyname, n=1, cfg=None)
if looks_like_dev(args[0]):
dev = args[0]
retries = args[1]
keyname = args[2]
n = args[3] if len(args) >= 4 else kwargs.get("n", 1)
cfg = kwargs.get("cfg", None)
# NEW style: keypress(cfg, dev, retries, keyname, n=1)
elif looks_like_cfg(args[0]) and len(args) >= 4 and looks_like_dev(args[1]):
cfg = args[0]
dev = args[1]
retries = args[2]
keyname = args[3]
n = args[4] if len(args) >= 5 else kwargs.get("n", 1)
else:
# Fall back to old style layout to avoid dev becoming int
dev = args[0]
retries = args[1]
keyname = args[2]
n = args[3] if len(args) >= 4 else kwargs.get("n", 1)
cfg = kwargs.get("cfg", None)
keyname = normalize(keyname).lower()
real = KEY_ALIASES.get(keyname, None)
if real is None:
# if user passes exact Roku name, accept it
real = normalize(keyname)
real = real[:1].upper() + real[1:]
# Behavior source: cfg if provided, else load_config()
if not isinstance(cfg, dict):
try:
cfg = load_config()
except Exception:
cfg = {}
beh = (cfg.get("behavior", {}) or {}) if isinstance(cfg, dict) else {}
# Optional extra gap for volume keys to prevent "jumping"
# Resolution order:
# - per-direction override (volume_up_press_gap / volume_down_press_gap)
# - shared fallback (volume_press_gap)
# - None (disabled)
def _get_gap_for(real_key: str):
base_gap = beh.get("volume_press_gap", None)
up_gap = beh.get("volume_up_press_gap", None)
down_gap = beh.get("volume_down_press_gap", None)
chosen = None
if real_key == "VolumeUp":
chosen = up_gap if up_gap is not None else base_gap
elif real_key == "VolumeDown":
chosen = down_gap if down_gap is not None else base_gap
if chosen is None:
return None
try:
chosen = float(chosen)
except Exception:
return None
if chosen <= 0:
return None
return chosen
presses = max(1, int(n))
for i in range(presses):
# Optional jitter for repeated keys that are sensitive to "machine-gun" timing
if i < presses - 1:
if real in ("VolumeUp", "VolumeDown"):
_sleep_jitter(0.0, beh.get("volume_jitter_min", 0.0), beh.get("volume_jitter_max", 0.0))
elif real in ("Up", "Down", "Left", "Right"):
_sleep_jitter(0.0, beh.get("nav_jitter_min", 0.0), beh.get("nav_jitter_max", 0.0))
if G["dry_run"]:
out(f"[DRY] keypress {real}")
else:
http_post(dev, f"/keypress/{real}", retries)
# Add only the missing time beyond rate_delay for volume keys
if real in ("VolumeUp", "VolumeDown") and i < presses - 1:
desired_gap = _get_gap_for(real)
if desired_gap is not None:
extra = max(0.0, float(desired_gap) - float(dev.get("rate_delay", 0.0)))
if extra > 0:
if G["dry_run"]:
out(f"[DRY] sleep {extra}")
else:
time.sleep(extra)
# ------------------------------------------------------
# Volume helpers
# ------------------------------------------------------
def _chunked_counts(total, chunk_size):
total = int(total)
chunk_size = max(1, int(chunk_size))
parts = []
while total > 0:
take = min(chunk_size, total)
parts.append(take)
total -= take
return parts
def volume_zero_out(cfg, dev, retries, downs=None):
"""
Zero-out behavior.
Preferred: hold VolumeDown for a fixed duration (ms), because DOWN can be fast safely.
Fallback: repeated VolumeDown presses.
"""
beh = (cfg.get("behavior", {}) or {}) if isinstance(cfg, dict) else {}
# Preferred hold duration (ms)
hold_ms = beh.get("zero_out_hold_ms", None)
try:
hold_ms = int(hold_ms) if hold_ms is not None else None
except Exception:
hold_ms = None
if hold_ms is not None and hold_ms > 0:
out(f"[ROKU] Volume zero-out hold {hold_ms}ms")
if G["dry_run"]:
out(f"[DRY] hold VolumeDown {hold_ms}ms")
return
hold_key(dev, retries, "VolumeDown", hold_ms)
return
# Fallback to old press-based behavior if hold not configured
if downs is None:
downs = int(beh.get("zero_out_down_presses", 8))
downs = int(downs)
if downs <= 0:
return
out(f"[ROKU] Volume zero-out x{downs}")
if G["dry_run"]:
return
keypress(dev, retries, "VolumeDown", downs)
def smart_volume(cfg, dev, retries, direction, n, chunk=None, chunk_pause=None):
"""
Volume presses with optional chunking for pacing.
Important: n means "number of keypresses" (not "volume units").
Chunking is only used to insert pauses during larger adjustments.
"""
direction = normalize(direction).lower()
n = int(n)
if n <= 0:
return
if direction not in ("up", "down"):
raise RuntimeError(f"smart_volume invalid direction: {direction}")
# Default chunk size (only affects pacing, not scaling)
if chunk is None:
chunk = int(cfg.get("behavior", {}).get("volume_chunk", 2))
# Direction-specific default pause
if chunk_pause is None:
beh = cfg.get("behavior", {}) or {}
if direction == "up":
chunk_pause = float(beh.get("volume_chunk_pause_up", beh.get("volume_chunk_pause", 1.75)))
else:
chunk_pause = float(beh.get("volume_chunk_pause_down", beh.get("volume_chunk_pause", 1.75)))
chunk = max(1, int(chunk))
chunk_pause = float(chunk_pause)
key = "VolumeUp" if direction == "up" else "VolumeDown"
# Small adjustments: just press directly, no chunking
if n <= chunk:
keypress(cfg, dev, retries, key, n)
return
# Larger adjustments: chunk for pacing
parts = _chunked_counts(n, chunk)
for i, take in enumerate(parts):
keypress(cfg, dev, retries, key, take)
if i < len(parts) - 1:
if G["dry_run"]:
out(f"[DRY] sleep {chunk_pause}")
else:
time.sleep(chunk_pause)
def volume_set(cfg, dev, retries, target, zero_down=None, chunk=None, chunk_pause=None):
"""
Set volume to target "number" by:
1) zero out fast (downs or hold)
2) smart up to target (with optional overrides)
"""
target = int(target)
if target < 0:
target = 0
volume_zero_out(cfg, dev, retries, downs=zero_down)
if target > 0:
smart_volume(cfg, dev, retries, "up", target, chunk=chunk, chunk_pause=chunk_pause)
def run_pre_launch(cfg, dev, retries, app_name):
"""
Optional pre-launch actions that run immediately after /launch is sent.
This is where we can zero out or set volume while the app is still loading.
"""
pre = cfg.get("pre_launch") or {}
rule = pre.get(app_name)
if not isinstance(rule, dict):
return
# Option 1: set volume (fast zero, then smart up) during load
if "set_volume" in rule:
try:
target = int(rule.get("set_volume"))
except Exception:
return
zero_down = rule.get("zero_down")
if zero_down is not None:
try:
zero_down = int(zero_down)
except Exception:
zero_down = None
out(f"[ROKU] Pre-launch set volume: {target}")
# Optional per-app overrides for the set-volume pacing
chunk = rule.get("chunk")
chunk_pause = rule.get("chunk_pause")
if chunk is not None:
try:
chunk = int(chunk)
except Exception:
chunk = None
if chunk_pause is not None:
try:
chunk_pause = float(chunk_pause)
except Exception:
chunk_pause = None
volume_set(cfg, dev, retries, target, zero_down=zero_down, chunk=chunk, chunk_pause=chunk_pause)
return
# Option 2: just zero out fast during load
if "zero_out_down" in rule:
try:
downs = int(rule.get("zero_out_down"))
except Exception:
downs = None
out("[ROKU] Pre-launch volume zero-out")
volume_zero_out(cfg, dev, retries, downs=downs)
return
# ------------------------------------------------------
# Post-launch actions (volume sequences, etc.)
# ------------------------------------------------------
def _chunked_taps(total, chunk_size):
total = int(total)