From f8aba2a0896404d5051dc76d62e290c3a136223f Mon Sep 17 00:00:00 2001 From: Kevin Date: Sun, 22 Nov 2026 00:02:01 +0100 Subject: [PATCH 1/2] feat: --get-settings-lock and --set-settings-lock DeviceUIConfig.settings_lock locks changing settings from the device's own screen menus. Until now no client could set it without hand-built admin messages. Node gains getUIConfig(), setUIConfig() and setSettingsLock(). The latter reads the current UI config and stores it back with only settings_lock changed, so brightness, screen timeout and the other UI settings are kept. If the UI config can't be read, nothing is stored. --- meshtastic/__main__.py | 33 ++++++++++++++ meshtastic/node.py | 54 ++++++++++++++++++++++- meshtastic/tests/test_main.py | 51 ++++++++++++++++++++++ meshtastic/tests/test_node.py | 81 +++++++++++++++++++++++++++++++++++ 4 files changed, 217 insertions(+), 2 deletions(-) diff --git a/meshtastic/__main__.py b/meshtastic/__main__.py index 08f002b51..d8ec87e16 100644 --- a/meshtastic/__main__.py +++ b/meshtastic/__main__.py @@ -459,6 +459,15 @@ def onConnected(interface): else: print("External Notification is excluded by firmware; skipping ringtone set.") + if args.set_settings_lock is not None: + closeNow = True + waitForAckNak = True + locked = meshtastic.util.fromStr(args.set_settings_lock) + if not isinstance(locked, bool): + meshtastic.util.our_exit("ERROR: --set-settings-lock takes true or false") + print(f"Setting settings_lock to {locked}") + interface.getNode(args.dest, False, **getNode_kwargs).setSettingsLock(locked) + if args.pos_fields: # If --pos-fields invoked with args, set position fields closeNow = True @@ -1100,6 +1109,15 @@ def setSimpleConfig(modem_preset): ringtone = interface.getNode(args.dest, **getNode_kwargs).get_ringtone() print(f"ringtone:{ringtone}") + if args.get_settings_lock: + closeNow = True + print("") + uiConfig = interface.getNode(args.dest, False, **getNode_kwargs).getUIConfig() + if uiConfig is None: + print("Could not read the UI config") + else: + print(f"settings_lock:{uiConfig.settings_lock}") + if args.info: print("") # If we aren't trying to talk to our local node, don't show it @@ -2015,6 +2033,21 @@ def addConfigArgs(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: metavar="RINGTONE", ) + group.add_argument( + "--get-settings-lock", + help="Show whether changing settings from the device's own screen menus is locked", + action="store_true", + ) + + group.add_argument( + "--set-settings-lock", + help="Lock (true) or unlock (false) changing settings from the device's own screen menus. " + "Other UI settings are kept. Takes effect without a reboot only on firmware that applies " + "store_ui_config immediately.", + metavar="true|false", + action="store", + ) + group.add_argument( "--ch-vlongslow", help="Change to the VERY_LONG_SLOW modem preset. Deprecated since 2.5 firmware.", diff --git a/meshtastic/node.py b/meshtastic/node.py index 4340fb538..2e4977991 100644 --- a/meshtastic/node.py +++ b/meshtastic/node.py @@ -7,7 +7,7 @@ from typing import Optional, Union, List -from meshtastic.protobuf import admin_pb2, apponly_pb2, channel_pb2, config_pb2, localonly_pb2, mesh_pb2, portnums_pb2 +from meshtastic.protobuf import admin_pb2, apponly_pb2, channel_pb2, config_pb2, device_ui_pb2, localonly_pb2, mesh_pb2, portnums_pb2 from meshtastic.util import ( Timeout, camel_to_snake, @@ -44,8 +44,9 @@ def __init__(self, iface, nodeNum, noProto=False, timeout: int = 300): self.cannedPluginMessageMessages = None self.ringtone = None self.ringtonePart = None + self.uiConfig: Optional[device_ui_pb2.DeviceUIConfig] = None - self.gotResponse = None + self.gotResponse: Optional[bool] = None def __repr__(self): r = f"Node({self.iface!r}, 0x{self.nodeNum:08x}" @@ -963,6 +964,55 @@ def setTime(self, timeSec: int = 0): onResponse = self.onAckNak return self._sendAdmin(p, onResponse=onResponse) + def onResponseRequestUIConfig(self, p): + """Handle the response packet for a get_ui_config_request""" + logger.debug(f"onResponseRequestUIConfig() p:{p}") + decoded = p.get("decoded", {}) + if "routing" in decoded: + if decoded["routing"]["errorReason"] != "NONE": + print(f'Error on response: {decoded["routing"]["errorReason"]}') + self.gotResponse = True + return + raw = decoded.get("admin", {}).get("raw") + if raw is not None and raw.HasField("get_ui_config_response"): + self.uiConfig = device_ui_pb2.DeviceUIConfig() + self.uiConfig.CopyFrom(raw.get_ui_config_response) + self.gotResponse = True + + def getUIConfig(self) -> Optional[device_ui_pb2.DeviceUIConfig]: + """Request the node's DeviceUIConfig. Returns None if there was no valid answer in time.""" + self.ensureSessionKey() + p = admin_pb2.AdminMessage() + p.get_ui_config_request = True + self.uiConfig = None + self.gotResponse = False + self._sendAdmin(p, wantResponse=True, onResponse=self.onResponseRequestUIConfig) + if not self._timeout.waitForSet(self, attrs=("gotResponse",)): + logger.warning("Timed out waiting for the UI config") + return self.uiConfig + + def setUIConfig(self, uiConfig: device_ui_pb2.DeviceUIConfig): + """Store a complete DeviceUIConfig on the node, replacing the one it has.""" + self.ensureSessionKey() + p = admin_pb2.AdminMessage() + p.store_ui_config.CopyFrom(uiConfig) + + if self == self.iface.localNode: + onResponse = None + else: + onResponse = self.onAckNak + return self._sendAdmin(p, onResponse=onResponse) + + def setSettingsLock(self, locked: bool): + """Lock or unlock changing settings from the device's own screen menus (DeviceUIConfig.settings_lock). + + Reads the current UI config first, so that the other UI settings are kept.""" + uiConfig = self.getUIConfig() + if uiConfig is None: + our_exit("Warning: Could not read the UI config, settings lock not changed.") + uiConfig.settings_lock = locked + return self.setUIConfig(uiConfig) + def _fixupChannels(self): """Fixup indexes and add disabled channels as needed""" diff --git a/meshtastic/tests/test_main.py b/meshtastic/tests/test_main.py index a25c0cc9c..3864dd660 100644 --- a/meshtastic/tests/test_main.py +++ b/meshtastic/tests/test_main.py @@ -29,6 +29,7 @@ ) from meshtastic import mt_config +from ..protobuf import device_ui_pb2 from ..protobuf.channel_pb2 import Channel # pylint: disable=E0611 from ..protobuf.config_pb2 import Config # pylint: disable=E0611 from ..protobuf.clientonly_pb2 import DeviceProfile # pylint: disable=E0611 @@ -710,6 +711,56 @@ def test_main_get_ringtone(capsys, caplog, iface_with_nodes): assert err == "" mo.assert_called() +@pytest.mark.unit +@pytest.mark.usefixtures("reset_mt_config") +@pytest.mark.parametrize("value,expected", [("true", True), ("false", False)]) +def test_main_set_settings_lock(capsys, value, expected): + """Test --set-settings-lock""" + sys.argv = ["", "--set-settings-lock", value] + mt_config.args = sys.argv + + iface = MagicMock(autospec=SerialInterface) + with patch("meshtastic.serial_interface.SerialInterface", return_value=iface) as mo: + main() + out, err = capsys.readouterr() + assert re.search(r"Connected to radio", out, re.MULTILINE) + assert re.search(rf"Setting settings_lock to {expected}", out, re.MULTILINE) + assert err == "" + mo.assert_called() + iface.getNode.return_value.setSettingsLock.assert_called_once_with(expected) + +@pytest.mark.unit +@pytest.mark.usefixtures("reset_mt_config") +def test_main_set_settings_lock_invalid(capsys): + """Test --set-settings-lock with a value that isn't a boolean""" + sys.argv = ["", "--set-settings-lock", "maybe"] + mt_config.args = sys.argv + + iface = MagicMock(autospec=SerialInterface) + with patch("meshtastic.serial_interface.SerialInterface", return_value=iface): + with pytest.raises(SystemExit) as pytest_wrapped_e: + main() + assert pytest_wrapped_e.value.code == 1 + out, _ = capsys.readouterr() + assert re.search(r"--set-settings-lock takes true or false", out, re.MULTILINE) + iface.getNode.return_value.setSettingsLock.assert_not_called() + +@pytest.mark.unit +@pytest.mark.usefixtures("reset_mt_config") +def test_main_get_settings_lock(capsys): + """Test --get-settings-lock""" + sys.argv = ["", "--get-settings-lock"] + mt_config.args = sys.argv + + iface = MagicMock(autospec=SerialInterface) + iface.getNode.return_value.getUIConfig.return_value = device_ui_pb2.DeviceUIConfig(settings_lock=True) + with patch("meshtastic.serial_interface.SerialInterface", return_value=iface) as mo: + main() + out, err = capsys.readouterr() + assert re.search(r"settings_lock:True", out, re.MULTILINE) + assert err == "" + mo.assert_called() + @pytest.mark.unit @pytest.mark.usefixtures("reset_mt_config") def test_main_set_ham_to_KI123(capsys): diff --git a/meshtastic/tests/test_node.py b/meshtastic/tests/test_node.py index c2879e65f..97f965062 100644 --- a/meshtastic/tests/test_node.py +++ b/meshtastic/tests/test_node.py @@ -2040,3 +2040,84 @@ def test_requested_config_nak(capsys): node.onResponseRequestSettings({"decoded": {"routing": {"errorReason": "NOT_AUTHORIZED"}}}) assert capsys.readouterr().out == "Error on response: NOT_AUTHORIZED\n" assert iface._acknowledgment.receivedNak is True + + +def _ui_config_response(**fields): + """Build a fake get_ui_config_response packet as the mesh interface delivers it""" + resp = admin_pb2.AdminMessage() + for k, v in fields.items(): + setattr(resp.get_ui_config_response, k, v) + return {"decoded": {"admin": {"raw": resp}}} + + +@pytest.mark.unit +def test_getUIConfig(): + """Test getUIConfig returns the config from the response""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=1) + + def answer(p, *args, **kwargs): # pylint: disable=unused-argument + assert p.get_ui_config_request is True + assert kwargs["wantResponse"] is True + kwargs["onResponse"](_ui_config_response(screen_brightness=153, settings_lock=True)) + + iface.sendData.side_effect = answer + cfg = node.getUIConfig() + assert cfg.screen_brightness == 153 + assert cfg.settings_lock is True + + +@pytest.mark.unit +def test_getUIConfig_timeout(): + """Test getUIConfig returns None when the node does not answer""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=1) + assert node.getUIConfig() is None + + +@pytest.mark.unit +def test_getUIConfig_routing_error(capsys): + """Test getUIConfig returns None and stops waiting on a routing error""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=30) + iface.sendData.side_effect = lambda p, *a, **kw: kw["onResponse"]( + {"decoded": {"routing": {"errorReason": "NO_RESPONSE"}}} + ) + assert node.getUIConfig() is None + out, _ = capsys.readouterr() + assert "Error on response: NO_RESPONSE" in out + + +@pytest.mark.unit +@pytest.mark.parametrize("locked", [True, False]) +def test_setSettingsLock_keeps_other_fields(locked): + """Test setSettingsLock only changes settings_lock and stores the rest unchanged""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=1) + sent = [] + + def answer(p, *args, **kwargs): # pylint: disable=unused-argument + sent.append(p) + if p.HasField("get_ui_config_request"): + kwargs["onResponse"]( + _ui_config_response(screen_brightness=153, screen_timeout=30, settings_lock=not locked) + ) + + iface.sendData.side_effect = answer + node.setSettingsLock(locked) + + assert len(sent) == 2 + stored = sent[1].store_ui_config + assert stored.settings_lock is locked + assert stored.screen_brightness == 153 + assert stored.screen_timeout == 30 + + +@pytest.mark.unit +def test_setSettingsLock_no_answer(): + """Test setSettingsLock does not store anything if the UI config can't be read""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=1) + with pytest.raises(SystemExit): + node.setSettingsLock(True) + assert iface.sendData.call_count == 1 From 6c2b2def9ac74182dd19fe20bd583d462c606458 Mon Sep 17 00:00:00 2001 From: Kevin Date: Sun, 22 Nov 2026 13:00:06 +0100 Subject: [PATCH 2/2] fix: scope UI config answers to their request, fail --get-settings-lock on no answer getUIConfig() kept its completion state on the Node, so a late answer to an earlier, timed-out request could complete a later one with stale values, which setSettingsLock() would then store back. Each request now has its own state. --get-settings-lock now exits with an error when the UI config can't be read. --- meshtastic/__main__.py | 5 ++-- meshtastic/node.py | 47 +++++++++++++++++++---------------- meshtastic/tests/test_main.py | 17 +++++++++++++ meshtastic/tests/test_node.py | 18 ++++++++++++++ 4 files changed, 62 insertions(+), 25 deletions(-) diff --git a/meshtastic/__main__.py b/meshtastic/__main__.py index d8ec87e16..f8f005ea0 100644 --- a/meshtastic/__main__.py +++ b/meshtastic/__main__.py @@ -1114,9 +1114,8 @@ def setSimpleConfig(modem_preset): print("") uiConfig = interface.getNode(args.dest, False, **getNode_kwargs).getUIConfig() if uiConfig is None: - print("Could not read the UI config") - else: - print(f"settings_lock:{uiConfig.settings_lock}") + meshtastic.util.our_exit("ERROR: Could not read the UI config") + print(f"settings_lock:{uiConfig.settings_lock}") if args.info: print("") diff --git a/meshtastic/node.py b/meshtastic/node.py index 2e4977991..cc690e102 100644 --- a/meshtastic/node.py +++ b/meshtastic/node.py @@ -5,6 +5,7 @@ import logging import time +from types import SimpleNamespace from typing import Optional, Union, List from meshtastic.protobuf import admin_pb2, apponly_pb2, channel_pb2, config_pb2, device_ui_pb2, localonly_pb2, mesh_pb2, portnums_pb2 @@ -44,9 +45,8 @@ def __init__(self, iface, nodeNum, noProto=False, timeout: int = 300): self.cannedPluginMessageMessages = None self.ringtone = None self.ringtonePart = None - self.uiConfig: Optional[device_ui_pb2.DeviceUIConfig] = None - self.gotResponse: Optional[bool] = None + self.gotResponse = None def __repr__(self): r = f"Node({self.iface!r}, 0x{self.nodeNum:08x}" @@ -964,32 +964,35 @@ def setTime(self, timeSec: int = 0): onResponse = self.onAckNak return self._sendAdmin(p, onResponse=onResponse) - def onResponseRequestUIConfig(self, p): - """Handle the response packet for a get_ui_config_request""" - logger.debug(f"onResponseRequestUIConfig() p:{p}") - decoded = p.get("decoded", {}) - if "routing" in decoded: - if decoded["routing"]["errorReason"] != "NONE": - print(f'Error on response: {decoded["routing"]["errorReason"]}') - self.gotResponse = True - return - raw = decoded.get("admin", {}).get("raw") - if raw is not None and raw.HasField("get_ui_config_response"): - self.uiConfig = device_ui_pb2.DeviceUIConfig() - self.uiConfig.CopyFrom(raw.get_ui_config_response) - self.gotResponse = True - def getUIConfig(self) -> Optional[device_ui_pb2.DeviceUIConfig]: """Request the node's DeviceUIConfig. Returns None if there was no valid answer in time.""" self.ensureSessionKey() p = admin_pb2.AdminMessage() p.get_ui_config_request = True - self.uiConfig = None - self.gotResponse = False - self._sendAdmin(p, wantResponse=True, onResponse=self.onResponseRequestUIConfig) - if not self._timeout.waitForSet(self, attrs=("gotResponse",)): + + # Completion state belongs to this request only, so a late answer to an earlier, + # timed-out request can't complete this one. + request = SimpleNamespace(done=False, uiConfig=None) + + def onResponse(packet): + logger.debug(f"getUIConfig onResponse() p:{packet}") + decoded = packet.get("decoded", {}) + if "routing" in decoded: + if decoded["routing"]["errorReason"] != "NONE": + print(f'Error on response: {decoded["routing"]["errorReason"]}') + request.done = True + return + raw = decoded.get("admin", {}).get("raw") + if raw is not None and raw.HasField("get_ui_config_response"): + uiConfig = device_ui_pb2.DeviceUIConfig() + uiConfig.CopyFrom(raw.get_ui_config_response) + request.uiConfig = uiConfig + request.done = True + + self._sendAdmin(p, wantResponse=True, onResponse=onResponse) + if not self._timeout.waitForSet(request, attrs=("done",)): logger.warning("Timed out waiting for the UI config") - return self.uiConfig + return request.uiConfig def setUIConfig(self, uiConfig: device_ui_pb2.DeviceUIConfig): """Store a complete DeviceUIConfig on the node, replacing the one it has.""" diff --git a/meshtastic/tests/test_main.py b/meshtastic/tests/test_main.py index 3864dd660..15b864394 100644 --- a/meshtastic/tests/test_main.py +++ b/meshtastic/tests/test_main.py @@ -761,6 +761,23 @@ def test_main_get_settings_lock(capsys): assert err == "" mo.assert_called() +@pytest.mark.unit +@pytest.mark.usefixtures("reset_mt_config") +def test_main_get_settings_lock_no_answer(capsys): + """Test --get-settings-lock exits with an error when the UI config can't be read""" + sys.argv = ["", "--get-settings-lock"] + mt_config.args = sys.argv + + iface = MagicMock(autospec=SerialInterface) + iface.getNode.return_value.getUIConfig.return_value = None + with patch("meshtastic.serial_interface.SerialInterface", return_value=iface): + with pytest.raises(SystemExit) as pytest_wrapped_e: + main() + assert pytest_wrapped_e.value.code == 1 + out, _ = capsys.readouterr() + assert re.search(r"ERROR: Could not read the UI config", out, re.MULTILINE) + assert not re.search(r"settings_lock:", out, re.MULTILINE) + @pytest.mark.unit @pytest.mark.usefixtures("reset_mt_config") def test_main_set_ham_to_KI123(capsys): diff --git a/meshtastic/tests/test_node.py b/meshtastic/tests/test_node.py index 97f965062..3ffa9a09d 100644 --- a/meshtastic/tests/test_node.py +++ b/meshtastic/tests/test_node.py @@ -2121,3 +2121,21 @@ def test_setSettingsLock_no_answer(): with pytest.raises(SystemExit): node.setSettingsLock(True) assert iface.sendData.call_count == 1 + + +@pytest.mark.unit +def test_getUIConfig_ignores_late_answer_to_earlier_request(): + """Test a late answer to a timed-out getUIConfig doesn't complete a later one""" + iface = MagicMock(autospec=SerialInterface) + node = Node(iface, 12345678, timeout=1) + callbacks = [] + + def answer(p, *args, **kwargs): # pylint: disable=unused-argument + callbacks.append(kwargs["onResponse"]) + if len(callbacks) == 2: + # only the first request's answer arrives, late, while the second request waits + callbacks[0](_ui_config_response(screen_brightness=153)) + + iface.sendData.side_effect = answer + assert node.getUIConfig() is None + assert node.getUIConfig() is None