Skip to content

CLI for SidePulse

Python

Add targeted writes and push notifications

Peter Kuhar0af743455069
diff --git a/README.md b/README.md
index 4026036..620b19a 100644
--- a/README.md
+++ b/README.md
@@ -54,15 +54,49 @@ python3 -m pip install -e .
sidepulse setup
```
-Write an LED program directly to a mounted SidePulse Pro or SidePulse Dot device:
+Send an LED program to SidePulse:
```sh
sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat"
```
+`sidepulse write` prefers mounted hardware and falls back to a linked phone.
+`sidepulse push` accepts the same options but prefers a linked phone, which is
+useful for hooks and remote notifications:
+
+```sh
+sidepulse push "off\n#00ff66 pulse\nrepeat" \
+ --title "Build complete" \
+ --message "All tests passed"
+```
+
+The LED program is optional when a title or message is present:
+
+```sh
+sidepulse push --title "Agent needs input" --message "Choose a deployment region"
+```
+
+Choose a destination by its displayed name or short ID. If multiple compatible
+destinations are available, SidePulse asks for `--to` instead of silently
+broadcasting. Use `--all` when broadcasting is intentional:
+
+```sh
+sidepulse write "off" --to "Peter's iPhone"
+sidepulse push "off" --to a1b2c3d4
+sidepulse write "off" --all
+```
+
+Both commands accept `-` for stdin. `sidepulse write` also reads piped stdin when
+no LED argument or notification text was supplied:
+
+```sh
+printf 'off\n#ff3a00 pulse\nrepeat' | sidepulse write
+sidepulse push - --title "Deploying" < deploy.LED
+```
+
The CLI auto-detects mounted devices under `/Volumes` by looking for a
-SidePulse Pro/SidePulse Dot-style volume name or an existing `LEDS.LED`. If more than
-one device is possible, pass the mounted folder or file explicitly:
+SidePulse Pro/SidePulse Dot-style volume name or an existing `LEDS.LED`. For a
+specific local path, the existing `--device` option remains available:
```sh
sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat" --device /Volumes/SidePulsePro
@@ -81,10 +115,11 @@ or paste the 64-character push token shown by the app:
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.
+Linked phones are stored locally. Remote LED-only writes are silent. Adding
+`--title` or `--message` produces one visible notification containing the same
+LED program and event metadata. Remote payloads also include the sending
+computer's name and available battery state. Set `SIDEPULSE_SERVER` to use
+another bridge origin.
## Battery LEDs
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.py
index 3b8af33..e7ba4da 100644
--- a/src/sidepulse/cli.py
+++ b/src/sidepulse/cli.py
@@ -6,6 +6,7 @@ import os
import queue
import select
import shutil
+import socket
import subprocess
import sys
import threading
@@ -27,7 +28,7 @@ from .device_writer import (
discover_devices,
normalize_led_text,
validate_led_text,
- write_led_program,
+ write_normalized_led_program,
)
from .hook import hook_log_main
from .install import (
@@ -140,22 +141,18 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:
write = subparsers.add_parser(
"write",
- help=f"Write an LED program to {DEFAULT_FILE_NAME} on a mounted SidePulse Pro or SidePulse Dot device.",
+ help="Send an LED program, notification, or both to SidePulse.",
)
- write.add_argument("text", help=r"LED program text. Backslash escapes like \n are decoded.")
- write.add_argument(
- "--device",
- type=Path,
- help="Mounted device folder or LED program file path. Defaults to auto-detecting /Volumes.",
- )
- write.add_argument(
- "--file-name",
- default=DEFAULT_FILE_NAME,
- help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
- )
- write.add_argument("--dry-run", action="store_true", help="Show the target without writing.")
+ add_sidepulse_delivery_arguments(write)
write.set_defaults(func=cmd_sidepulse_write)
+ push = subparsers.add_parser(
+ "push",
+ help="Send an LED program, notification, or both, preferring a linked phone.",
+ )
+ add_sidepulse_delivery_arguments(push)
+ push.set_defaults(func=cmd_sidepulse_push)
+
link = subparsers.add_parser(
"link",
help="Link an iPhone by scanning a QR code or pasting its push token.",
@@ -172,6 +169,29 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:
return parser
+def add_sidepulse_delivery_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "text",
+ nargs="?",
+ help=r"LED program text. Backslash escapes like \n are decoded. Use - to read stdin.",
+ )
+ parser.add_argument("--title", help="Notification title.")
+ parser.add_argument("--message", help="Notification message.")
+ parser.add_argument("--to", help="Destination name or ID. Use 'local' or 'phone' when unambiguous.")
+ parser.add_argument("--all", action="store_true", help="Send to every compatible destination.")
+ parser.add_argument(
+ "--device",
+ type=Path,
+ help="Mounted device folder or LED program file path. Cannot be combined with --to or --all.",
+ )
+ parser.add_argument(
+ "--file-name",
+ default=DEFAULT_FILE_NAME,
+ help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
+ )
+ parser.add_argument("--dry-run", action="store_true", help="Show the target without writing or sending.")
+
+
def add_hook_log_parser(subparsers: argparse._SubParsersAction) -> None:
hook_log = subparsers.add_parser("hook-log", help="Internal hook logging entry point.")
hook_log.add_argument("--provider", choices=HOOK_PROVIDERS, required=True)
@@ -310,62 +330,273 @@ def add_sidepulse_battery_parser(subparsers: argparse._SubParsersAction) -> None
def 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)
+ return _cmd_sidepulse_delivery(args, command="write", prefer_phone=False)
- try:
- target = write_led_program(
- args.text,
- device_path=args.device,
- file_name=args.file_name,
- dry_run=args.dry_run,
- )
- except DeviceWriteError as exc:
- print(f"sidepulse write: {exc}", file=sys.stderr)
- return 2
- except OSError as exc:
- print(f"sidepulse write: {exc}", file=sys.stderr)
- return 1
- action = "would write" if args.dry_run else "wrote"
- print(f"{action}: {target}")
- return 0
+def cmd_sidepulse_push(args: argparse.Namespace) -> int:
+ return _cmd_sidepulse_delivery(args, command="push", prefer_phone=True)
+
+def _cmd_sidepulse_delivery(
+ args: argparse.Namespace,
+ *,
+ command: str,
+ prefer_phone: bool,
+) -> int:
+ prefix = f"sidepulse {command}"
+ if args.to and args.all:
+ print(f"{prefix}: Use either --to or --all, not both.", file=sys.stderr)
+ return 2
+ if args.device is not None and (args.to or args.all):
+ print(f"{prefix}: --device cannot be combined with --to or --all.", file=sys.stderr)
+ return 2
-def cmd_sidepulse_write_ios(args: argparse.Namespace) -> int:
+ title = _clean_notification_text(args.title)
+ message = _clean_notification_text(args.message)
+ has_notification = title is not None or message is not None
try:
- program = normalize_led_text(args.text)
- validate_led_text(program)
+ program = _program_from_args(args.text, allow_implicit_stdin=not has_notification)
+ if program is not None:
+ validate_led_text(program)
except DeviceWriteError as exc:
- print(f"sidepulse write: {exc}", file=sys.stderr)
+ print(f"{prefix}: {exc}", file=sys.stderr)
return 2
- links = load_ios_links()
- if not links:
+ if program is None and not has_notification:
print(
- "sidepulse write: No SidePulse device found. "
- "Run `sidepulse link` to connect your phone.",
+ f"{prefix}: Provide an LED program, --title, or --message.",
file=sys.stderr,
)
return 2
+ if args.device is not None:
+ if has_notification:
+ print(
+ f"{prefix}: A local SidePulse cannot display notifications. "
+ "Choose a linked phone with --to.",
+ file=sys.stderr,
+ )
+ return 2
+ return _write_explicit_local(args, program, prefix=prefix)
+
+ local_devices = discover_devices(file_name=args.file_name)
+ phone_links = load_ios_links()
+ try:
+ local_targets, phone_targets = _select_delivery_targets(
+ requested=args.to,
+ send_all=args.all,
+ program=program,
+ has_notification=has_notification,
+ prefer_phone=prefer_phone,
+ local_devices=local_devices,
+ phone_links=phone_links,
+ )
+ except DeviceWriteError as exc:
+ print(f"{prefix}: {exc}", file=sys.stderr)
+ return 2
+
if args.dry_run:
- for link in links:
- print(f"would send: {link.name}")
+ for candidate in local_targets:
+ print(f"would write: {candidate.target}")
+ for link in phone_targets:
+ print(f"would send: {link.name} ({link.link_id})")
return 0
event_id = str(uuid.uuid4())
+ event_data = _remote_event_data(event_id) if phone_targets else None
failed = False
- for link in links:
+ for candidate in local_targets:
+ try:
+ target = write_normalized_led_program(
+ program or "",
+ device_path=candidate.target,
+ file_name=args.file_name,
+ )
+ print(f"wrote: {target}")
+ except (DeviceWriteError, OSError) as exc:
+ failed = True
+ print(f"{prefix}: {candidate.root}: {exc}", file=sys.stderr)
+
+ for link in phone_targets:
try:
- send_ios_program(link, program, event_id=event_id)
- print(f"sent: {link.name}")
+ send_ios_program(
+ link,
+ program,
+ event_id=event_id,
+ title=title,
+ message=message,
+ data=event_data,
+ )
+ print(f"sent: {link.name} ({link.link_id})")
except LinkError as exc:
failed = True
- print(f"sidepulse write: {link.name}: {exc}", file=sys.stderr)
+ print(f"{prefix}: {link.name}: {exc}", file=sys.stderr)
return 1 if failed else 0
+def _clean_notification_text(value: str | None) -> str | None:
+ if value is None:
+ return None
+ cleaned = value.strip()
+ return cleaned or None
+
+
+def _program_from_args(text: str | None, *, allow_implicit_stdin: bool) -> str | None:
+ if text == "-":
+ return normalize_led_text(sys.stdin.read())
+ if text is not None:
+ return normalize_led_text(text)
+ if allow_implicit_stdin:
+ piped = _read_available_stdin()
+ if piped is not None:
+ return normalize_led_text(piped)
+ return None
+
+
+def _read_available_stdin() -> str | None:
+ try:
+ if sys.stdin.isatty():
+ return None
+ readable, _, _ = select.select([sys.stdin], [], [], 0)
+ if readable:
+ return sys.stdin.read()
+ except (AttributeError, OSError, TypeError, ValueError):
+ return None
+ return None
+
+
+def _write_explicit_local(args: argparse.Namespace, program: str | None, *, prefix: str) -> int:
+ if program is None:
+ print(f"{prefix}: A local SidePulse requires an LED program.", file=sys.stderr)
+ return 2
+ try:
+ target = write_normalized_led_program(
+ program,
+ device_path=args.device,
+ file_name=args.file_name,
+ dry_run=args.dry_run,
+ )
+ except DeviceWriteError as exc:
+ print(f"{prefix}: {exc}", file=sys.stderr)
+ return 2
+ except OSError as exc:
+ print(f"{prefix}: {exc}", file=sys.stderr)
+ return 1
+ action = "would write" if args.dry_run else "wrote"
+ print(f"{action}: {target}")
+ return 0
+
+
+def _select_delivery_targets(
+ *,
+ requested: str | None,
+ send_all: bool,
+ program: str | None,
+ has_notification: bool,
+ prefer_phone: bool,
+ local_devices,
+ phone_links: tuple[IOSLink, ...],
+):
+ if send_all:
+ if has_notification and not phone_links:
+ raise DeviceWriteError(
+ "No linked phone can display the notification. Run `sidepulse link`."
+ )
+ local_targets = list(local_devices) if program is not None else []
+ phone_targets = list(phone_links)
+ if not local_targets and not phone_targets:
+ raise DeviceWriteError("No destinations found. Run `sidepulse link` to connect your phone.")
+ return local_targets, phone_targets
+
+ if requested:
+ matches = _matching_destinations(requested, local_devices, phone_links)
+ if not matches:
+ available = _format_destinations(local_devices, phone_links)
+ suffix = f"\nAvailable destinations:\n{available}" if available else ""
+ raise DeviceWriteError(f"No destination matches {requested!r}.{suffix}")
+ if len(matches) > 1:
+ rendered = "\n".join(f" {label}" for _, _, label in matches)
+ raise DeviceWriteError(
+ f"Destination {requested!r} is ambiguous:\n{rendered}\nUse its ID with --to."
+ )
+ kind, target, _ = matches[0]
+ if kind == "local":
+ if has_notification:
+ raise DeviceWriteError(
+ "A local SidePulse cannot display notifications. Choose a linked phone with --to."
+ )
+ if program is None:
+ raise DeviceWriteError("A local SidePulse requires an LED program.")
+ return [target], []
+ return [], [target]
+
+ targets_are_phones = has_notification or (prefer_phone and bool(phone_links)) or not local_devices
+ compatible = list(phone_links) if targets_are_phones else list(local_devices)
+ if not compatible:
+ if has_notification:
+ raise DeviceWriteError("No linked phone found. Run `sidepulse link`.")
+ raise DeviceWriteError("No SidePulse destination found. Run `sidepulse link` to connect your phone.")
+ if len(compatible) > 1:
+ if targets_are_phones:
+ rendered = _format_destinations([], compatible)
+ else:
+ rendered = _format_destinations(compatible, ())
+ raise DeviceWriteError(
+ "More than one destination is available:\n"
+ f"{rendered}\nChoose one with --to, or use --all."
+ )
+ if targets_are_phones:
+ return [], compatible
+ return compatible, []
+
+
+def _matching_destinations(requested: str, local_devices, phone_links: tuple[IOSLink, ...]):
+ query = requested.strip().casefold()
+ if not query:
+ return []
+ if query == "local":
+ return [("local", item, f"{item.root.name} ({item.root})") for item in local_devices]
+ if query == "phone":
+ return [("phone", item, f"{item.name} ({item.link_id})") for item in phone_links]
+
+ matches = []
+ for item in local_devices:
+ names = {item.root.name.casefold(), str(item.root).casefold(), str(item.target).casefold()}
+ if query in names:
+ matches.append(("local", item, f"{item.root.name} ({item.root})"))
+ for item in phone_links:
+ id_matches = query == item.link_id.casefold() or (
+ len(query) >= 4 and item.link_id.casefold().startswith(query)
+ )
+ if query == item.name.casefold() or id_matches:
+ matches.append(("phone", item, f"{item.name} ({item.link_id})"))
+ return matches
+
+
+def _format_destinations(local_devices, phone_links) -> str:
+ lines = [f" {item.root.name} ({item.root})" for item in local_devices]
+ lines.extend(f" {item.name} ({item.link_id})" for item in phone_links)
+ return "\n".join(lines)
+
+
+def _remote_event_data(event_id: str) -> dict[str, object]:
+ source: dict[str, object] = {"name": socket.gethostname()}
+ try:
+ battery = read_battery_snapshot()
+ except Exception:
+ battery = None
+ if battery is not None and battery.battery_present:
+ source["battery"] = {
+ "level": battery.percent,
+ "charging": battery.is_charging,
+ "plugged_in": battery.is_plugged,
+ }
+ return {
+ "sidepulse_event_id": event_id,
+ "source": source,
+ }
+
+
def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
try:
server = bridge_server()
@@ -394,7 +625,10 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
existing = load_ios_links()
if existing:
- print("Linked phones: " + ", ".join(link.name for link in existing))
+ print(
+ "Linked phones: "
+ + ", ".join(f"{link.name} ({link.link_id})" for link in existing)
+ )
print()
print("Link your iPhone")
print()
@@ -458,7 +692,11 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:
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.")
+ print(
+ f"Linked {link.name} ({link.link_id}). "
+ "`sidepulse write` uses it when no local device is mounted; "
+ "`sidepulse push` prefers it."
+ )
return 0
diff --git a/src/sidepulse/device_writer.py b/src/sidepulse/device_writer.py
index 260d0ec..feba484 100644
--- a/src/sidepulse/device_writer.py
+++ b/src/sidepulse/device_writer.py
@@ -36,6 +36,21 @@ def write_led_program(
dry_run: bool = False,
) -> Path:
program = normalize_led_text(text)
+ return write_normalized_led_program(
+ program,
+ device_path=device_path,
+ file_name=file_name,
+ dry_run=dry_run,
+ )
+
+
+def write_normalized_led_program(
+ program: str,
+ *,
+ device_path: Path | None = None,
+ file_name: str = DEFAULT_FILE_NAME,
+ dry_run: bool = False,
+) -> Path:
validate_led_text(program)
target = resolve_target_path(device_path=device_path, file_name=file_name)
diff --git a/src/sidepulse/links.py b/src/sidepulse/links.py
index b6c1e22..18f193f 100644
--- a/src/sidepulse/links.py
+++ b/src/sidepulse/links.py
@@ -271,13 +271,41 @@ def listen_for_ios_registration(
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()),
- },
+def send_ios_program(
+ link: IOSLink,
+ program: str | None = None,
+ *,
+ event_id: str | None = None,
+ title: str | None = None,
+ message: str | None = None,
+ data: dict[str, object] | None = None,
+) -> str:
+ clean_title = title.strip() if title else ""
+ clean_message = message.strip() if message else ""
+ if program is None and not clean_title and not clean_message:
+ raise LinkError("A remote write must contain LEDs, a title, or a message.")
+
+ custom_data = dict(data or {})
+ custom_data["sidepulse_event_id"] = event_id or str(uuid.uuid4())
+ aps: dict[str, object] = {"content-available": 1}
+ if clean_title or clean_message:
+ alert: dict[str, str] = {}
+ if clean_title:
+ alert["title"] = clean_title
+ if clean_message:
+ alert["body"] = clean_message
+ aps["alert"] = alert
+
+ payload: dict[str, object] = {
+ "aps": aps,
+ "data": custom_data,
}
+ if program is not None:
+ payload["leds"] = program
+ if clean_title:
+ payload["title"] = clean_title
+ if clean_message:
+ payload["body"] = clean_message
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(
diff --git a/tests/test_links.py b/tests/test_links.py
index 6532446..4969df7 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -7,7 +7,7 @@ import sys
import tempfile
import unittest
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
@@ -27,6 +27,7 @@ from sidepulse.links import ( # noqa: E402
parse_ios_registration,
render_terminal_qr,
save_ios_links,
+ send_ios_program,
store_ios_link,
)
@@ -127,27 +128,42 @@ class LinkStorageTests(unittest.TestCase):
class WriteFallbackTests(unittest.TestCase):
- def test_write_uses_all_linked_phones_when_no_local_device_exists(self) -> None:
+ def test_write_requires_selection_when_multiple_linked_phones_exist(self) -> None:
links = (IOSLink("Phone A", TOKEN_A), IOSLink("Phone B", TOKEN_B))
- sent: list[tuple[str, str, str | None]] = []
+ stderr = 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") as send,
+ patch("sys.stderr", stderr),
+ ):
+ result = sidepulse_main(["write", r"off\nrepeat"])
+
+ self.assertEqual(result, 2)
+ send.assert_not_called()
+ self.assertIn("--to", stderr.getvalue())
+ self.assertIn("--all", stderr.getvalue())
- def send(link: IOSLink, program: str, *, event_id: str | None = None) -> str:
- sent.append((link.name, program, event_id))
+ def test_write_all_uses_all_linked_phones(self) -> None:
+ links = (IOSLink("Phone A", TOKEN_A), IOSLink("Phone B", TOKEN_B))
+ sent: list[tuple[IOSLink, str | None, dict[str, object]]] = []
+
+ def send(link: IOSLink, program: str | None, **kwargs) -> str:
+ sent.append((link, program, kwargs))
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._remote_event_data", return_value={"source": {"name": "Mac"}}),
patch("sidepulse.cli.send_ios_program", side_effect=send),
- patch("sys.stdout", stdout),
):
- result = sidepulse_main(["write", r"off\nrepeat"])
+ result = sidepulse_main(["write", r"off\nrepeat", "--all"])
self.assertEqual(result, 0)
- self.assertEqual([item[0] for item in sent], ["Phone A", "Phone B"])
+ self.assertEqual([item[0].name 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)
+ self.assertEqual(len({item[2]["event_id"] for item in sent}), 1)
def test_write_does_not_contact_phone_when_local_device_exists(self) -> None:
stdout = io.StringIO()
@@ -165,6 +181,22 @@ class WriteFallbackTests(unittest.TestCase):
send.assert_not_called()
self.assertEqual((root / "LEDS.LED").read_text(), "off")
+ def test_write_prefers_discovered_local_device_over_phone(self) -> None:
+ 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.load_ios_links", return_value=(IOSLink("Phone", TOKEN_A),)),
+ patch("sidepulse.cli.send_ios_program") as send,
+ ):
+ result = sidepulse_main(["write", r"off\nrepeat"])
+
+ self.assertEqual(result, 0)
+ send.assert_not_called()
+ self.assertEqual((root / "LEDS.LED").read_text(), "off\nrepeat")
+
def test_missing_local_and_linked_devices_points_to_link_command(self) -> None:
stderr = io.StringIO()
with (
@@ -176,6 +208,185 @@ class WriteFallbackTests(unittest.TestCase):
self.assertEqual(result, 2)
self.assertIn("sidepulse link", stderr.getvalue())
+ def test_notification_prefers_phone_over_local_device(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary) / "SidePulseDot"
+ root.mkdir()
+ candidate = type("Candidate", (), {"root": root, "target": root / "LEDS.LED"})()
+ phone = IOSLink("Peter's iPhone", TOKEN_A)
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[candidate]),
+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ ):
+ result = sidepulse_main(
+ ["write", "off", "--title", "Build complete", "--message", "All tests passed"]
+ )
+
+ self.assertEqual(result, 0)
+ self.assertFalse((root / "LEDS.LED").exists())
+ send.assert_called_once()
+ self.assertEqual(send.call_args.args, (phone, "off"))
+ self.assertEqual(send.call_args.kwargs["title"], "Build complete")
+ self.assertEqual(send.call_args.kwargs["message"], "All tests passed")
+
+ def test_write_selects_phone_by_short_id(self) -> None:
+ phones = (IOSLink("Phone A", TOKEN_A), IOSLink("Phone B", TOKEN_B))
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[]),
+ patch("sidepulse.cli.load_ios_links", return_value=phones),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ ):
+ result = sidepulse_main(["write", "off", "--to", "bbbb"])
+
+ self.assertEqual(result, 0)
+ self.assertEqual(send.call_args.args[:2], (phones[1], "off"))
+
+ def test_notification_cannot_target_local_device(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary) / "SidePulseDot"
+ root.mkdir()
+ candidate = type("Candidate", (), {"root": root, "target": root / "LEDS.LED"})()
+ stderr = io.StringIO()
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[candidate]),
+ patch("sidepulse.cli.load_ios_links", return_value=()),
+ patch("sys.stderr", stderr),
+ ):
+ result = sidepulse_main(["write", "off", "--message", "Hello", "--to", "local"])
+
+ self.assertEqual(result, 2)
+ self.assertIn("cannot display notifications", stderr.getvalue())
+
+ def test_push_uses_same_payload_options_and_prefers_phone(self) -> None:
+ phone = IOSLink("Peter's iPhone", TOKEN_A)
+ local = type(
+ "Candidate",
+ (),
+ {"root": Path("/Volumes/SidePulseDot"), "target": Path("/Volumes/SidePulseDot/LEDS.LED")},
+ )()
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[local]),
+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ ):
+ result = sidepulse_main(
+ [
+ "push",
+ r"off\n#ff0000 pulse",
+ "--title",
+ "Agent needs input",
+ "--message",
+ "Choose a deployment region",
+ ]
+ )
+
+ self.assertEqual(result, 0)
+ self.assertEqual(send.call_args.args, (phone, "off\n#ff0000 pulse"))
+ self.assertEqual(send.call_args.kwargs["title"], "Agent needs input")
+ self.assertEqual(send.call_args.kwargs["message"], "Choose a deployment region")
+
+ def test_write_all_sends_leds_locally_and_combined_payload_to_phone(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary) / "SidePulseDot"
+ root.mkdir()
+ candidate = type("Candidate", (), {"root": root, "target": root / "LEDS.LED"})()
+ phone = IOSLink("Phone", TOKEN_A)
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[candidate]),
+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ ):
+ result = sidepulse_main(
+ ["write", "off", "--title", "Done", "--message", "Tests passed", "--all"]
+ )
+
+ self.assertEqual(result, 0)
+ self.assertEqual((root / "LEDS.LED").read_text(), "off")
+ self.assertEqual(send.call_args.args, (phone, "off"))
+ self.assertEqual(send.call_args.kwargs["title"], "Done")
+
+ def test_notification_only_write_is_supported(self) -> None:
+ phone = IOSLink("Phone", TOKEN_A)
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[]),
+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ ):
+ result = sidepulse_main(["write", "--title", "Done", "--message", "Tests passed"])
+
+ self.assertEqual(result, 0)
+ self.assertEqual(send.call_args.args, (phone, None))
+
+ def test_write_requires_content(self) -> None:
+ stderr = io.StringIO()
+ with patch("sys.stderr", stderr):
+ result = sidepulse_main(["write"])
+
+ self.assertEqual(result, 2)
+ self.assertIn("Provide an LED program", stderr.getvalue())
+
+ def test_write_reads_led_program_from_explicit_stdin(self) -> None:
+ phone = IOSLink("Peter's iPhone", TOKEN_A)
+ with (
+ patch("sidepulse.cli.discover_devices", return_value=[]),
+ patch("sidepulse.cli.load_ios_links", return_value=(phone,)),
+ patch("sidepulse.cli._remote_event_data", return_value={}),
+ patch("sidepulse.cli.send_ios_program", return_value="OK") as send,
+ patch("sys.stdin", io.StringIO(r"off\nrepeat")),
+ ):
+ result = sidepulse_main(["write", "-"])
+
+ self.assertEqual(result, 0)
+ self.assertEqual(send.call_args.args, (phone, "off\nrepeat"))
+
+
+class IOSPayloadTests(unittest.TestCase):
+ def test_notification_payload_contains_visible_alert_leds_and_metadata(self) -> None:
+ response = MagicMock()
+ response.__enter__.return_value.read.return_value = b"OK"
+ with patch("sidepulse.links.urllib.request.urlopen", return_value=response) as open_url:
+ result = send_ios_program(
+ IOSLink("Phone", TOKEN_A),
+ "off",
+ event_id="event-1",
+ title="Build complete",
+ message="All tests passed",
+ data={"source": {"name": "Studio Mac"}},
+ )
+
+ self.assertEqual(result, "OK")
+ request = open_url.call_args.args[0]
+ payload = json.loads(request.data)
+ self.assertEqual(payload["leds"], "off")
+ self.assertEqual(payload["title"], "Build complete")
+ self.assertEqual(payload["body"], "All tests passed")
+ self.assertEqual(
+ payload["aps"],
+ {
+ "content-available": 1,
+ "alert": {"title": "Build complete", "body": "All tests passed"},
+ },
+ )
+ self.assertEqual(payload["data"]["sidepulse_event_id"], "event-1")
+ self.assertEqual(payload["data"]["source"]["name"], "Studio Mac")
+
+ def test_led_only_payload_stays_silent(self) -> None:
+ response = MagicMock()
+ response.__enter__.return_value.read.return_value = b"OK"
+ with patch("sidepulse.links.urllib.request.urlopen", return_value=response) as open_url:
+ send_ios_program(IOSLink("Phone", TOKEN_A), "off", event_id="event-1")
+
+ payload = json.loads(open_url.call_args.args[0].data)
+ self.assertEqual(payload["aps"], {"content-available": 1})
+ self.assertNotIn("title", payload)
+ self.assertNotIn("body", payload)
+
if __name__ == "__main__":
unittest.main()