pilotdroid 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pilotdroid/u2shim.py ADDED
@@ -0,0 +1,1157 @@
1
+ #!/usr/bin/env python3
2
+ """pilotdroid u2-compat shim v0 (ADR-005: host-side translation layer).
3
+
4
+ Drop-in-ish subset of uiautomator2's top-level API backed by the PD01
5
+ agent — same call surface, persistent session (u2 pays a JSON-RPC HTTP
6
+ round-trip per call; shim pays one socket op).
7
+
8
+ import u2shim as u2
9
+ d = u2.connect(port=17932)
10
+ d.click(360, 1600); d(text="OK").click(); d.press("back")
11
+
12
+ Covered: connect / click(x,y) / long_click / swipe / press / set_text /
13
+ clear_text / dump_hierarchy / screenshot / shell / app_start / app_stop /
14
+ app_current / app_list / app_info / info / window_size / screen_on /
15
+ screen_off / unlock / orientation (get+set) / watcher;
16
+ d(text|resourceId|description|className|packageName|scrollable,index).click() /
17
+ .exists / .wait / .info / .set_text / .get_text / .long_click /
18
+ d(scrollable=True).scroll.(forward|backward|toEnd|toBeginning).
19
+ M18 additions (RESULTS-M17 G-gap closure): settings dict (transparent,
20
+ no type-validation/wait_timeout coupling), app_start front-wait +
21
+ stop=True, click implicit wait, swipe host-side duration sleep, push /
22
+ pull / wlan_ip / app_list_running / app_auto_grant_permissions /
23
+ watch_context, uiautomator2.exceptions submodule (SessionBrokenError /
24
+ UiObjectNotFoundError).
25
+ (xpath still rejected with ValueError — see _SUPPORTED.)
26
+ """
27
+ import os, re, socket, subprocess, sys, threading, time, types
28
+ import xml.etree.ElementTree as ET
29
+
30
+ try:
31
+ from .agent_client import (Agent, media_connect, # installed `pilotdroid` package
32
+ read_frame)
33
+ except ImportError:
34
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__),
35
+ "..", "agent", "scripts"))
36
+ from agent_client import Agent, media_connect, read_frame # noqa: E402
37
+
38
+ _KEYCODES = {"home": 3, "back": 4, "recent": 187, "recents": 187,
39
+ "power": 26, "volume_up": 24, "volume_down": 25,
40
+ "menu": 82, "search": 84, "enter": 66, "del": 67}
41
+
42
+ # u2's implicit wait budget for click()/exists-style resolves. u2's
43
+ # settings['wait_timeout'] defaults to 20s; the agent control socket
44
+ # times out at 10s so the shim stays under it.
45
+ _IMPLICIT_WAIT = 8.0
46
+
47
+
48
+ class SessionBrokenError(Exception):
49
+ """u2 `uiautomator2.exceptions.SessionBrokenError` — a session's
50
+ target app died mid-use. The shim does not run u2's crash-watch
51
+ relaunch loop; the symbol exists so verbatim `import`/`raises` sites
52
+ compile (they fail honestly if never raised)."""
53
+
54
+
55
+ # shim's no-node signal IS u2's UiObjectNotFoundError role — alias so
56
+ # `except u2.UiObjectNotFoundError` catches the same exception.
57
+ UiObjectNotFoundError = LookupError
58
+
59
+ # `from uiautomator2.exceptions import X` — shim is a module, not a
60
+ # package; register a synthetic submodule so drop-in imports work.
61
+ # setdefault never clobbers a real uiautomator2 install.
62
+ _exc_mod = types.ModuleType("uiautomator2.exceptions")
63
+ _exc_mod.SessionBrokenError = SessionBrokenError
64
+ _exc_mod.UiObjectNotFoundError = UiObjectNotFoundError
65
+ sys.modules.setdefault("uiautomator2.exceptions", _exc_mod)
66
+ sys.modules.setdefault(__name__ + ".exceptions", _exc_mod)
67
+
68
+
69
+ def _rid_eq(rid, v):
70
+ return rid == v or rid.endswith(":id/" + v)
71
+
72
+
73
+ def _cls_eq(cls, v):
74
+ return cls == v or cls.rsplit(".", 1)[-1] == v
75
+
76
+
77
+ # bool selector kwargs → a11y XML attribute names
78
+ _BOOL_KEYS = {"clickable": "clickable", "checkable": "checkable",
79
+ "checked": "checked", "enabled": "enabled",
80
+ "focusable": "focusable", "focused": "focused",
81
+ "selected": "selected", "longClickable": "long-clickable",
82
+ "scrollable": "scrollable"}
83
+
84
+ # host-side predicate per selector key (dump+post-filter path, M12)
85
+ _PRED = {
86
+ "text": lambda i, v: i["text"] == v,
87
+ "textContains": lambda i, v: v in i["text"],
88
+ "textStartsWith": lambda i, v: i["text"].startswith(v),
89
+ "textMatches": lambda i, v:
90
+ re.fullmatch(v, i["text"] or "") is not None,
91
+ "resourceId": lambda i, v: _rid_eq(i["id"], v),
92
+ "resourceIdMatches": lambda i, v:
93
+ re.fullmatch(v, i["id"] or "") is not None,
94
+ "description": lambda i, v: i["desc"] == v,
95
+ "descriptionContains": lambda i, v: v in i["desc"],
96
+ "descriptionStartsWith": lambda i, v: i["desc"].startswith(v),
97
+ "descriptionMatches": lambda i, v:
98
+ re.fullmatch(v, i["desc"] or "") is not None,
99
+ "className": lambda i, v: _cls_eq(i["class"], v),
100
+ "classNameMatches": lambda i, v:
101
+ re.fullmatch(v, i["class"] or "") is not None,
102
+ "packageName": lambda i, v: i["pkg"] == v,
103
+ "packageNameMatches": lambda i, v:
104
+ re.fullmatch(v, i["pkg"] or "") is not None,
105
+ # u2 `index` = child position among siblings (the a11y `index` attr);
106
+ # `instance` (Nth-match) is positional — applied in _node, not here.
107
+ "index": lambda i, v: i["index"] == int(v),
108
+ }
109
+ _PRED.update({k: (lambda a: lambda i, v:
110
+ i["attrs"].get(a, False) == bool(v))(a)
111
+ for k, a in _BOOL_KEYS.items()})
112
+
113
+ # keys the wire QUERY op can evaluate device-side (exact AND). `index` is
114
+ # deliberately NOT here — u2's `index` is the node's child-position attr
115
+ # (host-filter predicate below); the wire `index` field means Nth-match,
116
+ # which is what u2 calls `instance` — we map instance→wire index.
117
+ _WIRE_KEYS = ("text", "resourceId", "description", "className",
118
+ "packageName", "scrollable", "instance")
119
+
120
+ # spatial directions → (node-bound edge, anchor-bound edge, must hold)
121
+ _REL = {"left": lambda nb, ab: nb[2] <= ab[0],
122
+ "right": lambda nb, ab: nb[0] >= ab[2],
123
+ "up": lambda nb, ab: nb[3] <= ab[1],
124
+ "down": lambda nb, ab: nb[1] >= ab[3]}
125
+
126
+
127
+ def _info(el):
128
+ b = [int(x) for x in re.findall(r"-?\d+", el.get("bounds", ""))[:4]]
129
+ a = el.attrib
130
+ return {"bounds": b if len(b) == 4 else [0, 0, 0, 0],
131
+ "text": a.get("text", ""), "id": a.get("resource-id", ""),
132
+ "desc": a.get("content-desc", ""), "class": a.get("class", ""),
133
+ "pkg": a.get("package", ""),
134
+ "index": int(a.get("index", 0)),
135
+ "attrs": {k: a.get(v) == "true"
136
+ for k, v in _BOOL_KEYS.items()}}
137
+
138
+
139
+ class _Selector:
140
+ """Lazy selector bound to a device — resolves via QUERY on use, or
141
+ via dump+post-filter when a key the wire can't express is present
142
+ (contains/matches/attrs/spatial — M12 host-filter batch)."""
143
+
144
+ def __init__(self, dev, _base=None, _rel=None, **kw):
145
+ self.dev, self.kw = dev, kw
146
+ self._base, self._rel = _base, _rel # relative selector (left/…)
147
+
148
+ def _wireable(self):
149
+ return self._rel is None and all(k in _WIRE_KEYS for k in self.kw)
150
+
151
+ def _sel(self):
152
+ """Wire QUERY selector — only exact-match keys. Host-only keys are
153
+ a hard error here (dropping them would widen the match!)."""
154
+ bad = [k for k in self.kw if k not in _WIRE_KEYS]
155
+ if bad:
156
+ raise ValueError(
157
+ f"u2shim selector: keys {bad} need host post-filter "
158
+ f"(not wire-expressible); xpath not supported")
159
+ s = {}
160
+ if "text" in self.kw:
161
+ s["text"] = self.kw["text"]
162
+ if "resourceId" in self.kw:
163
+ rid = self.kw["resourceId"]
164
+ s["id"] = rid.split(":id/")[-1] # agent accepts bare name
165
+ if "description" in self.kw:
166
+ s["desc"] = self.kw["description"]
167
+ if "className" in self.kw:
168
+ s["class"] = self.kw["className"] # full or simple name
169
+ if "packageName" in self.kw:
170
+ s["pkg"] = self.kw["packageName"] # exact package match
171
+ if "scrollable" in self.kw:
172
+ s["scrollable"] = bool(self.kw["scrollable"])
173
+ if "instance" in self.kw:
174
+ s["index"] = int(self.kw["instance"]) # wire index = Nth-match
175
+ return s
176
+
177
+ def _kw_match(self, info):
178
+ bad = [k for k in self.kw
179
+ if k not in _PRED and k != "instance"]
180
+ if bad:
181
+ raise ValueError(
182
+ f"u2shim selector: unsupported keys {bad} "
183
+ f"(xpath not supported)")
184
+ return all(_PRED[k](info, v)
185
+ for k, v in self.kw.items()
186
+ if k != "instance")
187
+
188
+ def _index(self):
189
+ """u2 `instance` = Nth-match positional pick (0-based)."""
190
+ return int(self.kw.get("instance", 0))
191
+
192
+ def _resolve(self, pairs, parent):
193
+ """(el, info) hit pairs against an already-parsed tree. Recursive —
194
+ the relative-selector anchor is the BASE'S OWN resolution, so
195
+ chained `d(A).child(B).left(C)` resolves A→B→C correctly."""
196
+ if self._rel is None:
197
+ return [p for p in pairs if self._kw_match(p[1])]
198
+ base_hits = self._base._resolve(pairs, parent)
199
+ bi = self._base._index() # base's own `instance` positional pick
200
+ if not 0 <= bi < len(base_hits):
201
+ return []
202
+ ael, ab = base_hits[bi][0], base_hits[bi][1]["bounds"]
203
+ if self._rel == "child":
204
+ desc = {id(e) for e in ael.iter()} - {id(ael)}
205
+ return [p for p in pairs
206
+ if id(p[0]) in desc and self._kw_match(p[1])]
207
+ if self._rel == "sibling":
208
+ par = parent.get(ael)
209
+ sib = ({id(e) for e in par} - {id(ael)}
210
+ if par is not None else set())
211
+ return [p for p in pairs
212
+ if id(p[0]) in sib and self._kw_match(p[1])]
213
+ dir_ok = _REL[self._rel]
214
+ return [p for p in pairs if self._kw_match(p[1])
215
+ and dir_ok(p[1]["bounds"], ab)]
216
+
217
+ def _nodes(self):
218
+ """All matching nodes (one dump). Spatial/child/sibling resolve
219
+ here too — they need the full tree anyway."""
220
+ xml = self.dev.dump_hierarchy()
221
+ root = ET.fromstring(xml)
222
+ parent = {}
223
+ for el in root.iter("node"):
224
+ for ch in el:
225
+ parent[ch] = el
226
+ pairs = [(el, _info(el)) for el in root.iter("node")]
227
+ return [p[1] for p in self._resolve(pairs, parent)]
228
+
229
+ def _node(self):
230
+ if self._wireable():
231
+ r = self.dev.a.query(self._sel())["payload"]
232
+ return r.get("node") if r.get("found") else None
233
+ ns = self._nodes()
234
+ i = self._index()
235
+ return ns[i] if 0 <= i < len(ns) else None
236
+
237
+ @property
238
+ def exists(self):
239
+ return self._node() is not None
240
+
241
+ @property
242
+ def count(self):
243
+ """u2 `d(...).count` — real match count (dump+post-filter)."""
244
+ return len(self._nodes())
245
+
246
+ @property
247
+ def info(self):
248
+ return self._node()
249
+
250
+ def wait(self, timeout=10.0):
251
+ """u2 semantics: True when the selector appears within timeout,
252
+ False otherwise. The wireable path polls wait_until in <=1s
253
+ slices — a single long wait_until would hog the shared control
254
+ conn and starve concurrent ops (watcher arming; u2suite's
255
+ test_watch_context deadlocks on exactly this)."""
256
+ deadline = time.time() + timeout
257
+ if self._wireable():
258
+ while True:
259
+ slice_ms = int(min(1000,
260
+ max(50, (deadline - time.time())
261
+ * 1000)))
262
+ r = self.dev.a.wait_until(self._sel(), slice_ms)
263
+ if r["payload"]["results"][0]["code"] == "OK":
264
+ return True
265
+ if time.time() >= deadline:
266
+ return False
267
+ while time.time() < deadline:
268
+ if self._node() is not None:
269
+ return True
270
+ time.sleep(0.1)
271
+ return False
272
+
273
+ def wait_gone(self, timeout=10.0):
274
+ """u2 `d(...).wait_gone(t)` — True once no node matches."""
275
+ deadline = time.time() + timeout
276
+ while time.time() < deadline:
277
+ if self._node() is None:
278
+ return True
279
+ time.sleep(0.1)
280
+ return False
281
+
282
+ def _rel_sel(self, rel, other, kw):
283
+ if isinstance(other, _Selector):
284
+ if kw:
285
+ raise ValueError("pass either a Selector or kwargs")
286
+ kw = other.kw
287
+ elif other is not None:
288
+ kw.setdefault("text", other)
289
+ return _Selector(self.dev, _base=self, _rel=rel, **kw)
290
+
291
+ def left(self, other=None, **kw):
292
+ return self._rel_sel("left", other, kw)
293
+
294
+ def right(self, other=None, **kw):
295
+ return self._rel_sel("right", other, kw)
296
+
297
+ def up(self, other=None, **kw):
298
+ return self._rel_sel("up", other, kw)
299
+
300
+ def down(self, other=None, **kw):
301
+ return self._rel_sel("down", other, kw)
302
+
303
+ def child(self, other=None, **kw):
304
+ return self._rel_sel("child", other, kw)
305
+
306
+ def sibling(self, other=None, **kw):
307
+ return self._rel_sel("sibling", other, kw)
308
+
309
+ def click(self, timeout=None):
310
+ """u2 `d(...).click(timeout)` — u2 resolves the object with an
311
+ implicit wait (settings['wait_timeout'], 20s upstream default);
312
+ M17-G2: the shim previously resolved immediately and raced
313
+ activity transitions. timeout=None → _IMPLICIT_WAIT (8s, under
314
+ the agent socket ceiling); timeout=0 opts out (resolve now)."""
315
+ if timeout is None:
316
+ timeout = _IMPLICIT_WAIT
317
+ if timeout:
318
+ ok = self.wait(timeout)
319
+ node = self._node() if ok else None
320
+ else:
321
+ node = self._node()
322
+ if node is None:
323
+ raise LookupError(f"selector {self.kw} found no node")
324
+ l, t, r_, b = node["bounds"]
325
+ return self.dev.click((l + r_) / 2, (t + b) / 2)
326
+
327
+ def get_text(self):
328
+ """u2 `d(...).get_text()` — the matched node's text."""
329
+ node = self._node()
330
+ if node is None:
331
+ raise LookupError(f"selector {self.kw} found no node")
332
+ return node.get("text")
333
+
334
+ def set_text(self, s):
335
+ # u2 semantics: click the field first, then set
336
+ node = self._node()
337
+ if node is not None:
338
+ l, t, r_, b = node["bounds"]
339
+ self.dev.click((l + r_) / 2, (t + b) / 2)
340
+ return self.dev.set_text(s)
341
+
342
+ def long_click(self, duration=0.5):
343
+ node = self._node()
344
+ if node is None:
345
+ raise LookupError(f"selector {self.kw} found no node")
346
+ l, t, r_, b = node["bounds"]
347
+ return self.dev.long_click((l + r_) / 2, (t + b) / 2, duration)
348
+
349
+ def center(self):
350
+ """u2 `d(...).center()` -> (x, y) of the matched node's center."""
351
+ node = self._node()
352
+ if node is None:
353
+ raise LookupError(f"selector {self.kw} found no node")
354
+ l, t, r, b = node["bounds"]
355
+ return ((l + r) // 2, (t + b) // 2)
356
+
357
+ def swipe(self, direction, scale=0.8):
358
+ """u2 `d(...).swipe('left'|'right'|'up'|'down')` — swipe inside the
359
+ matched node's bounds (finger moves `direction` over `scale` of it)."""
360
+ node = self._node()
361
+ if node is None:
362
+ raise LookupError(f"selector {self.kw} found no node")
363
+ l, t, r, b = node["bounds"]
364
+ dx, dy = {"left": (-1, 0), "right": (1, 0),
365
+ "up": (0, -1), "down": (0, 1)}[str(direction).lower()]
366
+ cx, cy = (l + r) / 2, (t + b) / 2
367
+ w, h = r - l, b - t
368
+ return self.dev.swipe(cx - dx * w * scale / 2,
369
+ cy - dy * h * scale / 2,
370
+ cx + dx * w * scale / 2,
371
+ cy + dy * h * scale / 2)
372
+
373
+ def gesture(self, start1, start2, end1, end2, steps=100):
374
+ """u2 `d(...).gesture(p1, p2, p3, p4)` — two-pointer gesture scoped
375
+ to the element (pinch/drag class): ptrA start1->end1, ptrB
376
+ start2->end2 (CAP_MULTI_PTR required)."""
377
+ if self._node() is None:
378
+ raise LookupError(f"selector {self.kw} found no node")
379
+ n = max(1, int(steps))
380
+ pts = [{"action": 0, "pid": 0, "x": float(start1[0]),
381
+ "y": float(start1[1]), "t_ms": 0},
382
+ {"action": 0, "pid": 1, "x": float(start2[0]),
383
+ "y": float(start2[1]), "t_ms": 0}]
384
+ for i in range(1, n + 1):
385
+ f = i / n
386
+ pts += [{"action": 1 if i == n else 2, "pid": 0,
387
+ "x": start1[0] + (end1[0] - start1[0]) * f,
388
+ "y": start1[1] + (end1[1] - start1[1]) * f,
389
+ "t_ms": i * 10},
390
+ {"action": 1 if i == n else 2, "pid": 1,
391
+ "x": start2[0] + (end2[0] - start2[0]) * f,
392
+ "y": start2[1] + (end2[1] - start2[1]) * f,
393
+ "t_ms": i * 10}]
394
+ return self.dev.a.inject_multi(pts)["payload"].get("ok", False)
395
+
396
+ def _pinch(self, outward, percent=100, steps=10, duration=0.2):
397
+ """u2 `d().pinch_in/out(percent, steps)` — two-pointer gesture over
398
+ the matched node's bounds (CAP_MULTI_PTR agent required)."""
399
+ node = self._node()
400
+ if node is None:
401
+ raise LookupError(f"selector {self.kw} found no node")
402
+ l, t, r, b = node["bounds"]
403
+ # MIUI dialogs can report bounds outside the display (e.g.
404
+ # [268,3312] on a 3200px-tall screen) — an unclamped center
405
+ # injects at coordinates nothing can receive.
406
+ w, h = self.dev.a.hello()["payload"]["display"]
407
+ if r <= 0 or l >= w or b <= 0 or t >= h:
408
+ raise LookupError(
409
+ f"node bounds {node['bounds']} fully outside display {w}x{h}")
410
+ cx = min(max((l + r) / 2, 0), w - 1)
411
+ cy = min(max((t + b) / 2, 0), h - 1)
412
+ half = (r - l) / 2
413
+ edge = half * 0.9 * min(percent, 100) / 100.0
414
+ r0, r1 = (half * 0.9, edge) if not outward else (edge, half * 0.9)
415
+ r0, r1 = min(r0, cx, w - 1 - cx), min(r1, cx, w - 1 - cx)
416
+ if r0 < 2 or r1 < 2:
417
+ raise LookupError(
418
+ f"node bounds {node['bounds']} outside display {w}x{h}")
419
+ dur_ms = int(duration * 1000)
420
+ pts = [{"action": 0, "pid": 0, "x": cx - r0, "y": cy, "t_ms": 0},
421
+ {"action": 0, "pid": 1, "x": cx + r0, "y": cy, "t_ms": 10}]
422
+ for i in range(1, steps + 1):
423
+ f = i / (steps + 1)
424
+ d = r0 + (r1 - r0) * f
425
+ pts += [{"action": 2, "pid": 0, "x": cx - d, "y": cy,
426
+ "t_ms": 10 + int(dur_ms * f)},
427
+ {"action": 2, "pid": 1, "x": cx + d, "y": cy,
428
+ "t_ms": 10 + int(dur_ms * f)}]
429
+ pts += [{"action": 1, "pid": 1, "x": cx + r1, "y": cy,
430
+ "t_ms": 10 + dur_ms},
431
+ {"action": 1, "pid": 0, "x": cx - r1, "y": cy,
432
+ "t_ms": 20 + dur_ms}]
433
+ return self.dev.a.inject_multi(pts)["payload"].get("ok", False)
434
+
435
+ def pinch_in(self, percent=100, steps=10):
436
+ return self._pinch(False, percent, steps)
437
+
438
+ def pinch_out(self, percent=100, steps=10):
439
+ return self._pinch(True, percent, steps)
440
+
441
+ @property
442
+ def scroll(self):
443
+ """u2 `d(scrollable=True).scroll.<dir>` — swipes inside the
444
+ matched scrollable node's bounds. forward/backward = one
445
+ viewport; toEnd/toBeginning = repeat until content stops
446
+ changing (dump-hash stable) or 10 swipes."""
447
+ node = self._node()
448
+ if node is None:
449
+ raise LookupError(f"selector {self.kw} found no node")
450
+ return _Scroll(self.dev, node["bounds"])
451
+
452
+
453
+ class _Scroll:
454
+ def __init__(self, dev, bounds):
455
+ self.dev, self.b = dev, bounds
456
+
457
+ def _once(self, forward=True):
458
+ l, t, r, b = self.b
459
+ cx, h = (l + r) / 2, b - t
460
+ y_from = t + h * (0.8 if forward else 0.2)
461
+ y_to = t + h * (0.2 if forward else 0.8)
462
+ return self.dev.swipe(cx, y_from, cx, y_to, duration=0.2)
463
+
464
+ def forward(self):
465
+ return self._once(True)
466
+
467
+ def backward(self):
468
+ return self._once(False)
469
+
470
+ def _to(self, forward, max_swipes=10):
471
+ prev = ""
472
+ for _ in range(max_swipes):
473
+ cur = hash(self.dev.dump_hierarchy())
474
+ if cur == prev:
475
+ return True
476
+ prev = cur
477
+ self._once(forward)
478
+ time.sleep(0.4)
479
+ return False
480
+
481
+ def toEnd(self):
482
+ return self._to(True)
483
+
484
+ def toBeginning(self):
485
+ return self._to(False)
486
+
487
+
488
+ class _WhenCtx:
489
+ """One watcher rule builder: `d.watcher.when(text='x').click()`."""
490
+
491
+ def __init__(self, watcher, kw):
492
+ self._w, self.kw = watcher, kw
493
+
494
+ def click(self):
495
+ def action():
496
+ _Selector(self._w.dev, **self.kw).click()
497
+ action._pd_click = True # armed device-side: don't re-click
498
+ self._w._rules.append((self.kw, action))
499
+ return self._w
500
+
501
+ def call(self, func):
502
+ """u2 `watcher.when(sel).call(fn)` — run arbitrary callback on
503
+ match (test_xpath::test_watcher uses this)."""
504
+ self._w._rules.append((self.kw, func))
505
+ return self._w
506
+
507
+
508
+ class _Watcher:
509
+ """u2 `d.watcher` parity — host-side poll thread (u2 polls inside its
510
+ server; the semantic is the same: when a registered selector appears,
511
+ run its action once). Rules fire once each; the thread exits when all
512
+ have fired or `.stop()` is called."""
513
+
514
+ def __init__(self, dev, interval=2.0):
515
+ self.dev, self.interval = dev, interval
516
+ self._rules = [] # [(selector_kw, action)]
517
+ self._th = None
518
+ self._running = False # u2 watcher runs until .stop(), even
519
+ # with zero rules (u2suite caught the
520
+ # run-exits-on-empty race)
521
+
522
+ def when(self, *args, **kw):
523
+ # u2 allows positional text / resourceId strings
524
+ for a in args:
525
+ kw["text" if "text" not in kw else "description"] = a
526
+ return _WhenCtx(self, kw)
527
+
528
+ def _tick(self):
529
+ # device mode (CAP_WATCH): the poll loop runs inside the agent —
530
+ # detection latency = one tree-walk, not a host round-trip.
531
+ device_mode = bool(getattr(self.dev, "caps", 0) & 0x100)
532
+ fired = []
533
+ for i, (kw, action) in enumerate(self._rules):
534
+ try:
535
+ s = _Selector(self.dev, **kw)
536
+ if device_mode and s._wireable():
537
+ dev_act = "click" \
538
+ if getattr(action, "_pd_click", False) else "none"
539
+ r = self.dev.a.watch(
540
+ s._sel(), dev_act,
541
+ timeout_ms=int(self.interval * 1000),
542
+ poll_ms=50)["payload"]
543
+ if r.get("matched"):
544
+ if dev_act == "none":
545
+ try:
546
+ action()
547
+ except Exception:
548
+ pass
549
+ fired.append(i)
550
+ elif s.exists:
551
+ action()
552
+ fired.append(i)
553
+ except Exception:
554
+ fired.append(i) # a broken rule must not kill the loop
555
+ for i in reversed(fired):
556
+ self._rules.pop(i)
557
+ return not self._rules
558
+
559
+ def run(self):
560
+ while self._running:
561
+ self._tick()
562
+ time.sleep(self.interval)
563
+
564
+ def _run_async(self):
565
+ """CAP_WATCH_ASYNC path (agent 0.7.0+): arm each rule once, then
566
+ block on the media socket for WATCH_HIT frames — detection runs
567
+ inside the agent and the user's thread keeps the control conn
568
+ (u2 server-thread parity). New rules added while running are
569
+ armed on the next loop pass."""
570
+ armed = {} # watch_id -> rule tuple
571
+ ms = None
572
+ try:
573
+ ms = media_connect(self.dev._media_forward())
574
+ ms.settimeout(0.5)
575
+ while self._running:
576
+ for rule in list(self._rules):
577
+ if rule not in armed.values():
578
+ s = _Selector(self.dev, **rule[0])
579
+ if s._wireable():
580
+ dev_act = "click" if getattr(
581
+ rule[1], "_pd_click", False) else "none"
582
+ r = self.dev.a.watch_arm(
583
+ s._sel(), dev_act,
584
+ poll_ms=50)["payload"]
585
+ armed[r["watch_id"]] = rule
586
+ elif s.exists:
587
+ # host-only keys (contains/matches/attrs)
588
+ # can't arm device-side — poll host-side
589
+ try:
590
+ rule[1]()
591
+ except Exception:
592
+ pass
593
+ self._rules.remove(rule)
594
+ break
595
+ try:
596
+ fr = read_frame(ms)
597
+ except socket.timeout:
598
+ continue
599
+ if fr is None:
600
+ break
601
+ _ch, rtype, _flags, _rid, p = fr
602
+ rule = armed.pop(p.get("watch_id"), None) \
603
+ if rtype == 0x0002 else None # WATCH_HIT
604
+ if rule is not None and p.get("matched"):
605
+ if not getattr(rule[1], "_pd_click", False):
606
+ try:
607
+ rule[1]() # .call(fn): agent was armed
608
+ except Exception: # observe-only ("none")
609
+ pass
610
+ for i, r_ in enumerate(list(self._rules)):
611
+ if r_ is rule:
612
+ self._rules.pop(i)
613
+ break
614
+ finally:
615
+ for wid in armed:
616
+ try:
617
+ self.dev.a.watch_disarm(wid)
618
+ except Exception:
619
+ pass
620
+ if ms:
621
+ ms.close()
622
+
623
+ def start(self, interval=None):
624
+ if interval:
625
+ self.interval = interval
626
+ if self._th and self._th.is_alive():
627
+ return
628
+ target = self._run_async \
629
+ if getattr(self.dev, "caps", 0) & 0x200 else self.run
630
+ self._running = True
631
+ self._th = threading.Thread(target=target, daemon=True)
632
+ self._th.start()
633
+
634
+ def stop(self):
635
+ self._running = False
636
+ self._rules.clear()
637
+ if self._th:
638
+ self._th.join(timeout=self.interval + 1)
639
+
640
+ def reset(self):
641
+ self.stop()
642
+
643
+ @property
644
+ def running(self):
645
+ return bool(self._th and self._th.is_alive())
646
+
647
+
648
+ class _WatchContext:
649
+ """Backs `Device.watch_context` — thin ctx-manager over _Watcher."""
650
+
651
+ def __init__(self, dev, builtin):
652
+ self.dev, self.builtin = dev, builtin
653
+
654
+ def __enter__(self):
655
+ self._w = self.dev.watcher
656
+ self._w.start()
657
+ return self
658
+
659
+ def when(self, *args, **kw):
660
+ return self._w.when(*args, **kw)
661
+
662
+ def __exit__(self, *exc):
663
+ self._w.stop()
664
+ return False
665
+
666
+
667
+ class ShellResponse:
668
+ """u2 `d.shell` return shape (output + exit_code attribute access)."""
669
+ __slots__ = ("output", "exit_code")
670
+
671
+ def __init__(self, output, exit_code):
672
+ self.output, self.exit_code = output, exit_code
673
+
674
+ def __str__(self):
675
+ return self.output
676
+
677
+
678
+ _ORIENTATION = {0: "natural", 1: "left", 2: "upsidedown", 3: "right"}
679
+ _ORIENTATION_SET = {"natural": 0, "n": 0, "left": 1, "l": 1, "90": 1,
680
+ "upsidedown": 2, "u": 2, "180": 2, "right": 3, "r": 3,
681
+ "270": 3}
682
+
683
+
684
+ class Device:
685
+ def __init__(self, port=None, serial=None, agent=None):
686
+ port = port or _detect_port(serial)
687
+ self.a = agent or Agent(port).connect()
688
+ self._port = port
689
+ self.serial = serial
690
+ self.caps = self.a.hello()["payload"].get("caps", 0)
691
+
692
+ def __call__(self, **kw):
693
+ return _Selector(self, **kw)
694
+
695
+ def __enter__(self):
696
+ # `with dev.session(pkg) as sess` — shim session IS the device;
697
+ # u2's session-death semantics (running()/SessionBrokenError)
698
+ # are NOT implemented (deferred, RESULTS-M17 §5-G8).
699
+ return self
700
+
701
+ def __exit__(self, *exc):
702
+ return False
703
+
704
+ # u2 surface
705
+ def click(self, x, y):
706
+ return self.a.inject_tap(x, y)["payload"]["ok"]
707
+
708
+ def long_click(self, x, y, duration=0.5):
709
+ ms = int(duration * 1000)
710
+ return self.a.call(0x0010, { # T_INJECT
711
+ "kind": "Tap", "wait_finish": False,
712
+ "points": [{"action": 0, "x": float(x), "y": float(y), "t_ms": 0},
713
+ {"action": 1, "x": float(x), "y": float(y),
714
+ "t_ms": ms}]})["payload"]["ok"]
715
+
716
+ def swipe(self, x1, y1, x2, y2, duration=0.3, steps=10):
717
+ ok = self.a.inject_swipe(x1, y1, x2, y2,
718
+ int(duration * 1000),
719
+ steps)["payload"]["ok"]
720
+ # M17-G4 approx: the agent executes the gesture device-side
721
+ # asynchronously (M10 design decision — not changed); u2's
722
+ # client-side contract BLOCKS for `duration`. Host-side sleep
723
+ # approximates the client-visible contract (wall time >= dur).
724
+ time.sleep(duration)
725
+ return ok
726
+
727
+ def press(self, key):
728
+ code = _KEYCODES.get(str(key).lower(), None)
729
+ if code is None:
730
+ code = int(key)
731
+ return self.a.inject_key(code)["payload"]["ok"]
732
+
733
+ def set_text(self, s):
734
+ p = self.a.text(s)["payload"]
735
+ return p.get("ok", False)
736
+
737
+ def clear_text(self):
738
+ """u2 `d.clear_text()` — clear the currently focused field.
739
+ ACTION_SET_TEXT with empty payload achieves the same end state."""
740
+ return self.a.text("", clear=True)["payload"].get("ok", False)
741
+
742
+ def shell(self, command):
743
+ """u2 `d.shell('cmd')` -> ShellResponse(output, exit_code)."""
744
+ r = subprocess.run(self._sh_cmd([command]),
745
+ capture_output=True, text=True, timeout=60)
746
+ return ShellResponse(r.stdout.rstrip("\n"), r.returncode)
747
+
748
+ def window_size(self):
749
+ """u2 `d.window_size()` -> (w, h)."""
750
+ out = self.shell("wm size").output
751
+ m = re.search(r"(\d+)x(\d+)", out)
752
+ return (int(m.group(1)), int(m.group(2))) if m else None
753
+
754
+ def app_list(self):
755
+ """u2 `d.app_list()` -> [package names]."""
756
+ out = self.shell("pm list packages").output
757
+ return sorted(l.split(":", 1)[1].strip()
758
+ for l in out.splitlines() if ":" in l)
759
+
760
+ def app_info(self, pkg):
761
+ """u2 `d.app_info(pkg)` subset: versionName/versionCode/flags."""
762
+ out = self.shell(f"dumpsys package {pkg}").output
763
+ def grab(key):
764
+ m = re.search(key + r"=([^\s]+)", out)
765
+ return m.group(1) if m else None
766
+ return {"packageName": pkg if "versionCode" in out or
767
+ "versionName" in out else None,
768
+ "versionName": grab("versionName"),
769
+ "versionCode": grab("versionCode")}
770
+
771
+ def _wakefulness(self):
772
+ out = self.shell("dumpsys power").output
773
+ m = re.search(r"mWakefulness=(\w+)", out)
774
+ return m.group(1) if m else None
775
+
776
+ def screen_on(self):
777
+ if self._wakefulness() != "Awake":
778
+ self.press("power")
779
+ time.sleep(0.5)
780
+ return True
781
+
782
+ def screen_off(self):
783
+ if self._wakefulness() == "Awake":
784
+ self.press("power")
785
+ time.sleep(0.5)
786
+ return True
787
+
788
+ def unlock(self):
789
+ """u2 `d.unlock()`: wake + swipe up past the lockscreen."""
790
+ self.screen_on()
791
+ w, h = self.window_size() or (1080, 2400)
792
+ return self.swipe(w / 2, h * 0.8, w / 2, h * 0.2, duration=0.15)
793
+
794
+ @property
795
+ def orientation(self):
796
+ # user_rotation mirrors the display rotation the setter writes;
797
+ # dumpsys input has no stable SurfaceOrientation field across ROMs.
798
+ out = self.shell("settings get system user_rotation").output.strip()
799
+ if out.isdigit():
800
+ return _ORIENTATION.get(int(out))
801
+ out = self.shell("dumpsys input").output
802
+ m = re.search(r"displayId=0.*?orientation=(\d)", out, re.S)
803
+ return _ORIENTATION.get(int(m.group(1))) if m else None
804
+
805
+ @orientation.setter
806
+ def orientation(self, value):
807
+ rot = _ORIENTATION_SET[str(value).lower()]
808
+ self.shell("settings put system accelerometer_rotation 0")
809
+ self.shell(f"settings put system user_rotation {rot}")
810
+
811
+ @property
812
+ def watcher(self):
813
+ if not hasattr(self, "_watcher"):
814
+ self._watcher = _Watcher(self)
815
+ return self._watcher
816
+
817
+ def dump_hierarchy(self):
818
+ return self.a.dump()["payload"]["xml"]
819
+
820
+ def screenshot(self, path=None, scale=1.0, quality=80):
821
+ data = self.a.shot(quality=quality, scale=scale)["payload"]["data"]
822
+ if path:
823
+ with open(path, "wb") as f:
824
+ f.write(data)
825
+ return data
826
+
827
+ def app_start(self, pkg, activity=None, stop=False, wait_timeout=10.0):
828
+ """u2 `d.app_start(pkg, stop=...)`. M17-G1: u2's contract is
829
+ 'launched AND frontmost' — this now blocks on
830
+ `app_wait(front=True)` after the launch and returns False if the
831
+ app did not reach the foreground (e.g. a MIUI
832
+ ReviewPermissionsActivity gate is front instead — see
833
+ RESULTS-M17 §4-E2)."""
834
+ if stop:
835
+ self.app_stop(pkg)
836
+ comp = f"{pkg}/{activity}" if activity else pkg
837
+ cmd = ["adb", "shell", "monkey", "-p", pkg, "-c",
838
+ "android.intent.category.LAUNCHER", "1"] if activity is None \
839
+ else ["adb", "shell", "am", "start", "-n", comp]
840
+ if self._sh(cmd) != 0:
841
+ return False
842
+ return self.app_wait(pkg, timeout=wait_timeout, front=True) \
843
+ is not None
844
+
845
+ def app_stop(self, pkg):
846
+ return self._sh(["adb", "shell", "am", "force-stop", pkg]) == 0
847
+
848
+ def app_wait(self, pkg, timeout=20.0, front=False):
849
+ """u2 `d.app_wait`: poll until pkg runs (front=True → foreground).
850
+ Returns pid or None. Foreground check rides the conn APP_INFO path."""
851
+ deadline = time.time() + timeout
852
+ while time.time() < deadline:
853
+ pid = self.shell(f"pidof {pkg}").output.strip().split()
854
+ if pid and (not front or
855
+ self.app_current().get("package") == pkg):
856
+ return int(pid[0])
857
+ time.sleep(0.5)
858
+ return None
859
+
860
+ def session(self, pkg, attach=False, launch_timeout=None):
861
+ """u2 `d.session` simplified: launch pkg and wait foreground, return
862
+ self. u2's crash-watch relaunch loop is NOT implemented."""
863
+ if not attach:
864
+ self.app_start(pkg)
865
+ if self.app_wait(pkg, timeout=launch_timeout or 10.0,
866
+ front=True) is None:
867
+ raise RuntimeError(f"session: {pkg} did not reach foreground")
868
+ return self
869
+
870
+ def send_keys(self, text, clear=False):
871
+ """u2 `d.send_keys`: type into the focused field — rides the TEXT
872
+ op (ACTION_SET_TEXT on focused node, no IME round-trip)."""
873
+ return bool(self.a.text(text, clear=clear)["payload"].get("ok"))
874
+
875
+ def open_notification(self):
876
+ return self._sh(["adb", "shell", "cmd", "statusbar",
877
+ "expand-notifications"]) == 0
878
+
879
+ def open_quick_settings(self):
880
+ return self._sh(["adb", "shell", "cmd", "statusbar",
881
+ "expand-settings"]) == 0
882
+
883
+ def freeze_rotation(self, freeze=True):
884
+ """u2 `d.freeze_rotation` approximated via the system auto-rotate
885
+ switch (u2's orientation-service lock is not reproduced)."""
886
+ return self._sh(["adb", "shell", "settings", "put", "system",
887
+ "accelerometer_rotation",
888
+ "0" if freeze else "1"]) == 0
889
+
890
+ def set_orientation(self, orientation):
891
+ """u2 `d.set_orientation('l'|'n'|'r'|'u')` — alias of the
892
+ `orientation` setter (freezes auto-rotate, sets user_rotation)."""
893
+ self.orientation = orientation
894
+
895
+ def swipe_ext(self, direction, scale=0.9):
896
+ """u2 `d.swipe_ext('left'|'right'|'up'|'down', scale)` — swipe
897
+ across `scale` fraction of the display, centered."""
898
+ w, h = self.window_size() or (1080, 2400)
899
+ dx, dy = {"left": (-1, 0), "right": (1, 0),
900
+ "up": (0, -1), "down": (0, 1)}[str(direction).lower()]
901
+ x1 = w / 2 - dx * w * scale / 2
902
+ y1 = h / 2 - dy * h * scale / 2
903
+ return self.swipe(x1, y1, x1 + dx * w * scale,
904
+ y1 + dy * h * scale, duration=0.3)
905
+
906
+ def double_click(self, x, y, duration=0.1):
907
+ """u2 `d.double_click(x, y, duration)` — two taps `duration`s
908
+ apart."""
909
+ self.click(x, y)
910
+ time.sleep(max(0.01, duration))
911
+ return self.click(x, y)
912
+
913
+ def drag(self, sx, sy, ex, ey, duration=0.5):
914
+ """u2 `d.drag(sx, sy, ex, ey, duration)` — press-hold then move;
915
+ coords are fractions of the display when <= 1."""
916
+ w, h = self.window_size() or (1080, 2400)
917
+ x1, y1 = sx * w if sx <= 1 else sx, sy * h if sy <= 1 else sy
918
+ x2, y2 = ex * w if ex <= 1 else ex, ey * h if ey <= 1 else ey
919
+ n = 8
920
+ pts = [{"action": 0, "x": float(x1), "y": float(y1), "t_ms": 0},
921
+ {"action": 2, "x": float(x1), "y": float(y1), "t_ms": 300}]
922
+ for i in range(1, n + 1):
923
+ f = i / n
924
+ pts.append({"action": 1 if i == n else 2,
925
+ "x": x1 + (x2 - x1) * f, "y": y1 + (y2 - y1) * f,
926
+ "t_ms": 300 + int(duration * 1000 * f)})
927
+ return self.a.inject_multi(pts)["payload"].get("ok", False)
928
+
929
+ def service(self, name):
930
+ """u2 `d.service(name)` — the on-device automation service.
931
+ 'uiautomator' (u2's canonical service name) maps to the pilotdroid
932
+ agent process — same role, different binary."""
933
+ if name not in ("uiautomator", "pilotdroid", "pilotdroid_agent"):
934
+ raise ValueError(
935
+ f"service('{name}') unsupported — pilotdroid runs a single "
936
+ "device service (the agent); u2's 'uiautomator' maps to it")
937
+ return _Service(self)
938
+
939
+ def app_current(self):
940
+ """u2 app_current() -> {package, activity}. Prefers the conn-side
941
+ APP_INFO op (CAP_APP_INFO — UiAutomation window read, ~ms) over a
942
+ dumpsys adb spawn (~300-600ms per call)."""
943
+ if self.caps & 0x400:
944
+ p = self.a.app_info()["payload"]
945
+ if p.get("pkg"):
946
+ info = {"package": p["pkg"],
947
+ "activity": p.get("activity")}
948
+ pid = self.shell(f"pidof {info['package']}").output.strip()
949
+ if pid:
950
+ info["pid"] = int(pid.split()[0])
951
+ return info
952
+ out = subprocess.run(
953
+ self._sh_cmd(["dumpsys", "window"]),
954
+ capture_output=True, text=True).stdout
955
+ import re
956
+ m = re.search(r"mCurrentFocus=\S+\s+\S+\s+([\w.]+)/([\w.$]+)", out)
957
+ if not m: # some ROMs only expose mFocusedApp
958
+ m = re.search(r"([\w.]+)/([\w.$]+)\s", out)
959
+ if not m:
960
+ return {}
961
+ info = {"package": m.group(1), "activity": m.group(2)}
962
+ # u2 shape includes `pid` — u2suite test_app_mixin reads it
963
+ pid = self.shell(f"pidof {info['package']}").output.strip()
964
+ if pid:
965
+ info["pid"] = int(pid.split()[0])
966
+ return info
967
+
968
+ def _media_forward(self):
969
+ """adb forward for the ch=1 media socket (watch hits). Local port
970
+ = control port + 1, matching verify-agent.sh convention."""
971
+ port = self.a.port + 1
972
+ cmd = (["adb"] + (["-s", self.serial] if self.serial else [])
973
+ + ["forward", f"tcp:{port}",
974
+ "localabstract:pilotdroid_agent_media"])
975
+ subprocess.run(cmd, capture_output=True, check=True)
976
+ return port
977
+
978
+ def _sh_cmd(self, args):
979
+ return (["adb"] + (["-s", self.serial] if self.serial else [])
980
+ + ["shell"] + args)
981
+
982
+ def _sh(self, cmd):
983
+ if self.serial:
984
+ cmd[1:1] = ["-s", self.serial]
985
+ return subprocess.run(cmd, capture_output=True).returncode
986
+
987
+ @property
988
+ def info(self):
989
+ h = self.a.hello()["payload"]
990
+ return {"displayWidth": h["display"][0],
991
+ "displayHeight": h["display"][1],
992
+ "sdkInt": h.get("sdk"), "agent": h.get("ver")}
993
+
994
+ @property
995
+ def settings(self):
996
+ """u2 `d.settings` — transparent dict: keys read/write freely.
997
+ u2's TYPE validation (`xpath_debug` must be bool) and COUPLING
998
+ (`wait_timeout`/`implicit_wait`/`operation_delay` actually
999
+ driving behavior) are NOT implemented — RESULTS-M17 §5-G10."""
1000
+ store = getattr(self, "_settings_store", None)
1001
+ if store is None:
1002
+ store = self._settings_store = {}
1003
+ return store
1004
+
1005
+ def push(self, src, dst="/sdcard/"):
1006
+ """u2 `d.push(local, remote)` — adb spawn; `src` may be a path,
1007
+ bytes, or a file-like object (u2 surface; staged via temp)."""
1008
+ if isinstance(src, (bytes, bytearray)) or hasattr(src, "read"):
1009
+ data = bytes(src) if isinstance(src, (bytes, bytearray)) \
1010
+ else src.read()
1011
+ import tempfile
1012
+ with tempfile.NamedTemporaryFile(delete=False) as f:
1013
+ f.write(data)
1014
+ tmp = f.name
1015
+ try:
1016
+ return self.push(tmp, dst)
1017
+ finally:
1018
+ os.unlink(tmp)
1019
+ cmd = (["adb"] + (["-s", self.serial] if self.serial else [])
1020
+ + ["push", src, dst])
1021
+ return subprocess.run(cmd, capture_output=True).returncode == 0
1022
+
1023
+ def pull(self, src, dst="."):
1024
+ """u2 `d.pull(remote, local)` — adb spawn."""
1025
+ cmd = (["adb"] + (["-s", self.serial] if self.serial else [])
1026
+ + ["pull", src, dst])
1027
+ return subprocess.run(cmd, capture_output=True).returncode == 0
1028
+
1029
+ @property
1030
+ def wlan_ip(self):
1031
+ """u2 `d.wlan_ip` — device IPv4 on wlan0, None if absent."""
1032
+ out = self.shell("ip addr show wlan0").output
1033
+ m = re.search(r"inet (\d+\.\d+\.\d+\.\d+)", out)
1034
+ return m.group(1) if m else None
1035
+
1036
+ def app_list_running(self):
1037
+ """u2 `d.app_list_running()` — installed packages that have a
1038
+ live process (`ps -A` names ∩ `pm list packages`; process names
1039
+ may carry a `:sub` suffix — stripped)."""
1040
+ pkgs = set(self.app_list())
1041
+ running = set()
1042
+ for line in self.shell("ps -A -o NAME").output.splitlines():
1043
+ name = line.strip().split(":")[0]
1044
+ if name in pkgs:
1045
+ running.add(name)
1046
+ return sorted(running)
1047
+
1048
+ def app_auto_grant_permissions(self, pkg):
1049
+ """u2 `d.app_auto_grant_permissions(pkg)` — `pm grant` every
1050
+ permission the manifest requests; non-runtime perms fail
1051
+ harmlessly (pm exits nonzero, ignored)."""
1052
+ out = self.shell(f"dumpsys package {pkg}").output
1053
+ m = re.search(r"requested permissions:(.*?)"
1054
+ r"(?:install permissions|runtime permissions|"
1055
+ r"pkg=|Packages:)", out, re.S)
1056
+ if not m:
1057
+ return False
1058
+ for p in re.findall(r"android\.permission\.[\w.]+", m.group(1)):
1059
+ self.shell(f"pm grant {pkg} {p}")
1060
+ return True
1061
+
1062
+ def watch_context(self, builtin=False):
1063
+ """u2 `d.watch_context(builtin)` — context manager over
1064
+ `d.watcher`: `.when(sel).click()` registers rules; __exit__
1065
+ stops the watcher. u2's `builtin` stock-dialog rules are not
1066
+ reproduced (accepted, ignored — ROM dialogs differ anyway)."""
1067
+ return _WatchContext(self, builtin)
1068
+
1069
+ def close(self):
1070
+ self.a.close()
1071
+
1072
+
1073
+ # u2's `u2.Session` is the object `d.session()` returns; the shim's
1074
+ # session() returns the Device itself (crash-watch semantics deferred
1075
+ # — G8), so the honest type alias is Device.
1076
+ Session = Device
1077
+
1078
+
1079
+ def _detect_port(serial=None):
1080
+ """Auto-detect the local TCP port forwarding to pilotdroid_agent.
1081
+
1082
+ Parses `adb forward --list` for a `localabstract:pilotdroid_agent` rule;
1083
+ when `serial` is given the rule must belong to that device. Falls back to
1084
+ the conventional 17932 with an actionable error if nothing is listening.
1085
+ """
1086
+ try:
1087
+ out = subprocess.run(["adb", "forward", "--list"],
1088
+ capture_output=True, text=True, timeout=10).stdout
1089
+ except Exception:
1090
+ out = ""
1091
+ cands = []
1092
+ for line in out.splitlines():
1093
+ parts = line.split()
1094
+ if len(parts) == 3 and parts[2] == "localabstract:pilotdroid_agent":
1095
+ if serial is None or parts[0] == serial:
1096
+ if parts[1].startswith("tcp:"):
1097
+ cands.append(int(parts[1][4:]))
1098
+ if cands:
1099
+ return cands[0]
1100
+ for port in (17932,):
1101
+ try:
1102
+ Agent(port).connect().close()
1103
+ return port
1104
+ except Exception:
1105
+ pass
1106
+ raise RuntimeError(
1107
+ "no adb forward to localabstract:pilotdroid_agent found and "
1108
+ "tcp:17932 is not alive — run `pilotdroid-cli setup` (installed "
1109
+ "with `pip install pilotdroid`; without it, download the binary "
1110
+ "from github.com/mofanx/pilotdroid/releases), or "
1111
+ "`adb forward tcp:17932 localabstract:pilotdroid_agent`")
1112
+
1113
+
1114
+ class _Service:
1115
+ """`d.service('uiautomator')` over the agent app_process — u2's
1116
+ atx-agent service lifecycle applied to our daemon. Shell-based
1117
+ checks work even after the control conn dies on stop()."""
1118
+
1119
+ _PAT = "pilotdroid.Agent"
1120
+ _DIR = "/data/local/tmp/pilotdroid"
1121
+
1122
+ def __init__(self, dev):
1123
+ self.dev = dev
1124
+
1125
+ def running(self):
1126
+ return bool(self.dev.shell(
1127
+ f"pgrep -f '{self._PAT}'").output.strip())
1128
+
1129
+ def stop(self):
1130
+ self.dev.shell(f"pkill -f '{self._PAT}'")
1131
+ return not self.running()
1132
+
1133
+ def start(self):
1134
+ self.dev.shell(
1135
+ f"nohup setsid env CLASSPATH={self._DIR}/agent.jar "
1136
+ f"app_process {self._DIR} pilotdroid.Agent "
1137
+ f"</dev/null >{self._DIR}/agent.log 2>&1 &")
1138
+ for _ in range(40):
1139
+ if self.running():
1140
+ break
1141
+ time.sleep(0.25)
1142
+ try:
1143
+ self.dev.a = Agent(self.dev._port).connect()
1144
+ except Exception:
1145
+ pass
1146
+ return self.running()
1147
+
1148
+
1149
+ def connect(port=None, serial=None):
1150
+ """u2 `u2.connect(addr)` — the positional may be an adb serial string
1151
+ (canonical u2 style: `u2.connect('emulator-5554')`) or a local TCP
1152
+ port (pilotdroid-native: int or digit string). `serial=` kwarg and
1153
+ no-arg auto-detect unchanged."""
1154
+ if isinstance(port, str) and not port.isdigit():
1155
+ serial = serial or port
1156
+ port = None
1157
+ return Device(port=port, serial=serial)