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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guides/board-name.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Case is kept as you type it. mDNS and DHCP compare names without case.

| Where | Default | A new name is kept in |
|---|---|---|
| ESP32 | `omnipython-` and the last three bytes of `machine.unique_id()` in hex | NVS, namespace `omnipython`, key `board_name` |
| ESP32 | `omnipython-` and the last three bytes of its Wi-Fi MAC in hex (`machine.unique_id()` on a build without Wi-Fi) | NVS, namespace `omnipython`, key `board_name` |
| Other MicroPython boards | the same | `/omnipython.json` (`/flash/omnipython.json` on an STM32) |
| CircuitPython | `omnipython-` and the last three bytes of `microcontroller.cpu.uid` | `OMNIPYTHON_BOARD_NAME` in `settings.toml` |
| A desktop | the computer's name | the `OMNIPYTHON_BOARD_NAME` environment variable, for this process |
Expand Down
9 changes: 6 additions & 3 deletions docs/guides/vtterm.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,12 @@ lists every character of the set.

## Type on a keyboard

`vtterm.keyboards` reads a USB keyboard on the board's host port and a BLE
keyboard, each found on its own and found again after it's unplugged or
switched off. `vtterm.keys.key_bytes` turns each key press into the bytes a
`vtterm.keyboards` reads a USB keyboard on the board's host port, a BLE
keyboard, and the display's own keys: a desktop window's keyboard, or the
one in the browser [showing the display](show-a-display-in-a-browser.md).
Each is found on its own, and the USB and BLE ones are found again after
they're unplugged or switched off. While the display's keys come here,
LVGL's focused widget doesn't get them (`display_driver.take_keys`). `vtterm.keys.key_bytes` turns each key press into the bytes a
VT100 sends; [Keys](../reference/vtterm-keys.md) lists them.

