A connection that won't open says why, wherever it fails
The September messages reached the device picker and the command line, but three other places still lost them. The reconnect dialog retried every failure in silence, so a device that came back and refused (its port taken by the MeshCore app, a stale pairing) kept the spinner up forever; from the second failure in a row it now shows the reason under the spinner, and goes back to waiting if the device is unplugged again. A device named on the command line skipped the picker, and a failed start was dropped unlogged; it is now shown before the menu opens. And a failed open left the dead device behind, so is_connected said yes and every later tool failed with "not connected": it is dropped, and the next tool tries again and says why. TCP failures are named one by one (host not found, nothing on the port, no route, no answer, hung up) instead of all reading "no response from a MeshCore companion". A failure MeshTerm has no name for is no longer called "not a MeshCore device": it is said in its own words, its traceback is logged once, and the dialog says where the log file is. The tool-failure dialog stops reading an error's brackets as markup, which had silently deleted "[org.bluez.Error.Failed]" from Linux Bluetooth errors. docs/guide/connecting.md lists the TCP messages and where each message appears. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
58909d1373
commit
61d7463ddf
9 files changed
+857
-59
No files matched your search
@@ -2,14 +2,30 @@
|
||||
|
||||
MeshTerm talks to a MeshCore companion over USB, Bluetooth, or TCP, or runs the node itself
|
||||
on a radio on the SPI bus. When a connection fails, MeshTerm says which step failed and what
|
||||
to do about it, in the device picker and on the command line alike. This page collects those
|
||||
messages, so you can look one up before you meet it, or search for the one you have.
|
||||
to do about it. This page collects those messages, so you can look one up before you meet
|
||||
it, or search for the one you have.
|
||||
|
||||
You see the same message wherever the connection fails:
|
||||
|
||||
- **In the device picker**, when you choose a device.
|
||||
- **When MeshTerm starts**, if you named the device on the command line (`--port`, `--ble`,
|
||||
`--tcp`, or `--profile`). MeshTerm shows the message, then opens the menu without a
|
||||
radio. A tool that needs the radio tries to connect again when you open it.
|
||||
- **While MeshTerm waits for a device to come back**, after it was unplugged or rebooted.
|
||||
If the device comes back but still won't connect, the message appears under the
|
||||
spinner, so you are not left waiting for something that will not happen. Fix the
|
||||
problem, and MeshTerm connects without you doing anything else.
|
||||
- **On the command line**, as the error message.
|
||||
|
||||
Every failure is also written to the log file, `~/.meshterm/meshterm.log` (see
|
||||
[Where MeshTerm keeps its state](../cli/README.md#where-meshterm-keeps-its-state)). Attach it to a
|
||||
bug report. For more detail, set the **Log detail** preference to `DEBUG` (`meshterm
|
||||
preferences set log_level DEBUG`) and run it again.
|
||||
|
||||
Sometimes MeshTerm meets a failure it has no name for. Then the message is the error in
|
||||
its own words, and a second line says where the log file is. The log holds the full
|
||||
error, which is what a bug report needs.
|
||||
|
||||
- [Bluetooth](#bluetooth)
|
||||
- [Who does the pairing](#who-does-the-pairing)
|
||||
- [Finding the PIN](#finding-the-pin)
|
||||
@@ -79,7 +95,7 @@ diagnosis.
|
||||
| **Windows couldn't reach** / **Linux couldn't reach … to pair it** | The system could not find the companion when it came to pair. | As for a link that never opened: range, power, or another connection. |
|
||||
| **paired with …, but the device still refuses the connection** | Pairing succeeded, yet the companion still refuses. It is holding an old pairing for this computer. | Restart the companion, [forget the pairing](#forgetting-a-pairing), and try again. |
|
||||
| **was not paired. macOS asks for the pairing code in its own dialog** | macOS had not finished pairing. | Type the PIN into the macOS dialog when it appears. If none appears, check the terminal's Bluetooth permission (above). |
|
||||
| **connecting … took longer than** | The link, the pairing, or the service discovery stalled. | Move closer, restart the companion, and try again. |
|
||||
| **connecting … took longer than** / **connecting … timed out** | The link, the pairing, or the service discovery stalled. | Move closer, restart the companion, and try again. |
|
||||
| **connected …, but it didn't answer the identity query** | The link came up and the companion went quiet. | It may be busy with another app. Restart it and try again. |
|
||||
| **connected …, but it never answered as a MeshCore companion** | Something answered, but not as a companion. | It may be running repeater or room server firmware, which has no companion interface. |
|
||||
|
||||
@@ -114,10 +130,17 @@ cellular modem.
|
||||
|
||||
## TCP
|
||||
|
||||
**no response from a MeshCore companion at HOST:PORT** means nothing answered there. Check
|
||||
the host and the port (MeshTerm's default is `5000`), that the companion is powered on and
|
||||
reachable on your network, and that no other client is already connected to it. Like
|
||||
Bluetooth, a network companion serves one client at a time.
|
||||
Like Bluetooth, a network companion serves one client at a time. MeshTerm's default port
|
||||
is `5000`.
|
||||
|
||||
| The message starts with… | What happened | What to do |
|
||||
| --- | --- | --- |
|
||||
| **couldn't find a host named** | The name didn't lead to any address. | Check the spelling, or use the companion's IP address instead. |
|
||||
| **nothing is accepting connections on port** | The computer was reached, but nothing is listening on that port. | Check the port number, and that the companion, or the bridge in front of it, is running. |
|
||||
| **there's no route to** | Your computer can't reach that address at all. | Check the address, and that your computer is on the companion's network (or its VPN). |
|
||||
| **no answer from … on port** | Nothing answered in time. | Check that the companion is powered on and on your network. A firewall can also hold a connection without refusing it. |
|
||||
| **… closed the connection as it opened** | The companion hung up straight away. | Another client is probably connected to it. Disconnect that one first. |
|
||||
| **the connection to … opened, but nothing answered as a MeshCore companion** | Something is listening on the port, but it isn't a companion. | Check the port number. If it is right, the companion may be busy with another client. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -524,6 +524,11 @@ class AppContext:
|
||||
connection there had never been — and ``--port NOSUCHPORT`` is the most common way
|
||||
to reach this line.
|
||||
|
||||
A device that failed to open is not kept. It used to stay as :attr:`_device`, so
|
||||
:attr:`is_connected` said yes, the next :meth:`device` handed it back unopened, and
|
||||
every tool after a failed start failed with "not connected" instead of the reason.
|
||||
Dropped, the next caller tries the connection again and meets the real answer.
|
||||
|
||||
Args:
|
||||
what: The thing being opened, for the message (a port, an address, a host).
|
||||
|
||||
@@ -535,6 +540,11 @@ class AppContext:
|
||||
try:
|
||||
await self._device.connect()
|
||||
except Exception as exc: # noqa: BLE001 - reclassified, then re-raised
|
||||
failed, self._device = self._device, None
|
||||
try:
|
||||
await failed.disconnect() # whatever half of it did open
|
||||
except Exception: # noqa: BLE001 - best-effort; it never connected
|
||||
pass
|
||||
raise DeviceSelectionError(f"could not open {what}: {exc}") from exc
|
||||
|
||||
async def device(self) -> Device:
|
||||
|
||||
+165
-25
@@ -15,9 +15,11 @@ Two implementations are provided:
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import AsyncIterator, Callable, Iterable
|
||||
@@ -308,6 +310,18 @@ class DeviceAuthenticationError(DeviceCommandError):
|
||||
self.hint = hint
|
||||
|
||||
|
||||
class UnrecognisedConnectError(DeviceCommandError):
|
||||
"""A connect failed in a way MeshTerm has no name for.
|
||||
|
||||
Every failure MeshTerm recognises has a sentence of its own, naming what happened and
|
||||
what to do. This is the one it doesn't: rather than let a bare library error through —
|
||||
which a dialog could only call "didn't answer", and which used to leave nothing in the
|
||||
log — it says what was being opened, at which step, and the error's own words, and the
|
||||
full traceback is logged beside it (see :func:`_unrecognised`), so a dialog can say where
|
||||
to find that. Raised in place of the original, which stays its ``__cause__``.
|
||||
"""
|
||||
|
||||
|
||||
class FloodScopeError(DeviceCommandError):
|
||||
"""The companion could not send under the scope a channel send asked for — so it didn't.
|
||||
|
||||
@@ -763,6 +777,100 @@ def _serial_open_message(port: str, exc: BaseException) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
#: ``errno`` values a TCP connect fails with when no route leads to the host: POSIX's own
|
||||
#: constants, and Winsock's (WSAENETUNREACH, WSAEHOSTUNREACH), which Windows reports as-is.
|
||||
_ERRNO_UNREACHABLE = {errno.ENETUNREACH, errno.EHOSTUNREACH, 10051, 10065}
|
||||
|
||||
|
||||
def _tcp_open_message(host: str, port: int | None, exc: BaseException) -> str | None:
|
||||
"""Name why a TCP connection to a companion wouldn't open, or ``None`` if unrecognised.
|
||||
|
||||
Each of these used to be reported as "no response from a MeshCore companion", which
|
||||
sent the reader to the companion when the fault was the address, the port, or the
|
||||
network between them — and each has a different fix.
|
||||
|
||||
Args:
|
||||
host: The host, as the message names it.
|
||||
port: The TCP port.
|
||||
exc: What opening the socket raised.
|
||||
|
||||
Returns:
|
||||
The actionable sentence, or ``None`` to report it as unrecognised.
|
||||
"""
|
||||
if isinstance(exc, socket.gaierror):
|
||||
return f"couldn't find a host named {host} — check the spelling, or use its IP address."
|
||||
if isinstance(exc, ConnectionRefusedError):
|
||||
return (
|
||||
f"nothing is accepting connections on port {port} at {host} — check the port "
|
||||
"number, and that the companion, or the bridge in front of it, is running."
|
||||
)
|
||||
if isinstance(exc, (ConnectionResetError, ConnectionAbortedError)):
|
||||
return (
|
||||
f"{host}:{port} closed the connection as it opened — a network companion serves "
|
||||
"one client at a time, so another may already be connected to it."
|
||||
)
|
||||
if isinstance(exc, OSError) and exc.errno in _ERRNO_UNREACHABLE:
|
||||
return (
|
||||
f"there's no route to {host} from this computer — check the address, and that "
|
||||
"this computer is on the companion's network (or its VPN)."
|
||||
)
|
||||
if isinstance(exc, (TimeoutError, asyncio.TimeoutError)):
|
||||
return (
|
||||
f"no answer from {host} on port {port} — check that it is powered on and on this "
|
||||
"computer's network. A firewall can also hold a connection without refusing it."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _ble_stalled_message(where: str, seconds: float | None = None) -> str:
|
||||
"""Say that a Bluetooth connect ran out of time, and what usually stalls one.
|
||||
|
||||
Args:
|
||||
where: The device, as the message names it.
|
||||
seconds: The window it ran out of, when the caller set one.
|
||||
|
||||
Returns:
|
||||
The actionable sentence.
|
||||
"""
|
||||
took = f"took longer than {seconds:.0f}s" if seconds else "timed out"
|
||||
return (
|
||||
f"connecting to {where} over Bluetooth {took} — the link, pairing, or service "
|
||||
"discovery stalled. Move closer, restart the device, and try again."
|
||||
)
|
||||
|
||||
|
||||
def _error_words(exc: BaseException) -> str:
|
||||
"""The error's own message, or its type's name where it has none (a bare ``TimeoutError``)."""
|
||||
return str(exc).strip() or type(exc).__name__
|
||||
|
||||
|
||||
#: The unrecognised failures whose traceback is already in the log. The reconnect dialog
|
||||
#: retries every couple of seconds against whatever is refusing it, and one traceback says
|
||||
#: everything the next three hundred would.
|
||||
_TRACED: set[str] = set()
|
||||
|
||||
|
||||
def _unrecognised(what: str, exc: BaseException) -> UnrecognisedConnectError:
|
||||
"""Build the error for a connect failure MeshTerm has no sentence for, and log it whole.
|
||||
|
||||
Logged at warning, with the traceback the first time it is met, because that is what
|
||||
the dialog then points at: the sentence carries the error's own words, and the log
|
||||
carries where they came from.
|
||||
|
||||
Args:
|
||||
what: What was being done, as the start of the sentence ("couldn't open COM5").
|
||||
exc: The unrecognised error.
|
||||
|
||||
Returns:
|
||||
The error to raise, from ``exc``.
|
||||
"""
|
||||
words = _error_words(exc)
|
||||
message = f"{what}: {words}"
|
||||
_log.warning("%s", message, exc_info=exc if message not in _TRACED else None)
|
||||
_TRACED.add(message)
|
||||
return UnrecognisedConnectError(message)
|
||||
|
||||
|
||||
class _ConnectingClients(list):
|
||||
"""Every bleak client a connecting ``BLEConnection`` reported a disconnect for.
|
||||
|
||||
@@ -1749,30 +1857,48 @@ class MeshCoreDevice(Device):
|
||||
"--mock for the simulator."
|
||||
) from exc
|
||||
|
||||
# Every transport leaves here with a sentence: a failure it recognises is named with
|
||||
# its remedy, and one it doesn't is still said in words, as what was being opened and
|
||||
# the error's own message, with the traceback logged (see _unrecognised). A bare
|
||||
# library error used to escape instead, and a dialog could only call it "didn't
|
||||
# answer". The original stays the cause, so is_connection_lost still sees it.
|
||||
if self._transport == "ble":
|
||||
self._mc = await self._create_ble(MeshCore)
|
||||
where = self._address or "the selected Bluetooth device"
|
||||
try:
|
||||
self._mc = await self._create_ble(MeshCore)
|
||||
except DeviceCommandError:
|
||||
raise
|
||||
except (TimeoutError, asyncio.TimeoutError) as exc:
|
||||
_log.warning("BLE connect to %s timed out", where)
|
||||
raise DeviceCommandError(_ble_stalled_message(where)) from exc
|
||||
except Exception as exc: # noqa: BLE001 - said in words, logged whole
|
||||
raise _unrecognised(f"couldn't connect to {where} over Bluetooth", exc) from exc
|
||||
elif self._transport == "tcp":
|
||||
try:
|
||||
self._mc = await MeshCore.create_tcp(
|
||||
self._host, self._tcp_port, default_timeout=self._connect_timeout
|
||||
)
|
||||
except (OSError, asyncio.TimeoutError) as exc:
|
||||
# The socket couldn't be opened — host unreachable, connection refused, name
|
||||
# not resolved, or the connect timed out. That's not a MeshCore-level failure,
|
||||
# so translate it into a clean, actionable message (naming the host:port and
|
||||
# the things to check) rather than letting a raw socket traceback escape.
|
||||
raise DeviceCommandError(self._no_response_message()) from exc
|
||||
except Exception as exc: # noqa: BLE001 - named when recognised, else said in words
|
||||
# The socket couldn't be opened, which is not a MeshCore-level failure: the
|
||||
# name didn't resolve, nothing listens on the port, no route reaches the host,
|
||||
# or the connect timed out — four faults with four different fixes.
|
||||
message = _tcp_open_message(self._host or "the host", self._tcp_port, exc)
|
||||
if message is None:
|
||||
raise _unrecognised(f"couldn't connect to {self.endpoint}", exc) from exc
|
||||
_log.warning("couldn't connect to %s: %s", self.endpoint, exc)
|
||||
raise DeviceCommandError(message) from exc
|
||||
else:
|
||||
try:
|
||||
self._mc = await MeshCore.create_serial(
|
||||
self._port, self._baudrate, default_timeout=self._connect_timeout
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - named when recognised, else re-raised
|
||||
except Exception as exc: # noqa: BLE001 - named when recognised, else said in words
|
||||
# The port refused to open at all — which says nothing about whether a
|
||||
# companion is on it, and used to be reported as if it had said exactly that.
|
||||
message = _serial_open_message(self._port or "the serial port", exc)
|
||||
port = self._port or "the serial port"
|
||||
message = _serial_open_message(port, exc)
|
||||
if message is None:
|
||||
raise
|
||||
raise _unrecognised(f"couldn't connect to the device on {port}", exc) from exc
|
||||
_log.warning("couldn't open %s: %s", self._port, exc)
|
||||
raise DeviceCommandError(message) from exc
|
||||
# ``create_*`` returns ``None`` (after cleaning up its own connection) when the node
|
||||
@@ -2562,11 +2688,13 @@ class MeshCoreDevice(Device):
|
||||
"with another app."
|
||||
)
|
||||
if self._transport == "tcp":
|
||||
# The socket opened (one that didn't has its own message), so the address and
|
||||
# the network are not the question here — what is listening on the port is.
|
||||
where = self.endpoint or "the selected network device"
|
||||
return (
|
||||
f"no response from a MeshCore companion at {where}; check the host and port, "
|
||||
"and that the device is powered on, reachable on the network, and not already "
|
||||
"connected to another client."
|
||||
f"the connection to {where} opened, but nothing answered as a MeshCore "
|
||||
"companion — the port may belong to another service, or the companion may "
|
||||
"be busy with another client."
|
||||
)
|
||||
# ModemManager opens without locking, so the port opens fine and the handshake is
|
||||
# what it spoils — which makes this, not the open error, where it has to be named.
|
||||
@@ -5231,7 +5359,8 @@ async def _probe(device: MeshCoreDevice, timeout: float) -> tuple[MeshCoreDevice
|
||||
DeviceCommandError: On an *actionable* failure the user can fix — e.g. a Bluetooth
|
||||
companion that needs a pairing PIN. This is deliberately distinct from ``None``
|
||||
(an unremarkable "not a companion" miss) so the caller can show the real remedy
|
||||
instead of a generic "didn't answer".
|
||||
instead of a generic "didn't answer". A failure with no name of its own comes
|
||||
as :class:`UnrecognisedConnectError`, in the error's own words.
|
||||
"""
|
||||
# ``timeout`` is the handshake window handed to the client, so a non-MeshCore endpoint is
|
||||
# rejected in ~``timeout`` seconds and the client cleans up its own connection. The outer
|
||||
@@ -5245,18 +5374,22 @@ async def _probe(device: MeshCoreDevice, timeout: float) -> tuple[MeshCoreDevice
|
||||
info = await asyncio.wait_for(device.get_self_info(), timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
await _safe_disconnect(device)
|
||||
if getattr(device, "transport", None) != "ble":
|
||||
transport = getattr(device, "transport", None)
|
||||
if transport == "tcp" and stage == "connect":
|
||||
# The OS gives a silent host twenty seconds or more before it gives up, so it is
|
||||
# this window that runs out first, and it means the same thing the OS's would.
|
||||
where = getattr(device, "_host", None) or "the host"
|
||||
_log.warning("TCP probe of %s timed out connecting", device.endpoint)
|
||||
message = _tcp_open_message(where, getattr(device, "_tcp_port", None), exc)
|
||||
raise DeviceCommandError(message or str(exc)) from exc
|
||||
if transport != "ble":
|
||||
return None
|
||||
# A Bluetooth connect has more stages than a serial one (link, pairing, service
|
||||
# discovery, the identity reply), so saying which one ran out of time is what
|
||||
# tells a device out of range apart from one that connected and then went quiet.
|
||||
where = device.endpoint or "the selected Bluetooth device"
|
||||
if stage == "connect":
|
||||
message = (
|
||||
f"connecting to {where} over Bluetooth took longer than {timeout + 4.0:.0f}s — "
|
||||
"the link, pairing, or service discovery stalled. Move closer, restart the "
|
||||
"device, and try again."
|
||||
)
|
||||
message = _ble_stalled_message(where, timeout + 4.0)
|
||||
else:
|
||||
message = (
|
||||
f"connected to {where} over Bluetooth, but it didn't answer the identity query "
|
||||
@@ -5270,12 +5403,19 @@ async def _probe(device: MeshCoreDevice, timeout: float) -> tuple[MeshCoreDevice
|
||||
# through so the picker surfaces the remedy rather than hiding it behind "didn't answer".
|
||||
await _safe_disconnect(device)
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - any other failure just means "not confirmed"
|
||||
# Still "not confirmed" to the picker, but said in the log: this used to be the one
|
||||
# failure that left no trace, so a report from another machine had nothing to show.
|
||||
_log.warning("probe of %s failed: %r", getattr(device, "endpoint", None), exc)
|
||||
except Exception as exc: # noqa: BLE001 - said in words, logged whole
|
||||
# A failure nothing above recognised. It used to come back as "not confirmed", and
|
||||
# the picker called the device one that "didn't answer as a MeshCore device" — a
|
||||
# claim the probe never had grounds for, with the one clue left in the log. Now it
|
||||
# is said in the error's own words, and the log holds the traceback.
|
||||
await _safe_disconnect(device)
|
||||
return None
|
||||
where = getattr(device, "endpoint", None) or "the device"
|
||||
what = (
|
||||
f"couldn't connect to {where}"
|
||||
if stage == "connect"
|
||||
else f"connected to {where}, but reading its identity failed"
|
||||
)
|
||||
raise _unrecognised(what, exc) from exc
|
||||
if not info:
|
||||
await _safe_disconnect(device)
|
||||
return None
|
||||
|
||||
@@ -76,6 +76,26 @@ def log_path(log_dir: Path) -> Path:
|
||||
return log_dir / LOG_FILENAME
|
||||
|
||||
|
||||
def log_file_for(level: int) -> Path | None:
|
||||
"""Return the file a record at ``level`` is written to, or ``None`` if none takes it.
|
||||
|
||||
For a message that wants to say "the full error is in …": it may say so only when the
|
||||
record really went there, and the ``log_level`` preference decides that — a reader who
|
||||
turned the file down to ``ERROR`` has no warnings in it to be sent looking for.
|
||||
|
||||
Args:
|
||||
level: The level the record was logged at.
|
||||
|
||||
Returns:
|
||||
The log file's path, or ``None`` when logging isn't configured or the file's level
|
||||
is above ``level``.
|
||||
"""
|
||||
for handler in logging.getLogger(_LOGGER_NAME).handlers:
|
||||
if isinstance(handler, logging.FileHandler) and handler.level <= level:
|
||||
return Path(handler.baseFilename)
|
||||
return None
|
||||
|
||||
|
||||
def configure_logging(
|
||||
console: Console,
|
||||
log_dir: Path,
|
||||
|
||||
@@ -29,6 +29,8 @@ is connected to again.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable, Mapping
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -36,7 +38,11 @@ from rich.cells import cell_len
|
||||
from rich.text import Text
|
||||
|
||||
from ..core.config import DeviceProfile
|
||||
from ..core.connection import DeviceAuthenticationError, DeviceCommandError
|
||||
from ..core.connection import (
|
||||
DeviceAuthenticationError,
|
||||
DeviceCommandError,
|
||||
UnrecognisedConnectError,
|
||||
)
|
||||
from ..core.device_store import DeviceStore, RememberedDevice
|
||||
from ..core.discovery import (
|
||||
DEFAULT_TCP_PORT,
|
||||
@@ -48,6 +54,7 @@ from ..core.discovery import (
|
||||
tcp_device,
|
||||
)
|
||||
from ..core.spiradio import spi_radios
|
||||
from ..persistence.logging import log_file_for
|
||||
from ..platforms import get_platform
|
||||
from .logo import load_logo
|
||||
from .menus import Lane, align_icons, column_header, fit_cells
|
||||
@@ -223,6 +230,50 @@ def _model_from(info: dict) -> str:
|
||||
return str(info.get("model") or "")
|
||||
|
||||
|
||||
#: A connect failure's sentence starts lowercase, written for the command line's
|
||||
#: ``meshterm: …``. A dialog shows it as a sentence, so a plain leading word is capitalised —
|
||||
#: and only a plain word: a port, an address, or a host name opening it keeps its spelling.
|
||||
_LEADING_WORD = re.compile(r"^[a-z][a-z']*(?=\s)")
|
||||
|
||||
|
||||
def connect_failure_text(exc: BaseException) -> Text:
|
||||
"""The reason a connection failed, as a dialog shows it.
|
||||
|
||||
The sentence is the connection's own: the first
|
||||
:class:`~meshterm.core.connection.DeviceCommandError` in the chain, under whatever wraps
|
||||
it (the context's ``could not open …`` only repeats the endpoint the sentence names). It
|
||||
is plain text in the ``warn`` tone, so brackets in a library's words are shown rather
|
||||
than read as markup. Where MeshTerm had no name for the failure
|
||||
(:class:`~meshterm.core.connection.UnrecognisedConnectError`), a muted line follows
|
||||
saying where the log is, since the log holds the traceback; a named failure gets none,
|
||||
because there the dialog already says everything the log does.
|
||||
|
||||
Args:
|
||||
exc: What the connection attempt raised.
|
||||
|
||||
Returns:
|
||||
The dialog's lines.
|
||||
"""
|
||||
named: DeviceCommandError | None = None
|
||||
seen: set[int] = set()
|
||||
current: BaseException | None = exc
|
||||
while current is not None and id(current) not in seen:
|
||||
seen.add(id(current))
|
||||
if isinstance(current, DeviceCommandError):
|
||||
named = current
|
||||
break
|
||||
current = current.__cause__ or current.__context__
|
||||
sentence = str(named or exc).strip() or type(exc).__name__
|
||||
sentence = _LEADING_WORD.sub(lambda word: word.group().capitalize(), sentence, count=1)
|
||||
text = Text()
|
||||
text.append(sentence, style="warn") # a span, not the base: what callers add stays plain
|
||||
if isinstance(named, UnrecognisedConnectError):
|
||||
log = log_file_for(logging.WARNING)
|
||||
if log is not None:
|
||||
text.append(f"\nThe full error is in {log}", style="muted")
|
||||
return text
|
||||
|
||||
|
||||
async def _smoke_test(
|
||||
ui: Ui,
|
||||
chosen: DiscoveredDevice,
|
||||
@@ -277,10 +328,8 @@ async def _smoke_test(
|
||||
pin = entered
|
||||
continue
|
||||
except DeviceCommandError as exc:
|
||||
# A different actionable failure (not a PIN): show its remedy verbatim, then back to
|
||||
# the list. Plain styled text so the message's own punctuation isn't parsed as markup.
|
||||
notice = Text()
|
||||
notice.append(str(exc), style="warn")
|
||||
# A different actionable failure (not a PIN): show its remedy, then back to the list.
|
||||
notice = connect_failure_text(exc)
|
||||
notice.append("\nChoose another device.")
|
||||
await ui.notify_startup(notice, title="Can't connect yet", banner=load_logo())
|
||||
return None
|
||||
|
||||
+96
-19
@@ -21,6 +21,7 @@ from typing import Any
|
||||
|
||||
from rich.cells import cell_len
|
||||
from rich.logging import RichHandler
|
||||
from rich.markup import escape
|
||||
from rich.text import Text
|
||||
|
||||
from .. import __version__
|
||||
@@ -85,6 +86,11 @@ _BLE_RESCAN_PAUSE_S = 1.0
|
||||
#: otherwise be reopened against the old session, which dies under it a moment later.
|
||||
_REBOOT_SETTLE_S = 1.5
|
||||
|
||||
#: How many reconnect attempts in a row must fail before the dialog says why. The device is
|
||||
#: there by then (each attempt waits for its port or its advertisement), but a board can
|
||||
#: refuse once while it boots, and that is not worth announcing.
|
||||
_REASON_AFTER_FAILURES = 2
|
||||
|
||||
|
||||
def _arm_exit_watchdog(seconds: float = _EXIT_WATCHDOG_S) -> None:
|
||||
"""Guarantee the process terminates even if the exit path wedges.
|
||||
@@ -908,7 +914,9 @@ async def _startup(ctx: AppContext) -> bool:
|
||||
# the radio — a slow, silent step that would otherwise leave the screen blank for a beat.
|
||||
# Float the skeleton card across that gap on any real link (see _busy_over_link).
|
||||
async with _busy_over_link(ctx, title="Starting up"):
|
||||
await _resume_monitor(ctx)
|
||||
failure = await _resume_monitor(ctx)
|
||||
if failure is not None:
|
||||
await _report_startup_failure(ctx, failure)
|
||||
# A forgetful device (a firmware-less radio bridge) may have lost settings you saved through
|
||||
# MeshTerm; offer to reconcile them on the splash before the menu paints. Quiet unless a
|
||||
# connected device actually drifts from what's remembered (see settings_offer).
|
||||
@@ -918,7 +926,26 @@ async def _startup(ctx: AppContext) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
async def _resume_monitor(ctx: AppContext) -> None:
|
||||
async def _report_startup_failure(ctx: AppContext, failure: Exception) -> None:
|
||||
"""Say why the radio named on the command line didn't open, before the menu paints.
|
||||
|
||||
With ``--port``, ``--ble``, ``--tcp`` or ``--profile`` there is no device picker to say
|
||||
it, and this used to be said nowhere: the menu opened on "no device", and the reason
|
||||
came out only when a tool was opened, worded as that tool's failure.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
failure: What starting the radio raised.
|
||||
"""
|
||||
from .device_picker import connect_failure_text
|
||||
from .logo import load_logo
|
||||
|
||||
notice = connect_failure_text(failure)
|
||||
notice.append("\nThe menu opens without a radio; a tool that needs one tries again.")
|
||||
await ctx.ui.notify_startup(notice, title="Can't connect yet", banner=load_logo())
|
||||
|
||||
|
||||
async def _resume_monitor(ctx: AppContext) -> Exception | None:
|
||||
"""Start always-on background listening and history recording.
|
||||
|
||||
Recording has no switch: the monitor registers its hub subscription up front — a
|
||||
@@ -926,12 +953,14 @@ async def _resume_monitor(ctx: AppContext) -> None:
|
||||
from the moment the radio opens. The hub itself (a MeshCore client must always be
|
||||
listening) is started eagerly here unless the ``connect_on_start`` setting defers
|
||||
it, in which case it opens lazily when a tool first needs the radio and recording
|
||||
picks up then. A failure to start the hub (typically no companion device selected)
|
||||
is non-fatal; the header reflects the resulting state, so nothing needs to be
|
||||
printed here.
|
||||
picks up then. A failure to start the hub is non-fatal — the menu opens without a
|
||||
radio — but it is returned, for the caller to say why once the startup card is down.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
|
||||
Returns:
|
||||
What starting the hub raised, or ``None`` when it started or was deferred.
|
||||
"""
|
||||
await ctx.monitor.start()
|
||||
# The advert scheduler is safe to run from launch regardless of the connect policy:
|
||||
@@ -951,18 +980,23 @@ async def _resume_monitor(ctx: AppContext) -> None:
|
||||
# and skips quietly without a device, so it too is safe to run from launch.
|
||||
await ctx.battery.start()
|
||||
if not ctx.settings.connect_on_start:
|
||||
return
|
||||
return None
|
||||
failure: Exception | None = None
|
||||
try:
|
||||
await ctx.events.start()
|
||||
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
|
||||
pass
|
||||
except Exception as exc: # noqa: BLE001 - reported by the caller, never crashes the menu
|
||||
get_logger().warning("couldn't start the radio: %s", exc)
|
||||
failure = exc
|
||||
# Record inbound messages from launch so the inbox and unread badge stay current
|
||||
# even before the chat screen is opened. Deferred (like the hub) when connect on
|
||||
# start is off; the chat screen starts it lazily then.
|
||||
try:
|
||||
await ctx.chat.start()
|
||||
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
|
||||
pass
|
||||
# start is off; the chat screen starts it lazily then. Skipped when the hub couldn't
|
||||
# open the radio: it would only try the same connection again and wait out the same
|
||||
# failure a second time.
|
||||
if failure is None:
|
||||
try:
|
||||
await ctx.chat.start()
|
||||
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
|
||||
pass
|
||||
# Warm the map tile source's metadata behind the menu too: the first ``.max_zoom`` touch
|
||||
# resolves the TileJSON over the network, and the Map / Node-detail location preview would
|
||||
# otherwise pay that round-trip on the navigation path (a stall on opening a located node's
|
||||
@@ -976,6 +1010,7 @@ async def _resume_monitor(ctx: AppContext) -> None:
|
||||
# connect (connect_on_start off) returns above and warms lazily on first use instead.
|
||||
if ctx.is_connected:
|
||||
ctx.devstate.prewarm()
|
||||
return failure
|
||||
|
||||
|
||||
def _warm_basemap(ctx: AppContext) -> None:
|
||||
@@ -1042,7 +1077,9 @@ async def _run_selection(ctx: AppContext, name: str) -> None:
|
||||
name: The selected tool's name.
|
||||
"""
|
||||
from ..core.connection import is_connection_lost
|
||||
from ..core.selection import DeviceSelectionError
|
||||
from ..tools import get_tool
|
||||
from .device_picker import connect_failure_text
|
||||
|
||||
tool = get_tool(name)
|
||||
if tool is None: # pragma: no cover - registry and menu are always in sync
|
||||
@@ -1063,7 +1100,11 @@ async def _run_selection(ctx: AppContext, name: str) -> None:
|
||||
return
|
||||
result = await tool.execute(ctx, params)
|
||||
except Exception as exc: # noqa: BLE001 - surface errors without crashing the menu
|
||||
if is_connection_lost(exc):
|
||||
# A radio that never opened can't have been lost, however its error reads — and the
|
||||
# watcher, with nothing connected to watch, would never prompt for it. That case is
|
||||
# said here, in the connection's own sentence, rather than dropped.
|
||||
never_opened = isinstance(exc, DeviceSelectionError)
|
||||
if is_connection_lost(exc) and not never_opened:
|
||||
ctx.ui.discard() # drop the half-built output; the watcher will prompt to reconnect
|
||||
return
|
||||
# A tool that failed is a *caution*, not a loss: the run is over, nothing it was
|
||||
@@ -1071,7 +1112,14 @@ async def _run_selection(ctx: AppContext, name: str) -> None:
|
||||
# takes the amber tone rather than the reserved red — the same tier a danger dialog
|
||||
# uses — and the message dialog reads that tone off the note to frame itself
|
||||
# (see :func:`~meshterm.ui.tui.session._message_border`).
|
||||
ctx.ui.note(f"[warn]⚠ {title} failed:[/warn] {exc}")
|
||||
if never_opened:
|
||||
reason = Text("⚠ ", style="warn")
|
||||
reason.append_text(connect_failure_text(exc))
|
||||
ctx.ui.show(reason)
|
||||
else:
|
||||
# Escaped: an error carries a library's own words, and `[org.bluez.Error.Failed]`
|
||||
# read as markup is a tag that silently swallows the most telling part of it.
|
||||
ctx.ui.note(f"[warn]⚠ {title} failed:[/warn] {escape(str(exc))}")
|
||||
await ctx.ui.present(title=title)
|
||||
return
|
||||
|
||||
@@ -1255,9 +1303,10 @@ async def _auto_reconnect(
|
||||
which fails fast against an absent endpoint.
|
||||
|
||||
A failed attempt (the device is back but the board isn't ready yet, or it dropped again)
|
||||
just loops and retries. On the first success the dialog's future is resolved with
|
||||
``"reconnected"``, dismissing the popup. Runs until it succeeds or the task is cancelled
|
||||
(the user quit).
|
||||
loops and retries; once :data:`_REASON_AFTER_FAILURES` have failed in a row, the dialog
|
||||
says why under its spinner, in the connection's own sentence. On the first success the
|
||||
dialog's future is resolved with ``"reconnected"``, dismissing the popup. Runs until it
|
||||
succeeds or the task is cancelled (the user quit).
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
@@ -1269,6 +1318,20 @@ async def _auto_reconnect(
|
||||
"""
|
||||
from ..core.connection import serial_port_present
|
||||
from ..core.discovery import find_ble_device
|
||||
from .device_picker import connect_failure_text
|
||||
|
||||
failures = 0
|
||||
last_reason = ""
|
||||
waiting_message = dialog.message
|
||||
|
||||
def gone_again() -> None:
|
||||
# The device went away again, so what refused it last is no longer the question:
|
||||
# back to waiting, until it returns and refuses (or doesn't) afresh.
|
||||
nonlocal failures
|
||||
if failures:
|
||||
failures = 0
|
||||
dialog.set_message(waiting_message)
|
||||
dialog.set_detail(None)
|
||||
|
||||
# Put the dead link down before going looking for the device. A Bluetooth companion we are
|
||||
# still nominally connected to does not advertise, so the scan below would wait out a
|
||||
@@ -1285,6 +1348,7 @@ async def _auto_reconnect(
|
||||
# Off the loop: the probe enumerates ports, which blocks long enough to stall
|
||||
# the very spinner this dialog is showing while it waits.
|
||||
if port is not None and not await asyncio.to_thread(serial_port_present, port):
|
||||
gone_again()
|
||||
await asyncio.sleep(_LIVENESS_POLL_S)
|
||||
continue
|
||||
elif transport == "ble":
|
||||
@@ -1295,11 +1359,24 @@ async def _auto_reconnect(
|
||||
# The scan window is itself the wait — it just spent several seconds
|
||||
# listening — so only a brief pause is needed to keep a scan that fails
|
||||
# instantly (Bluetooth switched off mid-session) from spinning.
|
||||
gone_again()
|
||||
await asyncio.sleep(_BLE_RESCAN_PAUSE_S)
|
||||
continue
|
||||
try:
|
||||
await ctx.reconnect(ble_device=ble_device)
|
||||
except Exception: # noqa: BLE001 - not reachable yet; keep the popup up and retry
|
||||
except Exception as exc: # noqa: BLE001 - not reachable yet; keep the popup up and retry
|
||||
# A board can refuse once while it boots, so the first failure is only retried.
|
||||
# One that persists is said under the spinner — another program holding the
|
||||
# port, a pairing gone stale — or the reader waits on it forever. Logged once
|
||||
# per reason, not once per attempt.
|
||||
failures += 1
|
||||
reason = connect_failure_text(exc)
|
||||
if reason.plain != last_reason:
|
||||
last_reason = reason.plain
|
||||
get_logger().warning("reconnect failed: %s", last_reason)
|
||||
if failures >= _REASON_AFTER_FAILURES:
|
||||
dialog.set_message("Still trying to reconnect…")
|
||||
dialog.set_detail(reason)
|
||||
await asyncio.sleep(_LIVENESS_POLL_S)
|
||||
continue
|
||||
dialog.resolve("reconnected")
|
||||
|
||||
@@ -794,8 +794,16 @@ class ReconnectDialog(_KeylessDialog):
|
||||
cyan) — the same fill as the quit-confirmation dialog — so every popup dialog reads alike.
|
||||
The animation is the reusable :class:`~meshterm.ui.tui.spinner.Spinner`, advanced by
|
||||
:meth:`tick` from the session's animation timer.
|
||||
|
||||
Once the device is back but the reconnect keeps failing, the reason sits under the
|
||||
spinner line (:meth:`set_detail`) — a port another program took while we waited, a
|
||||
pairing that went stale — since a spinner alone would wait on it forever.
|
||||
"""
|
||||
|
||||
#: The widest a reason runs before it wraps: a sentence or two at a reading measure,
|
||||
#: rather than a box stretched to the terminal's edges to hold it on one line.
|
||||
DETAIL_MEASURE = 56
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
@@ -821,34 +829,57 @@ class ReconnectDialog(_KeylessDialog):
|
||||
self._message = message
|
||||
self._prompt_style = prompt_style
|
||||
self._spinner = Spinner()
|
||||
self._detail: Text | None = None
|
||||
|
||||
@property
|
||||
def dialog_width(self) -> int:
|
||||
"""Natural outer width so the frame sizes the box to its content (see ButtonDialog)."""
|
||||
detail = 0
|
||||
if self._detail is not None:
|
||||
widest = max(cell_len(line.plain) for line in self._detail.split("\n"))
|
||||
detail = min(widest, self.DETAIL_MEASURE)
|
||||
inner = max(
|
||||
cell_len(self._message),
|
||||
cell_len(self.title),
|
||||
cell_len(self.footer_hint),
|
||||
len(" Abort "),
|
||||
detail,
|
||||
)
|
||||
return inner + 12 # panel padding + border, plus horizontal breathing room
|
||||
|
||||
@property
|
||||
def message(self) -> str:
|
||||
"""The line shown beside the spinner."""
|
||||
return self._message
|
||||
|
||||
def set_message(self, message: str) -> None:
|
||||
"""Replace the line shown beside the spinner (e.g. to note a stalled retry)."""
|
||||
self._message = message
|
||||
|
||||
def set_detail(self, detail: Text | None) -> None:
|
||||
"""Show why the reconnect keeps failing, under the spinner line; ``None`` clears it."""
|
||||
self._detail = detail
|
||||
|
||||
def tick(self) -> None:
|
||||
"""Advance the spinner to its next frame (driven by the session's animation timer)."""
|
||||
self._spinner.tick()
|
||||
|
||||
def render_body(self, width: int) -> list[str]:
|
||||
"""Render the spinner and message centered above a single Abort button."""
|
||||
"""Render the spinner and message, then any reason, centered above an Abort button."""
|
||||
line = self._spinner.text()
|
||||
line.append(" ")
|
||||
line.append(self._message, style=self._prompt_style)
|
||||
row = Text()
|
||||
row.append(" Abort ", style="selected")
|
||||
return render_lines(Group(_center(line, width), Text(""), _center(row, width)), width)
|
||||
parts: list[Text] = [_center(line, width)]
|
||||
if self._detail is not None:
|
||||
# Wrapped and centred line by line; it holds no chip, so Rich's own centring
|
||||
# is safe here (see _center for the one case it isn't).
|
||||
detail = self._detail.copy()
|
||||
detail.justify = "center"
|
||||
parts += [Text(""), detail]
|
||||
parts += [Text(""), _center(row, width)]
|
||||
return render_lines(Group(*parts), width)
|
||||
|
||||
def handle(self, action: str, data: str = "") -> None:
|
||||
"""Abort only on Enter; ignore everything else, Esc included (the app auto-dismisses)."""
|
||||
|
||||
@@ -10,7 +10,9 @@ against the :class:`MockDevice` simulator; no hardware required.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import io
|
||||
import socket
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -699,6 +701,139 @@ async def test_serial_connect_raises_the_named_failure(monkeypatch) -> None:
|
||||
assert isinstance(excinfo.value.__cause__, SerialException)
|
||||
|
||||
|
||||
def _fake_meshcore(monkeypatch, **factories) -> None: # noqa: ANN003
|
||||
"""Stand a ``meshcore`` module in whose ``create_*`` factories are the ones given."""
|
||||
import types
|
||||
|
||||
module = types.ModuleType("meshcore")
|
||||
module.MeshCore = type("MeshCore", (), {k: staticmethod(v) for k, v in factories.items()})
|
||||
monkeypatch.setitem(sys.modules, "meshcore", module)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exc", "expected"),
|
||||
[
|
||||
(socket.gaierror(11001, "getaddrinfo failed"), "couldn't find a host named meshbox"),
|
||||
(ConnectionRefusedError(111, "Connection refused"), "nothing is accepting connections"),
|
||||
(ConnectionResetError(104, "Connection reset by peer"), "one client at a time"),
|
||||
(OSError(errno.EHOSTUNREACH, "No route to host"), "no route to meshbox"),
|
||||
(OSError(10065, "A socket operation was attempted to an unreachable host"), "no route"),
|
||||
(TimeoutError(110, "Connection timed out"), "no answer from meshbox on port 5000"),
|
||||
(asyncio.TimeoutError(), "no answer from meshbox"),
|
||||
],
|
||||
)
|
||||
def test_tcp_open_failures_are_named(exc: BaseException, expected: str) -> None:
|
||||
"""Each way a socket refuses has its own sentence, not "no response from a companion"."""
|
||||
message = connection._tcp_open_message("meshbox", 5000, exc)
|
||||
assert message is not None and expected in message
|
||||
|
||||
|
||||
def test_an_unrecognised_tcp_failure_is_left_to_the_caller() -> None:
|
||||
"""A failure that isn't one of the socket's own is not given a name it hasn't earned."""
|
||||
assert connection._tcp_open_message("meshbox", 5000, ValueError("odd")) is None
|
||||
|
||||
|
||||
async def test_tcp_connect_raises_the_named_failure(monkeypatch) -> None:
|
||||
"""``connect`` says a refused port is a refused port, keeping the socket error as cause."""
|
||||
|
||||
async def create_tcp(*_args, **_kwargs):
|
||||
raise ConnectionRefusedError(111, "Connection refused")
|
||||
|
||||
_fake_meshcore(monkeypatch, create_tcp=create_tcp)
|
||||
dev = connection.MeshCoreDevice(transport="tcp", host="10.0.0.9", tcp_port=5000)
|
||||
with pytest.raises(DeviceCommandError) as excinfo:
|
||||
await dev.connect()
|
||||
assert "port 5000 at 10.0.0.9" in str(excinfo.value)
|
||||
assert isinstance(excinfo.value.__cause__, ConnectionRefusedError)
|
||||
|
||||
|
||||
async def test_a_tcp_companion_that_never_answers_is_told_from_one_never_reached(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""A socket that opened onto silence names the listener, not the address or the network."""
|
||||
|
||||
async def create_tcp(*_args, **_kwargs):
|
||||
return None # meshcore's answer when the handshake goes unanswered
|
||||
|
||||
_fake_meshcore(monkeypatch, create_tcp=create_tcp)
|
||||
dev = connection.MeshCoreDevice(transport="tcp", host="10.0.0.9", tcp_port=5000)
|
||||
with pytest.raises(DeviceCommandError) as excinfo:
|
||||
await dev.connect()
|
||||
assert "opened, but nothing answered" in str(excinfo.value)
|
||||
|
||||
|
||||
async def test_an_unrecognised_connect_failure_is_said_in_its_own_words(
|
||||
monkeypatch, caplog
|
||||
) -> None:
|
||||
"""A failure with no name is still a sentence, and its traceback is logged — once."""
|
||||
monkeypatch.setattr(connection, "_TRACED", set())
|
||||
|
||||
async def create_serial(*_args, **_kwargs):
|
||||
raise ValueError("unsupported baud rate")
|
||||
|
||||
_fake_meshcore(monkeypatch, create_serial=create_serial)
|
||||
dev = connection.MeshCoreDevice(port="/dev/ttyACM0")
|
||||
caplog.set_level("WARNING", logger="meshterm.core.connection")
|
||||
for _ in range(2): # a reconnect retrying against the same fault
|
||||
with pytest.raises(connection.UnrecognisedConnectError) as excinfo:
|
||||
await dev.connect()
|
||||
assert str(excinfo.value) == (
|
||||
"couldn't connect to the device on /dev/ttyACM0: unsupported baud rate"
|
||||
)
|
||||
assert isinstance(excinfo.value.__cause__, ValueError)
|
||||
records = [r for r in caplog.records if "unsupported baud rate" in r.getMessage()]
|
||||
assert len(records) == 2
|
||||
assert records[0].exc_info is not None # the traceback, the first time
|
||||
assert records[1].exc_info is None # and only the line after that
|
||||
|
||||
|
||||
async def test_a_ble_connect_timeout_is_named_as_a_stall(monkeypatch) -> None:
|
||||
"""A Bluetooth stack's own timeout says what stalls, rather than a bare ``TimeoutError``."""
|
||||
dev = connection.MeshCoreDevice(transport="ble", address=_OPEN_ADDR)
|
||||
|
||||
async def _create_ble(_mesh_core):
|
||||
raise TimeoutError
|
||||
|
||||
dev._create_ble = _create_ble # type: ignore[method-assign]
|
||||
_fake_meshcore(monkeypatch)
|
||||
with pytest.raises(DeviceCommandError) as excinfo:
|
||||
await dev.connect()
|
||||
assert "timed out" in str(excinfo.value) and "Move closer" in str(excinfo.value)
|
||||
|
||||
|
||||
async def test_a_tcp_probe_that_runs_out_of_time_says_so() -> None:
|
||||
"""The probe's own window runs out before the OS gives up on a silent host: named too."""
|
||||
dev = connection.MeshCoreDevice(transport="tcp", host="10.0.0.9", tcp_port=5000)
|
||||
|
||||
async def _connect() -> None:
|
||||
raise asyncio.TimeoutError
|
||||
|
||||
dev.connect = _connect # type: ignore[method-assign]
|
||||
with pytest.raises(DeviceCommandError) as excinfo:
|
||||
await connection._probe(dev, 1.0)
|
||||
assert "no answer from 10.0.0.9 on port 5000" in str(excinfo.value)
|
||||
|
||||
|
||||
async def test_the_probe_names_a_failure_it_does_not_recognise(monkeypatch) -> None:
|
||||
"""An odd failure is said in its own words, not called "not a MeshCore device"."""
|
||||
monkeypatch.setattr(connection, "_TRACED", set())
|
||||
dev = connection.MeshCoreDevice(port="COM5")
|
||||
|
||||
async def _connect() -> None:
|
||||
pass
|
||||
|
||||
async def _self_info() -> dict:
|
||||
raise RuntimeError("frame decode failed")
|
||||
|
||||
dev.connect = _connect # type: ignore[method-assign]
|
||||
dev.get_self_info = _self_info # type: ignore[method-assign]
|
||||
with pytest.raises(connection.UnrecognisedConnectError) as excinfo:
|
||||
await connection._probe(dev, 1.0)
|
||||
assert str(excinfo.value) == (
|
||||
"connected to COM5, but reading its identity failed: frame decode failed"
|
||||
)
|
||||
|
||||
|
||||
def test_ble_address_int_parses_macs_and_rejects_others() -> None:
|
||||
"""A colon/dash MAC becomes a 48-bit int; a non-MAC (e.g. a macOS UUID) yields None."""
|
||||
parse = connection.MeshCoreDevice._ble_address_int
|
||||
@@ -1636,3 +1771,292 @@ async def test_a_healthy_bluetooth_teardown_still_releases_the_client() -> None:
|
||||
assert healthy.disconnected
|
||||
assert not healthy.force_stopped # the graceful path was enough, as it always was
|
||||
assert live.disconnect_calls == 1 # and the client is released regardless
|
||||
|
||||
|
||||
# --- What the reader is told when a connection won't open --------------------------------------
|
||||
|
||||
|
||||
def _refusal() -> Exception:
|
||||
"""A connect failure as the context raises it: its own wrapper round the named sentence."""
|
||||
from meshterm.core.selection import DeviceSelectionError
|
||||
|
||||
try:
|
||||
try:
|
||||
raise DeviceCommandError(
|
||||
"COM_TEST is in use by another program — the MeshCore app, a flasher, or a "
|
||||
"serial monitor. Close it and try again."
|
||||
)
|
||||
except DeviceCommandError as cause:
|
||||
raise DeviceSelectionError(f"could not open serial port COM_TEST: {cause}") from cause
|
||||
except DeviceSelectionError as exc:
|
||||
return exc
|
||||
|
||||
|
||||
async def test_a_device_that_failed_to_open_is_not_kept(tmp_path: Path, monkeypatch) -> None:
|
||||
"""After a failed open, nothing claims to be connected, and the next caller tries again.
|
||||
|
||||
The device used to stay behind unopened: ``is_connected`` said yes, and every tool after
|
||||
a failed start was handed it and failed with "not connected" instead of the reason.
|
||||
"""
|
||||
from meshterm.core.selection import DeviceSelectionError
|
||||
|
||||
ctx = _make_ctx(tmp_path)
|
||||
ctx.mock = False
|
||||
ctx.tcp_override = "10.0.0.9:5000"
|
||||
built: list = []
|
||||
|
||||
class _Refusing:
|
||||
transport = "tcp"
|
||||
disconnects = 0
|
||||
|
||||
async def connect(self) -> None:
|
||||
raise DeviceCommandError("nothing is accepting connections on port 5000 at 10.0.0.9")
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self.disconnects += 1
|
||||
|
||||
def fake_make_device(**_kw):
|
||||
built.append(_Refusing())
|
||||
return built[-1]
|
||||
|
||||
monkeypatch.setattr(context_module, "make_device", fake_make_device)
|
||||
try:
|
||||
for attempt in (1, 2):
|
||||
with pytest.raises(DeviceSelectionError, match="port 5000"):
|
||||
await ctx.device()
|
||||
assert not ctx.is_connected
|
||||
assert len(built) == attempt # a fresh attempt each time, not the dead one back
|
||||
assert built[0].disconnects == 1 # whatever half of it opened was put down
|
||||
finally:
|
||||
ctx.repo.close()
|
||||
|
||||
|
||||
def test_a_failure_reads_as_the_connection_s_own_sentence() -> None:
|
||||
"""The dialog shows the named sentence, not the context's wrapper repeating the endpoint."""
|
||||
from meshterm.ui.device_picker import connect_failure_text
|
||||
|
||||
text = connect_failure_text(_refusal())
|
||||
assert text.plain.startswith("COM_TEST is in use by another program")
|
||||
assert "could not open serial port" not in text.plain
|
||||
assert "The full error" not in text.plain # a named failure: the log has nothing more
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("sentence", "shown"),
|
||||
[
|
||||
("couldn't open a Bluetooth link to X", "Couldn't open a Bluetooth link to X"),
|
||||
("no permission to open COM5.", "No permission to open COM5."),
|
||||
("meshbox.local:5000 closed the connection", "meshbox.local:5000 closed the connection"),
|
||||
("/dev/ttyACM0 isn't there", "/dev/ttyACM0 isn't there"),
|
||||
("c0:ff:ee:00:00:01 rejected the PIN", "c0:ff:ee:00:00:01 rejected the PIN"),
|
||||
],
|
||||
)
|
||||
def test_a_dialog_capitalises_a_plain_word_and_never_a_name(sentence: str, shown: str) -> None:
|
||||
"""A dialog capitalises the command line's lowercase sentence, but never a name.
|
||||
|
||||
A sentence that starts with a port, a host, or an address keeps that spelling, since it
|
||||
is the reader's to match against their own.
|
||||
"""
|
||||
from meshterm.ui.device_picker import connect_failure_text
|
||||
|
||||
assert connect_failure_text(DeviceCommandError(sentence)).plain == shown
|
||||
|
||||
|
||||
def test_an_unrecognised_failure_says_where_the_log_is(monkeypatch, tmp_path: Path) -> None:
|
||||
"""Only a failure MeshTerm couldn't name points at the log, and only if the log took it."""
|
||||
from meshterm.ui import device_picker
|
||||
|
||||
log = tmp_path / "meshterm.log"
|
||||
odd = connection.UnrecognisedConnectError("couldn't connect to COM5: [WinError 31] odd")
|
||||
monkeypatch.setattr(device_picker, "log_file_for", lambda level: log)
|
||||
text = device_picker.connect_failure_text(odd)
|
||||
assert text.plain == f"Couldn't connect to COM5: [WinError 31] odd\nThe full error is in {log}"
|
||||
|
||||
monkeypatch.setattr(device_picker, "log_file_for", lambda level: None) # log level ERROR
|
||||
assert "The full error" not in device_picker.connect_failure_text(odd).plain
|
||||
|
||||
|
||||
async def test_reconnect_says_why_once_the_failure_persists(tmp_path: Path, monkeypatch) -> None:
|
||||
"""A device that is back but refuses gets its reason under the spinner, not a silent wait.
|
||||
|
||||
The first failure is let go (a board can refuse once while it boots), so the reason
|
||||
appears from the second.
|
||||
"""
|
||||
from rich.text import Text
|
||||
|
||||
from meshterm.ui.tui import ReconnectDialog
|
||||
|
||||
ctx = _make_ctx(tmp_path)
|
||||
ctx.mock = False
|
||||
ctx._device = object()
|
||||
ctx._active_port = "COM_TEST"
|
||||
dialog = ReconnectDialog("Waiting for your device — reconnect it to resume.")
|
||||
dialog.future = asyncio.get_running_loop().create_future()
|
||||
seen: list[str] = []
|
||||
|
||||
def body() -> str:
|
||||
return Text.from_ansi("\n".join(dialog.render_body(68))).plain
|
||||
|
||||
async def fake_reconnect(self: AppContext, *, ble_device: object | None = None) -> None:
|
||||
seen.append(body())
|
||||
if len(seen) <= 2:
|
||||
raise _refusal()
|
||||
|
||||
async def fake_release(self: AppContext) -> None:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(connection, "serial_port_present", lambda port: True)
|
||||
monkeypatch.setattr(AppContext, "reconnect", fake_reconnect)
|
||||
monkeypatch.setattr(AppContext, "release_link", fake_release)
|
||||
monkeypatch.setattr(menu, "_LIVENESS_POLL_S", 0.0)
|
||||
try:
|
||||
await asyncio.wait_for(menu._auto_reconnect(ctx, dialog), timeout=2.0)
|
||||
assert dialog.future.result() == "reconnected"
|
||||
assert "in use by another program" not in seen[1] # one failure: just retried
|
||||
assert "in use by another program" in seen[2] # two: said
|
||||
assert "Still trying to reconnect" in seen[2]
|
||||
finally:
|
||||
ctx.repo.close()
|
||||
|
||||
|
||||
async def test_reconnect_forgets_the_reason_when_the_device_goes_again(
|
||||
tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
"""Unplugged after it refused, the device is waited for again, not still called refusing."""
|
||||
from rich.text import Text
|
||||
|
||||
from meshterm.ui.tui import ReconnectDialog
|
||||
|
||||
ctx = _make_ctx(tmp_path)
|
||||
ctx.mock = False
|
||||
ctx._device = object()
|
||||
ctx._active_port = "COM_TEST"
|
||||
dialog = ReconnectDialog("Waiting for your device — reconnect it to resume.")
|
||||
dialog.future = asyncio.get_running_loop().create_future()
|
||||
present = iter([True, True, False, True]) # refuses twice, is pulled, comes back
|
||||
bodies: list[str] = []
|
||||
|
||||
def port_present(_port: str) -> bool:
|
||||
bodies.append(Text.from_ansi("\n".join(dialog.render_body(68))).plain)
|
||||
return next(present)
|
||||
|
||||
attempts = {"n": 0}
|
||||
|
||||
async def fake_reconnect(self: AppContext, *, ble_device: object | None = None) -> None:
|
||||
attempts["n"] += 1
|
||||
if attempts["n"] <= 2:
|
||||
raise _refusal()
|
||||
|
||||
async def fake_release(self: AppContext) -> None:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(connection, "serial_port_present", port_present)
|
||||
monkeypatch.setattr(AppContext, "reconnect", fake_reconnect)
|
||||
monkeypatch.setattr(AppContext, "release_link", fake_release)
|
||||
monkeypatch.setattr(menu, "_LIVENESS_POLL_S", 0.0)
|
||||
try:
|
||||
await asyncio.wait_for(menu._auto_reconnect(ctx, dialog), timeout=2.0)
|
||||
assert "in use by another program" in bodies[2] # said, while it was refusing
|
||||
assert "in use by another program" not in bodies[3] # gone again: waited for
|
||||
assert "Waiting for your device" in bodies[3]
|
||||
finally:
|
||||
ctx.repo.close()
|
||||
|
||||
|
||||
async def test_a_radio_that_will_not_start_is_reported_before_the_menu(
|
||||
tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
"""With the device named on the command line there is no picker, so startup says why."""
|
||||
ctx = _make_ctx(tmp_path)
|
||||
notes: list = []
|
||||
|
||||
async def failing_start() -> None:
|
||||
raise _refusal()
|
||||
|
||||
async def notify_startup(renderable, *, title="", banner=None, footnote=None):
|
||||
notes.append((title, renderable.plain))
|
||||
|
||||
monkeypatch.setattr(ctx.events, "start", failing_start)
|
||||
monkeypatch.setattr(menu, "_warm_basemap", lambda _ctx: None)
|
||||
monkeypatch.setattr(ctx, "ui", SimpleNamespace(notify_startup=notify_startup))
|
||||
try:
|
||||
failure = await menu._resume_monitor(ctx)
|
||||
assert failure is not None
|
||||
assert not ctx.chat.active # not a second try at the same refusal
|
||||
await menu._report_startup_failure(ctx, failure)
|
||||
[(title, plain)] = notes
|
||||
assert title == "Can't connect yet"
|
||||
assert plain.startswith("COM_TEST is in use by another program")
|
||||
assert "The menu opens without a radio" in plain
|
||||
finally:
|
||||
await ctx.aclose()
|
||||
|
||||
|
||||
class _ToolUi:
|
||||
"""Collects what a tool run leaves for its result dialog."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.buffer: list = []
|
||||
self.presented = False
|
||||
|
||||
def note(self, markup: str) -> None:
|
||||
from rich.text import Text
|
||||
|
||||
self.buffer.append(Text.from_markup(markup))
|
||||
|
||||
def show(self, *renderables) -> None: # noqa: ANN002
|
||||
self.buffer.extend(renderables)
|
||||
|
||||
def discard(self) -> None:
|
||||
self.buffer = []
|
||||
|
||||
async def present(self, *, title: str = "") -> None:
|
||||
self.presented = True
|
||||
|
||||
|
||||
async def _run_failing_tool(tmp_path: Path, monkeypatch, exc: Exception) -> _ToolUi:
|
||||
"""Run a menu tool that raises ``exc``, and return what it left to show."""
|
||||
from meshterm import tools
|
||||
|
||||
class _Tool:
|
||||
name = title = "Contacts"
|
||||
|
||||
async def prompt_params(self, _ctx):
|
||||
raise exc
|
||||
|
||||
ctx = _make_ctx(tmp_path)
|
||||
ui = _ToolUi()
|
||||
monkeypatch.setattr(tools, "get_tool", lambda name: _Tool())
|
||||
monkeypatch.setattr(ctx, "ui", ui)
|
||||
try:
|
||||
await menu._run_selection(ctx, "contacts")
|
||||
finally:
|
||||
ctx.repo.close()
|
||||
return ui
|
||||
|
||||
|
||||
async def test_a_tool_whose_radio_never_opened_says_why(tmp_path: Path, monkeypatch) -> None:
|
||||
"""A connect that failed reads as the connection's sentence, even if it looks like a lost link.
|
||||
|
||||
The watcher has nothing connected to notice, so nothing else would say it.
|
||||
"""
|
||||
from meshterm.core.selection import DeviceSelectionError
|
||||
|
||||
try:
|
||||
raise DeviceSelectionError("could not open BLE companion X") from OSError(
|
||||
"input/output error"
|
||||
)
|
||||
except DeviceSelectionError as raised:
|
||||
exc = raised
|
||||
assert is_connection_lost(exc)
|
||||
ui = await _run_failing_tool(tmp_path, monkeypatch, exc)
|
||||
assert ui.presented
|
||||
assert [t.plain for t in ui.buffer] == ["⚠ Could not open BLE companion X"]
|
||||
|
||||
|
||||
async def test_a_tool_failure_shows_the_error_s_brackets(tmp_path: Path, monkeypatch) -> None:
|
||||
"""A library's bracketed words are shown, not swallowed as a markup tag."""
|
||||
exc = RuntimeError("[org.bluez.Error.Failed] le-connection-abort-by-local")
|
||||
ui = await _run_failing_tool(tmp_path, monkeypatch, exc)
|
||||
[text] = ui.buffer
|
||||
assert text.plain == "⚠ Contacts failed: [org.bluez.Error.Failed] le-connection-abort-by-local"
|
||||
+25
-1
@@ -103,7 +103,7 @@ from meshterm.ui.theme import name_style
|
||||
from meshterm.ui.timemachine_screen import TimeMachineScreen
|
||||
from meshterm.ui.trace_screen import TraceScreen
|
||||
from meshterm.ui.tui import Screen, SelectScreen, fkeys, frame
|
||||
from meshterm.ui.tui.prompt import CountdownDialog
|
||||
from meshterm.ui.tui.prompt import CountdownDialog, ReconnectDialog
|
||||
from meshterm.ui.tx_screen import TxSweepScreen
|
||||
from meshterm.ui.walk_screen import WalkScreen
|
||||
from meshterm.ui.widgets import (
|
||||
@@ -1342,6 +1342,29 @@ def _cooldown_countdown(cols: int, rows: int) -> Screen:
|
||||
return CountdownDialog("Flood advert", 47.0, reason="a flood advert reaches the whole mesh")
|
||||
|
||||
|
||||
def _reconnect_reason(cols: int, rows: int) -> Screen:
|
||||
"""The reconnect dialog once a refusal has persisted: the reason wraps under the spinner.
|
||||
|
||||
Sized from its own content like the countdown, with the longest reason a reconnect can
|
||||
meet on a serial port — Linux's, which goes on to name ModemManager.
|
||||
"""
|
||||
from meshterm.core.connection import DeviceCommandError
|
||||
from meshterm.ui.device_picker import connect_failure_text
|
||||
|
||||
dialog = ReconnectDialog("Still trying to reconnect…")
|
||||
dialog.set_detail(
|
||||
connect_failure_text(
|
||||
DeviceCommandError(
|
||||
"/dev/ttyACM0 is in use by another program — the MeshCore app, a flasher, or "
|
||||
"a serial monitor. Close it and try again. On Linux this is often "
|
||||
"ModemManager, which probes new USB serial devices: `sudo systemctl stop "
|
||||
"ModemManager` and try again."
|
||||
)
|
||||
)
|
||||
)
|
||||
return dialog
|
||||
|
||||
|
||||
def _about_meshterm(cols: int, rows: int) -> Screen:
|
||||
return AboutPage("About MeshTerm", about_meshterm())
|
||||
|
||||
@@ -1507,6 +1530,7 @@ _ENTRIES: list[_Entry] = [
|
||||
_Entry("preferences", _preferences),
|
||||
_Entry("preferences-weekly-advert", _preferences_weekly_advert),
|
||||
_Entry("cooldown_countdown", _cooldown_countdown),
|
||||
_Entry("reconnect_reason", _reconnect_reason),
|
||||
_Entry("about_meshterm", _about_meshterm),
|
||||
_Entry("about_author", _about_author),
|
||||
_Entry("join_discord", _join_discord),
|
||||
|
||||
Reference in new issue
Block a user