Skip to content
Open
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
32 changes: 32 additions & 0 deletions meshtastic/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1100,6 +1109,14 @@ 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:
meshtastic.util.our_exit("ERROR: Could not read the UI config")
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
Expand Down Expand Up @@ -2015,6 +2032,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.",
Expand Down
55 changes: 54 additions & 1 deletion meshtastic/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
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, 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,
Expand Down Expand Up @@ -963,6 +964,58 @@ def setTime(self, timeSec: int = 0):
onResponse = self.onAckNak
return self._sendAdmin(p, onResponse=onResponse)

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

# 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 request.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"""

Expand Down
68 changes: 68 additions & 0 deletions meshtastic/tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -710,6 +711,73 @@ 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_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):
Expand Down
99 changes: 99 additions & 0 deletions meshtastic/tests/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -2040,3 +2040,102 @@ 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


@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