Author SHA1 Message Date
Richard OberholtzerandClaude Opus 5.5 b983f36ceb Merge upstream MeshTerm 1.0.0
Conflicts resolved by keeping both sides:
  docs/cli/README.md, docs/guide/features.md (parts/reactions + relay mark)
  meshterm/core/preferences.py (reaction_emoji, message_parts_max + heard_wait_s)
  meshterm/services/chat_service.py (reaction check + upstream mute/listed split)
  meshterm/ui/chat.py (reaction count + relay mark in the render cache;
    each sent part is tracked for the relay mark)
  meshterm/ui/tui/session.py: upstream's "e": "reveal" is kept, and the
    chat screen takes "reveal" as react, so ^E still reacts in the chat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0174TBnQH8S3nYNaxo5zk9Yu
2026-11-24 08:18:31 -05:00
Richard OberholtzerandClaude Opus 5.5 2e06e82b5e Merge upstream MeshTerm 0.13.0
Conflicts resolved by keeping both sides:
  docs/development/writing-style.md (reaction/part terms + pixel image)
  meshterm/core/connection.py (sender timestamp + empty channel slot error)
  meshterm/tools/chat.py, meshterm/ui/chat.py (reactions/parts + pixel images)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0174TBnQH8S3nYNaxo5zk9Yu
2026-11-24 08:06:31 -05:00
Jean-Pierre MartineauandClaude Opus 5 f8ae40ee43 MeshTerm 1.0.0
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 01:41:06 -05:00
Jean-Pierre MartineauandClaude Opus 5 ae83c6177f A wiring that never looks at the expander names the family
A profile that drives the Cap without its expander says nothing about
which Cap it is. The node then found no expander because it never
looked, and the model fell back to the name of the newer board. An
owner of the older Cap who wrote such a profile read "Cap LoRa-1262".

The parent now sends the name of the family in that case, which is what
the device screen shows before anything is connected. It is the most
that is true when nothing looked.

The About page names both Caps, because MeshTerm drives both now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 00:15:47 -05:00
Jean-Pierre MartineauandClaude Opus 5 fca92541f6 The device screen names the Cap's slot, and the node names the Cap
Until MeshTerm connects, nothing can say which LoRa Cap is on a
Cardputer Zero. A radio on the SPI bus answers nothing until the node
runs on it, and the list probes nothing on purpose: a radio is in it
exactly when there is a device file to open. A probe would have to
power the header on every pass of the device screen, and it still could
not tell the older Cap from an empty header, because that answer comes
from the radio itself.

So the row names the slot. It reads "Cap LoRa", the family of the two
boards, in place of a claim that the newer one is attached.

The node names the board. It is the one part that sees which revision
answered, so the parent sends it the model of each revision and the
node reports the one that it found. The rest of the path was already
there: the frame server gives that model to the client, the store keeps
it beside the node name, and the hardware column of the device screen
shows it. A Cap is exact from its first connection onward, with no
probing, no power to the header for a listing, and no new permissions.

board_name is gone. Its one caller wanted the model, which board_models
answers now, and the row takes its name from the table as it always
did.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 00:01:19 -05:00
Jean-Pierre MartineauandClaude Opus 5 fe063065e1 A radio that is not there says so, on a board with no expander
Making the expander optional took a sentence away from the user. A
Cardputer Zero with no Cap at all reaches the radio library now, where
before it stopped at the expander. The library then said "Something
went wrong, check your wiring", and MeshTerm passed that on.

A board whose expander did not answer is the one place where nothing
has answered anywhere yet. There, a radio that does not start is a
radio that is not attached, and the user reads that instead. The words
of the library stay in the log. A busy line keeps its own kind, because
a line that another program holds has its own correction.

The three ways of finding out that no radio is there (the chip did not
start, it did not answer a register read, it answered as something
else) now give the user one sentence. The log keeps which of the three
it was.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 00:01:19 -05:00
Jean-Pierre MartineauandClaude Opus 5 338b5678de MeshTerm drives the older Cap LoRa868 as well as the Cap LoRa-1262
A user on a Cardputer Zero could not connect his Cap. MeshTerm stopped
at "nothing answers at 0x43 on /dev/i2c-1". His Cap is the Cap LoRa868,
which M5Stack made before the Cap LoRa-1262. The two boards carry the
same SX1262 on the same pins of the same header, and the same GNSS at
the same speed. The newer board adds an antenna switch, and the chip at
0x43 that turns the switch on. The older board has no switch, so it has
no such chip. MeshTerm asked for one on every Cardputer Zero.

A wiring now says whether its expander is required. pi4io_required is
true by default, so every other board keeps the rule that an expander
which does not answer is an absent board. The Cap sets it to false.

An absent expander is then the other revision of the board, and the
node must prove that before it accepts it. After the radio starts, the
node reads the version register of the chip and requires the name of an
SX126x. A bus with nothing on it reads as all ones or all zeros, and
the library can start on such a bus, so a Cap that is absent or badly
seated still reports that no radio answered.

The read of the expander also tells its failures apart now. Only the
errors that mean "nobody is at this address" count as absent. A bus
error or a refused read is a failure of its own, and never becomes the
older board quietly.

The two boards come from M5Stack's own pages, and from two other
Cardputer Zero applications that drive both. The pins, the TCXO, and
DIO2 are the same everywhere, and they agree with the wiring MeshTerm
already had.

One thing is open. The device screen names the row "Cap LoRa-1262"
before anything is connected, because nothing can know which Cap is
attached until the node runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 00:01:19 -05:00
Jean-Pierre MartineauandClaude Opus 5 bf79f9975c A silent expander gets more tries, and a failed start says more in the log
A user on a Cardputer Zero could not connect his Cap. MeshTerm stopped
with "nothing answers at 0x43 on /dev/i2c-1", and no log said more than
the dialog did. His Cap is the older Cap LoRa868, which carries no
expander at all. Support for that board follows separately. What this
commit changes is what MeshTerm knows when the next board stays silent.

The expander gets more than one try. The first read still comes after
POWER_SETTLE_S, which is sufficient on the boards we have. A board with
a slower power rail refuses that read and answers a moment later, and
that must not read as an absent board. The node now tries again until
PI4IO_WAIT_S is spent. A board that is ready still answers at once, so
nothing waits.

The log of that failure carries the error of the bus. The sentence 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.

The node also writes its wiring to its own log. A board problem is
reported with that file, and the wiring can come from a profile that
the reporter wrote, so the file must say which pins the node used.

The startup picker writes a failed connection to meshterm.log at
WARNING. It wrote nothing before, on the reasoning that the dialog
already says all that the log would say. That holds while the dialog is
up. A user who reports a problem sends the log file long after it is
gone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-23 00:01:19 -05:00
Jean-Pierre MartineauandClaude Opus 5 63e31c334b The neighbour table is a full screen, not a dialog
The reader is in this list rather than being asked something by it:
they sort it, filter it, and open a node page from it. That is a place,
and the stack is for places, so it is a page like the Contacts list and
not a box over the admin page (JP, 2026-11-22).

The title gains the count, as a page announces its size, and a short
title keeps the way out of the title bar on a narrow frame where a long
node name would otherwise cut it.

It still does not pan, 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 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.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 23:26:37 -05:00
Jean-Pierre MartineauandClaude Opus 5 d2de2caf60 Repeater admin lists the neighbours the node hears
The neighbour table says which nodes a repeater receives directly, and
how strongly. Until now the only way to it was the Fetch neighbours row
of the trace path composer, three steps in, and the table dissolved into
the evidence graph with no screen that showed it.

The admin page gets a Neighbours row. The session is already open, so
the fetch sends no second login. It runs under the spinner dialog with
Abort that the reads use, and the answer floats as the Trace-target
picker does: the same lane layout, the same Ctrl+arrow sort ring, the
same type-to-filter, the same node hues, type marks, and key lane.
Enter opens the node page of the highlighted neighbour, and the list
stays pushed under it, so Esc comes back to the same row in the same
sort.

Only the two middle lanes are new, 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 received from the neighbour. Both are declarations in
the shared lane spec, so the header, the rows, the widths, and the sort
metric all read the same tuple. The contact list gains an `snr` lane
kind, an `absent` word for an age lane (a neighbour with no age is not
"never" heard: the node hears it and did not say when), and an
`unknown` flag that draws the `○` mark, because a type mark on a node
nobody identified is a claim we cannot make.

A neighbour the device holds as a contact carries that contact. One
that nothing can name carries a contact of its key prefix alone, so
every row opens a page: it shows what the stored history knows about a
node our own radio never heard, which is the question the reader has.

The snapshot goes to the repository as before, so a fetch from here
feeds the mesh walk, the path composer, and the trace scenarios exactly
as a fetch from the composer does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 22:44:53 -05:00
Jean-Pierre MartineauandClaude Opus 5 17912782ee A filter keeps what a page does, on every screen that filters
The rule reached the exit pair of an editor and stopped there. A typed
query still took the Actions section of the Device config, the repeater
admin and the region editor, the Archive and View archived rows of the
Contacts list, the Add rows of Channels and Outbound paths, the bulk
sync of the Clock drift page, the Queue and Clear rows of the Courier,
the delete rows of the Trophy case, the alert actions of the
Watchtower, the whole-mesh row of the Time Machine, Probe all and Keep
current path in Trace, and the actions of the Device route popup.

Find-as-you-type searches the data of a list: the contacts, the
settings, the slots, the queued messages, the records. A row that acts
on the page is not in that data, so a query that matches no record hid
the way to act and said nothing about how to get it back. Each such row
now declares always_shown, and menu_rows takes the flag for a whole
section.

A list that is a menu keeps the old behaviour. The main menu, the
actions of one room, the actions of one outbound path, and the startup
offer are made of verbs, and there the query is how a reader finds one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 14:05:03 -05:00
Jean-Pierre MartineauandClaude Opus 5 5902b76e68 A typed filter never hides the way out of an editor
Apply has no keyboard key of its own. On the Preferences page, the
Device config page, the repeater admin page, the outbound editor, the
region editor, and the archive sweep, a typed query narrowed the rows
and took the exit pair with them. The staged changes were then only
reachable by a press of Esc that clears the filter, which nothing on
the screen says.

A Choice can now declare always_shown, and the filter keeps such a row
as it keeps each separator. The exit pair of menus.exit_rows, the
live-then-save pair of the region editor, and the Archive/Back pair of
the sweep declare it. A verb row that a reader searches for, such as an
Actions section or a menu, is content and filters as before.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 12:06:15 -05:00
Jean-Pierre MartineauandClaude Opus 5 cd38012506 Ruff passes on the whole package again
Three breaks had landed: one docstring line of 102 cells in
public_default, and two calls that the formatter joins back onto one
line in chat and menu. Nothing but the shape of the text changed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 02:46:52 -05:00
Jean-Pierre MartineauandClaude Opus 5 19532570b3 Device info says everything the companion reports
The page had drifted behind the firmware. Three statistics frames arrive
at each open and the panel drew nine rows from them, so the outbound
queue, the firmware error count, and the split of the packet counters
into flood and direct were read and thrown away. The device-query frame
carries the companion protocol version and the contact and channel
capacities, and nothing in MeshTerm had ever asked for them. The
default flood scope was one row named Flood scope, between the two
auto-add rows, with no key beside it. The key of the node itself was
nowhere on the page.

The panel now has four groups, in the order a user asks them in. What
the node is: role, public key with the routed bytes lit, model,
firmware with the protocol version, and place. What MeshTerm does with
it: the scope and the transport key of that scope, the active site with
the outbound paths and kept device routes that apply, and the name of
the radio preset. How it is doing: battery, storage, its own sensor
readings, the clock with its drift, uptime, contacts and channels
against the capacities, the queue, and the errors. What it heard and
sent: the noise floor, the airtime, and the packet counts, split.

A node with no scope says that its floods reach everyone, because an
empty value there is a statement and not an absence. A node whose
stored scope key is not the key of its own name says so in amber: a
flood under that key reaches no repeater that listens for the name, and
nothing else in MeshTerm could show it.

The rows sit in a two-column grid, so a value wider than the panel
wraps under its own column instead of going back to the left edge, and
a 64-digit key stays whole. The gallery draws the panel now, so both
platforms hold it to their readable width.

Two new device reads, both optional and both answered by any firmware:
the scope frame read for its key as well as its name, and the sensor
readings of the node itself, which MeshTerm had never asked any device
for. The device-query frame is no longer read twice at each open, since
the snapshot already merges it.

The scripted face answers with the same three parts: the status, the
readings, and every setting. The settings come from the one definition
that config show answers with, under the keys config get and config set
take, so the two faces cannot drift and no setting is spelled two ways.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 02:02:32 -05:00
Jean-Pierre MartineauandClaude Opus 5 6eb611a6be A radio with no channel gets the standard Public one at startup
A radio that arrives with no channel at all cannot send anywhere: each
send needs a slot, and the device refuses a send on a slot it does not
have. A new user reads the empty Chat picker as "nobody is here", not
as "this radio has no channel".

So MeshTerm writes the channel that MeshCore itself ships, on slot 0,
and says so on the splash. It does not ask: the key is well known and
the device had nothing to lose, which is the same judgment as the
position that the settings offer restores silently. One preference,
public_on_empty_device, on by default, turns it off.

The step is cheap and quiet. It reads slot 0 first, so a radio that
has channels pays one round trip at each startup. It writes only on a
slot probe that finished, because an unfinished probe returns a short
list that reads exactly like an empty device. The simulator is passed
over: it starts empty at each launch, so it would write and raise a
card on every run of the development loop.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 00:39:43 -05:00
Jean-Pierre MartineauandClaude Opus 5 66ffae49f6 The name Public asks again, and the Public offer reads the key
#Public is not the standard Public channel: its key comes from its
name, so its hash differs and no other node is on it. But the two add
rows sit side by side, and Public is the obvious word to type into
"Public channel name:". A user who did that got a channel that looked
right in every list, that sent with no error, and that nobody heard.

