Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,24 @@ jobs:
assert ipc.request("toggle")["visible"] is False
assert ipc.request("toggle")["visible"] is True
ipc.request("reload")

# Send quit even if something above raised, so a failure earlier
# in the script cannot leave the daemon running and disguise
# itself as a shutdown that hung.
ipc.request("quit")
finally:
try:
daemon.wait(timeout=10)
# Generous: a contended runner has taken over ten seconds
# just to open the overlay, and a shutdown that is merely
# slow should not read as one that is stuck.
daemon.wait(timeout=45)
except subprocess.TimeoutExpired:
daemon.kill()
raise SystemExit("daemon did not stop on request") from None
raise SystemExit(
"daemon still running 45s after the script finished. If an "
"error appears above, `quit` was never sent and that error "
"is the real failure; otherwise the main loop ignored it."
) from None
assert daemon.returncode == 0, f"daemon exited {daemon.returncode}"
print("smoke test passed")
PY
Expand Down
39 changes: 39 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,46 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added
- `motionless sources` now names the source auto-detection would choose, and
`--auto` prints just that name for scripts. The installer uses it to say,
in the case that cannot be guessed from the overlay, that this machine has
no sensor and what to do about it.

### Changed
- The installer's closing output explains what it found rather than listing
commands: whether a motion sensor exists, the phone route with the exact
commands when it does not, and the axis check to run parked when it does.
- `motion.source = "auto"` no longer falls back to the synthetic `demo` source
when no accelerometer is present. It reports no source and draws nothing
instead. Cues that disagree with the vehicle you are in are a worse sensory
mismatch than no cues, so inventing motion to fill a missing sensor works
against the point of the program. `demo` remains available explicitly.
`doctor` now names the auto-detected source and explains what to do when
there is none.

### Fixed
- `motionless config set` and `motionless reload` reported a failure for a
change the daemon had in fact applied. Reload tore down and rebuilt every
overlay window even when nothing about the geometry had changed; on a loaded
machine that took longer than the control socket's three-second timeout, so
the client gave up while the daemon carried on and succeeded. Reload now
restyles the existing windows and only rebuilds when the set of monitors to
cover changes, and commands that do real work are allowed longer.
- The overlay connected a pair of monitor-added/removed handlers on every
start and never disconnected them, so each rebuild left another copy behind.
- `motionless stop` could hang and leave the daemon running. The quit was
scheduled with `GLib.idle_add`, which runs at `PRIORITY_DEFAULT_IDLE` —
below the overlay's `PRIORITY_DEFAULT` redraw timer. On a machine slow
enough for drawing to saturate the main loop, the quit was starved
indefinitely. It is now scheduled at `PRIORITY_HIGH`. Found when a loaded
CI runner, which took eleven seconds just to open the overlay, hit exactly
this.
- The installer asked pip to install `motionless-overlay` before checking
whether it exists, so every run printed pipx's "Fatal error from pip
prevented installation" before falling back to the repository and
succeeding. It now asks PyPI first and goes straight to the repository,
silently, while the package is unpublished.
- The installer looked frozen at `[sudo] password for ...` when run through
`curl | bash`. It now explains that sudo will ask, and that nothing is
echoed while you type, before the prompt appears rather than after.
Expand Down
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,21 @@ Run `motionless sources` to see which of these your machine can use.

| Source | Works when | Notes |
| --- | --- | --- |
| `iio` | Your device has an accelerometer | Most convertibles, tablets and some laptops. Read straight from `/sys/bus/iio`. |
| `iio` | Your device has an accelerometer | Convertibles, tablets, and laptops with screen-rotation or drive-protection sensors. Read straight from `/sys/bus/iio`. |
| `udp` | You stream readings from a phone | A phone in the car's cradle is a *better* motion sensor than a laptop on your knees. |
| `demo` | Always | Synthetic drive loop, for previewing and tuning. |
| `demo` | Always | Synthetic drive loop, for previewing and tuning **only**. |

`motion.source = "auto"` (the default) picks `iio` when an accelerometer
exists and falls back to `demo`.
`motion.source = "auto"` (the default) uses `iio` when this machine has an
accelerometer. When it does not, it reports **no source** and draws nothing.

That is deliberate. `demo` replays a scripted drive, and cues that disagree
with the vehicle you are actually in are a worse sensory mismatch than no cues
— which is the thing that makes people ill in the first place. Auto-detection
will not quietly substitute invented motion for a missing sensor. Run
`motionless doctor`: it names the source it chose, and says what to do when
there is none.

Most laptops have no accelerometer. If yours does not, use your phone.

