diff --git a/CHANGELOG.md b/CHANGELOG.md index 72dc0d5..f02b824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,12 +3,118 @@ This page lists the notable changes to MeshTerm. The newest version is first. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). The -version numbers follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). One -rule of SemVer applies to a leading zero: while the major version is `0`, a **minor** bump -can change how things behave. It does not only add new things. +version numbers follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The +releases below 1.0.0 used one more rule: while the major version is `0`, a **minor** bump +can change how things behave. From 1.0.0, a change that breaks the command line, the +`--json` answers, the configuration keys, or the preference names waits for the next major +version. ## [Unreleased] +## [1.0.0] - 2026-11-23 + +**MeshTerm reaches 1.0.** The command line, its `--json` answers, the configuration keys, +and the preference names are promises from now on. A change that breaks one of them waits +for 2.0. This release also gives MeshTerm sounds for the messages that you want to know +about, a device page that reports everything the companion knows, the neighbours that a +repeater hears, a relay mark on each channel message that you send, and the older LoRa Cap +of the Cardputer Zero. + +### Added + +- **Device info says everything that the companion reports.** The status panel grew from + nine rows to twenty-six, in four groups. **What the node is**: its role, its public key + with the routed bytes lit, its model, its firmware with the companion protocol version, + and the place where it says it is. **What MeshTerm does with it**: the default flood + scope and the transport key of that scope, the active site with the outbound paths and + the kept device routes that apply here, and the name of the radio preset that the four + radio settings match. **How it is doing**: the battery, the storage, the sensor readings + of the node itself, the clock with its drift as a readable duration, the uptime, the + contacts and the channels against the capacities of the device, the packets that wait to + go out, and the firmware error count. **What it heard and sent**: the noise floor with + the last RSSI and SNR, the airtime, and the packet counts, now split into flood and + direct for both directions. A node with no scope says that its floods reach everyone. A + node that stores a scope key that its own scope name does not give says so, which + nothing else in MeshTerm could show. Each value wraps under its own column, so a long + reading never goes back to the left edge, and a 64-digit key stays whole. +- **`meshterm info` answers with the settings too.** It gives three parts: the status, the + sensor readings as a listing, and every setting of the device. The settings come from + the one definition that `config show` answers with, under the keys that `config get` and + `config set` take. Thus the scripted face says the same about a device as the page does, + and no setting is spelled two ways. `--json` gives the status at the top level, the + readings under `telemetry`, and the settings under `settings`. +- **A channel message that you send shows whether a repeater relayed it.** A channel has + no acknowledgement, but your radio hears each repeater that relays your message. The + end of your message shows a spinner, then `βœ“` and the number of repeaters that sent a + copy back, or `βœ—` when none did. A copy that comes late changes the mark, the same as a + late acknowledgement of a direct message. Select the message to see the names of the + repeaters. The wait is the new *Relay wait* preference (`heard_wait_s`, 30 s). MeshTerm + sees only the repeaters that your radio hears, and only while it is connected. + `meshterm chat history --channel` shows the same count in a `HEARD` column, and + `--json` gives `heard` and `heard_by` (#38). +- **MeshTerm plays sounds for the messages that you want to know about.** A DM, a mention + of your node, a channel message, a room post, and a low battery each have their own + sound, from Android's set (the Android Open Source Project, under the same licence as + MeshTerm). Each event has its own switch, all on except the packet tick, and a muted + channel is silent. A mention plays *always* by default, also on a muted channel. It can + also follow the rules of other messages, or count as a regular message. A mention in a + DM plays the DM sound. *On-screen chat* (on by default) decides whether the open + conversation plays its sounds. + Ctrl+S mutes or unmutes the sounds from any screen, and the header shows πŸ”Š or πŸ”‡. The + new *Sound* group of preferences has the theme (Android, terminal bell, or no sound), a + volume slider of ten steps that plays each step, a short tick for each packet heard (off + by default), and a flash of the title for a notification that plays no sound. The + PicoCalc has no sound, so there each notification flashes. The idea came from the + MeshTerm Discord. + +- **MeshTerm drives the older LoRa Cap of the Cardputer Zero.** M5Stack made two LoRa + Caps. The newer Cap LoRa-1262 has an antenna switch, and a small chip that turns the + switch on. The older Cap LoRa868 has the same SX1262 radio on the same pins, and no such + chip, because it has no switch. MeshTerm asked for that chip on every Cardputer Zero, so + an owner of the older Cap read "nothing answers at 0x43 on /dev/i2c-1" and could not + connect at all. Now MeshTerm looks for the chip, and where none answers it asks the radio + what it is. An SX1262 that gives its name is the older Cap. The device screen calls the + row **Cap LoRa** before you connect, because nothing can know which Cap is attached until + the node runs, and after that it names the Cap that answered. A Cardputer Zero with no Cap + at all still says that no radio answered. Found on the MeshTerm Discord. +- **A repeater's admin page lists the neighbours that it hears.** A repeater keeps a table + of the nodes that it receives directly. Until now the only way to that table was three + steps into the trace path composer, and the answer dissolved into the evidence of a route. + The admin page has a **Neighbours** row, and the list it opens is a full screen with the + lanes, the sort, and the type-to-filter of the Contacts list. Two of its lanes belong to + the remote node: SNR is what that node measured, and HEARD is how long ago that node + received from the neighbour. Enter opens the node page of a neighbour, also one that + nothing can name, which then shows what the stored history knows about a node that your + own radio never heard. +- **A radio with no channel gets the standard Public channel at startup.** A radio that + arrives with no channel cannot send anywhere, because each send needs a slot. The empty + Chat picker read as "nobody is here". MeshTerm now writes the Public channel that MeshCore + itself ships, on slot 0, and says so on the splash. The new *Public on empty device* + preference (`public_on_empty_device`) turns it off. + +### Changed + +- **Ctrl+E shows or hides the pairing PIN.** It was Ctrl+S, which now mutes the sounds. + +### Fixed + +- **A filter never hides what a page does.** Find-as-you-type searches the data of a list: + the contacts, the settings, the channel slots, the queued messages, the records. A row + that acts on the page is not data. A typed query used to take the Apply and Back pair of + an editor, the Actions sections of Device config and of the repeater admin, the Add rows + of Channels and Outbound paths, the archive rows of the Contacts list, and the actions of + eight other pages. Apply has no key of its own, so a filter that hid it left it reachable + only by an Esc that nothing on the screen named. Those rows now stay while you type. +- **The name "Public" no longer makes a channel that nobody hears.** `#Public` is not the + standard Public channel. Its key comes from its name, so its hash is different and no + other node is on it. The two add rows sit side by side, and Public is the obvious word to + type into "Public channel name:". The name now asks again and offers the standard channel, + without refusing the name. +- **Two channel messages with the same text no longer share their copies.** The paths + dialog matched a copy of your channel message by its text in a window of 15 minutes. Two + "test" messages a few minutes apart then showed the copies of both. Now a copy of your + own message must also carry the time of that send. + ## [0.13.0] - 2026-11-20 **MeshTerm shows the pixel images that other MeshCore apps send.** A channel message can @@ -913,7 +1019,8 @@ commands. MeshTerm is free and open source, under the Apache 2.0 licence. The licence does not cover the name and the logo (refer to `NOTICE`). A fork is welcome under its own name. -[Unreleased]: https://github.com/jpmartineau/MeshTerm/compare/v0.13.0...HEAD +[Unreleased]: https://github.com/jpmartineau/MeshTerm/compare/v1.0.0...HEAD +[1.0.0]: https://github.com/jpmartineau/MeshTerm/releases/tag/v1.0.0 [0.13.0]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.13.0 [0.12.0]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.12.0 [0.11.5]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.11.5 diff --git a/CLAUDE.md b/CLAUDE.md index a51ae3b..b563bc3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -183,7 +183,10 @@ deliberately, one at a time, and say why in the code. keeps the chip that asked: its F3 reads `Quit!` and sends the same `quit`, which with the question up is the leaving β€” one key pressed twice, as ^Q is. `test_navigation` walks every string literal in the package to keep them out of the rest - of the UI. + of the UI. **^S** is the third global verb (JP, 2026-11-20): it mutes or unmutes the + sounds (`sound_muted`, `services/sound.py`), answered in `_dispatch` through + `set_sound_toggle`, shown by the header's πŸ”Š/πŸ”‡ and the menu's Sound row above Quit, never + a chip. The PIN reveal moved from ^S to ^E for it. "No sound" is a *theme*, not the mute. - **Holding Esc quits**, from anywhere, wherever MeshTerm can tell a key is held (`services/hold_to_quit.py`): a front end that reads its own keys (the emulator, both devices), or a probe that asks the keyboard whether a terminal's Esc is still down @@ -238,6 +241,18 @@ deliberately, one at a time, and say why in the code. holds live: the edits depend on each other there (a region must exist before it can be allowed), and a stage would have to re-implement the firmware's rules to order them. `ui/region_editor.py` is the reference. +- **A filter never hides what a page does** (JP, 2026-11-22). Find-as-you-type searches a + list's **data** β€” the contacts, the settings, the channel slots, the queued messages, the + records, the alerts, the regions, the paths β€” and a row that *acts on the page* is not + data: the `βœ“ Apply`/`βœ— Back` pair, a live page's Save pair, an **Actions** section, an Add + or New row, a bulk action, a maintenance row (Contacts' `Archive contacts…` and + `View archived contacts`), a way out of a result list. Those rows carry + `Choice.always_shown` (`menus.menu_rows(…, always_shown=True)` for a whole section), and + `SelectScreen._rows` keeps them exactly as it keeps a separator. A filter that hid them + left Apply, which has no key of its own, reachable only by an Esc that nothing on the + screen named. The other side of the rule: a list that **is** a menu β€” the main menu, one + room's actions, a path's actions, the startup offer β€” filters every row, because there the + verbs are the content and the query is how the reader finds one. - **A cursor clamps at both ends β€” nothing in the app rolls over.** ↓ off the last row and ↑ off the first stay put, in a select list, a hand-drawn action list, a reorder list, a dialog's button row, everywhere. The window follows the highlight, so a roll @@ -560,6 +575,7 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow πŸ”’ lock (a locked contact, a private channel) Β· πŸ”“ unlock Β· πŸ—‘ clear/delete Β· ✎ compose/edit Β· βš™ parameter Β· `#` count Β· β–Ά run Β· ⚑ explore/probe Β· β˜… best/winner Β· ⭐ watch Β· πŸ“€ send now Β· πŸ“¨ courier/queue Β· πŸ’¬ chat Β· πŸ”” notify Β· πŸ”• mute (notifications off) Β· + πŸ”Š sounds on Β· πŸ”‡ sounds muted (header, menu row) Β· πŸ“± QR Β· πŸ”— link Β· ↻ re-read Β· ↕ reorder Β· ⇄ reverse (flip a path's direction) Β· πŸ”– region/scope Β· πŸ“Œ rooms Β· πŸ† trophy case/record Β· ⌨ command line Β· πŸ“– read/about Β· πŸ’° support/donate Β· 🎨 pixel image (an MCOimg picture in a message) Β· πŸšͺ quit. Packet-class icons (feed/viewer diff --git a/NOTICE b/NOTICE index f8e2d26..92b33ad 100644 --- a/NOTICE +++ b/NOTICE @@ -70,3 +70,10 @@ which are provided under the following license: MeshTerm's MCOimg decoder is its own code, written from the published format reference; only these colour values come from meshcore-open. + +Notification sounds: the files in meshterm/assets/sounds/android/ come from +the Android Open Source Project (platform/frameworks/base, data/sounds), +Copyright The Android Open Source Project, licensed under the Apache License, +Version 2.0. MeshTerm changed them: each was decoded from Ogg Vorbis, mixed to +one channel, and written as 16-bit WAV (scripts/sounds.py). The README.md +beside them names each source file. diff --git a/README.md b/README.md index 2b9f7d8..031835e 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ run MeshTerm, the more the history of your mesh is worth. > change something, first say hello on [Discord](https://discord.gg/AZwe5Uvb3S). > [Read more about how the project is run](#how-this-project-is-run). -https://github.com/user-attachments/assets/a4ce1ef1-5c6b-41c3-b629-0514dc617ef3 +https://github.com/user-attachments/assets/4f918f68-6302-43c8-8d44-df8ad29b5bd3

A video of less than two minutes, in the demo mesh over MontrΓ©al (meshterm --demo).

diff --git a/docs/cli/README.md b/docs/cli/README.md index 275312e..f0f0368 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -1145,6 +1145,24 @@ $ meshterm --absolute chat history --to Alice takes the rest of the line. A message body is the one field that can hold any text, so no column can follow it. +**Relays.** A channel has no acknowledgement. But your radio hears the repeaters that relay +your message, and each copy names the relays that it went through. The `history` of a +channel has a `HEARD` column for each of your own messages: + +```console +$ meshterm chat history --channel 0 +TIME DIR PEER SNR_DB HEARD TEXT + 12m in Public +6.5 - Alice: anyone on the ridge? + 10m out Public - 2 heading up now + 4m out Public - none at the top + now out Public - wait coming down +``` + +A number is the count of repeaters that sent a copy back. `none` means that no repeater +sent it back. `wait` means that the message is still in its wait (the `heard_wait_s` +preference). MeshTerm sees only the relays that your radio hears, and only while it is +connected. A received message has no value (`-`). + **Rooms.** A room server is a message board that lives on a radio. First, join the room with [`meshterm rooms join`](#meshterm-rooms). After that, post with `send --to`, in the same way as a direct message. `acked yes` means that the room stored the post. It does @@ -1222,7 +1240,9 @@ $ meshterm chat send "all clear" --channel 0 --scope '*' --json the purpose of the one absence token. It is also the reason why the plain face prints nothing there: it has no way to say it. -`history` is an array, with the oldest message first: +`history` is an array, with the oldest message first. Each record also has `heard` +(`"waiting"`, `"heard"`, `"unheard"`, or `null` when the message is not your own channel +message) and `heard_by` (the hashes of the repeaters that sent a copy back): ```json {"created_at":"2026-09-08T08:27:37Z","direction":"out","node":{"name":"Alice","key":null,"hash":"d4e5f6a7","type":null,"self":false},"channel":null,"author":null,"snr_db":null,"text":"on my way","acked":true} @@ -2003,6 +2023,7 @@ weekly_flood_advert off off advert_quiet_s 30 30 Silence to wait for before the weekly advert direct_message_soft_retries 0 0 Times to resend a message that gets no reply message_parts_max 3 3 Send a long message as this many parts at most +heard_wait_s 30 30 Wait this long for a relay of a channel message room_relogin_minutes 30 30 Opening a room this quiet logs in again tx_opt_min 18 18 Weakest power it will try tx_opt_max 28 28 Strongest power it will try @@ -2072,7 +2093,7 @@ code beside each link. The scripted face prints only the link. **`--json`:** ```json -{"page":"discord","title":"Join Discord","version":"0.13.0","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n β€’ https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]} +{"page":"discord","title":"Join Discord","version":"1.0.0","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n β€’ https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]} ``` | Field | Type | Meaning | diff --git a/docs/devices/cardputer-zero.md b/docs/devices/cardputer-zero.md index f32c7a7..bc22c3d 100644 --- a/docs/devices/cardputer-zero.md +++ b/docs/devices/cardputer-zero.md @@ -180,6 +180,7 @@ The Cardputer Zero has no LoRa radio built in. You can add one in three ways: | Radio | Status | | --- | --- | | **Cap LoRa-1262** add-on board from M5Stack | Works, with no setup. MeshTerm runs the mesh node itself while it is open, as it does on a uConsole. | +| **Cap LoRa868**, the earlier add-on board | Works, with no setup. It is the same radio with no antenna switch (refer to [The older Cap LoRa868](#the-older-cap-lora868)). | | A MeshCore companion on USB | Expected to work as on any Linux computer. | | A MeshCore companion over Bluetooth | Expected to work as on any Linux computer. | @@ -198,8 +199,11 @@ says that power without the antenna can permanently damage the radio. 3. Push the Cap onto the expansion header at the back. 4. Turn on the Cardputer Zero, and start MeshTerm. -The device screen lists the Cap as **Cap LoRa-1262**. `meshterm --spi` also reaches it from the -command line. +The device screen lists the Cap as **Cap LoRa**. It cannot say more before it connects, +because a radio on the SPI bus answers nothing until MeshTerm starts the node on it. After +the first connection, the hardware column of the device screen names the Cap that +answered: **Cap LoRa-1262**, or **Cap LoRa868** for the older one. `meshterm --spi` also +reaches the Cap from the command line. The Cap has no MeshCore firmware of its own. It is only a radio chip. Thus, while MeshTerm is open, MeshTerm is the node, as it is on the AIO board of a uConsole. MeshTerm needs the @@ -227,6 +231,45 @@ A new node starts with the US/Canada settings of MeshCore (910.525 MHz). In othe change the settings on **Device config** before you send anything. MeshTerm keeps the key, the contacts, and the channels of the node in `~/.meshterm/radio/spidev0.1/`. +#### The older Cap LoRa868 + +M5Stack made an earlier LoRa Cap, the **Cap LoRa868**. MeshTerm works with it as well, +and you do nothing to make it work. + +The two Caps are almost the same board. Each one has an SX1262 radio and a GNSS +receiver, on the same pins of the same 14-pin header. The newer Cap LoRa-1262 adds an +antenna switch, and a small chip at I2C address `0x43` that turns that switch on. The +older Cap has no antenna switch, so it has no such chip. + +MeshTerm finds out which Cap you have each time it connects: + +1. It powers the header. +2. It looks for the switch chip at `0x43`, for one second. +3. If the chip answers, the Cap is a Cap LoRa-1262, and MeshTerm turns the antenna + switch on. +4. If nothing answers, MeshTerm starts the radio and asks the radio what it is. An + SX1262 that gives its name is the older Cap, and MeshTerm continues. + +Step 4 is the reason why a Cap that is absent, or that is not pushed fully onto the +header, is still reported as absent. Only a radio that answers for itself is accepted. + +#### If MeshTerm says that it cannot find the radio + +Two messages are possible, and they mean different things. + +**"Nothing answers at 0x43 on /dev/i2c-1"** comes from a profile of your own that +requires the switch chip. MeshTerm's own wiring for the Cap does not require it. Set +`pi4io_required = false` in your profile, or remove the `pi4io_bus` line from it (refer +to [Board wiring](uconsole.md#board-wiring)). + +**"No radio answered on the SPI bus"** means what it says. Turn the Cardputer +Zero off, push the Cap fully onto the header at the back, and check that no row of pins +is left over at either end. Then turn it on again. Never add or remove a Cap while the +device is on. + +The node writes what it did to `~/.meshterm/radio/spidev0.1/node.log`. That file names +the wiring it used and the answer it got from the bus. Send it with a problem report. + #### The Cap's GPS The Cap also has a GPS. MeshTerm can use it to keep the position of your node current. The diff --git a/docs/devices/uconsole.md b/docs/devices/uconsole.md index 736903e..fc98991 100644 --- a/docs/devices/uconsole.md +++ b/docs/devices/uconsole.md @@ -318,6 +318,7 @@ en_pins = [27] # the AIO v2 needs this | `en_pins` | `[]` | The power-enable lines that go high before MeshTerm touches the chip. The **AIO v2 needs `[27]`.** | | `leds` | `[]` | Switches that the device tree of the board shows as LEDs (under `/sys/class/leds/`). Write each one as `"name=brightness"`. MeshTerm sets them before it touches the chip. It puts them back as they were when it releases the radio. The Cardputer Zero powers its expansion header in this way. Its Cap needs no profile, but this is what you would write: `["ext_5v_out=1", "ext_usb_gpio_fun=0"]`. | | `pi4io_bus`, `pi4io_address`, `pi4io_high` | `-1`, `0x43`, `[]` | A PI4IOE5V6408 I/O expander that switches the antenna path of the radio. These are its I2C bus (`-1` for none), its address, and the pins that go high. | +| `pi4io_required` | `true` | Whether the radio works only with that expander. `false` says that the board has two revisions, one with the expander and one without it. An expander that does not answer is then the revision without it, and MeshTerm continues after the radio itself answers. The Cap of the Cardputer Zero is set this way. | | `use_dio2_rf`, `use_dio3_tcxo` | `true`, `true` | If DIO2 drives the RF switch, and if DIO3 drives a TCXO (both are on for the AIO). | | `is_waveshare` | `false` | The wiring quirks of the Waveshare HAT, which the radio library knows. | | `python` | `""` (empty) | An interpreter to run the node under. Use it when the interpreter that MeshTerm finds is not the one that you want. If it is empty, MeshTerm looks for one. | diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index c059173..4875d90 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -93,9 +93,11 @@ to install the library. **Two boards need no configuration.** The wiring of an AIO v1 is the MeshTerm default. Thus, when `/dev/spidev1.0` exists, the device screen lists it. The name is **uConsole AIO** -on a uConsole, and **SPI radio** on any other machine. MeshTerm also includes the Cap -LoRa-1262 of M5Stack on a Cardputer Zero. The device screen lists it as **Cap LoRa-1262** -on a Cardputer Zero (refer to [the Cardputer Zero page](../devices/cardputer-zero.md#the-cap-lora-1262)). +on a uConsole, and **SPI radio** on any other machine. MeshTerm also includes the LoRa +Cap of M5Stack on a Cardputer Zero. The device screen lists it as **Cap LoRa**, because +until MeshTerm connects, nothing can say which of the two Caps is attached. After it +connects, the hardware column names the one that answered (refer to [the Cardputer Zero +page](../devices/cardputer-zero.md#the-cap-lora-1262)). For either board, `meshterm --spi` reaches the radio. To add any other board, write a profile that states how the board is wired. A profile on the same `/dev/spidev*` replaces the wiring that MeshTerm includes. diff --git a/docs/guide/features.md b/docs/guide/features.md index d502511..de8d3e2 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -15,7 +15,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **πŸ’¬ Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. Select a message and press **^E** to react to it with an emoji. The reaction shows under the message, and MeshCore One and meshcore-open show it too. The emoji that ^E offers are a preference. A message that is too long for one packet goes out as parts, each ending with its number (`[1/3]`). MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` | +| **πŸ’¬ Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. Select a message and press **^E** to react to it with an emoji. The reaction shows under the message, and MeshCore One and meshcore-open show it too. The emoji that ^E offers are a preference. A message that is too long for one packet goes out as parts, each ending with its number (`[1/3]`). MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Your own channel message shows whether a repeater relayed it: a spinner, then `βœ“` and the number of repeaters that sent a copy back, or `βœ—` when none did. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` | | **πŸ“» Channels** | Create, join, reorder, mute, and share mesh channels. You can share a channel with a QR code or a `meshcore://` link. If you give a channel a **send scope**, its messages are flooded into one region. Only the repeaters that carry that region relay them. When you change to a new device, export all the channels to a file, then import the file on the new device. The **channel guide** lists the public channels that MeshTerm heard, also the channels that are not on your device, and adds one with Enter. | `meshterm channels list / add / join / import / share / clear / scope / export / guide` | | **πŸ“Œ Rooms** | Each room server that your radio knows. A room server is a message board on a radio. It keeps the latest posts and sends you the posts that you missed. Join a room with its password. If a room does not answer, MeshTerm tells you what it knows and offers the next step to try. For example, it can send again by flood when the route that your radio learned is no longer good. When the clock of a room goes back (often after a reboot), the room sends you no new post, because each new post looks older than the ones that you have. The node page of the room then says so and offers to ask for all its posts again. | `meshterm rooms list / join / forget` | | **πŸ“¨ Courier** | A store-and-forward outbox for contacts that you cannot reach yet. Queue a message. MeshTerm sends it when the contact is next heard, or at a time that you set. It tracks the acks, and it waits longer between each try (exponential backoff). | `meshterm courier queue / list / send / cancel / clear` | @@ -48,7 +48,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **πŸ“‹ Device info** | The identity of the connected companion and its full radio configuration, on one screen. | `meshterm info` | +| **πŸ“‹ Device info** | Everything that the connected companion knows about itself, on one screen. A status panel names the node, its key, its firmware and companion protocol version, and the place where it says it is. Then it names what MeshTerm does with the node: its flood scope and the key of that scope, the site and the outbound paths that apply here, and its radio preset. Then it names how the node is doing: the battery, the storage, its own sensor readings, the clock and its drift, the uptime, the contacts and channels against the capacities of the device, the packets that wait to go out, and the firmware errors. Last, it names what the node heard and sent, with the packet counts split into flood and direct. Under the panel is every setting of the device. The scripted face gives the same three parts: the status, the sensor readings, and every setting under the keys that `config get` and `config set` take. | `meshterm info` | | **πŸ”§ Device config** | Each setting that the companion firmware has: name, radio, client repeat, auto-add, telemetry, and custom variables. MeshTerm stages your changes for review and then applies them in place. The screen also has operations on the device itself: clock sync, TOML backup and restore, the identity key, reboot, and factory reset. Each operation acts when you confirm it, and the destructive operations need a confirm step. The screen has the same layout as Repeater admin. Thus you configure the radio in your hand and a radio over the mesh in the same way. | `meshterm config` / `config set ` / `config backup` / `config reboot` / … | | **πŸ“‘ Send advert** | Announce this node to the mesh with a zero-hop advert or a flood advert. You can also share the contact card of this node as a QR code. | `meshterm config advert` / `config share` | | **πŸ”Œ Devices** | This is not a menu screen. You select the companion on the startup splash. The splash lists the serial companions and the Bluetooth LE companions. If only one companion is present, MeshTerm selects it. You can add a network (TCP) companion with host:port. MeshTerm remembers the last good default. If the link drops, MeshTerm detects it at once and offers to reconnect. `meshterm devices` lists what discovery finds. | `meshterm devices` | @@ -70,13 +70,58 @@ only describe it. The written pages are at the end. | Feature | What it does | Scripted | | --- | --- | --- | -| **βš™ Preferences** | How MeshTerm behaves, in eight groups: Device, Sending, TX optimize, Watchtower, Map, History, Display, and Diagnostics. The page stages your changes, and you save them with one action at the bottom. MeshTerm writes only the values that you changed to `preferences.toml`. [Configuring MeshTerm](configuration.md) has the detail. | `meshterm preferences show / set / reset` | +| **βš™ Preferences** | How MeshTerm behaves, in nine groups: Device, Sending, TX optimize, Watchtower, Map, History, Sound, Display, and Diagnostics. The page stages your changes, and you save them with one action at the bottom. MeshTerm writes only the values that you changed to `preferences.toml`. [Configuring MeshTerm](configuration.md) has the detail. | `meshterm preferences show / set / reset` | | **🩺 Diagnostics** | One block of information that each bug report starts with. It shows which build you have and how you installed it, the operating system, the terminal and its size, and the radio and its link. It also shows the verdicts from boot time that no other screen shows (icons, powerline, platform flavour, and the reasons), and how much history MeshTerm stored. It has nothing private: no keys, passwords, positions, or contact names. It describes the mesh only as counts for each table and the span of time that the tables cover. Press `a` to anonymize it: your account name in the home folder and the addresses of your radio and hosts are masked, and each keeps a tidbit (`j*********u`, `DA:xx:xx:xx:7C:7C`). Press `s` to save the block beside the log, to attach to a report. The **Anonymize** preference opens the page anonymized, and masks the log too. | `meshterm diagnostics [--out PATH] [--anonymize]` | -| **πŸ“– About MeshTerm** | What MeshTerm is, where it came from, and the terms of its licence. It includes the map credit, the font credit, and the licence URL. | `meshterm about` | +| **πŸ“– About MeshTerm** | What MeshTerm is, where it came from, and the terms of its licence. It includes the map credit, the font credit, the sound credit, and the licence URL. | `meshterm about` | | **πŸ‘€ About the author** | The person behind MeshTerm, on the mesh and away from it. | `meshterm about-author` | | **πŸ”— Join Discord** | The community server. The page has one invite link and a QR code of the link, which a phone can read. | `meshterm discord` | | **πŸ’° Support MeshTerm** | What keeps MeshTerm going, and the ways to help it, with money and without money. | `meshterm support` | +## Sounds + +MeshTerm plays a sound when something arrives that you want to know about now. Each event +has its own sound, and its own switch on the Preferences page: + +| Event | When it plays | Default | +| --- | --- | --- | +| Direct message | A DM arrives | on | +| Mention | A message in a channel or a room mentions your node (`@[Your name]`). A mention in a DM plays the DM sound | always | +| Channel message | A message arrives on a channel | on | +| Room post | A room sends a new post | on | +| Battery low | The battery goes below the **Low level** (25%). It plays one time, and again only after the battery is 5 points higher or charges | on | +| Packet tick | A very short tick for each packet heard that plays no other sound, at most four times each second | off | + +A channel that you muted (πŸ”•) is silent, because the mute turns off all of its +notifications. The **On-screen chat** switch (on by default) decides whether the +conversation that is open on the screen plays its sounds too. + +**Mention** has three values: + +- **always** (the default): the mention sound plays, also on a muted channel, with the + **Channel message** or **Room post** switch off, and with **On-screen chat** off. +- **on**: the mention sound plays, under the same rules as other messages. +- **as a message**: a mention is a channel message or a room post, with their sound and + their rules. + +**Ctrl+S** mutes or unmutes the sounds from any screen. The header shows πŸ”Š while the +sounds play and πŸ”‡ while they are muted. The **Sound** row above Quit in the main menu +does the same. To have no sound at all, select the **no sound** theme on the Preferences +page. The other themes are **Android** (the default) and **terminal bell**, which rings the +bell of your terminal, also over SSH. + +**Volume** is a slider with ten steps on the Preferences page. Each step plays the +channel message sound, so that you hear the level before you apply it. + +When no sound plays, the title of the screen can flash instead. The **Flash** preference +selects when: off, on, or **when silent** (the default), which flashes when the sounds are +muted or the theme is no sound. The PicoCalc has no sound, so there each notification +flashes. + +MeshTerm plays the sounds through the player of your computer: MCI on Windows, `afplay` on +macOS, and `pw-play`, `paplay`, or `aplay` on Linux. Two sounds can play at the same time: +a new sound does not stop one that plays. If no player works, MeshTerm writes one line in +its log and continues with no sound. + ## Leaving MeshTerm **Quit** at the bottom of the main menu leaves MeshTerm, after it asks you to confirm. diff --git a/docs/screenshots/cardputer-zero/chat.png b/docs/screenshots/cardputer-zero/chat.png index 366330c..11c0958 100644 Binary files a/docs/screenshots/cardputer-zero/chat.png and b/docs/screenshots/cardputer-zero/chat.png differ diff --git a/docs/screenshots/cardputer-zero/map.png b/docs/screenshots/cardputer-zero/map.png index 0394c46..d4e83fe 100644 Binary files a/docs/screenshots/cardputer-zero/map.png and b/docs/screenshots/cardputer-zero/map.png differ diff --git a/docs/screenshots/cardputer-zero/mcoimg.png b/docs/screenshots/cardputer-zero/mcoimg.png index 32d1b48..971786b 100644 Binary files a/docs/screenshots/cardputer-zero/mcoimg.png and b/docs/screenshots/cardputer-zero/mcoimg.png differ diff --git a/docs/screenshots/cardputer-zero/menu.png b/docs/screenshots/cardputer-zero/menu.png index 56ce0c9..d785e0e 100644 Binary files a/docs/screenshots/cardputer-zero/menu.png and b/docs/screenshots/cardputer-zero/menu.png differ diff --git a/docs/screenshots/picocalc-lyra/chat.png b/docs/screenshots/picocalc-lyra/chat.png index cfe9552..0efdf63 100644 Binary files a/docs/screenshots/picocalc-lyra/chat.png and b/docs/screenshots/picocalc-lyra/chat.png differ diff --git a/docs/screenshots/picocalc-lyra/map.png b/docs/screenshots/picocalc-lyra/map.png index fd251f5..1d6c075 100644 Binary files a/docs/screenshots/picocalc-lyra/map.png and b/docs/screenshots/picocalc-lyra/map.png differ diff --git a/docs/screenshots/picocalc-lyra/mcoimg.png b/docs/screenshots/picocalc-lyra/mcoimg.png index 29eab5d..c564633 100644 Binary files a/docs/screenshots/picocalc-lyra/mcoimg.png and b/docs/screenshots/picocalc-lyra/mcoimg.png differ diff --git a/docs/screenshots/picocalc-lyra/menu.png b/docs/screenshots/picocalc-lyra/menu.png index 95793fb..e788472 100644 Binary files a/docs/screenshots/picocalc-lyra/menu.png and b/docs/screenshots/picocalc-lyra/menu.png differ diff --git a/docs/screenshots/picocalc-lyra/paths.png b/docs/screenshots/picocalc-lyra/paths.png index fd70e9b..ddaea4f 100644 Binary files a/docs/screenshots/picocalc-lyra/paths.png and b/docs/screenshots/picocalc-lyra/paths.png differ diff --git a/docs/screenshots/terminal/chat.png b/docs/screenshots/terminal/chat.png index bc213de..c7007a4 100644 Binary files a/docs/screenshots/terminal/chat.png and b/docs/screenshots/terminal/chat.png differ diff --git a/docs/screenshots/terminal/map.png b/docs/screenshots/terminal/map.png index 210786d..6a4c16f 100644 Binary files a/docs/screenshots/terminal/map.png and b/docs/screenshots/terminal/map.png differ diff --git a/docs/screenshots/terminal/mcoimg.png b/docs/screenshots/terminal/mcoimg.png index 2984d1b..44ead34 100644 Binary files a/docs/screenshots/terminal/mcoimg.png and b/docs/screenshots/terminal/mcoimg.png differ diff --git a/docs/screenshots/terminal/menu.png b/docs/screenshots/terminal/menu.png index 5827116..43e7594 100644 Binary files a/docs/screenshots/terminal/menu.png and b/docs/screenshots/terminal/menu.png differ diff --git a/docs/screenshots/terminal/paths.png b/docs/screenshots/terminal/paths.png index 4aaf129..aeba9d8 100644 Binary files a/docs/screenshots/terminal/paths.png and b/docs/screenshots/terminal/paths.png differ diff --git a/meshterm/__init__.py b/meshterm/__init__.py index 0f36d59..d098ed0 100644 --- a/meshterm/__init__.py +++ b/meshterm/__init__.py @@ -6,7 +6,7 @@ Connects to a companion over USB, Bluetooth, or TCP. For Windows, macOS, and Lin from datetime import datetime -__version__ = "0.13.0" +__version__ = "1.0.0" __author__ = "Jean-Pierre Martineau" #: The year when MeshTerm was first published. The copyright span starts in this year. diff --git a/meshterm/assets/pages/about.md b/meshterm/assets/pages/about.md index 0c87787..a80c005 100644 --- a/meshterm/assets/pages/about.md +++ b/meshterm/assets/pages/about.md @@ -38,7 +38,7 @@ The UX is a bit different on the PicoCalc's 16-colour 53-column screen layout, b ### M5Stack Cardputer Zero The **Cardputer Zero** is the easiest of the three: MeshTerm is in **M5Stack**'s app store, so installing it takes a few keypresses. Both models work, the standard **Cardputer Zero** and the **Cardputer Zero Lite**. -- Add the **Cap LoRa-1262**, and MeshTerm runs the mesh node itself, straight over SPI, just like on the uConsole. The Cap's GPS works too. +- Add a LoRa Cap, and MeshTerm runs the mesh node itself, straight over SPI, just like on the uConsole. Both of M5Stack's Caps work, the **Cap LoRa-1262** and the older **Cap LoRa868**, and MeshTerm works out which one you have. The Cap's GPS works too. - Power the Cardputer off before you plug in or remove a Cap β€” the LoRa one included. M5Stack doesn't support hot-swapping Caps, and says it may cause the device to malfunction. - Put the antenna on the Cap before you power it on. M5Stack warns that the radio can be permanently damaged without it. @@ -69,6 +69,9 @@ Built on **MeshCore** *https://meshcore.io/* β€” its firmware and companion library β€” with Rich, prompt_toolkit, Typer, bleak, pyserial, pycryptodome, markdown-it-py, tomli/tomli-w, and Segno, each under its own terms. +The notification sounds come from the **Android Open Source Project** +*https://source.android.com/*, under the same Apache License as MeshTerm. + Map data **Β© OpenStreetMap contributors**, served as vector tiles by **OpenFreeMap** *https://openfreemap.org/* on the **Β© OpenMapTiles** schema *https://openmaptiles.org/*, used under the **ODbL** diff --git a/meshterm/assets/sounds/android/Ariel.wav b/meshterm/assets/sounds/android/Ariel.wav new file mode 100644 index 0000000..4069ba7 Binary files /dev/null and b/meshterm/assets/sounds/android/Ariel.wav differ diff --git a/meshterm/assets/sounds/android/Carme.wav b/meshterm/assets/sounds/android/Carme.wav new file mode 100644 index 0000000..500d544 Binary files /dev/null and b/meshterm/assets/sounds/android/Carme.wav differ diff --git a/meshterm/assets/sounds/android/Ceres.wav b/meshterm/assets/sounds/android/Ceres.wav new file mode 100644 index 0000000..c033dc5 Binary files /dev/null and b/meshterm/assets/sounds/android/Ceres.wav differ diff --git a/meshterm/assets/sounds/android/Effect_Tick.wav b/meshterm/assets/sounds/android/Effect_Tick.wav new file mode 100644 index 0000000..7715de8 Binary files /dev/null and b/meshterm/assets/sounds/android/Effect_Tick.wav differ diff --git a/meshterm/assets/sounds/android/InCallNotification.wav b/meshterm/assets/sounds/android/InCallNotification.wav new file mode 100644 index 0000000..eaec910 Binary files /dev/null and b/meshterm/assets/sounds/android/InCallNotification.wav differ diff --git a/meshterm/assets/sounds/android/LowBattery.wav b/meshterm/assets/sounds/android/LowBattery.wav new file mode 100644 index 0000000..46cd600 Binary files /dev/null and b/meshterm/assets/sounds/android/LowBattery.wav differ diff --git a/meshterm/assets/sounds/android/README.md b/meshterm/assets/sounds/android/README.md new file mode 100644 index 0000000..877af7f --- /dev/null +++ b/meshterm/assets/sounds/android/README.md @@ -0,0 +1,25 @@ +# The Android sound theme + +These are the sounds of the `android` sound theme. MeshTerm plays them for its +notifications (refer to `meshterm/services/sound.py`). + +| File | Event | Source in AOSP `data/sounds` | +| --- | --- | --- | +| `Carme.wav` | Direct message | `notifications/material/ogg/Carme.ogg` | +| `Ariel.wav` | Mention of you | `notifications/material/ogg/Ariel.ogg` | +| `InCallNotification.wav` | Channel message | `effects/ogg/InCallNotification.ogg` | +| `Ceres.wav` | Room post | `notifications/material/ogg/Ceres.ogg` | +| `LowBattery.wav` | Battery low | `effects/ogg/LowBattery.ogg` | +| `Effect_Tick.wav` | Packet tick | `effects/ogg/Effect_Tick.ogg` | + +The sources are from the Android Open Source Project, `platform/frameworks/base` at +commit `1cdfff555f4a21f71ccc978290e2e212e2f8b168`. `scripts/sounds.py` makes these files +from them again. + + +Copyright The Android Open Source Project. Licensed under the Apache License, +Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). + +Modified by MeshTerm: each file was decoded from Ogg Vorbis, mixed down to one +channel, and written as 16-bit PCM WAV at its original sample rate. + diff --git a/meshterm/context.py b/meshterm/context.py index 7542d9d..d06cf7a 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -52,6 +52,7 @@ if TYPE_CHECKING: from .services.places import PlaceService from .services.rooms import RoomService from .services.site_suggest import SiteSuggester + from .services.sound import SoundService from .services.watchtower import WatchtowerService from .ui.surface import Ui @@ -202,6 +203,7 @@ class AppContext: _clock_sync: ClockSync | None = field(default=None, init=False, repr=False) _courier: CourierService | None = field(default=None, init=False, repr=False) _battery: BatteryService | None = field(default=None, init=False, repr=False) + _sound: SoundService | None = field(default=None, init=False, repr=False) _places: PlaceService | None = field(default=None, init=False, repr=False) _site_suggest: SiteSuggester | None = field(default=None, init=False, repr=False) _routes: RouteKeeper | None = field(default=None, init=False, repr=False) @@ -558,6 +560,20 @@ class AppContext: self._battery = BatteryService(self) return self._battery + @property + def sound(self) -> SoundService: + """Return the sound service of the session, and create it at first use. + + It plays the sound of a notification, and it flashes the title bar (refer to + :mod:`meshterm.services.sound`). It has no task. It acts only when a caller tells it + about an event. + """ + if self._sound is None: + from .services.sound import SoundService + + self._sound = SoundService(self) + return self._sound + @property def devstate(self) -> DeviceState: """Return the device-state cache of the session, and create it at first use. diff --git a/meshterm/core/config.py b/meshterm/core/config.py index 5edadce..125545a 100644 --- a/meshterm/core/config.py +++ b/meshterm/core/config.py @@ -114,6 +114,12 @@ class SpiWiring: ``0x44`` when it is high. pi4io_high: The pins of the expander (0–7) that MeshTerm drives high before it touches the chip. Each other pin stays an input. + pi4io_required: Whether the radio works only with that expander. ``True``, the + default, makes an expander that does not answer an absent board. Set it to + ``False`` on a board that has two revisions, one with the expander and one + without it. A board that does not answer at that address is then the revision + without it, and MeshTerm continues. The Cap LoRa868 of the Cardputer Zero is + that revision of the Cap LoRa-1262. use_dio2_rf: Whether DIO2 drives the RF switch. use_dio3_tcxo: Whether DIO3 powers a TCXO. is_waveshare: The wiring quirks of the Waveshare HAT, which the radio library @@ -144,6 +150,7 @@ class SpiWiring: pi4io_bus: int = -1 pi4io_address: int = 0x43 pi4io_high: tuple[int, ...] = () + pi4io_required: bool = True use_dio2_rf: bool = True use_dio3_tcxo: bool = True is_waveshare: bool = False diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 9a44dd1..7b6784c 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -1216,6 +1216,50 @@ def serial_port_present(port: str) -> bool: return False +def lpp_readings(raw: object) -> list[dict]: + """Turn the Cayenne LPP frame of a telemetry answer into one dict for each reading. + + The library decodes the frame already. It gives a list of entries, each with the + channel that the reading came from, the kind of value (``type``, which is a word and + not a number), and the value itself. This function keeps those three fields, names the + kind ``name``, and drops anything that it cannot read. Thus a malformed answer costs + the readings that it broke, and not the page that shows them. + + Args: + raw: The ``lpp`` field of a telemetry answer. + + Returns: + One dict for each reading, with ``channel``, ``name``, and ``value``. + """ + readings: list[dict] = [] + for item in raw if isinstance(raw, list) else (): + if not isinstance(item, dict): + continue + name = str(item.get("type") or "").strip() + if not name: + continue + readings.append({"channel": item.get("channel"), "name": name, "value": item.get("value")}) + return readings + + +def derived_scope_key(name: str | None) -> str | None: + """Return the transport key that a scope name gives, or ``None`` when there is no name. + + Args: + name: A region name, bare or with its ``#``. An empty name means no scope. + + Returns: + The 16-byte key as lowercase hex, or ``None`` for no scope and for a name that no + region can carry. + """ + if not name: + return None + try: + return region_key(name).hex() + except Exception: # noqa: BLE001 - a name the firmware stored can still be invalid here + return None + + class Device(ABC): """An abstract companion device, with the operations that MeshTerm uses. @@ -1902,6 +1946,42 @@ class Device(ABC): is set, or ``None`` if the firmware is older than flood scopes. """ + async def get_default_flood_scope_detail(self) -> dict: + """Return the stored default flood scope: its name, and its transport key. + + The firmware sends both in one frame. :meth:`get_default_flood_scope` gives only + the name, because that is all a send needs. The Device info page also shows the + key, so that the user can compare what the device stores with what the name gives. + + A transport that cannot report the key derives it from the name + (:func:`~meshterm.core.regions.region_key`), because the key is a pure function of + the name. A transport that reads the frame overrides this method and returns the + key of the device itself. Thus a device that stores a key that does not match its + own name is visible. + + Returns: + ``{"name": str | None, "key": str | None}``. The name is ``""`` when no scope + is set, and ``None`` on firmware that is older than flood scopes. The key is + lowercase hex, or ``None`` when there is no scope. + """ + name = await self.get_default_flood_scope() + return {"name": name, "key": derived_scope_key(name)} + + async def get_self_telemetry(self) -> list[dict]: + """Return the sensor readings of this node, as the firmware reports them. + + The firmware answers with a Cayenne LPP frame: one entry for each reading, each + with the channel that it came from and the kind of value that it holds. Firmware + that does not support the query, and a transport that cannot ask, both answer with + an empty list. Thus a caller never has to test which device it has. + + Returns: + One dict for each reading: ``channel`` (int), ``name`` (the kind of reading, + for example ``temperature``), and ``value`` (a number, or a dict of fields for + a reading that has several). + """ + return [] + @abstractmethod async def get_time(self) -> int | None: """Return the device clock as a UNIX epoch timestamp, or ``None`` if not known.""" @@ -4643,13 +4723,28 @@ class MeshCoreDevice(Device): ] async def get_default_flood_scope(self) -> str | None: # noqa: D102 + detail = await self.get_default_flood_scope_detail() + name = detail.get("name") + return None if name is None else str(name) + + async def get_default_flood_scope_detail(self) -> dict: # noqa: D102 event = self._ok(await self._require().commands.get_default_flood_scope()) payload = getattr(event, "payload", {}) or {} name = payload.get("scope_name") + key = payload.get("scope_key") # Return the name bare, whatever client wrote it. MeshTerm (before it built its own # frames) and the library (still now) stored a ``#`` that the firmware and the apps - # do not use. - return None if name is None else normalize_region(str(name)) + # do not use. The key comes from the same frame, so it is the key of the device and + # not a key that MeshTerm derived. + return { + "name": None if name is None else normalize_region(str(name)), + "key": str(key).lower() or None if key else None, + } + + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 + event = self._ok(await self._require().commands.get_self_telemetry()) + payload = getattr(event, "payload", {}) or {} + return lpp_readings(payload.get("lpp")) async def get_time(self) -> int | None: # noqa: D102 - inherited docstring event = self._ok(await self._require().commands.get_time()) @@ -5217,10 +5312,22 @@ class MockDevice(Device): "model": "MeshCore Simulator", "ver": "mock", "fw_build": "mock", + "fw ver": 12, + "max_contacts": 300, + "max_channels": self._max_channels, "ble_pin": self._device_pin, "repeat": self._client_repeat, } + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 - inherited docstring + # The readings that almost every board reports: the battery on channel 0, and one + # environment sensor. Thus the Device info page has a telemetry block to draw. + return [ + {"channel": 0, "name": "voltage", "value": 4.1}, + {"channel": 0, "name": "percentage", "value": 86}, + {"channel": 1, "name": "temperature", "value": 21.5}, + ] + async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring return list(self._contacts) diff --git a/meshterm/core/device_config.py b/meshterm/core/device_config.py index 5f564a6..ce44906 100644 --- a/meshterm/core/device_config.py +++ b/meshterm/core/device_config.py @@ -274,9 +274,10 @@ async def build_snapshot( Returns: A dict with the keys of ``SELF_INFO``, and also ``rx_delay``, ``airtime_factor``, ``path_hash_mode``, ``autoadd_config``, - ``autoadd_max_hops``, and ``flood_scope``. Below these, it has the facts of the - device-query frame (``ble_pin``, ``model``, client ``repeat``). If the firmware - can relay, the dict also has its ``repeat_freqs``. + ``autoadd_max_hops``, ``flood_scope``, and ``flood_scope_key``. Below these, it + has the facts of the device-query frame (``ble_pin``, ``model``, ``fw ver``, + ``max_contacts``, ``max_channels``, client ``repeat``). If the firmware can relay, + the dict also has its ``repeat_freqs``. """ snapshot = dict(self_info if self_info is not None else await device.get_self_info()) try: @@ -300,10 +301,16 @@ async def build_snapshot( hops = None if hops is not None: snapshot["autoadd_max_hops"] = hops + # One read gives the scope name and the transport key that the device stores for it. + # The settings registry uses the name. The Device info page shows the key beside it. try: - snapshot["flood_scope"] = await device.get_default_flood_scope() + scope = await device.get_default_flood_scope_detail() except Exception: # noqa: BLE001 - an optional read. Its absence is acceptable. - pass + scope = {} + if scope.get("name") is not None: + snapshot["flood_scope"] = scope["name"] + if scope.get("key"): + snapshot["flood_scope_key"] = scope["key"] # The device-query frame is a payload that is different from SELF_INFO, and some # settings are only there. One of them is the BLE pairing code: real firmware reports # it as ``ble_pin``, and never puts it in SELF_INFO. Without this read, the Device PIN diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 206aec9..72afb52 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -50,6 +50,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any +from ..platforms import ALL_PLATFORMS from .advert_store import DEFAULT_QUIET_S, QUIET_CHOICES_S from .atomicwrite import write_atomically from .courier_store import DONE_CAP @@ -75,6 +76,7 @@ GROUPS: tuple[str, ...] = ( "Watchtower", "Map", "History", + "Sound", "Display", "Diagnostics", ) @@ -109,6 +111,9 @@ class PrefSpec: relaunch: Whether the new value applies only at the next start. It is part of the description, instead of a mark of its own, because it is a caveat about one preference. It is not a status that the user looks for in a column. + question: The question of the dialog that edits the value, when the short help of + the row does not read as one ("When a DM plays a sound"). ``""`` (the default) + asks with the help. platforms: The :class:`~meshterm.platforms.Platform` names on which the page offers the preference, or ``None`` (the default) for all of them. Some preferences are about hardware that only one flavour has (the console font @@ -132,6 +137,7 @@ class PrefSpec: unit: str = "" relaunch: bool = False platforms: frozenset[str] | None = None + question: str = "" @property def description(self) -> str: @@ -155,6 +161,33 @@ class PrefSpec: #: sees, not the mechanism: an age is how long ago, and a timestamp is when. _CLI_TIME_CHOICES: dict[str, str] = {"relative": "ages", "absolute": "timestamps"} +#: The platforms that can play a sound (:attr:`~meshterm.platforms.Platform.sound`). The +#: Preferences page offers the sound preferences only there. A notification on the other +#: platforms is silent, and only the title bar can flash for it. +_SOUND_PLATFORMS: frozenset[str] = frozenset(p.name for p in ALL_PLATFORMS if p.sound) + +#: The sound themes (refer to :data:`meshterm.services.sound.THEMES`). ``android`` plays the +#: sounds of ``meshterm/assets/sounds/android``. ``bell`` sends the terminal bell (BEL) for +#: each event, which rings on the computer of the user also over SSH. ``none`` plays +#: nothing. +_SOUND_THEME_CHOICES: dict[str, str] = { + "android": "Android", + "bell": "terminal bell", + "none": "no sound", +} + +#: When the title bar flashes for a notification. ``silent`` flashes only when no sound +#: plays for it: the sounds are muted, the theme is ``none``, the platform has no sound, or the +#: player failed. +_FLASH_CHOICES: dict[str, str] = {"off": "off", "on": "on", "silent": "when silent"} + +#: How a mention of our node plays (JP, 2026-11-21). ``always`` plays the mention sound +#: also where the message would make no sound: on a muted channel, with the switch of its +#: kind off, and in the open conversation. ``on`` plays the mention sound under the same +#: rules as other messages. ``regular`` treats the mention as a channel message or a room +#: post. A mention in a DM is never a mention here: it plays the DM sound. +_MENTION_CHOICES: dict[str, str] = {"always": "always", "on": "on", "regular": "as a message"} + #: The sources of the place of a node (refer to :mod:`meshterm.services.places`). With #: ``tiles_nominatim``, the map tiles give the first answer at once, and Nominatim corrects it #: later, when MeshTerm is online, because only Nominatim knows the boundaries of a place. @@ -273,6 +306,20 @@ PREFERENCES: tuple[PrefSpec, ...] = ( # meshterm.services.site_suggest. default=True, ), + PrefSpec( + key="public_on_empty_device", + label="Public on an empty radio", + help="Add the standard Public channel to a radio that has none", + group="Device", + value_type="bool", + # On: a radio with no channel at all cannot send anywhere (each send needs a slot), + # and a new user reads an empty Chat as "nobody is here". MeshTerm writes the + # channel that MeshCore itself ships, on slot 0 at startup, and says so. The write + # overwrites nothing, because the device had no channel. Off: nothing is written, + # and the Chat picker still offers Public on its own. Refer to + # meshterm.ui.public_default. + default=True, + ), # --- Sending ----------------------------------------------------------------- PrefSpec( key="trace_cooldown_s", @@ -350,6 +397,21 @@ PREFERENCES: tuple[PrefSpec, ...] = ( minimum=1, maximum=9, ), + PrefSpec( + key="heard_wait_s", + label="Relay wait", + help="Wait this long for a relay of a channel message", + group="Sending", + value_type="int", + # A channel message that we sent shows a spinner until a repeater sends a copy + # back, or until this wait is over. Then it shows βœ— (no copy). A repeater relays + # in seconds, and 30 s also covers a busy channel (refer to + # meshterm.services.heard_by). + default=30, + minimum=5, + maximum=600, + unit="s", + ), PrefSpec( key="room_relogin_minutes", label="Room re-login", @@ -484,6 +546,152 @@ PREFERENCES: tuple[PrefSpec, ...] = ( value_type="str", default="https://nominatim.openstreetmap.org", ), + # --- Sound --------------------------------------------------------------------- + PrefSpec( + key="sound_theme", + label="Sound theme", + help="Which set of sounds to use", + group="Sound", + value_type="enum", + # Android, and not muted (JP, 2026-11-20). "No sound" is a theme, not a mute: the + # user who wants no sound at all selects it. + default="android", + choices=_SOUND_THEME_CHOICES, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_muted", + label="Mute", + help="Silence all sounds (^S)", + question="Mute all sounds? ^S does the same on any screen", + group="Sound", + value_type="bool", + # A mute is for now, and the theme is for always. ^S changes this preference from + # any screen, and the header shows its state (πŸ”Š on, πŸ”‡ muted). + default=False, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_volume", + label="Volume", + help="How loud sounds play", + question="How loud sounds play, from 1 (10%) to 10 (100%)", + group="Sound", + value_type="int", + # A slider of ten steps (JP, 2026-11-20). MeshTerm scales the samples itself, so + # that the volume is the same with each player. + default=7, + minimum=1, + maximum=10, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="notify_flash", + label="Flash", + help="Flash the title on new messages", + question="When should the title flash for a new message?", + group="Sound", + value_type="enum", + # When silent: the flash replaces a sound that does not play, and it does not add to + # one that does. On the PicoCalc, which has no sound, each notification flashes. + default="silent", + choices=_FLASH_CHOICES, + ), + # One switch for each sound event (JP, 2026-11-21: "These events should have on/off + # setting. All default to on, except packet tick"). A muted channel stays silent, and + # the conversation on the screen makes no sound. + PrefSpec( + key="sound_dm", + label="Direct message", + help="Sound for new direct messages", + question="Play a sound for new direct messages?", + group="Sound", + value_type="bool", + default=True, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_mention", + label="Mention", + help="Sound when someone names you", + question=( + "What plays when someone mentions you. Always: the mention sound, even on a" + " muted channel. On: the mention sound, unless the channel is muted. As a" + " message: the usual channel or room sound" + ), + group="Sound", + value_type="enum", + default="always", + choices=_MENTION_CHOICES, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_channel", + label="Channel message", + help="Sound for new channel messages", + question="Play a sound for new channel messages? Muted channels stay quiet", + group="Sound", + value_type="bool", + default=True, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_room", + label="Room post", + help="Sound for new room posts", + question="Play a sound for new room posts?", + group="Sound", + value_type="bool", + default=True, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_on_screen", + label="On-screen chat", + help="Play sounds for the open chat", + question="Play sounds for the chat you have open?", + group="Sound", + value_type="bool", + # On (JP, 2026-11-21): the user can look away from a screen that stays open. + default=True, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_battery", + label="Battery low", + help="Sound when the battery is low", + question="Play a sound when the battery gets low?", + group="Sound", + value_type="bool", + default=True, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="battery_low_pct", + label="Low level", + help="When the battery counts as low", + question="The battery is low below this level", + group="Sound", + value_type="int", + # 25: the level where the gauge of the header changes to its low band (batt.low). + default=25, + minimum=5, + maximum=90, + unit="%", + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="packet_tick", + label="Packet tick", + help="Tick for every other packet", + question="Play a short tick for each packet that has no sound of its own?", + group="Sound", + value_type="bool", + # Off: a busy mesh can send many packets each minute. The service plays at most one + # tick each 250 ms (JP, 2026-11-20). + default=False, + platforms=_SOUND_PLATFORMS, + ), # --- History kept ------------------------------------------------------------ PrefSpec( key="history_days", diff --git a/meshterm/core/radionode.py b/meshterm/core/radionode.py index ed2f103..a4c4d8f 100644 --- a/meshterm/core/radionode.py +++ b/meshterm/core/radionode.py @@ -58,6 +58,7 @@ from __future__ import annotations import argparse import asyncio import dataclasses +import errno import functools import json import logging @@ -84,7 +85,7 @@ BEGIN_BACKOFF_S = 1.5 #: The model string that the frame server reports for a radio on a board that MeshTerm #: does not know by name. MeshTerm shows it as the device model (the Cap reports -#: "Cap LoRa-1262"). +#: "Cap LoRa-1262", or "Cap LoRa868" where it found no expander). DEVICE_MODEL = "MeshTerm SPI node" log = logging.getLogger("radionode") @@ -300,11 +301,30 @@ LEDS = Path("/sys/class/leds") #: the chip does its own reset after this. POWER_SETTLE_S = 0.1 +#: How long the expander of a board gets to answer, after the header is powered on, and +#: before MeshTerm says that no board is attached. The first read comes after +#: :data:`POWER_SETTLE_S`, which is sufficient on the boards that we have. A board with a +#: slower power rail answers a moment later, and that must not read as an absent board. +#: :data:`PI4IO_RETRY_S` is the time between two tries, which is short, because a board +#: that is ready answers at once. +PI4IO_WAIT_S = 1.0 +PI4IO_RETRY_S = 0.05 + #: ``I2C_SLAVE``: point the open ``/dev/i2c-*`` at one device. The kernel refuses it #: (``EBUSY``) while a kernel driver is bound to that address. This is the correct answer, #: because then the device is not ours to use. _I2C_SLAVE = 0x0703 +#: The errors of a read that mean that nothing is at the address: the kernel found no +#: device there, or the device did not acknowledge. Each other error is a fault of the bus +#: or of this process, and must never read as an absent board. ENXIO and EREMOTEIO are the +#: two that a Linux I2C adapter gives for an address that nobody answers. EREMOTEIO is on +#: Linux alone, and this file is imported on each platform, so its number stands in where +#: the module does not have the name. +_ABSENT_ERRNOS = frozenset( + {errno.ENXIO, errno.ENODEV, errno.ETIMEDOUT, getattr(errno, "EREMOTEIO", 121)} +) + #: The registers of the PI4IOE5V6408, and the manufacturer field of its ID register (bits #: 7–5). This field tells a different chip at the same address apart from it. _PI4IO_ID, _PI4IO_DIRECTION, _PI4IO_OUTPUT, _PI4IO_HIGH_Z = 0x01, 0x03, 0x05, 0x07 @@ -342,7 +362,55 @@ def restore_leds(previous: list[tuple[Path, str]]) -> None: log.warning("could not put %s back to %s: %s", path, before, exc) -def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev")) -> None: +def _expander_id(fd: int, address: int, path: Path) -> int: + """Read the ID register of the expander at ``address``, and try again until it answers. + + The caller powers the header of the board a short time before this read. A board whose + power rail is slower than :data:`POWER_SETTLE_S` refuses the first read and answers + correctly a moment later. For this reason the function tries again until + :data:`PI4IO_WAIT_S` is spent, and calls the board absent only then. + + The log line carries the error of the last try. The sentence that the user reads cannot + carry it, because a refused address and a broken bus are the same thing to that user. + They are not the same thing to us, and only the log can tell them apart afterwards. + + Args: + fd: The open bus, already pointed at the address. + address: The address of the expander, for the message. + path: The bus device file, for the message. + + Returns: + The byte in the ID register. + + Raises: + NodeError: ``absent``, when nothing answered in the time above. + """ + deadline = time.monotonic() + PI4IO_WAIT_S + while True: + try: + os.write(fd, bytes([_PI4IO_ID])) + return os.read(fd, 1)[0] + except OSError as exc: + if exc.errno not in _ABSENT_ERRNOS: + raise NodeError( + "failed", f"{address:#04x} on {path} could not be read: {exc}" + ) from exc + if time.monotonic() >= deadline: + log.warning( + "no answer at %#04x on %s after %.1fs: %s", address, path, PI4IO_WAIT_S, exc + ) + raise NodeError("absent", f"nothing answers at {address:#04x} on {path}") from None + time.sleep(PI4IO_RETRY_S) + + +def drive_pi4io( + bus: int, + address: int, + high: list[int], + dev: Path = Path("/dev"), + *, + required: bool = True, +) -> bool: """Drive the ``high`` pins of a PI4IOE5V6408 high as outputs, and keep the rest as inputs. The function writes the output level before the direction. Thus a pin becomes an @@ -350,6 +418,26 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" register first. On a board where this is the expander of the radio itself, no answer there means that the radio is not attached. That is the one failure that the message must give in those words. + + A board that has two revisions is the exception (``required=False``). There an absent + expander is the revision that has none, and the node continues without it. The node + then proves that a radio is on the bus (refer to :func:`confirm_sx126x`), because + "no expander" and "no board at all" are the same thing at this point. + + Args: + bus: The I2C bus of the expander. + address: Its address. + high: The pins that go high. + dev: The directory of the device files, for the tests. + required: Whether an absent expander is a failure. + + Returns: + Whether the expander answered. + + Raises: + NodeError: ``no-i2c`` or ``permission`` for the bus, ``busy`` when a driver holds + the address, ``failed`` when the bus itself failed, and ``absent`` when nothing + answered and ``required`` is set. """ path = dev / f"i2c-{bus}" _check_device(str(path), "no-i2c", "I2C bus") @@ -363,10 +451,14 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" except OSError as exc: raise NodeError("busy", f"{address:#04x} on {path} is held: {exc}") from None try: - os.write(fd, bytes([_PI4IO_ID])) - ident = os.read(fd, 1)[0] - except OSError: - raise NodeError("absent", f"nothing answers at {address:#04x} on {path}") from None + ident = _expander_id(fd, address, path) + except NodeError as exc: + if exc.kind != "absent" or required: + raise + log.info( + "nothing at %#04x on %s: this board is the revision with no expander", address, path + ) + return False if ident >> 5 != _PI4IO_MAKER: raise NodeError( "absent", f"{address:#04x} on {path} is not a PI4IOE5V6408 (ID {ident:#04x})" @@ -380,31 +472,135 @@ def drive_pi4io(bus: int, address: int, high: list[int], dev: Path = Path("/dev" finally: os.close(fd) log.info("PI4IO %#04x on %s: pins %s high", address, path, high) + return True -def prepare_board(wiring: dict) -> list[tuple[Path, str]]: +#: What the user reads when no radio answered on the bus, however the node found out. The +#: three ways (the chip did not start, it did not answer a register read, it answered as +#: something else) are one thing to the user, and :func:`explain` adds the question about +#: the attachment. The log keeps which of the three it was. +NO_RADIO = "no radio answered on the SPI bus" + +#: The register where an SX126x holds its version string, how many bytes of it to read, +#: and the first bytes of what the string must be. A bus with no chip on it reads as all +#: ones or all zeros, and neither starts with these letters. +_VERSION_REGISTER, _VERSION_LENGTH, _SX126X = 0x0320, 16, b"SX126" + + +def confirm_sx126x(lora: Any) -> None: + """Refuse a radio that did not answer with the version string of an SX126x. + + This is for a board whose expander did not answer (refer to :func:`drive_pi4io`). + There, "this revision has no expander" and "no board is attached" look the same, and + only the chip can tell them apart. The library can start on a bus with nothing on it, + so the answer must come from the silicon. + + Args: + lora: The chip of the started radio. + + Raises: + NodeError: ``absent``, when the chip did not answer, or answered as something else. + """ + try: + signature = bytes(lora.readRegister(_VERSION_REGISTER, _VERSION_LENGTH)) + except Exception as exc: # noqa: BLE001 - any failure here means that nothing answered + log.warning("the version register could not be read: %s", exc) + raise NodeError("absent", NO_RADIO) from None + if not signature.startswith(_SX126X): + log.warning("the version register reads %r, which is not an SX126x", signature) + raise NodeError("absent", NO_RADIO) + name = signature.split(bytes(1))[0].decode("ascii", "replace") + log.info("the chip reports itself as %s", name) + + +def board_model(config: dict, expander: bool | None) -> str: + """The model that the node reports for the board it is on. + + The parent cannot know which revision of a board is attached, because nothing answers + on an SPI radio until the node runs. For this reason it sends the model of each + revision, and the node names the one that it found. A board with one revision has one + model, and the question does not come up. + + Args: + config: The configuration from the parent (``model``, and + ``model_without_expander`` for a board that has a revision with no expander). + expander: What :func:`prepare_board` found (``False`` for an absent one). + + Returns: + The model to report, or :data:`DEVICE_MODEL` for a board MeshTerm does not know. + """ + if expander is False: + without = str(config.get("model_without_expander") or "") + if without: + return without + return str(config.get("model") or DEVICE_MODEL) + + +def begin_failure(kind: str, detail: str, expander: bool | None) -> NodeError: + """The error that a failed ``radio.begin()`` gives the user. + + Usually this is the kind that the log lines of the library give, in the words of the + library (refer to :func:`classify_begin_failure`). A board whose expander did not + answer is the exception. Nothing has answered anywhere on that board, so the first + answer the user needs is that no radio is there. The words of the library stay in the + log. A busy line keeps its own kind, because a line that another program holds is a + cause of its own and has its own correction. + + Args: + kind: What :func:`classify_begin_failure` made of the lines of the library. + detail: The last line of the library. + expander: What :func:`prepare_board` found (``False`` for an absent one). + + Returns: + The error to raise. + """ + if expander is False and kind == "failed": + log.warning("the radio did not start: %s", detail) + return NodeError("absent", NO_RADIO) + return NodeError(kind, detail) + + +@dataclasses.dataclass(frozen=True) +class PreparedBoard: + """What :func:`prepare_board` switched on, and what it found there. + + Attributes: + switches: The LED-class switches that it set, each with the value that it had + before. :func:`restore_leds` puts them back. + expander: ``True`` when the expander of the board answered, ``False`` when the + wiring permits an absent one and none answered, and ``None`` when this wiring + has no expander at all. + """ + + switches: list[tuple[Path, str]] + expander: bool | None + + +def prepare_board(wiring: dict) -> PreparedBoard: """Switch on the parts that the chip must have before the radio library uses it. First the LED-class switches of the board (power, pin routing), then its RF expander. The node can get to the expander only after the header that it is on has power. The - function returns the previous states of the switches. The caller puts them back when - the node ends, also when the node did not start. Thus a failed start leaves the header - as it was. + function returns what it switched, and whether the expander answered. The caller puts + the switches back when the node ends, also when the node did not start. Thus a failed + start leaves the header as it was. """ previous = set_leds(list(wiring.get("leds") or ()), root=LEDS) if previous: time.sleep(POWER_SETTLE_S) + expander: bool | None = None try: if int(wiring.get("pi4io_bus", -1)) >= 0: - drive_pi4io( + expander = drive_pi4io( int(wiring["pi4io_bus"]), int(wiring.get("pi4io_address", 0x43)), list(wiring.get("pi4io_high") or ()), + required=bool(wiring.get("pi4io_required", True)), ) except BaseException: restore_leds(previous) raise - return previous + return PreparedBoard(switches=previous, expander=expander) # --- the GPS beside the chip --------------------------------------------------------------- @@ -663,8 +859,8 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non Args: config: ``state_dir``, ``wiring`` (the pins and switches of the board), ``seed`` (name and radio settings for a node that has no ``prefs.json`` yet), and - ``model`` (the name of the board, reported as the device model. Without it, - :data:`DEVICE_MODEL`). + ``model`` and ``model_without_expander`` (the name of the board, reported as + the device model. Refer to :func:`board_model`). report: Sends the one status line to the parent. Returns: @@ -687,27 +883,32 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non wiring = dict(config.get("wiring") or {}) seed = dict(config.get("seed") or {}) + # The log must say which wiring the node used. A board problem is reported with this + # file, and the wiring can come from a profile that the reporter wrote. + log.info("node wiring: %s", json.dumps(wiring, sort_keys=True)) + bus, cs = int(wiring.get("bus_id", 0)), int(wiring.get("cs_id", 0)) _check_device(f"/dev/spidev{bus}.{cs}", "no-spi", "SPI overlay") _check_device(f"/dev/gpiochip{int(wiring.get('gpio_chip', 0))}", "no-gpio", "GPIO chip") # The switches of the board go back to how they were, in any way that the node ends, # also when the radio did not start. Thus a failed start leaves the header as it was. - switched = prepare_board(wiring) + board = prepare_board(wiring) try: return await _serve( state, wiring, seed, report, - model=str(config.get("model") or DEVICE_MODEL), + expander=board.expander, + model=board_model(config, board.expander), models=models, sx1262=sx1262, companion_mod=companion_mod, identity_mod=identity_mod, ) finally: - restore_leds(switched) + restore_leds(board.switches) async def _serve( # noqa: PLR0913 - the library modules run_node imported, handed on @@ -716,6 +917,7 @@ async def _serve( # noqa: PLR0913 - the library modules run_node imported, hand seed: dict, report, # noqa: ANN001 - (dict) -> None *, + expander: bool | None, model: str, models: Any, sx1262: Any, @@ -767,11 +969,16 @@ async def _serve( # noqa: PLR0913 - the library modules run_node imported, hand pass if kind != "busy" or attempt == BEGIN_ATTEMPTS - 1: detail = recent.lines[-1] if recent.lines else "radio.begin() failed" - raise NodeError(kind, detail) + raise begin_failure(kind, detail, expander) await asyncio.sleep(BEGIN_BACKOFF_S * (attempt + 1)) logging.getLogger().removeHandler(recent) log.info("radio ready") + # The expander of this board did not answer, and the wiring permits that. Before the + # node accepts the board as the revision that has none, the chip itself must answer. + if expander is False: + confirm_sx126x(radio.lora) + try: seed_bytes = load_identity_seed( state, lambda: identity_mod.LocalIdentity().get_signing_key_bytes() diff --git a/meshterm/core/spiradio.py b/meshterm/core/spiradio.py index e2c0d56..dff7f91 100644 --- a/meshterm/core/spiradio.py +++ b/meshterm/core/spiradio.py @@ -226,7 +226,11 @@ def gpio_chip(wiring: SpiWiring) -> int: #: The header of the Cap has no power until the ``ext_5v_out`` switch of the device tree is #: on. Two of its pins (reset, interrupt) get to the chip only while ``ext_usb_gpio_fun`` #: routes them to GPIO, not to USB. Its PI4IOE5V6408 at 0x43 on I2C 1 turns on the RF path -#: from pin P0. The Cardputer variant of Meshtastic drives that pin in the same way. DIO2 +#: from pin P0. The older Cap LoRa868 has the same radio on the same pins, and no expander +#: at all, because it has no antenna switch to turn on. For this reason the expander of +#: this board is not required: a Cap that does not answer at 0x43 is the older one, and the +#: node proves that a radio is there before it accepts that. +#: The Cardputer variant of Meshtastic drives that pin in the same way. DIO2 #: switches the antenna and DIO3 supplies a 1.8 V TCXO, as on the AIO. Its GPS talks NMEA #: at 115200 on the UART of the header, which is the ``serial0`` of the Pi (``/dev/ttyS0`` #: on the Zero). The GPS gets its power from ``ext_5v_out``, as the radio does. Thus it @@ -241,6 +245,7 @@ CARDPUTER_ZERO_CAP = SpiWiring( pi4io_bus=1, pi4io_address=0x43, pi4io_high=(0,), + pi4io_required=False, gps_port="/dev/serial0", gps_baud=115200, ) @@ -340,12 +345,19 @@ class BuiltinRadio: marker. board: A test that only its machine passes, for a machine that has no single path of its own (:func:`is_uconsole`). ``None`` for no test. + with_expander: The model of the revision whose RF expander answers, for a board + that has two revisions. Empty where the board has one revision, and then + ``name`` is its model. + without_expander: The model of the revision that has no expander. Empty for a + board that must have one. """ name: str wiring: SpiWiring marker: str = "" board: Callable[[], bool] | None = None + with_expander: str = "" + without_expander: str = "" def present(self) -> bool: """Whether this machine is its board: the SPI device file and all its signs are there.""" @@ -364,22 +376,46 @@ class BuiltinRadio: BUILTIN_RADIOS = ( BuiltinRadio("uConsole AIO", SpiWiring(), board=is_uconsole), BuiltinRadio("", SpiWiring()), - BuiltinRadio("Cap LoRa-1262", CARDPUTER_ZERO_CAP, marker="/sys/class/leds/ext_5v_out"), + BuiltinRadio( + "Cap LoRa", + CARDPUTER_ZERO_CAP, + marker="/sys/class/leds/ext_5v_out", + with_expander="Cap LoRa-1262", + without_expander="Cap LoRa868", + ), ) -def board_name(wiring: SpiWiring) -> str: - """The name of the shipped board on which the radio of ``wiring`` is, or ``""`` for none. +def board_models(wiring: SpiWiring) -> tuple[str, str]: + """The model of the board of ``wiring`` with its RF expander, and the one without it. - The node reports this name as its model. Thus the Cap shows as "Cap LoRa-1262", and the - AIO as "uConsole AIO", in all places that show the model of a device. The match uses - the SPI device file on the board of this machine, not the full wiring. Thus a profile - that changes the pins of the Cap is still the Cap. + The device screen names the **slot**: the name in :data:`BUILTIN_RADIOS`, which is the + family where a board has two revisions ("Cap LoRa"), because nothing answers until the + node runs. The **model** is what the node found there, and a board with two revisions + has two of them. The match uses the SPI device file on the board of this machine, not + the full wiring. Thus a profile that changes the pins of the Cap is still the Cap. + + The node is given both models and names the one that it found (refer to + ``meshterm.core.radionode.board_model``). The Cap LoRa-1262 has the expander, and the + older Cap LoRa868 has none. + + Args: + wiring: The wiring of the radio, of a profile or of a board. + + Returns: + The model with the expander and the model without it. The second is empty for a + board that must have one, and both are empty where this machine is not its board. """ for radio in BUILTIN_RADIOS: if radio.name and radio.wiring.spidev == wiring.spidev and radio.present(): - return radio.name - return "" + if radio.without_expander and wiring.pi4io_bus < 0: + # This wiring never looks at the expander, which is what tells the two + # revisions apart. A profile that drops it is the usual way here. The name + # of the family is then the most that is true, as it is on the device + # screen before anything is connected. + return (radio.name, "") + return (radio.with_expander or radio.name, radio.without_expander) + return ("", "") def builtin_wiring(spidev: str) -> SpiWiring | None: @@ -801,6 +837,10 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP state.mkdir(parents=True, exist_ok=True) for line in await asyncio.to_thread(import_bridge_state, state): _log.info("spi radio: carried over %s", line) + # Both models go to the node, because only the node can see which revision of the board + # is attached. It answers with the one it found, and that model reaches the device + # screen through the store of remembered devices. + model, model_without_expander = board_models(wiring) config = { "state_dir": str(state), "wiring": { @@ -819,6 +859,7 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP "pi4io_bus": wiring.pi4io_bus, "pi4io_address": wiring.pi4io_address, "pi4io_high": list(wiring.pi4io_high), + "pi4io_required": wiring.pi4io_required, "use_dio2_rf": wiring.use_dio2_rf, "use_dio3_tcxo": wiring.use_dio3_tcxo, "is_waveshare": wiring.is_waveshare, @@ -826,7 +867,8 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP "gps_baud": wiring.gps_baud, }, "seed": {"node_name": node_name, **DEFAULT_SEED}, - "model": board_name(wiring), + "model": model, + "model_without_expander": model_without_expander, } log_path = state / "node.log" _rotate(log_path) diff --git a/meshterm/demo/device.py b/meshterm/demo/device.py index 9e60921..d401611 100644 --- a/meshterm/demo/device.py +++ b/meshterm/demo/device.py @@ -112,10 +112,22 @@ class DemoDevice(MockDevice): "model": "MeshCore Simulator", "ver": "v1.15.0", "fw_build": "demo", + "fw ver": 12, + "max_contacts": 300, + "max_channels": self._max_channels, "ble_pin": self._device_pin, "repeat": self._client_repeat, } + async def get_self_telemetry(self) -> list[dict]: # noqa: D102 - inherited docstring + # The board of our node: the battery, and the sensor on its expansion header. + return [ + {"channel": 0, "name": "voltage", "value": 3.98}, + {"channel": 0, "name": "percentage", "value": 74}, + {"channel": 1, "name": "temperature", "value": 18.5}, + {"channel": 1, "name": "humidity", "value": 46.0}, + ] + async def get_battery(self) -> dict: # noqa: D102 - inherited docstring return {"level": 3980, "used_kb": 412, "total_kb": 1024} diff --git a/meshterm/persistence/db.py b/meshterm/persistence/db.py index 8bf77e8..3e139f2 100644 --- a/meshterm/persistence/db.py +++ b/meshterm/persistence/db.py @@ -12,7 +12,7 @@ import json import sqlite3 from pathlib import Path -SCHEMA_VERSION = 23 +SCHEMA_VERSION = 24 _SCHEMA = """ CREATE TABLE IF NOT EXISTS schema_meta ( @@ -189,6 +189,14 @@ CREATE TABLE IF NOT EXISTS node_places ( found_at TEXT NOT NULL -- UTC ISO-8601 ); +-- Our own channel messages: the relays that sent a copy back (refer to +-- meshterm.services.heard_by). paths is a JSON list of the relay paths of the copies, +-- written one time when the message is out of the match window of the packet log. +CREATE TABLE IF NOT EXISTS heard_relays ( + message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE, + paths TEXT NOT NULL +); + CREATE INDEX IF NOT EXISTS idx_traces_run ON traces(run_id); CREATE INDEX IF NOT EXISTS idx_trace_hops_trace ON trace_hops(trace_id); CREATE INDEX IF NOT EXISTS idx_tx_samples_run ON tx_samples(run_id); @@ -445,6 +453,17 @@ def _migrate(conn: sqlite3.Connection) -> None: "WHERE sent_at IS NOT NULL" ) + heard_cols = {row["name"] for row in conn.execute("PRAGMA table_info(heard_relays)")} + if "near_hops" in heard_cols: + # The first build of schema 24 kept the near relays of each send. They are gone + # (refer to meshterm.services.heard_by), and the table holds only derived data, + # so it is made again. The chat fills it again from the packet log. + conn.execute("DROP TABLE heard_relays") + conn.execute( + "CREATE TABLE heard_relays (message_id INTEGER PRIMARY KEY " + "REFERENCES messages(id) ON DELETE CASCADE, paths TEXT NOT NULL)" + ) + stored = conn.execute("SELECT value FROM schema_meta WHERE key = 'version'").fetchone() if stored is not None and int(stored["value"]) < 19: # v18 -> v19: no private key in the run log. `config import-key` stored its key as diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index a8ce629..ac1c221 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -2252,6 +2252,48 @@ class Repository: self._conn.execute("UPDATE messages SET acked = ? WHERE id = ?", (int(acked), message_id)) self._conn.commit() + # -- relays that heard our channel messages --------------------------------------- + + def settle_heard(self, message_id: int, paths: list[tuple[str, ...]]) -> None: + """Store the relay paths of the copies of one message, when no more can come. + + Refer to :mod:`~meshterm.services.heard_by`. + + Args: + message_id: The ``messages`` row of the sent message. + paths: The relay paths of the copies that came back. An empty list is a stored + "no copy came back". + """ + self._conn.execute( + "INSERT INTO heard_relays (message_id, paths) VALUES (?, ?) " + "ON CONFLICT(message_id) DO UPDATE SET paths = excluded.paths", + (message_id, json.dumps([list(p) for p in paths])), + ) + self._conn.commit() + + def heard_records(self, message_ids: list[int]) -> dict[int, list[tuple[str, ...]]]: + """The stored relay paths of some of our channel messages. + + Args: + message_ids: The ``messages`` rows to read. + + Returns: + The relay paths of each row that is settled. A row that is not settled yet is + absent. + """ + out: dict[int, list[tuple[str, ...]]] = {} + ids = [int(i) for i in message_ids if i is not None] + for start in range(0, len(ids), 500): + part = ids[start : start + 500] + marks = ",".join("?" * len(part)) + rows = self._conn.execute( + f"SELECT message_id, paths FROM heard_relays WHERE message_id IN ({marks})", + part, + ).fetchall() + for row in rows: + out[int(row["message_id"])] = [tuple(p) for p in json.loads(row["paths"])] + return out + def delete_chat_history(self, peer: str | None) -> int: """Delete all the stored messages of one direct conversation. diff --git a/meshterm/platforms.py b/meshterm/platforms.py index 696e73b..061e36c 100644 --- a/meshterm/platforms.py +++ b/meshterm/platforms.py @@ -169,6 +169,12 @@ class Platform: battery: The source of the battery gauge in the header. ``"companion"`` reads it from the connected MeshCore device. ``"host"`` reads it from the ``power_supply`` driver of sysfs on the PicoCalc itself (confirmed present in P0). Wired in P5. + sound: Whether this platform can play a sound. ``True`` lets MeshTerm play its + notification sounds through the player of the operating system (refer to + :mod:`~meshterm.services.sound`). ``False`` on the PicoCalc: its speaker is silent + on the Lyra, because the speaker pins of the board cannot do hardware PWM. There, + the Preferences page does not offer the sound preferences, and a notification is + silent. The title bar can still flash for it. own_display: Whether MeshTerm itself draws this display (:mod:`meshterm.emulator`) and does not run in a terminal. Then the app is its own terminal, and the terminal that started it is not its business. Examples are a classic Windows @@ -204,6 +210,7 @@ class Platform: tick_s: float spinner_tick_s: float battery: str + sound: bool own_display: bool modifier_watch: str @@ -236,6 +243,7 @@ REGULAR = Platform( tick_s=1.0, spinner_tick_s=0.12, battery="companion", + sound=True, own_display=False, modifier_watch="", ) @@ -268,6 +276,7 @@ PICOCALC_LYRA = Platform( tick_s=2.0, spinner_tick_s=0.5, battery="host", + sound=False, own_display=False, modifier_watch="picocalc", ) @@ -318,11 +327,15 @@ CARDPUTER_ZERO = Platform( tick_s=2.0, spinner_tick_s=0.5, battery="host", + sound=True, own_display=True, modifier_watch="tca8418c", ) -_BY_NAME = {p.name: p for p in (REGULAR, PICOCALC_LYRA, CARDPUTER_ZERO)} +#: Each platform, in a fixed order. +ALL_PLATFORMS: tuple[Platform, ...] = (REGULAR, PICOCALC_LYRA, CARDPUTER_ZERO) + +_BY_NAME = {p.name: p for p in ALL_PLATFORMS} #: The active platform. Do not import this name directly (refer to the module docstring). #: Read it through :func:`get_platform`, and change it only through :func:`set_platform`. diff --git a/meshterm/services/battery_service.py b/meshterm/services/battery_service.py index 8e939a7..72d9894 100644 --- a/meshterm/services/battery_service.py +++ b/meshterm/services/battery_service.py @@ -326,12 +326,19 @@ class BatteryService: delay = POLL_S try: delay = await self._poll() + self._tell_sound() except asyncio.CancelledError: raise except Exception as exc: # noqa: BLE001 - a bad read must not stop the loop self._ctx.log.debug("battery poller: read failed: %s", exc) await asyncio.sleep(delay) + def _tell_sound(self) -> None: + """Give the new reading to the sound service, which plays the battery-low sound.""" + sound = getattr(self._ctx, "sound", None) + if sound is not None and self._reading is not None: + sound.note_battery(self._reading.percent, charging=self._reading.charging) + async def _poll(self) -> float: """One pass: read the pack, estimate the charge, and calculate the charging trend again. diff --git a/meshterm/services/chat_service.py b/meshterm/services/chat_service.py index 89be9d8..3d6980b 100644 --- a/meshterm/services/chat_service.py +++ b/meshterm/services/chat_service.py @@ -26,7 +26,7 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING from ..core import reactions -from ..core.channels import channel_identity, split_channel_sender +from ..core.channels import MENTION, channel_identity, split_channel_sender from ..core.connection import Unsubscribe from ..core.events import EventKind, MeshEvent from ..core.models import ( @@ -39,6 +39,7 @@ from ..core.models import ( ) from ..core.regions import WILDCARD, normalize from .arrival_backfill import backfill_arrivals +from .sound import SoundEvent if TYPE_CHECKING: from ..context import AppContext @@ -409,8 +410,11 @@ class ChatService: channel_id = ( await self.channel_id_for(message.channel) if message.is_channel else None ) - notify = await self._notifies(message, channel_id) - self._store_inbound(run_id, message, channel_id, notify=notify) + listed = await self._is_listed(message, channel_id) + muted = self._is_muted(message, channel_id) + chat = self._store_inbound(run_id, message, channel_id, notify=listed and not muted) + if listed: + await self._play_sound(message, chat.key, muted=muted) except Exception as exc: # noqa: BLE001 - one bad message must not stop the worker self._ctx.log.debug("chat: failed to record message: %s", exc) finally: @@ -423,7 +427,7 @@ class ChatService: channel_id: str | None, *, notify: bool = True, - ) -> None: + ) -> ChatMessage: """Store an inbound message under a resolved identity, and increase its unread count. MeshTerm always stores the transcript. It does not increase the unread count for @@ -432,6 +436,9 @@ class ChatService: that the Chat picker cannot list (refer to :meth:`_notifies`). A message that does not notify is still written to history. Thus when the user opens its conversation later, the conversation shows all messages. + + Returns: + The stored message. """ chat = ChatMessage.from_message(message, channel_id=channel_id) self._session_count += 1 @@ -441,6 +448,7 @@ class ChatService: self._ctx.repo.record_chat_message(chat, run_id=run_id) except Exception as exc: # noqa: BLE001 - the storage must never break the subscription self._ctx.log.debug("chat: failed to record message: %s", exc) + return chat async def _notifies(self, message: Message, channel_id: str | None) -> bool: """Whether this message increases the unread badge in the header: the only badge rule. @@ -486,13 +494,99 @@ class ChatService: """ if _is_reaction(message): return False + if self._is_muted(message, channel_id): + return False + return await self._is_listed(message, channel_id) + + def _is_muted(self, message: Message, channel_id: str | None) -> bool: + """Whether the message is on a channel that the user muted (refer to MuteStore).""" + if not message.is_channel: + return False + store = getattr(self._ctx, "mute_store", None) + return store is not None and store.is_muted(channel_id) + + async def _is_listed(self, message: Message, channel_id: str | None) -> bool: + """Whether the Chat picker lists the conversation of the message (refer to _notifies). + + The unread badge and the sound both use this rule. A message that has no row to open + makes no sound, for the same reason that it does not increase the badge. + """ if message.is_channel: - store = getattr(self._ctx, "mute_store", None) - if store is not None and store.is_muted(channel_id): - return False return await self._is_listed_channel(channel_id) return await self._is_listed_contact(message.sender, post=message.is_post) + async def _play_sound(self, message: Message, key: str, *, muted: bool = False) -> None: + """Play the sound of a received message. + + The rule (JP, 2026-11-21): + + * A message from the queue of the companion (``waited``) makes no sound, a mention + included. The companion keeps what arrived while MeshTerm was not connected, and + gives all of it at the connect. It is old news, and one sound for each message + was a burst of sounds at each start. + * A room post of the catch-up after a login makes no sound, for the same reason + (refer to :meth:`~meshterm.services.rooms.RoomService.catching_up`). + * A mention of our node in a channel or a room follows ``sound_mention``. A + mention in a DM is not a mention here: the message is already for us, so it plays + the DM sound. + * ``always`` plays the mention sound whatever the rules below say: on a muted + channel, with the switch of its kind off, and in the open conversation. + * The open conversation plays nothing when ``sound_on_screen`` is off. + * A muted channel (``muted``, refer to MuteStore) plays nothing. A mute turns off the + notifications of the channel, and a sound is one. + * ``on`` plays the mention sound. ``regular`` plays the sound of the kind, as for any + other message: a channel message or a room post. + * Each event has its own switch (refer to + :data:`~meshterm.services.sound.EVENT_PREFERENCE`), which the sound service + checks. + + A failure here must never stop the recording of messages, so it only goes to the log. + """ + sound = getattr(self._ctx, "sound", None) + if sound is None or message.waited: + return + rooms = getattr(self._ctx, "rooms", None) + if message.is_post and rooms is not None and rooms.catching_up(message.sender): + return + try: + prefs = self._ctx.preferences + if message.is_channel: + event = SoundEvent.CHANNEL_MESSAGE + elif message.is_post: + event = SoundEvent.ROOM_POST + else: + event = SoundEvent.DIRECT_MESSAGE + rule = prefs.sound_mention + mention = ( + event is not SoundEvent.DIRECT_MESSAGE + and rule != "regular" + and await self._mentions_us(message.text) + ) + if mention and rule == "always": + sound.notify(SoundEvent.MENTION) + return + if key == self._active and not prefs.sound_on_screen: + return + if muted: + return + sound.notify(SoundEvent.MENTION if mention else event) + except Exception as exc: # noqa: BLE001 - a sound must never stop the recorder + self._ctx.log.debug("chat: sound failed: %s", exc) + + async def _mentions_us(self, text: str | None) -> bool: + """Whether a message text mentions our node (``@[Name]`` with the name of our node).""" + if not text or "@[" not in text: + return False + devstate = getattr(self._ctx, "devstate", None) + if devstate is None: + return False + try: + info = await devstate.self_info() + except Exception: # noqa: BLE001 - with no name, nothing is a mention of us + return False + name = str(info.get("name") or "") + return bool(name) and any(m.group(1) == name for m in MENTION.finditer(text)) + async def _is_listed_channel(self, channel_id: str | None) -> bool: """Whether a channel identity is one of the configured channel slots of the device. diff --git a/meshterm/services/device_state.py b/meshterm/services/device_state.py index 2356bf7..d9070e5 100644 --- a/meshterm/services/device_state.py +++ b/meshterm/services/device_state.py @@ -444,6 +444,17 @@ class DeviceState: return slots return self._channels + def peek_channel_slots(self) -> list[ChannelSlot] | None: + """The channel slots that the cache already has, or ``None`` when it has none yet. + + This method never reads from the device. It is for a page that names how many + channels the device holds as one fact among many (the Device info page). The probe + behind :meth:`channel_slots` reads every slot index, which is one of the slowest + reads of a session. A count is not worth that cost, and the prewarm fills this + cache anyway. + """ + return None if self._channels is None else list(self._channels) + async def channel_capacity(self) -> int: """Return the channel-slot capacity of the device, found once and kept for the session. diff --git a/meshterm/services/heard_by.py b/meshterm/services/heard_by.py new file mode 100644 index 0000000..ef5be9e --- /dev/null +++ b/meshterm/services/heard_by.py @@ -0,0 +1,271 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tell whether a repeater relayed a channel message that we sent (issue #38). + +A channel broadcast has no acknowledgement. But the device hears the relay of our +broadcast by each repeater in range, and its RX log records each copy with the path that +the copy went through (refer to :mod:`~meshterm.services.message_paths`). Each hop in that +path heard the message. Thus a copy that comes back is the proof that a repeater heard the +message and sent it on. + +Each relay counts, the repeater next to us too. A first version counted only the relays +past the first hops of the outbound paths. In practice, nothing past them ever came back: +each repeater relays a packet one time, and the relays farther out are too far for our +radio to hear (JP, 2026-11-20, from 23 of 23 messages on his Public channel). + +The verdict of a message has three states, the same as the delivery of a direct message: + +* :data:`WAITING`: no copy came back yet, and the wait (``heard_wait_s``) is not over. The + chat shows a spinner. +* :data:`HEARD`: one or more relays sent a copy back. The chat shows ``βœ“`` and the number + of the relays. +* :data:`UNHEARD`: after the wait, no copy came back. The chat shows ``βœ—``. + +A copy that comes back late changes the verdict, as a late acknowledgement does for a +direct message. After the match window of the packet log +(:data:`~meshterm.services.message_paths.CHANNEL_WINDOW`), nothing can change it, and +MeshTerm stores the paths, so that the next visit does not decrypt the log again. + +Two limits stay. MeshTerm sees only the relays that our radio hears. And MeshTerm must be +connected while the copies come back. + +Nothing in this module transmits. It is a read-model over the repository. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass, field +from datetime import datetime +from typing import TYPE_CHECKING + +from ..core.models import ChatMessage, utcnow +from .message_paths import CHANNEL_WINDOW, Arrival, channel_arrivals + +if TYPE_CHECKING: + from ..context import AppContext + from ..persistence.repository import Repository + +#: The verdict states (refer to the module docstring). +WAITING = "waiting" +HEARD = "heard" +UNHEARD = "unheard" + +#: The number of messages that :meth:`HeardTracker.fill` examines before each yield to the +#: event loop. Each one is a query of the packet log and some decryptions. +_CHUNK = 4 + +#: A relay path, as hop hashes in the order of propagation. +RelayPath = tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class HeardBy: + """The verdict on one channel message that we sent. + + Attributes: + state: :data:`WAITING`, :data:`HEARD`, or :data:`UNHEARD`. + relays: The hashes of the relays in the copies, in the order first heard. Each one + heard the message. + copies: The number of copies that came back. + """ + + state: str + relays: tuple[str, ...] = () + copies: int = 0 + + +def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]: + """The paths of the copies that tell which relays heard the message. + + A copy with no hops tells nothing (a flood of ours always comes back through a relay), + and a direct-routed copy that used all its route tells nothing either (refer to + :attr:`~meshterm.services.message_paths.Arrival.route_known`). + """ + return [a.hops for a in arrivals if a.hops and a.route_known] + + +def judge(paths: Sequence[RelayPath], *, age_s: float, wait_s: float) -> HeardBy: + """The verdict on a message from the paths of its copies. + + Args: + paths: The relay paths of the copies that came back, in the order heard. + age_s: The time since the send, in seconds. + wait_s: The wait before "no relay" becomes the verdict (``heard_wait_s``). + + Returns: + The verdict. + """ + relays: list[str] = [] + for path in paths: + for hop in path: + if hop.lower() not in relays: + relays.append(hop.lower()) + if relays: + state = HEARD + elif age_s < wait_s: + state = WAITING + else: + state = UNHEARD + return HeardBy(state, tuple(relays), len(paths)) + + +@dataclass(slots=True) +class _Record: + """What the tracker knows about one message: the copies so far, and if more can come.""" + + paths: list[RelayPath] = field(default_factory=list) + settled: bool = False + + +class HeardTracker: + """The verdicts on our channel messages in one conversation, kept current. + + The chat screen reads :meth:`verdict` at each paint, and that read never touches the + packet log. The work is in :meth:`fill`, which runs in the background when the screen + opens, and in :meth:`refresh`, which the screen calls when the device hears a channel + packet. A message that is out of the match window is **settled**: MeshTerm stores its + paths one time, and reads them back on the next visit. + """ + + def __init__( + self, + repo: Repository, + *, + channel_name: str, + secret: bytes | None, + wait_s: Callable[[], float], + clock: Callable[[], datetime] = utcnow, + ) -> None: + """Make a tracker for one channel. + + Args: + repo: The repository with the packet log and the stored verdicts. + channel_name: The name of the channel (for the decryption). + secret: The key of the channel. With no key, nothing can be matched, and each + verdict is ``None``. + wait_s: Gives the ``heard_wait_s`` preference, read at each verdict. + clock: Gives the current time (a fixed clock in the tests). + """ + self._repo = repo + self._channel_name = channel_name + self._secret = secret + self._wait_s = wait_s + self._clock = clock + self._records: dict[int, _Record] = {} + self._revision = 0 + + @property + def revision(self) -> int: + """A number that changes each time that a verdict can have changed.""" + return self._revision + + def _ours(self, message: ChatMessage) -> bool: + return bool(self._secret and message.outbound and message.is_channel and message.row_id) + + def _age_s(self, message: ChatMessage) -> float: + return (self._clock() - message.created_at).total_seconds() + + def verdict(self, message: ChatMessage) -> HeardBy | None: + """The verdict on one message, or ``None`` when there is none to show. + + ``None`` is for a message that is not our own channel message, and for one that + :meth:`fill` did not examine yet. + """ + if not self._ours(message): + return None + record = self._records.get(message.row_id) # type: ignore[arg-type] + if record is None: + return None + return judge(record.paths, age_s=self._age_s(message), wait_s=self._wait_s()) + + def note_sent(self, message: ChatMessage) -> None: + """Start the verdict of a message that was sent while the screen is open.""" + if self._ours(message): + self._records[message.row_id] = _Record() # type: ignore[index] + self._revision += 1 + + async def fill(self, messages: Sequence[ChatMessage]) -> None: + """Examine each of our channel messages, the newest first, in small steps. + + The settled verdicts come from storage in one query. Each other message costs a + query of the packet log, so the work yields to the event loop after each few. + + Args: + messages: The transcript of the conversation. + """ + ours = [m for m in messages if self._ours(m)] + stored = self._repo.heard_records([m.row_id for m in ours]) # type: ignore[misc] + for message in ours: + paths = stored.get(message.row_id) # type: ignore[arg-type] + if paths is not None: + self._records[message.row_id] = _Record(paths=list(paths), settled=True) # type: ignore[index] + self._revision += 1 + todo = [m for m in reversed(ours) if m.row_id not in self._records] + for start in range(0, len(todo), _CHUNK): + for message in todo[start : start + _CHUNK]: + self._examine(message) + self._revision += 1 + await asyncio.sleep(0) + + def refresh(self, messages: Sequence[ChatMessage]) -> bool: + """Examine again the messages that are not settled, after a new channel packet. + + Args: + messages: The transcript of the conversation. + + Returns: + ``True`` when a verdict can have changed. + """ + changed = False + for message in messages: + if not self._ours(message): + continue + record = self._records.get(message.row_id) # type: ignore[arg-type] + if record is None or record.settled: + continue + before = list(record.paths) + self._examine(message) + changed = changed or self._records[message.row_id].paths != before # type: ignore[index] + if changed: + self._revision += 1 + return changed + + def waiting(self, messages: Sequence[ChatMessage]) -> bool: + """Whether one of the messages shows the spinner now.""" + return any((v := self.verdict(m)) is not None and v.state == WAITING for m in messages) + + def _examine(self, message: ChatMessage) -> None: + """Match the copies of one message in the packet log, and settle it if it is old.""" + assert self._secret is not None and message.row_id is not None + arrivals = channel_arrivals( + self._repo, message, channel_name=self._channel_name, secret=self._secret + ) + paths = relay_paths(arrivals) + settled = self._age_s(message) > CHANNEL_WINDOW.total_seconds() + self._records[message.row_id] = _Record(paths=paths, settled=settled) + if settled: + self._repo.settle_heard(message.row_id, paths) + + +def make_tracker( + ctx: AppContext, *, channel_name: str, secret: bytes | None +) -> HeardTracker | None: + """A tracker for one channel. + + Args: + ctx: The shared application context (the repository and the preferences). + channel_name: The name of the channel. + secret: The key of the channel. With no key, there is no tracker. + + Returns: + The tracker, or ``None`` when the channel has no key at hand. + """ + if not secret: + return None + return HeardTracker( + ctx.repo, + channel_name=channel_name, + secret=secret, + wait_s=lambda: float(ctx.preferences.heard_wait_s), + ) diff --git a/meshterm/services/message_paths.py b/meshterm/services/message_paths.py index 58b4831..0387182 100644 --- a/meshterm/services/message_paths.py +++ b/meshterm/services/message_paths.py @@ -15,7 +15,9 @@ message reached our node: recover the plaintext. A packet whose text is equal to the text of the message is one arrival of that message. The comparison accepts the ``Name: `` sender prefix on either side. Our own broadcasts are included, because the device overhears the relay of our - broadcast by a repeater and logs it like all other packets. + broadcast by a repeater and logs it like all other packets. For our own broadcast, the + sender time in the packet must also be near the stored time of the send. Thus two + messages with the same text a few minutes apart do not share their copies. * **Direct messages** go in ECDH-encrypted ``TEXT_MSG`` packets that only the recipient can decrypt. Thus a match by content is not possible from the log. But such a packet carries its **addressing and its MAC** in clear text (:mod:`~meshterm.core.frames`): the @@ -55,7 +57,14 @@ if TYPE_CHECKING: #: The span of the log that MeshTerm searches around a channel message. It is wide, #: because an inbound message has the time of the sender's clock, and that clock can be #: minutes different from our clock. -_CHANNEL_WINDOW = timedelta(minutes=15) +CHANNEL_WINDOW = timedelta(minutes=15) + +#: The largest difference between the sender time in a copy of our own channel message and +#: the time that MeshTerm stored for the send. The library puts the clock of the computer +#: on the packet, and MeshTerm stores the time after the companion accepts it. Two +#: messages with the same text ("test") inside the match window are then two different +#: messages, and not one message with the copies of both. +_SEND_SLACK = timedelta(seconds=10) #: The span of the log that MeshTerm searches around a direct message, before the other #: messages of the conversation make it narrower (refer to :func:`direct_window`). This @@ -194,7 +203,7 @@ def channel_arrivals( # Around the arrival time, not the sender time: a sender with a wrong clock put the # window hours or years away from its packets. at = message.arrived_at - frames = repo.packet_frames_between(at - _CHANNEL_WINDOW, at + _CHANNEL_WINDOW) + frames = repo.packet_frames_between(at - CHANNEL_WINDOW, at + CHANNEL_WINDOW) arrivals: list[Arrival] = [] for frame in frames: raw = frame.raw if isinstance(frame.raw, dict) else {} @@ -208,6 +217,12 @@ def channel_arrivals( decrypted = decrypt_channel_text(chan_hash, cipher_mac, crypted, [(channel_name, secret)]) if decrypted is None or not _texts_match(decrypted.text, message.text): continue + if ( + message.outbound + and decrypted.sent_at is not None + and abs(decrypted.sent_at - message.created_at) > _SEND_SLACK + ): + continue arrivals.append( Arrival( when=frame.observed_at, diff --git a/meshterm/services/places.py b/meshterm/services/places.py index 2ac8406..a6ff1af 100644 --- a/meshterm/services/places.py +++ b/meshterm/services/places.py @@ -144,6 +144,39 @@ def current() -> PlaceService | None: return _CURRENT +def place_of(ctx: AppContext, node: str | None) -> Place | None: + """The place of a node, with or without a running place service. + + A menu session always has a service, and its cache answers at once. A scripted run has + none, so this function reads the two sources that the service reads: the place that the + user typed, and the places that the job stored before. Thus one command gets the same + answer on both faces. + + Args: + ctx: The shared application context. + node: The key prefix or the full public key of the node. + + Returns: + The place, or ``None`` when MeshTerm knows none. + """ + service = current() + if service is not None: + return service.get(node) + if not node: + return None + key = _norm(node) + typed = ctx.place_store.get(key) if ctx.place_store is not None else None + if typed: + return Place(typed, None, SOURCE_USER) + try: + found = ctx.repo.node_places() + except Exception as exc: # noqa: BLE001 - no place is better than no answer + ctx.log.debug("places: read failed: %s", exc) + return None + hit = found.get(key) + return None if hit is None or hit[0].empty else hit[0] + + class PlaceService: """The places of the nodes: a read side from memory, and a background job that finds them.""" diff --git a/meshterm/services/rooms.py b/meshterm/services/rooms.py index 3784409..76ac28b 100644 --- a/meshterm/services/rooms.py +++ b/meshterm/services/rooms.py @@ -33,6 +33,14 @@ if TYPE_CHECKING: from ..context import AppContext +#: How long a room must send nothing before its catch-up counts as finished, in seconds. +#: After a login, a room sends the posts that it kept for us, one after another. They are +#: posts that were already there, so they play no sound (JP, 2026-11-21: "Reading what +#: already was there shouldn't trigger sounds"). The room has no mark for the last post of +#: its catch-up, and its clock is often wrong, so the end is a pause instead of a time. +CATCH_UP_QUIET_S = 8.0 + + class RoomService: """Joins rooms, remembers what they let us do, and decides when to log in again.""" @@ -51,6 +59,9 @@ class RoomService: #: The login in progress to each room, and the password that it carries, indexed by #: peer. self._inflight: dict[str, tuple[asyncio.Future, str]] = {} + #: The rooms that are sending their catch-up after a login, with the time of the last + #: sign of it (the login or a post), on the monotonic clock, indexed by peer. + self._catching_up: dict[str, float] = {} @staticmethod def _peer(room: Contact) -> str: @@ -127,6 +138,33 @@ class RoomService: if peer: self._heard[peer.lower()] = time.monotonic() + def catching_up(self, peer: str | None, now: float | None = None) -> bool: + """True if a post from ``peer`` is part of the catch-up after a login. + + A post that comes less than :data:`CATCH_UP_QUIET_S` after the login or after the + last post of the catch-up is part of it, and it extends the catch-up. The first pause + longer than that ends it. A post that carries the prefix of the room at any width + counts, as for :meth:`heard_recently`. + + Args: + peer: The key prefix of the room, as the sender of the post carried it. + now: The monotonic time now. Tests give it. + + Returns: + ``True`` while the room sends what it already had. + """ + if not peer: + return False + peer = peer.lower() + now = time.monotonic() if now is None else now + for known, last in list(self._catching_up.items()): + if known.startswith(peer) or peer.startswith(known): + if now - last < CATCH_UP_QUIET_S: + self._catching_up[known] = now + return True + del self._catching_up[known] + return False + def heard_recently(self, room: Contact) -> bool: """True if ``room`` was heard within ``room_relogin_minutes``: then no login is necessary. @@ -220,6 +258,9 @@ class RoomService: async def _login_once(self, room: Contact, password: str, *, flood: bool) -> RoomLogin: """One login exchange, and what its result means for the stores and the session.""" device = await self._ctx.device() + # The room can start its catch-up as soon as it has the login, before the reply + # reaches us. Thus the catch-up starts here, and the accept below starts it again. + self._catching_up[self._peer(room)] = time.monotonic() if flood: await device.reset_route(room) # The route in the contact cache is not valid now. The next read gets it again @@ -239,4 +280,5 @@ class RoomService: peer = self._peer(room) self._access[peer] = login.access self._heard[peer] = time.monotonic() + self._catching_up[peer] = time.monotonic() return login diff --git a/meshterm/services/sound.py b/meshterm/services/sound.py new file mode 100644 index 0000000..975185d --- /dev/null +++ b/meshterm/services/sound.py @@ -0,0 +1,492 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The sound service: play a sound, or flash the title bar, for a notification. + +A notification is an event that the user wants to know about now: a direct message, a +mention of our node, a channel message, a room post, a low battery, or (if the user wants +it) each packet heard. The callers decide *whether* an event notifies (the rules of each +conversation are in :class:`~meshterm.services.chat_service.ChatService`). This service +decides *how*: which sound, how loud, through which player, and whether the title bar +flashes. + +MeshTerm has no audio dependency. It plays a WAV file through the player of the operating +system: + +* **Windows**: MCI (``winmm``, through ``ctypes``), so that sounds can overlap. +* **macOS**: ``afplay``. +* **Linux** (the Cardputer Zero too): the first of ``pw-play``, ``paplay``, and ``aplay`` + that is installed. + +The volume is in MeshTerm, not in the player, so that it is the same with each player. Thus the +service writes a scaled copy of each sound into a cache folder, one time for each volume, +and plays the copy. The ``bell`` theme plays no file. It sends the terminal bell (BEL), +which rings on the computer of the user, also over SSH. + +A player can fail: no audio device, no player installed, a server that is not running. +The first failure goes to the log one time. After it, the service does not try the player +again in this session, and each notification counts as silent. Thus the flash (in the +``silent`` mode) replaces the sound. A failure never stops the app. + +The PicoCalc has no sound (:attr:`~meshterm.platforms.Platform.sound`). There, each +notification is silent, and only the flash can show it. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import shutil +import subprocess +import sys +import time +import wave +from array import array +from collections.abc import Callable +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING + +from ..core.events import EventKind, MeshEvent +from ..platforms import get_platform + +if TYPE_CHECKING: + from ..context import AppContext + +log = logging.getLogger(__name__) + + +class SoundEvent(str, Enum): + """The events that can play a sound.""" + + DIRECT_MESSAGE = "direct_message" + MENTION = "mention" + CHANNEL_MESSAGE = "channel_message" + ROOM_POST = "room_post" + BATTERY_LOW = "battery_low" + PACKET_TICK = "packet_tick" + + +#: The folder of the sound files in the package. +SOUNDS_DIR = Path(__file__).resolve().parent.parent / "assets" / "sounds" + +#: The file of each event, for each theme that plays files. The keys are the values of the +#: ``sound_theme`` preference. JP selected the sounds of ``android`` by ear on 2026-11-20 +#: (refer to ``meshterm/assets/sounds/android/README.md``). +THEMES: dict[str, dict[SoundEvent, str]] = { + "android": { + SoundEvent.DIRECT_MESSAGE: "android/Carme.wav", + SoundEvent.MENTION: "android/Ariel.wav", + SoundEvent.CHANNEL_MESSAGE: "android/InCallNotification.wav", + SoundEvent.ROOM_POST: "android/Ceres.wav", + SoundEvent.BATTERY_LOW: "android/LowBattery.wav", + SoundEvent.PACKET_TICK: "android/Effect_Tick.wav", + }, +} + +#: The seconds between a packet heard and its tick. A received message arrives as a packet +#: first, then as a message. The wait lets the sound of the message start first, and then +#: the tick sees that sound and does not play (refer to :data:`TICK_GAP_S`). Thus a message +#: plays only its own sound (JP, 2026-11-20: "a sound for packets that don't already make +#: sound"). +TICK_DELAY_S = 0.15 + +#: How many points above the ``battery_low_pct`` threshold the battery must rise before the +#: battery-low sound can play again. Without this margin, a reading that moves by one point +#: around the threshold plays the sound at each poll. +BATTERY_REARM_PCT = 5 + +#: The preference that turns each event on or off (JP, 2026-11-21). All are on by default, +#: except the packet tick. The mention has a rule of three values instead +#: (``sound_mention``), and :meth:`SoundService.event_on` reads it. +EVENT_PREFERENCE: dict[SoundEvent, str] = { + SoundEvent.DIRECT_MESSAGE: "sound_dm", + SoundEvent.CHANNEL_MESSAGE: "sound_channel", + SoundEvent.ROOM_POST: "sound_room", + SoundEvent.BATTERY_LOW: "sound_battery", + SoundEvent.PACKET_TICK: "packet_tick", +} + +#: The minimum seconds between the start of a sound and a packet tick. It limits the tick +#: to four each second on a busy mesh, and a tick does not play over the start of another +#: sound (JP, 2026-11-20). +TICK_GAP_S = 0.25 + + +def gain(volume_pct: int) -> float: + """The factor for the samples at a volume, on a curve that follows the ear. + + The ear hears loudness approximately on a logarithmic scale. A straight factor puts + almost all of the change in the lowest part of the range. The square of the fraction + is a simple curve that is near the ear: 50% is a factor of 0.25 (-12 dB). + + Args: + volume_pct: The volume, from 0 to 100. + + Returns: + The factor, from 0.0 to 1.0. + """ + fraction = max(0, min(100, volume_pct)) / 100 + return fraction * fraction + + +def scaled(source: Path, volume_pct: int, cache_dir: Path) -> Path: + """A copy of a 16-bit WAV file at a volume, made one time and kept in a cache. + + Args: + source: The WAV file at full volume. It must be 16-bit PCM. + volume_pct: The volume, from 0 to 100. At 100, the function returns ``source``. + cache_dir: The folder of the scaled copies. + + Returns: + The path of the file to play. + """ + if volume_pct >= 100: + return source + target = cache_dir / f"{source.parent.name}-{source.stem}-{volume_pct}.wav" + if target.exists(): + return target + with wave.open(str(source), "rb") as reader: + params = reader.getparams() + frames = reader.readframes(params.nframes) + if params.sampwidth != 2: + return source + samples = array("h") + samples.frombytes(frames) + if sys.byteorder == "big": + samples.byteswap() # WAV data is little-endian. + factor = gain(volume_pct) + out = array("h", (int(s * factor) for s in samples)) + if sys.byteorder == "big": + out.byteswap() + cache_dir.mkdir(parents=True, exist_ok=True) + partial = target.with_suffix(".part") + with wave.open(str(partial), "wb") as writer: + writer.setparams(params) + writer.writeframes(out.tobytes()) + os.replace(partial, target) + return target + + +class _Mci: + """Plays WAV files on Windows through MCI (``winmm``), each sound on its own device. + + ``winsound`` plays one sound at a time: a new sound stops the sound that plays. MCI + opens a new ``waveaudio`` device for each sound, and Windows mixes the devices. Thus two + sounds play at the same time (JP, 2026-11-21: "playing a sound shouldn't interrupt an + already playing sound"). Each device closes at the next sound after it stops. + """ + + def __init__(self) -> None: + """Bind ``mciSendStringW`` from ``winmm``.""" + import ctypes + + self._ctypes = ctypes + self._send_string = ctypes.windll.winmm.mciSendStringW # type: ignore[attr-defined] + self._count = 0 + self._open: list[str] = [] + + def _send(self, command: str) -> str: + """Send one MCI command string, and return its answer. + + Raises: + OSError: If MCI refuses the command. + """ + answer = self._ctypes.create_unicode_buffer(64) + error = self._send_string(command, answer, len(answer), None) + if error: + raise OSError(f"MCI error {error} for {command.split()[0]!r}") + return answer.value + + def play(self, path: Path) -> None: + """Open a new device on the file, and start it without a wait.""" + self._close_stopped() + self._count += 1 + alias = f"meshterm{self._count}" + self._send(f'open "{path}" type waveaudio alias {alias}') + self._open.append(alias) + self._send(f"play {alias}") + + def _close_stopped(self) -> None: + """Close each device whose sound has ended.""" + for alias in list(self._open): + try: + playing = self._send(f"status {alias} mode") == "playing" + except OSError: + playing = False + if not playing: + try: + self._send(f"close {alias}") + except OSError: + pass + self._open.remove(alias) + + +class Player: + """Plays a WAV file through the player of the operating system, without a wait. + + Sounds play at the same time: a new sound never stops one that plays. On macOS and + Linux, each sound is its own player process. On Windows, each sound is its own MCI + device (refer to :class:`_Mci`). + + The first failure goes to the log, and then the player stays off for the session. + """ + + def __init__(self) -> None: + """Make a player. It finds its command at the first sound.""" + self.broken = False + self._command: list[str] | None = None + self._running: list[subprocess.Popen[bytes]] = [] + self._mci: _Mci | None = None + + def play(self, path: Path) -> bool: + """Start the sound, and return at once. + + Args: + path: The WAV file. + + Returns: + ``True`` if the sound started. ``False`` if the player is off or failed. + """ + if self.broken: + return False + try: + if sys.platform == "win32": + if self._mci is None: + self._mci = _Mci() + self._mci.play(path) + return True + return self._spawn(path) + except Exception as error: # noqa: BLE001 - any failure of the player makes it off. + log.warning("sound: the player failed, sounds are off for this session: %s", error) + self.broken = True + return False + + def _spawn(self, path: Path) -> bool: + """Start the command of the player on a file (macOS and Linux).""" + if self._command is None: + self._command = _player_command() + if not self._command: + log.warning("sound: no player found (afplay, pw-play, paplay, or aplay)") + self.broken = True + return False + # Collect the players that stopped, so that no process stays as a zombie. + self._running = [p for p in self._running if p.poll() is None] + self._running.append( + subprocess.Popen( # noqa: S603 - a fixed command and a file of the package. + [*self._command, str(path)], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + ) + return True + + +def _player_command() -> list[str]: + """The command that plays a WAV file on this system, or an empty list.""" + if sys.platform == "darwin": + return ["afplay"] if shutil.which("afplay") else [] + for command in (["pw-play"], ["paplay"], ["aplay", "-q"]): + if shutil.which(command[0]): + return command + return [] + + +class SoundService: + """Plays the sound of a notification, and flashes the title bar if the user wants it. + + The interactive session gives the service two hooks: :meth:`set_hooks` names the + function that rings the terminal bell and the function that flashes the title bar. + Without them (a scripted run, a test), the bell and the flash do nothing. + """ + + def __init__( + self, + ctx: AppContext, + player: Player | None = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + """Make the service. + + Args: + ctx: The shared application context, read for the preferences and the config + folder. + player: The player. Tests give a fake one. + clock: The clock of the tick limit. Tests give a fake one. + """ + self._ctx = ctx + self._player = player or Player() + self._clock = clock + self._last_sound = float("-inf") + self._bell: Callable[[], None] | None = None + self._flash: Callable[[], None] | None = None + self._battery_armed = True + self._tick_pending = False + self._unsubscribe: Callable[[], None] | None = None + + def start(self) -> None: + """Listen to the packets heard, for the packet tick. The interactive session calls it.""" + events = getattr(self._ctx, "events", None) + if self._unsubscribe is None and events is not None: + self._unsubscribe = events.subscribe(self._on_packet, EventKind.OBSERVATION) + + def stop(self) -> None: + """Stop listening to the packets heard.""" + if self._unsubscribe is not None: + self._unsubscribe() + self._unsubscribe = None + + def _on_packet(self, event: MeshEvent) -> None: + """Schedule the tick of a packet heard, if the tick is on (refer to TICK_DELAY_S).""" + if self._tick_pending or not self._prefs.packet_tick or not self.enabled: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + self._tick_pending = True + loop.call_later(TICK_DELAY_S, self._tick) + + def _tick(self) -> None: + """Play the packet tick, unless another sound started a short time ago.""" + self._tick_pending = False + self.notify(SoundEvent.PACKET_TICK) + + def set_hooks( + self, + bell: Callable[[], None] | None = None, + flash: Callable[[], None] | None = None, + ) -> None: + """Name the functions that ring the terminal bell and flash the title bar.""" + self._bell = bell + self._flash = flash + + @property + def _prefs(self): # noqa: ANN202 - the Preferences of the context. + return self._ctx.preferences + + @property + def available(self) -> bool: + """Whether this platform can play a sound.""" + return get_platform().sound + + @property + def enabled(self) -> bool: + """Whether sounds can play now: the platform can play them, and they are not muted.""" + return self.available and not bool(self._prefs.sound_muted) + + @property + def audible_theme(self) -> bool: + """Whether the theme makes a sound (``android`` or ``bell``, not ``none``).""" + return self._prefs.sound_theme != "none" + + def event_on(self, event: SoundEvent) -> bool: + """Whether the preference of an event turns it on (refer to EVENT_PREFERENCE). + + The mention is on unless its rule treats a mention as a regular message. + """ + if event is SoundEvent.MENTION: + return self._prefs.sound_mention != "regular" + return bool(self._prefs.get(EVENT_PREFERENCE[event])) + + def toggle(self) -> bool: + """Mute or unmute the sounds (the ^S key), and save the preference. + + Returns: + ``True`` if the sounds are now on (not muted). + """ + muted = not bool(self._prefs.sound_muted) + self._prefs.set("sound_muted", muted) + try: + self._prefs.save() + except OSError as error: + log.warning("sound: could not save the preferences: %s", error) + return not muted + + def notify(self, event: SoundEvent) -> bool: + """Play the sound of an event, and flash the title bar if the preference says so. + + An event that its preference turns off does nothing: no sound, and no flash. + + Args: + event: The event. + + Returns: + ``True`` if a sound started (a file or the bell). + """ + if not self.event_on(event): + return False + tick = event is SoundEvent.PACKET_TICK + if tick and self._clock() - self._last_sound < TICK_GAP_S: + return False + audible = self.enabled and self._emit(event) + if not tick: + mode = self._prefs.notify_flash + if mode == "on" or (mode == "silent" and not audible): + if self._flash is not None: + self._flash() + return audible + + def note_battery(self, percent: int, *, charging: bool) -> None: + """Play the battery-low sound one time when the battery goes below the threshold. + + The battery service calls this method after each reading. The sound plays when the + level goes below ``battery_low_pct`` while the pack does not charge. It can play + again only after the level rises :data:`BATTERY_REARM_PCT` points above the + threshold, or the pack charges. + + Args: + percent: The level of the battery, from 0 to 100. + charging: Whether the pack takes charge now. + """ + threshold = int(self._prefs.battery_low_pct) + if charging or percent >= threshold + BATTERY_REARM_PCT: + self._battery_armed = True + elif percent < threshold and self._battery_armed: + self._battery_armed = False + self.notify(SoundEvent.BATTERY_LOW) + + def preview( + self, event: SoundEvent = SoundEvent.CHANNEL_MESSAGE, volume: int | None = None + ) -> bool: + """Play the sound of an event at the current volume, also when the sounds are muted. + + The Preferences page calls it while the user changes the volume or the theme + (JP, 2026-11-20: "while adjusting the volume, play the channel message sound"). + + Args: + event: The event whose sound plays. + volume: The volume from 1 to 10, or ``None`` for the ``sound_volume`` + preference. The volume slider gives the value that it shows, before the + user applies it. + + Returns: + ``True`` if a sound started. + """ + return self.available and self._emit(event, volume) + + def _emit(self, event: SoundEvent, volume: int | None = None) -> bool: + """Play the sound of an event in the current theme, with no rules.""" + theme = self._prefs.sound_theme + if theme == "bell": + if self._bell is None: + return False + self._bell() + self._last_sound = self._clock() + return True + files = THEMES.get(theme) + if not files or event not in files: + return False + try: + path = scaled( + SOUNDS_DIR / files[event], + int(self._prefs.sound_volume if volume is None else volume) * 10, + self._ctx.settings.config_dir / "sound-cache", + ) + except (OSError, wave.Error, EOFError) as error: + log.warning("sound: could not prepare %s: %s", files[event], error) + return False + if not self._player.play(path): + return False + self._last_sound = self._clock() + return True diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 3f6c268..3e5fbca 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -31,6 +31,7 @@ from ..core import exitcodes, mcoimg, reactions from ..core.channels import ( CHANNEL_SLOT_PROBE_CAP, DEFAULT_PUBLIC_SECRET, + MAX_CHANNELS, MENTION, channel_hash, channel_identity, @@ -80,6 +81,7 @@ if TYPE_CHECKING: from datetime import datetime from ..core.channel_probe import ChannelSlot + from ..services.heard_by import HeardBy from ..ui.report import Facts, Listing #: The number of recent messages that ``chat history`` prints by default. @@ -419,12 +421,14 @@ class ChatTool(Tool): room = False name_of: NodeResolver | None = None me: NodeRef | None = None + heard: Callable[[ChatMessage], HeardBy | None] | None = None if channel is not None: channel_id = await ctx.chat.channel_id_for(int(channel)) messages = ctx.repo.recent_chat_messages( is_channel=True, channel_id=channel_id, limit=limit ) label = f"#{channel}" + heard = await _channel_verdicts(ctx, int(channel), messages) else: device = await ctx.device() contacts = await device.get_contacts() @@ -443,7 +447,7 @@ class ChatTool(Tool): return ToolResult( summary={"conversation": label, "messages": len(messages)}, - report=(_transcript(messages, room=room, name_of=name_of, me=me),), + report=(_transcript(messages, room=room, name_of=name_of, me=me, heard=heard),), exit_code=exitcodes.OK if messages else exitcodes.NO_RESULT, ) @@ -640,18 +644,24 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]: This function maps that cached :class:`~meshterm.core.channel_probe.ChannelSlot` list onto the :class:`~meshterm.core.models.Conversation` rows of the picker. - When slot 0 is empty and no slot has the Public channel, this function adds a Public row - with ``on_device=False``. The device cannot send on a slot that it does not have: it - refuses the send. Thus that row never opens a chat. It is an offer: Enter asks to add - Public to slot 0 (refer to :func:`_add_public_channel`). Issue #36 was a row that looked - the same as a real channel and failed on each send. + When no slot has the Public channel, this function adds a Public row with + ``on_device=False``, on the lowest free slot. The device cannot send on a slot that it + does not have: it refuses the send. Thus that row never opens a chat. It is an offer: + Enter asks to add Public (refer to :func:`_add_public_channel`). Issue #36 was a row + that looked the same as a real channel and failed on each send. + + The offer asks only for the key of the channel, and not for slot 0. A user who made a + ``#Public`` channel by mistake (its key comes from its name, so it is a different + channel that nobody else is on) filled slot 0 with it. The offer then disappeared, + which hid the one way back to the real channel. The name of a slot proves nothing: only + the well-known key does. Args: slots: The configured channel slots, from the session cache. Returns: One :class:`~meshterm.core.models.Conversation` for each slot. A Public offer is at - the start when the device has no Public channel and slot 0 is empty. + the start when the device has no Public channel and a slot is free for it. """ conversations = [ Conversation( @@ -663,46 +673,56 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]: ) for slot in slots ] - if not any(c.channel_idx == 0 for c in conversations) and not any( - slot.secret == DEFAULT_PUBLIC_SECRET for slot in slots - ): - conversations.insert( - 0, - Conversation( - label="Public", - is_channel=True, - channel_idx=0, - channel_id="slot:0", - secret=DEFAULT_PUBLIC_SECRET, - on_device=False, - ), - ) + if not any(slot.secret == DEFAULT_PUBLIC_SECRET for slot in slots): + # The slot that the row names is the lowest one that no channel uses. The capacity + # of the device is not read here: that probe is a round trip, and this function runs + # at each paint of the picker. The add confirms the slot against the real capacity + # (refer to :func:`_add_public_channel`), and says so if there is no slot to give. + used = {slot.idx for slot in slots} + free = next((i for i in range(MAX_CHANNELS) if i not in used), None) + if free is not None: + conversations.insert( + 0, + Conversation( + label="Public", + is_channel=True, + channel_idx=free, + channel_id=f"slot:{free}", + secret=DEFAULT_PUBLIC_SECRET, + on_device=False, + ), + ) return conversations async def _add_public_channel(ctx: AppContext) -> Conversation | None: - """Ask to add the Public channel to slot 0. Write it if the user agrees. + """Ask to add the Public channel to a free slot. Write it if the user agrees. The Chat picker calls this function for its Public offer (``on_device=False``, refer to :func:`_channels_from_slots`). The function asks first and does not write silently, because the write changes what the device stores. The precedent is the contact that is not on the device (refer to :func:`meshterm.ui.chat._restore_contact`). + The slot comes from :func:`~meshterm.ui.channels._pick_free_slot`, which the channel + manager uses for each add. Thus the capacity of the device sets the slot, and the slot + is read one more time before the write. A cached slot list can be short (a probe that + stopped in the middle), and a slot that the probe did not reach must not be overwritten. + Args: ctx: The shared application context. Returns: The conversation of the Public channel on the device, ready to open. ``None`` if the - user cancelled, or if the probe after the write does not find the channel. + user cancelled, if no slot is free, or if the probe after the write does not find + the channel. Raises: DeviceCommandError: If the device refused the write. """ - from ..ui.channels import write_channel + from ..ui.channels import _pick_free_slot, write_channel add = await ctx.ui.dialog( - "This device has no Public channel, so it can't send there. " - "Add Public to slot 0 and open it?", + "This device has no Public channel, so it can't send there. Add Public and open it?", [("Cancel", False), ("Add", True)], title="Channel not on device", default=1, @@ -710,9 +730,15 @@ async def _add_public_channel(ctx: AppContext) -> Conversation | None: if not add: return None device = await ctx.device() - await write_channel(ctx, device, 0, "Public", DEFAULT_PUBLIC_SECRET) + slots = await ctx.devstate.channel_slots() + idx = await _pick_free_slot(ctx, device, slots, await ctx.devstate.channel_capacity()) + if idx is None: # full, or the slot could not be read: _pick_free_slot said why + return None + await write_channel(ctx, device, idx, "Public", DEFAULT_PUBLIC_SECRET) channels = _channels_from_slots(await ctx.devstate.channel_slots()) - return next((c for c in channels if c.on_device and c.channel_idx == 0), None) + # The key identifies the channel, and not the slot: the write went to the slot that the + # confirming read gave, which can be another slot than the one that the row named. + return next((c for c in channels if c.on_device and c.secret == DEFAULT_PUBLIC_SECRET), None) async def _read_channels(device: Device) -> list[Conversation]: @@ -1277,7 +1303,7 @@ def _channel_ref(idx: int | None, label: str, secret: bytes | None) -> ChannelRe ) -def _message_columns(*, author_lane: bool = False) -> tuple: +def _message_columns(*, author_lane: bool = False, heard_lane: bool = False) -> tuple: """The columns of one transcript row, shared by ``history`` and the ``listen`` stream. ``DIR`` holds what the transcript of the menu writes into its sender lane as the word @@ -1304,7 +1330,7 @@ def _message_columns(*, author_lane: bool = False) -> tuple: """ from dataclasses import replace - from ..ui import fields + from ..ui import fields, report peer = fields.plain_only(fields.name("conversation", "PEER")) when = fields.plain_only(fields.when("shown_at", "TIME")) @@ -1330,8 +1356,19 @@ def _message_columns(*, author_lane: bool = False) -> tuple: fields.channel("channel", lanes=()), _author_column(lane=author_lane), fields.snr("snr_db", "SNR_DB"), + *( + ( + fields.plain_only( + report.Column(key="heard_cell", lanes=(report.Lane(header="HEARD"),)) + ), + ) + if heard_lane + else () + ), fields.free("text", "TEXT"), fields.hidden("acked"), + fields.hidden("heard"), + fields.hidden("heard_by"), ) @@ -1377,12 +1414,38 @@ def _author_ref(author: str, name_of: NodeResolver | None) -> NodeRef: return NodeRef(name=label if key else None, hash=author) +async def _channel_verdicts( + ctx: AppContext, channel: int, messages: list[ChatMessage] +) -> Callable[[ChatMessage], HeardBy | None] | None: + """The verdicts on our messages in a channel: did a repeater send a copy back? + + Refer to :mod:`~meshterm.services.heard_by`. With no key for the slot, there is no + verdict, and the column is absent on each row. + """ + from ..services.heard_by import make_tracker + + try: + device = await ctx.device() + payload = await device.get_channel(channel) + raw = (payload or {}).get("channel_secret") + secret = bytes(raw) if raw else None + name = str((payload or {}).get("channel_name") or f"#{channel}") + except Exception: # noqa: BLE001 - no key, no verdict. The history still prints + return None + tracker = make_tracker(ctx, channel_name=name, secret=secret) + if tracker is None: + return None + await tracker.fill(messages) + return tracker.verdict + + def _transcript( messages: list[ChatMessage], *, room: bool = False, name_of: NodeResolver | None = None, me: NodeRef | None = None, + heard: Callable[[ChatMessage], HeardBy | None] | None = None, ) -> Listing: """The stored messages of a conversation, oldest first, one record for each. @@ -1393,6 +1456,9 @@ def _transcript( each row). name_of: Names the key of an author, for a room. me: Our node, the author of our own posts in a room. + heard: Gives the verdict on each of our channel messages (refer to + :mod:`~meshterm.services.heard_by`). With it, the plain face has a ``HEARD`` + lane. The document always has ``heard`` and ``heard_by``. """ from ..ui.report import Listing @@ -1405,6 +1471,7 @@ def _transcript( else None ) corrected = message.corrected(tolerance) + verdict = heard(message) if heard is not None else None rows.append( { "created_at": message.created_at, @@ -1425,16 +1492,36 @@ def _transcript( "snr_db": message.snr, "text": message.text, "acked": message.acked, + "heard": verdict.state if verdict is not None else None, + "heard_by": list(verdict.relays) if verdict is not None else None, + "heard_cell": _heard_cell(verdict), } ) + lanes = ("TIME", "DIR", "AUTHOR" if room else "PEER", "SNR_DB") return Listing( key="messages", - columns=_message_columns(author_lane=room), + columns=_message_columns(author_lane=room, heard_lane=heard is not None), rows=rows, - order=("TIME", "DIR", "AUTHOR" if room else "PEER", "SNR_DB", "TEXT"), + order=(*lanes, "HEARD", "TEXT") if heard is not None else (*lanes, "TEXT"), ) +def _heard_cell(verdict: HeardBy | None) -> str: + """The plain ``HEARD`` cell: the number of relays that sent a copy back, or a word. + + ``none`` is a message that no repeater sent back, and ``wait`` is one that is still in + its wait. A message that is not ours has no verdict (``-``). + """ + from ..services.heard_by import HEARD, UNHEARD, WAITING + from ..ui import script + + if verdict is None: + return script.NONE + if verdict.state == HEARD: + return str(len(verdict.relays)) + return {UNHEARD: "none", WAITING: "wait"}.get(verdict.state, script.NONE) + + def _live_messages() -> Listing: """The shape that ``chat listen`` streams: what arrived, when it arrived. diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py index 501dbcb..0546e2b 100644 --- a/meshterm/tools/config.py +++ b/meshterm/tools/config.py @@ -426,15 +426,36 @@ async def _show(ctx: AppContext, device: Device, snapshot: dict) -> Listing | No the one value in it that lets the phone of another person connect to the radio. ``config get device_pin`` names it on purpose. """ - from ..ui import fields, script - from ..ui.config_editor import PIN_KEY, conceal, config_table - from ..ui.report import Listing + from ..ui.config_editor import config_table from ..ui.surface import TuiUi custom = await device.get_custom_vars() if isinstance(ctx.ui, TuiUi): ctx.ui.show(config_table(snapshot, custom)) return None + return settings_listing(snapshot, custom) + + +def settings_listing(snapshot: dict, custom: dict[str, str]) -> Listing: + """Every setting and custom variable of a snapshot, as one listing. + + This is the scripted face of the settings table, and it is the only definition of it. + ``config show`` answers with it. ``info`` puts it under its status block, so that the + scripted face says the same about a device as the Device info page does + (:func:`~meshterm.tools.info.InfoTool.run`). Both faces use these keys, exactly as + ``config get`` and ``config set`` name them. Thus one setting is never spelled two + ways. + + Args: + snapshot: The device snapshot from ``build_snapshot``. + custom: The current custom variables of the device. + + Returns: + The listing, with one record for each setting and each custom variable. + """ + from ..ui import fields, script + from ..ui.config_editor import PIN_KEY, conceal + from ..ui.report import Listing rows: list[dict[str, Any]] = [] for _category, specs in settings_by_category(): diff --git a/meshterm/tools/info.py b/meshterm/tools/info.py index 4e2f9fa..ef30b29 100644 --- a/meshterm/tools/info.py +++ b/meshterm/tools/info.py @@ -5,20 +5,77 @@ from __future__ import annotations import time from collections.abc import Callable +from dataclasses import dataclass from datetime import datetime, timezone from typing import TYPE_CHECKING, Any import typer from rich.panel import Panel +from rich.table import Table from rich.text import Text from ..context import AppContext -from ..core.connection import Device +from ..core.connection import Device, derived_scope_key +from ..core.device_config import current_preset from ..core.models import node_type_label from .base import Tool, ToolResult, register if TYPE_CHECKING: # pragma: no cover - typing only - from ..ui.report import Column, Facts + from ..ui.report import Column, Facts, Listing + +#: The unit of each kind of telemetry reading that a companion can report. A reading whose +#: kind is not here has no unit (a count, a state, or a reading with several fields). The +#: names are the names that the Cayenne LPP decoder gives +#: (refer to :func:`~meshterm.core.connection.lpp_readings`). +_UNITS = { + "temperature": "Β°C", + "humidity": "%", + "percentage": "%", + "voltage": "V", + "current": "A", + "barometer": "hPa", + "illuminance": "lux", + "altitude": "m", + "distance": "m", + "energy": "kWh", + "power": "W", + "load": "kg", + "concentration": "ppm", + "direction": "Β°", + "frequency": "Hz", + "time": "s", +} + + +@dataclass(frozen=True, slots=True) +class AppFacts: + """What MeshTerm itself knows about the connected node, beside what the radio reports. + + The radio answers for its own settings and its own counters. These facts come from the + other side: the stores of this computer, the caches of the session, and what MeshTerm + derives from the radio settings. The Device info page shows them with the facts of the + radio, because the user reads one node and not two sources. + + Attributes: + place: The named area nearest the location of the node, or ``None``. + site: The name of the active site, or ``None`` when no site is active. + outbound_paths: How many outbound paths apply to this device. + fixed: Whether those paths come from a fixed-device list and not from the site. + kept_routes: How many device routes the user keeps for this device. + contacts: How many contacts the device holds, or ``None`` when no read gave them. + channels: How many channels are set, or ``None`` when no read gave them. + preset: The name of the radio preset that the four radio settings match, or + ``None`` when they match no preset. + """ + + place: str | None = None + site: str | None = None + outbound_paths: int | None = None + fixed: bool = False + kept_routes: int | None = None + contacts: int | None = None + channels: int | None = None + preset: str | None = None @register @@ -38,6 +95,15 @@ class InfoTool(Tool): async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: """Query the device, and render its live status and all its settings. + Both faces answer with the same three parts, in the same order: the status of the + device, its sensor readings, and every setting that it holds. The menu draws the + parts as a panel over the settings table. The scripted face returns them as three + blocks, and the renderer of the boundary prints them. + + The settings come from one definition, :func:`~meshterm.tools.config.settings_listing`, + which ``config show`` answers with. Thus the scripted face of this command says the + same about a device as the page does, and no setting is spelled two ways. + Args: ctx: The shared application context. params: Not used. @@ -51,32 +117,39 @@ class InfoTool(Tool): device = await ctx.device() snapshot = await cached_snapshot(ctx, device) + readings = await read_status(device) + app = await app_facts(ctx, snapshot) - # On the CLI, this is only the status report: the current condition of the device, - # one fact on each line. The settings are the answer of `config show`, with the - # same keys that `config get` and `config set` take. If this command also prints - # the settings, the same table shows two times, with two different spellings. + # On the CLI, the status block, the sensor readings, and the settings, in that + # order. The settings keep the keys that `config get` and `config set` take. session = getattr(ctx.ui, "session", None) if session is None: + from .config import settings_listing + + custom = await device.get_custom_vars() return ToolResult( summary={"name": snapshot.get("name")}, - report=(await status_facts(device, snapshot),), + report=( + status_facts(snapshot, readings, app), + telemetry_listing(readings["telemetry"]), + settings_listing(snapshot, custom), + ), ) from ..ui.device_info_screen import DeviceInfoScreen custom = await device.get_custom_vars() - # A live status panel (role, firmware, battery, clock, radio and packet statistics) - # above all the current settings, each with a short explanation. The panel is read - # one time. Only the table is different between the two states, and it is fast to - # build again. - panel = await _status_panel(device, snapshot) + # A live status panel (identity, place, scope, site, health, and the traffic + # statistics) above all the current settings, each with a short explanation. The + # panel is built one time. Only the table is different between the two states, and + # it is fast to build again. + panel = status_panel(snapshot, readings, app) def page(reveal_pin: bool) -> Group: return Group(panel, Text(""), config_table(snapshot, custom, reveal_pin=reveal_pin)) # The page is a separate screen, because it has its own keyboard key: the pairing - # PIN is masked until ``p`` shows it. + # PIN is masked until ``^E`` shows it. await session.run_screen( DeviceInfoScreen(session, page, title=self.title, conceals=has_pin(snapshot)) ) @@ -95,116 +168,391 @@ class InfoTool(Tool): run_tool_command(self, {}) -# -- the status panel ----------------------------------------------------------- +# -- the reads ------------------------------------------------------------------ -async def _read_status(device: Device) -> dict[str, Any]: +async def read_status(device: Device) -> dict: """Read each live status value that the firmware gives, as a best effort. - This is the only place that asks the device. Both faces use what it returns: the panel - of the menu makes prose rows from these values, and the CLI prints them one fact on - each line (refer to :func:`_status_panel` and :func:`status_facts`). Each read is - optional, because firmware that is older than a query gives nothing for it. Thus this - function works on any device. + This is the only place that asks the device for its live state. Both faces use what it + returns: the panel of the menu makes prose rows from these values, and the CLI prints + them one fact on each line (refer to :func:`status_panel` and :func:`status_facts`). + Each read is optional, because firmware that is older than a query gives nothing for + it. Thus this function works on any device. + + The device-query frame is not read here. :func:`~meshterm.core.device_config.build_snapshot` + already merges it into the snapshot, and one frame read one time is enough. Args: device: The connected device to query. Returns: - The merged raw readings: ``info``, ``battery``, ``stats``, and ``clock``. + The merged raw readings: ``battery``, ``stats``, ``clock``, and ``telemetry``. """ return { - "info": await _try(device.get_device_info) or {}, "battery": await _try(device.get_battery) or {}, "stats": await _try(device.get_stats) or {}, "clock": await _try(device.get_time), + "telemetry": await _try(device.get_self_telemetry) or [], } -async def _status_panel(device: Device, snapshot: dict) -> Panel: - """Build the live status panel: role, firmware, battery, clock, and statistics. +async def app_facts(ctx: AppContext, snapshot: dict) -> AppFacts: + """Collect what MeshTerm knows about the connected node, from its own stores. - This is the menu face of :func:`_read_status`. Each row is a short phrase, not an - atomic value, because a person reads "-110 dBm noise floor Β· last RSSI -62 dBm" in one - step. A script wants the three numbers separately. + Nothing here asks the radio. The place comes from the place service or from what it + stored before, the site and the paths from the outbound store, the counts from the + caches of the session, and the preset from the four radio settings. + + The count of contacts comes from the device-state cache, which is one read and which + the menu fills at startup. The count of channels comes from the same cache, but this + function never fills it: that probe reads every slot index, and a count is not worth + that cost on a report command. Thus the scripted face leaves the count of channels out + and keeps the capacity, which the device-query frame gives for nothing. Args: - device: The connected device to query. - snapshot: The settings snapshot that is already built (for the role and identity - fields). + ctx: The shared application context. + snapshot: The device snapshot (it gives the key, the location, and the radio + settings). + + Returns: + The facts, each one ``None`` where MeshTerm has nothing to say. + """ + key = str(snapshot.get("public_key") or "") + preset = current_preset(snapshot) + site, paths, fixed, kept = _outbound(ctx, key) + return AppFacts( + place=_place(ctx, key, snapshot), + site=site, + outbound_paths=paths, + fixed=fixed, + kept_routes=kept, + contacts=await _contact_count(ctx), + channels=_channel_count(ctx), + preset=preset.name if preset is not None else None, + ) + + +def _place(ctx: AppContext, key: str, snapshot: dict) -> str | None: + """The place of our own node, and a request to find it when a session can. + + MeshTerm never hears its own node, so the finder knows where this node is only when a + page tells it. The node page does the same (refer to + :meth:`~meshterm.services.places.PlaceService.want_at`). The request is for the next + time that this page opens: the panel is built one time, and a place that arrives after + that is not drawn again. + """ + from ..services import places as place_service + + service = place_service.current() + if service is not None: + service.want_at(key, snapshot.get("adv_lat"), snapshot.get("adv_lon")) + place = place_service.place_of(ctx, key) + return place.label if place is not None else None + + +def _outbound(ctx: AppContext, key: str) -> tuple[str | None, int | None, bool, int | None]: + """The active site, the outbound paths that apply here, and the kept device routes.""" + from ..core.outbound_store import SOURCE_DEVICE + + store = getattr(ctx, "outbound_store", None) + if store is None: + return None, None, False, None + try: + choice = store.lookup(key or None) + site = store.active_site() + if not choice.name and site is None: + return None, None, False, None + return ( + site.name if site is not None else None, + len(choice.paths), + choice.source == SOURCE_DEVICE, + len(store.kept_routes(key or None)), + ) + except Exception: # noqa: BLE001 - a store that cannot be read costs one row, not the page + return None, None, False, None + + +async def _contact_count(ctx: AppContext) -> int | None: + """How many contacts the device holds, or ``None`` when the read did not answer.""" + devstate = getattr(ctx, "devstate", None) + if devstate is None: + return None + try: + return len(await devstate.contacts()) + except Exception: # noqa: BLE001 - an optional count. Its absence is acceptable. + return None + + +def _channel_count(ctx: AppContext) -> int | None: + """How many channels are set, from the cache only (refer to :func:`app_facts`).""" + devstate = getattr(ctx, "devstate", None) + if devstate is None: + return None + try: + slots = devstate.peek_channel_slots() + except Exception: # noqa: BLE001 - an optional count. Its absence is acceptable. + return None + return None if slots is None else len(slots) + + +# -- the status panel ----------------------------------------------------------- + + +def status_panel(snapshot: dict, readings: dict, app: AppFacts) -> Panel: + """Build the live status panel: who this node is, how it is, and what it heard. + + This is the menu face of :func:`read_status` and :func:`app_facts`. Each row is a short + phrase, not an atomic value, because a person reads "-110 dBm noise floor Β· last RSSI + -62 dBm" in one step. A script wants the three numbers separately. + + The rows sit in a two-column grid, so a value that is wider than the panel wraps under + its own column and never goes back to column zero. A key is the one value that this + always costs a second line, and it stays whole: the page is where a user reads the key + of this node out to another person. + + Args: + snapshot: The device snapshot (the identity, the radio settings, and the facts of + the device-query frame). + readings: The live readings from :func:`read_status`. + app: What MeshTerm knows itself, from :func:`app_facts`. Returns: A Rich :class:`Panel` of status rows, each with a label and a value. """ - rows: list[tuple[str, Text]] = [] - readings = await _read_status(device) - info, battery, stats = readings["info"], readings["battery"], readings["stats"] + rows = _status_rows(snapshot, readings, app) + if not rows: + return Panel( + Text("no status reported", style="muted"), + title="[title.border]Status[/]", + border_style="border", + expand=False, + ) + grid = Table.grid(padding=(0, 2)) + grid.add_column(style="muted", no_wrap=True) + grid.add_column(overflow="fold") + for label, value in rows: + grid.add_row(label, value if value is not None else "") + return Panel(grid, title="[title.border]Status[/]", border_style="border", expand=False) + +def _status_rows(snapshot: dict, readings: dict, app: AppFacts) -> list[tuple[str, Text | None]]: + """The rows of the status panel, in four groups with a blank row between them. + + The groups answer four questions, in the order in which a user asks them: what this + node is, what MeshTerm does with it, how it is doing, and what it heard and sent. A row + whose value nothing reported is left out, so a panel never has a column of question + marks. + """ + battery, stats = readings["battery"], readings["stats"] + groups: list[list[tuple[str, Text]]] = [[], [], [], []] + + # 1. What this node is. adv_type = snapshot.get("adv_type") if adv_type is not None: - role = node_type_label(adv_type) - rows.append(("role", Text(role, style="brand"))) + groups[0].append(("role", Text(node_type_label(adv_type), style="brand"))) + key = str(snapshot.get("public_key") or "") + if key: + groups[0].append(("key", _key_text(key, snapshot))) + if snapshot.get("model"): + groups[0].append(("model", Text(str(snapshot["model"])))) + firmware = _firmware_text(snapshot) + if firmware is not None: + groups[0].append(("firmware", firmware)) + if app.place: + groups[0].append(("place", Text(app.place))) - if info.get("model"): - rows.append(("model", Text(str(info["model"])))) - firmware = _firmware(info) - if firmware: - rows.append(("firmware", Text(firmware))) + # 2. What MeshTerm does with it. + groups[1].append(("scope", _scope_text(snapshot))) + site = _site_text(app) + if site is not None: + groups[1].append(("site", site)) + groups[1].append(("preset", Text(app.preset or "custom", style="" if app.preset else "muted"))) + # 3. How it is doing. level = battery.get("level") if level: - rows.append(("battery", Text(f"{int(level) / 1000:.2f} V"))) + groups[2].append(("battery", Text(f"{int(level) / 1000:.2f} V"))) if battery.get("total_kb"): - rows.append(("storage", Text(f"{battery.get('used_kb', 0)} / {battery['total_kb']} kB"))) - + groups[2].append( + ("storage", Text(f"{battery.get('used_kb', 0)} / {battery['total_kb']} kB")) + ) + telemetry = _telemetry_text(readings["telemetry"]) + if telemetry is not None: + groups[2].append(("telemetry", telemetry)) clock = readings["clock"] if clock: stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(clock)) - rows.append(("clock", Text.assemble(stamp, (f" {_drift(clock)}", "muted")))) - + groups[2].append(("clock", Text.assemble(stamp, (f" {_drift(clock)}", "muted")))) if stats.get("uptime_secs") is not None: - rows.append(("uptime", Text(_uptime(int(stats["uptime_secs"]))))) + groups[2].append(("uptime", Text(_uptime(int(stats["uptime_secs"]))))) + contacts = _capacity_text(app.contacts, snapshot.get("max_contacts")) + if contacts is not None: + groups[2].append(("contacts", contacts)) + channels = _capacity_text(app.channels, snapshot.get("max_channels")) + if channels is not None: + groups[2].append(("channels", channels)) + if stats.get("queue_len") is not None: + groups[2].append(("queue", Text(f"{stats['queue_len']} waiting to send"))) + if stats.get("errors") is not None: + groups[2].append(("errors", _count_text(int(stats["errors"])))) + + # 4. What it heard and sent. if stats.get("noise_floor") is not None: parts = Text(f"{stats['noise_floor']} dBm noise floor") if stats.get("last_rssi") is not None: parts.append(f" Β· last RSSI {stats['last_rssi']} dBm", style="muted") if stats.get("last_snr") is not None: parts.append(f" Β· last SNR {stats['last_snr']:+.1f} dB", style="muted") - rows.append(("radio", parts)) + groups[3].append(("radio", parts)) if stats.get("tx_air_secs") is not None: - rows.append( + groups[3].append( ("airtime", Text(f"TX {stats['tx_air_secs']} s Β· RX {stats.get('rx_air_secs', 0)} s")) ) if stats.get("recv") is not None: packets = Text(f"{stats.get('sent', 0)} sent Β· {stats['recv']} received") if stats.get("recv_errors"): packets.append(f" Β· {stats['recv_errors']} receive errors", style="warn") - rows.append(("packets", packets)) + groups[3].append(("packets", packets)) + for label, sent, received in ( + ("flood", "flood_tx", "flood_rx"), + ("direct", "direct_tx", "direct_rx"), + ): + if stats.get(sent) is None and stats.get(received) is None: + continue + groups[3].append( + (label, Text(f"{stats.get(sent, 0)} sent Β· {stats.get(received, 0)} received")) + ) - width = max((len(label) for label, _ in rows), default=0) - body = Text() - for i, (label, value) in enumerate(rows): + rows: list[tuple[str, Text | None]] = [] + for group in groups: + if not group: + continue + if rows: + rows.append(("", None)) + rows.extend(group) + return rows + + +def _key_text(key: str, snapshot: dict) -> Text: + """The public key of this node, with the bytes that the mesh routes on lit.""" + from ..ui.widgets import highlighted_hash + + mode = snapshot.get("path_hash_mode") + prefix = (int(mode) + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0 + return highlighted_hash(key, prefix) + + +def _firmware_text(snapshot: dict) -> Text | None: + """The firmware version and build, with the companion protocol version after it.""" + version = _firmware(snapshot) + protocol = snapshot.get("fw ver") + if not version and protocol is None: + return None + text = Text(version or "unknown", style="" if version else "muted") + if protocol is not None: + text.append(f" Β· protocol {protocol}", style="muted") + return text + + +def _scope_text(snapshot: dict) -> Text: + """The default flood scope: its name and key, or the plain statement that it has none. + + A scope that the device stores with a key that its own name does not give is a fault + that nothing else shows. The row says so, because a packet that goes out under that + key reaches nobody who listens for the name. + """ + name = snapshot.get("flood_scope") + if not name: + text = Text("unscoped") + text.append(" Β· floods reach everyone", style="muted") + return text + text = Text(str(name)) + stored = str(snapshot.get("flood_scope_key") or "") + if stored: + text.append(f" Β· key {stored}", style="muted") + if stored != derived_scope_key(str(name)): + text.append(" Β· the key does not match the name", style="warn") + return text + + +def _site_text(app: AppFacts) -> Text | None: + """The active site, the outbound paths that apply, and the kept device routes.""" + if app.site is None and app.outbound_paths is None: + return None + text = Text(app.site or "no site", style="" if app.site else "muted") + if app.outbound_paths is not None: + text.append(f" Β· {app.outbound_paths} paths", style="muted") + text.append(" (this device)" if app.fixed else "", style="muted") + if app.kept_routes: + text.append(f" Β· {app.kept_routes} kept routes", style="muted") + return text + + +def _capacity_text(count: int | None, capacity: Any) -> Text | None: + """``27 / 300``, or one of the two numbers when the other one is not known.""" + total = int(capacity) if isinstance(capacity, (int, float)) else None + if count is None and total is None: + return None + if count is None: + return Text.assemble((f"{total}", "muted"), (" capacity", "muted")) + if total is None: + return Text(f"{count}") + return Text.assemble(f"{count}", (f" / {total}", "muted")) + + +def _count_text(count: int) -> Text: + """A count of faults: plain while it is zero, and in the warn colour once it is not.""" + return Text(str(count), style="warn" if count else "") + + +def _telemetry_text(telemetry: list[dict]) -> Text | None: + """The sensor readings of this node on one line, each with its unit.""" + if not telemetry: + return None + text = Text() + for i, reading in enumerate(telemetry): if i: - body.append("\n") - body.append(f"{label.ljust(width)} ", style="muted") - body.append_text(value) - if not rows: - body = Text("no status reported", style="muted") - return Panel(body, title="[title.border]Status[/]", border_style="border", expand=False) + text.append(" Β· ", style="muted") + text.append(f"{reading.get('name')} ", style="muted") + text.append(_reading_value(reading)) + return text -def _firmware(info: dict) -> str: +def _reading_value(reading: dict) -> str: + """One telemetry value with its unit: ``21.5 Β°C``, or the fields of a compound reading.""" + value = reading.get("value") + if isinstance(value, dict): + return ", ".join(f"{name} {_number(item)}" for name, item in value.items()) + unit = _UNITS.get(str(reading.get("name") or ""), "") + return f"{_number(value)} {unit}".strip() + + +def _number(value: Any) -> str: + """A reading as the shortest form that keeps it exact (``4.1``, not ``4.100000``).""" + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, (int, float)): + return f"{value:g}" + return str(value) + + +def _firmware(snapshot: dict) -> str: """The firmware version and build, joined, or ``""`` if the device reported neither.""" - return " ".join(str(info[k]) for k in ("ver", "fw_build") if info.get(k)) + return " ".join(str(snapshot[k]) for k in ("ver", "fw_build") if snapshot.get(k)) -async def status_facts(device: Device, snapshot: dict) -> Facts: +# -- the scripted faces --------------------------------------------------------- + + +def status_facts(snapshot: dict, readings: dict, app: AppFacts) -> Facts: """The live status of the device, as one set of facts. - This is the CLI face of :func:`_read_status`. The panel writes a phrase in each row, - but this function writes one value for each key. It puts the unit in the key - (``battery_v``, ``uptime_s``, ``noise_floor_dbm``), so that no program must get the - number out of prose. On both faces, a number never has a unit in its value. + This is the scripted face of :func:`read_status` and :func:`app_facts`. The panel + writes a phrase in each row, but this function writes one value for each key. It puts + the unit in the key (``battery_v``, ``uptime_s``, ``noise_floor_dbm``), so that no + program must get the number out of prose. On both faces, a number never has a unit in + its value. The three readings in seconds and the clock drift have a **gloss** next to the number: ``uptime_s 93784 (1d 2h)``. This is the only key/value block that can have a gloss. @@ -213,6 +561,11 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: ``93784`` is a value that no person can easily understand. The document holds only the number, because it has no useful place for a phrase. + ``flood_scope`` is also a setting, and the settings block of this command has it too. + Both blocks print the one value that ``config get flood_scope`` returns, in the one + spelling that ``config set`` takes back. The status block keeps it because + ``flood_scope_key`` is here, and a key with no name next to it says little. + If the firmware gave no answer for a reading, the plain block **leaves out** that reading, and it does not show a dash. These are optional queries. A missing key says "this device does not report it", but a dash says that it reported nothing. The @@ -221,8 +574,10 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: different here on purpose. Args: - device: The connected device to query. - snapshot: The settings snapshot that is already built (for the role and identity). + snapshot: The device snapshot (the identity, the settings, and the facts of the + device-query frame). + readings: The live readings from :func:`read_status`. + app: What MeshTerm knows itself, from :func:`app_facts`. Returns: The facts block. @@ -230,35 +585,52 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: from ..ui import fields from ..ui.report import Facts - readings = await _read_status(device) - info, battery, stats = readings["info"], readings["battery"], readings["stats"] - + battery, stats = readings["battery"], readings["stats"] level = battery.get("level") adv_type = snapshot.get("adv_type") clock = readings["clock"] + scope = snapshot.get("flood_scope") values: dict[str, Any] = { # The identity is first: which device this is. All the values that it can be set - # to are the answer of `config show`, not of this command. + # to are in the settings block below the status block. "name": snapshot.get("name"), "public_key": str(snapshot.get("public_key") or "").lower() or None, "role": node_type_label(adv_type), - "model": info.get("model"), - "firmware": _firmware(info) or None, + "model": snapshot.get("model"), + "firmware": _firmware(snapshot) or None, + "protocol_version": snapshot.get("fw ver"), + "place": app.place, + "flood_scope": None if scope is None else fields.Rendered(scope, scope or '""'), + "flood_scope_key": snapshot.get("flood_scope_key"), + "preset": app.preset, + "site": app.site, + "outbound_paths": app.outbound_paths, + "kept_routes": app.kept_routes, "battery_v": round(int(level) / 1000, 2) if level else None, "storage_used_kb": battery.get("used_kb", 0) if battery.get("total_kb") else None, "storage_total_kb": battery.get("total_kb"), + "contacts": app.contacts, + "max_contacts": snapshot.get("max_contacts"), + "channels": app.channels, + "max_channels": snapshot.get("max_channels"), "clock_at": ( datetime.fromtimestamp(clock, tz=timezone.utc).astimezone() if clock else None ), "clock_drift_s": (clock - int(time.time())) if clock else None, "uptime_s": stats.get("uptime_secs"), + "queue_len": stats.get("queue_len"), + "firmware_errors": stats.get("errors"), "noise_floor_dbm": stats.get("noise_floor"), "last_rssi_dbm": stats.get("last_rssi"), "last_snr_db": stats.get("last_snr"), "tx_air_s": stats.get("tx_air_secs"), "rx_air_s": stats.get("rx_air_secs"), "packets_sent": stats.get("sent"), + "packets_sent_flood": stats.get("flood_tx"), + "packets_sent_direct": stats.get("direct_tx"), "packets_received": stats.get("recv"), + "packets_received_flood": stats.get("flood_rx"), + "packets_received_direct": stats.get("direct_rx"), "receive_errors": stats.get("recv_errors"), } return Facts( @@ -269,19 +641,37 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: fields.word("role", "role"), fields.word("model", "model"), fields.word("firmware", "firmware"), + fields.integer("protocol_version", "protocol_version"), + fields.name("place", "place"), + fields.rendered("flood_scope", "flood_scope"), + fields.hexid("flood_scope_key", "flood_scope_key"), + fields.word("preset", "preset"), + fields.name("site", "site"), + fields.integer("outbound_paths", "outbound_paths"), + fields.integer("kept_routes", "kept_routes"), fields.decimal("battery_v", "battery_v", ".2f"), fields.integer("storage_used_kb", "storage_used_kb"), fields.integer("storage_total_kb", "storage_total_kb"), + fields.integer("contacts", "contacts"), + fields.integer("max_contacts", "max_contacts"), + fields.integer("channels", "channels"), + fields.integer("max_channels", "max_channels"), fields.instant("clock_at", "clock_at"), _glossed("clock_drift_s", _drift_gloss), _glossed("uptime_s", _span_gloss), + fields.integer("queue_len", "queue_len"), + fields.integer("firmware_errors", "firmware_errors"), fields.integer("noise_floor_dbm", "noise_floor_dbm"), fields.integer("last_rssi_dbm", "last_rssi_dbm"), fields.snr("last_snr_db", "last_snr_db"), _glossed("tx_air_s", _span_gloss), _glossed("rx_air_s", _span_gloss), fields.integer("packets_sent", "packets_sent"), + fields.integer("packets_sent_flood", "packets_sent_flood"), + fields.integer("packets_sent_direct", "packets_sent_direct"), fields.integer("packets_received", "packets_received"), + fields.integer("packets_received_flood", "packets_received_flood"), + fields.integer("packets_received_direct", "packets_received_direct"), fields.integer("receive_errors", "receive_errors"), ), values=values, @@ -289,6 +679,50 @@ async def status_facts(device: Device, snapshot: dict) -> Facts: ) +def telemetry_listing(telemetry: list[dict]) -> Listing: + """The sensor readings of this node, one record for each reading. + + The readings are a listing and not more keys in the status block, because a device + reports whichever sensors it has. A key for each possible sensor would be a contract + that no firmware keeps. A record names the channel that the reading came from, the kind + of reading, and its value. + + The unit is a field of the record and not part of the key, because the kind of reading + is data here and not a key that MeshTerm declared. The plain face puts the unit in the + value, where a person reads it. The document keeps the number alone and the unit beside + it. + + Args: + telemetry: The readings from :func:`read_status`. + + Returns: + The listing. It has no records on a device that reports no sensors, and the plain + face then draws nothing. + """ + from ..ui import fields + from ..ui.report import Listing + + rows = [ + { + "channel": reading.get("channel"), + "name": reading.get("name"), + "unit": _UNITS.get(str(reading.get("name") or "")) or None, + "value": fields.Rendered(reading.get("value"), _reading_value(reading)), + } + for reading in telemetry + ] + return Listing( + key="telemetry", + columns=( + fields.integer("channel", "CHANNEL"), + fields.name("name", "READING"), + fields.rendered("value", "VALUE"), + fields.hidden("unit"), + ), + rows=rows, + ) + + def _glossed(key: str, gloss: Callable[[int], str]) -> Column: """A reading in seconds, printed as its number with a readable duration next to it.""" from ..ui import script @@ -327,12 +761,20 @@ async def _try(read) -> Any | None: def _drift(device_epoch: int) -> str: - """Describe the drift of the device clock, compared with the clock of this computer.""" + """Describe the drift of the device clock, compared with the clock of this computer. + + The drift is a duration that a person reads, and not a count of seconds: a clock that + was never set is a year out, and ``31330116 s`` says nothing. The scripted face writes + the same duration beside its own number (refer to :func:`_drift_gloss`), so the two + faces spell one drift one way. + """ + from ..ui import script + drift = device_epoch - int(time.time()) if abs(drift) < 2: return "(in sync)" direction = "ahead" if drift > 0 else "behind" - return f"({abs(drift)} s {direction})" + return f"({script.duration(abs(drift))} {direction})" def _uptime(secs: int) -> str: diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index aa3b9c5..2eec589 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -77,6 +77,7 @@ from ..core.channel_file import ( ) from ..core.channel_probe import ChannelSlot, probe_channel_slots from ..core.channels import ( + DEFAULT_PUBLIC_NAME, DEFAULT_PUBLIC_SECRET, MAX_CHANNELS, derive_secret, @@ -779,7 +780,7 @@ def _menu_items( if len(slots) > 1: items.append(section_heading("Organize")) reorder = marked_label("↕", "Reorder channels", "", lane=lane) - items.append(Choice(title=reorder, value=_REORDER)) + items.append(Choice(title=reorder, value=_REORDER, always_shown=True)) # Before "Add a channel", because that section ends early when each slot is full, and an # import still has work then: it puts the channels in the order of its file. @@ -833,7 +834,9 @@ def _menu_items( ) # One call for the rows of the two sections, so that their descriptions start in the same # column. Two calls aligned each section to its own widest label, four cells apart. - aligned = menu_rows(transfer + adds) + # The channel slots are the data of this page, and these rows are what the page does. + # Thus a typed filter narrows the slots and keeps each command (Choice.always_shown). + aligned = menu_rows(transfer + adds, always_shown=True) items.append(section_heading("Export and import")) items.extend(aligned[: len(transfer)]) items.append(section_heading("Add a channel")) @@ -1181,23 +1184,85 @@ async def _add_default_public( return 1 -async def _add_public( - ctx: AppContext, device: Device, slots: list[ChannelSlot], capacity: int -) -> int: - """Create a public channel. The key comes from its name, which starts with ``#``.""" - idx = await _pick_free_slot(ctx, device, slots, capacity) - if idx is None: - return 0 +async def _ask_public_name(ctx: AppContext, slots: list[ChannelSlot]) -> tuple[str, bool] | None: + """Ask for the name of a public channel, and ask again when the name says ``Public``. + + The built-in Public channel of MeshCore has a fixed key that does not come from its name + (:data:`~meshterm.core.channels.DEFAULT_PUBLIC_SECRET`). Thus ``#Public`` is **not** that + channel. Its key comes from its name, its hash is different, and no other node is on it. + But the two rows that add a channel are beside each other in the menu, and ``Public`` is + the obvious word to type for the name of a public channel. A user who did this got a + channel that looked correct, that sent with no error, and that nobody heard. + + Thus this name gets a question. The question does not refuse the name: a user who wants + ``#Public`` can have it. It offers the standard channel instead, which is what the user + almost always wanted, and it says where that channel already is when a slot has it. + + Args: + ctx: The shared application context. + slots: The slots as they were last read, to find the standard Public channel. + + Returns: + The name to write, and whether the name derives the key (``False`` for the standard + Public channel, which carries its own fixed key). ``None`` if the user cancelled. + """ raw = await ctx.ui.text( "Public channel name:", help_text="A leading # is added automatically; the key is derived from the name", validate=_nonblank, ) if not raw: - return 0 + return None name = raw.strip() if not name.startswith("#"): name = f"#{name}" + if name.lstrip("#").casefold() != DEFAULT_PUBLIC_NAME: + return name, True + warning = ( + f"{name} is not the standard Public channel. Its key comes from its name, " + "so no other node is on that channel." + ) + here = next((slot for slot in slots if slot.secret == DEFAULT_PUBLIC_SECRET), None) + if here is not None: # nothing to offer: the real channel is already on the device + answer = await ctx.ui.dialog( + Text(f"{warning} The standard Public is already on slot {here.idx}.", style="warn"), + [("Cancel", None), (name, "named")], + title="Not the standard Public", + default=1, + danger=True, + ) + return (name, True) if answer == "named" else None + answer = await ctx.ui.dialog( + Text(f"{warning} The standard Public channel has one fixed key.", style="warn"), + [("Cancel", None), (name, "named"), ("Standard", "standard")], + title="Not the standard Public", + default=2, + danger=True, + ) + if answer == "standard": + return "Public", False + return (name, True) if answer == "named" else None + + +async def _add_public( + ctx: AppContext, device: Device, slots: list[ChannelSlot], capacity: int +) -> int: + """Create a public channel. The key comes from its name, which starts with ``#``. + + The name ``Public`` is the one name that asks again, because it names another channel + than the one that the user means (refer to :func:`_ask_public_name`). The answer can + write the standard Public channel on the slot instead. + """ + idx = await _pick_free_slot(ctx, device, slots, capacity) + if idx is None: + return 0 + chosen = await _ask_public_name(ctx, slots) + if chosen is None: + return 0 + name, derived = chosen + if not derived: # the standard Public channel, which carries its own well-known key + await write_channel(ctx, device, idx, name, DEFAULT_PUBLIC_SECRET) + return 1 secret = derive_secret(name) # what the firmware will calculate. It is for the QR and share await write_channel(ctx, device, idx, name, None) # None: the firmware derives the key await _show_share(ctx, name, secret) diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 46867b6..6036956 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -42,6 +42,7 @@ from ..core.models import ( ) from ..core.regions import WILDCARD from ..platforms import Platform, on_platform +from ..services.heard_by import HEARD, UNHEARD, WAITING, HeardBy, HeardTracker from . import pixelart from .compose import MentionEditor from .pathline import PATH_INK, PathHop @@ -89,6 +90,9 @@ _CORRECTED = ("?", "warn") #: animated spinner instead (refer to :meth:`ChatScreen._delivery_glyph`). _DELIVERED = ("βœ“", "ok") _FAILED = ("βœ—", "err") +#: The time that the chat waits after a channel packet before it looks for copies of our +#: messages in the packet log. The recorder stores each packet in the background. +_HEARD_SETTLE_S = 1.0 #: A word between whitespace. The wrap moves a word only as a whole. Thus the run that a #: wrap must not cut a URL in is the word that has the URL, with a bracket or a full stop @@ -306,6 +310,8 @@ class ChatScreen(Screen): part_gap_s: float = 0.0, self_key: str | None = None, resend_flood: Callable[[ChatMessage], Awaitable[ChatMessage]] | None = None, + heard: HeardTracker | None = None, + hop_name: Callable[[str], str] | None = None, ) -> None: """Build the chat screen. @@ -360,8 +366,20 @@ class ChatScreen(Screen): resend_flood: Like ``resend``, but it first forgets the route that the device learned to the contact, so that the retry floods (direct chats only). With ``None``, ^R always retries on the route, as it did before. + heard: The verdicts on our own channel messages: whether a repeater sent a copy + back (refer to :mod:`~meshterm.services.heard_by`). + With ``None`` (a direct chat, or a channel with no key), our channel + messages show no mark. + hop_name: Gives the name of a relay from its hash, for the note under a + selected message. With ``None``, the note shows the hashes. """ super().__init__() + self._heard_by = heard + self._hop_name: Callable[[str], str] = hop_name or (lambda hop: hop) + # The task that turns the spinner while one of our channel messages waits for a + # relay, and the task that examines the packet log again after a channel packet. + self._heard_ticker: asyncio.Task | None = None + self._heard_refresh: asyncio.Task | None = None self._self_name = self_name self._self_key = self_key self._scope = scope if conversation.is_channel else None @@ -794,7 +812,7 @@ class ChatScreen(Screen): # the divider. The heading of a select list can also have its description. self._sticky_headers = [] ids: list[int] = [] - ackeds: list[bool | None] = [] + ackeds: list[tuple] = [] selecteds: list[bool] = [] reacts: list[int] = [] boundaries: list[int] = [] @@ -820,7 +838,10 @@ class ChatScreen(Screen): # A slice that the selection changes renders again, now and on the next paint # after the selection leaves it: the selected message, and the head of its group. marked = selected or idx == picked_head - pending = message.acked is None and message.outbound and not message.is_channel + mark_key = self._mark_key(message) + pending = (message.acked is None and message.outbound and not message.is_channel) or ( + mark_key[1] is not None and mark_key[1][0] == WAITING + ) react_count = self._fold.count(message) if self._fold is not None else 0 reusable = ( not marked @@ -828,7 +849,7 @@ class ChatScreen(Screen): and idx < cache_count and not cached_selected[idx] and cached_ids[idx] == id(message) - and cached_acked[idx] == message.acked + and cached_acked[idx] == mark_key and cached_reacts[idx] == react_count ) # A blank line closes the messages of an author and the messages of a day, where @@ -874,7 +895,7 @@ class ChatScreen(Screen): self._selected_end = len(lines) prev_group, prev_day = group, day ids.append(id(message)) - ackeds.append(message.acked) + ackeds.append(mark_key) selecteds.append(marked) reacts.append(react_count) boundaries.append(len(lines)) @@ -1048,6 +1069,11 @@ class ChatScreen(Screen): ) indent = prefix.cell_len lines += render_hanging(Text(" " * indent), note, width, indent=indent) + heard = self._heard(message) if selected else None + heard_note = self._heard_note(heard) if heard is not None else None + if heard_note is not None: + indent = prefix.cell_len + lines += render_hanging(Text(" " * indent), heard_note, width, indent=indent) if image is not None and self._show_images: picture = pixelart.decoded(body) if picture is not None: @@ -1126,6 +1152,11 @@ class ChatScreen(Screen): if message.is_channel: if message.acked is False: text.append(" ⚠ no ack", style="warn") + else: + heard = self._heard(message) + if heard is not None: + text.append(" ") + text.append_text(self._heard_mark(heard)) text.append_text(self._scope_note(message)) else: text.append(" ") @@ -1215,6 +1246,113 @@ class ChatScreen(Screen): glyph, style = _DELIVERED if acked else _FAILED return Text(glyph, style=style) + # --- relays that heard our channel messages (issue #38) ------------------------ + + def _heard(self, message: ChatMessage) -> HeardBy | None: + """The verdict on one of our channel messages, or ``None`` when it has no mark.""" + return self._heard_by.verdict(message) if self._heard_by is not None else None + + def _mark_key(self, message: ChatMessage) -> tuple: + """What the mark at the end of a message depends on, for the render cache.""" + heard = self._heard(message) + return ( + message.acked, + None if heard is None else (heard.state, heard.relays), + ) + + def _heard_mark(self, heard: HeardBy) -> Text: + """The mark at the end of our channel message: the marks of a direct message. + + The spinner turns while no repeater sent a copy back, until the ``heard_wait_s`` + wait is over. Then ``βœ“`` and the number of the relays, or ``βœ—`` for no copy at all. + """ + if heard.state == WAITING: + return self._spinner.text() + if heard.state == HEARD: + glyph, style = _DELIVERED + return Text(f"{glyph} {len(heard.relays)}", style=style) + glyph, style = _FAILED + return Text(glyph, style=style) + + def _heard_note(self, heard: HeardBy) -> Text | None: + """The line under a selected channel message of ours: which relays heard it.""" + note = Text() + if heard.state == HEARD: + names = ", ".join(self._hop_name(hop) for hop in heard.relays) + note.append(f"{_DELIVERED[0]} ", style=_DELIVERED[1]) + note.append(f"relayed by {names}", style="muted") + elif heard.state == UNHEARD: + note.append(f"{_FAILED[0]} ", style=_FAILED[1]) + note.append("no repeater sent it back", style="muted") + else: + return None + return note + + def start_heard(self) -> None: + """Examine our channel messages in the background, then turn the spinners.""" + if self._heard_by is None: + return + + async def fill() -> None: + assert self._heard_by is not None + await self._heard_by.fill(self._messages) + self._render_cache = None + self._session.invalidate() + self._tick_heard() + + self._spawn(fill()) + + def track_sent(self, message: ChatMessage) -> None: + """Start the verdict of a channel message that we just sent.""" + if self._heard_by is None: + return + self._heard_by.note_sent(message) + self._tick_heard() + + def heard_packet(self) -> None: + """The device heard a channel packet: look again for copies of our messages. + + The recorder stores the packet in the background, so the look waits a moment. One + look covers each packet that arrives in that moment. + """ + if self._heard_by is None or ( + self._heard_refresh is not None and not self._heard_refresh.done() + ): + return + + async def refresh() -> None: + assert self._heard_by is not None + await asyncio.sleep(_HEARD_SETTLE_S) + if self._heard_by.refresh(self._messages): + self._session.invalidate() + + self._heard_refresh = self._spawn(refresh()) + + def _tick_heard(self) -> None: + """Turn the spinner while one of our channel messages waits for a relay. + + The loop stops when no message waits. At the end of a wait, it looks one more + time in the packet log, so that the mark that replaces the spinner is current. + """ + if self._heard_by is None or ( + self._heard_ticker is not None and not self._heard_ticker.done() + ): + return + + async def tick() -> None: + assert self._heard_by is not None + try: + while self._heard_by.waiting(self._messages): + await asyncio.sleep(spinner_interval()) + self._spinner.tick() + self._session.invalidate() + self._heard_by.refresh(self._messages) + self._session.invalidate() + except Exception: # noqa: BLE001 - a spinner problem must never break the chat + pass + + self._heard_ticker = self._spawn(tick()) + def _pick_banner(self) -> Text: """A one-line note above the input while a message is selected. @@ -1293,7 +1431,9 @@ class ChatScreen(Screen): self._open_map() elif action == "author_page": self._open_author_page() - elif action == "react": + # ^E is "reveal" in the chord table (upstream uses it to show a PIN). The chat + # conceals nothing, so here ^E reacts. + elif action in ("react", "reveal"): self._begin_react() elif action == "lock": self._toggle_lock() @@ -1760,6 +1900,7 @@ class ChatScreen(Screen): sent += 1 if message is not None: self._admit(message) + self.track_sent(message) self._session.invalidate() self._status = "" except Exception as exc: # noqa: BLE001 - show the error inline, keep the chat open @@ -2008,6 +2149,7 @@ class ChatScreen(Screen): message = await self._resend_unscoped(target) if message is not None: self._admit(message) + self.track_sent(message) self._status = "" except Exception as exc: # noqa: BLE001 - show the error inline, keep the chat open self._status = f"resend failed: {exc}" @@ -2328,6 +2470,7 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int: paths = await _make_paths_presenter(ctx, conversation, device) self_name, self_key = await our_node(ctx) + heard, hop_name = await _make_heard_tracker(ctx, conversation, device, contacts) screen = ChatScreen( conversation, history, @@ -2347,8 +2490,11 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int: max_parts=ctx.preferences.message_parts_max, part_gap_s=ctx.preferences.trace_cooldown_s, resend_flood=resend_flood, + heard=heard, + hop_name=hop_name, ) ctx.chat.set_active(conversation.key) + screen.start_heard() def on_event(event: MeshEvent) -> None: message = event.message @@ -2360,15 +2506,61 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int: ) ) + def on_packet(event: MeshEvent) -> None: + obs = event.observation + raw = obs.raw if obs is not None and isinstance(obs.raw, dict) else {} + if raw.get("payload_typename") == "GRP_TXT": + screen.heard_packet() + unsubscribe = ctx.events.subscribe(on_event, EventKind.MESSAGE) + unsubscribe_packets = ( + ctx.events.subscribe(on_packet, EventKind.OBSERVATION) if heard is not None else None + ) try: await session.run_screen(screen) finally: unsubscribe() + if unsubscribe_packets is not None: + unsubscribe_packets() ctx.chat.set_active(None) return len(screen._messages) +async def _channel_secret(conversation: Conversation, device: Any) -> bytes | None: + """The key of a channel conversation, from the conversation or from its slot.""" + secret = conversation.secret + if conversation.is_channel and not secret and conversation.channel_idx is not None: + try: + payload = await device.get_channel(conversation.channel_idx) + raw = (payload or {}).get("channel_secret") + secret = bytes(raw) if raw else None + except Exception: # noqa: BLE001 - no key, no decrypt. The callers say so + secret = None + return secret + + +async def _make_heard_tracker( + ctx: AppContext, conversation: Conversation, device: Any, contacts: list[Contact] +) -> tuple[HeardTracker | None, Callable[[str], str] | None]: + """The verdicts on our channel messages in this conversation, and a namer for relays. + + A direct chat has its acknowledgements, and a channel with no key at hand cannot match + its copies. Both get ``None``, and our messages show no mark. + """ + if not conversation.is_channel: + return None, None + from ..services import trace_runner + from ..services.heard_by import make_tracker + + secret = await _channel_secret(conversation, device) + tracker = make_tracker(ctx, channel_name=conversation.label, secret=secret) + if tracker is None: + return None, None + stored_names, _named_at = ctx.repo.node_names_with_times() + resolve = trace_runner.make_node_resolver(contacts, stored_names) + return tracker, lambda hop: resolve(hop) or hop + + async def _with_restore(ctx: AppContext, attempt: Callable[[], Awaitable[Any]]) -> Any: """Run a direct send. If the device forgot the contact, offer to restore it, then retry. @@ -2646,14 +2838,7 @@ async def _make_paths_presenter( # only gets no white highlight. self_name, self_key = await our_node(ctx) - secret = conversation.secret - if conversation.is_channel and not secret and conversation.channel_idx is not None: - try: - payload = await device.get_channel(conversation.channel_idx) - raw = (payload or {}).get("channel_secret") - secret = bytes(raw) if raw else None - except Exception: # noqa: BLE001 - no key, no decrypt. The view says so correctly - secret = None + secret = await _channel_secret(conversation, device) async def present(message: ChatMessage) -> None: peer_key: str | None = None diff --git a/meshterm/ui/clocks_screen.py b/meshterm/ui/clocks_screen.py index 4917ccd..92e89d4 100644 --- a/meshterm/ui/clocks_screen.py +++ b/meshterm/ui/clocks_screen.py @@ -385,7 +385,11 @@ def clock_drift_screen(rows: Sequence[ClockRow], *, tolerance_s: float) -> Selec if due: label = marked_label("πŸ•’", "Sync their clocks…", "") label.append(f" Β· {len(due)} {'node' if len(due) == 1 else 'nodes'}", "muted") - items += [Separator(" "), Choice(title=label, value=SYNC_ALL), Separator(" ")] + items += [ + Separator(" "), + Choice(title=label, value=SYNC_ALL, always_shown=True), + Separator(" "), + ] others = _by_size([r for r in off if not r.managed and r.contact is not None]) items.append(section_heading("Out of sync")) diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 99d3e3a..550f2f8 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -486,7 +486,7 @@ def _setting_value( class _ConfigMenu(SelectScreen): - """The list of the editor, with the row of the pairing PIN concealed until ``^S`` shows it. + """The list of the editor, with the row of the pairing PIN concealed until ``^E`` shows it. It does all that a grouped select list does. It also has the same toggle as the Device info page: the same chord, the same chip, and the same words. The two pages @@ -682,14 +682,19 @@ def _menu_items( ] lane = icon_lane(icon for icon, _, _, _ in actions) items.append(section_heading("Actions")) + # The settings are the data of the page, so a typed filter narrows them and keeps each + # action (Choice.always_shown). items.extend( menu_rows( ( - marked_label(icon, label, "err" if value == _RESET else "", lane=lane), - help_text, - value, - ) - for icon, label, help_text, value in actions + ( + marked_label(icon, label, "err" if value == _RESET else "", lane=lane), + help_text, + value, + ) + for icon, label, help_text, value in actions + ), + always_shown=True, ) ) diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index 79bcd37..b255991 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -32,8 +32,10 @@ say "and if it's the trace picker…". longest place, and the full key. No value is cut to fit the terminal. A row that is wider than the terminal pans: ←→ slide the column header and all the rows by one shared shift, with the mark column and the name held still (refer to -:attr:`~meshterm.ui.tui.select.Choice.pans`). The other lists can be floating dialogs (the -Trace picker), so they keep the lanes that fit the terminal. +:attr:`~meshterm.ui.tui.select.Choice.pans`). The other lists keep the lanes that fit the +terminal. The Trace picker floats as a dialog, and the width of a dialog comes from the +width of its rows. The neighbour table of a repeater has one lane only of an unknown +width, and that lane is the key. **A list with the** ``PLACE`` **lane reads its places from the place service.** The caller gives the service (``places``), and the list fills the place of each row from the key of @@ -52,9 +54,9 @@ from typing import TYPE_CHECKING, Any from rich.cells import cell_len from rich.text import Text -from .marks import LOCK_ICON, MANAGED_ICON, SELF_MARK +from .marks import LOCK_ICON, MANAGED_ICON, SELF_MARK, UNKNOWN_MARK from .menus import fit_cells -from .theme import glyph, name_style +from .theme import glyph, name_style, snr_style from .tui.select import Choice, SelectScreen, Separator from .widgets import ( DEFAULT_GLYPH, @@ -115,9 +117,16 @@ class ContactLane: field: The :class:`ContactRow` attribute that holds the value of the lane. kind: ``"age"`` for a datetime drawn as a relative age in the colour of the recency heat, ``"count"`` for an integer count drawn muted (a faint ``β€”`` - when ``None``), or ``"text"`` for a string drawn on the left (a faint ``β€”`` - when ``None``). A ``text`` lane has no fixed width: the list sizes it to its - widest value (refer to :func:`_sized`), and :attr:`width` is the minimum. + when ``None``), ``"snr"`` for a signal reading drawn in the SNR scale of the + app (a muted ``β€”`` when ``None``), or ``"text"`` for a string drawn on the + left (a faint ``β€”`` when ``None``). A ``text`` lane has no fixed width: the + list sizes it to its widest value (refer to :func:`_sized`), and + :attr:`width` is the minimum. + absent: What an ``age`` lane draws when it has no value. ``"never"`` is the usual + word, and it is a *fact*: MeshTerm never heard the node. A lane whose source + can leave the age out without that meaning says so with ``"β€”"`` instead + (:data:`NEIGHBOUR_HEARD_LANE`: the remote node hears the neighbour, and it did + not say when). """ column: str @@ -125,6 +134,7 @@ class ContactLane: width: int field: str kind: str = "age" + absent: str = "never" #: How long ago MeshTerm last heard the node: the lane that each list of *live* contacts has. @@ -148,6 +158,18 @@ ARCHIVED_LANE = ContactLane("archived", "ARCHIVED", 8, "archived_at") #: Archived list it is the first lane, after the name (JP, 2026-11-03). PLACE_LANE = ContactLane("place", "PLACE", 5, "place", kind="text") +#: The signal-to-noise ratio that a **remote** node measured when it received from this +#: one: the first lane of the neighbour table of a repeater. It is not our own reading, and +#: the title of that dialog names the node whose reading it is. +SNR_LANE = ContactLane("snr", "SNR", 5, "snr", kind="snr") + +#: How long ago a **remote** node last heard this one: the second lane of its neighbour +#: table. It is drawn exactly as ``HEARD`` is, with the recency heat, because it is the same +#: question (how long ago did this node receive from that one) asked at the other end of the +#: link. A node that gave no age for an entry shows ``β€”``, which is not ``never``: it hears +#: the neighbour, and it did not say when. +NEIGHBOUR_HEARD_LANE = ContactLane("heard", "HEARD", 5, "heard_by_node", absent="β€”") + #: The middle lanes of the usual contact list: ``NAME Β· HEARD Β· PKTS Β· KEY``. DEFAULT_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE) @@ -157,6 +179,11 @@ CONTACTS_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE, PLACE_LANE) #: The middle lanes of the Trace-target picker, which puts ``TRACED`` before the usual two. TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE) +#: The middle lanes of the neighbour table of a repeater: ``NAME Β· SNR Β· HEARD Β· KEY``. +#: Both middle lanes are the readings of the *remote* node, so there is no ``PKTS`` lane: +#: our own packet count would be the one number on the row that is not its measurement. +NEIGHBOUR_LANES: tuple[ContactLane, ...] = (SNR_LANE, NEIGHBOUR_HEARD_LANE) + #: The middle lanes of the Archived list: ``NAME Β· PLACE Β· ARCHIVED Β· KEY``. There is no #: ``HEARD`` and no ``PKTS``. An archived contact is not on the device, so this screen is not #: about what the contact still transmits. It is about where the contact is, and when it @@ -229,6 +256,19 @@ TRACE_SORT_OPENS_ASCENDING: dict[str, bool] = { "hash": True, } +#: The sort ring of the neighbour table of a repeater: ``NAME Β· SNR Β· HEARD Β· KEY``, the +#: same as :data:`NEIGHBOUR_LANES`. It opens on ``snr`` *descending*, so the strongest link +#: is first: the strongest neighbours say where the node sits in the mesh. An entry with no +#: reading has ``-inf``, so it collects at the weak end in both directions (refer to +#: :func:`_ordered`). +NEIGHBOUR_SORT_COLUMNS: tuple[str, ...] = ("name", "snr", "heard", "hash") +NEIGHBOUR_SORT_OPENS_ASCENDING: dict[str, bool] = { + "name": True, + "snr": False, + "heard": True, + "hash": True, +} + #: The sort ring of the Archived list: ``NAME Β· PLACE Β· ARCHIVED Β· KEY``, the same as #: :data:`ARCHIVED_LANES`. ``archived`` opens *ascending* on the age of the lane, so the #: most recently archived contacts come first. This screen answers the question "what did @@ -286,11 +326,22 @@ class ContactRow: archived_at: When this contact was archived and removed from the device (aware UTC). It fills the ``ARCHIVED`` lane (:data:`ARCHIVED_LANES`). Lists without that lane ignore it. + snr: The signal reading that a remote node measured for this one, in dB. It fills + the ``SNR`` lane (:data:`NEIGHBOUR_LANES`). ``None`` renders a muted ``β€”``. + Lists that do not declare the lane ignore it. + heard_by_node: When a remote node last heard this one (aware UTC). It fills the + ``HEARD`` lane of a neighbour table (:data:`NEIGHBOUR_LANES`), in the colour of + the recency heat. ``None`` renders a muted ``β€”``. Lists that do not declare the + lane ignore it. locked: Whether the contact is locked, so that it cannot be archived. A padlock then starts the row, on the left of the type glyph. ``False`` draws nothing there. managed: Whether the contact is a managed node: MeshTerm stores its admin password. The ``πŸ”‘`` then goes in the same column, after a padlock. + unknown: Whether nothing can place this node: it is not a contact of the device, + and no stored advert names it. The row then starts with the ``β—‹`` unknown mark + in place of a type mark, because a type mark would be a claim about a node + that nobody identified. ``False`` keeps the mark of :attr:`node_type`. you: Whether this is our node. Our node gets the ``β˜…`` marker, the pure-white ``you`` name style with a muted ``(you)`` tag, and faint ``β€”`` heard and packet lanes (MeshTerm never hears our node). Its row is pinned above the sorted @@ -305,9 +356,12 @@ class ContactRow: count: int | None = None last_traced: datetime | None = None archived_at: datetime | None = None + snr: float | None = None + heard_by_node: datetime | None = None place: str | None = None locked: bool = False managed: bool = False + unknown: bool = False you: bool = False @@ -401,10 +455,12 @@ def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: An ``age`` lane draws the relative age in the column form (:func:`format_age`), in the colour of the recency heat. Thus a new value is bright and an old value is grey, the - same for each event that the lane measures. A ``count`` lane draws the count muted, or + same for each event that the lane measures. An age lane with no value draws the word of + its :attr:`~ContactLane.absent`. A ``count`` lane draws the count muted, or a faint ``β€”`` where there is nothing to count. It clamps the count, so that a very - large count cannot make the column wider. A ``text`` lane draws its string on the left, - padded to the lane, or a faint ``β€”`` where there is none. + large count cannot make the column wider. An ``snr`` lane draws the reading signed, to + one decimal, in the SNR scale that each other surface of the app uses. A ``text`` lane + draws its string on the left, padded to the lane, or a faint ``β€”`` where there is none. """ value = getattr(row, lane.field, None) if lane.kind == "text": @@ -415,7 +471,13 @@ def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: if value is None: return Text(f"{'β€”':>{lane.width}}", style="faint") return Text(f"{min(value, 99999):>{lane.width}}", style="muted") + if lane.kind == "snr": + if value is None: + return Text(f"{'β€”':>{lane.width}}", style="muted") + return Text(f"{value:+.1f}".rjust(lane.width), style=snr_style(float(value))) secs = age_seconds(value) + if secs is None: + return Text(f"{lane.absent:>{lane.width}}", style=_recency_style(None)) return Text(f"{format_age(secs):>{lane.width}}", style=_recency_style(secs)) @@ -503,7 +565,9 @@ def _lane( """ if row.you: return _you_lane(row, name_w, prefix_bytes, hash_w, lanes, lock_w) - mark, mark_style = NODE_GLYPHS.get(row.node_type, DEFAULT_GLYPH) + mark, mark_style = ( + UNKNOWN_MARK if row.unknown else NODE_GLYPHS.get(row.node_type, DEFAULT_GLYPH) + ) text = Text(_lock_cell(row, lock_w), no_wrap=True, overflow="ellipsis") text.append(mark, style=mark_style) text.append(" ") @@ -536,11 +600,11 @@ def _ordered( The two fixed columns sort on their own values: name Aβ†’Z, and ``hash`` by the displayed key (ascending = ``0`` β†’ ``f``). Each other column is a declared :class:`ContactLane`, - and sorts by the metric of the lane. A ``count`` lane sorts by its count, and an ``age`` - lane sorts by *age in seconds*. Thus ascending puts the newest first, and a row with no - value at all collects at the old end in both directions. Because of this property, - ``heard``, ``traced``, and ``archived`` behave the same, and no line of code names any - of them. + and sorts by the metric of the lane. A ``count`` lane sorts by its count, an ``snr`` + lane by its reading, and an ``age`` lane by *age in seconds*. Thus ascending puts the + newest first, and a row with no value at all collects at the old end in both + directions. Because of this property, ``heard``, ``traced``, and ``archived`` behave + the same, and no line of code names any of them. A pre-sort by name, ascending, is the stable tiebreak. Thus two contacts with the same metric keep an Aβ†’Z order in both directions, and do not change places with the primary @@ -569,6 +633,11 @@ def _ordered( return (0, str(value).casefold()) if value else (1, "") if lane.kind == "count": return value or 0 + if lane.kind == "snr": + # A reading that the node did not give is the weakest value there is, so it + # collects at the weak end in both directions, as a node that was never heard + # does in an age column. + return value if value is not None else float("-inf") secs = age_seconds(value) return secs if secs is not None else float("inf") diff --git a/meshterm/ui/contacts_screen.py b/meshterm/ui/contacts_screen.py index 7d5e8c4..11053f9 100644 --- a/meshterm/ui/contacts_screen.py +++ b/meshterm/ui/contacts_screen.py @@ -166,7 +166,9 @@ class ContactsScreen(ContactListScreen): self._managed = managed self._contacts, self._counts = contacts, counts rows = self._contact_rows_for(locked) - # The maintenance actions close the list, after each contact, for each sort. First + # The maintenance actions close the list, after each contact, for each sort. A typed + # filter narrows the contacts and keeps these two rows (Choice.always_shown): the + # filter searches the list, and the actions of the page are not in it. First # a blank spacer, then the sweep (it has a `…` because it opens more prompts), then # the way to what the sweep already took. The two rows are together because they are # the two halves of one idea. The archived row is *under* the sweep for the same @@ -183,6 +185,7 @@ class ContactsScreen(ContactListScreen): Choice( title=marked_label("πŸ’Ύ", "Archive contacts…", "", lane=lane), value=_ARCHIVE, + always_shown=True, ), ] if archived: @@ -191,7 +194,7 @@ class ContactsScreen(ContactListScreen): # of the verb. It is what the row leads to, not what the row does. label = marked_label("πŸ“‚", "View archived contacts", "", lane=lane) label.append(f" Β· {archived}", style="muted") - tail.append(Choice(title=label, value=_ARCHIVED)) + tail.append(Choice(title=label, value=_ARCHIVED, always_shown=True)) # The title counts both halves of the contacts of this device: those that are on it # and those that a sweep moved off it. If the frame is too narrow for the words, the # numbers stay and the words go (``Contacts Β· 198 + 123``). diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index d5fbe99..ecb0045 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -415,7 +415,11 @@ def _menu_items(ctx: AppContext, entries: list[QueuedMessage]) -> list: ) ) items.append(Separator(" ")) # put space between the action and the outbox rows above it - items.append(Choice(marked_label("πŸ“¨", "Queue a message…", "", lane=lane), _QUEUE)) + items.append( + # The queued messages are the data of the page, so a typed filter keeps this row + # and the Clear row below (Choice.always_shown). + Choice(marked_label("πŸ“¨", "Queue a message…", "", lane=lane), _QUEUE, always_shown=True) + ) if done: items.append(section_heading("Finished")) @@ -429,7 +433,9 @@ def _menu_items(ctx: AppContext, entries: list[QueuedMessage]) -> list: pans=True, ) ) - items.append(Choice(marked_label("πŸ—‘", "Clear finished", "", lane=lane), _CLEAR)) + items.append( + Choice(marked_label("πŸ—‘", "Clear finished", "", lane=lane), _CLEAR, always_shown=True) + ) return items diff --git a/meshterm/ui/device_info_screen.py b/meshterm/ui/device_info_screen.py index f57f7bc..69fbb46 100644 --- a/meshterm/ui/device_info_screen.py +++ b/meshterm/ui/device_info_screen.py @@ -30,7 +30,7 @@ from .tui.screen import ScrollScreen #: out with two different keys, depending on the page, the user would have one more thing #: to learn with no benefit. A chord also must be *intended*: a PIN never appears because a #: hand touched a letter. -REVEAL_KEY = "^S" +REVEAL_KEY = "^E" class DeviceInfoScreen(ScrollScreen): @@ -112,7 +112,7 @@ class DeviceInfoScreen(ScrollScreen): """Toggle the PIN, or scroll or dismiss, as each result screen does. The chord and the chip of the lane arrive as the same action. Thus the chip is not a - second implementation of the key (``^S`` is bound one time, in the chord table of the + second implementation of the key (``^E`` is bound one time, in the chord table of the session). """ if action == "reveal": diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 2b7b11d..bba7402 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -63,7 +63,7 @@ from ..core.discovery import ( tcp_device, ) from ..core.spiradio import spi_radios, without_radio_ports -from ..persistence.logging import log_file_for +from ..persistence.logging import get_logger, log_file_for from .logo import load_logo from .menus import Lane, align_icons, column_header from .tui import Choice, DeleteRequest, KeyRequest, Separator @@ -332,7 +332,10 @@ async def _smoke_test( continue except DeviceCommandError as exc: # A different failure that the user can act on (not a PIN). Show its remedy, then - # go back to the list. + # go back to the list. The log keeps the failure also when the dialog says all + # that the log would say, because a user who reports a problem sends the log file, + # and the dialog is gone long before that. + get_logger().warning("%s did not connect (%s): %s", name, type(exc).__name__, exc) notice = connect_failure_text(exc) notice.append("\nChoose another device.") await ui.notify_startup(notice, title="Can't connect yet", banner=load_logo()) diff --git a/meshterm/ui/device_route_screen.py b/meshterm/ui/device_route_screen.py index 6fb6cce..42b3d99 100644 --- a/meshterm/ui/device_route_screen.py +++ b/meshterm/ui/device_route_screen.py @@ -318,7 +318,9 @@ def _action_rows(status: RouteStatus, proven: ProvenRoute | None = None) -> list if status.hops is not None: rows.append(("Forget the route", "the next message floods", _FORGET)) rows.append(("Discover routes…", "one flood: the route each way", _DISCOVER)) - return menu_rows(rows) + # The rows above these say what the radio holds, which is the data of the popup. Thus a + # typed filter narrows that and keeps what the popup does. + return menu_rows(rows, always_shown=True) def _scenario_tag(scenario: PathScenario) -> str: @@ -357,7 +359,7 @@ def _picker_rows(env: RouteEnv, status: RouteStatus) -> list[Any]: if scenario.source != "direct": add(tuple(scenario.hops), _scenario_tag(scenario)) add((), "no relays: the contact is a neighbour") - rows.extend(menu_rows([("Compose…", "choose each hop yourself", _COMPOSE)])) + rows.extend(menu_rows([("Compose…", "choose each hop yourself", _COMPOSE)], always_shown=True)) return rows diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 8951131..0dd2674 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -40,7 +40,7 @@ from .menus import ( section_heading, ) from .surface import TuiUi -from .theme import make_console +from .theme import glyph, make_console from .tui import ( Choice, PopToMenu, @@ -377,9 +377,25 @@ def _header_segments(ctx: AppContext, cache: dict) -> list[Text]: badge.append("β–²", style="err") badge.append(f" {alerts}", style="warn") segments.append(badge) + speaker = _sound_badge(ctx) + if speaker: + segments.append(speaker) return segments +def _sound_badge(ctx: AppContext) -> Text: + """The state of the sounds in the header: πŸ”Š on, πŸ”‡ off, or nothing. + + The header shows nothing where no sound can play: on a platform with no sound (the + PicoCalc), and with the ``none`` theme (JP, 2026-11-20: "No sound, no speaker emoji at + all"). ^S changes the state from any screen. + """ + sound = getattr(ctx, "sound", None) + if sound is None or not sound.available or not sound.audible_theme: + return Text() + return Text(glyph(_SOUND_ON_ICON if sound.enabled else _SOUND_OFF_ICON), style="muted") + + def _demo_name() -> str: """The name of our node in the demo world.""" from ..demo.world import SELF @@ -467,6 +483,10 @@ async def run_menu(ctx: AppContext) -> None: session.set_quit_confirm(lambda: _confirm_quit(ctx, session)) # What a held Esc engages while its dialog is open. The app keeps it while it exits. session.set_quiesce(lambda: _off_the_air(ctx)) + # ^S mutes or unmutes the sounds from any screen. The bell theme rings the terminal, and + # a notification with no sound can flash the title. + session.set_sound_toggle(lambda: _toggle_sound(ctx)) + ctx.sound.set_hooks(bell=session.bell, flash=session.flash) # Where a terminal gives the keys, MeshTerm asks the keyboard whether Esc is still # held. Thus a held Esc quits there too. The emulator reads its keys itself, and the # keyboard of its machine is not the keyboard of the handheld. @@ -589,6 +609,27 @@ _QUIT_ICON = "πŸšͺ" #: :class:`_MainMenu`). _QUIT_VALUE = "__quit__" +#: The icons of the sound state: in the header, and on the Sounds row of the menu. +_SOUND_ON_ICON = "πŸ”Š" +_SOUND_OFF_ICON = "πŸ”‡" + +#: The value with which the Sounds row resolves. The row mutes or unmutes the sounds, and +#: the menu stays (refer to :func:`_menu_round`). +_SOUND_VALUE = "__sound__" + + +def _toggle_sound(ctx: AppContext) -> None: + """Mute or unmute the sounds (the Sounds row, and ^S from any screen). + + When the sounds come on, the channel message sound plays one time. Thus the user hears + that they are on, and how loud they are. + """ + sound = ctx.sound + if not sound.available or not sound.audible_theme: + return + if sound.toggle(): + sound.preview() + async def _confirm_quit(ctx: AppContext, session: TuiSession) -> bool: """Open the quit confirm as a dialog over the current screen, and return whether to leave. @@ -725,7 +766,7 @@ def _menu_lane(tools: Sequence[Any]) -> int: The column width from :func:`~meshterm.ui.menus.icon_lane`: ``0`` where the platform draws no icon lane. """ - return icon_lane([*(tool.icon for tool in tools), _QUIT_ICON]) + return icon_lane([*(tool.icon for tool in tools), _QUIT_ICON, _SOUND_ON_ICON, _SOUND_OFF_ICON]) def _menu_labels(tools: Sequence[Any], *, lane: int | None = None) -> list[Text]: @@ -760,7 +801,7 @@ def _menu_labels(tools: Sequence[Any], *, lane: int | None = None) -> list[Text] return labels -def _menu_items(tools: Sequence[Any]) -> list: +def _menu_items(tools: Sequence[Any], sound: Any = None) -> list: """The rows of the main menu: the tools under their section headings, then Quit. This function is separate from :func:`_menu_loop`, so that the list can be built and @@ -779,6 +820,8 @@ def _menu_items(tools: Sequence[Any]) -> list: tools: The visible tools of the menu, in the order in which they are drawn (already sorted by category, so that each heading opens its section only one time). + sound: The sound service (:class:`~meshterm.services.sound.SoundService`), for the + Sounds row above Quit. ``None``, or a platform with no sound, has no such row. Returns: The :class:`~meshterm.ui.tui.Choice` and :class:`~meshterm.ui.tui.Separator` @@ -800,6 +843,26 @@ def _menu_items(tools: Sequence[Any]) -> list: # stays (Choice.hscroll_from). items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) items.append(Separator(" ")) + if sound is not None and sound.available: + # The row names the state that the sounds are in now, and Enter changes it. The + # title is read at each paint, so ^S on another screen shows here too. + # With the "no sound" theme, the row has no speaker (JP, 2026-11-20: "No sound, no + # speaker emoji at all") and Enter does nothing: there is nothing to mute. + def sounds_title() -> Text: + if not sound.audible_theme: + label = Text(" " * (lane + 1) if lane else "") # an empty icon column + label.append("No sound") + hint = "the sound theme is in Preferences" + else: + on = sound.enabled + label = icon_mark(_SOUND_ON_ICON if on else _SOUND_OFF_ICON, "", lane) + label.append("Sound on" if on else "Sound muted") + hint = "^S on any screen" + label.append(" " * max(2, name_w - label.cell_len + 2)) + label.append(hint, style="muted") + return label + + items.append(Choice(title=sounds_title, value=_SOUND_VALUE)) # Quit has no description, so it is not part of name_w. Only its icon uses the icon # column of the tools. quit_label = icon_mark(_QUIT_ICON, "", lane) @@ -833,7 +896,7 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: session: The running TUI session. """ tools = [tool for tool in all_tools() if tool.menu_visible] - items = _menu_items(tools) + items = _menu_items(tools, ctx.sound) # Drive the menu list here (instead of through session.select), so that it stays on # the stack while the quit dialog shows over it. The confirm is drawn as a centred box @@ -931,6 +994,9 @@ async def _menu_round( if await session.confirm_quit(): raise _Quit() return + if selection == _SOUND_VALUE: + _toggle_sound(ctx) + return # A ``popup`` tool runs while the menu is still pushed. Thus its prompts and its # result show over the menu as modal dialogs, and do not replace the screen. tool = next((t for t in tools if t.name == selection), None) @@ -1046,6 +1112,13 @@ async def _startup(ctx: AppContext) -> bool: from .settings_offer import offer_remembered_settings await offer_remembered_settings(ctx) + # A device with no channel at all cannot send anywhere. Give it the standard Public + # channel, and say so. This step runs last, so that the replay of the remembered + # channels (at connect) and the settings offer are both done, and a device that forgot + # its own channels has them back before this step counts them. + from .public_default import add_public_when_empty + + await add_public_when_empty(ctx) return True @@ -1109,6 +1182,9 @@ async def _resume_monitor(ctx: AppContext) -> Exception | None: # reads, and it skips silently without a device, so it is also safe to run from the # start. await ctx.battery.start() + # The packet tick listens to the packets heard. It does nothing while its preference is + # off. + ctx.sound.start() # The place finder reads only stored locations and the network (tiles, Nominatim), never # the device. Its first read waits some seconds, so it does not slow the start. await ctx.places.start() diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 2084a96..d121682 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -308,15 +308,17 @@ def exit_rows(staged: int, *, apply_value: Any, back_value: Any) -> list: Choice( title=Text.assemble(("βœ“ ", "ok"), f"Apply {changes_phrase(staged)}"), value=apply_value, + always_shown=True, ), Choice( title=Text.assemble(("βœ— ", "err"), "Back β€” discard staged changes"), value=back_value, + always_shown=True, ), ] -def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: +def menu_rows(rows: Iterable[tuple[str | Text, str, Any]], *, always_shown: bool = False) -> list: """:class:`Choice` rows with a label and a description, in two aligned lanes. This is the menu form that the channel detail and the Actions of the Device config and @@ -338,6 +340,14 @@ def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: Args: rows: ``(label, description, value)`` triples. A :class:`Text` label keeps its own styling (a destructive row with the ``err`` tint, a live unread badge). + always_shown: Whether a typed filter keeps these rows + (:attr:`~meshterm.ui.tui.select.Choice.always_shown`). Set it where the rows + are the **actions of a page whose other rows are data**: the Actions section + of an editor, the Add row of a list. There the filter searches the data, and an + action that it hid was gone until the user cleared a query that nothing names. + Leave it off for a list that *is* a menu (the main menu, the actions of one + room): there the rows are the content, and the filter is how the user finds + one. Returns: One :class:`Choice` for each row, with the lanes aligned across all the rows. @@ -358,7 +368,9 @@ def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: # The label lane identifies the row. Only the description overflows, so the # h-scroll moves only the description, and the name does not move (refer to # Choice.hscroll_from). - items.append(Choice(title=row, value=value, hscroll_from=width + 2)) + items.append( + Choice(title=row, value=value, hscroll_from=width + 2, always_shown=always_shown) + ) return items diff --git a/meshterm/ui/outbound_screen.py b/meshterm/ui/outbound_screen.py index 2234597..b0b8d6b 100644 --- a/meshterm/ui/outbound_screen.py +++ b/meshterm/ui/outbound_screen.py @@ -201,8 +201,11 @@ def _page(store: OutboundStore, env: _Env) -> tuple[str, str, list]: items.append( Separator(" no sites yet β€” a site holds the paths for where you are", style="muted") ) + # The sites and the fixed devices are the data of this page. Thus a typed filter + # narrows them and keeps the rows that add one (Choice.always_shown). items += menu_rows( - [(marked_label("✎", "New site…", "", lane=lane), "Name it, then add its paths", _NEW)] + [(marked_label("✎", "New site…", "", lane=lane), "Name it, then add its paths", _NEW)], + always_shown=True, ) items.append(section_heading("Fixed devices")) @@ -220,7 +223,8 @@ def _page(store: OutboundStore, env: _Env) -> tuple[str, str, list]: "It never moves: give it its own paths", _FIX, ) - ] + ], + always_shown=True, ) return "Outbound paths", prompt, items @@ -427,7 +431,7 @@ def _site_actions(store: OutboundStore, name: str) -> list: _DELETE, ) ) - return [section_heading("Site"), *menu_rows(rows)] + return [section_heading("Site"), *menu_rows(rows, always_shown=True)] def _device_actions() -> list: @@ -442,7 +446,8 @@ def _device_actions() -> list: "Forget its paths: it follows the active site", _UNFIX, ) - ] + ], + always_shown=True, ), ] @@ -463,7 +468,8 @@ def _editor_items(env: _Env, staged: list[OutboundPath], owner: list, changes: i "Compose it hop by hop", _ADD, ) - ] + ], + always_shown=True, ) rows += owner rows += exit_rows(changes, apply_value=_APPLY, back_value=_BACK) diff --git a/meshterm/ui/preferences.py b/meshterm/ui/preferences.py index a560ed7..341f929 100644 --- a/meshterm/ui/preferences.py +++ b/meshterm/ui/preferences.py @@ -61,7 +61,8 @@ from .menus import ( lane_row, section_heading, ) -from .tui import Choice, Separator +from .slider import SliderScreen +from .tui import CANCEL, Choice, Separator if TYPE_CHECKING: from ..context import AppContext @@ -297,6 +298,9 @@ def _menu_items( title=lane_row(label, value, help_text, label_w, value_w), value=key, hscroll_from=description_at, + # The preferences are the data of the page. The reset row is what the + # page does, so a typed filter keeps it (Choice.always_shown). + always_shown=key == _RESET, ) ) if key == _WEEKLY_ADVERT and _effective(prefs, key, pending): @@ -470,7 +474,7 @@ async def _prompt_value(ctx: AppContext, spec: PrefSpec, current: Any) -> Any: # A choice between two states is clearest as a pair of buttons. The current state # is highlighted, so that Enter does not change anything by accident. return await ctx.ui.dialog( - spec.description, + (spec.question or spec.description), [("Off", False), ("On", True)], title=spec.label, default=1 if current else 0, @@ -486,9 +490,26 @@ async def _prompt_value(ctx: AppContext, spec: PrefSpec, current: Any) -> Any: for value, label in spec.choices.items() ] return await ctx.ui.select( - spec.label, items, prompt=f"{spec.description}:", default=current + spec.label, items, prompt=f"{(spec.question or spec.description)}:", default=current ) + if spec.key == "sound_volume": + # A slider of ten steps, and each step plays the channel message sound at the new + # volume (JP, 2026-11-20). The value is staged, so the preview gives it directly. + result = await ctx.ui.session.run_screen( + SliderScreen( + spec.label, + spec.question or spec.help, + int(current), + int(spec.minimum or 1), + int(spec.maximum or 10), + on_change=lambda volume: ctx.sound.preview(volume=volume), + more="Louder", + less="Softer", + ) + ) + return None if result is CANCEL else result + def validate(text: str) -> bool | str: try: parse_value(spec, text) @@ -498,7 +519,7 @@ async def _prompt_value(ctx: AppContext, spec: PrefSpec, current: Any) -> Any: raw = await ctx.ui.text( spec.label, - prompt=f"{spec.description}:", + prompt=f"{(spec.question or spec.description)}:", default="" if current is None else str(current), validate=validate, help_text=range_hint(spec), diff --git a/meshterm/ui/public_default.py b/meshterm/ui/public_default.py new file mode 100644 index 0000000..25c3111 --- /dev/null +++ b/meshterm/ui/public_default.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Add the standard Public channel at startup to a device that has no channels. + +A MeshCore companion ships with the standard ``Public`` channel on slot 0. A device that +arrives with **no channel at all** cannot send to anybody: each send needs a slot, and the +device refuses a send on a slot that it does not have (issue #36). A new user does not know +this. The user reads an empty Chat picker as "nobody is here", and not as "this radio has +no channel". + +Thus MeshTerm gives such a device the standard Public channel at startup, on slot 0, and +says what it did (JP, 2026-11-22). It does not ask. The channel is the one that MeshCore +itself ships, its key is well known, and the device had nothing to lose: the write +overwrites nothing. This is the same judgment as the position that MeshTerm restores +silently (refer to :mod:`meshterm.ui.settings_offer`): an empty slot is not a value that +competes. + +The step is one preference (``public_on_empty_device``, on by default). A user who wants a +radio with no channel turns it off, and then nothing is written. The Chat picker still +offers Public there, because that offer only asks (refer to +:func:`meshterm.tools.chat._add_public_channel`). + +The step is quiet and cheap. It reads slot 0 first, and a channel there ends the step after +one round trip. Thus a device that has channels pays almost nothing at each startup. Only a +device whose slot 0 is empty pays the full slot probe. + +The step runs after the replay of the remembered channels (refer to +:meth:`meshterm.context.AppContext._reconcile_channels`). Thus a device that forgot its +channels gets its own channels back first, and this step sees them. + +The simulator is the one device that the step passes over. It is not a radio, it keeps +nothing between launches, and it starts with no channel each time. Thus the step would +write and give its card at each ``--mock`` launch, which is each launch of the development +loop and of the emulator. The simulator instead shows the other half of the same feature: +the Chat picker offers Public on its own (refer to +:func:`meshterm.tools.chat._add_public_channel`). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rich.text import Text + +from ..core.channels import DEFAULT_PUBLIC_SECRET + +if TYPE_CHECKING: + from ..context import AppContext + from ..core.connection import Device + +#: The slot that the new channel goes into. The device had no channel, so slot 0 is free, +#: and slot 0 is where the firmware itself keeps Public. +PUBLIC_SLOT = 0 + + +async def _has_a_channel(ctx: AppContext, device: Device) -> bool: + """Whether the device has any channel at all, and whether that answer is proved. + + The function reads slot 0 by itself first, because a channel there answers the question + with one round trip. A full probe of the slots follows only for an empty slot 0. + + An unproved answer counts as "it has a channel". A probe that stopped because a read + failed returns a short list, and an empty short list looks exactly the same as a device + with no channels (refer to + :func:`~meshterm.core.channel_probe.probe_channel_slots`). MeshTerm must not write to a + device on that evidence. + + Args: + ctx: The shared application context, for the log. + device: The connected device. + + Returns: + ``True`` if the device has a channel, or if the code could not prove that it has + none. + """ + from ..core.channel_probe import probe_channel_slots + + try: + first = await device.get_channel(PUBLIC_SLOT) + except Exception as exc: # noqa: BLE001 - a read that failed proves nothing + ctx.log.debug("channels: could not read slot %s at startup: %s", PUBLIC_SLOT, exc) + return True + if first and first.get("channel_name"): + return True + slots, complete = await probe_channel_slots(device) + if not complete: + ctx.log.debug("channels: the slot probe did not finish, so the startup step stops") + return True + return bool(slots) + + +async def add_public_when_empty(ctx: AppContext) -> bool: + """Give a device with no channels the standard Public channel, and say so. + + The function does its best only, and it is quiet. It does nothing in these cases: the + preference is off, the simulator, no live link, a device that has a channel, or a probe + that could not prove that the device has none. It never opens the radio itself. A + deferred connect (``connect_on_start`` off) skips the function, because + ``is_connected`` is false. A failure here must not stop the user from reaching the + menu, so the function guards each step. + + Args: + ctx: The shared application context. + + Returns: + ``True`` if the function wrote the channel. + """ + from .channels import write_channel + from .logo import load_logo + + if not ctx.preferences.public_on_empty_device: + return False + if ctx.mock or not ctx.is_connected: + return False + try: + device = await ctx.device() + if await _has_a_channel(ctx, device): + return False + await write_channel(ctx, device, PUBLIC_SLOT, "Public", DEFAULT_PUBLIC_SECRET) + except Exception as exc: # noqa: BLE001 - a startup step must not stop the menu + ctx.log.debug("channels: could not add Public at startup: %s", exc) + return False + ctx.log.info("channels: added the standard Public channel to slot %s", PUBLIC_SLOT) + notice = Text.assemble( + ("This radio had no channel, so it could not send anywhere.\n", ""), + ("MeshTerm added ", ""), + ("Public", "accent"), + (f" to slot {PUBLIC_SLOT}: MeshCore's built-in meshwide channel.\n", ""), + ("Chat opens it. Preferences can turn this step off.", "muted"), + ) + await ctx.ui.notify_startup(notice, title="Public channel added", banner=load_logo()) + return True diff --git a/meshterm/ui/records_screen.py b/meshterm/ui/records_screen.py index 73e489e..22cc2b9 100644 --- a/meshterm/ui/records_screen.py +++ b/meshterm/ui/records_screen.py @@ -1246,16 +1246,20 @@ async def open_records(ctx: AppContext) -> dict: ) if total: items.append(Separator(" ")) + # The records are the data of the page. Thus a typed filter narrows them and + # keeps these two rows (Choice.always_shown). items.append( Choice( title=marked_label("πŸ—‘", "Delete a discipline's records…", "err"), value=("del_cat", None, 0, None), + always_shown=True, ) ) items.append( Choice( title=marked_label("πŸ—‘", "Delete all records…", "err"), value=("del_all", None, 0, None), + always_shown=True, ) ) return items diff --git a/meshterm/ui/region_editor.py b/meshterm/ui/region_editor.py index 98bea09..fe3f419 100644 --- a/meshterm/ui/region_editor.py +++ b/meshterm/ui/region_editor.py @@ -242,10 +242,15 @@ def region_items(node: Contact, table: RegionTable, unsaved: int) -> tuple[str, # list adds no second line after it (Separator.spaced). items.append(Separator(" ")) items.append(section_heading("Actions")) + # The region table is the data of the page, so a typed filter narrows it and keeps each + # action (Choice.always_shown). items.extend( menu_rows( - (marked_label(icon, label, "", lane=lane), help_text, value) - for icon, label, help_text, value in actions + ( + (marked_label(icon, label, "", lane=lane), help_text, value) + for icon, label, help_text, value in actions + ), + always_shown=True, ) ) items.extend(_save_rows(unsaved)) @@ -315,8 +320,13 @@ def _save_rows(unsaved: int) -> list: Choice( title=Text.assemble(("βœ“ ", "ok"), f"Save {unsaved} {noun} to the repeater"), value=_SAVE, + always_shown=True, + ), + Choice( + title=Text.assemble(("βœ— ", "err"), "Back β€” a reboot undoes them"), + value=_BACK, + always_shown=True, ), - Choice(title=Text.assemble(("βœ— ", "err"), "Back β€” a reboot undoes them"), value=_BACK), ] diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 0e8d991..ce56836 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -42,14 +42,14 @@ from __future__ import annotations import asyncio import re -from collections.abc import Iterable +from collections.abc import Iterable, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any from rich.cells import cell_len from rich.text import Text -from ..core.models import Contact +from ..core.models import Contact, NeighbourInfo from ..core.remote_config import ( DISCOVERED_CATEGORY, NEVER_STORED, @@ -70,6 +70,13 @@ from ..core.remote_config import ( validate_value, write_plan, ) +from .contactlist import ( + NEIGHBOUR_LANES, + NEIGHBOUR_SORT_COLUMNS, + NEIGHBOUR_SORT_OPENS_ASCENDING, + ContactListScreen, + ContactRow, +) from .menus import ( PICK_LOCATION_HELP, PICK_LOCATION_LABEL, @@ -84,9 +91,10 @@ from .menus import ( section_heading, ) from .trace_screen import TracingDialog -from .tui import Choice, Separator +from .tui import CANCEL, Choice, Separator from .tui.select import DeleteRequest, SelectScreen, splice_hint from .tui.spinner import Spinner, spinner_interval +from .widgets import ContactsSort, _key_id if TYPE_CHECKING: from ..context import AppContext @@ -107,6 +115,7 @@ _CLOCK = "__clock__" _PASSWORD = "__password__" _REBOOT = "__reboot__" _REGIONS = "__regions__" +_NEIGHBOURS = "__neighbours__" _APPLY = "__apply__" _CANCEL = "__cancel__" @@ -398,6 +407,8 @@ async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict from .region_editor import open_region_editor await open_region_editor(ctx, device, node) + elif choice == _NEIGHBOURS: + await _neighbours(ctx, device, node) elif choice == _ADVERT: await _simple_action( ctx, @@ -518,6 +529,7 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st ("↻", "Read settings", "Fetch every value from the node, one paced read", _READ), ("⌨", "Command line…", "Talk to the node's CLI directly", _CLI), ("πŸ”–", "Regions…", "Which scoped floods it relays", _REGIONS), + ("⚑", "Neighbours…", "The nodes it hears directly, and how well", _NEIGHBOURS), ("πŸ“‘", "Send advert…", "Have the node announce itself now", _ADVERT), ("πŸ•’", "Sync clock…", "Set the node's clock over the mesh", _CLOCK), ("πŸ”", "Admin password…", "Change the node's admin password", _PASSWORD), @@ -525,10 +537,15 @@ def _menu_items(node: Contact, cache: dict, pending: dict[str, str]) -> tuple[st ] lane = icon_lane(icon for icon, _, _, _ in actions) items.append(section_heading("Actions")) + # The settings are the data of the page, so a typed filter narrows them and keeps each + # action (Choice.always_shown). items.extend( menu_rows( - (marked_label(icon, label, "", lane=lane), help_text, value) - for icon, label, help_text, value in actions + ( + (marked_label(icon, label, "", lane=lane), help_text, value) + for icon, label, help_text, value in actions + ), + always_shown=True, ) ) @@ -1015,6 +1032,179 @@ async def _run_under_dialog(ctx: AppContext, title: str, work) -> bool: return aborted +# --- the neighbour table ---------------------------------------------------------- + + +def neighbours_picker( + node: Contact, + entries: Sequence[NeighbourInfo], + *, + contacts: list[Contact], + prefix_bytes: int, +) -> ContactListScreen: + """Build the neighbour table of a node as the shared contact list, on a full screen. + + It is the Trace-target picker in a different subject: the same lane layout, the same + Ctrl+arrow sort ring, the same type-to-filter, the same node hues, type marks, and key + lane. Only the two middle lanes differ, because here the readings belong to the + *remote* node and not to us. ``SNR`` is what that node measured, and ``HEARD`` is how + long ago it last received from the neighbour (refer to + :data:`~meshterm.ui.contactlist.NEIGHBOUR_LANES`). The list opens on ``SNR``, with the + strongest link first. + + It is a **page**, not a dialog (JP, 2026-11-22). The reader is in it: they sort it, + filter it, and open a node from it. It does not pan (``pan=False``, the default), + unlike the two other full-screen contact lists. Panning earns its cells where a lane + holds text of an unknown width (the ``PLACE`` of the Contacts list). Here each middle + lane is five cells, so the only value that the terminal can cut is the key, and a key + cut at the edge reads better than a short key padded to the width of a 64-hex lane. + + A neighbour that the device holds as a contact carries that contact, so Enter opens the + node page that the Contacts list opens. A neighbour that nothing can name gets a + contact built from its key prefix, so the row still opens. The page then shows what the + stored history knows about that key, which is the question that a reader has about a + node that their own radio never heard. + + Args: + node: The node that gave the table. Its name is the subject of the title. + entries: The table as the node gave it. + contacts: The contacts of the device, to name each key prefix. + prefix_bytes: The width in bytes of the hash that the routing of the mesh + addresses, to light at the start of each key. + + Returns: + The page. Each row resolves with the :class:`Contact` of its neighbour. + """ + count = len(entries) + picker = ContactListScreen( + f"Neighbours β€” {node.name} Β· {count} node{'' if count == 1 else 's'}", + rows=[_neighbour_row(entry, contacts) for entry in entries], + prefix_bytes=prefix_bytes, + sort=ContactsSort.from_name("snr", NEIGHBOUR_SORT_COLUMNS, NEIGHBOUR_SORT_OPENS_ASCENDING), + lanes=NEIGHBOUR_LANES, + ) + # On a narrow frame the full title costs the way out of the title bar ("Esc back" + # sheds to "Esc"). The short form keeps the count, which is the part the reader + # cannot read off the rows that fit. + picker.short_title = f"Neighbours Β· {count}" + return picker + + +def _neighbour_row(entry: NeighbourInfo, contacts: list[Contact]) -> ContactRow: + """One row of the neighbour table: its contact if the device has one, or else a stub. + + The node gives a key prefix, so the match is by prefix in the two directions (the + device can hold a contact that is itself only a prefix). With no match, the row carries + a contact of that prefix alone. It has no name, so the list draws the key prefix in the + grey of an unidentified node, after the ``β—‹`` unknown type mark. + """ + key = entry.node.lower().removeprefix("0x") + found = next( + ( + c + for c in contacts + for held in ((c.public_key or c.key_prefix or "").lower().removeprefix("0x"),) + if held and (held.startswith(key) or key.startswith(held)) + ), + None, + ) + contact = found or Contact(name="", key_prefix=key) + return ContactRow( + value=contact, + name=found.name if found and found.name else None, + key=contact.public_key or contact.key_prefix or key, + node_type=contact.node_type, + snr=entry.snr, + heard_by_node=entry.heard_at, + unknown=found is None, + ) + + +async def _neighbours(ctx: AppContext, device: Device, node: Contact) -> None: + """Ask the node for its neighbour table, keep the snapshot, and open it as a list. + + The neighbour table is what the node hears for itself: one entry for each node whose + packets reach it directly. It is a second point of view on the mesh, and it shows + links, and whole nodes, that our own radio never received anything from. + + The admin session of this page is already open, so this sends no login. The firmware + gives the table in pages of approximately 25 entries, so the fetch can take some + seconds. Thus it runs under the same spinner dialog with Abort that the reads use. The + snapshot goes to the repository, where it becomes evidence for the topology that the + mesh walk, the path composer, and the trace scenarios read. Thus a fetch from this page + helps the same screens as a fetch from the path composer of the trace. + + The list is a full screen, and a hub: it stays pushed while a node page opens above it. + Thus Esc from that page lands on the same list, at the same row, in the same sort, and + a second Esc goes back to the admin page. + + Args: + ctx: The shared application context. + device: The connected companion. + node: The repeater or room server, which this page is already logged in to. + """ + from .node_detail_screen import open_node_detail + + session = ctx.ui.session + title = f"Neighbours β€” {node.name}" + run_id = ctx.repo.start_run( + "repeater-admin", {"node": node.name, "mode": "neighbours"}, ctx.profile_name + ) + entries: list[NeighbourInfo] = [] + done = False + + async def work(dialog: TracingDialog) -> None: + nonlocal entries, done + dialog.status = f"asking {node.name} for its neighbours…" + session.invalidate() + entries = await device.fetch_neighbours(node) + done = True + + aborted = await _run_under_dialog(ctx, title, work) + if aborted or not done: + # A failure already showed its own dialog (refer to _run_under_dialog). A second + # dialog with an empty list would say the node answered, and it did not. + ctx.repo.finish_run(run_id, "error", {"error": "aborted" if aborted else "no reply"}) + return + # The snapshot is keyed by the node, so a node with no key at all stores nothing. + # (A managed node always has one, because the login addresses it.) + node_id = _key_id(node.public_key or node.key_prefix or "") + if node_id: + ctx.repo.record_neighbours(run_id, node_id, entries) + ctx.repo.finish_run(run_id, "ok", {"node": node.name, "neighbours": len(entries)}) + + if not entries: + # Checked on real firmware: an empty table is a normal answer. A repeater forgets + # its neighbours when it reboots, and it learns them again from the adverts that + # arrive. An empty list to sort and filter is a worse answer than a sentence. + await session.message_dialog( + Text( + "no neighbours β€” it learns them again from the adverts it hears", + style="muted", + ), + title=title, + ) + return + + try: + contacts = await ctx.devstate.contacts() + except Exception: # noqa: BLE001 - the key prefixes alone still make a usable list + contacts = [] + try: + prefix_bytes = int(await ctx.devstate.routing_prefix_bytes()) + except Exception: # noqa: BLE001 - an optional read. Without it, nothing is lit. + prefix_bytes = 0 + picker = neighbours_picker(node, entries, contacts=contacts, prefix_bytes=prefix_bytes) + async with session.stay(picker) as visit: + while True: + chosen = await visit.result() + if chosen is CANCEL or chosen is None: + return + # To look, not to manage: the verbs that remove a contact belong to the list + # that the contact is in, and this list is the table of another node. + await open_node_detail(ctx, chosen, manage=False, lock=True) + + # --- one-shot actions ------------------------------------------------------------ diff --git a/meshterm/ui/slider.py b/meshterm/ui/slider.py new file mode 100644 index 0000000..2e92e66 --- /dev/null +++ b/meshterm/ui/slider.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A horizontal slider: a dialog that sets a whole number in a short range, one step at a time. + +The Preferences page opens it for the volume of the sounds (JP, 2026-11-20: "a slider +(horizontal) 1 at a time"). ←→ move the value one step, Home and End go to the ends, Enter +sets the value, and Esc keeps the old one. The ends clamp, as each cursor in the app does. + +Each step calls ``on_change`` with the new value. The volume uses it to play the channel +message sound at the new volume, so that the user hears the value while choosing it. A +typed number is not necessary: a short range is faster with the arrows, and the bar shows +where the value is in the range. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from rich.console import Group +from rich.text import Text + +from .braillechart import meter +from .tui.fkeys import FPair +from .tui.render import render_lines +from .tui.screen import Screen + +#: The width of the dialog, in cells. The bar takes what the value label does not. +_WIDTH = 44 + + +class SliderScreen(Screen): + """The slider dialog. It resolves with the value that Enter sets, or with ``CANCEL``.""" + + floating = True + footer_hint = "←→ change Β· Home/End ends Β· Enter set Β· Esc keep" + + def __init__( + self, + title: str, + prompt: str, + value: int, + minimum: int, + maximum: int, + on_change: Callable[[int], None] | None = None, + more: str = "More", + less: str = "Less", + ) -> None: + """Make a slider. + + Args: + title: The title of the dialog (the label of the preference). + prompt: The line above the bar (the description of the preference). + value: The value at the start. The slider clamps it to the range. + minimum: The lowest value. + maximum: The highest value. + on_change: Called with the new value at each step. + more: The F-key chip of a step up on a handheld (six cells at most). + less: The F-key chip of a step down. + """ + super().__init__() + self.title = title + self._prompt = prompt + self._minimum = minimum + self._maximum = maximum + self.value = max(minimum, min(maximum, value)) + self._on_change = on_change + self._more = more + self._less = less + + @property + def dialog_width(self) -> int: + """A small box: the prompt and the bar.""" + return _WIDTH + + @property + def picocalc_lyra_lane(self): + """A step up on F1 and a step down on F2: a directional pair rises to its outer key.""" + return ( + FPair(self._more, "right", enabled=self.value < self._maximum), + FPair(self._less, "left", enabled=self.value > self._minimum), + None, + None, + None, + ) + + def render_body(self, width: int) -> list[str]: + """The prompt, then the bar with the value at its right end. + + The bar is a whole number of cells for each step, so that each step lights whole + cells and the bar never ends on a half cell. The value follows the bar. + """ + label = f" {self.value:>{len(str(self._maximum))}}" + steps = self._maximum - self._minimum + 1 + room = max(steps, width - len(label) - 1) + cells = room - room % steps + fraction = (self.value - self._minimum + 1) / steps + bar = meter(fraction, cells, style="accent", slim=True, track="track") + bar.append(label, style="bold") + return render_lines(Group(Text(self._prompt, style="muted"), Text(""), bar), width) + + def handle(self, action: str, data: str = "") -> None: + """Move one step, go to an end, set, or keep.""" + if action == "escape": + super().handle(action, data) + return + if action == "enter": + self.resolve(self.value) + return + steps = {"left": -1, "right": 1, "home": -self._maximum, "end": self._maximum} + if action in steps: + new = max(self._minimum, min(self._maximum, self.value + steps[action])) + if new != self.value: + self.value = new + if self._on_change is not None: + self._on_change(new) diff --git a/meshterm/ui/sweep_screen.py b/meshterm/ui/sweep_screen.py index 7504525..c9d52e8 100644 --- a/meshterm/ui/sweep_screen.py +++ b/meshterm/ui/sweep_screen.py @@ -625,12 +625,13 @@ def _preview_items(victims: list[ScoredContact], locks: list[ScoredContact] | No # of the other way out. This is not ``exit_rows`` itself, because these rows are not # staged changes to a set of values, and the pair must say what it archives. Separator(" "), - Choice(title=Text.assemble(("βœ“ ", "ok"), apply), value=_APPLY), + Choice(title=Text.assemble(("βœ“ ", "ok"), apply), value=_APPLY, always_shown=True), Choice( title=Text.assemble( ("βœ— ", "err"), "Back β€” change nothing" if staged else "Back β€” keep them all" ), value=_BACK, + always_shown=True, ), ] diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index ec940f2..2c72285 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -851,6 +851,8 @@ _GLYPH_MAP: dict[str, str] = { "πŸ“¨": "=", # courier/queue: stacked letters "πŸ””": "β€’", # notify: the badge dot "πŸ”•": "Β·", # mute: the hollowed-out dot + "πŸ”Š": "β—„", # sounds on: the cone of a speaker + "πŸ”‡": "⌫", # sounds off: the speaker with a cross in it "πŸ“±": "β–“", # QR: a dense block "🎨": "β–‘", # pixel image (MCOimg): a fine grid of dots "πŸ”—": "&", # link: the joining glyph diff --git a/meshterm/ui/timemachine_screen.py b/meshterm/ui/timemachine_screen.py index e8decee..9158343 100644 --- a/meshterm/ui/timemachine_screen.py +++ b/meshterm/ui/timemachine_screen.py @@ -1503,7 +1503,13 @@ class TimeMachinePickerScreen(ContactListScreen): sort=sort, prompt=prompt, lead=[ - Choice(command_label("🌐 The whole mesh β€” days, arrivals, the ledger"), MESH), + # The nodes are the data of the picker. Thus a typed filter narrows them + # and keeps this row (Choice.always_shown). + Choice( + command_label("🌐 The whole mesh β€” days, arrivals, the ledger"), + MESH, + always_shown=True, + ), section_heading("Nodes"), ], ) diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index a660d5f..6a8682d 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -2507,6 +2507,9 @@ async def _open_session( Choice( title=marked_label("⚑", "Probe all β€” trace each path once and rank", "warn"), value=("probe", None), + # The candidates are the data of the list, so a typed filter keeps this + # row (Choice.always_shown). + always_shown=True, ) ) picked = await session.run_screen( @@ -2547,7 +2550,8 @@ async def _open_session( ) ) result_items.append(Separator(" ")) - result_items.append(Choice(title="Keep current path", value=None)) # the exit: no adoption + # The way out of the results, which a typed filter keeps (Choice.always_shown). + result_items.append(Choice(title="Keep current path", value=None, always_shown=True)) adopted = await session.run_screen( SelectScreen( f"Probe results β€” {target_label}", diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index f92070c..a4f95f8 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -10,6 +10,7 @@ past it. from __future__ import annotations import re +import time from collections import OrderedDict from collections.abc import Callable, Sequence @@ -180,6 +181,44 @@ def _breathing_room(body_len: int, budget: int) -> int: return 1 if body_len + 2 <= budget else 0 +#: How long the title flashes for a notification, in seconds (refer to :func:`flash_title`). +FLASH_S = 0.3 + +#: The monotonic time until which the title flashes. +_flash_until = 0.0 + + +def flash_title(now: float | None = None) -> None: + """Flash the title of the frame for :data:`FLASH_S` seconds: the notification flash. + + The title shows in reverse video until the time ends. The caller paints at once, and + again when the time ends (refer to :meth:`~meshterm.ui.tui.session.TuiSession.flash`). + The flash is the way to see a notification where no sound plays: on the PicoCalc, with + the sounds muted, or with the "no sound" theme (refer to :mod:`meshterm.services.sound`). + + Args: + now: The monotonic time now. Tests give it. + """ + global _flash_until + _flash_until = (time.monotonic() if now is None else now) + FLASH_S + + +def flashing(now: float | None = None) -> bool: + """Whether the title flashes now.""" + return (time.monotonic() if now is None else now) < _flash_until + + +def _title_markup(title: str, style: str) -> str: + """The markup of a panel title, in reverse video while it flashes. + + The reverse is a markup tag of its own inside the style tag. Rich does not resolve a + theme name and an attribute in one style string (``reverse title.border``). + """ + if flashing(): + return f"[{style}][reverse]{title}[/reverse][/]" + return f"[{style}]{title}[/]" + + def _panel_box( title: str, visible: list[str], @@ -223,7 +262,7 @@ def _panel_box( subtitle = f"[{hint_style(border)}]{' Β· '.join(atoms)}[/]" if atoms else None return Panel( body, - title=f"[{title_style(border)}]{title}[/]" if title else None, + title=_title_markup(title, title_style(border)) if title else None, subtitle=subtitle, subtitle_align="right" if caption else "center", border_style=border, @@ -367,6 +406,8 @@ def _title_bar( break rule_span = max(0, cols - head_span - tail_span - stat_span) heading = screen.bar_title(title, title_style(border)) if title else Text() + if title and flashing(): + heading.stylize("reverse") if status and label_w > rule_span - 2: # One rule cell on each side, and the remaining cells for the title. The status stays. heading.truncate(max(1, rule_span - 4), overflow="ellipsis") @@ -472,7 +513,18 @@ def compose_base( # Rich sets the padded title into the inner ``cols - 4`` cells of the rule. title = fitted_title(base, cols - 4 - 2) flush = base.flush - key = (cols, rows, title, caption, flush, footer_hint, more_above, more_below, *visible) + key = ( + cols, + rows, + title, + flashing(), + caption, + flush, + footer_hint, + more_above, + more_below, + *visible, + ) if footer_lane is None and _BASE_BOX_CACHE is not None and _BASE_BOX_CACHE[0] == key: body = _BASE_BOX_CACHE[1] else: diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index f5e4950..d90b2e1 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -86,6 +86,13 @@ class Choice: row, there is nothing that is worth a slide. Also, if the highlight changes the row back to a chart that is cut off, the fit is lost on the row that the user reads. + always_shown: The row stays in the list while a find-as-you-type filter narrows + it. It is for an **action** row, which is a way out of the screen and not one + of the rows that the user searches: the ``βœ“ Apply …`` / ``βœ— Back …`` pair of an + editor, and the save pair of a live page. Apply has no keyboard key of its own, + so a filter that hid it put the only way to commit the staged changes behind a + press of Esc that the user does not know to make. The filter looks through the + *content* of a list. An action is not content. pans: The row is a line of a table that ←→ pan as one unit. Each row and each column header that pans (:attr:`Separator.pans`) slides by the same shift. Thus the lanes stay under their labels, however far the user panned. The shift also @@ -101,6 +108,7 @@ class Choice: detail: str | Text | Callable[[], str | Text] | None = None hscroll_from: int = 0 fitted: bool = False + always_shown: bool = False pans: bool = False def __post_init__(self) -> None: @@ -624,7 +632,9 @@ class SelectScreen(Screen): Without a filter, groups and headings show as written. With a filter, only the choices that match are shown. But each separator stays, so the list keeps its - section landmarks (and column headers) while it narrows. + section landmarks (and column headers) while it narrows. An action row stays too + (:attr:`Choice.always_shown`): the filter searches the content of the list, and the + way out of the screen is not content. """ needle = self._filter.strip().lower() if not needle: @@ -632,7 +642,7 @@ class SelectScreen(Screen): return [ it for it in self._items - if isinstance(it, Separator) or needle in _plain(it.label).lower() + if isinstance(it, Separator) or it.always_shown or needle in _plain(it.label).lower() ] def _choices(self, rows: list | None = None) -> list: diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 9140b88..978184d 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -102,9 +102,9 @@ from .spinner import spinner_interval #: ``IXON``/``IXOFF``, so ^Q is not XON here. _CTRL_LETTER_CHORDS: dict[str, str] = { "c": "quit", - # ^E reacts to the selected message with an emoji. The raw mode of prompt_toolkit has no - # line editing, so ^E is not "end of line" here (the End key moves the caret). - "e": "react", + # ^E shows or hides a concealed value, for example the pairing PIN (JP, 2026-11-20: it + # was ^S, which the sound mute took). No terminal or multiplexer takes it in raw mode. + "e": "reveal", # ^G logs in to the room that a room screen shows. In the input, ^G is not a special key: # it is the bell only in output, and no terminal or multiplexer takes it. "g": "login", @@ -124,10 +124,10 @@ _CTRL_LETTER_CHORDS: dict[str, str] = { "p": "paths", "q": "quit", "r": "retry", - # ^S is the XOFF key. It is safe here for the same reason that ^Q is not XON (refer to - # the text above): the raw mode clears IXON/IXOFF. Thus the terminal never takes it to - # freeze the screen. - "s": "reveal", + # ^S mutes or unmutes the sounds from any screen (JP, 2026-11-20). S for sound and + # silence. It is the XOFF key, but the raw mode clears IXON/IXOFF (refer to the text + # above), so the terminal never takes it to freeze the screen. + "s": "sound", "u": "url_code", "v": "paste_clipboard", "w": "to_menu", @@ -635,6 +635,8 @@ class TuiSession: # (refer to :meth:`set_quiesce`). Then the quiesce while it is held. Then the # one-way flag that :meth:`leave` raises, which tells if the app is on its way out. self._quiesce: Callable[[], AbstractAsyncContextManager[Any]] | None = None + # What ^S does: the app mutes or unmutes its sounds (refer to set_sound_toggle). + self._sound_toggle: Callable[[], None] | None = None self._quiet: Quiet | None = None self._leaving = False # The Esc of a terminal, held back while the keyboard says that the key is still @@ -816,6 +818,40 @@ class TuiSession: """ self._quiesce = enter + def set_sound_toggle(self, toggle: Callable[[], None] | None) -> None: + """Declare what ^S does: mute or unmute the sounds of the app, from any screen. + + Args: + toggle: Mutes or unmutes the sounds, or ``None`` for nothing. + """ + self._sound_toggle = toggle + + def bell(self) -> None: + """Ring the terminal bell (BEL), for the ``bell`` sound theme. + + Over SSH, the bell rings on the computer of the user, because the terminal there + gets the byte. + """ + output = getattr(self._app, "output", None) + if output is not None: + output.bell() + + def flash(self) -> None: + """Flash the title of the frame, for a notification that plays no sound. + + The title shows in reverse video for :data:`~meshterm.ui.tui.frame.FLASH_S`. The + session paints now, and again when the time ends, so that the title comes back. + """ + from . import frame + + frame.flash_title() + self.invalidate() + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + loop.call_later(frame.FLASH_S + 0.02, self.invalidate) + def set_esc_probe(self, down: Callable[[], bool] | None) -> None: """Declare how to ask whether the Esc key is physically down, for the Esc of a terminal. @@ -2415,6 +2451,13 @@ class TuiSession: # ^W can hit. self._exit_app() return + if action == "sound": + # Mute or unmute the sounds, from any screen (^S). The app declares what the key + # does, because only the app has the sound service (refer to set_sound_toggle). + if self._sound_toggle is not None: + self._sound_toggle() + self.invalidate() + return if action == "paste_clipboard": # Some terminals send Ctrl-V as the literal control key, with no bracketed-paste # sequence, so the event has no text. Read the OS clipboard here, and give the diff --git a/meshterm/ui/watchtower_screen.py b/meshterm/ui/watchtower_screen.py index 78479fd..5360cbb 100644 --- a/meshterm/ui/watchtower_screen.py +++ b/meshterm/ui/watchtower_screen.py @@ -211,28 +211,40 @@ def _menu_items( # toggle for new nodes below them. The set of icons is declared whole and not found from # the rows that are present. Thus the column does not move when the conditional rows # appear and disappear. It is empty where the platform draws no icons. + # The alerts and the watched nodes are the data of the page, so each action row below + # declares that a typed filter keeps it (Choice.always_shown). lane = icon_lane(("βœ“", "πŸ—‘", "⭐", "πŸ””")) unacked = sum(1 for a in alerts if not a.acked) acked = len(alerts) - unacked if unacked: ack_all = marked_label("βœ“", f"Acknowledge all ({unacked})", "ok", lane=lane) - items.append(Choice(ack_all, _ACK_ALL)) + items.append(Choice(ack_all, _ACK_ALL, always_shown=True)) if acked: - items.append(Choice(marked_label("πŸ—‘", "Clear acknowledged", "err", lane=lane), _CLEAR)) + items.append( + Choice( + marked_label("πŸ—‘", "Clear acknowledged", "err", lane=lane), + _CLEAR, + always_shown=True, + ) + ) items.append(section_heading("Watched nodes")) if not watched: items.append(Separator(" none starred yet β€” silence and SNR rules need one")) for key in sorted(watched, key=lambda k: watched[k].name.casefold()): items.append(Choice(_watched_row(watched[key], type_of), ("node", key))) - items.append(Choice(marked_label("⭐", "Watch a node…", "", lane=lane), _WATCH)) + items.append( + Choice(marked_label("⭐", "Watch a node…", "", lane=lane), _WATCH, always_shown=True) + ) items.append(Separator(" ")) state = "[ok]on[/ok]" if new_node_alerts else "[muted]off[/muted]" toggle = Text.from_markup( f"New-node alerts: {state} [muted]β€” announce first-ever appearances[/muted]" ) - items.append(Choice(Text.assemble(icon_mark("πŸ””", "", lane), toggle), _TOGGLE_NEW)) + items.append( + Choice(Text.assemble(icon_mark("πŸ””", "", lane), toggle), _TOGGLE_NEW, always_shown=True) + ) return items diff --git a/scripts/README.md b/scripts/README.md index 6f74314..d6c5077 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -7,6 +7,7 @@ These are tools for the repository. None of them is in the wheel. | `basemap-doctor.py` | Finds why a user's map has no basemap: certificates, DNS, proxy, or colour depth | | `ladders/` | The tools with which JP chooses a visual value by eye: each draws the candidates side by side with MeshTerm's own renderer (the lightness of the node hues, the threshold of the chip seams). `README.md` there explains the method, and how Claude Code opens a ladder in a new window | | `cardputer-zero/` | `build-deb.sh` builds the Debian package for M5Stack's app store. Run it on the Cardputer Zero or on another arm64 Debian 13 system. `store/` holds the listing for the store (`app-builder.json`, which `czdev publish` reads), its icon, and its screenshots. `screenshot.py` saves the display of a Cardputer as a 320Γ—170 PNG over SSH, as the store wants a screenshot. `store-publish.py` sends a package to the store with M5Stack's `czdev`, with two corrections. The release workflow runs it after each release. `launcher-entry.sh` puts a source checkout in the Cardputer Zero's app launcher. `remove` takes it out. `meshterm.png` is the package's icon: the website's logo, at the launcher's 100Γ—100 size. `meshterm-dev.png` is its negative, for the checkout's entry, so that the two entries look different. `type-text.py` types a pasted string (an API key, a Wi-Fi password) on the Cardputer's keyboard from another computer, over SSH | +| `sounds.py` | Makes the WAV files of the Android sound theme (`meshterm/assets/sounds/android/`) from the AOSP sources at a fixed commit. It needs `soundfile`, which is not a dependency of MeshTerm: run it from a separate environment | | `screenshots.py` | Makes the screenshots of the website from the demo mesh (`--demo`): the main menu, the chat, the paths of a message, and the map, for the terminal, the Cardputer Zero, and the PicoCalc. They are the same at each run. The result goes to `docs/screenshots//`. It also draws the two wordmarks of the splash into `docs/screenshots/splash/`, which the website uses as its splash | | `video.py` | Makes the demo video of the website from the demo mesh: a tour of less than two minutes in the terminal, with its poster and its play card. The result goes to `src/` of the `meshterm.net` checkout beside this one | | `reels.py` | Makes the videos for Instagram from the demo mesh: one vertical video for each page, with subtitles in the picture and no sound, a cover, and a caption for the post. The tours are in `reel_tours.py`. The result goes to `output/reels/` | diff --git a/scripts/sounds.py b/scripts/sounds.py new file mode 100644 index 0000000..2a4c158 --- /dev/null +++ b/scripts/sounds.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Make the WAV files of the Android sound theme from the AOSP sources. + +MeshTerm plays its notification sounds through the player of the operating system: +``winsound`` on Windows, ``afplay`` on macOS, and ``pw-play``, ``paplay``, or ``aplay`` on +Linux. All of these players read WAV, but not all of them read Ogg Vorbis. The sources in +AOSP are Ogg Vorbis. Thus this script downloads each source at a fixed AOSP commit, decodes +it, mixes it to one channel, and writes a 16-bit WAV into ``meshterm/assets/sounds/android``. +The WAV files are in the repository, so a build of MeshTerm never runs this script. + +The decoder is ``soundfile`` (libsndfile), which is not a dependency of MeshTerm. Install +it in a separate environment first:: + + python -m venv /tmp/sounds-venv + /tmp/sounds-venv/bin/pip install soundfile + /tmp/sounds-venv/bin/python scripts/sounds.py + +The sources are under the Apache License 2.0 (``Android.bp`` in ``data/sounds`` declares +``Android-Apache-2.0``), the same licence as MeshTerm. ``README.md`` in the output folder +names them. +""" + +from __future__ import annotations + +import base64 +import urllib.request +import wave +from pathlib import Path + +import numpy as np +import soundfile + +#: The AOSP commit of ``platform/frameworks/base`` that the files come from. A fixed commit +#: makes the output the same at each run. +COMMIT = "1cdfff555f4a21f71ccc978290e2e212e2f8b168" + +#: Each source, by its path under ``data/sounds`` at :data:`COMMIT`. JP selected them by +#: ear on 2026-11-20, from an audition of 188 sounds. +SOURCES: tuple[str, ...] = ( + "notifications/material/ogg/Carme.ogg", + "notifications/material/ogg/Ariel.ogg", + "notifications/material/ogg/Ceres.ogg", + "effects/ogg/InCallNotification.ogg", + "effects/ogg/LowBattery.ogg", + "effects/ogg/Effect_Tick.ogg", +) + +_BASE = "https://android.googlesource.com/platform/frameworks/base/+/{commit}/data/sounds/{path}" +_OUT = Path(__file__).resolve().parent.parent / "meshterm" / "assets" / "sounds" / "android" + + +def download(path: str) -> bytes: + """Download one source file from Gitiles, which serves a file as Base64 text.""" + url = _BASE.format(commit=COMMIT, path=path) + "?format=TEXT" + with urllib.request.urlopen(url, timeout=30) as reply: # noqa: S310 - a fixed https URL. + return base64.b64decode(reply.read()) + + +def write_wav(target: Path, samples: np.ndarray, rate: int) -> None: + """Write mono samples (floats from -1 to 1) as a 16-bit PCM WAV file.""" + pcm = np.clip(samples, -1.0, 1.0) + data = (pcm * 32767).round().astype(" None: + """Download, decode, and write each source.""" + _OUT.mkdir(parents=True, exist_ok=True) + tmp = _OUT / "_source.ogg" + for path in SOURCES: + tmp.write_bytes(download(path)) + samples, rate = soundfile.read(str(tmp), dtype="float64", always_2d=True) + mono = samples.mean(axis=1) + target = _OUT / (Path(path).stem + ".wav") + write_wav(target, mono, rate) + print(f"{target.name}: {len(mono) / rate:.2f} s, {target.stat().st_size} bytes") + tmp.unlink() + + +if __name__ == "__main__": + main() diff --git a/tests/test_channels.py b/tests/test_channels.py index 3e6d619..7db9d66 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -514,6 +514,8 @@ class _ScriptedUi: self._selects = list(selects) self._texts = list(texts) self._dialogs = list(dialogs) + self.asked: list[str] = [] + self.notices: list[str] = [] def show(self, *renderables) -> None: # noqa: ANN002 pass @@ -557,8 +559,20 @@ class _ScriptedUi: danger: bool = False, destructive: bool = False, ): + self.asked.append(prompt.plain if hasattr(prompt, "plain") else str(prompt)) return self._dialogs.pop(0) + async def notify_startup( # noqa: ANN201 + self, + renderable, # noqa: ANN001 + *, + title: str = "", + banner=None, # noqa: ANN001 + footnote: str | None = None, + ): + plain = renderable.plain if hasattr(renderable, "plain") else str(renderable) + self.notices.append(f"{title}: {plain}") + async def test_recreating_a_slot_refiles_messages_to_the_new_channel(ctx: AppContext) -> None: """If a channel is cleared and another channel uses its slot, the histories must not mix. @@ -1361,3 +1375,191 @@ async def test_a_reorder_that_breaks_partway_says_so(ctx: AppContext) -> None: device.set_channel = flaky # type: ignore[method-assign] assert await _reorder_channels(ctx, device, slots) == 0 # not counted as a complete reorder assert said and "reorder stopped partway" in said[0] + + +# -- the name that says Public (the #Public trap) ------------------------------ + + +async def test_the_name_public_offers_the_standard_channel_instead(ctx: AppContext) -> None: + """``Public`` typed as a # name asks again, and the answer can write the real channel. + + ``#Public`` is a different channel: its key comes from its name, so no other node is on + it. A user who made it by mistake had a channel that sent with no error and that nobody + heard. + """ + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=["standard"]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert (slot.idx, slot.name, slot.secret) == (0, "Public", DEFAULT_PUBLIC_SECRET) + assert ctx.ui.asked and "is not the standard Public channel" in ctx.ui.asked[0] + + +async def test_the_name_public_can_still_be_used_on_purpose(ctx: AppContext) -> None: + """The question does not refuse the name. A user who wants ``#Public`` can have it.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=["named"]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert slot.name == "#Public" and slot.secret != DEFAULT_PUBLIC_SECRET + + +async def test_cancel_on_the_public_question_writes_nothing(ctx: AppContext) -> None: + """Cancel on the question leaves the slot as it was.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["#public"], dialogs=[None]) + assert await _add_public(ctx, device, [], 8) == 0 + assert await read_channel_slots(device) == [] + + +async def test_any_other_public_name_asks_nothing(ctx: AppContext) -> None: + """Only the one name that names the standard channel asks again. + + The scripted UI has no dialog to give. Thus a question here would raise. + """ + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["yul"], dialogs=[]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert slot.name == "#yul" + + +async def test_the_question_says_where_the_standard_public_already_is(ctx: AppContext) -> None: + """With the real Public on the device, the question names its slot and offers no copy.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + await device.set_channel(2, "Public", DEFAULT_PUBLIC_SECRET) + slots = list(await read_channel_slots(device)) + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=[None]) + assert await _add_public(ctx, device, slots, 8) == 0 + assert "already on slot 2" in ctx.ui.asked[0] + + +# -- the Public channel of a device that has none ------------------------------ + + +def _as_a_radio(ctx: AppContext) -> None: + """Let the startup step act, which it does not do on the simulator. + + The step passes over ``--mock``, because that device starts with no channel at each + launch (refer to :mod:`meshterm.ui.public_default`). These tests are about a real radio + with no channel, and the simulator is what stands in for it. + """ + ctx.mock = False + + +async def test_a_device_with_no_channel_gets_public_at_startup(ctx: AppContext) -> None: + """A radio with no channel at all cannot send. MeshTerm gives it Public, and says so.""" + from meshterm.ui.public_default import add_public_when_empty + + await ctx.device() # open the link, so that the step has one to use + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is True + (slot,) = await read_channel_slots(await ctx.device()) + assert (slot.idx, slot.name, slot.secret) == (0, "Public", DEFAULT_PUBLIC_SECRET) + assert ctx.ui.notices and "Public channel added" in ctx.ui.notices[0] + + +async def test_a_device_that_has_a_channel_is_left_alone(ctx: AppContext) -> None: + """One channel is enough. The step then reads slot 0 only, and writes nothing.""" + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + await device.set_channel(0, "#yul", None) + reads: list[int] = [] + real = device.get_channel + + async def counted(idx: int): # noqa: ANN202 + reads.append(idx) + return await real(idx) + + device.get_channel = counted # type: ignore[method-assign] + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert reads == [0] # one round trip, at each startup of a device with channels + assert ctx.ui.notices == [] + + +async def test_a_device_with_channels_above_slot_zero_is_left_alone(ctx: AppContext) -> None: + """An empty slot 0 is not an empty device. The step counts each slot before it writes.""" + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + await device.set_channel(3, "#yul", None) + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert [s.idx for s in await read_channel_slots(device)] == [3] + + +async def test_a_probe_that_did_not_finish_writes_nothing(ctx: AppContext) -> None: + """A read that failed proves nothing: an empty short list looks like an empty device.""" + from meshterm.core.connection import DeviceCommandError + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + real = device.get_channel + + async def flaky(idx: int): # noqa: ANN202 + if idx == 0: + return await real(idx) # empty, and that much is true + raise DeviceCommandError("no reply in time") + + device.get_channel = flaky # type: ignore[method-assign] + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + device.get_channel = real # type: ignore[method-assign] + assert await read_channel_slots(device) == [] + + +async def test_the_startup_step_never_opens_the_radio(ctx: AppContext) -> None: + """With no live link, the step does nothing at all: it never connects to write.""" + from meshterm.ui.public_default import add_public_when_empty + + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert ctx.is_connected is False + assert await add_public_when_empty(ctx) is False + assert ctx.is_connected is False + + +async def test_the_preference_turns_the_step_off(ctx: AppContext) -> None: + """A user who wants a radio with no channel turns the preference off. + + The Chat picker still offers Public there, because that offer only asks. + """ + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + _as_a_radio(ctx) + ctx.preferences.set("public_on_empty_device", False) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert await read_channel_slots(device) == [] + + +async def test_the_simulator_is_passed_over(ctx: AppContext) -> None: + """``--mock`` starts with no channel at each launch, so the step leaves it alone. + + Without this, each launch of the development loop and of the emulator wrote a channel + and stopped on a card. + """ + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + assert ctx.mock is True + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert await read_channel_slots(device) == [] diff --git a/tests/test_chat.py b/tests/test_chat.py index 42da55a..e063dac 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -10,7 +10,9 @@ from __future__ import annotations import asyncio import logging import re +from contextlib import asynccontextmanager from pathlib import Path +from types import SimpleNamespace import pytest from rich.cells import cell_len @@ -2784,6 +2786,232 @@ async def test_badge_still_respects_a_muted_channel(tmp_path: Path, repo: Reposi await device.disconnect() +# -- the sound of a received message ------------------------------------------------- + + +class _FakeSound: + """Records each event that the chat service asks to play, under the real rules. + + It is the real sound service with its output replaced, so that the switches of the + events and the mention rule are the real ones. + """ + + def __init__(self, ctx) -> None: # noqa: ANN001 - the test context + """Wrap the real service around ``ctx``, with an output that records.""" + from meshterm.services.sound import SoundService + + self.events: list = [] + self._service = SoundService(ctx, player=SimpleNamespace(play=lambda path: True)) + self._service._emit = self._record # type: ignore[method-assign] + + def _record(self, event, volume=None) -> bool: # noqa: ANN001 - a SoundEvent + self.events.append(event) + return True + + def notify(self, event) -> bool: # noqa: ANN001 - a SoundEvent + """Play the event through the real rules of the service.""" + return self._service.notify(event) + + +async def _sound_chat(repo: Repository, tmp_path: Path, **prefs: object): + """A chat service on the mock device with Public on slot 0, and a list of sound events.""" + device = MockDevice() + await device.connect() + device._channels[0] = { + "channel_idx": 0, + "channel_name": "Public", + "channel_secret": DEFAULT_PUBLIC_SECRET, + } + ctx = _GatedContext(device, repo) + ctx.preferences = Preferences(values=prefs) + ctx.sound = _FakeSound(ctx) + chat = ChatService(ctx) + await chat.start() + return device, ctx, chat, ctx.sound.events + + +def _public_key() -> str: + from meshterm.core.channels import channel_identity + + return f"chan:{channel_identity('Public', DEFAULT_PUBLIC_SECRET)}" + + +def _mute_public(ctx, tmp_path: Path) -> None: + from meshterm.core.channels import channel_identity + from meshterm.core.mute_store import MuteStore + + ctx.mute_store = MuteStore(tmp_path / "mutes.json") + ctx.mute_store.set_muted(channel_identity("Public", DEFAULT_PUBLIC_SECRET), True) + + +async def test_sound_each_kind_plays_its_own_event(tmp_path: Path, repo: Repository) -> None: + """A DM, a channel message, and a mention each play their own event, by default.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True)) + await _record( + chat, ctx, Message(text="Ann: @[MockCompanion] look", channel=0, is_channel=True) + ) + assert events == [ + SoundEvent.DIRECT_MESSAGE, + SoundEvent.CHANNEL_MESSAGE, + SoundEvent.MENTION, + ] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_mention_in_a_dm_is_a_dm(tmp_path: Path, repo: Repository) -> None: + """A DM is already for us, so a mention in it plays the DM sound (JP, 2026-11-21).""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="@[MockCompanion] hi", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_switched_off_event_is_silent(tmp_path: Path, repo: Repository) -> None: + """``sound_channel = off`` silences channel messages, and DMs still play.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path, sound_channel=False) + try: + await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True)) + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_the_open_conversation_plays_by_default( + tmp_path: Path, repo: Repository +) -> None: + """The conversation on the screen plays, until ``sound_on_screen`` is off.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + chat.set_active("dm:d4e5f6a7") + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + ctx.preferences.set("sound_on_screen", False) + await _record(chat, ctx, Message(text="again", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_muted_channel_is_silent(tmp_path: Path, repo: Repository) -> None: + """A mute turns off the notifications of a channel, and a sound is one.""" + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + _mute_public(ctx, tmp_path) + await _record(chat, ctx, Message(text="Ann: hey", channel=0, is_channel=True)) + assert events == [] + assert chat.unread(_public_key()) == 0 + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_an_always_mention_passes_every_rule(tmp_path: Path, repo: Repository) -> None: + """``always`` plays on a muted channel, with its kind off, and on screen with that off.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat( + repo, tmp_path, sound_channel=False, sound_on_screen=False + ) + try: + _mute_public(ctx, tmp_path) + chat.set_active(_public_key()) + await _record( + chat, ctx, Message(text="Ann: @[MockCompanion] look", channel=0, is_channel=True) + ) + assert events == [SoundEvent.MENTION] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_an_on_mention_follows_the_rules(tmp_path: Path, repo: Repository) -> None: + """``on`` plays the mention sound, but a muted channel stays silent.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path, sound_mention="on") + try: + await _record( + chat, ctx, Message(text="Ann: @[MockCompanion] look", channel=0, is_channel=True) + ) + assert events == [SoundEvent.MENTION] + _mute_public(ctx, tmp_path) + await _record( + chat, ctx, Message(text="Ann: @[MockCompanion] look", channel=0, is_channel=True) + ) + assert events == [SoundEvent.MENTION] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_mention_as_a_message_plays_its_kind( + tmp_path: Path, repo: Repository +) -> None: + """``regular`` treats a mention as a channel message, with the rules of one.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path, sound_mention="regular") + try: + await _record( + chat, ctx, Message(text="Ann: @[MockCompanion] look", channel=0, is_channel=True) + ) + assert events == [SoundEvent.CHANNEL_MESSAGE] + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_the_backlog_of_the_companion_is_silent( + tmp_path: Path, repo: Repository +) -> None: + """Messages that waited in the companion before the connect play nothing, mentions too.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="hello", sender="d4e5f6a7", waited=True)) + text = "Ann: @[MockCompanion] look" + await _record(chat, ctx, Message(text=text, channel=0, is_channel=True, waited=True)) + assert events == [] + await _record(chat, ctx, Message(text="live", sender="d4e5f6a7")) + assert events == [SoundEvent.DIRECT_MESSAGE] + # The backlog is still stored and counted: only the sound is skipped. + assert chat.unread("dm:d4e5f6a7") == 2 + finally: + await chat.stop() + await device.disconnect() + + +async def test_sound_a_conversation_with_no_row_is_silent(tmp_path: Path, repo: Repository) -> None: + """A message that the Chat picker cannot list (a repeater reply) plays nothing.""" + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + await _record(chat, ctx, Message(text="> ok", sender="a1b2c3d4")) + assert events == [] + finally: + await chat.stop() + await device.disconnect() + + async def test_channel_slot_change_drops_the_cached_channel_list(repo: Repository) -> None: """If a slot resolves to a new identity, the cached channel list of the screens is invalid. @@ -3894,6 +4122,17 @@ def test_a_sender_with_no_key_opens_trace_target_under_its_name(monkeypatch) -> # -- the Public offer (issue #36) --------------------------------------------- +@asynccontextmanager +async def _nothing(): + """A busy dialog that draws nothing, for the fake UI of the offer tests.""" + yield + + +async def _empty_slot(_idx: int) -> dict: + """A slot read that proves the slot is free.""" + return {} + + def test_picker_offers_public_when_the_device_has_none() -> None: """With no Public on the device, the picker offers it on slot 0, as a row that is not on it.""" from meshterm.core.channel_probe import ChannelSlot @@ -3905,6 +4144,34 @@ def test_picker_offers_public_when_the_device_has_none() -> None: assert [c.on_device for c in _channels_from_slots([other])] == [False, True] +def test_picker_offers_public_when_another_channel_holds_slot_zero() -> None: + """A full slot 0 does not hide the offer. The key of the channel decides, not the slot. + + A user who made ``#Public`` by mistake (a different channel, whose key comes from its + name) filled slot 0 with it. The offer then disappeared, which hid the one way back to + the real channel. + """ + from meshterm.core.channel_probe import ChannelSlot + from meshterm.tools.chat import _channels_from_slots + + wrong = ChannelSlot(0, "#Public", derive_secret("#Public")) + rows = _channels_from_slots([wrong]) + assert [(c.label, c.channel_idx, c.on_device) for c in rows] == [ + ("Public", 1, False), # the offer, on the lowest free slot + ("#Public", 0, True), + ] + + +def test_picker_has_no_offer_when_each_slot_is_full() -> None: + """With no free slot, the offer has nowhere to go, so the picker does not show it.""" + from meshterm.core.channel_probe import ChannelSlot + from meshterm.core.channels import MAX_CHANNELS + from meshterm.tools.chat import _channels_from_slots + + full = [ChannelSlot(i, f"#c{i}", derive_secret(f"#c{i}")) for i in range(MAX_CHANNELS)] + assert all(c.on_device for c in _channels_from_slots(full)) + + def test_picker_has_no_offer_when_public_is_on_the_device() -> None: """A Public channel on any slot is the real row. The picker adds no second Public.""" from meshterm.core.channel_probe import ChannelSlot @@ -3929,11 +4196,18 @@ class _OfferUi: def __init__(self, answer) -> None: self.answer = answer self.asked: list[str] = [] + self.session = None async def dialog(self, prompt, buttons, **_kw): self.asked.append(prompt) return self.answer + def busy_dialog(self, *_a, **_kw): + return _nothing() + + def note(self, *_a, **_kw) -> None: + return None + class _OfferDevstate: def __init__(self) -> None: @@ -3942,6 +4216,9 @@ class _OfferDevstate: async def channel_slots(self): return list(self.slots) + async def channel_capacity(self): + return 8 + def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch): from types import SimpleNamespace @@ -3958,7 +4235,9 @@ def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("meshterm.ui.channels.write_channel", write_channel) async def device(): - return object() + # _pick_free_slot reads the slot one more time before it writes. An empty answer + # proves that the slot is free. + return SimpleNamespace(get_channel=_empty_slot) ctx = SimpleNamespace(ui=_OfferUi(answer), devstate=devstate, device=device) return ctx, writes @@ -3981,3 +4260,22 @@ def test_public_offer_add_writes_slot_zero(monkeypatch: pytest.MonkeyPatch) -> N added = asyncio.run(_add_public_channel(ctx)) assert writes == [(0, "Public", DEFAULT_PUBLIC_SECRET)] assert added is not None and added.on_device and added.channel_idx == 0 + + +async def test_sound_a_room_catch_up_is_silent(tmp_path: Path, repo: Repository) -> None: + """The posts that a room sends after a login were already there, so they play nothing.""" + from meshterm.services.sound import SoundEvent + + device, ctx, chat, events = await _sound_chat(repo, tmp_path) + try: + catching_up = [True] + ctx.rooms = SimpleNamespace(catching_up=lambda peer: catching_up[0]) + post = Message(text="old news", sender="aabbccddeeff", author="11223344") + await chat._play_sound(post, "dm:aabbccddeeff") + assert events == [] + catching_up[0] = False + await chat._play_sound(post, "dm:aabbccddeeff") + assert events == [SoundEvent.ROOM_POST] + finally: + await chat.stop() + await device.disconnect() diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index 8bdda1e..b942ddc 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -53,7 +53,14 @@ _PATH_SPEC = re.compile(r"[0-9a-f]+(?:,[0-9a-f]+)*") _LISTINGS: list[tuple[str, list[str], list[str]]] = [ # (command, arguments, headings or keys the output must carry) ("contacts", [], ["NAME", "TYPE", "HEARD", "PKTS", "HASH", "LOCATION", "PLACE", "KEY"]), - ("info", [], ["name", "public_key", "role"]), + # ``info`` answers with three blocks: the status, the sensor readings, and every + # setting. The settings come from the definition that ``config show`` answers with, so + # one setting is never spelled two ways. + ( + "info", + [], + ["name", "public_key", "role", "queue_len", "packets_sent_flood", "CHANNEL", "radio_freq"], + ), ("config", ["show"], ["name", "radio_freq", "tx_power"]), ("preferences", ["show"], ["PREFERENCE", "VALUE", "DEFAULT", "DESCRIPTION"]), ("chat", ["list"], ["CONVERSATION", "KIND", "UNREAD", "LAST", "LAST_TEXT"]), diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 1f54b9f..fd65ca8 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -12,7 +12,7 @@ import pytest import typer from meshterm.core.config_io import backup_config, plan_restore, read_backup -from meshterm.core.connection import MockDevice +from meshterm.core.connection import MockDevice, derived_scope_key from meshterm.core.device_config import ( RADIO_PRESETS, DeviceConfigError, @@ -1370,6 +1370,30 @@ def test_contacts_screen_tail_offers_archive_only_when_populated() -> None: assert _ARCHIVE not in values # nothing to archive, so no action row +def test_a_filter_on_the_contacts_narrows_them_and_keeps_the_archive_rows() -> None: + """A typed query hides the contacts that do not match. The two tail rows stay. + + The contacts are the data of the list. What the page *does* is not in the query, so a + filter that hid the actions left them unreachable until the user cleared it. + """ + from meshterm.core.models import Contact + from meshterm.ui.contacts_screen import _ARCHIVE, _ARCHIVED, ContactsScreen + + screen = ContactsScreen( + "Us", + "cc" * 32, + [Contact(name="Alice", public_key="aa" * 32)], + 1, + {}, + _contacts_sort(), + archived=2, + ) + screen.note_viewport(20) + for ch in "zzzz": # a query that no contact matches + screen.handle("text", ch) + assert [c.value for c in screen._choices()] == [_ARCHIVE, _ARCHIVED] + + def test_the_archived_row_appears_only_when_something_is_archived() -> None: """The row for the archived list, with its count, shows only when there is an archived list. @@ -1818,11 +1842,12 @@ async def test_status_panel_reports_role_battery_clock_and_stats() -> None: from rich.console import Console - from meshterm.tools.info import _status_panel + from meshterm.tools.info import AppFacts, read_status, status_panel from meshterm.ui.theme import MESH_THEME device = await _connected_mock() - panel = await _status_panel(device, await build_snapshot(device)) + snapshot = await build_snapshot(device) + panel = status_panel(snapshot, await read_status(device), AppFacts(preset="Default")) console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) console.print(panel) out = console.file.getvalue() @@ -1836,6 +1861,97 @@ async def test_status_panel_reports_role_battery_clock_and_stats() -> None: assert "210 sent" in out and "1234 received" in out +async def test_status_panel_reports_the_facts_that_only_the_newer_frames_give() -> None: + """The panel draws each fact that the firmware reports and that no screen drew before.""" + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + await device.set_default_flood_scope("yul") + snapshot = await build_snapshot(device) + app = AppFacts(place="Villeray", site="Home", outbound_paths=2, kept_routes=3, contacts=27) + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), app)) + out = console.file.getvalue() + + assert "protocol 12" in out # the companion API version of the device-query frame + assert "yul" in out and derived_scope_key("yul") in out # the scope and its key + assert "Villeray" in out and "Home" in out and "3 kept routes" in out + assert "27 / 300" in out # the contacts of the device against its capacity + assert "waiting to send" in out # the outbound queue of the firmware + assert "40 sent" in out and "900 received" in out # the flood split of the packets + assert "170 sent" in out and "334 received" in out # and the direct split + assert "temperature 21.5 Β°C" in out # the sensor readings of the node itself + + +async def test_status_panel_warns_when_a_stored_scope_key_is_not_the_key_of_its_name() -> None: + """A device that stores a key that its scope name does not give gets a warning on the row. + + Nothing else in MeshTerm can show this fault. A flood that goes out under that key + reaches no repeater that listens for the name. + """ + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + await device.set_default_flood_scope("yul") + snapshot = {**await build_snapshot(device), "flood_scope_key": "ff" * 16} + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), AppFacts())) + + assert "does not match the name" in console.file.getvalue() + + +async def test_an_unscoped_device_says_that_its_floods_reach_everyone() -> None: + """With no default scope, the row is a statement and not an empty value.""" + import io + + from rich.console import Console + + from meshterm.tools.info import AppFacts, read_status, status_panel + from meshterm.ui.theme import MESH_THEME + + device = await _connected_mock() + snapshot = await build_snapshot(device) + console = Console(theme=MESH_THEME, file=io.StringIO(), width=100) + console.print(status_panel(snapshot, await read_status(device), AppFacts())) + out = console.file.getvalue() + + assert "unscoped" in out and "floods reach everyone" in out + + +async def test_the_snapshot_holds_the_transport_key_of_the_default_scope() -> None: + """``build_snapshot`` reads the scope name and its key in one frame.""" + device = await _connected_mock() + await device.set_default_flood_scope("yul") + + snapshot = await build_snapshot(device) + + assert snapshot["flood_scope"] == "yul" + assert snapshot["flood_scope_key"] == derived_scope_key("yul") + + +async def test_telemetry_readings_carry_their_unit_on_each_face() -> None: + """The plain face puts the unit in the value. The document keeps the number alone.""" + from meshterm.tools.info import read_status, telemetry_listing + + device = await _connected_mock() + listing = telemetry_listing((await read_status(device))["telemetry"]) + rows = {row["name"]: row for row in listing.rows} + + assert rows["temperature"]["value"].text == "21.5 Β°C" + assert rows["temperature"]["value"].value == 21.5 + assert rows["temperature"]["unit"] == "Β°C" + + def test_uptime_renders_compact_units() -> None: """Uptime shows only seconds under a minute. Then it shows the d, h, and m parts as needed.""" from meshterm.tools.info import _uptime diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 3ac3272..d4537a2 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -36,9 +36,11 @@ from types import SimpleNamespace import pytest from rich.cells import cell_len +from rich.console import Group from rich.text import Text from meshterm.core.channels import DEFAULT_PUBLIC_SECRET, derive_secret +from meshterm.core.connection import derived_scope_key from meshterm.core.courier_store import CourierStore from meshterm.core.models import ( NODE_TYPE_CHAT, @@ -68,10 +70,12 @@ from meshterm.platforms import ( set_platform, ) from meshterm.services.courier import CourierService +from meshterm.services.heard_by import HEARD, UNHEARD, WAITING, HeardBy from meshterm.services.message_paths import Arrival from meshterm.services.monitor_service import ACTIVITY_BUCKETS from meshterm.services.records import CATEGORY_BY_ID from meshterm.services.topology import MeshTopology, build_topology +from meshterm.tools.info import AppFacts, status_panel from meshterm.ui.about import ( AboutPage, about_author, @@ -98,7 +102,7 @@ from meshterm.ui.path_composer import PathComposerScreen from meshterm.ui.preferences import _menu_items as _preference_items from meshterm.ui.records_screen import RecordScreen, WalkVertex from meshterm.ui.remote_cli import RemoteCliScreen -from meshterm.ui.repeater_admin import AdminMenu +from meshterm.ui.repeater_admin import AdminMenu, neighbours_picker from meshterm.ui.repeater_admin import _menu_items as _admin_menu_items from meshterm.ui.theme import name_style from meshterm.ui.timemachine_screen import TimeMachineScreen @@ -850,6 +854,54 @@ _WOODPECKER = ( ) +class _GalleryHeard: + """A fixed verdict for each of our channel messages, by its text (issue #38).""" + + def __init__(self, verdicts: dict[str, HeardBy]) -> None: + self._verdicts = verdicts + + def verdict(self, message: ChatMessage) -> HeardBy | None: + return self._verdicts.get(message.text) if message.outbound else None + + def waiting(self, messages) -> bool: # noqa: ANN001 - the transcript + return False + + +def _chat_heard(cols: int, rows: int) -> Screen: + """Our channel messages with the three relay marks, and the note of the picked one. + + The marks are ``βœ—`` (no repeater sent a copy back), the spinner, and ``βœ“ 3`` (three + relays sent a copy back). The newest message is picked, so its note names the relays. + The names are long, so the note wraps under the body on the PicoCalc. + """ + conv = Conversation(label="Lakeside", is_channel=True, channel_idx=1) + messages = [ + ChatMessage(text="Alice: anyone on the ridge tonight?", is_channel=True), + ChatMessage(text="anyone hear this?", outbound=True, is_channel=True, row_id=1), + ChatMessage(text="one more try", outbound=True, is_channel=True, row_id=2), + ChatMessage(text="heading up the ridge now", outbound=True, is_channel=True, row_id=3), + ] + heard = _GalleryHeard( + { + "anyone hear this?": HeardBy(UNHEARD), + "one more try": HeardBy(WAITING), + "heading up the ridge now": HeardBy(HEARD, relays=("a1", "b2", "c3"), copies=3), + } + ) + names = {"a1": "Lakeside-North-Shore", "b2": "Marina-Tower", "c3": "Ridge-Top-Solar"} + screen = ChatScreen( + conv, + messages, + send=None, + names={}, + session=_GallerySession(cols, rows), + heard=heard, # type: ignore[arg-type] + hop_name=lambda hop: names.get(hop, hop), + ) + screen.handle("up") + return screen + + def _chat_image(cols: int, rows: int, *, picked: bool = False) -> Screen: """A channel message that is a pixel image: its caption, and the image in half blocks. @@ -1720,9 +1772,17 @@ def _tx_sweep(cols: int, rows: int) -> Screen: #: field that the config table draws, with the pairing PIN that the table conceals. _DEVICE_SNAPSHOT = { "name": "Homestead-Hub", + "public_key": "3d63c6429436b1e8a4f2c0d5768e9a1b2c3d4e5f60718293a4b5c6d7e8f90a1b", + "adv_type": 1, "adv_lat": 45.5017, "adv_lon": -73.5673, "ble_pin": 123456, + "model": "Heltec V3", + "ver": "v1.15.0", + "fw_build": "1a2b3c4d", + "fw ver": 12, + "max_contacts": 300, + "max_channels": 8, "radio_freq": 869525, "radio_bw": 250, "radio_sf": 11, @@ -1733,7 +1793,8 @@ _DEVICE_SNAPSHOT = { "rx_delay": 0.0, "manual_add_contacts": 0, "autoadd_config": 0, - "flood_scope": "", + "flood_scope": "yul", + "flood_scope_key": derived_scope_key("yul"), "adv_loc_policy": 1, "multi_acks": 0, "telemetry_mode_base": 1, @@ -1743,17 +1804,68 @@ _DEVICE_SNAPSHOT = { } +#: The live readings behind the status panel of the Device info page. Every field that any +#: of the three statistics frames reports is here, so that the gallery measures the widest +#: row that a real device can draw. +_DEVICE_READINGS = { + "battery": {"level": 4100, "used_kb": 412, "total_kb": 1024}, + "stats": { + "uptime_secs": 273_640, + "errors": 0, + "queue_len": 2, + "noise_floor": -112, + "last_rssi": -96, + "last_snr": 7.25, + "tx_air_secs": 318, + "rx_air_secs": 9_412, + "recv": 14_803, + "sent": 1_212, + "flood_tx": 388, + "direct_tx": 824, + "flood_rx": 11_590, + "direct_rx": 3_213, + "recv_errors": 41, + }, + "clock": 1_764_000_000, + "telemetry": [ + {"channel": 0, "name": "voltage", "value": 4.1}, + {"channel": 1, "name": "temperature", "value": 21.5}, + ], +} + +#: What MeshTerm knows about its own node, with each field filled: the panel then draws +#: every row that it has. +_DEVICE_APP_FACTS = AppFacts( + place="Villeray, MontrΓ©al", + site="Home", + outbound_paths=2, + kept_routes=3, + contacts=27, + channels=4, + preset="Default", +) + + +def _device_info_page(reveal: bool) -> Group: + """The Device info page: the status panel over the settings table, as the tool draws it.""" + return Group( + status_panel(_DEVICE_SNAPSHOT, _DEVICE_READINGS, _DEVICE_APP_FACTS), + Text(""), + config_table(_DEVICE_SNAPSHOT, {}, reveal_pin=reveal), + ) + + def _device_info(cols: int, rows: int) -> Screen: return DeviceInfoScreen( _GallerySession(cols, rows), - lambda reveal: config_table(_DEVICE_SNAPSHOT, {}, reveal_pin=reveal), + _device_info_page, title="Device info", conceals=has_pin(_DEVICE_SNAPSHOT), ) def _device_info_revealed(cols: int, rows: int) -> Screen: - # The same page after ^S: the widest state of the row that the other case masks. + # The same page after ^E: the widest state of the row that the other case masks. screen = _device_info(cols, rows) screen.handle("reveal") return screen @@ -1770,7 +1882,7 @@ def _config_editor(cols: int, rows: int) -> Screen: def _config_editor_revealed(cols: int, rows: int) -> Screen: - # The same list after ^S, where the PIN row is at its widest. + # The same list after ^E, where the PIN row is at its widest. screen = _config_editor(cols, rows) screen.handle("reveal") return screen @@ -1789,6 +1901,33 @@ def _repeater_admin(cols: int, rows: int) -> Screen: return AdminMenu(title, items, footer_hint="↑↓ move Β· type to filter Β· Enter select Β· Esc back") +def _repeater_neighbours(cols: int, rows: int) -> Screen: + """The neighbour table of a repeater: a full screen in the shared contact-list lanes. + + It has the widest shapes that the list can draw: a long name, a node that nothing can + name (which reads as its grey key prefix, after the unknown type mark), and an entry + for which the node gave neither a reading nor an age. + """ + from datetime import timedelta + + from meshterm.core.models import NeighbourInfo + + hub = Contact(name="Hilltop-Repeater", public_key=_HUB_KEY, key_prefix="3d63c6429436") + now = utcnow() + entries = [ + NeighbourInfo("a1b2c3d4", 7.5, now - timedelta(minutes=12)), + NeighbourInfo("b7c80912", 2.0, now - timedelta(days=9)), + NeighbourInfo("c3d4e5f6", -4.25, now - timedelta(hours=3)), + NeighbourInfo("ffee0011", None, None), + ] + contacts = [ + Contact(name="Mont-Royal", public_key="a1b2c3d4" + "1" * 56, node_type=NODE_TYPE_REPEATER), + Contact(name="A Rather Long Node Name", public_key="b7c80912" + "2" * 56), + Contact(name="Chalet-Sensor", public_key="c3d4e5f6" + "3" * 56, node_type=NODE_TYPE_SENSOR), + ] + return neighbours_picker(hub, entries, contacts=contacts, prefix_bytes=1) + + def _preferences(cols: int, rows: int) -> Screen: """The Preferences page when it is widest. @@ -1975,6 +2114,15 @@ def _quit_hold(cols: int, rows: int) -> Screen: return HoldQuitDialog(0.0, clock=lambda: (DIALOG_S + QUIT_S) / 2) +def _volume_slider(cols: int, rows: int) -> Screen: + """The volume slider of the Preferences page, at its default step.""" + from meshterm.core.preferences import get_spec + from meshterm.ui.slider import SliderScreen + + spec = get_spec("sound_volume") + return SliderScreen(spec.label, spec.help, 7, 1, 10, more="Louder", less="Softer") + + def _share_qr(cols: int, rows: int) -> Screen: """The share screen: the code and the link of a contact card on a bare frame (the widest QR).""" from meshterm.ui.qr import QrScreen @@ -2075,6 +2223,7 @@ _ENTRIES: list[_Entry] = [ _Entry("map_find", _map_find), _Entry("chat", _chat), _Entry("chat_channel_scoped", _chat_channel_scoped), + _Entry("chat_heard", _chat_heard), _Entry("chat_urls", _chat_urls), _Entry("chat_reactions", _chat_reactions), _Entry("chat_long_url", _chat_long_url), @@ -2123,11 +2272,13 @@ _ENTRIES: list[_Entry] = [ _Entry("config_editor_revealed", _config_editor_revealed), _Entry("repeater_admin", _repeater_admin), _Entry("region_editor", _region_editor), + _Entry("repeater_neighbours", _repeater_neighbours), _Entry("preferences", _preferences), _Entry("preferences-weekly-advert", _preferences_weekly_advert), _Entry("cooldown_countdown", _cooldown_countdown), _Entry("reconnect_reason", _reconnect_reason), _Entry("quit_hold", _quit_hold), + _Entry("volume_slider", _volume_slider), _Entry("about_meshterm", _about_meshterm), _Entry("about_author", _about_author), _Entry("join_discord", _join_discord), diff --git a/tests/test_heard_by.py b/tests/test_heard_by.py new file mode 100644 index 0000000..96503b9 --- /dev/null +++ b/tests/test_heard_by.py @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the verdict on our channel messages: did a repeater send a copy back? + +The pure part (:func:`judge` and its helpers) is tested with plain paths. The tracker runs +against a real temporary repository, with GRP_TXT packets in the firmware form, so the +tests also use the window query, the decryption, and the stored verdicts. +""" + +from __future__ import annotations + +import asyncio +import sqlite3 +from datetime import datetime, timedelta, timezone +from pathlib import Path + +from Crypto.Cipher import AES +from Crypto.Hash import HMAC, SHA256 + +from meshterm.core.channels import channel_hash, derive_secret +from meshterm.core.models import ChatMessage, Observation, utcnow +from meshterm.persistence.repository import Repository +from meshterm.services.heard_by import ( + HEARD, + UNHEARD, + WAITING, + HeardTracker, + judge, + relay_paths, +) +from meshterm.services.message_paths import Arrival, channel_arrivals + +SECRET = derive_secret("#general") + + +def _grp_txt_raw(secret: bytes, text: str, *, sent: datetime | None = None) -> dict: + """A GRP_TXT packet payload in the firmware form, with ``sent`` as its sender time.""" + stamp = int(sent.timestamp()) if sent is not None else 0 + plain = stamp.to_bytes(4, "little") + bytes([0]) + text.encode("utf-8") + plain += b"\x00" * (-len(plain) % 16) + crypted = AES.new(secret, AES.MODE_ECB).encrypt(plain) + mac = HMAC.new(secret, digestmod=SHA256) + mac.update(crypted) + return { + "payload_typename": "GRP_TXT", + "chan_hash": channel_hash(secret), + "cipher_mac": mac.digest()[:2].hex(), + "crypted": crypted.hex(), + } + + +def _repo(tmp_path: Path) -> tuple[Repository, int]: + repo = Repository(tmp_path / "test.db") + return repo, repo.start_run("monitor", {}, None) + + +def _copy(repo: Repository, run: int, *, when: datetime, path: str, text: str, sent=None): + repo.record_observation( + run, + Observation( + node=None, + kind="packet", + path=path, + snr=1.0, + observed_at=when, + raw=_grp_txt_raw(SECRET, f"Homestead: {text}", sent=sent), + ), + ) + + +def _sent(repo: Repository, text: str, at: datetime) -> ChatMessage: + message = ChatMessage( + text=text, outbound=True, is_channel=True, channel_id="general", created_at=at + ) + message.row_id = repo.record_chat_message(message) + return message + + +# --- the pure verdict ------------------------------------------------------------------ + + +def test_each_relay_in_the_copies_counts_one_time() -> None: + """The repeater next to us counts, and a relay in two copies counts one time.""" + heard = judge([("3D",), ("27", "3d")], age_s=1, wait_s=30) + assert heard.state == HEARD + assert heard.relays == ("3d", "27") + assert heard.copies == 2 + + +def test_the_verdict_waits_before_it_says_unheard() -> None: + """With no copy, the verdict waits, then it is unheard. A copy ends the wait at once.""" + assert judge([], age_s=5, wait_s=30).state == WAITING + assert judge([], age_s=31, wait_s=30).state == UNHEARD + assert judge([("3d",)], age_s=5, wait_s=30).state == HEARD + + +def test_relay_paths_skip_the_copies_that_tell_nothing() -> None: + """An empty path, and a direct-routed copy that used its route, name no relay.""" + now = utcnow() + arrivals = [ + Arrival(when=now, hops=("3d",), snr=None, routed=False), + Arrival(when=now, hops=(), snr=None, routed=False), + Arrival(when=now, hops=(), snr=None, routed=True), + ] + assert relay_paths(arrivals) == [("3d",)] + + +# --- the match of our own messages ----------------------------------------------------- + + +def test_two_sends_of_the_same_text_keep_their_own_copies(tmp_path: Path) -> None: + """Two "test" messages five minutes apart do not share copies: the sender time decides.""" + repo, run = _repo(tmp_path) + first_at = utcnow().replace(microsecond=0) - timedelta(minutes=5) + second_at = first_at + timedelta(minutes=5) + first = _sent(repo, "test", first_at) + second = _sent(repo, "test", second_at) + _copy(repo, run, when=first_at + timedelta(seconds=2), path="3d", text="test", sent=first_at) + _copy(repo, run, when=second_at + timedelta(seconds=2), path="51", text="test", sent=second_at) + one = channel_arrivals(repo, first, channel_name="#general", secret=SECRET) + two = channel_arrivals(repo, second, channel_name="#general", secret=SECRET) + assert [a.hops for a in one] == [("3d",)] + assert [a.hops for a in two] == [("51",)] + repo.close() + + +# --- the tracker ----------------------------------------------------------------------- + + +def _tracker(repo: Repository, now: datetime) -> HeardTracker: + return HeardTracker( + repo, + channel_name="#general", + secret=SECRET, + wait_s=lambda: 30.0, + clock=lambda: now, + ) + + +def test_the_tracker_gives_no_verdict_before_it_examined_the_message(tmp_path: Path) -> None: + """The paint never touches the packet log: an unexamined message has no mark yet.""" + repo, _run = _repo(tmp_path) + now = utcnow().replace(microsecond=0) + message = _sent(repo, "hello", now) + tracker = _tracker(repo, now) + assert tracker.verdict(message) is None + asyncio.run(tracker.fill([message])) + verdict = tracker.verdict(message) + assert verdict is not None and verdict.state == WAITING + repo.close() + + +def test_the_tracker_ignores_other_messages(tmp_path: Path) -> None: + """A received message and a direct message have no verdict.""" + repo, _run = _repo(tmp_path) + now = utcnow() + inbound = ChatMessage(text="hi", is_channel=True, created_at=now, row_id=1) + direct = ChatMessage(text="hi", outbound=True, created_at=now, row_id=2) + tracker = _tracker(repo, now) + asyncio.run(tracker.fill([inbound, direct])) + assert tracker.verdict(inbound) is None + assert tracker.verdict(direct) is None + repo.close() + + +def test_a_late_copy_changes_the_verdict(tmp_path: Path) -> None: + """A copy after the wait turns the verdict from unheard to heard.""" + repo, run = _repo(tmp_path) + sent_at = utcnow().replace(microsecond=0) - timedelta(seconds=40) + message = _sent(repo, "hello", sent_at) + tracker = _tracker(repo, sent_at + timedelta(seconds=40)) + asyncio.run(tracker.fill([message])) + assert tracker.verdict(message).state == UNHEARD # type: ignore[union-attr] + _copy(repo, run, when=sent_at + timedelta(seconds=35), path="3d", text="hello", sent=sent_at) + assert tracker.refresh([message]) is True + verdict = tracker.verdict(message) + assert verdict is not None and verdict.state == HEARD and verdict.relays == ("3d",) + repo.close() + + +def test_an_old_message_is_stored_and_read_back(tmp_path: Path) -> None: + """Out of the match window, the paths are stored, and the next visit reads them.""" + repo, run = _repo(tmp_path) + sent_at = utcnow().replace(microsecond=0) - timedelta(hours=2) + message = _sent(repo, "old one", sent_at) + _copy( + repo, run, when=sent_at + timedelta(seconds=3), path="27,9f", text="old one", sent=sent_at + ) + asyncio.run(_tracker(repo, utcnow()).fill([message])) + assert repo.heard_records([message.row_id]) == {message.row_id: [("27", "9f")]} # type: ignore[list-item,dict-item] + + again = _tracker(repo, utcnow()) + asyncio.run(again.fill([message])) + verdict = again.verdict(message) + assert verdict is not None and verdict.relays == ("27", "9f") + repo.close() + + +def test_a_message_sent_while_the_screen_is_open_waits(tmp_path: Path) -> None: + """A new send starts in the wait.""" + repo, _run = _repo(tmp_path) + now = datetime.now(timezone.utc).replace(microsecond=0) + message = _sent(repo, "new", now) + tracker = _tracker(repo, now) + before = tracker.revision + tracker.note_sent(message) + assert tracker.revision != before + assert tracker.waiting([message]) + repo.close() + + +def test_the_first_build_of_the_table_is_made_again(tmp_path: Path) -> None: + """A database with the near relays column of the first build gets the table again.""" + path = tmp_path / "old.db" + Repository(path).close() + conn = sqlite3.connect(path) + conn.execute("DROP TABLE heard_relays") + conn.execute( + "CREATE TABLE heard_relays (message_id INTEGER PRIMARY KEY, near_hops TEXT, paths TEXT)" + ) + conn.commit() + conn.close() + repo = Repository(path) + cols = {row["name"] for row in repo._conn.execute("PRAGMA table_info(heard_relays)")} + assert cols == {"message_id", "paths"} + repo.close() diff --git a/tests/test_menus.py b/tests/test_menus.py index aefccf0..28fc326 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -47,6 +47,37 @@ def test_exit_rows_staged_state_spells_out_the_consequence() -> None: assert back_row.title.plain == "βœ— Back β€” discard staged changes" +def test_a_filter_keeps_the_way_out_and_the_actions_of_a_page() -> None: + """A typed query narrows the data of a list and keeps the rows that act on the page. + + The exit pair declares it, and so does each command row that a page builds with + ``always_shown``. Apply has no keyboard key of its own, so a filter that hid it left + the staged changes with no way to commit them. + """ + from meshterm.ui.tui import Choice, SelectScreen + + actions = menu_rows([("Read settings", "Ask the device again", "read")], always_shown=True) + items = [ + Choice(title="Airtime budget", value="airtime"), + Choice(title="Radio preset", value="preset"), + *actions, + *exit_rows(2, apply_value="A", back_value="B"), + ] + screen = SelectScreen("Settings", items) + screen.note_viewport(len(items) + 4) + for ch in "zzzz": # a query that no setting matches + screen.handle("text", ch) + assert [choice.value for choice in screen._choices()] == ["read", "A", "B"] + + # A menu is a list of actions, and there the filter is how the user finds one. Thus the + # rows of a plain menu_rows call narrow as before. + menu = SelectScreen("Menu", menu_rows([("Map", "Where the nodes are", "map")])) + menu.note_viewport(8) + for ch in "zzzz": + menu.handle("text", ch) + assert menu._choices() == [] + + def test_menu_rows_align_descriptions_in_display_cells() -> None: """Each description starts at the same cell column, also after a label with a wide emoji.""" rows = menu_rows( diff --git a/tests/test_places.py b/tests/test_places.py index 26de05e..0854012 100644 --- a/tests/test_places.py +++ b/tests/test_places.py @@ -268,6 +268,40 @@ def _run(coro): # noqa: ANN001, ANN202 - a small helper for the async steps return asyncio.run(coro) +def test_place_of_answers_through_a_running_service(tmp_path: Path) -> None: + """With a service, ``place_of`` gives what the service holds.""" + service, repo = _service(tmp_path) + repo.save_node_place("aaaaaaaaaaaa", 45.0, -73.0, Place("Villeray", "MontrΓ©al", SOURCE_TILES)) + + place = places_service.place_of(service._ctx, "aaaaaaaaaaaa") + + assert place is not None and place.label == "Villeray, MontrΓ©al" + + +def test_place_of_reads_the_stores_when_no_service_runs(tmp_path: Path) -> None: + """A scripted run has no service, so the function reads the two sources itself. + + The Device info page and ``meshterm info`` must name the same place. The page has a + service and the command has none, so this path is the one that the command takes. + """ + service, repo = _service(tmp_path) + ctx = service._ctx + places_service._CURRENT = None # the state of a scripted run: no session made a service + try: + repo.save_node_place( + "aaaaaaaaaaaa", 45.0, -73.0, Place("Villeray", "MontrΓ©al", SOURCE_TILES) + ) + repo.save_node_place("bbbbbbbbbbbb", 45.0, -73.0, Place(None, None, SOURCE_TILES)) + ctx.place_store.set("cccccccccccc", "The Shed", when=0) + + assert places_service.place_of(ctx, "aaaaaaaaaaaa").label == "Villeray, MontrΓ©al" + assert places_service.place_of(ctx, "bbbbbbbbbbbb") is None # an empty place is none + assert places_service.place_of(ctx, "cccccccccccc").label == "The Shed" # typed + assert places_service.place_of(ctx, None) is None + finally: + places_service._CURRENT = service + + def test_a_typed_place_wins_and_an_empty_place_is_none(tmp_path: Path) -> None: """A typed place wins over a found place, and an empty found place is none.""" service, repo = _service(tmp_path) diff --git a/tests/test_preferences.py b/tests/test_preferences.py index 454912a..3b03833 100644 --- a/tests/test_preferences.py +++ b/tests/test_preferences.py @@ -346,6 +346,33 @@ def test_a_staged_change_shows_its_arrow_and_the_save_action() -> None: assert any("βœ— Back β€” discard staged changes" in row for row in rows) +def test_a_filter_narrows_the_settings_and_keeps_the_apply_and_back_rows() -> None: + """A typed filter hides the settings that do not match. The exit pair stays. + + Apply has no keyboard key of its own. Thus a filter that hid it left no way to commit + the staged changes. The filter searches the content of the page, and an action is not + content. + """ + from meshterm.ui.tui import SelectScreen + + title, items = _menu_items(Preferences(), {"history_days": 90}) + screen = SelectScreen(title, items) + screen.note_viewport(len(items) + 4) + for ch in "zzzz": # a query that no setting matches + screen.handle("text", ch) + rows = [line.strip() for line in _plain(screen.render_body(_WIDE)).splitlines()] + assert not any("Map tiles" in row for row in rows) + assert any("βœ“ Apply 1 staged change" in row for row in rows) + assert any("βœ— Back β€” discard staged changes" in row for row in rows) + # They are still rows that the highlight can reach, and not only drawn lines. The reset + # row is an action of the page too, so the filter keeps it with them. + assert [choice.value for choice in screen._choices()] == [ + "__reset__", + "__apply__", + "__cancel__", + ] + + def test_a_long_value_is_capped_so_the_descriptions_keep_their_lane() -> None: """The page makes the basemap URL shorter in the lane. diff --git a/tests/test_radionode.py b/tests/test_radionode.py index 1c1f6ce..b4316c9 100644 --- a/tests/test_radionode.py +++ b/tests/test_radionode.py @@ -16,6 +16,7 @@ import ast import asyncio import dataclasses import json +import logging import os import sys from pathlib import Path @@ -165,7 +166,7 @@ def test_a_failed_expander_puts_the_switches_back( monkeypatch.setattr(radionode, "LEDS", tmp_path) monkeypatch.setattr(radionode, "POWER_SETTLE_S", 0) - def absent(*_args: object) -> None: + def absent(*_args: object, **_kwargs: object) -> None: raise radionode.NodeError("absent", "nothing answers at 0x43 on /dev/i2c-1") monkeypatch.setattr(radionode, "drive_pi4io", absent) @@ -176,6 +177,126 @@ def test_a_failed_expander_puts_the_switches_back( assert power.read_text() == "0" +def test_a_board_whose_expander_is_optional_starts_without_one( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The Cap LoRa868 is the Cap LoRa-1262 with no antenna switch. It keeps the power on.""" + power = _switch(tmp_path, "ext_5v_out", "0") + monkeypatch.setattr(radionode, "LEDS", tmp_path) + monkeypatch.setattr(radionode, "POWER_SETTLE_S", 0) + asked: dict[str, object] = {} + + def nothing_there(*args: object, required: bool = True) -> bool: + asked["required"] = required + return False + + monkeypatch.setattr(radionode, "drive_pi4io", nothing_there) + wiring = { + "leds": ["ext_5v_out=1"], + "pi4io_bus": 1, + "pi4io_high": [0], + "pi4io_required": False, + } + board = radionode.prepare_board(wiring) + assert asked["required"] is False, "the wiring decides, not the function" + assert board.expander is False, "the node knows that it is the board with no expander" + assert power.read_text() == "1", "the header keeps its power, because the radio is there" + radionode.restore_leds(board.switches) + assert power.read_text() == "0" + + +def test_a_broken_bus_is_not_an_absent_board(monkeypatch: pytest.MonkeyPatch) -> None: + """Only "nobody answered" is an absent board. Each other error of the bus is a failure.""" + real_write = os.write + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + raise OSError(5, "Input/output error") + + monkeypatch.setattr(os, "write", write) + with pytest.raises(radionode.NodeError) as err: + radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) + assert err.value.kind == "failed", "a broken bus must never read as a board that is not there" + + +class _VersionChip: + """A started radio that answers a register read with ``answer``.""" + + def __init__(self, answer: bytes) -> None: + self.answer = answer + + def readRegister(self, address: int, count: int) -> tuple[int, ...]: # noqa: N802 + """The spelling of the radio library. It returns the bytes at ``address``.""" + assert (address, count) == (0x0320, 16) + return tuple(self.answer.ljust(count, bytes(1))[:count]) + + +def test_the_chip_says_that_it_is_an_sx126x() -> None: + """A board with no expander is accepted only after the chip answers with its own name.""" + radionode.confirm_sx126x(_VersionChip(b"SX1262 V2D")) + + +@pytest.mark.parametrize( + "answer", [bytes(16), bytes([0xFF] * 16), b"NOTARADIO"], ids=["zeros", "ones", "other"] +) +def test_a_bus_with_nothing_on_it_is_not_a_board(answer: bytes) -> None: + """An empty bus reads as all ones or all zeros. The library can start on it.""" + with pytest.raises(radionode.NodeError) as err: + radionode.confirm_sx126x(_VersionChip(answer)) + assert err.value.kind == "absent" + + +@pytest.mark.parametrize( + ("expander", "kind", "expected"), + [ + (False, "failed", "absent"), + (False, "busy", "busy"), + (True, "failed", "failed"), + (None, "failed", "failed"), + ], + ids=["no-expander", "busy-line", "with-expander", "no-expander-in-wiring"], +) +def test_a_radio_that_does_not_start_says_the_useful_thing( + expander: bool | None, kind: str, expected: str +) -> None: + """On a board where nothing answered at all, the user must read that nothing is there.""" + error = radionode.begin_failure(kind, "Something went wrong, check your wiring!", expander) + assert error.kind == expected + if expected == "absent": + assert str(error) == radionode.NO_RADIO, "one sentence for a radio that is not there" + + +@pytest.mark.parametrize( + ("expander", "expected"), + [(True, "Cap LoRa-1262"), (False, "Cap LoRa868"), (None, "Cap LoRa-1262")], + ids=["found", "absent", "no-expander-in-wiring"], +) +def test_the_node_reports_the_revision_that_it_found(expander: bool | None, expected: str) -> None: + """The parent sends both names, because only the node can see which board answered.""" + config = {"model": "Cap LoRa-1262", "model_without_expander": "Cap LoRa868"} + assert radionode.board_model(config, expander) == expected + + +def test_a_board_with_one_revision_keeps_its_one_model() -> None: + """The AIO has no second name, and a board MeshTerm does not know has none at all.""" + assert radionode.board_model({"model": "uConsole AIO"}, False) == "uConsole AIO" + assert radionode.board_model({}, False) == radionode.DEVICE_MODEL + + +def test_a_chip_that_cannot_be_read_is_not_a_board() -> None: + """A read that fails is the same answer as a read of nothing: no board is attached.""" + + class _Dead: + def readRegister(self, address: int, count: int) -> tuple[int, ...]: # noqa: N802 + """Fail as a chip that is not there fails.""" + raise OSError(5, "Input/output error") + + with pytest.raises(radionode.NodeError) as err: + radionode.confirm_sx126x(_Dead()) + assert err.value.kind == "absent" + + def test_an_expander_on_a_missing_bus_is_named(tmp_path: Path) -> None: """A missing ``/dev/i2c-N`` is its own kind, and the parent knows the correction for it.""" with pytest.raises(radionode.NodeError) as err: @@ -183,9 +304,63 @@ def test_an_expander_on_a_missing_bus_is_named(tmp_path: Path) -> None: assert err.value.kind == "no-i2c" +#: A number that stands for the open I2C bus in the two tests below. The tests put their +#: own ``os.write`` and ``os.read`` in front of the real ones, and those answer for this +#: number alone. Each other file in the process, the capture of pytest included, goes +#: through to the real function. +_BUS_FD = 9001 + + +def test_a_slow_expander_gets_more_than_one_try(monkeypatch: pytest.MonkeyPatch) -> None: + """A board whose power rail is slow answers a later read, and is attached after all.""" + real_write, real_read = os.write, os.read + tries: list[bytes] = [] + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + tries.append(data) + return len(data) + + def read(fd: int, count: int) -> bytes: + if fd != _BUS_FD: + return real_read(fd, count) + if len(tries) < 3: + raise OSError(121, "Remote I/O error") + return bytes([0xA2]) + + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(os, "read", read) + monkeypatch.setattr(radionode, "PI4IO_RETRY_S", 0) + assert radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) == 0xA2 + assert len(tries) == 3, "it read the ID register again until the board answered" + + +def test_an_expander_that_never_answers_is_absent_and_the_log_says_why( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The user reads that nothing is there. Only the log says what the bus answered.""" + real_write = os.write + + def write(fd: int, data: bytes) -> int: + if fd != _BUS_FD: + return real_write(fd, data) + raise OSError(121, "Remote I/O error") + + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(radionode, "PI4IO_WAIT_S", 0) + with caplog.at_level(logging.WARNING, logger="radionode"): + with pytest.raises(radionode.NodeError) as err: + radionode._expander_id(_BUS_FD, 0x43, Path("/dev/i2c-1")) + assert err.value.kind == "absent" + assert "nothing answers at 0x43" in str(err.value), "the sentence of the user is unchanged" + assert "Remote I/O error" in caplog.text, "the log keeps the error of the bus" + + def test_a_board_with_no_switches_prepares_nothing() -> None: """The wiring of the AIO has neither, and its node starts the same as it always did.""" - assert radionode.prepare_board({"bus_id": 1, "pi4io_bus": -1}) == [] + board = radionode.prepare_board({"bus_id": 1, "pi4io_bus": -1}) + assert (board.switches, board.expander) == ([], None) def test_an_identity_is_minted_once_and_then_kept(tmp_path: Path) -> None: diff --git a/tests/test_slider.py b/tests/test_slider.py new file mode 100644 index 0000000..cb6977f --- /dev/null +++ b/tests/test_slider.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The horizontal slider: steps of one, clamped ends, a call at each step, Enter and Esc.""" + +from __future__ import annotations + +import asyncio +import re + +from rich.cells import cell_len + +from meshterm.ui.slider import SliderScreen +from meshterm.ui.tui.screen import CANCEL + + +def strip_ansi(text: str) -> str: + """The text of a rendered line, without its SGR codes.""" + return re.sub(r"\x1b\[[0-9;]*m", "", text) + + +def _slider(value: int = 7) -> tuple[SliderScreen, list[int]]: + changes: list[int] = [] + return SliderScreen("Volume", "How loud", value, 1, 10, on_change=changes.append), changes + + +def test_the_arrows_move_one_step_and_call_on_change() -> None: + """β†’ adds one, ← removes one, and each step calls ``on_change`` with the new value.""" + slider, changes = _slider() + slider.handle("right") + slider.handle("left") + slider.handle("left") + assert slider.value == 6 + assert changes == [8, 7, 6] + + +def test_the_ends_clamp_and_a_step_at_an_end_calls_nothing() -> None: + """Nothing rolls over, and a key that changes nothing plays no preview.""" + slider, changes = _slider(10) + slider.handle("right") + assert slider.value == 10 and changes == [] + slider.handle("home") + assert slider.value == 1 and changes == [1] + slider.handle("left") + assert changes == [1] + slider.handle("end") + assert slider.value == 10 + + +def test_enter_sets_and_esc_keeps() -> None: + """Enter resolves with the value, and Esc resolves with ``CANCEL``.""" + loop = asyncio.new_event_loop() + try: + slider, _ = _slider() + slider.future = loop.create_future() + slider.handle("right") + slider.handle("enter") + assert slider.future.result() == 8 + slider, _ = _slider() + slider.future = loop.create_future() + slider.handle("escape") + assert slider.future.result() is CANCEL + finally: + loop.close() + + +def test_a_start_value_out_of_range_is_clamped() -> None: + """A value from a file that was edited by hand comes into the range.""" + assert _slider(42)[0].value == 10 + assert _slider(-3)[0].value == 1 + + +def test_the_bar_fills_the_line_on_both_widths() -> None: + """The bar and its value fill each line exactly, at 72 and at 53 columns.""" + for width in (40, 49): + lines = _slider()[0].render_body(width) + assert all(cell_len(strip_ansi(line)) <= width for line in lines) + assert strip_ansi(lines[-1]).rstrip().endswith(" 7") + + +def test_the_handheld_lane_dims_a_step_past_an_end() -> None: + """``More`` is dim at the top, and ``Less`` at the bottom.""" + top = _slider(10)[0].picocalc_lyra_lane + assert top[0].enabled is False and top[1].enabled is True + bottom = _slider(1)[0].picocalc_lyra_lane + assert bottom[0].enabled is True and bottom[1].enabled is False diff --git a/tests/test_sound.py b/tests/test_sound.py new file mode 100644 index 0000000..5e0301c --- /dev/null +++ b/tests/test_sound.py @@ -0,0 +1,378 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The sound service: the themes, the volume, the tick limit, the flash, and failures.""" + +from __future__ import annotations + +import asyncio +import time +import wave +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from meshterm.core.preferences import Preferences +from meshterm.platforms import PICOCALC_LYRA, REGULAR, get_platform, set_platform +from meshterm.services import sound +from meshterm.services.sound import SOUNDS_DIR, THEMES, SoundEvent, SoundService + + +class FakePlayer: + """Records each file that it plays, and can act as a failed player.""" + + def __init__(self, works: bool = True) -> None: + """Make a player that works, or one that fails.""" + self.played: list[Path] = [] + self.works = works + + def play(self, path: Path) -> bool: + """Record the file, and say if the sound started.""" + self.played.append(path) + return self.works + + +class Clock: + """A clock that the test moves.""" + + def __init__(self) -> None: + """Start at a fixed time.""" + self.now = 100.0 + + def __call__(self) -> float: + """The time now.""" + return self.now + + +def _service(tmp_path: Path, works: bool = True, **prefs: object): + ctx = SimpleNamespace( + preferences=Preferences(values=prefs), + settings=SimpleNamespace(config_dir=tmp_path), + ) + player, clock = FakePlayer(works), Clock() + service = SoundService(ctx, player=player, clock=clock) # type: ignore[arg-type] + flashes: list[int] = [] + bells: list[int] = [] + service.set_hooks(bell=lambda: bells.append(1), flash=lambda: flashes.append(1)) + return service, player, clock, flashes, bells + + +@pytest.fixture(autouse=True) +def _regular(): + previous = get_platform() + set_platform(REGULAR) + yield + set_platform(previous) + + +def test_each_theme_file_exists_and_is_16_bit_pcm() -> None: + """Each file that a theme names is in the package, and the volume code can read it.""" + for files in THEMES.values(): + assert set(files) == set(SoundEvent) + for name in files.values(): + with wave.open(str(SOUNDS_DIR / name), "rb") as reader: + assert reader.getsampwidth() == 2 + + +def test_sounds_play_by_default(tmp_path: Path) -> None: + """The default is the Android theme, not muted (JP, 2026-11-20).""" + service, player, _, flashes, _ = _service(tmp_path) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is True + assert len(player.played) == 1 + assert flashes == [] + + +def test_a_muted_service_is_silent_and_flashes(tmp_path: Path) -> None: + """A mute plays nothing, and the default flash replaces the sound.""" + service, player, _, flashes, _ = _service(tmp_path, sound_muted=True) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is False + assert player.played == [] + assert flashes == [1] + + +def test_an_event_plays_its_file_of_the_theme(tmp_path: Path) -> None: + """An event plays its own file of the theme, and the flash stays off.""" + service, player, _, flashes, _ = _service( + tmp_path, + ) + assert service.notify(SoundEvent.MENTION) is True + assert player.played[0].name.startswith("android-Ariel-") + assert flashes == [] # when silent: a sound played, so no flash + + +def test_the_volume_scales_a_cached_copy(tmp_path: Path) -> None: + """A volume below 100 plays a scaled copy from the cache: 50% is a quarter.""" + service, player, _, _, _ = _service(tmp_path, sound_volume=5) + service.notify(SoundEvent.DIRECT_MESSAGE) + copy = player.played[0] + assert copy.parent == tmp_path / "sound-cache" + with wave.open(str(SOUNDS_DIR / "android/Carme.wav"), "rb") as full: + loud = max( + abs(int.from_bytes(full.readframes(4000)[i : i + 2], "little", signed=True)) + for i in range(0, 8000, 2) + ) + with wave.open(str(copy), "rb") as quiet: + soft = max( + abs(int.from_bytes(quiet.readframes(4000)[i : i + 2], "little", signed=True)) + for i in range(0, 8000, 2) + ) + assert soft == pytest.approx(loud * 0.25, abs=2) + + +def test_full_volume_plays_the_file_of_the_package(tmp_path: Path) -> None: + """At 100%, the service plays the file of the package, with no copy.""" + service, player, _, _, _ = _service(tmp_path, sound_volume=10) + service.notify(SoundEvent.ROOM_POST) + assert player.played == [SOUNDS_DIR / "android/Ceres.wav"] + + +def test_the_gain_follows_the_square_of_the_volume() -> None: + """The gain is the square of the volume fraction.""" + assert sound.gain(100) == 1.0 + assert sound.gain(50) == 0.25 + assert sound.gain(0) == 0.0 + + +def test_the_bell_theme_rings_the_bell(tmp_path: Path) -> None: + """The bell theme rings the terminal bell and plays no file.""" + service, player, _, _, bells = _service(tmp_path, sound_theme="bell") + assert service.notify(SoundEvent.CHANNEL_MESSAGE) is True + assert bells == [1] + assert player.played == [] + + +def test_the_none_theme_is_silent_and_flashes(tmp_path: Path) -> None: + """The none theme plays nothing, so the default flash shows the event.""" + service, player, _, flashes, _ = _service(tmp_path, sound_theme="none") + assert service.notify(SoundEvent.DIRECT_MESSAGE) is False + assert player.played == [] + assert flashes == [1] + + +def test_the_tick_is_off_by_default(tmp_path: Path) -> None: + """The packet tick is off until the user turns it on.""" + service, player, _, flashes, _ = _service( + tmp_path, + ) + assert service.notify(SoundEvent.PACKET_TICK) is False + assert player.played == [] + assert flashes == [] # a tick never flashes + + +def test_the_tick_plays_at_most_one_each_quarter_second(tmp_path: Path) -> None: + """The tick plays at most one time each 250 ms.""" + service, player, clock, _, _ = _service(tmp_path, packet_tick=True) + assert service.notify(SoundEvent.PACKET_TICK) is True + clock.now += 0.1 + assert service.notify(SoundEvent.PACKET_TICK) is False + clock.now += 0.2 + assert service.notify(SoundEvent.PACKET_TICK) is True + assert len(player.played) == 2 + + +def test_no_tick_right_after_another_sound(tmp_path: Path) -> None: + """A tick does not play over the start of another sound.""" + service, player, clock, _, _ = _service(tmp_path, packet_tick=True) + service.notify(SoundEvent.DIRECT_MESSAGE) + clock.now += 0.1 + assert service.notify(SoundEvent.PACKET_TICK) is False + assert len(player.played) == 1 + + +def test_a_failed_player_counts_as_silent(tmp_path: Path) -> None: + """A player that fails counts as silent, so the flash shows the event.""" + service, _, _, flashes, _ = _service( + tmp_path, + works=False, + ) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is False + assert flashes == [1] + + +@pytest.mark.parametrize( + ("mode", "muted", "flashes"), + [ + ("off", True, 0), + ("off", False, 0), + ("on", True, 1), + ("on", False, 1), + ("silent", True, 1), + ("silent", False, 0), + ], +) +def test_the_flash_modes(tmp_path: Path, mode: str, muted: bool, flashes: int) -> None: + """The flash follows its preference: off, on, or only when no sound plays.""" + service, _, _, flashed, _ = _service(tmp_path, sound_muted=muted, notify_flash=mode) + service.notify(SoundEvent.DIRECT_MESSAGE) + assert len(flashed) == flashes + + +def test_the_picocalc_is_silent_and_flashes(tmp_path: Path) -> None: + """The PicoCalc plays no sound, also for a preview, and it flashes.""" + set_platform(PICOCALC_LYRA) + service, player, _, flashes, _ = _service( + tmp_path, + ) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is False + assert service.preview() is False + assert player.played == [] + assert flashes == [1] + + +def test_the_preview_plays_also_when_muted(tmp_path: Path) -> None: + """The preview plays the channel message sound also when the sounds are muted.""" + service, player, _, flashes, _ = _service(tmp_path, sound_muted=True) + assert service.preview() is True + assert player.played[0].name.startswith("android-InCallNotification-") + assert flashes == [] + + +def test_toggle_changes_and_saves_the_preference(tmp_path: Path) -> None: + """The toggle changes the preference and saves it to the file.""" + prefs = Preferences(path=tmp_path / "preferences.toml") + ctx = SimpleNamespace(preferences=prefs, settings=SimpleNamespace(config_dir=tmp_path)) + service = SoundService(ctx, player=FakePlayer()) # type: ignore[arg-type] + assert service.toggle() is False # muted + assert Preferences.load(tmp_path / "preferences.toml").sound_muted is True + assert service.toggle() is True # on again + assert Preferences.load(tmp_path / "preferences.toml").sound_muted is False + + +def test_the_battery_sound_plays_once_below_the_threshold(tmp_path: Path) -> None: + """The sound plays when the level goes below 25%, and not again at the next reading.""" + service, player, _, _, _ = _service(tmp_path) + service.note_battery(30, charging=False) + assert player.played == [] + service.note_battery(24, charging=False) + service.note_battery(23, charging=False) + assert [p.name.split("-")[1] for p in player.played] == ["LowBattery"] + + +def test_the_battery_sound_rearms_above_the_margin_or_on_charge(tmp_path: Path) -> None: + """A level near the threshold does not rearm it. Five points above, or a charge, does.""" + service, player, _, _, _ = _service(tmp_path) + service.note_battery(20, charging=False) + service.note_battery(27, charging=False) # not 5 points above 25: still played once + service.note_battery(20, charging=False) + assert len(player.played) == 1 + service.note_battery(30, charging=False) + service.note_battery(20, charging=False) + assert len(player.played) == 2 + service.note_battery(20, charging=True) + service.note_battery(19, charging=False) + assert len(player.played) == 3 + + +def test_a_packet_heard_ticks_after_a_short_wait(tmp_path: Path) -> None: + """With the tick on, a packet heard plays the tick after TICK_DELAY_S.""" + + async def run() -> list[Path]: + service, player, _, _, _ = _service(tmp_path, packet_tick=True) + service._clock = time.monotonic + service._on_packet(None) # type: ignore[arg-type] + service._on_packet(None) # type: ignore[arg-type] - one tick is already waiting + await asyncio.sleep(sound.TICK_DELAY_S + 0.1) + return player.played + + played = asyncio.run(run()) + assert [p.name.split("-")[1] for p in played] == ["Effect_Tick"] + + +def test_a_message_sound_in_the_wait_cancels_the_tick(tmp_path: Path) -> None: + """The packet of a message ticks no tick when the message plays its own sound.""" + + async def run() -> list[Path]: + service, player, _, _, _ = _service(tmp_path, packet_tick=True) + service._clock = time.monotonic + service._on_packet(None) # type: ignore[arg-type] + service.notify(SoundEvent.DIRECT_MESSAGE) + await asyncio.sleep(sound.TICK_DELAY_S + 0.1) + return player.played + + played = asyncio.run(run()) + assert [p.name.split("-")[1] for p in played] == ["Carme"] + + +def test_no_tick_is_scheduled_when_the_tick_is_off(tmp_path: Path) -> None: + """With the tick off (the default), a packet heard schedules nothing.""" + + async def run() -> bool: + service, _, _, _, _ = _service(tmp_path) + service._on_packet(None) # type: ignore[arg-type] + return service._tick_pending + + assert asyncio.run(run()) is False + + +def test_each_event_has_a_switch_on_by_default_except_the_tick() -> None: + """Each event names a preference, on by default except the tick. A mention has a rule.""" + from meshterm.core.preferences import get_spec + from meshterm.services.sound import EVENT_PREFERENCE + + assert set(EVENT_PREFERENCE) == set(SoundEvent) - {SoundEvent.MENTION} + assert get_spec("sound_mention").default == "always" + for event, key in EVENT_PREFERENCE.items(): + assert get_spec(key).default is (event is not SoundEvent.PACKET_TICK) + + +def test_a_switched_off_event_plays_nothing_and_does_not_flash(tmp_path: Path) -> None: + """An event that its switch turns off does nothing at all.""" + service, player, _, flashes, _ = _service(tmp_path, sound_dm=False) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is False + assert player.played == [] and flashes == [] + assert service.notify(SoundEvent.ROOM_POST) is True + + +def test_the_battery_switch_silences_the_battery_sound(tmp_path: Path) -> None: + """With ``sound_battery`` off, a low battery plays nothing.""" + service, player, _, _, _ = _service(tmp_path, sound_battery=False) + service.note_battery(10, charging=False) + assert player.played == [] + + +def test_a_mention_as_a_message_turns_the_mention_event_off(tmp_path: Path) -> None: + """With the ``regular`` rule, the mention event plays nothing of its own.""" + service, player, _, _, _ = _service(tmp_path, sound_mention="regular") + assert service.notify(SoundEvent.MENTION) is False + assert player.played == [] + + +def test_a_room_catch_up_lasts_until_a_pause() -> None: + """After a login, posts are part of the catch-up until the room pauses 8 s.""" + from meshterm.services.rooms import CATCH_UP_QUIET_S, RoomService + + rooms = RoomService(SimpleNamespace()) # type: ignore[arg-type] + assert rooms.catching_up("a1b2c3d4e5f6", now=10.0) is False # no login yet + rooms._catching_up["a1b2c3d4e5f6"] = 100.0 # the login + assert rooms.catching_up("A1B2C3D4", now=103.0) is True # a shorter prefix matches + assert rooms.catching_up("a1b2c3d4e5f6", now=103.0 + CATCH_UP_QUIET_S - 1) is True + assert rooms.catching_up("a1b2c3d4e5f6", now=200.0) is False # the pause ended it + assert rooms.catching_up("a1b2c3d4e5f6", now=201.0) is False + + +def test_mci_opens_a_device_for_each_sound_and_closes_the_stopped_ones() -> None: + """Each sound gets its own device, so a new sound never stops one that plays.""" + from meshterm.services.sound import _Mci + + sent: list[str] = [] + playing: set[str] = set() + + def send(command: str) -> str: + sent.append(command) + verb, alias = command.split()[0], command.split()[-1] + if verb == "play": + playing.add(alias) + if verb == "status": + return "playing" if command.split()[1] in playing else "stopped" + return "" + + mci = _Mci.__new__(_Mci) + mci._count, mci._open = 0, [] + mci._send = send # type: ignore[method-assign] + mci.play(Path("a.wav")) + mci.play(Path("b.wav")) + assert mci._open == ["meshterm1", "meshterm2"] # both play at the same time + assert not any(c.startswith("stop") for c in sent) + playing.discard("meshterm1") # the first sound ended + mci.play(Path("c.wav")) + assert mci._open == ["meshterm2", "meshterm3"] + assert "close meshterm1" in sent diff --git a/tests/test_sound_controls.py b/tests/test_sound_controls.py new file mode 100644 index 0000000..e5007e4 --- /dev/null +++ b/tests/test_sound_controls.py @@ -0,0 +1,152 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The controls of the sounds: the πŸ”Š/πŸ”‡ header badge, the Sound row, and ^S.""" + +from __future__ import annotations + +import re +from collections.abc import Iterator +from types import SimpleNamespace + +import pytest + +from meshterm.platforms import CARDPUTER_ZERO, REGULAR, set_platform +from meshterm.tools import all_tools, load_all_tools +from meshterm.ui import menu +from meshterm.ui.tui import Choice +from meshterm.ui.tui.session import _CTRL_LETTER_CHORDS + + +class FakeSound: + """The parts of the sound service that the controls read.""" + + def __init__(self, available: bool = True, enabled: bool = False, theme: str = "android"): + """Make a service in a fixed state.""" + self.available = available + self.enabled = enabled + self.audible_theme = theme != "none" + self.previews = 0 + + def toggle(self) -> bool: + """Turn the sounds on or off.""" + self.enabled = not self.enabled + return self.enabled + + def preview(self) -> bool: + """Count the previews.""" + self.previews += 1 + return True + + +@pytest.fixture +def regular() -> Iterator[None]: + """Run on the regular platform.""" + set_platform(REGULAR) + yield + set_platform(REGULAR) + + +def test_the_badge_shows_the_state_of_the_sounds(regular: None) -> None: + """πŸ”Š while the sounds are on, πŸ”‡ while they are off.""" + ctx = SimpleNamespace(sound=FakeSound(enabled=True)) + assert menu._sound_badge(ctx).plain == "πŸ”Š" + ctx.sound.enabled = False + assert menu._sound_badge(ctx).plain == "πŸ”‡" + + +def test_no_badge_where_no_sound_can_play(regular: None) -> None: + """No speaker with the ``none`` theme, nor on a platform with no sound.""" + assert menu._sound_badge(SimpleNamespace(sound=FakeSound(theme="none"))).plain == "" + assert menu._sound_badge(SimpleNamespace(sound=FakeSound(available=False))).plain == "" + + +def test_the_cardputer_badge_is_one_glyph_of_its_font() -> None: + """The Cardputer draws no emoji, so the badge is the compact glyph.""" + set_platform(CARDPUTER_ZERO) + try: + ctx = SimpleNamespace(sound=FakeSound(enabled=True)) + assert menu._sound_badge(ctx).plain == "β—„" + ctx.sound.enabled = False + assert menu._sound_badge(ctx).plain == "⌫" + finally: + set_platform(REGULAR) + + +def _sound_row(sound: FakeSound | None) -> Choice | None: + load_all_tools() + tools = [tool for tool in all_tools() if tool.menu_visible] + rows = [r for r in menu._menu_items(tools, sound) if isinstance(r, Choice)] + return next((r for r in rows if r.value == menu._SOUND_VALUE), None) + + +def test_the_menu_row_names_the_state_now(regular: None) -> None: + """The row says the state of the sounds at each paint.""" + sound = FakeSound() + row = _sound_row(sound) + assert row is not None + assert "Sound muted" in row.title().plain + sound.enabled = True + assert "Sound on" in row.title().plain + sound.audible_theme = False + title = row.title().plain + assert "No sound" in title and "πŸ”Š" not in title and "πŸ”‡" not in title + + +def test_no_menu_row_where_no_sound_can_play(regular: None) -> None: + """The PicoCalc, or no service at all, has no Sounds row.""" + assert _sound_row(FakeSound(available=False)) is None + assert _sound_row(None) is None + + +def test_the_toggle_plays_the_preview_only_when_the_sounds_come_on() -> None: + """Unmute: the channel message sound plays one time. Mute: nothing plays.""" + ctx = SimpleNamespace(sound=FakeSound()) + menu._toggle_sound(ctx) + assert ctx.sound.enabled and ctx.sound.previews == 1 + menu._toggle_sound(ctx) + assert not ctx.sound.enabled and ctx.sound.previews == 1 + + +def test_the_toggle_does_nothing_with_the_no_sound_theme() -> None: + """With the ``none`` theme there is nothing to mute.""" + ctx = SimpleNamespace(sound=FakeSound(theme="none")) + menu._toggle_sound(ctx) + assert not ctx.sound.enabled and ctx.sound.previews == 0 + + +def test_ctrl_s_is_the_sound_chord_and_ctrl_e_reveals() -> None: + """^S turns the sounds on or off, and ^E shows a concealed value (JP, 2026-11-20).""" + assert _CTRL_LETTER_CHORDS["s"] == "sound" + assert _CTRL_LETTER_CHORDS["e"] == "reveal" + + +def test_the_title_flashes_in_reverse_video_for_a_short_time() -> None: + """The flash draws the title in reverse video, and the title comes back after FLASH_S.""" + from meshterm.ui.tui import frame + + frame.flash_title(now=100.0) + assert frame.flashing(now=100.1) + assert not frame.flashing(now=100.0 + frame.FLASH_S + 0.01) + frame.flash_title(now=0.0) # long ago: the next test sees no flash + assert frame._title_markup("Nodes", "title.border") == "[title.border]Nodes[/]" + + +def test_the_flash_reaches_the_drawn_title(regular: None) -> None: + """While the flash lasts, the composed frame carries the reverse attribute (SGR 7).""" + import time + + from rich.text import Text + + from meshterm.ui.tui import frame + from meshterm.ui.tui.screen import ScrollScreen + + screen = ScrollScreen(Text("body"), title="Nodes", floating=False) + plain = frame.compose_base(Text(""), screen, screen.footer_hint, 72, 24) + frame.flash_title(now=time.monotonic()) + try: + lit = frame.compose_base(Text(""), screen, screen.footer_hint, 72, 24) + finally: + frame.flash_title(now=0.0) + first = lit.split("\n")[0] + codes = [c.split(";") for c in re.findall(r"\x1b\[([0-9;]*)m", first)] + assert any("7" in c for c in codes) + assert plain.split("\n")[0] != first diff --git a/tests/test_spiradio.py b/tests/test_spiradio.py index a86018b..1bd6e2e 100644 --- a/tests/test_spiradio.py +++ b/tests/test_spiradio.py @@ -263,7 +263,13 @@ def cardputer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: "BUILTIN_RADIOS", ( spiradio.BuiltinRadio("", SpiWiring()), - spiradio.BuiltinRadio("Cap LoRa-1262", spiradio.CARDPUTER_ZERO_CAP, marker=str(marker)), + spiradio.BuiltinRadio( + "Cap LoRa", + spiradio.CARDPUTER_ZERO_CAP, + marker=str(marker), + with_expander="Cap LoRa-1262", + without_expander="Cap LoRa868", + ), ), ) return marker @@ -272,7 +278,7 @@ def cardputer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: def test_the_cardputer_cap_is_listed_with_no_profile(cardputer: Path) -> None: """On a Cardputer Zero, the Cap is a radio like the AIO: it is present, named, and wired.""" radios = spiradio.spi_radios({}) - assert [(d.port, d.name) for d in radios] == [("/dev/spidev0.1", "Cap LoRa-1262")] + assert [(d.port, d.name) for d in radios] == [("/dev/spidev0.1", "Cap LoRa")] assert radios[0].spi == spiradio.CARDPUTER_ZERO_CAP @@ -283,14 +289,26 @@ def test_a_bare_spidev_node_is_not_a_cardputer(cardputer: Path) -> None: assert spiradio.builtin_wiring("/dev/spidev0.1") is None -def test_the_cap_reports_itself_by_name(cardputer: Path) -> None: - """The model of the node is the name of the board: the Cap, also under a changed profile.""" - assert spiradio.board_name(spiradio.CARDPUTER_ZERO_CAP) == "Cap LoRa-1262" +def test_the_node_is_given_the_model_of_each_revision(cardputer: Path) -> None: + """The node sees which Cap is attached. Thus the parent sends it both names.""" + assert spiradio.board_models(spiradio.CARDPUTER_ZERO_CAP) == ("Cap LoRa-1262", "Cap LoRa868") tweaked = replace(spiradio.CARDPUTER_ZERO_CAP, use_dio3_tcxo=False) - assert spiradio.board_name(tweaked) == "Cap LoRa-1262" - assert spiradio.board_name(SpiWiring()) == "" # the node of the AIO: no board name to give + assert spiradio.board_models(tweaked) == ("Cap LoRa-1262", "Cap LoRa868"), "a profile of it" + assert spiradio.board_models(SpiWiring()) == ("", "") # the AIO: no name to give + blind = replace(spiradio.CARDPUTER_ZERO_CAP, pi4io_bus=-1) + assert spiradio.board_models(blind) == ("Cap LoRa", ""), "a wiring that never looks cannot say" cardputer.rmdir() - assert spiradio.board_name(spiradio.CARDPUTER_ZERO_CAP) == "" # another Pi + assert spiradio.board_models(spiradio.CARDPUTER_ZERO_CAP) == ("", "") # another Pi + + +def test_the_shipped_table_knows_both_revisions_of_the_cap() -> None: + """The fixture above copies the table. This keeps the table itself from drifting.""" + cap = next(r for r in spiradio.BUILTIN_RADIOS if r.wiring is spiradio.CARDPUTER_ZERO_CAP) + assert (cap.name, cap.with_expander, cap.without_expander) == ( + "Cap LoRa", + "Cap LoRa-1262", + "Cap LoRa868", + ) #: Each mark of a uConsole, as the CM5 uConsole of JP showed them. @@ -324,7 +342,7 @@ def test_the_aio_is_named_on_a_uconsole(uconsole: set) -> None: """When each mark of a uConsole is present, the AIO is the uConsole AIO.""" radios = spiradio.spi_radios({}) assert [(d.port, d.name) for d in radios] == [("/dev/spidev1.0", "uConsole AIO")] - assert spiradio.board_name(SpiWiring()) == "uConsole AIO" + assert spiradio.board_models(SpiWiring()) == ("uConsole AIO", "") @pytest.mark.parametrize("missing", _UCONSOLE_MARKS, ids=str) @@ -333,14 +351,14 @@ def test_one_missing_mark_is_enough_to_doubt_it(uconsole: set, missing: object) uconsole.discard(missing) radios = spiradio.spi_radios({}) assert [(d.port, d.name) for d in radios] == [("/dev/spidev1.0", None)] - assert spiradio.board_name(SpiWiring()) == "" + assert spiradio.board_models(SpiWiring()) == ("", "") def test_the_keyboard_s_names_are_part_of_its_mark(uconsole: set) -> None: """1eaf:0024 is any LeafLabs Maple. Only the uConsole keyboard of ClockworkPi counts.""" uconsole.discard(spiradio.UCONSOLE_KEYBOARD) uconsole.add(("1eaf", "0024", "LeafLabs", "Maple")) - assert spiradio.board_name(SpiWiring()) == "" + assert spiradio.board_models(SpiWiring()) == ("", "") def test_usb_devices_are_read_from_sysfs(tmp_path: Path) -> None: diff --git a/tests/test_vt_console_font.py b/tests/test_vt_console_font.py index beefcad..f69407c 100644 --- a/tests/test_vt_console_font.py +++ b/tests/test_vt_console_font.py @@ -267,8 +267,14 @@ def test_the_preference_is_offered_on_the_handheld_only() -> None: spec = get_spec("console_font") assert spec.offered_on("picocalc-lyra") is True assert spec.offered_on("regular") is False - # All other preferences are offered on all platforms. The gate is the exception. - gated = {s.key for _, specs in by_group() for s in specs if s.platforms is not None} + # The other gated preferences are the sound preferences, which the PicoCalc does not + # offer because it has no sound. All other preferences are offered on all platforms. + gated = { + s.key + for group, specs in by_group() + for s in specs + if s.platforms is not None and group != "Sound" + } assert gated == {"console_font"}