Two halves of the same hole. The name now asks again and offers the
standard channel instead, without refusing the name. And the Chat
picker's offer no longer waits for slot 0 to be empty: the
well-known key decides, not the slot, so a #Public in slot 0 cannot
hide the one way back to the real channel. The offer names the lowest
free slot, and the add confirms that slot against the real capacity
before it writes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-22 00:39:35 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 01a2768ef9 Sound preferences speak plainly in their helps and questions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:27:05 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 bd37ea2687 Sounds overlap on Windows: each one plays on its own MCI device
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:17:33 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 73eed72391 No sound for what was already there: the companion's queue and a room's catch-up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:12:59 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 da20d3e93d Mentions play always, on, or as a message; the open conversation can play too
A mention in a DM plays the DM sound. The sound keys of this unpushed
work are not retired: they never left this machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:01:09 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 d6a5bed974 Each sound event has its own switch; the per-conversation sound settings are gone
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 01:35:16 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 da2e5d3044 Channels have no sound row; a muted channel is silent; mentions always play
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 01:06:32 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 037585dd15 The Sound preferences read clearly at 72 columns, and their dialogs ask a real question
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:54:11 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 95f12c0a22 Document the sounds: the guide, the changelog, and the working notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:36:39 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 ea84d7f9dd A notification with no sound can flash the title
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:35:15 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 317279f934 A low battery plays its sound once, and each packet can tick
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:09 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 6c58299e7d Each channel, DM, and room has a Sound row: default, off, mentions, or all
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:21:54 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 0b04ce5c94 The volume is a slider of ten steps, and each step plays the channel sound
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:14:29 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 72631f623f ^S mutes the sounds from any screen; the header and the menu show 🔊 or 🔇
The first switch (sounds on or off, off by default) becomes a mute,
off by default: "no sound" is a theme. The volume is now ten steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:07:11 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 89a8eea16b A received message plays its conversation's sound: off, mentions, or all
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:50:39 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 f7e5cd9049 A sound service that plays notifications through the system's own player
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:43:34 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 0896109fb2 Sound preferences, and which platforms can play a sound
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:40:29 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 7807a4cc2c Six Android notification sounds, for the sound theme to come
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 23:25:26 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 af34c622b6 The PIN reveal moves to ^E, so ^S is free for the sound mute
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:59:40 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 5dc62cdc5b Relay marks count every repeater; near relays are gone
The first build counted only the relays past the first hops of the
outbound paths. On JP's Public channel, 23 of 23 sent messages came back
only through the two home repeaters: each repeater relays one time, and
the next hop (8 km away) is too far for the companion to hear. So every
message showed the warning mark, and nothing was ever confirmed.

Now each repeater that sends a copy back counts, the same as a DM ack:
spinner, then a check with the number of repeaters, or a cross. The
warning state, the near-relay snapshot of each send, the ^P atom, and
heard_via are removed. heard_relays keeps only the paths; a database with
the first build of the table gets it made again (derived data only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:21:11 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 f4b1d659d1 A sent channel message shows whether it went past your near relays
A channel has no acknowledgement, but the radio hears each repeater that
relays our message, and each copy names the relays that it went through.
The end of our channel message now shows a spinner, then a check and the
number of relays past the near relays (the first hops of the outbound
paths that apply), a warning when only the near relays sent it back, or a
cross when no relay did. A near relay is near by identity, at any place
in a path. Managed nodes play no part: a remote managed repeater counts.

- services/heard_by.py: the verdict, and a tracker that fills in the
  background and refreshes on each channel packet. Settled verdicts are
  stored (schema 24, heard_relays), with the near relays of each send.
- The picked message names the relays and the near relay that carried it.
- ^P counts the relays past the near relays.
- chat history --channel: a HEARD lane; --json gives heard, heard_by,
  heard_via.
- New preference heard_wait_s (Relay wait, 30 s).
- Fix: a copy of our own channel message must carry the time of that
  send, so two messages with the same text no longer share copies.

Closes #38

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:29:59 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 fa912032a3 MeshTerm 0.13.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:54:25 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 d3148d340e A demo channel added later no longer changes the rest of the demo
The history draws its conversations, greetings, traces and neighbours from
one random source. #mcoimg's lines took numbers from it (as messages and as
the greeting adverts before them), which moved the route the video's trace
to Brossard learns off Mont-Royal, and the trace got no reply. Channels past
the first four slots now draw from sources of their own, so the shared one
ends where it did in 0.12.0 and the route is Mont-Royal again (3233x).

Four holds of the video tour are shorter, so it stays under two minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:54:09 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 89037f6616 A pixel image keeps its own size; a tall one scrolls instead of shrinking
The transcript capped an image's height by the platform's rows, so the
Cardputer drew the 30x30 woodpecker at 20x20, and the ^U view at 18x18.
Now neither shrinks it: one pixel is one cell wide, a tall image scrolls
like a long message, and the ^U view only grows it by a whole number
where the frame has room. Only an image wider than the screen still
shrinks, to fit the width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:05:14 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 25f1b42b15 Demo world gets a #mcoimg channel; the screenshot tour captures it
The demo device holds #mcoimg in slot 4: a short talk about pixel art
around three images, the real 30x30 woodpecker last so the chat opens on
it. The tour saves it as mcoimg.png after the map, waiting on the
channel's title, which every set draws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:00:23 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 c5b2e87ca4 Gallery covers the pixel image; ^U view never shrinks it for its string
Three gallery cases with a real 30x30 image: the transcript, the picked
message (^U image, the Image chip), and the ^U view, on all four sizes.
They showed the Cardputer's view shrinking the image to 12x12 to fit the
im3: string. The string may now only stop the image from growing; when
it would make the image smaller than it is alone, it goes a page down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:47:17 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 e5dc602e11 The show_mcoimg preference is labelled Show MCOimg
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:44:51 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 3c5c0e811b MCOimg tests decode a real image: a 30x30 woodpecker in 74 bytes
The first test image from a real encoder rather than the tests' own raw
one. It uses the 512-colour dynamic profile and a compact regions stream
with three regions, which the reference vectors only cover at tiny sizes.
The pixels were checked by eye; the test pins their hash and colour counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:40:21 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 e84c902a80 The MCOimg pixel decoder loads at the first image, not with the chat
The decoder moves from core/mcoimg.py to core/mcoimg_decode.py, unchanged.
mcoimg.py keeps recognition (the caption needs only the header) and is
what the chat imports; pixelart imports the decoder inside decoded().
On the PicoCalc the decoder cost about 50 ms on every chat import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:47:53 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 2f2225b8bb The full-screen image shows the message's im3: string under its caption
The ^U view now shows the text the sender transmitted, as a centred block
under the caption, so it can be examined or copied. The string never
shrinks the image below its own size: when both cannot fit, the image
keeps the rows and the string goes a page down, as a large QR code's URL
does. A test now pins that ^U opens the view with images shown too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:37:23 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 24b7690870 The pixel image preference is show_mcoimg
Renamed from chat_images, which no released version ever had, so the old
name is not retired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:49:23 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 6f63cfbad3 NOTICE carries meshcore-open's MIT notice for the MCOimg colour tables
mcoimg_palettes.py is generated from meshcore-open's palette files, so
the copyright line and MIT permission text now travel with every copy,
as the Cascadia font's terms do. The decoder itself is MeshTerm's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:45:19 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 7306f05d9f The full-screen image keeps a margin, centred like the QR codes
A small image grown to fill the bare frame touched its edges: a wide one
ran edge to edge, and a tall one took every row. It now keeps two cells
at each side and three free rows, which the frame splits one above and
two below, so it sits centred a little above the middle as a code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:44:32 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 1ff2eecf76 ^U opens a chat's pixel image full-frame; chat_images preference
On a picked message that is an MCOimg image, ^U opens it on a bare frame,
grown by a whole number to fill it, with its caption under it. The lane
chip reads Image and the hint ^U image. The new chat_images preference
(Display, on by default) can turn the inline drawing off; then the chat
shows the caption only, and ^U is the way to see the image. Refs #37.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:41:18 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 5fb11e1acd Chat draws MCOimg pixel images in half blocks under their caption
A v3 image (im3:) is now decoded in full: all 16 palette profiles, 4 scan
orders, 8 containers, 16 block algorithms, and every local palette form.
The decoder is written from the published spec; the palette colours are
interop data generated from meshcore-open's tables (MIT, credited).
Hostile input returns None and never raises; a 64x64 image takes ~20 ms.

The chat draws two pixels per cell (top colour over bottom background),
at the body's indent, shrunk by nearest pixel to fit the lane and the
platform's rows. All 45 reference vectors pass, copied to tests/data.
Refs #37.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:18:21 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 017fdcfce7 Chat shows an MCOimg pixel image as a short line instead of Base91 noise
A message whose body is an MCOimg image (im3:, or im: for v1/v2) now reads
"🎨 image · 24×24 · 16 colours" in the transcript and the Messages preview.
The v3 header gives the size and the palette; the pixels are not decoded yet.
The Base91 text no longer makes false mention chips, links, or QR codes.
Checked against all 51 reference vectors. Refs #37.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:58:45 -05:00
Jean-Pierre MartineauandClaude Opus 5.5 696ac634b9 Release skill comments the shipping version on each fixed issue
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:27:57 -05:00
Jean-Pierre MartineauandClaude Haiku 5.5 888dc3b633 Chat offers to add Public instead of opening a channel the device lacks
When slot 0 was empty, the Chat picker showed a Public row that looked like
a real channel, and every send on it failed with "the device has no contact
with that key" (#36). The row is now an offer: Enter asks to add Public to
slot 0, and the chat opens only after the write. The CLI lists only the
channels on the device, and a refused channel send names the empty slot.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-16 23:19:34 -05:00
116 changed files with 10505 additions and 342 deletions

No files matched your search