<details>
<summary>Using your phone as the sensor</summary>
Expand Down
102 changes: 83 additions & 19 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# download is cut short, nothing runs at all rather than running half a script.
#
# Environment overrides:
# MOTIONLESS_SOURCE=pypi|git where to install from (default: pypi, git fallback)
# MOTIONLESS_SOURCE=auto|pypi|git where to install from (default: auto)
# MOTIONLESS_REF=<branch|tag> git ref when installing from git (default: main)
# MOTIONLESS_SKIP_DEPS=1 do not touch the system package manager
# MOTIONLESS_YES=1 never prompt (implied when stdin is not a terminal)
Expand Down Expand Up @@ -212,6 +212,19 @@ venv_install() {
ln -sf "$venv/bin/motionless" "$HOME/.local/bin/motionless"
}

# Is the package published? Cheap GET against the JSON API, so we never hand
# pip a name it cannot resolve just to discover it does not exist yet.
pypi_has_package() {
local name="$1"
if has curl; then
curl -fsS --max-time 10 -o /dev/null "https://pypi.org/pypi/$name/json" 2>/dev/null
elif has wget; then
wget -q --timeout=10 -O /dev/null "https://pypi.org/pypi/$name/json" 2>/dev/null
else
return 1
fi
}

install_target() {
case "${MOTIONLESS_SOURCE:-pypi}" in
git) printf 'git+%s@%s' "$REPO_URL" "${MOTIONLESS_REF:-main}" ;;
Expand All @@ -220,19 +233,28 @@ install_target() {
}

install_package() {
local target
target="$(install_target)"
info "Installing $target"

local installer=venv_install
if has pipx; then installer=pipx_install; fi

# "auto" asks PyPI whether the package exists yet; git and pypi force it.
local source="${MOTIONLESS_SOURCE:-auto}"
if [ "$source" = "auto" ]; then
if pypi_has_package "$PACKAGE"; then
source=pypi
else
info "not published to PyPI yet; installing from the git repository"
source=git
fi
fi

local target
target="$(MOTIONLESS_SOURCE="$source" install_target)"
info "Installing $target"

if ! "$installer" "$target"; then
if [ "${MOTIONLESS_SOURCE:-pypi}" = "pypi" ]; then
# Expected until the first release is published; not a failure.
info "not available on PyPI yet; installing from the git repository"
MOTIONLESS_SOURCE=git
"$installer" "$(install_target)" || die "installation failed"
if [ "$source" = "pypi" ]; then
warn "install from PyPI failed; falling back to the git repository"
"$installer" "$(MOTIONLESS_SOURCE=git install_target)" || die "installation failed"
else
die "installation failed"
fi
Expand All @@ -247,21 +269,63 @@ post_install() {

case ":$PATH:" in
*":$bin:"*) ;;
*) warn "$bin is not on your PATH; add it to your shell profile" ;;
*) warn "$bin is not on your PATH; add it to your shell profile, then open a new shell" ;;
esac

echo
if has motionless; then
motionless doctor || true
if ! has motionless; then
warn "the 'motionless' command is not on your PATH yet — open a new shell and try again"
return 0
fi

info "Checking this machine"
echo
motionless doctor || true
echo

# The one thing people need to know and cannot guess: whether there is
# anything to react to. Without a sensor the overlay is correct and idle,
# which is indistinguishable from broken unless we say so here.
local source
source="$(motionless sources --auto 2>/dev/null || true)"

if [ "$source" = "none" ]; then
warn "No motion sensor found on this machine."
echo " This laptop has no accelerometer under /sys/bus/iio, so there is"
echo " nothing for the cues to follow. motionless will start, and draw"
echo " nothing, until you give it a source of motion."
echo
info "Next steps"
echo " motionless start # run it now"
echo " motionless toggle # bind this to a hotkey"
echo " motionless service install # start with your session"
echo " motionless config edit # tune the look"
info "Use your phone instead — it has the sensor this machine lacks"
echo " 1. Put your laptop and phone on the same network (a phone hotspot is fine)."
echo " 2. Install any Android app that streams the accelerometer over UDP."
echo " 3. Point it at this machine on port 5577, then:"
echo
echo " motionless config set motion.source udp"
echo " motionless config set motion.udp.host 0.0.0.0"
echo " motionless start"
echo " motionless status # 'samples' should climb"
echo
echo " Full instructions: https://github.com/guilyx/motionless#where-the-motion-comes-from"
echo
info "To see what the cues look like without any sensor"
echo " motionless run --source demo --always-on"
echo " (a scripted drive — for previewing only, never use it in a vehicle)"
else
warn "the 'motionless' command is not on your PATH yet — open a new shell and try again"
ok "Motion sensor found: $source"
echo
info "Get going"
echo " motionless start # run it now"
echo " motionless toggle # bind this to a hotkey"
echo " motionless service install # start with your session"
echo
warn "Check the axis mapping before you rely on it — parked, not driving:"
echo " motionless start"
echo " watch -n 0.3 'motionless status | grep motion'"
echo " Slide the laptop to your right: 'lat' should go positive."
echo " If it does not, see the Tuning section of the README."
fi
echo
info "Anything unclear: motionless doctor | motionless --help"
}

