CLI for SidePulse
Python
Link iPhones through the SidePulse bridge
Peter Kuharfc2474c16ec2
diff --git a/README.md b/README.mdindex 0f4122f..4026036 100644--- a/README.md+++ b/README.md@@ -72,6 +72,20 @@ sidepulse write "off" --device /Volumes/SidePulsePro/LEDS.LEDThe writer decodes simple escapes such as `\n`, then enforces the controller's512-byte and 20-line limits before writing the LED control file.+### Link an iPhone++Run one command and either scan the terminal QR code with the SidePulse iOS app+or paste the 64-character push token shown by the app:++```sh+sidepulse link+```++Linked phones are stored locally. `sidepulse write` still prefers mounted+SidePulse hardware; when no local device is mounted, it sends the validated LED+program silently to every linked iPhone through `https://bridge.sidepulse.io`.+Set `SIDEPULSE_SERVER` to use another bridge origin.+## Battery LEDsShow the current Mac battery state:diff --git a/pyproject.toml b/pyproject.tomlindex 0afe0ea..46aa7cf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -28,6 +28,7 @@ classifiers = ["Topic :: Utilities",]dependencies = [+ "qrcode>=8,<9","pyobjc-framework-Cocoa>=10; sys_platform == 'darwin'","pyobjc-framework-Quartz>=10; sys_platform == 'darwin'","pyobjc-framework-WebKit>=10; sys_platform == 'darwin'",diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex ca8f460..4f963ef 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -3,10 +3,14 @@ from __future__ import annotationsimport argparseimport jsonimport os+import queue+import selectimport shutilimport subprocessimport sys+import threadingimport time+import uuidfrom pathlib import Pathfrom .battery import (@@ -17,7 +21,14 @@ from .battery import (render_battery_snapshot,)from .collector import AgentMonitor, SourceSpec, default_sources-from .device_writer import DEFAULT_FILE_NAME, DeviceWriteError, write_led_program+from .device_writer import (+ DEFAULT_FILE_NAME,+ DeviceWriteError,+ discover_devices,+ normalize_led_text,+ validate_led_text,+ write_led_program,+)from .hook import hook_log_mainfrom .install import (install_claude_hooks,@@ -30,6 +41,19 @@ from .install import (uninstall_grok_hooks,)from .led_status import AgentLedController, LedStatusWrite+from .links import (+ IOSLink,+ LinkError,+ PAIRING_TIMEOUT_SECONDS,+ bridge_server,+ listen_for_ios_registration,+ load_ios_links,+ normalize_apns_token,+ pairing_url,+ render_terminal_qr,+ send_ios_program,+ store_ios_link,+)from .lid_sleep import (install_sleep_helper,sleep_helper_install_command,@@ -131,6 +155,12 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:write.add_argument("--dry-run", action="store_true", help="Show the target without writing.")write.set_defaults(func=cmd_sidepulse_write)+ link = subparsers.add_parser(+ "link",+ help="Link an iPhone by scanning a QR code or pasting its push token.",+ )+ link.set_defaults(func=cmd_sidepulse_link)+add_sidepulse_status_bar_parser(subparsers)add_sidepulse_sdejectguard_parser(subparsers)add_sidepulse_battery_parser(subparsers)@@ -279,6 +309,9 @@ def add_sidepulse_battery_parser(subparsers: argparse._SubParsersAction) -> Nonedef cmd_sidepulse_write(args: argparse.Namespace) -> int:+ if args.device is None and not discover_devices(file_name=args.file_name):+ return cmd_sidepulse_write_ios(args)+try:target = write_led_program(args.text,@@ -298,6 +331,131 @@ def cmd_sidepulse_write(args: argparse.Namespace) -> int:return 0+def cmd_sidepulse_write_ios(args: argparse.Namespace) -> int:+ try:+ program = normalize_led_text(args.text)+ validate_led_text(program)+ except DeviceWriteError as exc:+ print(f"sidepulse write: {exc}", file=sys.stderr)+ return 2++ links = load_ios_links()+ if not links:+ print(+ "sidepulse write: No SidePulse device found. "+ "Run `sidepulse link` to connect your phone.",+ file=sys.stderr,+ )+ return 2++ if args.dry_run:+ for link in links:+ print(f"would send: {link.name}")+ return 0++ event_id = str(uuid.uuid4())+ failed = False+ for link in links:+ try:+ send_ios_program(link, program, event_id=event_id)+ print(f"sent: {link.name}")+ except LinkError as exc:+ failed = True+ print(f"sidepulse write: {link.name}: {exc}", file=sys.stderr)+ return 1 if failed else 0+++def cmd_sidepulse_link(_args: argparse.Namespace) -> int:+ try:+ server = bridge_server()+ channel = str(uuid.uuid4())+ url = pairing_url(server, channel)+ qr = render_terminal_qr(url)+ except LinkError as exc:+ print(f"sidepulse link: {exc}", file=sys.stderr)+ return 1++ results: queue.Queue[IOSLink] = queue.Queue()+ stop = threading.Event()+ deadline = time.monotonic() + PAIRING_TIMEOUT_SECONDS+ listener = threading.Thread(+ target=listen_for_ios_registration,+ args=(server, channel, results, stop),+ kwargs={"deadline": deadline},+ daemon=True,+ )+ listener.start()++ existing = load_ios_links()+ if existing:+ print("Linked phones: " + ", ".join(link.name for link in existing))+ print()+ print("Link your iPhone")+ print()+ print("Scan this QR code with your phone:")+ print()+ print(qr)+ print()+ print("Or paste the push token shown in the SidePulse app.")++ input_enabled = True+ prompt_visible = False+ try:+ while time.monotonic() < deadline:+ try:+ link = results.get_nowait()+ break+ except queue.Empty:+ pass++ if input_enabled and not prompt_visible:+ print("Push token: ", end="", flush=True)+ prompt_visible = True++ readable = []+ if input_enabled:+ try:+ readable, _, _ = select.select([sys.stdin], [], [], 0.2)+ except (OSError, ValueError):+ input_enabled = False+ else:+ time.sleep(0.2)++ if readable:+ value = sys.stdin.readline()+ if not value:+ input_enabled = False+ continue+ try:+ token = normalize_apns_token(value)+ except LinkError as exc:+ print(f"Invalid token: {exc}")+ prompt_visible = False+ continue+ link = IOSLink(+ name="iPhone",+ token=token,+ server=server,+ linked_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ )+ break+ else:+ print("\nPairing timed out. Run `sidepulse link` to try again.", file=sys.stderr)+ return 1+ finally:+ stop.set()++ if prompt_visible:+ print()+ try:+ store_ios_link(link)+ except OSError as exc:+ print(f"sidepulse link: Could not save the phone: {exc}", file=sys.stderr)+ return 1+ print(f"Linked {link.name}. `sidepulse write` will use it when no local device is mounted.")+ return 0++def cmd_sidepulse_battery_status(args: argparse.Namespace) -> int:try:snapshot = read_battery_snapshot(full_charge_watts=full_watts_from_args(args))diff --git a/src/sidepulse/links.py b/src/sidepulse/links.pynew file mode 100644index 0000000..8478ac3--- /dev/null+++ b/src/sidepulse/links.py@@ -0,0 +1,268 @@+from __future__ import annotations++import json+import os+import queue+import re+import socket+import threading+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Iterable++from .settings import default_config_dir+++DEFAULT_BRIDGE_SERVER = "https://bridge.sidepulse.io"+PAIRING_TIMEOUT_SECONDS = 5 * 60+IOS_BUNDLE_ID = "io.sidepulse.ios"+APNS_TOKEN_PATTERN = re.compile(r"^[0-9a-fA-F]{64}$")+++class LinkError(RuntimeError):+ pass+++@dataclass(frozen=True)+class IOSLink:+ name: str+ token: str+ server: str = DEFAULT_BRIDGE_SERVER+ linked_at: str = ""++ @property+ def link_id(self) -> str:+ return self.token[:12]++ def to_dict(self) -> dict[str, str]:+ return {+ "id": self.link_id,+ "name": self.name,+ "token": self.token,+ "server": self.server,+ "linked_at": self.linked_at,+ }+++def default_links_path() -> Path:+ return default_config_dir() / "links.json"+++def bridge_server() -> str:+ return normalize_server(os.environ.get("SIDEPULSE_SERVER", DEFAULT_BRIDGE_SERVER))+++def normalize_server(value: str) -> str:+ text = value.strip().rstrip("/")+ parsed = urllib.parse.urlsplit(text)+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:+ raise LinkError("Bridge server must be an HTTP or HTTPS origin.")+ if parsed.username or parsed.password or parsed.query or parsed.fragment:+ raise LinkError("Bridge server must not contain credentials, a query, or a fragment.")+ if parsed.path not in {"", "/"}:+ raise LinkError("Bridge server must be an origin without a path.")+ return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))+++def normalize_apns_token(value: str) -> str:+ token = "".join(value.split()).lower()+ if not APNS_TOKEN_PATTERN.fullmatch(token):+ raise LinkError("Push token must be exactly 64 hexadecimal characters.")+ return token+++def load_ios_links(path: Path | None = None) -> tuple[IOSLink, ...]:+ target = (path or default_links_path()).expanduser()+ try:+ data = json.loads(target.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return ()+ except Exception:+ return ()+ if not isinstance(data, dict) or data.get("version") != 1:+ return ()+ items = data.get("ios")+ if not isinstance(items, list):+ return ()+ links: list[IOSLink] = []+ for item in items:+ if not isinstance(item, dict):+ continue+ try:+ links.append(+ IOSLink(+ name=str(item.get("name") or "iPhone"),+ token=normalize_apns_token(str(item["token"])),+ server=normalize_server(str(item.get("server") or DEFAULT_BRIDGE_SERVER)),+ linked_at=str(item.get("linked_at") or ""),+ )+ )+ except (KeyError, LinkError):+ continue+ return tuple(links)+++def save_ios_links(links: Iterable[IOSLink], path: Path | None = None) -> Path:+ target = (path or default_links_path()).expanduser()+ target.parent.mkdir(parents=True, exist_ok=True)+ try:+ target.parent.chmod(0o700)+ except OSError:+ pass+ payload = {+ "version": 1,+ "ios": [link.to_dict() for link in links],+ }+ temporary = target.with_suffix(target.suffix + ".tmp")+ temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ temporary.chmod(0o600)+ temporary.replace(target)+ target.chmod(0o600)+ return target+++def store_ios_link(link: IOSLink, path: Path | None = None) -> tuple[IOSLink, ...]:+ current = list(load_ios_links(path))+ updated: list[IOSLink] = []+ replaced = False+ for existing in current:+ if existing.token == link.token:+ updated.append(link)+ replaced = True+ else:+ updated.append(existing)+ if not replaced:+ updated.append(link)+ save_ios_links(updated, path)+ return tuple(updated)+++def pairing_url(server: str, channel: str, sender: str | None = None) -> str:+ normalized_server = normalize_server(server)+ try:+ normalized_channel = str(uuid.UUID(channel))+ except ValueError as exc:+ raise LinkError("Pairing channel must be a UUID.") from exc+ query = {+ "v": "1",+ "server": normalized_server,+ "channel": normalized_channel,+ }+ clean_sender = (sender or socket.gethostname()).strip()[:80]+ if clean_sender:+ query["sender"] = clean_sender+ return "sidepulse://pair?" + urllib.parse.urlencode(query)+++def render_terminal_qr(value: str) -> str:+ try:+ import qrcode+ from qrcode.constants import ERROR_CORRECT_M+ except ImportError as exc: # pragma: no cover - packaging installs it.+ raise LinkError("QR support is unavailable; reinstall SidePulse and try again.") from exc++ code = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_M, box_size=1, border=2)+ code.add_data(value)+ code.make(fit=True)+ matrix = code.get_matrix()+ return "\n".join("".join("██" if cell else " " for cell in row) for row in matrix)+++def parse_ios_registration(value: str, *, server: str) -> IOSLink:+ try:+ payload = json.loads(value)+ except json.JSONDecodeError as exc:+ raise LinkError("Pairing response was not valid JSON.") from exc+ if not isinstance(payload, dict) or payload.get("v") != 1 or payload.get("type") != "ios_registration":+ raise LinkError("Pairing response has an unsupported format.")+ device = payload.get("device")+ if not isinstance(device, dict):+ raise LinkError("Pairing response did not include a device.")+ bundle_id = str(device.get("bundle_id") or "")+ if bundle_id != IOS_BUNDLE_ID:+ raise LinkError(f"The phone uses unsupported bundle ID {bundle_id or '(missing)' }.")+ name = str(device.get("name") or "iPhone").strip()[:80] or "iPhone"+ token = normalize_apns_token(str(device.get("push_token") or ""))+ return IOSLink(+ name=name,+ token=token,+ server=normalize_server(server),+ linked_at=datetime.now(timezone.utc).isoformat(),+ )+++def iter_sse_messages(response) -> Iterable[str]:+ data_lines: list[str] = []+ for raw_line in response:+ line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")+ if not line:+ if data_lines:+ yield "\n".join(data_lines)+ data_lines = []+ continue+ if line.startswith("data:"):+ value = line[5:]+ if value.startswith(" "):+ value = value[1:]+ data_lines.append(value)+ if data_lines:+ yield "\n".join(data_lines)+++def listen_for_ios_registration(+ server: str,+ channel: str,+ results: queue.Queue[IOSLink],+ stop: threading.Event,+ *,+ deadline: float,+) -> None:+ url = f"{normalize_server(server)}/api/leds/{urllib.parse.quote(channel, safe='')}"+ while not stop.is_set() and time.monotonic() < deadline:+ remaining = max(1.0, deadline - time.monotonic())+ request = urllib.request.Request(url, headers={"Accept": "text/event-stream"})+ try:+ with urllib.request.urlopen(request, timeout=min(20.0, remaining)) as response:+ for message in iter_sse_messages(response):+ if stop.is_set():+ return+ try:+ link = parse_ios_registration(message, server=server)+ except LinkError:+ continue+ results.put(link)+ return+ except (OSError, urllib.error.URLError):+ if not stop.wait(0.5):+ continue+++def send_ios_program(link: IOSLink, program: str, *, event_id: str | None = None) -> str:+ payload = {+ "leds": program,+ "data": {+ "sidepulse_event_id": event_id or str(uuid.uuid4()),+ },+ }+ body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+ url = f"{normalize_server(link.server)}/api/leds/apns_{link.token}"+ request = urllib.request.Request(+ url,+ data=body,+ method="POST",+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(request, timeout=10.0) as response:+ return response.read().decode("utf-8", errors="replace").strip()+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", errors="replace").strip()+ raise LinkError(detail or f"Bridge returned HTTP {exc.code}.") from exc+ except (OSError, urllib.error.URLError) as exc:+ raise LinkError(f"Could not reach the bridge: {exc}") from excdiff --git a/tests/test_links.py b/tests/test_links.pynew file mode 100644index 0000000..5358e52--- /dev/null+++ b/tests/test_links.py@@ -0,0 +1,160 @@+from __future__ import annotations++import io+import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch+++ROOT = Path(__file__).resolve().parents[1]+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))++from sidepulse.cli import sidepulse_main # noqa: E402+from sidepulse.links import ( # noqa: E402+ IOSLink,+ LinkError,+ iter_sse_messages,+ load_ios_links,+ normalize_apns_token,+ pairing_url,+ parse_ios_registration,+ render_terminal_qr,+ save_ios_links,+ store_ios_link,+)+++TOKEN_A = "a" * 64+TOKEN_B = "b" * 64+++class LinkStorageTests(unittest.TestCase):+ def test_token_is_normalized_and_validated(self) -> None:+ self.assertEqual(normalize_apns_token("AA " * 32), TOKEN_A)+ for invalid in ("", "a" * 63, "g" * 64):+ with self.subTest(invalid=invalid):+ with self.assertRaises(LinkError):+ normalize_apns_token(invalid)++ def test_links_round_trip_with_private_permissions(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ link = IOSLink("Peter's iPhone", TOKEN_A, linked_at="now")+ save_ios_links((link,), path)+ self.assertEqual(load_ios_links(path), (link,))+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)++ def test_relinking_a_token_updates_instead_of_duplicating(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "links.json"+ store_ios_link(IOSLink("Old name", TOKEN_A), path)+ stored = store_ios_link(IOSLink("New name", TOKEN_A), path)+ self.assertEqual(len(stored), 1)+ self.assertEqual(stored[0].name, "New name")++ def test_pairing_url_contains_a_uuid_channel_and_no_nonce(self) -> None:+ channel = "6f1c2a9e-8f4b-4c1d-9b3a-2e5d7c8f0a11"+ url = pairing_url("https://bridge.sidepulse.io/", channel, "Studio Mac")+ self.assertIn("sidepulse://pair?", url)+ self.assertIn("channel=6f1c2a9e-8f4b-4c1d-9b3a-2e5d7c8f0a11", url)+ self.assertIn("sender=Studio+Mac", url)+ self.assertNotIn("nonce", url)++ def test_pairing_qr_renders_without_printing_the_raw_link(self) -> None:+ url = pairing_url(+ "https://bridge.sidepulse.io",+ "6f1c2a9e-8f4b-4c1d-9b3a-2e5d7c8f0a11",+ "Studio Mac",+ )+ rendered = render_terminal_qr(url)+ self.assertIn("██", rendered)+ self.assertNotIn("sidepulse://", rendered)++ def test_sse_parser_returns_complete_data_events(self) -> None:+ response = iter(+ [+ b": keepalive\n",+ b"data: first\n",+ b"data: second\n",+ b"\n",+ ]+ )+ self.assertEqual(list(iter_sse_messages(response)), ["first\nsecond"])++ def test_registration_response_becomes_a_link(self) -> None:+ response = json.dumps(+ {+ "v": 1,+ "type": "ios_registration",+ "device": {+ "name": "Peter's iPhone",+ "platform": "ios",+ "bundle_id": "io.sidepulse.ios",+ "push_token": TOKEN_B.upper(),+ },+ }+ )+ link = parse_ios_registration(response, server="https://bridge.sidepulse.io")+ self.assertEqual(link.name, "Peter's iPhone")+ self.assertEqual(link.token, TOKEN_B)+++class WriteFallbackTests(unittest.TestCase):+ def test_write_uses_all_linked_phones_when_no_local_device_exists(self) -> None:+ links = (IOSLink("Phone A", TOKEN_A), IOSLink("Phone B", TOKEN_B))+ sent: list[tuple[str, str, str | None]] = []++ def send(link: IOSLink, program: str, *, event_id: str | None = None) -> str:+ sent.append((link.name, program, event_id))+ return "OK"++ stdout = io.StringIO()+ with (+ patch("sidepulse.cli.discover_devices", return_value=[]),+ patch("sidepulse.cli.load_ios_links", return_value=links),+ patch("sidepulse.cli.send_ios_program", side_effect=send),+ patch("sys.stdout", stdout),+ ):+ result = sidepulse_main(["write", r"off\nrepeat"])++ self.assertEqual(result, 0)+ self.assertEqual([item[0] for item in sent], ["Phone A", "Phone B"])+ self.assertTrue(all(item[1] == "off\nrepeat" for item in sent))+ self.assertEqual(len({item[2] for item in sent}), 1)++ def test_write_does_not_contact_phone_when_local_device_exists(self) -> None:+ stdout = io.StringIO()+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary) / "SidePulseDot"+ root.mkdir()+ candidate = type("Candidate", (), {"root": root, "target": root / "LEDS.LED"})()+ with (+ patch("sidepulse.cli.discover_devices", return_value=[candidate]),+ patch("sidepulse.cli.send_ios_program") as send,+ patch("sys.stdout", stdout),+ ):+ result = sidepulse_main(["write", "off", "--device", str(root)])+ self.assertEqual(result, 0)+ send.assert_not_called()+ self.assertEqual((root / "LEDS.LED").read_text(), "off")++ def test_missing_local_and_linked_devices_points_to_link_command(self) -> None:+ stderr = io.StringIO()+ with (+ patch("sidepulse.cli.discover_devices", return_value=[]),+ patch("sidepulse.cli.load_ios_links", return_value=()),+ patch("sys.stderr", stderr),+ ):+ result = sidepulse_main(["write", "off"])+ self.assertEqual(result, 2)+ self.assertIn("sidepulse link", stderr.getvalue())+++if __name__ == "__main__":+ unittest.main()