+14
View File
@@ -260,6 +260,20 @@ gh release view vX.Y.Z --json assets --jq '.assets | length'
If a *build* fails, the tag is already public: fix forward with a new patch version rather
than deleting and re-pushing a tag people may have fetched.
### Tell each fixed issue which release has its fix
An issue is closed when its fix is pushed (JP, 2026-11-16), so the reporter does not yet
have a version to install. Once the release has landed, comment on each issue whose fix is
in this release: the issues that commits since the previous tag name, and the issues closed
since then. Read each one first, and skip one whose fix is not in the range.
```
git log vPREV..vX.Y.Z --format='%s%n%b' | grep -oE '#[0-9]+' | sort -u
gh issue comment N --body "The fix is in MeshTerm X.Y.Z: https://github.com/jpmartineau/MeshTerm/releases/tag/vX.Y.Z"
```
If a fix did not work, say so on the issue and reopen it instead.
## 7. The Discord announcement — for JP to post
Once the release has landed and checked out, end by showing JP a short announcement for
+145 -4
View File
@@ -3,12 +3,151 @@
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
carry a very small picture in the MCOimg format, as `im3:` and a line of characters. Before,
MeshTerm showed those characters as noise. Now the chat draws the picture. Also, Chat no
longer opens a Public channel that is not on your device.
### Added
- **The chat draws MCOimg pixel images.** A message that is an MCOimg image (version 3,
`im3:`) shows a line with its size and its number of colours, and the picture under it.
Each pixel is one cell wide, so the picture keeps its own size. A tall picture scrolls
with the transcript. The Messages list shows the same line in its preview. An image of
version 1 or 2 (`im:`) shows the line, but not the picture: MeshTerm does not decode
these older versions. Before, the characters of an image could also look like a mention
or a link. Now they do not.
- **^U shows the picked image on the full screen.** The picture is as large as the screen
permits, by a whole number, so each pixel stays square. It never becomes smaller than its
own size. Under it are its size, its colours, and the text of the message itself. On the
PicoCalc and the Cardputer Zero, the F-key chip reads `Image`.
- **The Show MCOimg preference turns the pictures in the chat off.** It is in the Display
group, and it is on by default. When it is off, the chat shows only the line about each
image, and ^U shows the picture.
### Fixed
- **Chat no longer opens a Public channel that is not on your device.** When slot 0 of the
device was empty, the Chat picker showed a Public row that looked like a real channel.
Each message that you sent there failed with "the device has no contact with that key".
Now the row offers to add Public to slot 0, and the chat opens after the device has the
channel. The command line lists only the channels on the device, and a refused send
names the empty slot.
## [0.12.0] - 2026-11-11
**MeshTerm finds wrong clocks, names the place of each node, and lets you choose the route
@@ -880,7 +1019,9 @@ 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.12.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
[0.11.4]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.11.4
+24 -2
View File
@@ -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
@@ -326,6 +341,12 @@ deliberately, one at a time, and say why in the code.
narrower quiet zone, before it would ever be cut (a contact card is 57 cells and 29
rows at the standard fit in half blocks; a regular terminal is 24 tall), and when code
and URL can't share the frame the code is whole at the top and the URL a page down.
A picked message that is a pixel image (MCOimg, `ui/pixelart.py`) opens its image on the
same bare frame instead, grown by a whole number to fill it (`ImageScreen`; the chip
reads `Image`, the hint `^U image`); with `show_mcoimg` off, that is the only view.
**A pixel image is never shrunk** (JP, 2026-11-20): one pixel is one cell wide in the
transcript and on that frame, and a tall one scrolls; only a width the screen can't
hold makes it smaller.
A chat message's links open there too, on every platform: ^U on the picked message,
and with several, one code at a time that ←→ step through, clamped. That screen's URL
line is flanked `←`/`→`, lit toward another code and dim at an end — the one mark the
@@ -554,9 +575,10 @@ 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 ·
🚪 quit. Packet-class icons (feed/viewer
🎨 pixel image (an MCOimg picture in a message) · 🚪 quit. Packet-class icons (feed/viewer
lane): 📢 advert · 📊 telemetry · 📦 packet · 💬 message · ✅ ack. Raw payload
classes (`PAYLOAD_ICONS`): 📻 channel text · 💽 channel data · 📩 direct message
(overheard) · 📥 request · 📮 response · 🎭 anon request · 🧭 path · 🎯 trace ·
+38
View File
@@ -39,3 +39,41 @@ Cascadia Code. It is redistributed here unmodified under the SIL Open Font
License, Version 1.1, which is included beside it as CascadiaMono-OFL.txt and
is its only license -- the Apache License above does not apply to it. The
inclusion of this font does not imply that Microsoft endorses MeshTerm.
MCOimg colour tables: meshterm/core/mcoimg_palettes.py holds the colour
tables of the MCOimg image format, generated from lib/helpers/mcoimg_palette.dart
and lib/helpers/mcoimg_dynamic_palettes.dart of meshcore-open
(https://github.com/zjs81/meshcore-open, and the HDDen/meshcore-open fork),
which are provided under the following license:
MIT License
Copyright (c) 2025 zjs81
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
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.
+1 -1
View File
@@ -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/3d0414dc-d3f0-491d-83b7-11686e4922f5
https://github.com/user-attachments/assets/4f918f68-6302-43c8-8d44-df8ad29b5bd3
<p align="center"><sub>A video of less than two minutes, in the demo mesh over Montréal (<code>meshterm --demo</code>).</sub></p>
+23 -2
View File
@@ -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.12.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 |
+1
View File
@@ -207,6 +207,7 @@ and in quoted text.
| reaction | An emoji that a node sends to answer one message. It is a message on the wire, and the chat shows it under the message that it names | |
| part | One of the messages that MeshTerm sends for a message that is too long for one packet | chunk, segment |
| part number | The `[1/3]` at the end of a part | marker (for this) |
| pixel image | A very small picture in the MCOimg format that a message carries as text (`im3:` and Base91 characters) | picture, MCOimg image |
| sender time | The time that a message or an advert carries, from the clock of the node that sent it. It is a claim, and a node with a wrong clock makes it false | timestamp (alone) |
| arrival time | Our clock when MeshTerm got a received message from the companion (`received_at`) | receive time |
| clock offset | The sender time minus the arrival time. A positive offset is a clock ahead of ours. The offset of a node is the median of its three newest clock samples | skew, drift (for this) |
+45 -2
View File
@@ -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
+1
View File
@@ -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. |
+5 -3
View File
@@ -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.
+49 -4
View File
@@ -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 <key> <value>` / `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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

+1 -1
View File
@@ -6,7 +6,7 @@ Connects to a companion over USB, Bluetooth, or TCP. For Windows, macOS, and Lin
from datetime import datetime
__version__ = "0.12.0"
__version__ = "1.0.0"
__author__ = "Jean-Pierre Martineau"
#: The year when MeshTerm was first published. The copyright span starts in this year.
+4 -1
View File
@@ -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**
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+25
View File
@@ -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.
<!-- ste: off -->
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.
<!-- ste: on -->
+16
View File
@@ -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.
+7
View File
@@ -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
+117 -3
View File
@@ -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."""
@@ -4556,7 +4636,14 @@ class MeshCoreDevice(Device):
) -> None:
transmit_gate.mark()
async with self.transmitting():
self._ok(await self._require().commands.send_chan_msg(index, text, timestamp))
event = await self._require().commands.send_chan_msg(index, text, timestamp)
# For a channel send, "not found" is an empty slot, not a contact. The general
# clause names a contact, which was the wrong lead in issue #36.
if error_code(event) == 2:
raise RuntimeError(
f"device rejected the command: the device has no channel in slot {index}"
)
self._ok(event)
@staticmethod
def _ok(event): # type: ignore[no-untyped-def]
@@ -4636,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())
@@ -5210,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)
+12 -5
View File
@@ -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
+190
View File
@@ -0,0 +1,190 @@
# SPDX-License-Identifier: Apache-2.0
"""Recognize a pixel image in the body of a message: the MCOimg format.
MCOimg is a format for very small pictures (1 to 256 pixels for each side, in practice 10
to 30) that some MeshCore apps send on a channel. Each image is one packet. As a text
message, it is a prefix and then Base91 text: ``im:`` for the versions 1 and 2, ``im3:``
for version 3. A client that does not know the format shows that text as noise. The
reference is ``docs/mcoimg_v3_reference.md`` in the HDDen/meshcore-open repository (MIT).
This module only *recognizes* an image: :func:`recognize` finds that a body is an image,
and for a version 3 image it reads the header (the size and the number of colours of the
palette). Thus the chat can show a short line in place of the noise. It is fast, and it
does not decode the pixels. The pixel decoder is :mod:`meshterm.core.mcoimg_decode`. It is
a separate module because it is large: the chat loads it only when it draws the first
image, and not each time that it opens (approximately 50 ms on the PicoCalc).
Version 3 data, after the Base91 decode::
0x13 subtype 1 (MCOimg) in the high nibble, revision 3 in the low
nonce: u8 changes with each send, and has no meaning for the picture
header: u8 bit 7 transparent, bit 6 white background, bits 5..4 scan,
bits 3..0 palette profile
dimensions bit-packed, LSB first (refer to :func:`_dimensions`)
... the pixels, which :mod:`meshterm.core.mcoimg_decode` reads
"""
from __future__ import annotations
import re
from dataclasses import dataclass
#: The Base91 alphabet of MCOimg, in the order of its values. It is the alphabet of
#: basE91, which has no space, no ``'``, no ``-``, and no ``\\``.
_ALPHABET = (
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~"'
)
_VALUE = {char: index for index, char in enumerate(_ALPHABET)}
#: A body that is an image: the prefix and one word of Base91 text. The version digit is
#: optional, because the versions 1 and 2 use ``im:``.
_IMAGE = re.compile(r"im(\d?):(\S+)")
#: The shortest Base91 text that MeshTerm accepts as an image of a version whose header it
#: cannot read. The smallest such image of the reference tests has 11 characters. A
#: shorter word after ``im:`` is more probably words that a person typed. A version 3 image
#: needs no minimum, because its first byte and its header must be correct.
_MIN_TEXT = 8
#: The first byte of a version 3 image: subtype 1 (MCOimg), revision 3.
_V3 = 0x13
#: The number of colours of each palette profile of version 3, by profile id. The ids
#: 0 to 5 are the master palettes, 6 to 8 are the grey palettes, and 9 to 15 are the
#: dynamic palettes (subsets of the global palette of 512 colours).
_PROFILE_COLOURS = (2, 4, 8, 16, 32, 64, 16, 32, 8, 8, 16, 32, 64, 128, 256, 512)
@dataclass(frozen=True)
class PixelImage:
"""What a message body tells about the pixel image that it carries.
Attributes:
version: The format version: 3 for ``im3:``, or ``None`` for ``im:``, which is
version 1 or 2 (its text does not say which).
width: The width in pixels, or ``None`` when MeshTerm cannot read the header.
height: The height in pixels, or ``None`` when MeshTerm cannot read the header.
colours: The number of colours of the palette, or ``None`` when MeshTerm cannot
read the header.
"""
version: int | None
width: int | None = None
height: int | None = None
colours: int | None = None
def recognize(body: str) -> PixelImage | None:
"""Return the pixel image that ``body`` carries, or ``None`` when it is not an image.
The body must be the image and nothing else (spaces at the ends are permitted). An
``im3:`` body must also start with the version 3 byte after the decode. A body with a
version that MeshTerm does not know (``im4:``) is an image with no header.
Args:
body: The text of a message, without the ``Name: `` of a channel sender.
Returns:
The image, or ``None``.
"""
match = _IMAGE.fullmatch(body.strip())
if match is None:
return None
digit, text = match.groups()
data = base91_decode(text)
if data is None:
return None
version = int(digit) if digit else None
if version != 3:
# Here MeshTerm cannot read a header, so only the length makes the claim.
return PixelImage(version=version) if len(text) >= _MIN_TEXT else None
if len(data) < 4 or data[0] != _V3:
return None
header = data[2]
size = _dimensions(_Bits(data[3:]))
if size is None:
return PixelImage(version=3)
width, height = size
return PixelImage(3, width, height, _PROFILE_COLOURS[header & 0x0F])
def base91_decode(text: str) -> bytes | None:
"""Decode the Base91 text of an image, or return ``None`` for a character not in it.
Each pair of characters holds 13 or 14 bits: 13 when the low 13 bits of the pair are
more than 88, or else 14. A last single character holds the remaining bits.
"""
out = bytearray()
queue = bits = 0
value = -1
for char in text:
index = _VALUE.get(char)
if index is None:
return None
if value < 0:
value = index
continue
value += index * 91
queue |= value << bits
bits += 13 if (value & 8191) > 88 else 14
while bits > 7:
out.append(queue & 0xFF)
queue >>= 8
bits -= 8
value = -1
if value >= 0:
out.append((queue | (value << bits)) & 0xFF)
return bytes(out)
class _Bits:
"""A reader of bit fields, LSB first, from a byte string.
:func:`recognize` uses it. :func:`decode` uses the subclass :class:`_Reader`, which
adds the integer forms of the format.
"""
def __init__(self, data: bytes) -> None:
self._value = int.from_bytes(data, "little")
self._left = len(data) * 8
self._pos = 0
def read(self, count: int) -> int | None:
"""The next ``count`` bits as an unsigned number, or ``None`` past the end."""
if self._pos + count > self._left:
return None
value = (self._value >> self._pos) & ((1 << count) - 1)
self._pos += count
return value
def _dimensions(bits: _Bits) -> tuple[int, int] | None:
"""Read the width and the height of a version 3 image, or ``None`` past the end.
The first two bits are the mode. Each mode stores the sizes minus one:
- 0: a square up to 64, one width of 6 bits.
- 1: up to 32 × 32, a width and a height of 5 bits each.
- 2: up to 64 × 64, a width and a height of 6 bits each.
- 3: up to 256 × 256. One bit is set for a rectangle. Then there is a width of 8 bits,
and for a rectangle a height of 8 bits.
"""
mode = bits.read(2)
if mode == 0:
side = bits.read(6)
return None if side is None else (side + 1, side + 1)
if mode in (1, 2):
size = 5 if mode == 1 else 6
width, height = bits.read(size), bits.read(size)
elif mode == 3:
rectangle = bits.read(1)
if rectangle is None:
return None
width = bits.read(8)
height = bits.read(8) if rectangle else width
else:
return None
if width is None or height is None:
return None
return width + 1, height + 1
File diff suppressed because it is too large. Load diff
+279
View File
@@ -0,0 +1,279 @@
# SPDX-License-Identifier: Apache-2.0
"""The colour tables of the MCOimg palette profiles.
This module is data for interoperability, and has no code. A script made it from the
files ``lib/helpers/mcoimg_palette.dart`` and ``lib/helpers/mcoimg_dynamic_palettes.dart``
of the meshcore-open repository (HDDen/meshcore-open, a fork of zjs81/meshcore-open, MIT).
Do not edit the values by hand. A different value changes the colour of a pixel.
- The fixed profiles are tuples of (red, green, blue), in the order of the colour ids.
- ``GLOBAL_512`` is the dynamic global palette of 512 colours.
- Each ``DYNAMIC_n`` tuple gives the index in ``GLOBAL_512`` of each colour id of the
dynamic profile of n colours.
"""
from __future__ import annotations
# The tables keep several values on each line, so the formatter must not change them.
# fmt: off
MONO: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (0, 0, 0),
)
MASTER_4: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (192, 192, 192), (86, 86, 86), (0, 0, 0),
)
MASTER_8: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (141, 141, 141), (0, 0, 0), (254, 36, 0), (241, 209, 0),
(71, 192, 0), (61, 105, 255), (121, 0, 255),
)
MASTER_16: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (164, 164, 164), (0, 0, 0), (209, 30, 1), (98, 14, 1),
(255, 132, 0), (123, 64, 0), (241, 209, 0), (144, 124, 2), (65, 176, 0),
(40, 110, 0), (127, 220, 255), (0, 58, 255), (0, 34, 150), (106, 0, 227),
(47, 0, 100),
)
MASTER_32: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (179, 179, 179), (102, 102, 102), (0, 0, 0), (255, 176, 163),
(255, 85, 65), (254, 36, 0), (98, 14, 1), (255, 179, 99), (255, 132, 0),
(197, 102, 1), (142, 73, 0), (245, 222, 91), (241, 209, 0), (181, 157, 2),
(120, 105, 2), (149, 218, 118), (71, 192, 0), (40, 110, 0), (29, 79, 0),
(196, 241, 255), (1, 195, 255), (3, 141, 184), (1, 109, 143), (117, 150, 255),
(0, 58, 255), (2, 46, 202), (0, 34, 150), (215, 178, 255), (178, 135, 255),
(133, 61, 255), (47, 0, 100),
)
MASTER_64: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (217, 217, 217), (179, 179, 179), (138, 139, 138), (111, 111, 111),
(79, 79, 79), (36, 36, 36), (0, 0, 0), (255, 176, 163), (255, 154, 137),
(255, 85, 65), (254, 36, 0), (209, 30, 1), (145, 21, 0), (98, 14, 1),
(69, 10, 0), (255, 179, 99), (255, 168, 85), (255, 147, 51), (255, 132, 0),
(228, 118, 1), (197, 102, 1), (142, 73, 0), (123, 64, 0), (247, 229, 114),
(245, 222, 91), (241, 209, 0), (223, 193, 2), (203, 177, 1), (181, 157, 2),
(144, 124, 2), (120, 105, 2), (183, 230, 155), (149, 218, 118), (109, 205, 75),
(71, 192, 0), (65, 176, 0), (54, 148, 1), (40, 110, 0), (29, 79, 0),
(196, 241, 255), (171, 233, 255), (127, 220, 255), (1, 195, 255), (0, 182, 238),
(1, 170, 223), (3, 141, 184), (1, 109, 143), (145, 170, 255), (117, 150, 255),
(59, 100, 255), (0, 58, 255), (2, 51, 225), (2, 46, 202), (1, 40, 176),
(0, 34, 150), (215, 178, 255), (178, 135, 255), (154, 101, 255), (133, 61, 255),
(121, 0, 255), (105, 2, 221), (83, 1, 175), (47, 0, 100),
)
GREY_16: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (238, 238, 238), (221, 221, 221), (204, 204, 204), (187, 187, 187),
(170, 170, 170), (153, 153, 153), (136, 136, 136), (119, 119, 119), (102, 102, 102),
(85, 85, 85), (68, 68, 68), (51, 51, 51), (34, 34, 34), (17, 17, 17),
(0, 0, 0),
)
GREY_32: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (247, 247, 247), (239, 239, 239), (230, 230, 230), (222, 222, 222),
(214, 214, 214), (206, 206, 206), (197, 197, 197), (189, 189, 189), (181, 181, 181),
(173, 173, 173), (165, 165, 165), (156, 156, 156), (148, 148, 148), (140, 140, 140),
(132, 132, 132), (123, 123, 123), (115, 115, 115), (107, 107, 107), (99, 99, 99),
(90, 90, 90), (82, 82, 82), (74, 74, 74), (66, 66, 66), (57, 57, 57),
(49, 49, 49), (41, 41, 41), (33, 33, 33), (24, 24, 24), (16, 16, 16),
(8, 8, 8), (0, 0, 0),
)
GREY_8: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (219, 219, 219), (182, 182, 182), (145, 145, 145), (109, 109, 109),
(72, 72, 72), (36, 36, 36), (0, 0, 0),
)
GLOBAL_512: tuple[tuple[int, int, int], ...] = (
(255, 255, 255), (241, 211, 179), (215, 174, 131), (187, 135, 93), (155, 99, 62),
(124, 73, 45), (94, 51, 31), (65, 33, 22), (37, 17, 11), (217, 217, 217),
(255, 237, 229), (255, 229, 211), (255, 216, 198), (248, 204, 191), (244, 191, 165),
(235, 184, 143), (224, 169, 132), (210, 151, 123), (179, 179, 179), (255, 214, 224),
(255, 220, 200), (255, 242, 184), (205, 236, 207), (201, 238, 240), (206, 221, 250),
(224, 210, 244), (234, 207, 227), (138, 139, 138), (228, 224, 174), (202, 199, 131),
(170, 169, 95), (137, 139, 67), (109, 113, 52), (83, 86, 41), (58, 60, 30),
(35, 36, 22), (111, 111, 111), (255, 241, 184), (255, 224, 138), (244, 201, 93),
(221, 175, 55), (196, 147, 36), (157, 113, 24), (116, 80, 15), (73, 48, 8),
(79, 79, 79), (185, 243, 232), (130, 221, 207), (78, 195, 181), (39, 164, 151),
(22, 132, 121), (14, 99, 92), (8, 68, 63), (3, 38, 34), (36, 36, 36),
(244, 192, 168), (231, 155, 124), (212, 118, 87), (185, 86, 62), (150, 61, 45),
(114, 43, 34), (79, 28, 24), (43, 14, 13), (0, 0, 0), (255, 176, 163),
(250, 243, 232), (239, 227, 210), (226, 209, 185), (211, 191, 162), (194, 169, 135),
(170, 144, 111), (141, 118, 92), (111, 92, 73), (255, 154, 137), (255, 224, 194),
(244, 194, 159), (223, 165, 126), (200, 137, 98), (170, 107, 73), (130, 80, 58),
(91, 53, 42), (53, 32, 27), (255, 85, 65), (141, 141, 141), (164, 164, 164),
(102, 102, 102), (255, 63, 36), (254, 58, 29), (254, 52, 22), (254, 47, 14),
(254, 41, 7), (254, 36, 0), (249, 35, 0), (244, 35, 0), (239, 34, 0),
(234, 33, 0), (229, 33, 1), (224, 32, 1), (219, 31, 1), (214, 31, 1),
(209, 30, 1), (202, 29, 1), (195, 28, 1), (188, 27, 1), (181, 26, 1),
(173, 25, 0), (166, 24, 0), (159, 23, 0), (152, 22, 0), (145, 21, 0),
(140, 20, 0), (135, 19, 0), (129, 19, 0), (124, 18, 0), (119, 17, 1),
(114, 16, 1), (108, 16, 1), (103, 15, 1), (98, 14, 1), (95, 14, 1),
(92, 13, 1), (88, 13, 1), (85, 12, 1), (82, 12, 0), (79, 11, 0),
(75, 11, 0), (72, 10, 0), (69, 10, 0), (255, 179, 99), (255, 178, 97),
(255, 177, 96), (255, 175, 94), (255, 174, 93), (255, 173, 91), (255, 172, 90),
(255, 170, 88), (255, 169, 87), (255, 168, 85), (255, 166, 81), (255, 163, 77),
(255, 161, 74), (255, 159, 70), (255, 156, 66), (255, 154, 62), (255, 152, 59),
(255, 149, 55), (255, 147, 51), (255, 145, 45), (255, 144, 40), (255, 142, 34),
(255, 140, 28), (255, 139, 23), (255, 137, 17), (255, 135, 11), (255, 134, 6),
(255, 132, 0), (252, 130, 0), (249, 129, 0), (246, 127, 0), (243, 126, 0),
(240, 124, 1), (237, 123, 1), (234, 121, 1), (231, 120, 1), (228, 118, 1),
(225, 116, 1), (221, 114, 1), (218, 113, 1), (214, 111, 1), (211, 109, 1),
(207, 107, 1), (204, 106, 1), (200, 104, 1), (197, 102, 1), (191, 99, 1),
(185, 96, 1), (179, 92, 1), (173, 89, 1), (166, 86, 0), (160, 83, 0),
(154, 79, 0), (148, 76, 0), (142, 73, 0), (140, 72, 0), (138, 71, 0),
(136, 70, 0), (134, 69, 0), (131, 68, 0), (129, 67, 0), (127, 66, 0),
(125, 65, 0), (123, 64, 0), (247, 229, 114), (247, 228, 111), (247, 227, 109),
(246, 227, 106), (246, 226, 104), (246, 225, 101), (246, 224, 99), (245, 224, 96),
(245, 223, 94), (245, 222, 91), (245, 221, 81), (244, 219, 71), (244, 218, 61),
(243, 216, 51), (243, 215, 40), (242, 213, 30), (242, 212, 20), (241, 210, 10),
(241, 209, 0), (239, 207, 0), (237, 205, 0), (235, 204, 1), (233, 202, 1),
(231, 200, 1), (229, 198, 1), (227, 197, 2), (225, 195, 2), (223, 193, 2),
(221, 191, 2), (219, 189, 2), (216, 188, 2), (214, 186, 2), (212, 184, 1),
(210, 182, 1), (207, 181, 1), (205, 179, 1), (203, 177, 1), (201, 175, 1),
(198, 173, 1), (196, 170, 1), (193, 168, 1), (191, 166, 2), (188, 164, 2),
(186, 161, 2), (183, 159, 2), (181, 157, 2), (177, 153, 2), (173, 150, 2),
(169, 146, 2), (165, 142, 2), (160, 139, 2), (156, 135, 2), (152, 131, 2),
(148, 128, 2), (144, 124, 2), (141, 122, 2), (139, 120, 2), (136, 118, 2),
(133, 116, 2), (131, 113, 2), (128, 111, 2), (125, 109, 2), (123, 107, 2),
(120, 105, 2), (183, 230, 155), (179, 229, 151), (175, 227, 147), (172, 226, 143),
(168, 225, 139), (164, 223, 134), (160, 222, 130), (157, 221, 126), (153, 219, 122),
(149, 218, 118), (145, 217, 113), (140, 215, 108), (136, 214, 104), (131, 212, 99),
(127, 211, 94), (122, 209, 89), (118, 208, 85), (113, 206, 80), (109, 205, 75),
(105, 204, 67), (101, 202, 58), (96, 201, 50), (92, 199, 42), (88, 198, 33),
(84, 196, 25), (79, 195, 17), (75, 193, 8), (71, 192, 0), (70, 190, 0),
(70, 188, 0), (69, 187, 0), (68, 185, 0), (68, 183, 0), (67, 181, 0),
(66, 180, 0), (66, 178, 0), (65, 176, 0), (64, 173, 0), (63, 170, 0),
(61, 167, 0), (60, 164, 0), (59, 160, 1), (58, 157, 1), (56, 154, 1),
(55, 151, 1), (54, 148, 1), (52, 144, 1), (51, 140, 1), (49, 135, 1),
(48, 131, 1), (46, 127, 0), (45, 123, 0), (43, 118, 0), (42, 114, 0),
(40, 110, 0), (39, 107, 0), (38, 103, 0), (36, 100, 0), (35, 96, 0),
(34, 93, 0), (33, 89, 0), (31, 86, 0), (30, 82, 0), (29, 79, 0),
(196, 241, 255), (193, 240, 255), (190, 239, 255), (188, 238, 255), (185, 237, 255),
(182, 237, 255), (179, 236, 255), (177, 235, 255), (174, 234, 255), (171, 233, 255),
(166, 232, 255), (161, 230, 255), (156, 229, 255), (151, 227, 255), (147, 226, 255),
(142, 224, 255), (137, 223, 255), (132, 221, 255), (127, 220, 255), (113, 217, 255),
(99, 214, 255), (85, 212, 255), (71, 209, 255), (57, 206, 255), (43, 203, 255),
(29, 201, 255), (15, 198, 255), (1, 195, 255), (1, 194, 253), (1, 192, 251),
(1, 191, 249), (1, 189, 247), (0, 188, 246), (0, 186, 244), (0, 185, 242),
(0, 183, 240), (0, 182, 238), (0, 181, 236), (0, 179, 235), (0, 178, 233),
(0, 177, 231), (1, 175, 230), (1, 174, 228), (1, 173, 226), (1, 171, 225),
(1, 170, 223), (1, 167, 219), (1, 164, 214), (2, 160, 210), (2, 157, 206),
(2, 154, 201), (2, 151, 197), (3, 147, 193), (3, 144, 188), (3, 141, 184),
(3, 137, 179), (3, 134, 175), (2, 130, 170), (2, 127, 166), (2, 123, 161),
(2, 120, 157), (1, 116, 152), (1, 113, 148), (1, 109, 143), (145, 170, 255),
(142, 168, 255), (139, 166, 255), (136, 163, 255), (133, 161, 255), (129, 159, 255),
(126, 157, 255), (123, 154, 255), (120, 152, 255), (117, 150, 255), (111, 144, 255),
(104, 139, 255), (98, 133, 255), (91, 128, 255), (85, 122, 255), (78, 117, 255),
(72, 111, 255), (61, 105, 255), (59, 100, 255), (52, 95, 255), (46, 91, 255),
(39, 86, 255), (33, 81, 255), (26, 77, 255), (20, 72, 255), (13, 67, 255),
(7, 63, 255), (0, 58, 255), (0, 57, 252), (0, 56, 248), (1, 56, 245),
(1, 55, 242), (1, 54, 238), (1, 53, 235), (2, 53, 232), (2, 52, 228),
(2, 51, 225), (2, 50, 222), (2, 50, 220), (2, 49, 217), (2, 49, 215),
(2, 48, 212), (2, 48, 210), (2, 47, 207), (2, 47, 205), (2, 46, 202),
(2, 45, 199), (2, 45, 196), (2, 44, 193), (2, 43, 190), (1, 43, 188),
(1, 42, 185), (1, 41, 182), (1, 41, 179), (1, 40, 176), (1, 39, 173),
(1, 39, 170), (1, 38, 167), (1, 37, 164), (0, 37, 162), (0, 36, 159),
(0, 35, 156), (0, 35, 153), (0, 34, 150), (215, 178, 255), (211, 173, 255),
(207, 168, 255), (203, 164, 255), (199, 159, 255), (194, 154, 255), (190, 149, 255),
(186, 145, 255), (182, 140, 255), (178, 135, 255), (175, 131, 255), (173, 127, 255),
(170, 124, 255), (167, 120, 255), (165, 116, 255), (162, 112, 255), (159, 109, 255),
(157, 105, 255), (154, 101, 255), (152, 97, 255), (149, 92, 255), (147, 88, 255),
(145, 83, 255), (142, 79, 255), (140, 74, 255), (138, 70, 255), (135, 65, 255),
(133, 61, 255), (132, 54, 255), (130, 47, 255), (129, 41, 255), (128, 34, 255),
(126, 27, 255), (125, 20, 255), (124, 14, 255), (122, 7, 255), (121, 0, 255),
(119, 0, 251), (117, 0, 247), (116, 1, 244), (114, 1, 240), (112, 1, 236),
(110, 1, 232), (109, 2, 229), (106, 0, 227), (105, 2, 221), (103, 2, 216),
(100, 2, 211), (98, 2, 206), (95, 2, 201), (93, 1, 195), (90, 1, 190),
(88, 1, 185), (85, 1, 180), (83, 1, 175), (79, 1, 167), (75, 1, 158),
(71, 1, 150), (67, 1, 142), (63, 0, 133), (59, 0, 125), (55, 0, 117),
(51, 0, 108), (47, 0, 100),
)
DYNAMIC_8: tuple[int, ...] = (
0, 83, 63, 91, 210, 283, 401, 484,
)
DYNAMIC_16: tuple[int, ...] = (
0, 84, 63, 100, 118, 155, 191, 210, 246, 292, 310, 338, 411, 447, 492, 511,
)
DYNAMIC_32: tuple[int, ...] = (
0, 18, 85, 63, 64, 82, 91, 118, 128, 155, 173, 182, 201, 210, 237, 255,
265, 283, 310, 319, 320, 347, 374, 383, 393, 411, 429, 447, 448, 457, 475, 511,
)
DYNAMIC_64: tuple[int, ...] = (
0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
)
DYNAMIC_128: tuple[int, ...] = (
0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53,
55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72,
)
DYNAMIC_256: tuple[int, ...] = (
0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53,
55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72,
74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90,
92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108,
110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126,
129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145,
147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 160, 161, 162, 163,
165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181,
183, 184, 185, 186, 187, 188, 189, 190, 193, 194, 195, 196, 197, 198, 199, 200,
202, 203, 204, 205, 206, 207, 208, 209, 211, 212, 213, 214, 215, 216, 217, 218,
)
DYNAMIC_512: tuple[int, ...] = (
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271,
272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287,
288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303,
304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319,
320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335,
336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351,
352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367,
368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383,
384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399,
400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415,
416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431,
432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447,
448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463,
464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479,
480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495,
496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511,
)
# fmt: on
+4
View File
@@ -917,6 +917,9 @@ class Conversation:
secret: For channels: the 16-byte secret of the channel. MeshTerm uses it only to
show the public or private mark of the channel. ``None`` when it is not known.
contact: The contact, for direct conversations and rooms.
on_device: For channels: ``False`` when the device has no such channel. The Chat
picker shows the Public channel in this state when no slot has it. The row is
an offer to add the channel, and it never opens a chat.
"""
label: str
@@ -925,6 +928,7 @@ class Conversation:
channel_id: str | None = None
secret: bytes | None = None
contact: Contact | None = None
on_device: bool = True
@property
def peer(self) -> str | None:
+219
View File
@@ -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",
@@ -623,6 +831,17 @@ PREFERENCES: tuple[PrefSpec, ...] = (
maximum=86400,
unit="s",
),
PrefSpec(
key="show_mcoimg",
label="Show MCOimg",
help="Draw the pixel images of messages. Off: ^U shows one",
group="Display",
value_type="bool",
# On: a pixel image (MCOimg) is what its sender wanted the channel to see. Off: the
# chat shows only the line about the image, and ^U on the picked message opens it
# (JP, 2026-11-19). A 30 x 30 image takes 15 rows of the transcript.
default=True,
),
PrefSpec(
key="clock_report_days",
label="Clock report",
+225 -18
View File
@@ -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()
+53 -11
View File
@@ -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)
+12
View File
@@ -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}
+59 -17
View File
@@ -49,6 +49,13 @@ TX_POWER = 22
#: The map viewport that the demo opens on: the island of Montréal, with the two shores.
MAP_VIEW = (45.5150, -73.5900, 10)
#: The channel slots whose history draws from the one source of chance of the history. A
#: channel in a later slot draws from a source of its own, seeded by its name. Thus a
#: channel added to the demo never changes the rest of it: the shared source gives the same
#: numbers to everything after the conversations (the traces, the neighbours), and the
#: video's trace to Brossard keeps the route that it was made for.
_SHARED_SLOTS = 4
def seed(repo: Repository, now: datetime) -> None:
"""Write the full history of the demo into ``repo``.
@@ -128,8 +135,13 @@ def _conversations(
"""
messages: list[ChatMessage] = []
heard: list[traffic.Heard] = _greetings(rng)
shared = rng
for channel in world.CHANNELS:
identity = channel_identity(channel.name, channel.secret)
if channel.slot < _SHARED_SLOTS:
rng = shared
else:
rng = random.Random(f"meshterm-demo/history/{channel.name}")
for line in script.CHANNEL_LINES.get(channel.name, ()):
offset = -line.age_min * 60.0
sender = world.node(line.sender)
@@ -165,6 +177,7 @@ def _conversations(
created_at=when,
)
)
rng = shared
for peer_name, lines in script.DIRECT_LINES.items():
peer = world.node(peer_name)
for line in lines:
@@ -242,26 +255,55 @@ def _greetings(rng: random.Random) -> list[traffic.Heard]:
spoke a few minutes ago was also heard a few minutes ago, and the lists show it as
recent. The function adds one advert before the first line of each sitting in the last
two days (a sitting is a run of lines less than an hour apart).
The lines of the channels in the shared slots and of the direct messages draw from
``rng``, as they always did. The lines of a later channel come in a second pass, with a
source of their own (refer to :data:`_SHARED_SLOTS`). Thus a channel added to the demo
does not change the adverts, or anything after them, of the rest of the history.
"""
lines = [
line
for group in (script.CHANNEL_LINES, script.DIRECT_LINES)
for conversation in group.values()
for line in conversation
if line.sender != script.ME and line.age_min < 2 * 1440
]
slots = {channel.name: channel.slot for channel in world.CHANNELS}
def recent(conversations) -> list: # noqa: ANN001 - the values of a dict of lines
return [
line
for conversation in conversations
for line in conversation
if line.sender != script.ME and line.age_min < 2 * 1440
]
shared = recent(
[
lines
for name, lines in script.CHANNEL_LINES.items()
if slots.get(name, _SHARED_SLOTS) < _SHARED_SLOTS
]
+ list(script.DIRECT_LINES.values())
)
later = recent(
[
lines
for name, lines in script.CHANNEL_LINES.items()
if slots.get(name, _SHARED_SLOTS) >= _SHARED_SLOTS
]
)
last_advert: dict[str, float] = {}
heard: list[traffic.Heard] = []
for line in sorted(lines, key=lambda line: -line.age_min):
offset = -line.age_min * 60.0
if offset - last_advert.get(line.sender, -1e12) < 3600.0:
continue
sender = world.node(line.sender)
moment = offset - rng.uniform(60.0, 900.0)
heard.extend(
traffic.heard_flood(sender, moment, traffic.advert_body(sender), rng, advert=True)
)
last_advert[line.sender] = offset
for lines, source in (
(shared, rng),
(later, random.Random("meshterm-demo/history/greetings")),
):
for line in sorted(lines, key=lambda line: -line.age_min):
offset = -line.age_min * 60.0
if abs(offset - last_advert.get(line.sender, -1e12)) < 3600.0:
continue
sender = world.node(line.sender)
moment = offset - source.uniform(60.0, 900.0)
heard.extend(
traffic.heard_flood(
sender, moment, traffic.advert_body(sender), source, advert=True
)
)
last_advert[line.sender] = offset
return heard
+22
View File
@@ -64,6 +64,19 @@ class Line:
#: The sender name of our own lines.
ME = SELF.name
#: The pixel images (MCOimg) of the ``#mcoimg`` channel. The woodpecker is a real image
#: from an MCOimg encoder (30 x 30, 74 bytes). The leaf and the smiley are not compressed:
#: the small encoder of ``tests/test_mcoimg.py`` made them.
WOODPECKER = (
'im3:J!jBVY"9UPkugAX54#9BX:e"FM|cL0G|IS.@$q^=N:4D*B9d1d$450M>W/tOqmq`wqd..bJp|}'
"d/4v2vpi5BAZ9wD/B"
)
MAPLE_LEAF = (
'im3:g/U"eLAAAAAAAAC"BAAAAA5JAAAA_98(AA|;umiCv(umb$1I~lb$O=2AB=0maToIumb$8(umb$O=:EY'
"$O=0mDAumb$NAAAumbAAAAAYAAAAA@QAAAAAAAAAAA"
)
SMILEY = 'im3:g/U"aLdZSA%ZpL[c%Z>M5wqOW0Dz9Z3BfzEA'
#: The channel conversations, by channel name, oldest line first.
CHANNEL_LINES: dict[str, tuple[Line, ...]] = {
"Public": (
@@ -227,6 +240,15 @@ CHANNEL_LINES: dict[str, tuple[Line, ...]] = {
Line(at(0, "08:15"), "Léa", "It's 2 degrees this morning, dress warm!"),
Line(at(0, "08:18"), ME, "Too late, I'm already outside 🥶"),
),
"#mcoimg": (
Line(at(2, "19:05"), "Noor", "Is this the channel for the pixel art?"),
Line(at(2, "19:09"), "Kim-NDG", "Yes! Images go here, so that Public stays readable"),
Line(at(0, "08:50"), ME, MAPLE_LEAF),
Line(at(0, "09:10"), "Marie-Ève", "Nice leaf 🍁"),
Line(at(0, "10:20"), "Noor", SMILEY),
Line(at(0, "11:05"), "Kim-NDG", "Pileated woodpecker on Mont-Royal this morning!"),
Line(at(0, "11:06"), "Kim-NDG", WOODPECKER),
),
}
#: The direct conversations, by the name of the other node, oldest line first.
+3 -1
View File
@@ -610,12 +610,14 @@ class Channel:
#: The channels of the demo device. ``Family`` is a private channel, with a fixed secret
#: that is not derived from its name.
#: that is not derived from its name. ``#mcoimg`` carries pixel images (MCOimg), so that
#: the screenshots can show how the chat draws them.
CHANNELS: tuple[Channel, ...] = (
Channel(0, "Public", DEFAULT_PUBLIC_SECRET),
Channel(1, "#montreal", derive_secret("#montreal"), scope="yul"),
Channel(2, "#cycling", derive_secret("#cycling")),
Channel(3, "Family", hashlib.sha256(b"meshterm-demo/Family").digest()[:16]),
Channel(4, "#mcoimg", derive_secret("#mcoimg")),
)
#: Hashtag channels that other people of the mesh use and our device does not have. Our
+20 -1
View File
@@ -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
+42
View File
@@ -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.
+14 -1
View File
@@ -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`.
+7
View File
@@ -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.
+101 -7
View File
@@ -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.
+11
View File
@@ -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.
+271
View File
@@ -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),
)
+18 -3
View File
@@ -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,
+33
View File
@@ -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."""
+42
View File
@@ -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
+492
View File
@@ -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
+186 -41
View File
@@ -27,10 +27,11 @@ from rich.cells import cell_len
from rich.text import Text
from ..context import AppContext
from ..core import exitcodes, reactions
from ..core import exitcodes, mcoimg, reactions
from ..core.channels import (
CHANNEL_SLOT_PROBE_CAP,
DEFAULT_PUBLIC_SECRET,
MAX_CHANNELS,
MENTION,
channel_hash,
channel_identity,
@@ -71,6 +72,7 @@ from ..ui.widgets import (
format_age,
mention_chip,
mention_mark,
pixel_image_text,
self_chip,
)
from .base import Tool, ToolResult, register
@@ -79,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.
@@ -177,6 +180,14 @@ class ChatTool(Tool):
await self._delete_history(ctx, choice.value)
elif choice is CANCEL or choice is None: # Esc: back to the menu
return ToolResult(summary={"conversations": opened, "messages": shown})
elif not choice.on_device:
# A channel that the device does not have never opens: the device
# refuses each send on it. Enter asks to add it. After a refusal, the
# picker stays.
added = await _add_public_channel(ctx)
if added is not None:
shown = await open_chat(ctx, added)
opened += 1
else:
shown = await open_chat(ctx, choice)
opened += 1
@@ -410,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()
@@ -434,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,
)
@@ -623,23 +636,32 @@ def _enable_receive_debug() -> None:
def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
"""Change cached channel slots into channel conversations, and always offer Public (slot 0).
"""Change cached channel slots into channel conversations, and offer Public if it is absent.
The picker reads its channels through the session cache
(:meth:`~meshterm.services.device_state.DeviceState.channel_slots`). Thus it uses the one
slow slot probe again, and does not read each slot again each time that Chat opens.
This function maps that cached :class:`~meshterm.core.channel_probe.ChannelSlot` list
onto the :class:`~meshterm.core.models.Conversation` rows of the picker. When the
firmware reports no slot for channel 0 (the default public channel), this function
makes one. Thus there is always a place to chat. :func:`_read_channels` (the CLI path)
gives the same guarantee.
onto the :class:`~meshterm.core.models.Conversation` rows of the picker.
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, with Public at the
start when slot 0 is absent.
One :class:`~meshterm.core.models.Conversation` for each slot. A Public offer is at
the start when the device has no Public channel and a slot is free for it.
"""
conversations = [
Conversation(
@@ -651,32 +673,87 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
)
for slot in slots
]
if not any(c.channel_idx == 0 for c in conversations):
conversations.insert(
0,
Conversation(
label="Public",
is_channel=True,
channel_idx=0,
channel_id="slot:0",
secret=DEFAULT_PUBLIC_SECRET,
),
)
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 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, 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 _pick_free_slot, write_channel
add = await ctx.ui.dialog(
"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,
)
if not add:
return None
device = await ctx.device()
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())
# 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]:
"""Probe the channel slots, and return them as channel conversations.
This function always offers channel 0 (the default public channel), also when the
firmware reports no configured slots. Thus there is always a place to chat.
This function returns only the channels that are on the device. The device refuses a
send on an empty slot. Thus a listed channel that is not on the device is a promise that
fails at the first send (issue #36). ``channels join`` with the well-known key adds the
Public channel.
Args:
device: The connected device to probe.
Returns:
One :class:`~meshterm.core.models.Conversation` for each configured channel (at
least channel 0).
One :class:`~meshterm.core.models.Conversation` for each configured channel.
"""
conversations: list[Conversation] = []
for idx in range(CHANNEL_SLOT_PROBE_CAP):
@@ -696,17 +773,6 @@ async def _read_channels(device: Device) -> list[Conversation]:
secret=secret,
)
)
if not any(c.channel_idx == 0 for c in conversations):
conversations.insert(
0,
Conversation(
label="Public",
is_channel=True,
channel_idx=0,
channel_id="slot:0",
secret=DEFAULT_PUBLIC_SECRET,
),
)
return conversations
@@ -1003,7 +1069,11 @@ def _title(
else:
text.append(lane, style="muted")
text.append(" ")
if last is not None:
if not conversation.on_device:
# The preview lane explains the offer. Enter asks to add the channel (it never opens
# a chat), so the text ends with the ellipsis of a row that opens a prompt.
text.append("not on the device — Enter adds it…", style="muted")
elif last is not None:
text.append_text(_preview_text(last, key_of, name_of, us=us))
return text
@@ -1170,7 +1240,14 @@ def _append_body(
refer to :func:`~meshterm.ui.widgets.mention_chip`). It takes the node grey when the
name resolves to no node that we know. A mention of our own name (``us``) has the chip
of our key with a white label, as in the transcript.
A body that is a pixel image shows the short line of the transcript in place of its
Base91 text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`).
"""
image = mcoimg.recognize(body)
if image is not None:
text.append_text(pixel_image_text(image))
return
pos = 0
for match in MENTION.finditer(body):
if match.start() > pos:
@@ -1188,7 +1265,14 @@ def _append_body(
def _names_us(last: ChatMessage, us: tuple[str | None, str | None]) -> bool:
"""Whether the message ``last`` has a mention of our name (``us``)."""
name = us[0]
return bool(name) and any(match.group(1) == name for match in MENTION.finditer(last.text))
if not name:
return False
body = (
split_channel_sender(last.text)[1] if last.is_channel and not last.outbound else last.text
)
if mcoimg.recognize(body) is not None:
return False # the Base91 text of an image can hold an ``@[`` by chance
return any(match.group(1) == name for match in MENTION.finditer(body))
def _ago(when: Any) -> str:
@@ -1219,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
@@ -1246,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"))
@@ -1272,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"),
)
@@ -1319,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.
@@ -1335,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
@@ -1347,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,
@@ -1367,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.
+24 -3
View File
@@ -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():
+517 -75
View File
@@ -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:
+75 -10
View File
@@ -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)
+290 -23
View File
@@ -27,7 +27,7 @@ from rich.cells import cell_len
from rich.console import Group, RenderableType
from rich.text import Text
from ..core import links, parts, reactions
from ..core import links, mcoimg, parts, preferences, reactions
from ..core.channels import MENTION, split_channel_sender
from ..core.connection import ContactNotOnDeviceError
from ..core.events import EventKind, MeshEvent
@@ -42,6 +42,8 @@ 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
from .qr import QrScreen, qr_strip
@@ -63,11 +65,13 @@ from .widgets import (
mention_hop,
mention_mark,
picked_hop,
pixel_image_text,
self_chip,
)
if TYPE_CHECKING:
from ..context import AppContext
from ..core.mcoimg_decode import Picture
from ..services.message_paths import TraceWalk
from .map_render import MapMarker
from .map_screen import Locator
@@ -86,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
@@ -263,10 +270,10 @@ class ChatScreen(Screen):
else:
toggle = ("", "")
lane[1] = FPair(
"URL→QR",
"Image" if self._picked_picture() is not None else "URL→QR",
"url_code",
*toggle,
enabled=bool(self._picked_urls()),
enabled=self._picked_picture() is not None or bool(self._picked_urls()),
opp_enabled=lock is not None,
)
if self._locator is not None or self._pages is not None:
@@ -303,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.
@@ -357,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
@@ -434,6 +455,8 @@ class ChatScreen(Screen):
self._render_cache: dict | None = None
# The clock tolerance of the last render: which times show as corrected.
self._tolerance_s = clock_tolerance_s()
# Whether the last render drew the pixel images (the ``show_mcoimg`` preference).
self._show_images = True
# Strong references to the sends, resends, and spinner tickers that a key handler
# starts. The event loop holds only a *weak* reference. Thus the garbage collector
# can remove a task that nothing else names while it runs: the result is a message
@@ -484,7 +507,13 @@ class ChatScreen(Screen):
def _hint_with(self, lock: str) -> str:
"""The key hint, with the ``lock`` atom after ``^O author`` (or no atom for ``""``)."""
if self._selected is not None:
code = "^U QR" if self._picked_urls() else ""
code = (
"^U image"
if self._picked_picture() is not None
else "^U QR"
if self._picked_urls()
else ""
)
where = "^L map" if self._locate_target() is not None else ""
who = "^O author" if self._author_page() is not None else ""
react = "^E react" if self._can_react() else ""
@@ -753,8 +782,11 @@ class ChatScreen(Screen):
locks = self._pages.locked_keys() if self._pages is not None else frozenset()
tolerance = clock_tolerance_s()
self._tolerance_s = tolerance
images = bool(preferences.current().show_mcoimg)
self._show_images = images
if (
cache is not None
and cache["images"] == images
and cache["width"] == width
and cache["spacing"] == spacing
and cache["locks"] == locks
@@ -780,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] = []
@@ -806,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
@@ -814,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
@@ -860,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))
@@ -870,6 +905,7 @@ class ChatScreen(Screen):
"spacing": spacing,
"locks": locks,
"tolerance": tolerance,
"images": images,
"ids": ids,
"acked": ackeds,
"selected": selecteds,
@@ -985,6 +1021,10 @@ class ChatScreen(Screen):
:func:`~meshterm.ui.tui.render.render_hanging`). This is because a terminal opens
a link, and a user copies one, only while it is on one line.
A body that is a pixel image (MCOimg) shows a short line with its size, and the
image under it in half blocks, at the indent of the body (refer to
:mod:`~meshterm.ui.pixelart`).
Where the platform draws them (:data:`_URL_CODES`, the PicoCalc), each URL in the
body gets a QR code under it. The codes are side by side, at the indent of the
body. Thus the user can open a link from the handheld on a phone, and does not
@@ -997,10 +1037,11 @@ class ChatScreen(Screen):
"""
tolerance = self._tolerance_s
corrected = message.corrected(tolerance)
image = mcoimg.recognize(body)
stamp = message.shown_at(tolerance).astimezone()
prefix = Text()
prefix.append("❯ " if selected else " ", style="cursor" if selected else None)
if self._names_us(body):
if image is None and self._names_us(body):
prefix.append_text(mention_mark(self._self_key))
prefix.append(" ")
else:
@@ -1011,7 +1052,7 @@ class ChatScreen(Screen):
else:
prefix.append(" ")
prefix.append(" ")
body_text = self._body_text(body, message, selected=selected)
body_text = self._body_text(body, message, selected=selected, image=image)
whole = [m.span() for m in _WORD.finditer(body_text.plain) if links.urls(m.group())]
# A mention is a chip, and a chip never breaks across two lines.
whole += [(s.start, s.end) for s in body_text.spans if str(s.style) == PATH_INK]
@@ -1028,7 +1069,18 @@ class ChatScreen(Screen):
)
indent = prefix.cell_len
lines += render_hanging(Text(" " * indent), note, width, indent=indent)
urls = links.urls(body) if _URL_CODES else []
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:
indent = prefix.cell_len
art = pixelart.picture_text(picture, width - indent, indent=indent)
lines += render_lines(art, width, no_wrap=True)
urls = links.urls(body) if _URL_CODES and image is None else []
if urls:
lines += render_lines(qr_strip(urls, width, indent=prefix.cell_len), width)
badges = self._fold.badges(message) if self._fold is not None else []
@@ -1076,9 +1128,23 @@ class ChatScreen(Screen):
runs.append((start, len(text))) # the emoji never ends a line alone
return text, runs
def _body_text(self, body: str, message: ChatMessage, *, selected: bool) -> Text:
"""Build the styled body of a message: mentions in colour, then the glyphs at the end."""
text = self._render_mentions(body, selected=selected)
def _body_text(
self,
body: str,
message: ChatMessage,
*,
selected: bool,
image: mcoimg.PixelImage | None = None,
) -> Text:
"""Build the styled body of a message: mentions in colour, then the glyphs at the end.
A body that is a pixel image (``image``) shows a short line in place of its Base91
text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`).
"""
if image is not None:
text = pixel_image_text(image, style="cursor" if selected else "muted")
else:
text = self._render_mentions(body, selected=selected)
if message.outbound:
# A direct message shows its own delivery (spinner → ✓/✗, and a retry is
# possible). A channel broadcast has no ack. Thus mark only a channel message
@@ -1086,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(" ")
@@ -1175,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.
@@ -1253,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()
@@ -1447,6 +1627,46 @@ class ChatScreen(Screen):
message = self._messages[max(0, min(self._selected, len(self._messages) - 1))]
return links.urls(self._sender_and_body(message)[1])
def _picked_picture(self) -> Picture | None:
"""The pixel image of the selected message, or ``None`` (no selection, or no image)."""
if self._selected is None or not self._messages:
return None
message = self._messages[max(0, min(self._selected, len(self._messages) - 1))]
body = self._sender_and_body(message)[1]
return pixelart.decoded(body) if mcoimg.recognize(body) is not None else None
def _open_image(self) -> bool:
"""Show the pixel image of the selected message on a bare frame (^U).
The image is as large as the frame permits, with its caption and the text of the
message under it (refer to :class:`~meshterm.ui.pixelart.ImageScreen`). When the
``show_mcoimg`` preference is off, this is the way to see an image. When it is on,
this is the large view.
Returns:
``True`` when the selected message has an image, so that ^U does nothing more.
"""
picture = self._picked_picture()
if picture is None:
return False
if self._codes_open:
return True
message = self._messages[max(0, min(self._selected or 0, len(self._messages) - 1))]
body = self._sender_and_body(message)[1]
image = mcoimg.recognize(body)
caption = pixel_image_text(image) if image is not None else Text("")
self._codes_open = True
async def run() -> None:
try:
await self._session.run_screen(pixelart.ImageScreen(picture, caption, body))
finally:
self._codes_open = False
self._session.invalidate()
self._session.run_detached(run())
return True
def _open_codes(self) -> None:
"""Show the links of the selected message as QR codes on the share screen (^U).
@@ -1457,6 +1677,8 @@ class ChatScreen(Screen):
message, and when nothing is selected, the screen cannot know which message. One
share screen at a time.
"""
if self._open_image():
return
urls = self._picked_urls()
if not urls or self._codes_open:
return
@@ -1678,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
@@ -1926,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}"
@@ -2246,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,
@@ -2265,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
@@ -2278,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.
@@ -2564,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
+5 -1
View File
@@ -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"))
+11 -6
View File
@@ -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,
)
)
+85 -16
View File
@@ -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")
+5 -2
View File
@@ -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``).
+8 -2
View File
@@ -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
+2 -2
View File
@@ -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":
+5 -2
View File
@@ -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())
+4 -2
View File
@@ -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
+80 -4
View File
@@ -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()
+14 -2
View File
@@ -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
+11 -5
View File
@@ -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)
+238
View File
@@ -0,0 +1,238 @@
# SPDX-License-Identifier: Apache-2.0
"""Draw a pixel image (MCOimg) in the terminal with half blocks.
A cell is approximately two times as tall as it is wide. Thus a cell holds two pixels, one
above the other, and each pixel is square: ``▀`` with the top pixel as its colour and the
bottom pixel as its background. A transparent pixel shows the page. A cell with only the
bottom pixel is ``▄`` in that colour, and a cell with no pixel is a space.
An image keeps its own size: one pixel is one cell wide and half a cell tall (JP,
2026-11-20). A tall image scrolls with the transcript, as a long message does. The one
exception is an image that is wider than the lane: it becomes smaller to fit the width
(refer to :func:`fit`), because an image that is cut shows only a part of it. MCOimg
images are 10 to 30 pixels wide in practice, so this is rare.
On the picked message, ^U opens the image on a bare frame (:class:`ImageScreen`). There it
becomes larger by a whole number when the frame has the room, so each pixel stays square,
but it never becomes smaller than its own size. When the ``show_mcoimg`` preference is
off, the chat shows only the line about the image, and ^U is the way to see it.
"""
from __future__ import annotations
from functools import lru_cache
from typing import TYPE_CHECKING
from rich.console import Group
from rich.style import Style
from rich.text import Text
from .tui.screen import ScrollScreen
if TYPE_CHECKING:
from ..core.mcoimg_decode import Picture
RGB = tuple[int, int, int]
@lru_cache(maxsize=128)
def decoded(body: str) -> Picture | None:
"""The image of a message body, or ``None``. It keeps the last results.
A transcript paints many times while a message is visible. Each paint asks again, and
the cache answers without a second decode. The decoder is large, so it loads here, at
the first image, and not when the chat opens.
"""
from ..core.mcoimg_decode import decode
return decode(body)
def fit(
width: int, height: int, max_cols: int, max_rows: int | None = None, *, grow: bool = False
) -> tuple[int, int]:
"""The size in pixels at which to draw an image of ``width`` × ``height``.
The image keeps its proportions, and becomes smaller only to fit ``max_cols`` cells and
``max_rows`` rows (two pixels in each row). ``None`` rows is no limit on the height:
then only the width can make the image smaller. With ``grow``, an image that is smaller
than that space becomes larger by the largest whole number that fits. Thus each pixel
of the image is the same number of cells.
"""
scale = max_cols / width
if max_rows is not None:
scale = min(scale, (max_rows * 2) / height)
if scale >= 1:
scale = int(scale) if grow else 1
return max(1, int(width * scale)), max(1, int(height * scale))
def picture_text(
picture: Picture,
max_cols: int,
*,
indent: int = 0,
max_rows: int | None = None,
grow: bool = False,
) -> Text:
"""Draw ``picture`` as lines of half blocks, each after ``indent`` spaces.
Args:
picture: The decoded image.
max_cols: The most cells that the image can use, after the indent.
indent: The cells of page before each line (the indent of the body of a message).
max_rows: The most rows that the image can use, or ``None`` for no limit (the
image under a message: a tall image scrolls with the transcript).
grow: Make a small image larger to fill the space (refer to :func:`fit`).
Returns:
One :class:`~rich.text.Text` with a line for each two rows of pixels. It has no
newline after the last line.
"""
rows_cap = None if max_rows is None else max(1, max_rows)
cols, rows = fit(picture.width, picture.height, max(1, max_cols), rows_cap, grow=grow)
pixel = _sampler(picture, cols, rows)
text = Text(no_wrap=True)
for y in range(0, rows, 2):
if y:
text.append("\n")
text.append(" " * indent)
for x in range(cols):
top = pixel(x, y)
bottom = pixel(x, y + 1) if y + 1 < rows else None
text.append(*_cell(top, bottom))
return text
def _sampler(picture: Picture, cols: int, rows: int): # noqa: ANN202
"""A function that gives the pixel at ``(x, y)`` of the image drawn at ``cols`` × ``rows``.
A smaller image takes the nearest pixel of the original, so the colours stay the
colours of the palette. A mix of colours makes pixel art look blurred.
"""
width, height, pixels = picture.width, picture.height, picture.pixels
def pixel(x: int, y: int) -> RGB | None:
return pixels[(y * height // rows) * width + (x * width // cols)]
return pixel
def _cell(top: RGB | None, bottom: RGB | None) -> tuple[str, Style | None]:
"""The character and the style of one cell, for its top and bottom pixels."""
if top is None and bottom is None:
return " ", None
if top is None:
return "▄", Style(color=_hex(bottom))
if bottom is None:
return "▀", Style(color=_hex(top))
if top == bottom:
return "█", Style(color=_hex(top))
return "▀", Style(color=_hex(top), bgcolor=_hex(bottom))
def _hex(rgb: RGB | None) -> str:
"""The colour of a pixel as ``#rrggbb``."""
r, g, b = rgb # type: ignore[misc]
return f"#{r:02x}{g:02x}{b:02x}"
#: The cells of page at each side of the image on its bare frame.
_MARGIN_COLS = 2
#: The rows of page that the image and its caption leave free on the bare frame, in total.
#: The frame puts two fifths of the free rows above the block (refer to
#: :func:`~meshterm.ui.tui.frame.compose_bare`). With three, one row is above and two are
#: below. With two, the frame puts both below, and the image touches the top.
_MARGIN_ROWS = 3
class ImageScreen(ScrollScreen):
"""The pixel image of a message on a bare frame, as large as the frame permits (^U).
It is the share screen of a link (:class:`~meshterm.ui.qr.QrScreen`) for an image: no
header, no footer, no box, and no hint. Esc leaves, as it does everywhere. The image
fits itself to the frame at each paint, so a larger terminal shows a larger image.
Under it are the caption (its size and its colours) and the text of the message itself,
the ``im3:`` string that the sender transmitted. Thus the user can examine or copy the
text that made the image.
The image never touches the edges of the frame. It keeps :data:`_MARGIN_COLS` cells at
each side and at least one row above and below, as a QR code keeps its quiet zone. The
frame puts the block a little above the true centre, as it does for a code.
The image never becomes smaller than its own size (JP, 2026-11-20), except to fit the
width of the frame. On a frame that has the room, it grows by the largest whole number
that holds it with its text, or else alone. An image that is taller than the frame
(on the 14 rows of the Cardputer, a 30-pixel image) starts at the top of the page, and
the arrows scroll it.
The text of the message has no spaces, so it breaks at the width of the image area,
into a block of lines that is centred as one. The text never makes the image smaller
than the size that it has alone on the frame: the text can only stop it from growing.
When the frame cannot hold both, the image gets the rows, and the text is under it, a
page down, as the URL of a large QR code is.
"""
bare = True
def __init__(self, picture: Picture, caption: Text, raw: str = "") -> None:
"""Set up the screen for ``picture``, with ``caption`` and ``raw`` under it.
Args:
picture: The decoded image.
caption: The line about the image, as the chat shows it.
raw: The text of the message: the ``im3:`` string.
"""
super().__init__(Text(""), title="Image", floating=False)
self.picture = picture
self._caption = caption
self.raw = raw.strip()
def render_body(self, width: int) -> list[str]:
"""The image as large as the frame permits, then its caption and its text."""
# The frame notes its height before it asks for the body, as on the share screen.
rows = self._scroll_viewport
picture = self.picture
art_cols = max(1, width - 2 * _MARGIN_COLS)
raw_lines = _raw_lines(self.raw, art_cols, width)
# The margins, a blank row and the caption, then a blank row and the text.
alone = max(1, rows - _MARGIN_ROWS - 2)
art_rows = max(1, alone - (1 + len(raw_lines) if raw_lines else 0))
size = (picture.width, picture.height)
# The smallest that the image can be: its own size, or less only to fit the width.
least = fit(*size, art_cols)[0]
# The largest that it can be without the text: the text can stop it from growing,
# but never make it smaller than that.
alone_cols = max(least, fit(*size, art_cols, alone, grow=True)[0])
limit: int | None = art_rows
if fit(*size, art_cols, art_rows, grow=True)[0] < alone_cols:
limit = alone # the text goes a page down
if fit(*size, art_cols, limit, grow=True)[0] < least:
limit = None # taller than the frame: its own size, and the page scrolls
cols, _ = fit(*size, art_cols, limit, grow=limit is not None)
indent = max(0, (width - cols) // 2)
art = picture_text(picture, art_cols, indent=indent, max_rows=limit, grow=True)
caption = self._caption.copy()
caption.justify = "center"
parts = [art, Text(""), caption]
if raw_lines:
parts += [Text(""), *raw_lines]
self.replace_content(Group(*parts))
return super().render_body(width)
def _raw_lines(raw: str, max_cols: int, width: int) -> list[Text]:
"""The text of a message as a block of lines no wider than ``max_cols``, centred in ``width``.
The text is Base91 characters only, each one cell wide, so a line is a slice of it.
Each line has the same indent, so that the block is centred and its last line starts
under the others.
"""
if not raw:
return []
size = max(1, min(len(raw), max_cols))
indent = " " * max(0, (width - size) // 2)
return [
Text(indent + raw[start : start + size], style="muted", no_wrap=True)
for start in range(0, len(raw), size)
]
+25 -4
View File
@@ -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),
+131
View File
@@ -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
+4
View File
@@ -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
+13 -3
View File
@@ -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),
]
+195 -5
View File
@@ -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 ------------------------------------------------------------
+114
View File
@@ -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)
+2 -1
View File
@@ -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,
),
]
+3
View File
@@ -851,7 +851,10 @@ _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
"🏆": "★", # trophy case: the best/winner star
"⌨": "❯", # command line: the prompt pointer
+7 -1
View File
@@ -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"),
],
)
+5 -1
View File
@@ -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}",
+54 -2
View File
@@ -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:
+12 -2
View File
@@ -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:
+50 -7
View File
@@ -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
+16 -4
View File
@@ -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
+30
View File
@@ -64,6 +64,7 @@ from .theme import glyph, mark_rgb, name_style, node_style, snr_style
if TYPE_CHECKING:
from ..core.discovery import DiscoveredDevice
from ..core.mcoimg import PixelImage
from ..core.regions import Scope
@@ -98,6 +99,35 @@ def channel_glyph(name: str, secret: bytes | None) -> str:
#: The concept icon for a region (the scope of a flood). Refer to the icon table of ``CLAUDE.md``.
REGION_ICON = "🔖"
#: The concept icon for a pixel image in a message (MCOimg). It is the palette of pixel
#: art. ``🖼`` is not used, because it is a text character by default and terminals do
#: not agree about its width.
IMAGE_ICON = "🎨"
def pixel_image_text(image: PixelImage, *, style: str | None = "muted") -> Text:
"""The short line that a message shows in place of the Base91 text of a pixel image.
The Base91 text is noise to the user. Its ``@[``, ``]``, and ``.`` characters can also
look like a mention or a link. Thus the chat and the Messages list show this line in
its place: ``🎨 image · 24×24 · 16 colours`` when MeshTerm can read the header of the
image, or else the version of the format.
Args:
image: The image that :func:`~meshterm.core.mcoimg.recognize` found in the body.
style: The style of the line: ``muted``, or ``cursor`` on the selected message.
"""
parts = [f"{glyph(IMAGE_ICON)} image"]
if image.width is not None and image.height is not None:
parts.append(f"{image.width}×{image.height}")
if image.colours is not None:
parts.append(f"{image.colours} colours")
elif image.version is None:
parts.append("MCOimg v1/v2")
else:
parts.append(f"MCOimg v{image.version}")
return Text(" · ".join(parts), style=style)
def scope_text(scope: Scope | None, *, bare: bool = False) -> Text:
"""The only rendering of the scope of a flood, for each surface that states one.
+1
View File
@@ -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/<set>/`. 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/` |
+15 -1
View File
@@ -6,7 +6,8 @@
The script runs MeshTerm three times, one time for each set: ``terminal`` (the desktop, in
an 80×24 terminal), ``cardputer-zero``, and ``picocalc-lyra``. Each run uses ``--demo``
(refer to :mod:`meshterm.demo`) and types the same keys: it opens the chat on Public,
the paths of a message, and the map, and it saves each screen as a PNG. The result is
the paths of a message, the map, and the pixel images of the ``#mcoimg`` channel, and it
saves each screen as a PNG. The result is
``DIR/<set>/<screen>.png`` (``DIR`` is ``docs/screenshots`` by default).
The script also draws each wordmark of the startup splash (``meshterm/assets/splash``) as
@@ -361,6 +362,19 @@ def _tour(capture: Capture, type_text: Callable[[str], None], save: Callable[[st
press("enter")
capture.settle(quiet=4.0, timeout=120.0)
save("map")
# The pixel images of the #mcoimg channel, from the main menu.
press(text="w", ctrl=True)
capture.settle(quiet=0.8)
press("escape")
typed("chat")
press("enter")
capture.wait_for("Public")
capture.settle()
typed("mcoimg")
press("enter")
capture.wait_for("#mcoimg")
capture.settle(quiet=1.5)
save("mcoimg")
# --------------------------------------------------------------------------- drawing
+85
View File
@@ -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("<i2").tobytes()
with wave.open(str(target), "wb") as out:
out.setnchannels(1)
out.setsampwidth(2)
out.setframerate(rate)
out.writeframes(data)
def main() -> 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()
+4 -4
View File
@@ -356,7 +356,7 @@ def _tour(p: Presenter) -> None:
print("the main menu", flush=True)
p.camera.roll()
p.hold(3.0)
p.hold(2.5)
print("the chat, and the paths of a message", flush=True)
p.type("chat")
@@ -405,7 +405,7 @@ def _tour(p: Presenter) -> None:
# Dave answers a few seconds later (``meshterm.demo.script.REPLIES``). His answer
# mentions our node, so it has our star.
p.wait_for("be there at 2", timeout=30)
p.hold(3.5)
p.hold(3.0)
print("a trace", flush=True)
_menu(p, "trace t")
@@ -415,14 +415,14 @@ def _tour(p: Presenter) -> None:
p.hold(0.4)
p.key("enter")
p.wait_for("Trace — Brossard")
p.hold(2.0)
p.hold(1.5)
p.key("enter", pause=0.0)
p.wait_for("Per-hop medians", timeout=30)
p.hold(1.0)
# The history stores walks of one byte for each hop. Thus this walk of two bytes is new,
# and its records go to the trophy case.
if p.shows("new record"):
p.hold(3.0)
p.hold(2.5)
p.key("enter", pause=0.0) # Close
p.hold(1.5)
p.key("pagedown", pause=0.0)
+42
View File
@@ -0,0 +1,42 @@
# MCOimg test vectors
These two files are the test vectors of version 3 of the MCOimg pixel image format. They
come without change from the folder `docs/mcoimg-js/tests/` of the meshcore-open repository
([HDDen/meshcore-open](https://github.com/HDDen/meshcore-open), a fork of
[zjs81/meshcore-open](https://github.com/zjs81/meshcore-open)):
- `v3-js-decoder-fixtures.json`: 39 images, one or more for each container, block
algorithm, scan order, and local palette form.
- `v3-js-encoder-fixtures.json`: 6 images that the JavaScript encoder of the format made.
Each vector has the `im3:` text of an image, its size, its palette profile, and the palette
reference of each pixel. `tests/test_mcoimg.py` decodes each text and compares the result.
MeshTerm does not include these files in its package.
The files are under the MIT licence of the meshcore-open repository:
<!-- ste: off -->
MIT License
Copyright (c) 2025 zjs81
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<!-- ste: on -->
@@ -0,0 +1,847 @@
{
"schema": 1,
"generator": "docs/mcoimg-js/tests/v3-decoder-fixtures.js",
"fixtures": [
{
"name": "rawGlobal",
"bodyBase64": "egGNAEK+AQ==",
"appPayloadBase64": "E3oBjQBCvgE=",
"text": "im3:g/5WjAL`NA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
1,
2,
3,
3,
2,
1,
0
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawGlobal"
},
{
"name": "rawLocal",
"bodyBase64": "egGNECLWAg==",
"appPayloadBase64": "E3oBjRAi1gI=",
"text": "im3:g/5W6LuitA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
3,
0,
3,
0
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "compactRle",
"bodyBase64": "egGNICCmIQ==",
"appPayloadBase64": "E3oBjSAgpiE=",
"text": "im3:g/5W[Wqi^F",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
3,
3,
0,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "compactRle"
},
{
"name": "compactSparse",
"bodyBase64": "egGNMABOIgA=",
"appPayloadBase64": "E3oBjTAATiIA",
"text": "im3:g/5WNi+>CGA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
3,
0,
0,
3,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "compactSparse"
},
{
"name": "biColorMask",
"bodyBase64": "egGNQMJa",
"appPayloadBase64": "E3oBjUDCWg==",
"text": "im3:g/5Wktw8F",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
3,
0,
3,
0
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "biColorMask"
},
{
"name": "rowRepeat",
"bodyBase64": "egGNUCDW",
"appPayloadBase64": "E3oBjVAg1g==",
"text": "im3:g/5W74qiN",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
0,
3,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "rowRepeat"
},
{
"name": "lzPixels",
"bodyBase64": "egGNYCAWHw==",
"appPayloadBase64": "E3oBjWAgFh8=",
"text": "im3:g/5W](qiqF",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
0,
3,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "lzPixels"
},
{
"name": "quadtree",
"bodyBase64": "egEEB2J9",
"appPayloadBase64": "E3oBBAdifQ==",
"text": "im3:g/N\"qC8]D",
"width": 2,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
3,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "quadtree"
},
{
"name": "bitplanesRawAndRle",
"bodyBase64": "egGNgGByqm0=",
"appPayloadBase64": "E3oBjYBgcqpt",
"text": "im3:g/5Wl\"#zslb",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
1,
0,
1,
2,
3,
2,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "bitplanes"
},
{
"name": "adaptiveBitplanesRaw",
"bodyBase64": "egGNkCCmBQ==",
"appPayloadBase64": "E3oBjZAgpgU=",
"text": "im3:g/5W6Lri\"A",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
3,
0,
3,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "directBitplanes",
"bodyBase64": "egiNoEAVM3g=",
"appPayloadBase64": "E3oIjaBAFTN4",
"text": "im3:g/WX[Wyd~I8",
"width": 4,
"height": 2,
"paletteProfile": "grayscale8",
"pixels": [
0,
1,
2,
3,
4,
5,
6,
7
],
"transparentColor": null,
"container": "block",
"algorithm": "directBitplanes"
},
{
"name": "compactRowDelta",
"bodyBase64": "egGNsCCmAA==",
"appPayloadBase64": "E3oBjbAgpgA=",
"text": "im3:g/5WNiriKA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
0,
3,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "compactRowDelta"
},
{
"name": "directRowDelta",
"bodyBase64": "egiNwADRAA==",
"appPayloadBase64": "E3oIjcAA0QA=",
"text": "im3:g/WXkt6FNA",
"width": 4,
"height": 2,
"paletteProfile": "grayscale8",
"pixels": [
0,
1,
2,
3,
0,
1,
2,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "directRowDelta"
},
{
"name": "rowDelta",
"bodyBase64": "egGN0CBGAw==",
"appPayloadBase64": "E3oBjdAgRgM=",
"text": "im3:g/5W74ri0A",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
3,
0,
3,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "rowDelta"
},
{
"name": "varUintRle",
"bodyBase64": "egGN4CA2UMAA",
"appPayloadBase64": "E3oBjeAgNlDAAA==",
"text": "im3:g/5W](riJOFBA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
3,
3,
0,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "varUintRle"
},
{
"name": "varUintSparse",
"bodyBase64": "egGN8AAWCBAQCAA=",
"appPayloadBase64": "E3oBjfAAFggQEAgA",
"text": "im3:g/5WO?+hmB2WgAA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
3,
0,
0,
3,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "varUintSparse"
},
{
"name": "adaptiveLegacyRle",
"bodyBase64": "egEdkCDOBg==",
"appPayloadBase64": "E3oBHZAgzgY=",
"text": "im3:g/5WeLs?RB",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
3,
3,
3,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "adaptiveShortRle",
"bodyBase64": "egEdkCCeNg==",
"appPayloadBase64": "E3oBHZAgnjY=",
"text": "im3:g/5WeLs?2J",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
0,
0,
3,
3,
3,
0,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "adaptiveConstantZero",
"bodyBase64": "egEdkCA+",
"appPayloadBase64": "E3oBHZAgPg==",
"text": "im3:g/5WeLs?D",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
0,
0,
0,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "adaptiveConstantOne",
"bodyBase64": "egEdkCB+",
"appPayloadBase64": "E3oBHZAgfg==",
"text": "im3:g/5WeLs?H",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
3,
3,
3,
3,
3,
3,
3,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "adaptiveSparseOne",
"bodyBase64": "egEdkCC+CQE=",
"appPayloadBase64": "E3oBHZAgvgkB",
"text": "im3:g/5WeLs?%uA",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
0,
0,
0,
3,
0
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "adaptiveSparseZero",
"bodyBase64": "egEdkCD+CQE=",
"appPayloadBase64": "E3oBHZAg/gkB",
"text": "im3:g/5WeLs?*uA",
"width": 8,
"height": 1,
"paletteProfile": "master4",
"pixels": [
3,
0,
3,
3,
3,
3,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "adaptiveBitplanes"
},
{
"name": "boundsBlock",
"bodyBase64": "egEMQgQEBATgAQ==",
"appPayloadBase64": "E3oBDEIEBAQE4AE=",
"text": "im3:g/N\"UXbLi\"+>BA",
"width": 4,
"height": 4,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
0,
3,
3,
0,
0,
3,
3,
0,
0,
0,
0,
0
],
"transparentColor": null,
"container": "boundsBlock",
"algorithm": "compactRle"
},
{
"name": "compactBoundsBlock",
"bodyBase64": "egEMYFTlAQ==",
"appPayloadBase64": "E3oBDGBU5QE=",
"text": "im3:g/N\"+h\"OPA",
"width": 4,
"height": 4,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
0,
1,
2,
0,
0,
3,
1,
0,
0,
0,
0,
0
],
"transparentColor": null,
"container": "compactBoundsBlock",
"algorithm": "rawGlobal"
},
{
"name": "regions",
"bodyBase64": "egEMgAQEBAQEtQE=",
"appPayloadBase64": "E3oBDIAEBAQEBLUB",
"text": "im3:g/N\"CtbLi\"lB/EA",
"width": 4,
"height": 4,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
0,
1,
3,
0,
0,
3,
1,
0,
0,
0,
0,
0
],
"transparentColor": null,
"container": "regions",
"algorithm": "rawGlobal"
},
{
"name": "compactRegionsSharedDelta",
"bodyBase64": "egGNEMqDGrUAQAI=",
"appPayloadBase64": "E3oBjRDKgxq1AEAC",
"text": "im3:g/5W6LdV9x\"AdZA",
"width": 4,
"height": 2,
"paletteProfile": "master4",
"pixels": [
1,
3,
3,
1,
3,
1,
1,
3
],
"transparentColor": null,
"container": "compactRegionsStream",
"algorithm": "rawGlobal"
},
{
"name": "solidBackground",
"bodyBase64": "egEAwg==",
"appPayloadBase64": "E3oBAMI=",
"text": "im3:g/LAU)",
"width": 1,
"height": 1,
"paletteProfile": "master4",
"pixels": [
2
],
"transparentColor": null,
"container": "solidBackground",
"algorithm": "rawGlobal"
},
{
"name": "solidRects",
"bodyBase64": "egEM4GBV",
"appPayloadBase64": "E3oBDOBgVQ==",
"text": "im3:g/N\",>M8C",
"width": 4,
"height": 4,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0,
0,
3,
3,
0,
0,
3,
3,
0,
0,
0,
0,
0
],
"transparentColor": null,
"container": "solidRects",
"algorithm": "rawGlobal"
},
{
"name": "implicitWhiteSolid",
"bodyBase64": "ekEEwA==",
"appPayloadBase64": "E3pBBMA=",
"text": "im3:g/)FCtB",
"width": 2,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
0,
0,
0
],
"transparentColor": null,
"container": "solidBackground",
"algorithm": "rawGlobal"
},
{
"name": "transparentSolid",
"bodyBase64": "eoEEwgM=",
"appPayloadBase64": "E3qBBMID",
"text": "im3:g/iLnuHA",
"width": 2,
"height": 2,
"paletteProfile": "master4",
"pixels": [
2,
2,
2,
2
],
"transparentColor": 3,
"container": "solidBackground",
"algorithm": "rawGlobal"
},
{
"name": "scanV",
"bodyBase64": "ehGJIGByEGQQ",
"appPayloadBase64": "E3oRiSBgchBkEA==",
"text": "im3:g/DY@WhN[CFXA",
"width": 3,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
2,
0,
1,
3,
1
],
"transparentColor": null,
"container": "block",
"algorithm": "compactRle"
},
{
"name": "scanS",
"bodyBase64": "eiGJIGByEGQQ",
"appPayloadBase64": "E3ohiSBgchBkEA==",
"text": "im3:g/oZ@WhN[CFXA",
"width": 3,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
1,
2,
1,
0,
3
],
"transparentColor": null,
"container": "block",
"algorithm": "compactRle"
},
{
"name": "scanSV",
"bodyBase64": "ejGJIGByEGQQ",
"appPayloadBase64": "E3oxiSBgchBkEA==",
"text": "im3:g/=a@WhN[CFXA",
"width": 3,
"height": 2,
"paletteProfile": "master4",
"pixels": [
0,
3,
0,
1,
2,
1
],
"transparentColor": null,
"container": "block",
"algorithm": "compactRle"
},
{
"name": "paletteBitmap",
"bodyBase64": "egENEJI0",
"appPayloadBase64": "E3oBDRCSNA==",
"text": "im3:g/5WaL%ZD",
"width": 4,
"height": 1,
"paletteProfile": "master4",
"pixels": [
0,
3,
3,
0
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "paletteSortedDelta",
"bodyBase64": "egINEDJBIgM=",
"appPayloadBase64": "E3oCDRAyQSID",
"text": "im3:g/%WaL&GDzB",
"width": 4,
"height": 1,
"paletteProfile": "master8",
"pixels": [
0,
2,
4,
2
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "paletteRangeRuns",
"bodyBase64": "egINENJAFTk=",
"appPayloadBase64": "E3oCDRDSQBU5",
"text": "im3:g/%WaL4E)wc",
"width": 4,
"height": 1,
"paletteProfile": "master8",
"pixels": [
0,
1,
5,
6
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "paletteBankBitmaps",
"bodyBase64": "eg8NEPIrEAAAAAAAAAAgAAAAAAAAAFA=",
"appPayloadBase64": "E3oPDRDyKxAAAAAAAAAAIAAAAAAAAABQ",
"text": "im3:g/>XaLT(<CAAAAAAAAQAAAAAAAuWB",
"width": 4,
"height": 1,
"paletteProfile": "dynamicGlobal512",
"pixels": [
1,
130,
1,
130
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "paletteOrderedSingleBank",
"bodyBase64": "eg8NEPInWJBEZA==",
"appPayloadBase64": "E3oPDRDyJ1iQRGQ=",
"text": "im3:g/>XaL$stPmGlE",
"width": 4,
"height": 1,
"paletteProfile": "dynamicGlobal512",
"pixels": [
193,
201,
209,
201
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
},
{
"name": "paletteOrderedMultiBank",
"bodyBase64": "eg8NEPI3LBAUDAly",
"appPayloadBase64": "E3oPDRDyNywQFAwJcg==",
"text": "im3:g/>XaL$s+HUc,LJo",
"width": 4,
"height": 1,
"paletteProfile": "dynamicGlobal512",
"pixels": [
1,
130,
3,
132
],
"transparentColor": null,
"container": "compactBlock",
"algorithm": "rawLocal"
}
]
}
@@ -0,0 +1,792 @@
{
"schema": 1,
"generator": "mcoimg-v3-codec.global.js Normal/High encoder",
"fixtures": [
{
"name": "mono-checker-normal",
"width": 9,
"height": 7,
"paletteProfile": "mono",
"pixels": [
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0,
1,
0
],
"compressionLevel": "normal",
"maxRegions": 16,
"bodyBase64": "QAAhY6DkMwE=",
"appPayloadBase64": "E0AAIWOg5DMB",
"text": "im3:TAYL>iBNGbA",
"byteLength": 8,
"charLength": 15,
"subtypeVersion": 19,
"packetNonce": 64,
"mode": "extended",
"scan": "h",
"container": "block",
"algorithm": "lzPixels",
"backgroundColor": 0,
"regionCount": 0
},
{
"name": "master8-sparse-high",
"width": 12,
"height": 10,
"paletteProfile": "master8",
"pixels": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
1,
2,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
1,
2,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
3,
3,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
3,
4,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
3,
3,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
"compressionLevel": "high",
"maxRegions": 32,
"bodyBase64": "QUKtFJoQMSMRmAGWkhEC",
"appPayloadBase64": "E0FCrRSaEDEjEZgBlpIRAg==",
"text": "im3:CDecxOjD61JY`R)0nxQA",
"byteLength": 15,
"charLength": 24,
"subtypeVersion": 19,
"packetNonce": 65,
"mode": "regionsBg",
"scan": "h",
"container": "compactRegionsStream",
"algorithm": "rawGlobal",
"backgroundColor": 0,
"regionCount": 2
},
{
"name": "master16-regions-high",
"width": 16,
"height": 12,
"paletteProfile": "master16",
"pixels": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
2,
2,
0,
0,
0,
1,
3,
3,
1,
0,
0,
0,
0,
0,
0,
0,
2,
2,
0,
0,
0,
1,
3,
3,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
4,
4,
4,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
5,
5,
5,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
5,
6,
5,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
5,
5,
5,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
4,
4,
4,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
"compressionLevel": "high",
"maxRegions": 32,
"bodyBase64": "QkO9JZpExIyIAWbAUQApIxZEwCkHLkI=",
"appPayloadBase64": "E0JDvSWaRMSMiAFmwFEAKSMWRMApBy5C",
"text": "im3:<Fmcxa[ZuiCM1(7([Azj,H)A3@QQ&A",
"byteLength": 23,
"charLength": 34,
"subtypeVersion": 19,
"packetNonce": 66,
"mode": "regionsBg",
"scan": "h",
"container": "compactRegionsStream",
"algorithm": "rawGlobal",
"backgroundColor": 0,
"regionCount": 3
},
{
"name": "grayscale16-gradient-high",
"width": 16,
"height": 8,
"paletteProfile": "grayscale16",
"pixels": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
2,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
2,
3,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
2,
3,
4,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
2,
3,
4,
5,
7,
8,
9,
10,
11,
12,
13,
14,
15,
0,
1,
2,
3,
4,
5,
6
],
"compressionLevel": "high",
"maxRegions": 16,
"bodyBase64": "Qwa9wwBChsoOU5fb//////8=",
"appPayloadBase64": "E0MGvcMAQobKDlOX2///////",
"text": "im3:7IFX6vYL3X/Um]T=B\"B\"B\"B",
"byteLength": 17,
"charLength": 27,
"subtypeVersion": 19,
"packetNonce": 67,
"mode": "extended",
"scan": "h",
"container": "block",
"algorithm": "directRowDelta",
"backgroundColor": 0,
"regionCount": 0
},
{
"name": "master8-transparent-normal",
"width": 8,
"height": 8,
"paletteProfile": "master8",
"transparentColor": 0,
"pixels": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
0,
0,
1,
2,
2,
2,
2,
1,
0,
0,
1,
2,
3,
3,
2,
1,
0,
0,
1,
2,
3,
3,
2,
1,
0,
0,
1,
2,
2,
2,
2,
1,
0,
0,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
"compressionLevel": "normal",
"maxRegions": 16,
"bodyBase64": "RMIcbUjaONR6LWPLtB4=",
"appPayloadBase64": "E0TCHG1I2jjUei1jy7Qe",
"text": "im3:qLHR(<=5\"J)])jv,i{A",
"byteLength": 14,
"charLength": 23,
"subtypeVersion": 19,
"packetNonce": 68,
"mode": "rowDelta",
"scan": "h",
"container": "compactBoundsBlock",
"algorithm": "rowDelta",
"backgroundColor": 0,
"regionCount": 0
},
{
"name": "dynamic-global8-high",
"width": 10,
"height": 8,
"paletteProfile": "dynamicGlobal8",
"pixels": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
83,
83,
83,
0,
0,
63,
63,
63,
0,
0,
83,
91,
83,
0,
0,
63,
210,
63,
0,
0,
83,
83,
83,
0,
0,
63,
63,
63,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
283,
283,
283,
0,
0,
401,
401,
401,
0,
0,
283,
484,
283,
0,
0,
401,
484,
401,
0,
0,
283,
283,
283,
0,
0,
401,
401,
401,
0
],
"compressionLevel": "high",
"maxRegions": 32,
"bodyBase64": "RUmlM5oQEUkGwaJEhBAVpYdgVfEhAA==",
"appPayloadBase64": "E0VJpTOaEBFJBsGiRIQQFaWHYFXxIQA=",
"text": "im3:ZO{cdkjDBw<I\"eMYqugYiFXeo|QAA",
"byteLength": 22,
"charLength": 33,
"subtypeVersion": 19,
"packetNonce": 69,
"mode": "regionsBg",
"scan": "h",
"container": "compactRegionsStream",
"algorithm": "rawGlobal",
"backgroundColor": 0,
"regionCount": 4
}
]
}
+202
View File
@@ -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) == []
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more