uninstall() {
Expand Down
31 changes: 26 additions & 5 deletions src/motionless/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,12 @@ def build_parser() -> argparse.ArgumentParser:
help="backdrop colour, or 'none' for a transparent PNG",
)

sub.add_parser("sources", help="list motion sources and whether they are usable")
sources = sub.add_parser("sources", help="list motion sources and whether they are usable")
sources.add_argument(
"--auto",
action="store_true",
help="print only the source auto-detection would choose, for scripts",
)
doctor = sub.add_parser("doctor", help="check this machine can run the overlay")
doctor.add_argument("--json", action="store_true", help="machine-readable output")

Expand Down Expand Up @@ -366,16 +371,32 @@ def cmd_preview(args: argparse.Namespace) -> int:
return 0


def cmd_sources(_args: argparse.Namespace) -> int:
from motionless.sources import SOURCES
def cmd_sources(args: argparse.Namespace) -> int:
from motionless.sources import SOURCES, detect

if args.auto:
# Machine-readable and nothing else, so the installer can branch on it.
print(detect().name)
return 0

available = probe_all()
for source in SOURCES:
availability = probe_all()[source.name]
if source.name == "none":
continue
availability = available[source.name]
level = Level.OK if availability.available else Level.WARN
print(f"{_paint(_MARKERS[level], level)} {source.name:<6} {source.description}")
if availability.detail:
print(f" {availability.detail}")
print("\nSelect one with `motionless config set motion.source <name>`.")

chosen = detect().name
print()
if chosen == "none":
print("Auto-detection finds no sensor on this machine, so no cues will appear.")
print("Stream from a phone instead: `motionless config set motion.source udp`.")
else:
print(f"Auto-detection would use: {chosen}")
print("Override with `motionless config set motion.source <name>`.")
return 0


Expand Down
18 changes: 15 additions & 3 deletions src/motionless/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,15 @@ def run(self) -> int:
GLib.unix_signal_add(GLib.PRIORITY_HIGH, sig, self._on_signal)

self._source.start()
log.info("motion source: %s", self._source.name)
if self._source.name == "none":
log.warning(
"no motion source: this machine has no accelerometer under "
"/sys/bus/iio, so there is nothing to react to and no cues "
"will appear. Run `motionless sources`; the usual answer is "
'to stream from a phone with `motion.source = "udp"`.'
)
else:
log.info("motion source: %s", self._source.name)
self._overlay.start(visible=self._initial_visible)
log.info(
"overlay ready on %d monitor(s), cues %s",
Expand Down Expand Up @@ -197,8 +205,12 @@ def _handle_command(self, command: str, _args: dict[str, Any]) -> dict[str, Any]
if command == "reload":
return self.reload()
if command == "quit":
# Defer so the reply reaches the client before the loop ends.
self._glib.idle_add(self.quit)
# Defer so the reply reaches the client before the loop ends, but
# at high priority: the overlay's redraw is a PRIORITY_DEFAULT
# timeout, and a default-idle callback sits *below* that. On a
# machine slow enough for drawing to saturate the loop, the quit
# would be starved indefinitely and `motionless stop` would hang.
self._glib.idle_add(self.quit, priority=self._glib.PRIORITY_HIGH)
return {"stopping": True}
raise ValueError(f"unhandled command {command!r}") # pragma: no cover

Expand Down
19 changes: 19 additions & 0 deletions src/motionless/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,29 @@ def check_display() -> list[Check]:


def check_sources() -> list[Check]:
from motionless.sources import detect

checks = []
for name, availability in probe_all().items():
if name == "none":
continue
level = Level.OK if availability.available else Level.WARN
checks.append(Check(f"Source: {name}", level, availability.detail or "-"))

chosen = detect()
if chosen.name == "none":
checks.append(
Check(
"Auto-detected source",
Level.WARN,
"none — no accelerometer on this machine, so no cues will appear",
"stream from a phone: `motionless config set motion.source udp` "
"(see the README), or preview the look with "
"`motionless run --source demo`",
)
)
else:
checks.append(Check("Auto-detected source", Level.OK, chosen.name))
return checks


Expand Down
6 changes: 6 additions & 0 deletions src/motionless/ipc.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
#: Seconds a CLI call waits for the daemon to answer.
DEFAULT_TIMEOUT = 3.0

#: Commands the daemon answers only after real work, and how long to allow.
#: Giving up early is worse than waiting: the daemon still applies the change,
#: so a timeout reports a failure for something that in fact succeeded.
SLOW_COMMANDS = {"reload": 30.0}

#: Dispatches a command name plus arguments and returns the response payload.
CommandHandler = Callable[[str, dict[str, Any]], dict[str, Any]]

Expand Down Expand Up @@ -88,6 +93,7 @@ def request(
:class:`RuntimeError` if the daemon reports a failure.
"""
target = path or socket_file()
timeout = max(timeout, SLOW_COMMANDS.get(command, 0.0))
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connection.settimeout(timeout)
try:
Expand Down
Loading
Loading