Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: philips-api.py says nothing was learned when neither port answers, instead of naming a package

xbsheng2219367a4051
diff --git a/tests/test_philips_api.py b/tests/test_philips_api.py
index 9296797e2..90911a3d4 100644
--- a/tests/test_philips_api.py
+++ b/tests/test_philips_api.py
@@ -2,16 +2,29 @@
On a 77OLED806/12 (Android TV 11) port 1925 is open and answers nothing, while
https://<tv>:1926/6/system answers without pairing. The tool must report the API from 1926, count a 401
-on the other endpoints as present (they wait for pairing), and exit 1 naming org.droidtv.xtv when
-neither port answers. No TV and no network: the HTTP calls are replaced with a fake.
+on the other endpoints as present (they wait for pairing), and name org.droidtv.xtv when a port answered
+and it is not the API. No TV and no network: the HTTP calls are replaced with a fake.
+
+The other half is telling a TV this run reached from one it never did. A port that refuses the
+connection is the set answering - nothing listens there, which is what a disabled org.droidtv.xtv looks
+like - while a timeout, a "No route to host" or a name that does not resolve is the network between here
+and the TV. A set that is asleep, at another address or behind a VPN's firewall leaves both ports silent,
+and the run answered that with the advice and exit 1 it uses for a TV it did reach, so an owner whose set
+was simply asleep went looking for a package nothing had touched. That shape exits 2 now and says
+nothing was learned; it is the rule tools/adb-closed.py and docs/TROUBLESHOOTING.md keep for port 5555 -
+only a refused connection is the TV speaking.
Run from the repository root: python3 -m unittest discover -s tests -v
"""
import contextlib
+import errno
import importlib.util
import io
import json
+import socket
+import ssl
import unittest
+import urllib.error
from pathlib import Path
from unittest import mock
@@ -27,28 +40,36 @@ SYSTEM = json.dumps({
"jsonfeatures": {"ambilight": ["LoungeLight", "Hue", "Ambilight", "HueStreaming"]}},
})
+# What a port raises, in the shapes this file needs: the set's own refusal, a network that never
+# reached it, and a name that does not resolve.
+REFUSED = ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused")
+TIMEOUT = TimeoutError("timed out")
+NO_ROUTE = OSError(errno.EHOSTUNREACH, "No route to host")
+NO_NAME = socket.gaierror(getattr(socket, "EAI_NONAME", -2), "Name or service not known")
+
def run(answers, argv=("philips-api.py", "192.168.1.50")):
- """Exit code and output, with get() answering from {url: (status, body)}; anything else is unreachable."""
+ """(exit code, stdout, urls asked, stderr), with get() answering from {url: (status, body, failure)};
+ a URL the test does not answer times out, so a silent TV is the default."""
asked = []
def fake_get(url, timeout=8):
asked.append(url)
- return answers.get(url, (None, "timed out"))
+ return answers.get(url, (None, "timed out", TIMEOUT))
- out = io.StringIO()
+ out, err = io.StringIO(), io.StringIO()
with mock.patch.object(philips_api, "get", fake_get), contextlib.redirect_stdout(out), \
- contextlib.redirect_stderr(io.StringIO()):
+ contextlib.redirect_stderr(err):
code = philips_api.main(list(argv))
- return code, out.getvalue(), asked
+ return code, out.getvalue(), asked, err.getvalue()
class PhilipsApi(unittest.TestCase):
def test_the_api_on_1926_is_found_and_401_counts_as_there(self):
base = "https://192.168.1.50:1926/6/"
- answers = {base + "system": (200, SYSTEM)}
- answers.update({base + p: (401, "") for p in philips_api.PROBE})
- code, out, asked = run(answers)
+ answers = {base + "system": (200, SYSTEM, None)}
+ answers.update({base + p: (401, "", None) for p in philips_api.PROBE})
+ code, out, asked, _ = run(answers)
self.assertEqual(code, 0)
self.assertIn("API on https://192.168.1.50:1926", out)
self.assertIn("6.1.0", out)
@@ -57,17 +78,18 @@ class PhilipsApi(unittest.TestCase):
self.assertFalse([u for u in asked if ":1925/" in u], "1925 was tried although 1926 answered")
def test_an_empty_1925_is_not_taken_for_the_api(self):
- answers = {"http://192.168.1.50:1925/6/system": (200, "")}
- code, out, _ = run(answers)
+ # A 200 with no /6/system object is still the set answering, so the package to check is named.
+ answers = {"http://192.168.1.50:1925/6/system": (200, "", None)}
+ code, out, _, _ = run(answers)
self.assertEqual(code, 1)
self.assertIn("org.droidtv.xtv", out)
def test_a_page_that_is_not_the_api_falls_back_to_1925(self):
base = "http://192.168.1.50:1925/6/"
- answers = {"https://192.168.1.50:1926/6/system": (200, "<html>login</html>"),
- base + "system": (200, SYSTEM)}
- answers.update({base + p: (401, "") for p in philips_api.PROBE})
- code, out, _ = run(answers)
+ answers = {"https://192.168.1.50:1926/6/system": (200, "<html>login</html>", None),
+ base + "system": (200, SYSTEM, None)}
+ answers.update({base + p: (401, "", None) for p in philips_api.PROBE})
+ code, out, _, _ = run(answers)
self.assertEqual(code, 0)
self.assertIn("API on http://192.168.1.50:1925", out)
self.assertIn("(not the API)", out)
@@ -75,24 +97,91 @@ class PhilipsApi(unittest.TestCase):
def test_json_that_is_not_a_system_object_is_no_api(self):
for body in ("{}", "null", "[]", '{"api_version": "6"}', "{broken"):
with self.subTest(body=body):
- code, out, _ = run({"https://192.168.1.50:1926/6/system": (200, body)})
+ code, out, _, _ = run({"https://192.168.1.50:1926/6/system": (200, body, None)})
self.assertEqual(code, 1)
self.assertIn("org.droidtv.xtv", out)
def test_wrong_typed_feature_metadata_counts_as_unknown(self):
system = json.dumps({"api_version": {"Major": 6, "Minor": 1, "Patch": 0},
"featuring": {"systemfeatures": [], "jsonfeatures": {"ambilight": 5}}})
- code, out, _ = run({"https://192.168.1.50:1926/6/system": (200, system)})
+ code, out, _, _ = run({"https://192.168.1.50:1926/6/system": (200, system, None)})
self.assertEqual(code, 0)
self.assertIn("6.1.0", out)
self.assertNotIn("LoungeLight", out)
def test_no_address_is_a_usage_error(self):
with mock.patch.dict("os.environ", {"TV_HOST": ""}):
- code, _, asked = run({}, argv=("philips-api.py",))
+ code, _, asked, _ = run({}, argv=("philips-api.py",))
self.assertEqual(code, 2)
self.assertEqual(asked, [])
+class ASilentTVIsNotADisabledPackage(unittest.TestCase):
+ """Nothing answered on either port: the run learned nothing, so it must not send the owner to the
+ package list - the shape a set that is asleep, at another address or behind a VPN produces."""
+
+ def test_a_timeout_on_both_ports_is_exit_2(self):
+ code, out, asked, err = run({})
+ self.assertEqual(code, 2)
+ self.assertEqual(len(asked), 2, "both ports have to be tried before giving up")
+ # The two lines naming the ports are all that was learned; no advice and no verdict.
+ self.assertTrue(all(line.startswith(" ") for line in out.splitlines()), out)
+ self.assertIn("could not check 192.168.1.50", err)
+ self.assertIn("nothing answered on 1926 and 1925", err)
+ self.assertIn("off, asleep", err)
+ self.assertNotIn("No JointSpace API", err + out)
+ self.assertNotIn("still enabled", err + out)
+
+ def test_a_name_that_does_not_resolve_is_exit_2(self):
+ answers = {f"{scheme}://no-such-set.invalid:{port}/6/system":
+ (None, "Name or service not known", NO_NAME)
+ for port, scheme in philips_api.PORTS}
+ code, out, _, err = run(answers, argv=("philips-api.py", "no-such-set.invalid"))
+ self.assertEqual(code, 2)
+ self.assertNotIn("No JointSpace API", out)
+ self.assertIn("could not check no-such-set.invalid", err)
+
+ def test_no_route_to_the_tv_is_exit_2(self):
+ answers = {f"{scheme}://192.168.1.51:{port}/6/system": (None, "No route to host", NO_ROUTE)
+ for port, scheme in philips_api.PORTS}
+ code, _, _, err = run(answers, argv=("philips-api.py", "192.168.1.51"))
+ self.assertEqual(code, 2)
+ self.assertIn("could not check 192.168.1.51", err)
+
+ def test_a_refused_port_is_the_tv_answering(self):
+ # Nothing listens on 1925, which is what a disabled org.droidtv.xtv looks like: the set itself
+ # sent the reset, so the package is worth naming even though 1926 stayed silent.
+ answers = {"http://192.168.1.50:1925/6/system": (None, "Connection refused", REFUSED)}
+ code, out, _, err = run(answers)
+ self.assertEqual(code, 1)
+ self.assertIn("org.droidtv.xtv", out)
+ self.assertEqual(err, "")
+
+ def test_the_refusal_on_the_https_port_counts_too(self):
+ answers = {"https://192.168.1.50:1926/6/system": (None, "Connection refused", REFUSED)}
+ code, out, _, _ = run(answers)
+ self.assertEqual(code, 1)
+ self.assertIn("org.droidtv.xtv", out)
+
+
+class Answered(unittest.TestCase):
+ """The one judgement the exit code rests on, over the exceptions the socket layer hands over."""
+
+ def test_a_refusal_is_an_answer(self):
+ for failure in (REFUSED, urllib.error.URLError(REFUSED), ssl.SSLError("WRONG_VERSION_NUMBER"),
+ ConnectionResetError(errno.ECONNRESET, "Connection reset")):
+ with self.subTest(failure=type(failure).__name__ + str(getattr(failure, "reason", ""))):
+ self.assertTrue(philips_api.answered(failure))
+
+ def test_never_reaching_the_tv_is_not(self):
+ for failure in (TIMEOUT, urllib.error.URLError(TIMEOUT), NO_ROUTE, urllib.error.URLError(NO_ROUTE),
+ NO_NAME, urllib.error.URLError(NO_NAME)):
+ with self.subTest(failure=type(failure).__name__ + str(getattr(failure, "reason", ""))):
+ self.assertFalse(philips_api.answered(failure))
+
+ def test_an_answer_is_not_a_failure(self):
+ self.assertFalse(philips_api.answered(None))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/philips-api.py b/tools/philips-api.py
index cacb66256..b76ec9b0d 100644
--- a/tools/philips-api.py
+++ b/tools/philips-api.py
@@ -3,7 +3,13 @@
philips-api.py [tv ip] the IP defaults to TV_HOST
-Exits 0 when the API answers, 1 when neither port does, and 2 on a usage error.
+Exits 0 when the API answers; 1 when a port answered and it is not the JointSpace API (the package to
+check is named); and 2 when this run could not tell - nothing answered on either port, so the TV may be
+off, asleep, at another address or out of reach from here - or the command line was not one address.
+
+A port that refuses the connection is the TV answering: nothing listens there, which is what a disabled
+org.droidtv.xtv looks like. A port that times out, answers "No route to host", or a name that does not
+resolve is the network between here and the TV, and says nothing about the package.
Philips Android TVs are driven from Home Assistant (the built-in philips_js integration), openHAB and
the like over the JointSpace API. It is served by org.droidtv.xtv, which is in the DO NOT DISABLE block
@@ -21,8 +27,10 @@ Two things trip people up, and this handles both:
endpoints answer 401 until a client has done the digest-auth pairing, and for this check a 401 is the good
answer: the endpoint is there.
"""
+import errno
import json
import os
+import socket
import ssl
import sys
import urllib.error
@@ -31,20 +39,41 @@ import urllib.request
PORTS = ((1926, "https"), (1925, "http"))
PROBE = ("ambilight/topology", "ambilight/power", "ambilight/mode", "ambilight/currentconfiguration",
"powerstate")
+# errno values that mean this computer never reached the TV: a timeout, a network that is not the
+# set's, a host that is gone. What the port said in those cases is about the route, not the TV.
+UNREACHED = (errno.EHOSTUNREACH, errno.ENETUNREACH, errno.EHOSTDOWN, errno.ENETDOWN, errno.ETIMEDOUT,
+ errno.ECONNABORTED)
+
+
+def answered(failure):
+ """True when the TV answered at the TCP level, so what the port said is about the TV.
+
+ A connection the set refuses is its own reset: nothing is listening on that port, which is what a
+ disabled org.droidtv.xtv looks like. A timeout, a "No route to host" or a name that does not
+ resolve is this computer's network, or a set that is off, asleep or at another address, and it
+ says nothing either way about the package: on a TV that is asleep every port looks like this.
+ """
+ if isinstance(failure, urllib.error.URLError): # urlopen wraps what the socket raised
+ failure = failure.reason
+ if isinstance(failure, (socket.gaierror, TimeoutError)):
+ return False
+ if isinstance(failure, OSError):
+ return failure.errno not in UNREACHED
+ return False
def get(url, timeout=8):
- """(status, body); status is None when nothing answered, and body then says why."""
+ """(status, body, failure); status is None when nothing answered and body then says why."""
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
with urllib.request.urlopen(url, timeout=timeout, context=ctx) as r:
- return r.status, r.read().decode("utf-8", "replace")
+ return r.status, r.read().decode("utf-8", "replace"), None
except urllib.error.HTTPError as e:
- return e.code, ""
+ return e.code, "", None
except Exception as failure:
- return None, str(failure)
+ return None, str(failure), failure
def system_info(body):
@@ -65,17 +94,23 @@ def section(parent, key):
def find_api(host):
- """The base URL and decoded /6/system of the first port that answers as the API, or (None, None).
- Prints each port it tried."""
+ """(base URL, decoded /6/system, whether any port answered at all), or (None, None, reached).
+
+ Prints each port it tried. `reached` is what tells "the TV is there and the API is not" (the
+ package to check) from "this computer never reached the TV" (nothing was learned).
+ """
+ reached = False
for port, scheme in PORTS:
base = f"{scheme}://{host}:{port}"
- status, body = get(f"{base}/6/system")
+ status, body, failure = get(f"{base}/6/system")
+ if status is not None or answered(failure):
+ reached = True
info = system_info(body) if status == 200 else None
if info is not None:
- return base, info
+ return base, info, True
why = status if status is not None else body
print(f" {base}/6/system -> {why}{' (not the API)' if status == 200 else ''}")
- return None, None
+ return None, None, reached
def main(argv):
@@ -85,10 +120,21 @@ def main(argv):
print(__doc__.split("\n\n")[1], file=sys.stderr)
return 2
- base, info = find_api(host)
+ base, info, reached = find_api(host)
if not base:
- print("\nNo JointSpace API. If this TV used to work with Home Assistant, check that\n"
- "org.droidtv.xtv is still enabled:\n"
+ if not reached:
+ # The run used to end here with the advice below and exit 1, which is what "the TV is
+ # there and org.droidtv.xtv is off" looks like: a set that is asleep, on another VLAN or
+ # behind a VPN's firewall sent the owner hunting for a package nothing had touched.
+ ports = " and ".join(str(port) for port, _ in PORTS)
+ print(f"could not check {host}: nothing answered on {ports}, and that says nothing about "
+ "the TV.\nNothing is known about org.droidtv.xtv: the set may be off, asleep or still "
+ "starting, at\nanother address, or out of reach from here (a VPN, another VLAN, an "
+ "assistant's sandbox).\nRun this from an ordinary terminal on the same network, check "
+ "the address, and run it again.", file=sys.stderr)
+ return 2
+ print(f"\nNo JointSpace API. If this TV used to work with Home Assistant, check that\n"
+ f"org.droidtv.xtv is still enabled:\n"
f" TV_HOST={host} tools/tv.py 'pm list packages -d' | grep droidtv")
return 1
@@ -106,7 +152,7 @@ def main(argv):
print("\nendpoints (401 = there, waiting for pairing):")
for path in PROBE:
- status, _ = get(f"{base}/6/{path}")
+ status, _, _ = get(f"{base}/6/{path}")
verdict = {200: "open", 401: "there", 404: "MISSING"}.get(status, str(status))
print(f" {path:32s} {verdict}")
return 0