From d483755006cd1430dabfe565afa5c44768d31370 Mon Sep 17 00:00:00 2001 From: Brad Barnett <127794626+bdbarnett@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:47:03 -0600 Subject: [PATCH 1/4] wifinet: a failed join goes back to the network the board was on Joining a network from a picker left the one the board was on first, and when the new join failed (a wrong password, a network that never answered) the board stayed off every network. A board reached over Wi-Fi, through WebREPL or a browser display, was cut off with the error shown on a page nobody could reach. wifinet now rejoins the network it was on with its saved password, and the error says so: "Wrong password for Cafe. Back on Home", or that the way back failed too. The checks' stand-in station now leaves its network when it joins another, as the real one does; with it, the old wifinet fails four new checks. --- docs/guides/wifi.md | 8 ++++++-- lib/wifinet.py | 25 ++++++++++++++++++++----- tests/endpoint_providers_checks.py | 25 ++++++++++++++++++++++++- 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/docs/guides/wifi.md b/docs/guides/wifi.md index 1c187cd4..fa1fa4c2 100644 --- a/docs/guides/wifi.md +++ b/docs/guides/wifi.md @@ -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 diff --git a/lib/wifinet.py b/lib/wifinet.py index 001ef27c..315cc552 100644 --- a/lib/wifinet.py +++ b/lib/wifinet.py @@ -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.""" diff --git a/tests/endpoint_providers_checks.py b/tests/endpoint_providers_checks.py index de6350ce..f5a0dbdd 100644 --- a/tests/endpoint_providers_checks.py +++ b/tests/endpoint_providers_checks.py @@ -328,7 +328,9 @@ def ip(self): return "10.0.0.7" if self.on else None def join(self, ssid, password, timeout): + # Like the real station, a join leaves the network it was on first. self.joins.append(ssid) + self.on = None if ssid not in self.seen: return "network not found" if self.passwords.get(ssid, "") != password: @@ -481,7 +483,28 @@ def remember(ssid, password, hidden=False): r.pair("wifi:Cafe", "latte") check(False, "a wrong password is refused") except ValueError as exc: - check(str(exc) == "Wrong password for Cafe", "the refusal says the password was wrong: %s" % exc) + check(str(exc) == "Wrong password for Cafe. Back on Home", "the refusal says the password was wrong: %s" % exc) + check(radio.on == "Home" and radio.joins[-2:] == ["Cafe", "Home"], "a failed join goes back to the network the board was on") + seen["Faraway"] = (-90, True) + r.refresh("net") + r.poll() + del seen["Faraway"] + try: + r.pair("wifi:Faraway", "x") + check(False, "a network gone from range is refused") + except ValueError as exc: + check(str(exc) == "Couldn't join Faraway: network not found. Back on Home", "the refusal says why and where the board is: %s" % exc) + check(radio.on == "Home", "the board is back on its network after a network not found") + radio.passwords["Home"] = "changed" + try: + r.pair("wifi:Cafe", "latte") + check(False, "a wrong password is refused when the way back fails too") + except ValueError as exc: + check(str(exc) == "Wrong password for Cafe. Couldn't get back on Home: wrong password", "the refusal says the way back failed too: %s" % exc) + radio.passwords["Home"] = "homepw" + radio.join("Home", "homepw", 1) + r.refresh("net") + r.poll() check(r.find("wifi:Cafe").state == endpointkit.NEEDS_PAIRING and "Cafe" not in [n["ssid"] for n in store], "a failed join remembers nothing") ep = r.pair("wifi:Cafe", "espresso") check(ep.state == endpointkit.CONNECTED, "the right password joins") From 4db93489fefb3915da9afd484134ce70b4693f9d Mon Sep 17 00:00:00 2001 From: Brad Barnett <127794626+bdbarnett@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:47:03 -0600 Subject: [PATCH 2/4] boarddev: an ESP32's name comes from its Wi-Fi MAC On a chip with an IEEE 802.15.4 radio (ESP32-C5, C6, H2, S31), machine.unique_id() is an EUI-64 cut to six bytes: the vendor's three, ff:fe and one byte of the MAC. Every default name ended in fffe and that byte, so two ESP32-S31 boards on one network both answered to omnipython-fffed0.local. The default name now takes the station MAC's last three bytes, which equal unique_id()'s on every ESP32 without 802.15.4, so no other board's name changes. A build without Wi-Fi still uses unique_id(). RemoteDisplay also prints the address by host name beside the IP address, and keeps it as RemoteServer.name_url. --- docs/guides/board-name.md | 2 +- lib/boarddev.py | 14 +++++++++++++- lib/boarddev.pyi | 5 +++-- lib/displaydev/remotedisplay.py | 29 +++++++++++++++++++++++++++-- lib/displaydev/remotedisplay.pyi | 1 + tests/board_name_checks.py | 29 +++++++++++++++++++++++++++++ tests/test_remotedisplay.py | 12 ++++++++++++ 7 files changed, 86 insertions(+), 6 deletions(-) diff --git a/docs/guides/board-name.md b/docs/guides/board-name.md index 8a48e548..9d950670 100644 --- a/docs/guides/board-name.md +++ b/docs/guides/board-name.md @@ -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 | diff --git a/lib/boarddev.py b/lib/boarddev.py index 609a471e..0ecc0ad5 100644 --- a/lib/boarddev.py +++ b/lib/boarddev.py @@ -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. @@ -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()) diff --git a/lib/boarddev.pyi b/lib/boarddev.pyi index f1fe9ebc..5c1d89b9 100644 --- a/lib/boarddev.pyi +++ b/lib/boarddev.pyi @@ -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: diff --git a/lib/displaydev/remotedisplay.py b/lib/displaydev/remotedisplay.py index 469c6d7a..9fd8351e 100644 --- a/lib/displaydev/remotedisplay.py +++ b/lib/displaydev/remotedisplay.py @@ -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. @@ -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 -- @@ -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 diff --git a/lib/displaydev/remotedisplay.pyi b/lib/displaydev/remotedisplay.pyi index 284dea2f..2d580b74 100644 --- a/lib/displaydev/remotedisplay.pyi +++ b/lib/displaydev/remotedisplay.pyi @@ -11,6 +11,7 @@ class RemoteServer: display: DisplayDriver port: int url: str + name_url: str | None sent: int frames: int quality: int diff --git a/tests/board_name_checks.py b/tests/board_name_checks.py index 134c2c28..1e79caeb 100644 --- a/tests/board_name_checks.py +++ b/tests/board_name_checks.py @@ -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 @@ -190,6 +218,7 @@ def main(): test_desktop() test_browser() test_esp32() + test_esp32_mac() test_other_ports() test_circuitpython() print("OK") diff --git a/tests/test_remotedisplay.py b/tests/test_remotedisplay.py index ec2d08dd..4b5e0dae 100644 --- a/tests/test_remotedisplay.py +++ b/tests/test_remotedisplay.py @@ -16,9 +16,12 @@ import socket import struct import subprocess +import sys import threading import time +import types import unittest +from unittest import mock import _env import _mprun @@ -205,6 +208,15 @@ def tearDown(self): def _crc(self): return binascii.crc32(bytes(self.d._raw_buffer)) + def test_a_board_says_its_host_name_too(self): + from displaydev import remotedisplay + + board = types.ModuleType("network") + board.hostname = lambda: "omnipython-d0a23a" + with mock.patch.dict(sys.modules, {"network": board}): + self.assertEqual(remotedisplay._own_name(), "omnipython-d0a23a") + self.assertIsNone(self.d.server.name_url, "a desktop has no host name of its own") + def test_page(self): data = _get_page(self.port) self.assertTrue(data.startswith(b"HTTP/1.1 200")) From a2370fb664eb262383df999fc58eb8f941aba5f6 Mon Sep 17 00:00:00 2001 From: Brad Barnett <127794626+bdbarnett@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:47:03 -0600 Subject: [PATCH 3/4] vtterm: the REPL takes keys typed on the display itself vtterm read USB and BLE keyboards only, so the REPL on a desktop window or in the browser showing a RemoteDisplay ignored the keyboard in front of it. display_driver.take_keys() hands the display's own keys to a callback instead of LVGL's focused widget, and vtterm.keyboards.DisplayKeyboard uses it: start_all() starts it wherever the display has a keyboard of its own. --- docs/guides/vtterm.md | 9 +++-- lib/display_driver.py | 33 +++++++++++++++++- lib/display_driver.pyi | 4 +++ packages/vtterm/vtterm/keyboards.py | 35 ++++++++++++++++++- tests/test_lvgl_display_driver.py | 54 +++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 5 deletions(-) diff --git a/docs/guides/vtterm.md b/docs/guides/vtterm.md index e392fddc..41397495 100644 --- a/docs/guides/vtterm.md +++ b/docs/guides/vtterm.md @@ -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 diff --git a/lib/display_driver.py b/lib/display_driver.py index d4d88593..ef96c7a4 100644 --- a/lib/display_driver.py +++ b/lib/display_driver.py @@ -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 `. 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: @@ -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 diff --git a/lib/display_driver.pyi b/lib/display_driver.pyi index c8bd65a0..e3d1599b 100644 --- a/lib/display_driver.pyi +++ b/lib/display_driver.pyi @@ -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).""" diff --git a/packages/vtterm/vtterm/keyboards.py b/packages/vtterm/vtterm/keyboards.py index d9607372..31deca3f 100644 --- a/packages/vtterm/vtterm/keyboards.py +++ b/packages/vtterm/vtterm/keyboards.py @@ -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 @@ -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. @@ -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()) diff --git a/tests/test_lvgl_display_driver.py b/tests/test_lvgl_display_driver.py index 921e5432..06ae15b1 100644 --- a/tests/test_lvgl_display_driver.py +++ b/tests/test_lvgl_display_driver.py @@ -821,5 +821,59 @@ def test_a_new_press_cancels_the_park(self): self.assertEqual(self.read(None), ((50, 60), "pressed")) +class KeyTakersTest(unittest.TestCase): + """``take_keys``: a terminal gets the display's own keys, and LVGL doesn't.""" + + def setUp(self): + import events + + import appdev + + self.events = events + ns = {"events": events, "lv": types.SimpleNamespace(), "_wheel_navigate_cb": lambda e: None, + "HOST": appdev.HOST, "POINTER": appdev.POINTER, "ENCODER": appdev.ENCODER, + "KEYPAD": appdev.KEYPAD, "JOYSTICK": appdev.JOYSTICK, + "_virtual_peers": {}, "_key_takers": []} + cls = _exec_class("VirtualDevices", ns) + for name in ("take_keys", "give_back_keys"): + exec(compile(_function_source(name), str(DISPLAY_DRIVER), "exec"), ns) + self.ns = ns + vd = cls.__new__(cls) + vd._window_id = None + vd._vd_keypad = cls.VirtualDevice(vd, appdev.KEYPAD) + self.vd = vd + + def key(self, down=True): + e = self.events + return e.Key(e.KEYDOWN if down else e.KEYUP, "a", ord("a"), 0, 0, None) + + def test_keys_go_to_lvgl_when_nobody_takes_them(self): + self.vd._route(self.key()) + self.assertEqual(len(self.vd._vd_keypad._fifo), 1) + + def test_a_taker_gets_the_keys_and_lvgl_none(self): + self.ns["_virtual_peers"][1] = [self.vd] + got = [] + self.assertTrue(self.ns["take_keys"](got.append)) + self.vd._route(self.key()) + self.vd._route(self.key(down=False)) + self.assertEqual([k.type for k in got], [self.events.KEYDOWN, self.events.KEYUP]) + self.assertEqual(self.vd._vd_keypad._fifo, []) + + def test_given_back_keys_reach_lvgl_again(self): + self.ns["_virtual_peers"][1] = [self.vd] + got = [] + take = got.append + self.ns["take_keys"](take) + self.ns["give_back_keys"](take) + self.vd._route(self.key()) + self.assertEqual(got, []) + self.assertEqual(len(self.vd._vd_keypad._fifo), 1) + + def test_a_display_without_host_input_has_no_keys_to_take(self): + self.assertFalse(self.ns["take_keys"](lambda e: None)) + self.assertEqual(self.ns["_key_takers"], []) + + if __name__ == "__main__": unittest.main() From 56c84e66636245899794279fbb0d3bdfd2e0fbd9 Mon Sep 17 00:00:00 2001 From: Brad Barnett <127794626+bdbarnett@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:33:23 -0600 Subject: [PATCH 4/4] wifi_manager: a join waits until the station has left the old network On esp32 the station still reads as connected, with the old address, for a moment after disconnect(). A join from one network to another took that for the new link and returned at once: a wrong password passed, was saved over the right one, and the board was left off the network. --- lib/wifi_manager.py | 24 ++++++++++++++++++------ tests/test_wifi_manager.py | 23 +++++++++++++++++++++-- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/lib/wifi_manager.py b/lib/wifi_manager.py index 263e32a1..49ec9c10 100644 --- a/lib/wifi_manager.py +++ b/lib/wifi_manager.py @@ -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" @@ -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.""" @@ -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) diff --git a/tests/test_wifi_manager.py b/tests/test_wifi_manager.py index 5a340d58..8e379f45 100644 --- a/tests/test_wifi_manager.py +++ b/tests/test_wifi_manager.py @@ -127,19 +127,27 @@ class FakeSta: """An esp32 station: ``status()`` follows *timeline*, a list of ``(ms from connect, status)``, and it is connected from *up_at* on.""" - def __init__(self, timeline, up_at=None): + def __init__(self, timeline, up_at=None, on_before=False, lingers_ms=0): self.timeline = timeline self.up_at = up_at self.t0 = None + # On a network already, whose link still reads as up for + # *lingers_ms* after disconnect(), as the esp32 port's does. + self.linked_until = 0 if on_before else None + self.lingers_ms = lingers_ms def disconnect(self): + if self.linked_until is not None: + self.linked_until = _clock[0] + self.lingers_ms self.t0 = None def connect(self, ssid, password): self.t0 = _clock[0] def isconnected(self): - return self.up_at is not None and _clock[0] - self.t0 >= self.up_at + if self.linked_until is not None and _clock[0] < self.linked_until: + return True + return self.up_at is not None and self.t0 is not None and _clock[0] - self.t0 >= self.up_at def ifconfig(self): return ("10.0.0.7", "255.255.255.0", "10.0.0.1", "10.0.0.1") @@ -179,6 +187,17 @@ def test_no_access_point_is_reported(self): sta = FakeSta([(0, 1001), (3000, 201)]) self.assertEqual(self._radio(sta).join("home", "pw", 20), "network not found") + def test_the_old_link_lingering_after_disconnect_is_not_taken_for_the_new_one(self): + # Moving from one network to another: the old link still reads as + # up for a moment, and a wrong password must not pass for a join. + sta = FakeSta([(0, 1001), (4000, 202)], on_before=True, lingers_ms=300) + self.assertEqual(self._radio(sta).join("cafe", "wrong", 20), "wrong password") + + def test_a_link_that_never_drops_is_not_waited_on_for_ever(self): + sta = FakeSta([(0, 1001)], up_at=2000, on_before=True, lingers_ms=10**9) + self.assertIsNone(self._radio(sta).join("cafe", "pw", 20)) + self.assertLess(_clock[0], 10000) + class JoinKnownTest(_Patched): def test_in_range_first_strongest_first_then_the_rest(self):