Interface Management initial (2/2)

This commit is contained in:
RFNexus 2025-04-20 09:18:56 -04:00
parent c415345f59
commit dfa7adc21e
5 changed files with 1016 additions and 211 deletions

View file

@ -1 +1 @@
__version__ = "0.6.1"
__version__ = "0.6.2"

View file

@ -387,8 +387,223 @@ Links can be inserted into micron documents. See the `*Markup`* section of this
'''
TOPIC_INTERFACES = '''
>TODO
TOPIC_INTERFACES = '''>Interfaces
Reticulum supports using many kinds of devices as networking interfaces, and allows you to mix and match them in any way you choose.
The number of distinct network topologies you can create with Reticulum is more or less endless, but common to them all is that you will need to define one or more interfaces for Reticulum to use.
The `![ Interfaces ]`! section of NomadNet lets you add, monitor, and update interfaces configured for your Reticulum instance.
If you are starting NomadNet for the first time you will find that an `!AutoInterface`! has been added by default. This interface will try to use your available network device to communicate with other peers discovered on your local network.
Interfaces come in many different types and can interact with physical mediums like LoRa radios or standard IP networks.
>>Viewing Interfaces
To view more info about an interface, navigate using the `!Up`! and `!Down`! arrow keys or by clicking with the mouse. Pressing `! < Enter >`! on a selected interface will bring you to a detailed interface view, which will show configuration parameters and realtime charts. From here you can also disable or edit the interface. To change the orientation of the TX/RX charts, press `!< V >`! for a vertical layout, and `!< H >`! for a horizontal view.
>>Updating Interfaces
To edit an interface, select the interface and press `!< Ctrl + E >`!.
To remove an interface, select the interface and press `!< Ctrl + X >`!. You can also perform both of these actions from the details view.
>>Adding Interfaces
To add a new interface, press `!< Ctrl + A >`!. From here you can select which type of interface you want to add. Each unique interface type will have different configuration options.
`Ffff`! (!) Note:`! After adding or modifying interfaces, you will need to restart NomadNet or your Reticulum instance for changes to take effect.`f`b
>Interface Types
>>AutoInterface
The Auto Interface enables communication with other discoverable Reticulum nodes over autoconfigured IPv6 and UDP. It does not need any functional IP infrastructure like routers or DHCP servers, but will require at least some sort of switching medium between peers (a wired switch, a hub, a WiFi access point or similar).
```
Required Parameters:
Interface Name
Optional Parameters:
Devices: Specific network devices to use
Ignored Devices: Network devices to exclude
Group ID: Create isolated networks on the same physical LAN
Discovery Scope: Can set to link, admin, site, organisation or global
```
The AutoInterface is ideal for quickly connecting to other Reticulum nodes on your local network without complex configuration.
>>TCPClientInterface
The TCP Client interface connects to remote TCP server interfaces, enabling communication over the Internet or private networks.
```
Required Parameters:
Target Host: Hostname or IP address of the server
Target Port: Port number to connect to
Optional Parameters:
I2P Tunneled: Enable for connecting through I2P
KISS Framing: Enable for KISS framing for software modems
```
This interface is commonly used to connect to Reticulum testnets or other persistent nodes on the Internet.
>>TCPServerInterface
The TCP Server interface listens for incoming connections, allowing other Reticulum peers to connect to your node using TCPClientInterface.
```
Required Parameters:
Listen IP: IP address to bind to (0.0.0.0 for all interfaces)
Listen Port: Port number to listen on
Optional Parameters:
Prefer IPv6: Bind to IPv6 address if available
I2P Tunneled: Enable for I2P tunnel support
Device: Specific network device to use (e,g
```
Useful when you want other nodes to be able to connect to your Transport instance over TCP/IP.
>>UDPInterface
The UDP interface allows communication over IP networks using UDP packets.
```
Required Parameters:
Listen IP: IP address to bind to
Listen Port: Port to listen on
Forward IP: IP address to forward to (Can be broadcast address)
Forward Port: Port to forward to
Optional Parameters:
Device: Specific network device to use
```
>>I2PInterface
The I2P interface enables connections over the Invisible Internet Protocol. The I2PInterface requires an I2P daemon to be running on your system, such as `!i2pd`!
```
Optional Parameters:
Peers: I2P addresses to connect to (Can be left as none if running as a Transport)
```
>>RNodeInterface
The RNode interface allows using LoRa transceivers running RNode firmware as Reticulum network interfaces.
```
Required Parameters:
Port: Serial port or BLE device path
Frequency: Operating frequency in MHz
Bandwidth: Channel bandwidth
TX Power: Transmit power in dBm
Spreading Factor: LoRa spreading factor (7-12)
Coding Rate: LoRa coding rate (4:5-4:8)
Optional Parameters:
ID Callsign: Station identification
ID Interval: Identification interval in seconds
Airtime Limits: Control duty cycle
```
The interface includes a parameter calculator to estimate link budget, sensitivity, and data rate on the air based on your settings.
>>RNodeMultiInterface
The RNode Multi Interface is designed for use with specific hardware platforms that support multiple subinterfaces or virtual radios. For most LoRa hardware platforms, you will want to use the standard `!RNodeInterface`! instead.
```
Required Parameters:
Port: Serial port or BLE device path
Subinterfaces: Configuration for each subinterface / virtual radio port
```
>>SerialInterface
The Serial interface enables using direct serial connections as Reticulum interfaces.
```
Required Parameters:
Port: Serial port path
Speed: Baud rate of serial device
Databits: Number of data bits
Parity: Parity setting
Stopbits: Number of stop bits
```
>>KISSInterface
The KISS interface supports packet radio modems and TNCs using the KISS protocol.
```
Required Parameters:
Port: Serial port path
Speed: Baud rate of serial device
Databits: Number of data bits
Parity: Parity setting
Stopbits: Number of stop bits
Preamble: Modem preamble in milliseconds
TX Tail: Transmit tail in milliseconds
Slottime: CSMA slottime in milliseconds
Persistence: CSMA persistence value
Optional Parameters:
ID Callsign: Station identification
ID Interval: Identification interval in seconds
Flow Control: Enable packet flow control
```
>>PipeInterface
The Pipe interface allows using external programs as Reticulum interfaces via stdin and stdout.
```
Required Parameters:
Command: External command to execute
Optional Parameters:
Respawn Delay: Seconds to wait before restarting after failure
```
<
>>
-
For more information and to view the full Interface documentation consult the Reticulum manual or visit https://reticulum.network/manual/interfaces.html (Requires external Internet connection)
>Interface Access Code (IFAC) Settings
Interface Access Codes create private networks and securely segment network traffic. Under `!Show more options`!, you'll find these IFAC settings:
`!Virtual Network Name`! (network_name):
When added, creates a logical network that only communicates with other interfaces using the same name. This allows multiple separate Reticulum networks to exist on the same physical channel or medium.
`!IFAC Passphrase`! (passphrase):
Sets an authentication passphrase for the interface. Only interfaces configured with the same passphrase will be able to communicate. Can be used with or without a network name.
`!IFAC Size`! (ifac_size):
Controls the length of Interface Authentication Codes (8-512 bits). Larger sizes provide stronger security but add overhead to each packet. The default of `!8`! is usually appropriate for most uses.
>Interface Modes
When running a Transport node, you can configure interface modes that affect how Reticulum selects paths, propagates announces, and discovers routes:
`!full`!: Default mode with all discovery, meshing and transport functionality
`!gateway`!: Discovers paths on behalf of other nodes
`!access_point`!: Operates as a network access point
`!roaming`!: For physically mobile interfaces
`!boundary`!: For interfaces connecting different network segments
'''
TOPIC_CONVERSATIONS = '''>Conversations

View file

@ -15,6 +15,13 @@ INTERFACE_GLYPHS = {
}
### HELPER ###
PLATFORM_IS_LINUX = False
try:
PLATFORM_IS_LINUX = (RNS.vendor.platformutils.is_android() or
RNS.vendor.platformutils.is_linux())
except Exception:
pass
def _get_interface_icon(glyphset, iface_type):
glyphset_index = 1 # Default to unicode
if glyphset == "plain":
@ -23,6 +30,7 @@ def _get_interface_icon(glyphset, iface_type):
glyphset_index = 2 # nerdfont
type_to_glyph_tuple = {
"BackboneInterface": "NetworkInterfaceType",
"AutoInterface": "NetworkInterfaceType",
"TCPClientInterface": "NetworkInterfaceType",
"TCPServerInterface": "NetworkInterfaceType",
@ -46,10 +54,10 @@ def _get_interface_icon(glyphset, iface_type):
return glyph_tuple[glyphset_index + 1]
# Fallback
return "(#)" if glyphset == "plain" else "🙾" if glyphset == "unicode" else ""
return "(#)" if glyphset == "plain" else "\U0001f67e" if glyphset == "unicode" else "\ued95"
def format_bytes(bytes_value):
units = ['bytes', 'KB/s', 'MB/s', 'GB/s', 'TB/s']
units = ['bytes', 'KB', 'MB', 'GB', 'TB']
size = float(bytes_value)
unit_index = 0
@ -62,6 +70,7 @@ def format_bytes(bytes_value):
else:
return f"{size:.1f} {units[unit_index]}"
### PORT FUNCTIONS ###
PYSERIAL_AVAILABLE = False # If NomadNet is installed on environments with rnspure instead of rns, pyserial won't be available
try:
@ -389,6 +398,66 @@ COMMON_INTERFACE_OPTIONS = [
]
INTERFACE_FIELDS = {
"BackboneInterface": [
{
"config_key": "listen_on",
"type": "edit",
"label": "Listen On: ",
"default": "",
"placeholder": "e.g., 0.0.0.0",
"transform": lambda x: x.strip()
},
{
"config_key": "port",
"type": "edit",
"label": "Port: ",
"default": "",
"placeholder": "e.g., 4242",
"validation": ["number"],
"transform": lambda x: int(x.strip()) if x.strip() else 4242
},
{
"config_key": "device",
"type": "edit",
"label": "Device: ",
"default": "",
"placeholder": "e.g., eth0",
"transform": lambda x: x.strip()
},
{
"config_key": "remote",
"type": "edit",
"label": "Remote: ",
"default": "",
"placeholder": "e.g., a remote TCPServerInterface location",
"transform": lambda x: x.strip()
},
{
"config_key": "target_host",
"type": "edit",
"label": "Target Host: ",
"default": "",
"placeholder": "e.g., 201:5d78:af73:5caf:a4de:a79f:3278:71e5",
"transform": lambda x: x.strip()
},
{
"config_key": "port",
"type": "edit",
"label": "Target Port: ",
"default": "",
"placeholder": "e.g., 4242",
"validation": ["number"],
"transform": lambda x: int(x.strip()) if x.strip() else 4242
},
{
"config_key": "prefer_ipv6",
"type": "checkbox",
"label": "",
"default": False,
"validation": [],
"transform": lambda x: bool(x)
},
],
"AutoInterface": [
{
@ -687,6 +756,73 @@ INTERFACE_FIELDS = {
]
}
],
"RNodeMultiInterface": [
get_port_field(),
{
"config_key": "subinterfaces",
"type": "multitable",
"fields": {
"frequency": {
"label": "Freq (Hz)",
"type": "edit",
"validation": ["required", "float"],
"transform": lambda x: int(x) if x else None
},
"bandwidth": {
"label": "BW (Hz)",
"type": "edit",
"options": ["7800", "10400", "15600", "20800", "31250", "41700", "62500", "125000", "250000", "500000", "1625000"],
"transform": lambda x: int(x) if x else None
},
"txpower": {
"label": "TX (dBm)",
"type": "edit",
"validation": ["required", "number"],
"transform": lambda x: int(x) if x else None
},
"vport": {
"label": "V.Port",
"type": "edit",
"validation": ["required", "number"],
"transform": lambda x: int(x) if x else None
},
"spreadingfactor": {
"label": "SF",
"type": "edit",
"transform": lambda x: int(x) if x else None
},
"codingrate": {
"label": "CR",
"type": "edit",
"transform": lambda x: int(x) if x else None
}
},
"validation": ["required"],
"transform": lambda x: x
},
{
"additional_options": [
{
"config_key": "id_callsign",
"type": "edit",
"label": "Callsign: ",
"default": "",
"placeholder": "e.g. MYCALL-0",
"validation": [""],
"transform": lambda x: x.strip()
},
{
"config_key": "id_interval",
"type": "edit",
"label": "ID Interval (Seconds): ",
"placeholder": "e.g. 600",
"default": "",
"validation": ['number'],
"transform": lambda x: "" if x == "" else int(x)
}
]
}
],
"SerialInterface": [
get_port_field(),
{
@ -954,6 +1090,24 @@ INTERFACE_FIELDS = {
]
}
],
"CustomInterface": [
{
"config_key": "type",
"type": "edit",
"label": "Interface Type: ",
"default": "",
"placeholder": "Name of custom interface class",
"validation": ["required"],
"transform": lambda x: x.strip()
},
{
"config_key": "custom_parameters",
"type": "keyvaluepairs",
"label": "Parameters: ",
"validation": [],
"transform": lambda x: x
},
],
"default": [
{
@ -1059,7 +1213,18 @@ class SelectableInterfaceItem(urwid.WidgetWrap):
return super().render(size, focus=focus)
def keypress(self, size, key):
if key == "enter":
if key == "up":
listbox = self.parent.box_adapter._original_widget
walker = listbox.body
interface_items = [i for i, item in enumerate(walker)
if isinstance(item, SelectableInterfaceItem)]
if interface_items and walker[listbox.focus_position] is self and \
listbox.focus_position == interface_items[0]:
self.parent.app.ui.main_display.frame.focus_position = "header"
return None
elif key == "enter":
self.parent.switch_to_show_interface(self.name)
return None
return key
@ -1236,10 +1401,10 @@ class InterfaceFiller(urwid.WidgetWrap):
# edit interface
self.app.ui.main_display.sub_displays.interface_display.edit_selected_interface()
return None
elif key == "tab":
# navigation
self.app.ui.main_display.frame.focus_position = "header"
return
elif key == "ctrl w":
# open config file editor
self.app.ui.main_display.sub_displays.interface_display.open_config_editor()
return None
return super().keypress(size, key)
@ -1280,7 +1445,6 @@ class AddInterfaceView(urwid.WidgetWrap):
form_pile = urwid.Pile(pile_items)
form_filler = urwid.Filler(form_pile, valign="top")
#todo
form_box = urwid.LineBox(
form_filler,
title="Add Interface",
@ -1298,7 +1462,6 @@ class AddInterfaceView(urwid.WidgetWrap):
width=('relative', 85),
valign='middle',
height=('relative', 85),
)
super().__init__(self.overlay)
@ -1306,7 +1469,7 @@ class AddInterfaceView(urwid.WidgetWrap):
if field["type"] == "dropdown":
widget = FormDropdown(
config_key=field["config_key"],
label=field["label"],
label=field.get("label", ""),
options=field["options"],
default=field.get("default"),
validation_types=field.get("validation", []),
@ -1315,7 +1478,7 @@ class AddInterfaceView(urwid.WidgetWrap):
elif field["type"] == "checkbox":
widget = FormCheckbox(
config_key=field["config_key"],
label=field["label"],
label=field.get("label", ""),
state=field.get("default", False),
validation_types=field.get("validation", []),
transform=field.get("transform")
@ -1327,6 +1490,19 @@ class AddInterfaceView(urwid.WidgetWrap):
validation_types=field.get("validation", []),
transform=field.get("transform")
)
elif field["type"] == "multitable":
widget = FormMultiTable(
config_key=field["config_key"],
fields=field.get("fields", {}),
validation_types=field.get("validation", []),
transform=field.get("transform")
)
elif field["type"] == "keyvaluepairs":
widget = FormKeyValuePairs(
config_key=field["config_key"],
validation_types=field.get("validation", []),
transform=field.get("transform")
)
else:
widget = FormEdit(
config_key=field["config_key"],
@ -1337,8 +1513,12 @@ class AddInterfaceView(urwid.WidgetWrap):
transform=field.get("transform")
)
label = field.get("label", "")
if not label:
label = " ".join(word.capitalize() for word in field["config_key"].split('_')) + ": "
self.fields[field["config_key"]] = {
'label': field["label"],
'label': label,
'widget': widget
}
@ -1349,7 +1529,7 @@ class AddInterfaceView(urwid.WidgetWrap):
if option["type"] == "checkbox":
widget = FormCheckbox(
config_key=option["config_key"],
label=option["label"],
label=option.get("label", ""),
state=option.get("default", False),
validation_types=option.get("validation", []),
transform=option.get("transform")
@ -1357,7 +1537,7 @@ class AddInterfaceView(urwid.WidgetWrap):
elif option["type"] == "dropdown":
widget = FormDropdown(
config_key=option["config_key"],
label=option["label"],
label=option.get("label", ""),
options=option["options"],
default=option.get("default"),
validation_types=option.get("validation", []),
@ -1380,14 +1560,17 @@ class AddInterfaceView(urwid.WidgetWrap):
transform=option.get("transform")
)
label = option.get("label", "")
if not label:
label = " ".join(word.capitalize() for word in option["config_key"].split('_')) + ": "
self.additional_fields[option["config_key"]] = {
'label': option["label"],
'label': label,
'widget': widget,
'type': option["type"]
}
def _initialize_common_fields(self):
if self.parent.app.rns.transport_enabled():
# Transport mode options
COMMON_INTERFACE_OPTIONS.extend([
@ -1447,8 +1630,6 @@ class AddInterfaceView(urwid.WidgetWrap):
transform=option.get("transform")
)
self.common_fields[option["config_key"]] = {
'label': option["label"],
'widget': widget,
@ -1461,13 +1642,22 @@ class AddInterfaceView(urwid.WidgetWrap):
def _build_form_layout(self, iface_fields):
pile_items = []
pile_items.append(urwid.Text(("form_title", f"Add new {_get_interface_icon(self.parent.glyphset, self.iface_type)} {self.iface_type}"), align="center"))
pile_items.append(urwid.Text(
("form_title", f"Add new {_get_interface_icon(self.parent.glyphset, self.iface_type)} {self.iface_type}"),
align="center"))
pile_items.append(urwid.Divider(""))
for key in ["name"] + [f["config_key"] for f in iface_fields]:
field = self.fields[key]
widget = field["widget"]
# Special case for multitable and keyvaluepairs - they already have their own layout
if isinstance(widget, (FormMultiTable, FormKeyValuePairs)):
pile_items.append(urwid.Text(("key", field["label"]), align="left"))
pile_items.append(widget)
pile_items.append(urwid.Padding(widget.error_widget, left=2))
continue
field_pile = urwid.Pile([
urwid.Columns([
(26, urwid.Text(("key", field["label"]), align="right")),
@ -1476,7 +1666,8 @@ class AddInterfaceView(urwid.WidgetWrap):
urwid.Padding(widget.error_widget, left=24)
])
if self.iface_type in ["RNodeInterface", "SerialInterface", "AX25KISSInterface", "KISSInterface"] and key == "port":
if self.iface_type in ["RNodeInterface", "RNodeMultiInterface", "SerialInterface", "AX25KISSInterface",
"KISSInterface"] and key == "port":
refresh_btn = urwid.Button("Refresh Ports", on_press=self.refresh_ports)
refresh_btn = urwid.AttrMap(refresh_btn, "button_normal", focus_map="button_focus")
refresh_row = urwid.Padding(refresh_btn, left=26, width=20)
@ -1495,7 +1686,7 @@ class AddInterfaceView(urwid.WidgetWrap):
self.ifac_options_button = urwid.AttrMap(self.ifac_options_button, "button_normal", focus_map="button_focus")
self.ifac_options_widget = urwid.Pile([])
if self.iface_type == "RNodeInterface":
if self.iface_type in ["RNodeInterface", "RNodeMultiInterface"]:
self.calculator_button = urwid.Button("Show On-Air Calculations", on_press=self.toggle_calculator)
self.calculator_button = urwid.AttrMap(self.calculator_button, "button_normal", focus_map="button_focus")
@ -1512,7 +1703,7 @@ class AddInterfaceView(urwid.WidgetWrap):
self.more_options_button,
self.more_options_widget,
])
if self.iface_type == "RNodeInterface":
if self.iface_type in ["RNodeInterface", "RNodeMultiInterface"]:
self.rnode_calculator = RNodeCalculator(self)
self.calculator_visible = False
self.calculator_widget = urwid.Pile([])
@ -1564,7 +1755,6 @@ class AddInterfaceView(urwid.WidgetWrap):
pile_contents.append(urwid.Divider(""))
if self.common_fields:
# pile_contents.append(urwid.Text(("interface_title", "Common "), align="center"))
for key, field in self.common_fields.items():
widget = field['widget']
@ -1697,18 +1887,36 @@ class AddInterfaceView(urwid.WidgetWrap):
if not all_valid:
return
if self.iface_type == "CustomInterface":
custom_type = self.fields.get('type', {}).get('widget').get_value()
interface_config = {
"type": custom_type,
"interface_enabled": True
}
else:
interface_config = {
"type": self.iface_type,
"interface_enabled": True
}
for field_key, field in self.fields.items():
if field_key != "name":
if field_key not in ["name", "custom_parameters", "type"]:
widget = field["widget"]
value = widget.get_value()
if value is not None and value != "":
if field_key == "subinterfaces" and self.iface_type == "RNodeMultiInterface" and isinstance(value,
dict):
for subname, subconfig in value.items():
interface_config[f"{subname}"] = subconfig
elif value is not None and value != "":
interface_config[widget.config_key] = value
if self.iface_type == "CustomInterface" and "custom_parameters" in self.fields:
custom_params = self.fields["custom_parameters"]["widget"].get_value()
if isinstance(custom_params, dict):
for param_key, param_value in custom_params.items():
interface_config[param_key] = param_value
for field_key, field in self.additional_fields.items():
widget = field["widget"]
value = widget.get_value()
@ -1721,23 +1929,22 @@ class AddInterfaceView(urwid.WidgetWrap):
if value is not None and value != "":
interface_config[widget.config_key] = value
# Add interface to RNS config
try:
interfaces = self.parent.app.rns.config['interfaces']
interfaces[name] = interface_config
self.parent.app.rns.config.write()
print(self.parent.glyphset)
display_type = custom_type if self.iface_type == "CustomInterface" else self.iface_type
new_item = SelectableInterfaceItem(
parent=self.parent,
name=name,
is_connected=False, # will always be false until restart
is_enabled=True,
iface_type=self.iface_type,
iface_type=display_type,
tx=0,
rx=0,
icon=_get_interface_icon(self.parent.glyphset, self.iface_type),
icon=_get_interface_icon(self.parent.glyphset, display_type),
iface_options=interface_config
)
@ -1754,7 +1961,6 @@ class AddInterfaceView(urwid.WidgetWrap):
self.parent.switch_to_list()
def show_message(self, message, title="Notice"):
def dismiss_dialog(button):
self.parent.switch_to_list()
@ -1781,72 +1987,80 @@ class AddInterfaceView(urwid.WidgetWrap):
self.parent.widget = overlay
self.parent.app.ui.main_display.update_active_sub_display()
class EditInterfaceView(AddInterfaceView):
def __init__(self, parent, iface_name):
self.parent = parent
self.iface_name = iface_name
self.interface_config = parent.app.rns.config['interfaces'][iface_name]
self.iface_type = self.interface_config.get("type", "Unknown")
config_type = self.interface_config.get("type", "Unknown")
# check if this is a custom interface type
known_types = list(INTERFACE_FIELDS.keys())
if config_type not in known_types:
self.original_type = config_type
self.iface_type = "CustomInterface"
else:
self.original_type = None
self.iface_type = config_type
super().__init__(parent, self.iface_type)
self.overlay.top_w.title_widget.set_text(f"Edit Interface: {iface_name}")
self._populate_form_fields()
def _populate_form_fields(self):
self.fields['name']['widget'].edit_text = self.iface_name
if self.original_type and self.iface_type == "CustomInterface":
if "type" in self.fields:
self.fields["type"]["widget"].edit_text = self.original_type
if "custom_parameters" in self.fields:
custom_params = {}
standard_keys = ["type", "interface_enabled", "enabled", "description",
"network_name", "bitrate", "passphrase", "ifac_size",
"mode", "outgoing", "announce_cap"]
for key, value in self.interface_config.items():
if key not in standard_keys:
custom_params[key] = value
self.fields["custom_parameters"]["widget"].set_value(custom_params)
for key, field in self.fields.items():
if key != 'name' and key in self.interface_config:
if key not in ['name', 'type', 'custom_parameters']:
widget = field['widget']
if key == "subinterfaces" and isinstance(widget, FormMultiTable):
self._populate_subinterfaces(widget)
continue
if key in self.interface_config:
value = self.interface_config[key]
if key == 'frequency':
# convert Hz back to MHz
value = float(value) / 1000000
# decimal format
value = f"{value:.6f}".rstrip('0').rstrip('.') if '.' in f"{value:.6f}" else f"{value}"
if hasattr(widget, 'edit_text'):
# For text input fields, set edit_text
widget.edit_text = str(value)
elif hasattr(widget, 'set_state'):
# For checkboxes
widget.set_state(bool(value))
elif isinstance(widget, FormDropdown):
# For dropdowns - update selected and update display
str_value = str(value)
if str_value in widget.options:
widget.selected = str_value
widget.main_button.base_widget.set_text(str_value)
else:
for opt in widget.options:
try:
if widget.transform(opt) == value:
widget.selected = opt
widget.main_button.base_widget.set_text(opt)
break
except:
pass
elif isinstance(widget, FormMultiList):
if isinstance(value, str):
items = [item.strip() for item in value.split(',') if item.strip()]
self._populate_multilist(widget, items)
elif isinstance(value, list):
self._populate_multilist(widget, value)
self._set_field_value(widget, value)
for key, field in self.additional_fields.items():
if key in self.interface_config:
widget = field['widget']
value = self.interface_config[key]
self._set_field_value(field['widget'], self.interface_config[key])
for key, field in self.common_fields.items():
if key in self.interface_config:
self._set_field_value(field['widget'], self.interface_config[key])
def _set_field_value(self, widget, value):
if hasattr(widget, 'edit_text'):
widget.edit_text = str(value)
elif hasattr(widget, 'set_state'):
# RNS.log(f"KEY: {key} VAL: {value}")
checkbox_state = value if isinstance(value, bool) else value.strip().lower() not in ('false', 'off', 'no', '0')
checkbox_state = value if isinstance(value, bool) else value.strip().lower() not in (
'false', 'off', 'no', '0')
widget.set_state(checkbox_state)
elif isinstance(widget, FormDropdown):
str_value = str(value)
@ -1864,44 +2078,15 @@ class EditInterfaceView(AddInterfaceView):
except:
pass
elif isinstance(widget, FormMultiList):
if isinstance(value, str):
items = [item.strip() for item in value.split(',') if item.strip()]
self._populate_multilist(widget, items)
elif isinstance(value, list):
self._populate_multilist(widget, value)
for key, field in self.common_fields.items():
if key in self.interface_config:
widget = field['widget']
value = self.interface_config[key]
if hasattr(widget, 'edit_text'):
widget.edit_text = str(value)
elif hasattr(widget, 'set_state'):
widget.set_state(bool(value))
elif isinstance(widget, FormDropdown):
str_value = str(value)
if str_value in widget.options:
widget.selected = str_value
widget.main_button.base_widget.set_text(str_value)
else:
# Try to match after transform
for opt in widget.options:
try:
if widget.transform(opt) == value:
widget.selected = opt
widget.main_button.base_widget.set_text(opt)
break
except:
pass
elif isinstance(widget, FormMultiList):
def _populate_multilist(self, widget, value):
items = []
if isinstance(value, str):
items = [item.strip() for item in value.split(',') if item.strip()]
self._populate_multilist(widget, items)
elif isinstance(value, list):
self._populate_multilist(widget, value)
items = value
def _populate_multilist(self, widget, items):
while len(widget.entries) > 1:
widget.remove_entry(None, widget.entries[-1])
@ -1917,24 +2102,64 @@ class EditInterfaceView(AddInterfaceView):
edit_widget = entry.contents[0][0]
edit_widget.edit_text = items[i]
def _populate_subinterfaces(self, widget):
subinterfaces = {}
for key, value in self.interface_config.items():
if isinstance(value, dict):
if key.startswith('[[[') and key.endswith(']]]'):
clean_key = key[3:-3] # removes [[[...]]]
subinterfaces[clean_key] = value
elif key not in ["type", "interface_enabled", "enabled", "port",
"id_callsign", "id_interval"]:
subinterfaces[key] = value
if subinterfaces:
widget.set_value(subinterfaces)
def on_save(self, button):
if not self.validate_all():
return
new_name = self.fields['name']["widget"].get_value() or self.iface_name
if new_name != self.iface_name and new_name in self.parent.app.rns.config['interfaces']:
self.fields['name']["widget"].error = f"Interface name '{new_name}' already exists"
self.fields['name']["widget"].error_widget.set_text(("error", self.fields['name']["widget"].error))
return
if self.iface_type == "CustomInterface":
interface_type = self.fields.get('type', {}).get('widget').get_value()
else:
interface_type = self.iface_type
updated_config = {
"type": self.iface_type,
"type": interface_type,
"interface_enabled": True
}
for field_key, field in self.fields.items():
if field_key != "name":
if field_key not in ["name", "custom_parameters", "type"]:
widget = field["widget"]
value = widget.get_value()
if value is not None and value != "":
updated_config[widget.config_key] = value
if self.iface_type == "CustomInterface" and "custom_parameters" in self.fields:
custom_params = self.fields["custom_parameters"]["widget"].get_value()
if isinstance(custom_params, dict):
for param_key, param_value in custom_params.items():
updated_config[param_key] = param_value
elif self.iface_type == "RNodeMultiInterface" and "subinterfaces" in self.fields:
subinterfaces = self.fields["subinterfaces"]["widget"].get_value()
for subname, subconfig in subinterfaces.items():
if any(k.startswith('[[[') for k in self.interface_config.keys()):
updated_config[f"[[[{subname}]]]"] = subconfig
else:
updated_config[subname] = subconfig
for field_key, field in self.additional_fields.items():
widget = field["widget"]
value = widget.get_value()
@ -1963,13 +2188,14 @@ class EditInterfaceView(AddInterfaceView):
self.parent.app.rns.config.write()
display_type = interface_type
for item in self.parent.interface_items:
if item.name == new_name:
item.iface_type = self.iface_type
item.iface_type = display_type
break
self.parent._rebuild_list()
self.show_message(f"Interface {new_name} updated. Restart NomadNet for these changes to take effect")
except Exception as e:
@ -1992,6 +2218,8 @@ class ShowInterface(urwid.WidgetWrap):
self.config_rows = []
self.history_length=60
# get interface stats
interface_stats = self.parent.app.rns.get_interface_stats()
stats_lookup = {iface['short_name']: iface for iface in interface_stats['interfaces']}
@ -2070,7 +2298,7 @@ class ShowInterface(urwid.WidgetWrap):
self.info_rows.append(self.stat_row)
self.info_rows.append(urwid.Divider("-"))
self.bandwidth_chart = InterfaceBandwidthChart(history_length=60, glyphset=self.parent.glyphset)
self.bandwidth_chart = InterfaceBandwidthChart(history_length=self.history_length, glyphset=self.parent.glyphset)
self.bandwidth_chart.update(self.rx, self.tx)
self.rx_chart_text = urwid.Text("Loading RX data...", align='left')
@ -2117,7 +2345,8 @@ class ShowInterface(urwid.WidgetWrap):
screen = urwid.raw_display.Screen()
screen_cols, _ = screen.get_cols_rows()
if screen_cols >= 100:
# RNS.log(screen_cols)
if screen_cols >= 145:
self.charts_widget = self.horizontal_charts
self.is_horizontal = True
@ -2415,7 +2644,6 @@ class ShowInterface(urwid.WidgetWrap):
if isinstance(button_row, urwid.Columns):
button_row.focus_position = 0
return None
# If we're currently in footer change the focus
elif self.frame.focus_position == 'footer':
footer_pile = self.frame.footer
if isinstance(footer_pile, urwid.Pile):
@ -2451,6 +2679,33 @@ class ShowInterface(urwid.WidgetWrap):
elif button_row.focus_position == 0: # back button
self.frame.focus_position = 'body'
return None
elif key == 'down':
if self.frame.focus_position == 'body':
result = super().keypress(size, key)
# if the key wasn't consumed, we're at the bottom
if result == 'down':
self.frame.focus_position = 'footer'
footer_pile = self.frame.footer
if isinstance(footer_pile, urwid.Pile):
footer_pile.focus_position = 1 # button row
button_row = footer_pile.contents[1][0]
if isinstance(button_row, urwid.Columns):
button_row.focus_position = 0 # focus on back button
return None
return result
elif key == 'up':
if self.frame.focus_position == 'footer':
self.frame.focus_position = 'body'
listbox = self.frame.body
if hasattr(listbox, 'body') and len(listbox.body) > 0:
listbox.focus_position = len(listbox.body) - 1
return None
elif self.frame.focus_position == 'body':
result = super().keypress(size, key)
# if the key wasn't consumed, we're at the top
if result == 'up':
pass
return result
elif key == "h" and self.is_connected: # horizontal layout
if not self.is_horizontal:
self.switch_to_horizontal()
@ -2496,6 +2751,7 @@ class ShowInterface(urwid.WidgetWrap):
if not self.started:
return
try:
interface_stats = self.parent.app.rns.get_interface_stats()
stats_lookup = {iface['short_name']: iface for iface in interface_stats['interfaces']}
stats = stats_lookup.get(self.iface_name, {})
@ -2524,7 +2780,29 @@ class ShowInterface(urwid.WidgetWrap):
self.tx = tx
self.rx = rx
except Exception as e:
if not hasattr(self.parent,
'disconnect_overlay') or self.parent.widget is not self.parent.disconnect_overlay:
dialog_text = urwid.Pile([
urwid.Text(("disconnected_status", "(!) RNS Instance Disconnected"), align="center"),
urwid.Text("Waiting to Reconnect...", align="center")
])
dialog_content = urwid.Filler(dialog_text)
dialog_box = urwid.LineBox(dialog_content)
self.parent.disconnect_overlay = urwid.Overlay(
dialog_box,
self,
align='center',
width=35,
valign='middle',
height=4
)
self.parent.widget = self.parent.disconnect_overlay
self.parent.app.ui.main_display.update_active_sub_display()
self.started = False
finally:
if self.started:
loop.set_alarm_in(1, self.update_bandwidth_charts)
@ -2666,6 +2944,11 @@ class InterfaceDisplay:
loop.set_alarm_in(5, self.check_terminal_size)
def poll_stats(self, loop, user_data):
try:
if hasattr(self, 'disconnect_overlay') and self.widget is self.disconnect_overlay:
self.widget = self.interfaces_display
self.app.ui.main_display.update_active_sub_display()
interface_stats = self.app.rns.get_interface_stats()
stats_lookup = {iface['short_name']: iface for iface in interface_stats['interfaces']}
for item in self.interface_items:
@ -2675,10 +2958,31 @@ class InterfaceDisplay:
tx = stats_for_interface.get("txb", 0)
rx = stats_for_interface.get("rxb", 0)
item.update_stats(tx, rx)
except Exception as e:
if not hasattr(self, 'disconnect_overlay') or self.widget is not self.disconnect_overlay:
dialog_text = urwid.Pile([
urwid.Text(("disconnected_status", "(!) RNS Instance Disconnected"), align="center"),
urwid.Text(("Waiting to Reconnect..."), align="center")
])
dialog_content = urwid.Filler(dialog_text)
dialog_box = urwid.LineBox(dialog_content)
self.disconnect_overlay = urwid.Overlay(
dialog_box,
self.interfaces_display,
align='center',
width=35,
valign='middle',
height=4
)
if self.widget is self.interfaces_display:
self.widget = self.disconnect_overlay
self.app.ui.main_display.update_active_sub_display()
finally:
if self.started:
loop.set_alarm_in(1, self.poll_stats)
def shortcuts(self):
return self.shortcuts_display
@ -2717,10 +3021,13 @@ class InterfaceDisplay:
add_option("TCP Server Interface", "TCPServerInterface")
add_option("UDP Interface", "UDPInterface")
add_option("I2P Interface", "I2PInterface")
if PLATFORM_IS_LINUX:
add_option("Backbone Interface", "BackboneInterface")
if PYSERIAL_AVAILABLE:
add_heading(f"{rnode_icon} RNodes")
add_option("RNode Interface", "RNodeInterface")
# add_option("RNode Multi Interface", "RNodeMultiInterface") TODO
add_option("RNode Multi Interface", "RNodeMultiInterface")
add_heading(f"{serial_icon} Hardware")
add_option("Serial Interface", "SerialInterface")
@ -2729,7 +3036,8 @@ class InterfaceDisplay:
add_heading(f"{other_icon} Other")
add_option("Pipe Interface", "PipeInterface")
# add_option("Custom Interface", "CustomInterface") TODO
add_option("Custom Interface", "CustomInterface")
listbox = urwid.ListBox(urwid.SimpleFocusListWalker(dialog_widgets))
dialog = DialogLineBox(listbox, parent=self, title="Select Interface Type")
@ -2834,11 +3142,38 @@ class InterfaceDisplay:
self.box_adapter._original_widget.body = walker
self.box_adapter._original_widget.focus_position = len(new_list) - 1
def open_config_editor(self):
import platform
editor_cmd = self.app.config["textui"]["editor"]
if platform.system() == "Darwin" and editor_cmd == "editor":
editor_cmd = "nano"
editor_term = urwid.Terminal(
(editor_cmd, self.app.rns.configpath),
encoding='utf-8',
main_loop=self.app.ui.loop,
)
def quit_term(*args, **kwargs):
self.widget = self.interfaces_display
self.app.ui.main_display.update_active_sub_display()
self.app.ui.main_display.request_redraw()
urwid.connect_signal(editor_term, 'closed', quit_term)
editor_box = urwid.LineBox(editor_term, title="Editing RNS Config")
self.widget = editor_box
self.app.ui.main_display.update_active_sub_display()
self.app.ui.main_display.frame.focus_position = "body"
editor_term.change_focus(True)
### SHORTCUTS ###
class InterfaceDisplayShortcuts:
def __init__(self, app):
self.app = app
self.default_shortcuts = "[C-a] Add Interface [C-e] Edit Interface [C-x] Remove Interface [Enter] Show Interface"
self.default_shortcuts = "[C-a] Add Interface [C-e] Edit Interface [C-x] Remove Interface [Enter] Show Interface [C-w] Open Text Editor"
self.current_shortcuts = self.default_shortcuts
self.widget = urwid.AttrMap(
urwid.Text(self.current_shortcuts),
@ -2853,7 +3188,7 @@ class InterfaceDisplayShortcuts:
self.update_shortcuts(self.default_shortcuts)
def set_show_interface_shortcuts(self):
show_shortcuts = "[Back] Return to List [Tab] Navigate [Shift-tab] Change Focus [h] Horizontal Charts [v] Vertical Charts [Up/Down] Scroll"
show_shortcuts = "[Up/Down] Navigate [Tab] Switch Focus [h] Horizontal Charts [v] Vertical Charts "
self.update_shortcuts(show_shortcuts)
def set_add_interface_shortcuts(self):

View file

@ -281,3 +281,258 @@ class FormMultiList(urwid.Pile, FormField):
self.error_widget.set_text(("error", self.error or ""))
return self.error is None
class FormMultiTable(urwid.Pile, FormField):
def __init__(self, config_key, fields, validation_types=None, transform=None, **kwargs):
self.entries = []
self.fields = fields
self.error_widget = urwid.Text("")
self.error = None
self.validation_types = validation_types or []
header_columns = [('weight', 3, urwid.Text(("list_focus", "Name")))]
for field_key, field_config in self.fields.items():
header_columns.append(('weight', 2, urwid.Text(("list_focus", field_config.get("label", field_key)))))
header_columns.append((4, urwid.Text(("list_focus", ""))))
self.header_row = urwid.Columns(header_columns)
first_entry = self.create_entry_row()
self.entries.append(first_entry)
self.add_button = urwid.Button("+ Add ", on_press=self.add_entry)
add_button_padded = urwid.Padding(self.add_button, left=2, right=2)
pile_widgets = [
self.header_row,
urwid.Divider("-"),
first_entry,
add_button_padded
]
urwid.Pile.__init__(self, pile_widgets)
FormField.__init__(self, config_key, transform)
def create_entry_row(self, name="", values=None):
if values is None:
values = {}
name_edit = urwid.Edit("", name)
columns = [('weight', 3, name_edit)]
field_widgets = {}
for field_key, field_config in self.fields.items():
field_value = values.get(field_key, "")
if field_config.get("type") == "checkbox":
widget = urwid.CheckBox("", state=bool(field_value))
elif field_config.get("type") == "dropdown":
# TODO: dropdown in MultiTable
widget = urwid.Edit("", str(field_value))
else:
widget = urwid.Edit("", str(field_value))
field_widgets[field_key] = widget
columns.append(('weight', 2, widget))
remove_button = urwid.Button("×", on_press=lambda button: self.remove_entry(button, entry_row))
columns.append((4, remove_button))
entry_row = urwid.Columns(columns)
entry_row.name_edit = name_edit
entry_row.field_widgets = field_widgets
return entry_row
def remove_entry(self, button, entry_row):
if len(self.entries) > 1:
self.entries.remove(entry_row)
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def add_entry(self, button):
new_entry = self.create_entry_row()
self.entries.append(new_entry)
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def get_pile_widgets(self):
return [
self.header_row,
urwid.Divider("-")
] + self.entries + [
urwid.Padding(self.add_button, left=2, right=2)
]
def get_value(self):
values = {}
for entry in self.entries:
name = entry.name_edit.edit_text.strip()
if name:
subinterface = {}
subinterface["interface_enabled"] = True
for field_key, widget in entry.field_widgets.items():
field_config = self.fields.get(field_key, {})
if hasattr(widget, "get_state"):
value = widget.get_state()
elif hasattr(widget, "edit_text"):
value = widget.edit_text.strip()
transform = field_config.get("transform")
if transform and value:
try:
value = transform(value)
except (ValueError, TypeError):
pass
value = ""
if value:
subinterface[field_key] = value
values[name] = subinterface
return self.transform(values) if self.transform else values
def set_value(self, value):
self.entries = []
if not value:
self.entries.append(self.create_entry_row())
else:
for name, config in value.items():
self.entries.append(self.create_entry_row(name=name, values=config))
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def validate(self):
values = self.get_value()
self.error = None
for validation in self.validation_types:
if validation == "required" and not values:
self.error = "At least one subinterface is required"
break
self.error_widget.set_text(("error", self.error or ""))
return self.error is None
class FormKeyValuePairs(urwid.Pile, FormField):
def __init__(self, config_key, validation_types=None, transform=None, **kwargs):
self.entries = []
self.error_widget = urwid.Text("")
self.error = None
self.validation_types = validation_types or []
header_columns = [
('weight', 1, urwid.AttrMap(urwid.Text("Parameter Key"), "multitable_header")),
('weight', 1, urwid.AttrMap(urwid.Text("Parameter Value"), "multitable_header")),
(4, urwid.AttrMap(urwid.Text("Action"), "multitable_header"))
]
self.header_row = urwid.AttrMap(urwid.Columns(header_columns), "multitable_header")
first_entry = self.create_entry_row()
self.entries.append(first_entry)
self.add_button = urwid.Button("+ Add Parameter", on_press=self.add_entry)
add_button_padded = urwid.Padding(self.add_button, left=2, right=2)
pile_widgets = [
self.header_row,
urwid.Divider("-"),
first_entry,
add_button_padded
]
urwid.Pile.__init__(self, pile_widgets)
FormField.__init__(self, config_key, transform)
def create_entry_row(self, key="", value=""):
key_edit = urwid.Edit("", key)
value_edit = urwid.Edit("", value)
remove_button = urwid.Button("×", on_press=lambda button: self.remove_entry(button, entry_row))
entry_row = urwid.Columns([
('weight', 1, key_edit),
('weight', 1, value_edit),
(4, remove_button)
])
entry_row.key_edit = key_edit
entry_row.value_edit = value_edit
return entry_row
def remove_entry(self, button, entry_row):
if len(self.entries) > 1:
self.entries.remove(entry_row)
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def add_entry(self, button):
new_entry = self.create_entry_row()
self.entries.append(new_entry)
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def get_pile_widgets(self):
return [
self.header_row,
urwid.Divider("-")
] + self.entries + [
urwid.Padding(self.add_button, left=2, right=2)
]
def get_value(self):
values = {}
for entry in self.entries:
key = entry.key_edit.edit_text.strip()
value = entry.value_edit.edit_text.strip()
if key:
if value.isdigit():
values[key] = int(value)
elif value.replace('.', '', 1).isdigit() and value.count('.') <= 1:
values[key] = float(value)
elif value.lower() == 'true':
values[key] = True
elif value.lower() == 'false':
values[key] = False
else:
values[key] = value
return self.transform(values) if self.transform else values
def set_value(self, value):
self.entries = []
if not value or not isinstance(value, dict):
self.entries.append(self.create_entry_row())
else:
for key, val in value.items():
self.entries.append(self.create_entry_row(key=key, value=str(val)))
self.contents = [(w, self.options()) for w in self.get_pile_widgets()]
def validate(self):
values = self.get_value()
self.error = None
keys = [entry.key_edit.edit_text.strip() for entry in self.entries
if entry.key_edit.edit_text.strip()]
if len(keys) != len(set(keys)):
self.error = "Duplicate keys are not allowed"
self.error_widget.set_text(("error", self.error))
return False
for validation in self.validation_types:
if validation == "required" and not values:
self.error = "Atleast one parameter is required"
break
self.error_widget.set_text(("error", self.error or ""))
return self.error is None

View file

@ -30,6 +30,6 @@ setuptools.setup(
entry_points= {
'console_scripts': ['nomadnet=nomadnet.nomadnet:main']
},
install_requires=["rns>=0.9.3", "lxmf>=0.6.2", "urwid>=2.6.16", "qrcode"],
install_requires=["rns>=0.9.4", "lxmf>=0.6.3", "urwid>=2.6.16", "qrcode"],
python_requires=">=3.7",
)