diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 269dd47..64cb0c5 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -63,6 +63,8 @@ from ..platforms import Platform, on_platform from .device_info_screen import REVEAL_KEY from .marks import MASK_MARK from .menus import ( + PICK_LOCATION_HELP, + PICK_LOCATION_LABEL, confirm_discard, exit_rows, icon_lane, @@ -100,8 +102,7 @@ _CANCEL = "__cancel__" # Sentinel for the "enter a value myself" option on non-strict enum prompts. _OTHER = "__other__" -#: The setting keys folded into the single "Location" row (they stay individually -#: addressable from the CLI; only the editor presents them as one place-on-earth value). +#: The setting keys the map pick sets together (each also has its own row, for a typed value). _COORD_KEYS = ("adv_lat", "adv_lon") #: How long the reboot flow waits to *observe* the link actually dropping before handing @@ -474,27 +475,6 @@ def _setting_value( return value -def _format_coords(lat: Any, lon: Any) -> str: - """Render a coordinate pair for display (``"not set"`` for the 0,0 no-fix value).""" - try: - lat_f, lon_f = float(lat or 0.0), float(lon or 0.0) - except (TypeError, ValueError): - return "?" - if abs(lat_f) < 1e-6 and abs(lon_f) < 1e-6: - return "not set" - return f"{lat_f:.5f}, {lon_f:.5f}" - - -def _location_value(snapshot: dict, pending: dict) -> Text: - """The Location row's VALUE lane, standing in for the ``adv_lat``/``adv_lon`` pair.""" - value = Text(_format_coords(snapshot.get("adv_lat"), snapshot.get("adv_lon"))) - if any(k in pending for k in _COORD_KEYS): - lat = pending.get("adv_lat", snapshot.get("adv_lat")) - lon = pending.get("adv_lon", snapshot.get("adv_lon")) - value.append(f" → {_format_coords(lat, lon)}", style="warn") - return value - - class _ConfigMenu(SelectScreen): """The editor's list, with the pairing PIN's row concealed until ``^S`` uncovers it. @@ -623,19 +603,10 @@ def _menu_items( for category, specs in settings_by_category(): rows: list[tuple[str, Text, str, Any]] = [] for spec in specs: - if spec.key in _COORD_KEYS: - # Latitude/longitude collapse into one Location row (inserted in - # adv_lat's slot so it sits where the coordinates used to). - if spec.key == "adv_lat": - rows.append( - ( - "Location", - _location_value(snapshot, pending), - "Advertised position; pick it on the map", - _LOCATION, - ) - ) - continue + if spec.key == "adv_lat": + # The map pick sets both coordinates at once, so it heads the pair it fills — + # the same row, in the same place, as on the repeater admin page. + rows.append((PICK_LOCATION_LABEL, Text(), PICK_LOCATION_HELP, _LOCATION)) rows.append( ( spec.label, @@ -887,78 +858,26 @@ async def _stage_advert_cadence( async def _stage_location(ctx: AppContext, snapshot: dict, pending: dict[str, Any]) -> None: - """Set the advertised location: on the map, typed as a pair, or cleared. + """Pick the advertised location on the map and stage both coordinates it sets. - Staged like any other setting — the coordinates only reach the device on Apply. + The map opens on the position as staged (or as the device holds it), and on the mesh + where there is none. Each coordinate keeps its own row for a typed value — ``0`` in both + is MeshCore's "no fix", and the node stops advertising a position. Staged like any other + setting: the coordinates only reach the device on Apply. """ + from .map_screen import coords_or_none, pick_location + lat = pending.get("adv_lat", snapshot.get("adv_lat")) lon = pending.get("adv_lon", snapshot.get("adv_lon")) - choice = await ctx.ui.dialog( - f"Advertised location: {_format_coords(lat, lon)}", - [("Pick on map", "map"), ("Type coordinates", "type"), ("Clear", "clear")], - title="Location", - ) - if choice is None: + picked = await pick_location(ctx, initial=coords_or_none(lat, lon)) + if picked is None: return - - if choice == "map": - from .map_screen import pick_location - - initial = None - try: - if abs(float(lat or 0.0)) >= 1e-6 or abs(float(lon or 0.0)) >= 1e-6: - initial = (float(lat), float(lon)) - except (TypeError, ValueError): - initial = None - picked = await pick_location(ctx, initial=initial) - if picked is None: - return - # Six decimals ≈ 0.1 m — beyond the map's own precision, plenty for an advert. - pending["adv_lat"] = round(picked[0], 6) - pending["adv_lon"] = round(picked[1], 6) - elif choice == "type": - raw = await ctx.ui.text( - "Set location", - prompt="Enter latitude, longitude in decimal degrees", - default=f"{lat}, {lon}" if _format_coords(lat, lon) != "not set" else "", - validate=_valid_coords, - help_text="e.g. 45.50000, -73.60000", - ) - if not raw: - return - parsed = _parse_coords(raw) - pending["adv_lat"], pending["adv_lon"] = parsed - elif choice == "clear": - # 0, 0 is MeshCore's "no fix" value: the node stops advertising a position. - pending["adv_lat"], pending["adv_lon"] = 0.0, 0.0 - - # Staging the device's own values back is a no-op; drop them so the row reads clean. - for key in _COORD_KEYS: - if key in pending and pending[key] == snapshot.get(key): - del pending[key] - - -def _parse_coords(text: str) -> tuple[float, float]: - """Parse a ``lat, lon`` pair (comma or space separated), range-checked via the specs. - - Raises: - DeviceConfigError: If the text is not two in-range decimal degrees. - """ - parts = [p for p in text.replace(",", " ").split() if p] - if len(parts) != 2: - raise DeviceConfigError("enter two numbers: latitude, longitude") - lat = parse_value(get_spec("adv_lat"), parts[0]) - lon = parse_value(get_spec("adv_lon"), parts[1]) - return float(lat), float(lon) - - -def _valid_coords(text: str) -> bool | str: - """Validate a typed coordinate pair, returning the parse error as the message.""" - try: - _parse_coords(text) - return True - except DeviceConfigError as exc: - return str(exc) + # Six decimals ≈ 0.1 m — beyond the map's own precision, plenty for an advert. + for key, value in zip(_COORD_KEYS, picked, strict=True): + if round(value, 6) == snapshot.get(key): + pending.pop(key, None) # the device's own value — nothing to change + else: + pending[key] = round(value, 6) async def _stage_preset(ctx: AppContext, snapshot: dict, pending: dict[str, Any]) -> None: diff --git a/meshterm/ui/map_screen.py b/meshterm/ui/map_screen.py index 33befd2..bd62083 100644 --- a/meshterm/ui/map_screen.py +++ b/meshterm/ui/map_screen.py @@ -1210,6 +1210,23 @@ class LocationPickScreen(MapScreen): super().handle(action, data) +def coords_or_none(lat: object, lon: object) -> tuple[float, float] | None: + """A stored coordinate pair as the picker's opening spot, or ``None`` to frame the mesh. + + Takes whatever a caller holds — floats from the companion, strings from a repeater's + CLI, ``None`` where nothing was read — and reads MeshCore's ``0, 0`` "no fix" as no + location at all, so a node that never had a position opens on the mesh rather than on + a point in the Gulf of Guinea. + """ + try: + lat_f, lon_f = float(lat), float(lon) # type: ignore[arg-type] + except (TypeError, ValueError): + return None + if abs(lat_f) < 1e-6 and abs(lon_f) < 1e-6: + return None + return lat_f, lon_f + + async def pick_location( ctx: AppContext, *, initial: tuple[float, float] | None = None ) -> tuple[float, float] | None: diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 6efd6a9..40682ec 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -432,6 +432,12 @@ def lane_header(label_w: int, value_w: int, width: int) -> str: ) +#: The row both editor pages (Device config, repeater admin) head their coordinates with: it +#: opens the map picker and stages latitude and longitude together. +PICK_LOCATION_LABEL = "Pick location on map…" +PICK_LOCATION_HELP = "Point at the map to set both coordinates" + + def changes_phrase(count: int) -> str: """``"1 staged change"`` / ``"3 staged changes"`` for dialogs and menu rows.""" return f"{count} staged change{'' if count == 1 else 's'}" diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 250cf43..0c30f4b 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -49,6 +49,8 @@ from ..core.remote_config import ( write_plan, ) from .menus import ( + PICK_LOCATION_HELP, + PICK_LOCATION_LABEL, confirm_discard, exit_rows, icon_lane, @@ -73,6 +75,7 @@ _REPLY_TIMEOUT_S = 10.0 # Menu action sentinels (distinct from setting keys, which are CLI parameter names). _CLI = "__cli__" +_LOCATION = "__location__" _READ = "__read__" _ADVERT = "__advert__" _CLOCK = "__clock__" @@ -312,6 +315,8 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict applied += await _apply(ctx, device, node, pending) elif choice == _READ: await read_settings(ctx, device, node, REPEATER_SETTINGS) + elif choice == _LOCATION: + await _stage_location(ctx, cache, pending) elif choice == _CLI: await _command_line(ctx, device, node) elif choice == _ADVERT: @@ -375,6 +380,10 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st for category, specs in settings_by_category(): rows: list[tuple[str, Text, str, Any]] = [] for spec in specs: + if spec.key == "lat": + # The map pick sets both coordinates at once, so it heads the pair it fills — + # the same row, in the same place, as on the Device config page. + rows.append((PICK_LOCATION_LABEL, Text(), PICK_LOCATION_HELP, _LOCATION)) rows.append((spec.label, _value_text(spec, cache, pending), spec.help, spec.key)) sections.append((category, rows)) @@ -423,8 +432,8 @@ def _value_text(spec: RemoteSetting, cache: dict, pending: dict[str, str]) -> Te """One setting's VALUE lane: what the node last said, and any staged arrow. Four states, each its own word: the value; ``empty`` for a string the node holds blank; - ``n/a`` when the node's firmware answered that it has no such setting; ``?`` when it was - never read. No age: the lane is the value, and a stamp beside it only crowded it. + ``n/a`` when the node answered with something that can't be this setting's value — its + firmware has no such setting; ``?`` when it was never read (or never answered). No age: the lane is the value, and a stamp beside it only crowded it. """ cached = cache.get(spec.key) if not spec.readable: @@ -502,6 +511,37 @@ async def _stage_setting(ctx: AppContext, key: str, cache: dict, pending: dict[s pending[key] = value +async def _stage_location(ctx: AppContext, cache: dict, pending: dict[str, str]) -> None: + """Pick the node's advertised location on the map and stage both coordinates it sets. + + The Device config page's row, speaking this node's CLI: the map opens on the position + as staged (or as the node last said), and on the mesh where there is none. Each picked + coordinate is stored the way a read of it would be, so picking the spot the node + already holds unstages rather than queueing a no-op ``set``. Nothing is sent until Apply. + """ + from .map_screen import coords_or_none, pick_location + + def known(key: str) -> str | None: + cached = cache.get(key) + return cached.value if cached is not None and cached.supported else None + + lat = pending.get("lat", known("lat")) + lon = pending.get("lon", known("lon")) + picked = await pick_location(ctx, initial=coords_or_none(lat, lon)) + if picked is None: + return + for key, value in zip(("lat", "lon"), picked, strict=True): + spec = get_setting(key) + if spec is None: # pragma: no cover - both keys are in the catalog + continue + # Six decimals ≈ 0.1 m — beyond the map's own precision, plenty for an advert. + text = normalize_value(spec, f"{value:.6f}") + if text == known(key): + pending.pop(key, None) # what the node already says — nothing to send + else: + pending[key] = text + + def _known_values(ctx: AppContext, node: Contact) -> dict[str, str]: """The node's last-read values, for restating a composite's unstaged fields.""" return { @@ -615,21 +655,24 @@ async def _apply(ctx: AppContext, device: Device, node: Contact, pending: dict[s def remember_reply(ctx: AppContext, node: Contact, fills: list[RemoteSetting], reply: str) -> int: """Fold one read's reply into the cache for every setting it answers. - An error reply is the firmware saying it has no such setting, and is remembered as - that (the row reads ``n/a``). A reply that isn't an error but doesn't parse leaves the - cache alone: a phrasing we don't understand is not evidence the setting is missing. + A reply that can't be the setting's value is the node saying it has no such setting, + and is remembered as that (the row reads ``n/a``) — an error (``??: key``, ``Error: + unsupported``) and an answer to some other question alike. The second is how older + firmware says it: ``get`` matches its keys by *prefix*, so on v1.15 a key it lacks + falls into a shorter sibling's branch — ``get radio.fem.rxgain`` answers with + ``get radio``'s ``> 910.525,62.5,7,5`` — and ``gps`` on a board whose receiver is + absent answers ``Can't find GPS``. Leaving those rows alone left them on ``?``, which + says *never asked*; only a read that got no reply at all (not passed here) keeps that. Returns: How many settings got a value. """ - if reply_is_error(reply): - for spec in fills: - ctx.remote_store.remember_unsupported(node, spec.key) - return 0 got = 0 for spec in fills: - value = parse_reply_value(spec, reply) - if value is not None: + value = parse_reply_value(spec, reply) # None for an error reply, too + if value is None: + ctx.remote_store.remember_unsupported(node, spec.key) + else: ctx.remote_store.remember_setting(node, spec.key, value) got += 1 return got diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index 9be0a7c..21345d2 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -27,8 +27,6 @@ from meshterm.platforms import PICOCALC, REGULAR, set_platform from meshterm.ui.config_editor import ( _ConfigMenu, _menu_items, - _parse_coords, - _valid_coords, config_table, contact_share_url, edit_config, @@ -397,24 +395,19 @@ async def test_show_contact_card_pops_the_qr_over_the_link() -> None: assert "█" in out # the QR actually drew its modules -# -- coordinate parsing ---------------------------------------------------------- +# -- the map pick's opening spot -------------------------------------------------- -def test_parse_coords_accepts_comma_and_space_pairs() -> None: - """A typed pair parses with a comma, a space, or both.""" - assert _parse_coords("45.5, -73.6") == (45.5, -73.6) - assert _parse_coords("45.5 -73.6") == (45.5, -73.6) - assert _parse_coords(" 45.5 , -73.6 ") == (45.5, -73.6) +def test_the_map_opens_on_a_stored_position_and_on_the_mesh_without_one() -> None: + """Floats or CLI strings open the picker there; no fix (0, 0) or no value frames the mesh.""" + from meshterm.ui.map_screen import coords_or_none - -def test_parse_coords_rejects_garbage_and_out_of_range() -> None: - """Wrong shape or out-of-range degrees surface as validation messages.""" - assert _valid_coords("45.5") != True # noqa: E712 - message, not False - assert _valid_coords("45.5, -73.6, 7") != True # noqa: E712 - assert _valid_coords("91.0, 0") != True # noqa: E712 - latitude out of range - assert _valid_coords("0, 181") != True # noqa: E712 - longitude out of range - assert _valid_coords("here, there") != True # noqa: E712 - assert _valid_coords("45.5, -73.6") is True + assert coords_or_none(45.5, -73.6) == (45.5, -73.6) + assert coords_or_none("45.5", "-73.6") == (45.5, -73.6) + assert coords_or_none(0.0, 0.0) is None + assert coords_or_none("0", "0") is None + assert coords_or_none(None, -73.6) is None + assert coords_or_none("here", "there") is None # -- the typed-confirmation dialog ------------------------------------------------ @@ -869,23 +862,25 @@ async def test_editor_menu_pins_the_column_header_over_the_category(ctx: AppCont assert any("Flood advert" in _ANSI.sub("", row) for row in visible) -async def test_editor_location_typed_coordinates_stage_both_axes( +async def test_editor_latitude_and_longitude_are_rows_of_their_own( ctx: AppContext, applied_ops: list[tuple] ) -> None: - """Typing a coordinate pair stages latitude and longitude together.""" + """Each coordinate is typed on its own row, as on the repeater admin page.""" _install( ctx, [ - ("select", "__location__"), - ("dialog", "type"), - ("text", "45.5, -73.6"), + ("select", "adv_lat"), + ("text", "45.5"), + ("select", "adv_lon"), + ("text", "-73.6"), ("select", "__apply__"), ("select", None), ], ) await edit_config(ctx) - assert ("set", "adv_lat", 45.5) in applied_ops - assert ("set", "adv_lon", -73.6) in applied_ops + assert applied_ops == [("set", "adv_lat", 45.5), ("set", "adv_lon", -73.6)] + info = await (await ctx.device()).get_self_info() + assert (info["adv_lat"], info["adv_lon"]) == (45.5, -73.6) async def test_editor_location_map_pick_stages_rounded_coordinates( @@ -901,35 +896,50 @@ async def test_editor_location_map_pick_stages_rounded_coordinates( _install( ctx, [ - ("select", "__location__"), - ("dialog", "map"), + ("select", "__location__"), # straight onto the map — no dialog in between ("select", "__apply__"), ("select", None), ], ) await edit_config(ctx) - assert ("set", "adv_lat", 45.512346) in applied_ops - assert ("set", "adv_lon", -73.654321) in applied_ops + assert applied_ops == [("set", "adv_lat", 45.512346), ("set", "adv_lon", -73.654321)] -async def test_editor_location_clear_stages_the_no_fix_pair( - ctx: AppContext, applied_ops: list[tuple] +async def test_editor_map_pick_opens_on_the_staged_position_and_can_be_backed_out_of( + ctx: AppContext, monkeypatch: pytest.MonkeyPatch ) -> None: - """Clear stages 0, 0 — MeshCore's "no fix" value — for both axes.""" - device = await ctx.device() - await device.set_coords(45.5, -73.6) # give the device a position to clear + """The map opens where the typed coordinates put the node; Esc on the map stages nothing.""" + opened: list = [] + + async def _fake_pick(_ctx: AppContext, *, initial=None): + opened.append(initial) + return None # Esc on the map + + monkeypatch.setattr("meshterm.ui.map_screen.pick_location", _fake_pick) _install( ctx, [ + ("select", "adv_lat"), + ("text", "45.5"), + ("select", "adv_lon"), + ("text", "-73.6"), ("select", "__location__"), - ("dialog", "clear"), - ("select", "__apply__"), - ("select", None), + ("select", None), # the typed pair is still staged, so leaving asks + ("dialog", "discard"), ], ) - await edit_config(ctx) - assert ("set", "adv_lat", 0.0) in applied_ops - assert ("set", "adv_lon", 0.0) in applied_ops + assert await edit_config(ctx) is None + assert opened == [(45.5, -73.6)] + + +def test_the_map_pick_row_heads_the_coordinates_it_sets() -> None: + """``Pick location on map…`` sits directly above Latitude and Longitude.""" + _title, items = _menu_items(_SNAPSHOT, {}, 0, AdvertPolicy()) + rows = _row_texts(items) + at = next(i for i, row in enumerate(rows) if row.startswith("Pick location on map…")) + assert rows[at + 1].startswith("Latitude") + assert rows[at + 2].startswith("Longitude") + assert not any(row.startswith("Location") for row in rows) async def test_send_advert_sends_zero_hop_and_flood_immediately(ctx: AppContext) -> None: diff --git a/tests/test_repeater_admin.py b/tests/test_repeater_admin.py index 807c593..393d0a2 100644 --- a/tests/test_repeater_admin.py +++ b/tests/test_repeater_admin.py @@ -591,6 +591,46 @@ def test_admin_editor_ends_long_rows_at_the_edge_like_device_config() -> None: assert list(menu.render_body(40)) == before +def test_the_map_pick_row_heads_the_coordinates_it_sets() -> None: + """``Pick location on map…`` sits directly above Latitude and Longitude, as on Device config.""" + from meshterm.ui.tui import Choice + + _title, items = repeater_admin._menu_items(NODE, {}, {}) + rows = [ + item.title.plain + for item in items + if isinstance(item, Choice) and hasattr(item.title, "plain") + ] + at = next(i for i, row in enumerate(rows) if row.startswith("Pick location on map…")) + assert rows[at + 1].startswith("Latitude") + assert rows[at + 2].startswith("Longitude") + + +async def test_the_map_pick_stages_both_coordinates_as_a_read_would_spell_them( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The map opens where the node says it is; a coordinate it already holds stays unstaged.""" + opened: list = [] + + async def _fake_pick(_ctx, *, initial=None): # noqa: ANN001 + opened.append(initial) + return (45.51234567, -73.6) + + monkeypatch.setattr("meshterm.ui.map_screen.pick_location", _fake_pick) + now = utcnow() + cache = {"lat": CachedValue("45.5", now), "lon": CachedValue("-73.6", now)} + pending: dict[str, str] = {} + await repeater_admin._stage_location(None, cache, pending) + assert opened == [(45.5, -73.6)] + assert pending == {"lat": "45.512346"} # the longitude is already where the node has it + + # A node that never reported a position opens the map on the mesh, and takes both. + unread: dict[str, str] = {} + await repeater_admin._stage_location(None, {}, unread) + assert opened[-1] is None + assert unread == {"lat": "45.512346", "lon": "-73.6"} + + # --- the command-line screen -----------------------------------------------------------