```python
Expand Down
8 changes: 6 additions & 2 deletions docs/guides/wifi.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,12 @@ The network the board is on is `connected`, and registering chooses it when
nothing else is chosen. A network the board knows (from `secrets.py`,
`settings.toml`, or a join before) is `available`, and choosing it joins it.
A new secured network `needs pairing`: `pair()` with its password joins it,
or raises `ValueError("Wrong password for Cafe")`. A network it joins is
remembered with the others, so `connect()` joins it at the next boot.
or raises `ValueError("Wrong password for Cafe. Back on Home")`. Joining
leaves the network the board was on, so when the new one fails it goes back
there, and the message says whether it got back. A board you reach over
Wi-Fi, through WebREPL or a browser display, then stays in reach to show you
the error. A network it joins is remembered with the others, so `connect()`
joins it at the next boot.

A scan only runs when something asks for one, because it holds the board.
Between scans, each `endpointkit.poll()` notices within three seconds when
Expand Down
14 changes: 13 additions & 1 deletion lib/boarddev.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ def name(new=_GET):
medialink and hmilink.

With no saved name, a board is ``omnipython-`` plus the last three bytes
of its unique ID in hex (``omnipython-a1b2c3``), a desktop is the
of its unique ID in hex (``omnipython-a1b2c3``; of its Wi-Fi MAC on an
ESP32), a desktop is the
computer's name, and a browser is ``omnipython-`` plus six random hex
digits, new on each page load.

Expand Down Expand Up @@ -519,6 +520,17 @@ def _name_default(impl, platform):
import microcontroller

return _name_from_id(microcontroller.cpu.uid)
if platform == "esp32":
# On a chip with an 802.15.4 radio (C6, H2, S31) unique_id() is the
# 8-byte EUI-64 cut to six bytes, ending ff:fe and one byte of the
# MAC, so boards from one batch would share a name. The station's MAC
# is the base MAC, which is unique_id() on every other ESP32.
try:
import network

return _name_from_id(network.WLAN(network.STA_IF).config("mac"))
except (ImportError, AttributeError):
pass # firmware without Wi-Fi: the H2, or a build with network left out
import machine

return _name_from_id(machine.unique_id())
Expand Down
5 changes: 3 additions & 2 deletions lib/boarddev.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ def name(new: str | None) -> None:
"""The board's name, or give it a new one.

With no argument, the name: a saved one, else `omnipython-` and the last
three bytes of the unique ID on a board, the computer's name on a desktop,
or `omnipython-` and six random hex digits in a browser. With a string,
three bytes of the unique ID on a board (of the Wi-Fi MAC on an ESP32), the
computer's name on a desktop, or `omnipython-` and six random hex digits
in a browser. With a string,
save it as the new name; with None, forget a saved one.

Raises:
Expand Down
33 changes: 32 additions & 1 deletion lib/display_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,34 @@ def _poll(self):

_virtual_peers = {}
_virtual_pending = {}
_key_takers = [] # newest last: it gets the keys


def take_keys(callback):
"""Send the keys typed on the display itself to *callback* instead of LVGL.

The display's own keys are the ones its host input brings: a desktop
window's keyboard, or the browser showing a
`RemoteDisplay <displaydev.remotedisplay.RemoteDisplay>`. A terminal
takes them while it's open, so typing reaches it and not the focused
widget. ``callback(event)`` gets each ``events.Key``, down and up, from
LVGL's input timer. The newest taker gets them until `give_back_keys`.

Returns:
bool: True when the display has a host input to take keys from;
False, and nothing is taken, when it has none (a panel with only
touch).
"""
if not _virtual_peers:
return False
_key_takers.append(callback)
return True


def give_back_keys(callback):
"""Stop sending the display's keys to *callback* (from `take_keys`)."""
if callback in _key_takers:
_key_takers.remove(callback)


class VirtualDevices:
Expand Down Expand Up @@ -550,7 +578,10 @@ def _route(self, event):
self._vd_encoder.add_event(event)
_wheel_navigate_cb(event)
elif event.type in (events.KEYDOWN, events.KEYUP):
self._vd_keypad.add_event(event)
if _key_takers:
_key_takers[-1](event)
else:
self._vd_keypad.add_event(event)
elif event.type == events.QUIT:
# Window-close reaches here (e.g. windisplay.WinDisplay's
# WM_CLOSE handler queues one) but nothing previously acted on
Expand Down
4 changes: 4 additions & 0 deletions lib/display_driver.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ TWO_FINGER_SWIPE_PX: int

def set_wheel_mapping(adjust_axis: str | None = None, adjust_sign: int | None = None, navigate: bool | None = None, navigate_sign: int | None = None) -> None:
"""Configure how the two wheel/swipe axes map onto LVGL."""
def take_keys(callback: Callable[[Any], None]) -> bool:
"""Send the keys typed on the display itself to *callback* instead of LVGL."""
def give_back_keys(callback: Callable[[Any], None]) -> None:
"""Stop sending the display's keys to *callback* (from `take_keys`)."""
def create_devices(devs: Iterable[Any], lv_display: Any, virtual_devices: list[Any] | None = None, window_id: int | None = None) -> list[Any]:
"""Register LVGL input devices as LVGL indevs (pointer / encoder / keypad)."""

Expand Down
29 changes: 27 additions & 2 deletions lib/displaydev/remotedisplay.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ class RemoteServer:
Attributes:
url (str): Where to point a browser, as best the board knows its
own address.
name_url (str): The same by the board's host name
(``http://omnipython-a1b2c3.local/``), which stays right when the
address changes, or None where there is no host name (a desktop).
sent (int): Bytes of pixels sent since the server started.
frames (int): Updates sent since the server started.
quality (int): JPEG quality, 1 to 100, for a video player. Default 70.
Expand Down Expand Up @@ -249,9 +252,15 @@ def __init__(self, display, port=80, period_ms=40, sweep_ms=2000, bind="0.0.0.0"
s.listen(2)
s.setblocking(False)
self._listener = s
self.url = "http://%s%s/" % (_own_address(), "" if port == 80 else ":%d" % port)
at = "" if port == 80 else ":%d" % port
self.url = "http://%s%s/" % (_own_address(), at)
name = _own_name()
self.name_url = "http://%s.local%s/" % (name, at) if name else None
self._timer = every(period_ms, self.poll, name="remotedisplay")
print("Display at %s" % self.url)
if self.name_url:
print("Display at %s and %s" % (self.url, self.name_url))
else:
print("Display at %s" % self.url)

# -- the frame --

Expand Down Expand Up @@ -958,6 +967,22 @@ def _put_head(buf, off, x, y, w, h, enc, n):
buf[off + 15] = n >> 24


def _own_name():
"""The host name mDNS answers to on a board, without ``.local``; None on a desktop."""
try:
import network

return network.hostname() or None
except (ImportError, AttributeError, OSError):
pass
try:
import wifi

return wifi.radio.hostname or None
except (ImportError, AttributeError):
return None


def _own_address():
try:
import network
Expand Down
1 change: 1 addition & 0 deletions lib/displaydev/remotedisplay.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class RemoteServer:
display: DisplayDriver
port: int
url: str
name_url: str | None
sent: int
frames: int
quality: int
Expand Down
24 changes: 18 additions & 6 deletions lib/wifi_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def _cache_file(platform=None):
# A join that ended with one of these never reached the access point.
_NOT_FOUND = ("network not found", "No network with that ssid")
_WRONG_HOLD_MS = 8000 # how long esp32 must report a bad password before we believe it
_LEAVE_MS = 3000 # how long a station may take to say it has left a network

_MAX_NETWORKS = 16
_MAGIC = b"WSU1"
Expand Down Expand Up @@ -747,11 +748,25 @@ def ssid(self):

def start(self, ssid, password):
"""Begin joining and return; ``ip()`` says when it has."""
self._leave()
self.sta.connect(ssid, password)

def _leave(self):
# Until the station has handled the disconnect, isconnected() and the
# old address still read as a link, and a join that follows would
# take them for the new network: a wrong password then passes.
try:
self.sta.disconnect()
except OSError:
pass
self.sta.connect(ssid, password)
return
t0 = _ticks_ms()
while _ticks_diff(_ticks_ms(), t0) < _LEAVE_MS:
try:
if not self.sta.isconnected():
return
except Exception:
return
_sleep_ms(50)

def join(self, ssid, password, timeout):
"""None on success, else a short reason."""
Expand All @@ -763,10 +778,7 @@ def join(self, ssid, password, timeout):
# status has to hold for _WRONG_HOLD_MS, not just show once.
wrong = (getattr(net, "STAT_WRONG_PASSWORD", 202), 15, 204)
no_ap = getattr(net, "STAT_NO_AP_FOUND", 201)
try:
self.sta.disconnect()
except OSError:
pass
self._leave()
# `reconnects` stays at its default of 0, which in this port is retry
# forever. -1 means give up after the first drop (network_wlan.c).
self.sta.connect(ssid, password)
Expand Down
25 changes: 20 additions & 5 deletions lib/wifinet.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,28 @@ def pair(self, endpoint, secret=None):
self._join(endpoint.local_id, secret or "", ValueError)

def _join(self, ssid, password, error):
# Joining leaves the network the board is on first. When the new one
# fails, go back: a board reached over Wi-Fi (WebREPL, a browser
# display) is otherwise cut off, with the error shown where nobody
# can see it.
before = self.radio.ssid()
back = self._password(before) if before else None
self._last = _ticks_ms() - self.rescan_ms # the next poll shows where it ended up
reason = self.radio.join(ssid, password, self.timeout)
if reason is None:
wifi_manager._remember(ssid, password)
return
if reason == "wrong password":
raise error("Wrong password for %s" % ssid)
if reason is not None:
raise error("Couldn't join %s: %s" % (ssid, reason))
wifi_manager._remember(ssid, password)
self._last = _ticks_ms() - self.rescan_ms # the next poll shows it joined
message = "Wrong password for %s" % ssid
else:
message = "Couldn't join %s: %s" % (ssid, reason)
if back is not None:
again = self.radio.join(before, back, self.timeout)
if again is None:
message += ". Back on %s" % before
else:
message += ". Couldn't get back on %s: %s" % (before, again)
raise error(message)

def _password(self, ssid):
"""The password a known network was joined with; "" for an open one, None when unknown."""
Expand Down
35 changes: 34 additions & 1 deletion packages/vtterm/vtterm/keyboards.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# SPDX-FileCopyrightText: 2026 Brad Barnett
#
# SPDX-License-Identifier: MIT
"""Keyboards on the USB host port and over BLE, read from a timer.
"""Keyboards on the USB host port, over BLE and on the display itself, read from a timer.

Each source has ``poll()``, which never waits and returns a list of
``events.Key`` records (possibly empty), ``status``, a line saying what it's
Expand Down Expand Up @@ -179,6 +179,35 @@ def close(self):
pass


class DisplayKeyboard:
"""The keys typed on the display itself: a desktop window's keyboard, or
the browser showing a RemoteDisplay. While it's open they come here, not
to LVGL's focused widget.

Raises:
ImportError: the display has no keys of its own to give (only touch),
or there's no LVGL display.
"""

def __init__(self):
import display_driver

self._driver = display_driver
self._events = []
# One bound method, kept: give_back_keys finds it by equality.
self._take = self._events.append
if not display_driver.take_keys(self._take):
raise ImportError("this display has no keyboard of its own")
self.status = "Display: typing here"

def poll(self):
out, self._events[:] = list(self._events), []
return out

def close(self):
self._driver.give_back_keys(self._take)


def start_all():
"""Start every keyboard source this board can have.

Expand All @@ -187,6 +216,10 @@ def start_all():
for each that couldn't, saying why.
"""
out, missing = [], []
try:
out.append(DisplayKeyboard())
except (ImportError, AttributeError):
pass # a panel with no keyboard of its own isn't worth a line
for name, cls in (("USB", UsbKeyboard), ("BLE", BleKeyboard)):
try:
out.append(cls())
Expand Down
29 changes: 29 additions & 0 deletions tests/board_name_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,34 @@ def test_esp32():
_unfake("esp32", "machine")


class _WLAN:
STA_IF = 0
mac = b""

def __init__(self, interface):
pass

def config(self, key):
return _WLAN.mac


def test_esp32_mac():
"""A C6, H2 or S31 reads an EUI-64 cut to six bytes from unique_id(): the name comes from the station's MAC."""
_fake("esp32", NVS=_NVS)
_fake("network", WLAN=_WLAN, STA_IF=0)
try:
for mac, eui in ((b"\x1c\x29\x04\xd0\xa2\x3a", b"\x1c\x29\x04\xff\xfe\xd0"), (b"\x1c\x29\x04\xd0\x1d\x00", b"\x1c\x29\x04\xff\xfe\xd0")):
_WLAN.mac = mac
_fake("machine", unique_id=lambda eui=eui: eui)
want = "omnipython-" + "".join("%02x" % b for b in mac[3:])
got = boarddev._name_default("micropython", "esp32")
check(got == want, "the MAC's last three bytes, not the EUI-64's: %r" % got)
_unfake("network")
check(boarddev._name_default("micropython", "esp32") == "omnipython-fffed0", "without Wi-Fi, the unique ID")
finally:
_unfake("esp32", "machine", "network")


def test_other_ports():
_fake("machine", unique_id=lambda: b"\xe6\x61\x41\x04\x03\x5a\x2b\x2c")
saved = boarddev._name_file
Expand Down Expand Up @@ -190,6 +218,7 @@ def main():
test_desktop()
test_browser()
test_esp32()
test_esp32_mac()
test_other_ports()
test_circuitpython()
print("OK")
Expand Down
Loading