From 6b2aee72e09f204f2c7375d09a10ab826ce12af9 Mon Sep 17 00:00:00 2001 From: Logan Cusano Date: Sat, 7 Jun 2025 23:22:16 -0400 Subject: [PATCH] Add default node nickname --- app/client.py | 5 ++++- app/utils.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 app/utils.py diff --git a/app/client.py b/app/client.py index c69f225..9bf2afc 100644 --- a/app/client.py +++ b/app/client.py @@ -8,6 +8,7 @@ from drb_cdb_types import ConfigGenerator, TalkgroupTag from server_api import RadioAPIClient from enum import Enum from config import Config +from utils import generate_node_nickname app_conf = Config() @@ -21,7 +22,9 @@ if not app_conf.get("client_id"): app_conf.set("client_id", f"client-{uuid.uuid4().hex[:8]}") CLIENT_ID = app_conf.client_id -# Get the nickname (even if it's empty) +# Get the nickname or set the reg ID +if not app_conf.get("nickname"): + app_conf.set("nickname", generate_node_nickname()) NICKNAME = app_conf.get("nickname") # ---------------------------- diff --git a/app/utils.py b/app/utils.py new file mode 100644 index 0000000..24b7bd6 --- /dev/null +++ b/app/utils.py @@ -0,0 +1,43 @@ +import socket +import requests + +def generate_node_nickname(): + """ + Generates a temporary unit registration ID in the format: + "Node-{last octet of local IP}-{last octet of public IP}". + + This ID is intended for initial unit registration and will be replaced + by a server-generated GUID upon assignment. + + Returns: + str: The formatted registration ID. + """ + local_ip_octet = "unknown" + public_ip_octet = "unknown" + + # Get the last octet of the local IP address + try: + # Create a UDP socket + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + # Connect to an external host (Google's DNS) to get the local IP + # This doesn't send any data, just establishes a connection for getsockname() + s.connect(("1.1.1.1", 80)) + local_ip = s.getsockname()[0] + s.close() + local_ip_octet = local_ip.split('.')[-1] + except Exception as e: + print(f"Warning: Could not determine local IP address. Error: {e}") + + # Get the last octet of the public IP address using an external service + try: + # Use ipify.org to get the public IP (a widely used, simple service) + response = requests.get('https://api.ipify.org?format=json') + response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx) + public_ip = response.json()['ip'] + public_ip_octet = public_ip.split('.')[-1] + except requests.exceptions.RequestException as e: + print(f"Warning: Could not determine public IP address. Error: {e}") + except ValueError as e: + print(f"Warning: Could not parse public IP response. Error: {e}") + + return f"Node-{local_ip_octet}-{public_ip_octet}" \ No newline at end of file